@ones-editor/editor 0.0.3-beta.181 → 0.0.3-beta.182
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 m6={boxType:"br",updateBoxContent:HI,convertTo:jI},g6=S("editor-boxes");class p6{constructor(t){m(this,"boxes",new Map);this.editor=t}registerBoxClass(t){const e=t.boxType,o=this.boxes.get(e);g(g6,!o,`duplicated box type: ${e}`),this.boxes.set(e,t)}getBoxClass(t){const e=this.boxes.get(t);return g(g6,e,`unknown box type: ${t}`),e}createBox(t,e){const o=VC(e),r=qC(o);return this.getBoxClass(e.type).updateBoxContent(this.editor,o,r,e),o}}function UI(n,t,e,o){const r=o,{width:i,height:s,src:l}=r,a=["editor-box-image"];r.link&&a.push("editor-box-image-link");const d=w("img",a,e);i&&(d.style.width=`${i}px`),s&&(d.style.height=`${s}px`),d.src=n.doc.buildResourceUrl(l)}const C6={boxType:"image",updateBoxContent:UI},zI="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9InJnYigxNzgsIDE4OCwgMjA1KSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0ibTE3IDE1IDEuNTUgMS41NWMtLjk2IDEuNjktMy4zMyAzLjA0LTUuNTUgMy4zN1YxMWgzVjloLTNWNy44MkMxNC4xNiA3LjQgMTUgNi4zIDE1IDVjMC0xLjY1LTEuMzUtMy0zLTNTOSAzLjM1IDkgNWMwIDEuMy44NCAyLjQgMiAyLjgyVjlIOHYyaDN2OC45MmMtMi4yMi0uMzMtNC41OS0xLjY4LTUuNTUtMy4zN0w3IDE1bC00LTN2M2MwIDMuODggNC45MiA3IDkgN3M5LTMuMTIgOS03di0zbC00IDN6TTEyIDRjLjU1IDAgMSAuNDUgMSAxcy0uNDUgMS0xIDEtMS0uNDUtMS0xIC40NS0xIDEtMXoiPjwvcGF0aD4KPC9zdmc+Cg==";function VI(n,t,e){W(e,"editor-box-anchor"),gm(zI,[],e)}const A6={boxType:"anchor",updateBoxContent:VI};function WI(n,t,e,o){w("span",[],e,o.text)}const b6={insertionType:"inputting",updateInsertionContent:WI},v6=S("editor-insertion");class y6{constructor(t){m(this,"insertions",new Map);this.editor=t}registerInsertionClass(t){const e=t.insertionType,o=this.insertions.get(e);g(v6,!o,`duplicated insertion type: ${e}`),this.insertions.set(e,t)}getInsertionClass(t){const e=this.insertions.get(t);return g(v6,e,`unknown insertion type: ${t}`),e}createInsertion(t,e){const o=GC(e.type,e.id),r=QC(o);return this.getInsertionClass(e.type).updateInsertionContent(this.editor,o,r,e),o}}class qI{constructor(t){m(this,"cursors",new Map);m(this,"timer");this.editor=t,this.timer=this.startTimer()}add(t,e){this.cursors.set(t,e)}startTimer(){return setInterval(()=>{const t=Date.now();Array.from(this.cursors).forEach(([e,o])=>{if(t-o>3e3){const r=ZC(this.editor,e);r&&ot(r,"active"),this.cursors.delete(e)}})},1e3)}destroy(){clearInterval(this.timer)}}function GI(n,t,e,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",d=>new qI(d)).add(r.id,r.time),W(t,"active")),w("span",[],e,"|").setAttribute("data-cursor-name",r.name),t.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const yg={insertionType:"remote-cursor",updateInsertionContent:GI};class k6{constructor(t){m(this,"decorators",[]);this.editor=t}registerDecorator(t){this.decorators.push(t)}decorateBlock(t,e){let o=e;return this.decorators.forEach(r=>{if(r.decorateBlock){const i=r.decorateBlock(this.editor,t,e);i&&(o=mt.default(i))}}),o}decorateText(t,e){let o=e;const r=new Map;return this.decorators.forEach(i=>{if(i.decorateText){const s=i.decorateText(this.editor,t,e);if(s){const{insertions:l,text:a}=s;l&&Array.from(l.entries()).forEach(([d,h])=>{const p=r.get(d);p?p.push(...h):r.set(d,h)}),a&&(o=mt.default(a))}}}),{insertions:r,text:o}}}const kg=S("editor-input");class ZI{constructor(t,e){m(this,"editor");m(this,"composing",!1);m(this,"callbacks");m(this,"inputElement");m(this,"handleDocumentClick",t=>{const e=this.editor.rootContainer,o=t.target;if(o&&e.contains(o)&&!Ss(o)){this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus();return}this.editor.emit("blur",this.editor),this.callbacks.onBlur()});m(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var e;const t=(e=document.getSelection())==null?void 0:e.focusNode;t&&this.editor.contains(t)&&!Ss(t)||(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});m(this,"handleEditorSelectionChanged",()=>{const e=!this.editor.isWritable();this.inputElement.readOnly=e});m(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});m(this,"handleCompositionstart",t=>{!this.editor.isWritable()||(this.composing=!0,this.callbacks.onCompositionStart(t))});m(this,"handleCompositionend",t=>{this.composing=!1,this.callbacks.onUpdateCompositionText(t,this.inputElement.value,!0),this.inputElement.value=""});m(this,"handleInput",t=>{if(t instanceof InputEvent&&!!t.data){if(this.editor.readonly||!this.editor.isWritable()){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(t,t.data,!1):(this.callbacks.onInsertText(t,t.data),this.inputElement.value="")}});m(this,"handleKeyDown",t=>{if(!this.composing){if(this.callbacks.onKeyDown(t)){t.preventDefault(),t.stopPropagation();return}!this.editor.isWritable()||setTimeout(()=>{this.composing||(this.inputElement.value="")})}});m(this,"handleCopy",t=>{this.callbacks.onCopy(t)});m(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onCut(t),kg.debug("on cut")});m(this,"handlePaste",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onPaste(t)});m(this,"handlePasteText",(t,e)=>{this.callbacks.onPasteText(t,e)});this.editor=t,this.callbacks=e;const o=w("input",["editor-input"],t.contentElement);o.type="text",o.name="editor-input",o.onkeydown=this.handleKeyDown,o.oninput=this.handleInput,o.oncopy=this.handleCopy,o.onpaste=this.handlePaste,o.oncut=this.handleCut,o.addEventListener("compositionstart",this.handleCompositionstart),o.addEventListener("compositionend",this.handleCompositionend),this.inputElement=o,document.addEventListener("click",this.handleDocumentClick),document.addEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("click",this.handleDocumentClick),document.removeEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.removeListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged);const t=this.inputElement;t.removeEventListener("compositionstart",this.handleCompositionstart),t.removeEventListener("compositionend",this.handleCompositionend),t.onkeydown=null,t.oninput=null,t.oncopy=null,t.onpaste=null,t.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),Ke.isMobileSafari?this.inputElement.focus():setTimeout(()=>{this.inputElement.focus()})}handleChanged(t){this.callbacks.onChanged(t)}handleRemoteChanged(t){this.callbacks.onRemoteChanged(t)}addHandler(t){this.callbacks.addHandler(t)}removeHandler(t){this.callbacks.removeHandler(t)}defaultInsertText(t,e,o,r,i){g(kg,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return g(kg,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function w6(n){const t=n.rootElement,e=t.getBoundingClientRect(),o=vs(t),r=window.innerWidth,i=window.innerHeight,s=e.left<0?0:e.left,l=e.top<0?0:e.top,a=e.right>r?r:e.right,d=e.bottom>i?i:e.bottom,h=(s+a)/2,p=(l+d)/2,A=0-e.left+h,v=0-e.top+p,B=n.input.inputElement;B.style.left=`${A/o}px`,B.style.top=`${v/o}px`}const wg=S("editor-caret");class QI{constructor(t){m(this,"editor");m(this,"caretElem");m(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=t,this.caretElem=w("div",["editor-cursor"],this.editor.contentElement),this.editor.on("readonlyChanged",this.handleReadOnlyChanged)}destroy(){this.editor.off("readonlyChanged",this.handleReadOnlyChanged)}visible(){const t=window.getComputedStyle(this.caretElem);return t.display!=="none"&&t.opacity!=="0"}hasCaret(){if(this.editor.readonly||!this.editor.selection.range.isCollapsed())return!1;const t=this.editor.selection.range.start;if(!(t instanceof je))return!1;const e=this.editor.getBlockById(t.blockId);return!!tt(this.editor,e)}update(){if(eC(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",w6(this.editor);return}const{range:e}=this.editor.selection;g(wg,e.isCollapsed,"range is not collapsed");const o=e.start;g(wg,o instanceof je,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);g(wg,tt(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=Vn(r,o);const l=this.editor.contentElement.getBoundingClientRect(),a=i.left-l.left,d=i.top-l.top;t.style.left=`${a}px`,t.style.top=`${d}px`,t.style.height=`${i.height}px`;const h=this.editor.input.inputElement;h.style.left=`${a}px`,h.style.top=`${d+i.height-24}px`,Ke.isMobileSafari&&(h.style.left=`${a-4}px`,h.style.height=`${i.height}px`);const A=ro(r,{horizontal:!0}).getBoundingClientRect(),v=A.left-l.left,B=v+A.width;a<v||a>B?(w6(this.editor),t.style.display="none"):t.style.display=""}}function YI(n){t4(n),n.selection.range.getSelectedBlocks().forEach(t=>e4(n,t.block,t.start,t.end))}const JI=S("editor-dom");function B6(n){return ro(n.rootContainer).clientHeight}function KI(n){return n.getFirstBlock().getBoundingClientRect().top}function XI(n){return n.getLastBlock().getBoundingClientRect().bottom}function Bg(n){const e=ro(n.rootContainer).getBoundingClientRect(),o=e.x<0?0:e.x,r=e.y<0?0:e.y,i=e.right>window.innerWidth?window.innerWidth:e.right,s=e.bottom>window.innerHeight?window.innerHeight:e.bottom;return new DOMRect(o,r,i-o,s-r)}function tT(n,t){const e=Bg(n),o=n.getBlockById(t.blockId),i=So(n,o,t);return ys(e,i.x,i.y)&&ys(e,i.right,i.bottom)}function E6(n,t){const e=Bg(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function eT(n,t){const e=Bg(n),o=t.getBoundingClientRect();return ys(e,o.x,o.y)||ys(e,o.right,o.bottom)}function nT(n){if(!vm(n.rootContainer)){JI.warn("editorScrollIntoView: editor is not visible");return}const t=n.rootContainer.getBoundingClientRect();if(t.height<1&&t.width<1)return;const e=n.selection,o=e.range.focus;if(!o.isSimple()){const h=o,p=n.getContainerById(h.childContainerId);eT(n,p)||p.scrollIntoView();return}if(e.range.start.blockId===e.range.end.blockId){const h=n.getBlockById(e.range.start.blockId);if(Me(h)&&E6(n,h)||Mt(n,h)&&E6(n,h))return}const r=o,i=n.getBlockById(r.blockId);if(tT(n,r))return;const s=So(n,i,r),l=i.getBoundingClientRect(),a=re(i),d=w("div",["editor-block-anchor"],a);d.style.top=`${s.top-l.top}px`,ym(d,{elementToScroll:ro(n.rootContainer)}),setTimeout(()=>{d.remove()},200)}function oT(n,t){if(t.isCollapsed())return!1;const e=Le(n.rootContainer),o=Ze(n.rootContainer),{start:r,end:i}=t;return r.blockId===it(e)&&r.offset===0&&i.blockId===it(o)&&i.offset===ut(n,o)}const x6=S("range-in-block");function I6(n,t){const e=t.getEditor(),o=e.getBlockById(t.start.blockId),r=e.getBlockById(t.end.blockId),i=o===n||Kt(n,o),s=r===n||Kt(n,r);return!!(i||s)}function T6(n,t){const e=n.doc.toJSON(),o=new Set(Object.values(e.blocks).map(s=>s.map(l=>l.id)).flat());let r,i=ce(t);if(i){for(;i&&!o.has(it(i));)i=ce(i);g(x6,i,"no prev block while deleting a block"),r=ye(n,i,ut(n,i))}else{const s=Zt(t);g(x6,s,"no prev and next block while deleting a block"),r=ye(n,s,0)}return r}const rT=S("block-to-html");function Eg(n,t,e,o){const r=Ls(n,t.type);if(r.convertTo)return r.convertTo(n,t,e,"html",o);if(r.blockKind!=="text")return`[${t.type}]`;g(rT,t.text,"no text");const i=ie(t.text);return`<div>${iC(i)}</div>`}const D6=S("block-to-text");function iT(n,t,e){let o="";return t.forEach(r=>{if(g(D6,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const i=r.attributes,s=n.editorBoxes.getBoxClass(i.type);if(s!=null&&s.convertTo){o+=s.convertTo(n,i,e,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}function Ah(n,t,e,o){const r=Ls(n,t.type);return r.convertTo?r.convertTo(n,t,e,"text",o):r.blockKind!=="text"?`[${t.type}]`:(g(D6,t.text,"no text"),iT(n,t.text,e))}function xg(n,t,e,o){const r=Ls(n,t.type);return r.convertTo?r.convertTo(n,t,e,"markdown",o):Ah(n,t,e,o)}function bh(n,t){return t.blocks.root.map((r,i)=>Eg(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
|
|
25
25
|
`)}function S6(n,t){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${bh(n,t)}</body></html>`}function Sa(n,t){return t.blocks.root.map((r,i)=>Ah(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
|
|
26
26
|
`)}function La(n,t){const e=t.blocks.root.map((r,i)=>xg(n,r,t,[{containerId:"root",blockIndex:i}]));return e[e.length-1]=e[e.length-1].trimEnd(),e.join(`
|
|
27
|
-
`)}const sT=S("get-text-position");function ql(n,t){const e=t!=null?t:n.selection.range.start;e instanceof je||g(sT,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=bt(r),s=nt(r),l=at(s),{offset:a}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const Gl=S("insert-text");function Ig(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(g(Gl,r,"no block data"),g(Gl,r.text,"no block text"),rn(r.text)===0)return g(Gl,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=ze(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function lT(n,t,e){const o=nt(t),r=at(o),i=bt(t);return Ig(n,r,i,e)}function L6(n,t,e,o,r){const i=nt(t),s=at(i),l=bt(t),a=lT(n,t,e),d=ch(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),mn(n,t)}function M6(n,t,e,o){const r=nt(t),i=at(r),s=bt(t),l=ch(e," ",o);return n.doc.localUpdateBlockText(i,s,l),mn(n,t)}function cT(n,t){let e=0;if(t===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(Gl,typeof r.insert=="string","invalid text op, no insert");const i=e+ah(r);if(i===t)return!1;if(i>t)return!0;e=i}return!1}function Tg(n,t,e,o,r){const i=n.doc.getBlockData(e,o);g(Gl,i,"no block data"),g(Gl,i.text,"no block text");const s=Ig(n,e,o,r);s&&Object.keys(s).includes("link")&&(cT(i.text,r)||delete s.link);const l=ch(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),mn(n,n.getBlockById(i.id))}function Dg(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=ql(n);Tg(n,t,e,o,r)}const vh=S("update-composition-text");function R6(n){const t=n.selection.range.start;t instanceof je||g(vh,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(vh,tt(n,o),"not a text kind block");const r=nt(o),i=at(r),s=bt(o),l=n.doc.getBlockData(i,s);g(vh,l,"no block data in doc"),g(vh,l.text,"no text data in text block");const a=Lt(o);rh(n,Si(o),e,a,l.text)}function O6(n){Hx(n)}function Zl(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Ma=S("delete-block-text");function Sg(n,t,e,o,r){if(!n.isBlockWritable(t))return Ma.error("block is not writable"),0;g(Ma,tt(n,t),"block is not a text kind block");const i=nt(t),s=at(i),l=bt(t),a=n.doc.getBlockData(s,l);g(Ma,a,"no block data in doc"),g(Ma,a.text,"no text data in text block");let d=e;sn(t,e)||(d=Mi(t,d));let h=e+o;g(Ma,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),sn(t,h)||(h=Fs(t,h));const p=h-d,A=z4(d,p);return n.doc.localUpdateBlockText(s,l,A,r),p}const Lg=S("break-text-block");function _6(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Ql(n,t,e,o){g(Lg,tt(n,t),`block is not a text kind block: ${Dt(t)}`),g(Lg,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=nt(t),i=at(r),s=bt(t),l=o!=null&&o.copyBlockAttributes?_6(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...lr(""),...l,...o==null?void 0:o.newBlockData},D=ye(n,t.id,0),x=Zl(n,i,v,B,D);return{block:t,newBlock:x}}g(Lg,sn(t,e),"not a valid offset");const a=mn(n,t),{right:d}=xn(a,e),h=rn(d);h>0&&Sg(n,t,e,h);const p={...lr(d),...l,...o==null?void 0:o.newBlockData},A=Zl(n,i,s+1,p,ye(n,p.id,0));return{block:t,newBlock:A}}const aT=S("prepare-insert-new-block");function uT(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=pe(d);return g(aT,e>=0&&e<=h.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(t=at(nt(r)),e=bt(r),!tt(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===ut(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const a=Ql(n,r,s).newBlock;return{containerId:t,blockIndex:bt(a)}}const dT=S("auto-insert-block");function F6(n,t,e,o,r,i){const s=uT(n,e,o);g(dT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},a={anchor:l,focus:l};return Zl(n,s.containerId,s.blockIndex,t,r!=null?r:a,i)}const hT=S("delete-block");function yh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{yh(n,i,e)})}))}function kh(n,t,e){const o=nt(t),r=at(o),i=bt(t),s=n.doc.getBlockData(r,i);return g(hT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ue(n,{anchor:e.start,focus:e.end})),s}function Mg(n,t,e){return n.undoManager.runInGroup(()=>{const o=nt(t);Io(o)===1&&n.insertTextBlock("",at(o),0);let r=e?Li(n,e):null;if(!r){const l=n.selection.range;I6(t,l)?r=T6(n,t):r=l}const i=kh(n,t,r),s=[];return yh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function fT(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{yh(n,r,e)}),n.doc.localDeleteChildContainers(e)}function P6(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{yh(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const Rg=S("merge-text-block");function N6(n,t,e){g(Rg,tt(n,t),"only text block can be merged"),g(Rg,tt(n,e),"only text block can be merged");const o=Oi(n,t),r=Oi(n,e),i=o.text,s=r.text;g(Rg,i&&s,"block data has no text");const l=nt(t),a=at(l),d=bt(t),h=ut(n,t),p=Tg(n,s,a,d,h),A=ye(n,t,rn(i));return Mg(n,e,A),p}const cr=S("clear-selected-contents");function wh(n,t){g(cr,tt(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(cr,e.isSimple(),"not a simple block position"),g(cr,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(cr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function $6(n,t,e){const o=at(t),r=pe(t),i=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});e.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function mT(n,t){const{block:e,start:o,end:r}=t;if(tt(n,e)){wh(n,t);return}if(Me(e)||o.isSimple()){g(cr,r.isSimple(),"invalid range");const s=nt(e),l=bt(e),a=n.insertTextBlock("",at(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(cr,Mt(n,e),"invalid block kind"),g(cr,!o.isSimple()&&!r.isSimple(),"invalid range"),Rs(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{$6(n,s,{focus:l===0})})}function gT(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(cr,e.length>0,"no selected block"),e.length===1){mT(n,e[0]);return}const o=e[0],r=o.block,i=nt(r);g(cr,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(tt(n,r)){wh(n,o);const h=ye(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(A=>n.deleteBlock(A.block)),tt(n,l)){wh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(tt(n,l)){wh(n,s),e.slice(0,e.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(e.length===Io(i)){$6(n,i,{focus:!0});return}const a=ce(r),d=Zt(l);g(cr,a||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function Og(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),gT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const pT=S("core");function H6(n,t,e){const o=nt(t),r=at(o),i=bt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),mn(n,t)}function j6(n,t,e){if(!n.isBlockWritable(t)){pT.error("block is not writable");return}const o=n.getBlockText(t),r=ln.diff(o,e);H6(n,t,r)}function Bh(n,t,e){const o=mn(n,t),r=typeof e=="string"?Ri(e):e,i=ln.diff(o,r);return H6(n,t,i)}const Ra=S("update-block-data");function Eh(n,t,e,o){const r=nt(t),i=at(r),s=bt(t),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(e));return d.forEach(A=>{if(!h.has(A)){if(A==="id"||A==="type"||A==="text")return;Ra.debug(`delete key: ${A}`),a.delete.push(A)}}),Object.entries(e).forEach(([A,v])=>{g(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&&(aa.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),Oi(n,t)}function U6(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function _g(n,t,e){if(!Mt(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=Un(n,t).getChildContainers(n,t)[0],i=Le(r);_g(n,i,e)}function $s(n){const t=[];let e={};return n.forEach(o=>{t.push(...o.blocks.root);const{root:r,...i}=o.blocks;e={...e,...i}}),{blocks:{...e,root:t},meta:{},comments:{}}}const Oa=S("clone-block");function _i(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,p)=>(g(Oa,e!==p,"invalid child block"),_i(n,h,e,o)));let i={};const s=new Map,l=mt.default(e);l.children&&(l.children=l.children.map(h=>{const p=K(),A=t.blocks[h];g(Oa,Array.isArray(A),"invalid child blocks");const v=A.map(_=>_i(n,t,_,o)),B=$s(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(e.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Fg(n,t,e,o){const r=t.blocks[e];g(Oa,Array.isArray(r),"invalid child blocks");const i=r.map(l=>_i(n,t,l,o));return $s(i)}function Pg(n,t,e){const o=t.blocks.root.map(r=>_i(n.editorBlocks,t,r,e));return mt.default($s(o))}const z6=S("insert-doc");function V6(n,t,e,o,r){if(Mt(n,t)){z6.warn("failed to insert doc into a complex block");return}const i=Pg(n,o,r),s=nt(t),l=bt(t),a=at(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var M,H,z;Object.entries(i.blocks).forEach(([q,rt])=>{q!=="root"&&n.doc.localInsertChildContainer(q,rt)});const d=i.blocks.root;if(Me(t)){n.deleteBlock(t);let q;d.reverse().forEach(rt=>{const ft=n.insertBlock(a,l,rt);q||(q=ft)}),q&&n.selection.selectBlock(q,ut(n,q));return}if(g(z6,tt(n,t),"not a text block"),he(n,t)){const q=a==="root"&&n.getBlockByIndex(a,0)===t,rt=bt(t);let ft;d.forEach((Bt,jt)=>{const Ut=n.insertBlock(a,rt+jt,Bt);jt===d.length-1&&(ft=Ut)}),ft&&n.selection.selectBlock(ft,ut(n,ft)),q&&n.deleteBlock(t);return}if(d.length===1){const q=d[0];if(va(n,q.type)){n.insertTextToBlock(t,e,(M=q.text)!=null?M:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,q);return}const h=e===ut(n,t),p=e===0,A=d[0],v=d[d.length-1];let B;!h&&!p?B=n.breakTextBlock(t,e,{forceInsertAfter:!0}):B=t;const D=p?l:l+1;h?(B=n.insertBlock(a,l+1,v),n.selection.selectBlock(B,ut(n,B))):(n.selection.selectBlock(B,0),va(n,v.type)?n.insertTextToBlock(B,0,(H=v.text)!=null?H:[]):n.insertBlock(a,D,v));const x=n.selection.range;let _=D;va(n,A.type)?p?(n.insertBlock(a,D,A),_+=1):n.insertTextToBlock(t,e,(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 Ng(n,t,e,o,r){const i=Pg(n,o,r),s=at(t),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,e,d);l.push(h)})}),l}function W6(n,t,e){const o=Io(t);Ng(n,t,o,e);for(let r=0;r<o;r++){const i=Le(t);n.deleteBlock(i)}}const _a=S("add-text-attribute");function CT(n,t,e,o){const{start:r,end:i}=e;g(_a,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g(_a,o,"invalid attribute name");const s=n.getBlockText(t),l=Wl(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function q6(n,t,e,o,r){const{start:i,end:s}=e;g(_a,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(_a,o,"invalid attribute name");const l=n.getBlockText(t),a=xa(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Yl(n,t,e,o,r){const{start:i,end:s}=e;g(_a,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=X4(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function G6(n,t,e,o){const r=Ro(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!tt(n,s))return;if(he(n,s)){o(n,it(s),t,e);return}const d=Ue(n,{anchor:l,focus:a});t==="color"||t==="backgroundColor"?Yl(n,s,d,t,e):(Yl(n,s,d,"color",null),Yl(n,s,d,"backgroundColor",null))})})}function Z6(n,t,e){const o=Ro(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!tt(n,i))return;if(he(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,it(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,it(i),"backgroundColor",null);return}const a=Ue(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Yl(n,i,a,"color",null),(t==="clearBackground"||t==="clearAll")&&Yl(n,i,a,"backgroundColor",null)})})}function $g(n,t){const e=Ro(n,{simpleBlockOnly:!0}).filter(s=>tt(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(ut(n,s.block)===0)return t(n,it(s.block));const l=s.start,a=s.end,d=n.getBlockText(s.block);return n6(l.offset,a.offset-l.offset,d)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,a]=o(s);l===null||r===null?r=null:r=l===r?r:null,a===null||i===null?i=null:i=a===i?i:null}),[r,i])}const Wn=S("adjust-selection-pos");function Q6(n){const t=[];for(;n;){const e=nt(n);if(t.unshift(e),Xt(e))return t;const o=et(e);g(Wn,o,"child container has not parent container"),n=o}g(Wn,!1,"should not come here: getParentContainers")}function Y6(n,t){for(;t;){const e=nt(t);if(e===n)return t;const o=et(e);g(Wn,o,"could not find parent block for a child container"),t=o}g(Wn,!1,"no parent block in specified container")}function AT(n,t){const e=Q6(n),o=Q6(t);g(Wn,e.length>0&&o.length>0,"block has not parent container"),g(Wn,e[0]===o[0],"root container does not equal");let r=e[0];for(let l=1;l<e.length||o.length;l++)if(e[l]!==o[l]){r=e[l-1];break}const i=Y6(r,n),s=Y6(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function J6(n,t){let e=et(t);for(g(Wn,e,"element is not in a block");e;){const o=nt(e);g(Wn,Lo(o),"not a child container");const r=et(o);if(g(Wn,r,"child container has not parent block"),r===n)return o;e=r}g(Wn,!1,"failed to find parent container in complex block")}function xh(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof je&&e instanceof je?{anchor:t,focus:e}:t instanceof Mo&&e instanceof Mo?nh(n,o,t,e):null;const i=nt(o),s=nt(r);if(i===s)return t instanceof Mo&&(t=st(o,0,"home")),e instanceof Mo&&(e=st(r,ut(n,r),"end")),g(Wn,t instanceof je,"not valid position type"),g(Wn,e instanceof je,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof je&&e instanceof Mo){const B=n.getContainerById(e.childContainerId);if(B===i)return{anchor:e,focus:e};const D=et(i);if(D&&D===et(B)){const x=fe(D,at(i)),_=fe(D,at(B));return nh(n,D,x,_)}}return null}const l=$d(o,r)>0,{newBlock1:a,newBlock2:d}=AT(o,r);if(a===d){const B=a,D=J6(B,o),x=J6(B,r);return t=fe(a,at(D)),e=fe(a,at(x)),Wn.debug(`select in complex block: ${D.id}, ${x.id}`),nh(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof je&&(h=t.offset);let A=l?0:ut(n,d);return d===r&&e instanceof je&&(A=e.offset),t=st(a,h,l?"end":"home"),e=st(d,A,l?"home":"end"),{anchor:t,focus:e}}const bT=S("move-complex-block-position");function vT(n,t,e){const o=n.getBlockById(t.blockId);g(bT,Mt(n,o),"is not a complex block");const r=Un(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?fe(o,at(s)):null}const Fa=S("move-simple-block-position");function K6(n,t){const e=En(n,t,{visibleOnly:!0});g(Fa,e.length>0,"complex block has not any child container");const o=e[0];return Le(o)}function X6(n,t){const e=En(n,t,{visibleOnly:!0});g(Fa,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Ze(o)}function tA(n,t,e){const o=e?K6(n,t):X6(n,t);return Mt(n,o)?tA(n,o,e):o}function yT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===0?K6(n,e):Ds(e)}function kT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===1?X6(n,e):Ts(e)}function Hg(n){return n==="ArrowLeft"||n==="ArrowUp"}function jg(n,t,e){const o=nt(t);if(Xt(o))return null;const r=et(o);g(Fa,r,"child container has not parent block"),g(Fa,Mt(n,r),"is not a complex block");const i=Un(n,r).getNextContainer(n,r,o,e);return i?Hg(e)?Ze(i):Le(i):jg(n,r,e)}function wT(n,t,e){const o=nt(t);if(Xt(o))return null;const r=et(o);if(g(Fa,r,"child container has not parent block"),Hg(e)){const l=ce(r);if(l)return l}else{const l=Zt(r);if(l)return l}const i=jg(n,r,e);if(i)return i;let s=r;for(;!Xt(nt(s));)s=et(nt(s));return Hg(e)?ce(s):Zt(s)}function BT(n,t,e){return!Mt(n,t)||Un(n,t).enableKeyboardSelect?t:tA(n,t,e==="ArrowDown"||e==="ArrowRight")}function ET(n,t,e){const o=n.getBlockById(t.blockId),i=Qt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?yT(n,t):kT(n,t);if(s||(s=jg(n,o,e),s||(s=wT(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Xt(nt(o)))return null;const l=n.insertTextBlock("",at(n.rootContainer),Io(n.rootContainer));return st(l,0,"home")}return null}if(s=BT(n,s,e),tt(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return Kx(n,s,o,t,l);if(e==="ArrowUp")return Jx(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?st(s,ut(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?st(s,0,"home"):null}function xT(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(tt(n,r))return o;const i=Zt(r);if(i)return st(i,0,"home");if(!Xt(nt(r))||n.readonly)return o;const s=n.insertTextBlock("",at(n.rootContainer),Io(n.rootContainer));return st(s,0,"home")}function IT(n,t,e){const o=n.selection.range;let r;if(o instanceof Qe)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=xT(n,t,o):r=ET(n,o.getFocusedPos(),t);else if(r=vT(n,o.focus,t),e==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Ze(s);r=st(l,0,"home")}else{const l=Le(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:xh(n,o.anchor,r):null}function Fi(n,t,e){const o=IT(n,t,e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function eA(n){return Fi(n,"ArrowLeft","move"),!0}function nA(n){return Fi(n,"ArrowRight","move"),!0}function oA(n){return Fi(n,"ArrowUp","move"),!0}function rA(n){if(Fi(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=nt(t);if(Xt(e)||Ze(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",at(o),Io(o)),!0}function iA(n){return Fi(n,"ArrowDown","select"),!0}function sA(n){return Fi(n,"ArrowLeft","select"),!0}function lA(n){return Fi(n,"ArrowRight","select"),!0}function cA(n){return Fi(n,"ArrowUp","select"),!0}const aA=S("word-offset");function Ug(n,t){const e=n.selection.range.focus;g(aA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"home");if(e.offset===0||!tt(n,o)){const s=ce(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&tt(n,s)){const a=bg(n,s,l.offset);return st(s,a,"normal")}return l}const r=bg(n,o,e.offset);return st(o,r,"normal")}function zg(n,t){const e=n.selection.range.focus;g(aA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!tt(n,o)){const s=Zt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&tt(n,s)){const a=vg(n,s,l.offset);return st(s,a,"end")}return l}const r=vg(n,o,e.offset);return st(o,r,"normal")}function uA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ug(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function dA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function hA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ug(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function fA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function Vg(n,t){if(!Mt(n,t))return t;const o=Un(n,t).getChildContainers(n,t)[0],i=pe(o)[0];return Vg(n,i)}function Wg(n,t){if(!Mt(n,t))return t;const e=Un(n,t).getChildContainers(n,t),o=e[e.length-1],r=pe(o),i=r[r.length-1];return Wg(n,i)}function mA(n){const t=Wg(n,Ze(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function gA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function pA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function qg(n){const t=Wg(n,Ze(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const CA=S("line-offset");function AA(n){const t=n.selection.range.focus;g(CA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!tt(n,e))return st(e,0,"home");let r=N4(e,t).start;const{next:i}=Kd(e,r);return i&&so(i)&&ba(i)==="br"&&(r+=1),st(e,r,"home")}function bA(n){const t=n.selection.range.focus;g(CA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!tt(n,e))return st(e,ut(n,e),"end");const o=N4(e,t);return st(e,o.end,"end")}function vA(n){if(!n.selection.range.focus.isSimple())return!1;const e=AA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function yA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function kA(n){if(!n.selection.range.focus.isSimple())return!1;const e=AA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function wA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const BA=S("find-block-position");function TT(n,t,e,o){g(BA,Mt(n,t),"is not a complex block");const r=Un(n,t).getChildContainers(n,t);g(BA,r.length>0,"complex block has not any child container");const i=So(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=I4(n,t,s,l);return Gg(n,a,e,o)}function Gg(n,t,e,o){if(Mt(n,t))return TT(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=So(n,e,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=st(r,0,"home");const h=ut(n,t);for(let p=0;p<=h;p++){const A=st(r,p,"normal"),v=So(n,t,A),B=nr(v,l,a);B<i&&(i=B,d=A)}return d}const EA=S("page-offset");function DT(n,t){const e=B6(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<KI(n))return n.getFirstBlock();const i=ce(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ce(s)}return n.getFirstBlock()}function ST(n,t){const e=B6(n)*.9,o=t.getBoundingClientRect(),r=XI(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=Zt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Zt(l)}return n.getLastBlock()}function xA(n){const t=n.selection.range.focus;g(EA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=DT(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=Gg(n,o,e,t),r}function IA(n){const t=n.selection.range.focus;g(EA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=ST(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=Gg(n,o,e,t),r}function TA(n){if(!n.selection.range.focus.isSimple())return!1;const e=xA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function DA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function SA(n){if(!n.selection.range.focus.isSimple())return!1;const e=xA(n);if(!e)return!1;const o=xh(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function LA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);if(!e)return!1;const o=xh(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const Pa=S("select-all");function MA(n,t){const e=Le(n),o=Ze(n);return t.start.offset===0&&t.start.blockId===it(e)&&t.end.offset===ut(t.getEditor(),o)&&t.end.blockId===it(o)}function LT(n,t){const e=t.getEditor(),o=Un(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=it(n);return t.start.blockId===s&&t.start.childContainerId===at(r)&&t.end.blockId===s&&t.end.childContainerId===at(i)}function MT(n,t){g(Pa,t,"no parent block"),g(Pa,Mt(n,t),"not a complex block");const e=Un(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Ue(n,{anchor:fe(t,at(o)),focus:fe(t,at(r))}))}function RA(n,t){const e=nt(t);Zg(n,e)}function OA(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&tt(n,t)){const r=e.start,i=e.end,s=ut(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return W(n.rootContainer,"select-all"),RA(n,Le(n.rootContainer)),!1}return g(Pa,!e.isSimple(),"invalid range type"),LT(t,e)?(RA(n,t),!1):(g(Pa,t,"no parent block"),g(Pa,Mt(n,t),"not a complex block"),MT(n,t),!0)}function Zg(n,t){const e=pe(t),o=e[0],r=e[e.length-1],i=st(o,0,"home"),s=st(r,ut(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function _A(n){qg(n),n.focus()}const Qg=S("selected-block-to-doc");function FA(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{FA(n,i,e)}),e.blocks[o]=mt.default(r)})}function Ih(n,t){const e=Qt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(Oi(n,t.block));if(tt(n,t.block)){const i=t.start,s=t.end;if(g(Qg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=ze(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Me(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(Qg,Mt(n,t.block),"not complex block"),g(Qg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return FA(n,o,r),r}function Yg(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Ih(n,{block:t,start:e,end:o})}const RT=S("block-to-doc");function OT(n,t){g(RT,t.length>0,"invalid params, no blocks");const e=t.map(o=>Yg(n,o));return $s(e)}function Th(n){const e=n.selection.range.getSelectedBlocks().map(o=>Ih(n,o));return $s(e)}function PA(n,t){const e=n.getContainerById(t),i=pe(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Ih(n,s));return $s(i)}const Dh=S("editor-selection");class _T{constructor(t){m(this,"editor");m(this,"caret");m(this,"_range");m(this,"lastCaretRect");m(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(I6(e,i)){Dh.debug("adjust selection because remote deleted current block");const s=T6(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new QI(t);const r=st(o,0,"normal");this._range=Ue(t,{anchor:r,focus:r}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const t=this.range.focus;return this.editor.getBlockById(t.blockId)}getStartBlock(){const t=this.range.start;return this.editor.getBlockById(t.blockId)}getEndBlock(){const t=this.range.end;return this.editor.getBlockById(t.blockId)}selectBlock(t,e,o){const r=st(t,e,"normal");let i;o&&(i=st(t,o,"normal")),this.setSelection(r,i)}setSelection(t,e,o){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const r=Ue(this.editor,{anchor:t,focus:e});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),xt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!oT(this.editor,r))&&ot(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),YI(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(t,e){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const t=this.range.focus;if(!jr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=So(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){nT(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Dh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Dh,!1,"invalid complex block position, no container found")}}updateFocusedBlock(t){if(t&&this.range.start.blockId===t.start.blockId)return;let e;t&&t.start.blockId===t.end.blockId&&(e=this.editor.findBlockById(t.start.blockId));let o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;e&&xt(e,"focused")&&(ot(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=Th(this.editor);return t==="text"?Sa(this.editor,e):t==="markdown"?La(this.editor,e):S6(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{ot(t,"focused"),ot(t,"child-focused")})}setBlockFocused(t){if(xt(t,"focused"))return!1;W(t,"focused");let e=nt(t);for(;Lo(e);){const o=et(e);g(Dh,o,"parent block not found"),W(o,"child-focused"),e=nt(o)}return!0}}function FT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,ut(n,e))}function PT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!tt(n,e))return;let o=Ug(n,"select"),r=zg(n,"select");if(!o||!r)return;const i=t.blockId;o.blockId!==i&&(o=st(e,0,"home")),r.blockId!==i&&(r=st(e,ut(n,e),"end")),n.selection.setSelection(o,r)}class NT{constructor(t){m(this,"editor");m(this,"startPos",null);m(this,"lastCaretRect");m(this,"mouseDownEvent",null);m(this,"autoScroll",null);m(this,"handleMouseDown",(t,e)=>{var r;this.mouseDownEvent=t;const o=S4(this.editor,t.x,t.y);if(o){if(o instanceof rr)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=ro(s[0].block);this.autoScroll=new qd({scrollElement:l,edge:{top:50,bottom:50}})}const i=this.editor.selection.range;if(t.shiftKey&&i.isSimple()){const s=i.anchor;this.editor.selection.setSelection(s,o.focus),this.startPos=o.start}else this.editor.selection.setSelection(o.anchor,o.focus),this.startPos=o.start;this.editor.selection.updateLastCaretRect(),e.autoScroll&&((r=this.autoScroll)==null||r.active())}});m(this,"handleMouseMove",t=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-t.x)<3&&Math.abs(this.mouseDownEvent.y-t.y)<3)return;const e=oh(this.editor,t.x,t.y);if(!e)return;const o=xh(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});m(this,"handleMouseUp",t=>{var e;(e=this.autoScroll)==null||e.inactive(),this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){PT(this.editor)}handleTripleClick(t){FT(this.editor)}}function $T(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function HT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const NA=S("delete-text");function $A(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof je||g(NA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(NA,tt(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!sn(s,l-e)){const a=Mi(s,l);e=l-a}}else if(t==="forward"&&l+e>ut(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function HA(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const jT=S("handle-backspace");function Jg(n,t){if(!he(n,t))return;const e=nt(t);Io(e)!==1&&n.deleteBlock(t)}function UT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===0){if(HA(n,o))return;const r=ce(o);if(r){if(!n.isBlockWritable(r))return;if(tt(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Mt(n,r)){Jg(n,o);const i=zl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else Jg(n,o),g(jT,Me(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=nt(o);if(Lo(i)){const s=B4(n,i);if(s){if(!n.isBlockWritable(s))return;Jg(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else $A(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function zT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===ut(n,o)){const r=Zt(o);if(r){if(!n.isBlockWritable(r))return;tt(n,r)?n.mergeTextBlock(o,r,{focus:!0}):he(n,o)?n.deleteBlock(o,ye(n,r,0)):n.deleteBlock(r)}}else $A(n,"forward",1,null);else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function VT(n){const{range:t}=n.selection,{start:e,end:o}=t,r=n.getBlockById(e.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Mt(n,r))return!1;if(jr(e))return!0;const s=Rs(n,r,e,o),l=En(n,r);return s.length===l.length}function WT(n,t){if(VT(n)){const o=n.getFocusedBlock(),r=bt(o),i=at(nt(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(tt(n,e)){if(he(n,e)&&HA(n,e))return;const o=n.selection.range.start,r=n.breakTextBlock(e,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 qT(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!tt(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const GT=S("input-handler-actions");function ZT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(WT(n),!0))}function QT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(zT(n),!0))}function YT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(UT(n),!0))}function JT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(qT(n),!0))}function KT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{GT.error(t)}),!0)}const Sh={ArrowDown:rA,ArrowUp:oA,ArrowLeft:eA,ArrowRight:nA,"Shift+ArrowDown":iA,"Shift+ArrowUp":cA,"Shift+ArrowLeft":sA,"Shift+ArrowRight":lA,"CtrlOrCmd+ArrowLeft":uA,"CtrlOrCmd+ArrowRight":dA,"CtrlOrCmd+Shift+ArrowLeft":hA,"CtrlOrCmd+Shift+ArrowRight":fA,"CtrlOrCmd+ArrowUp":gA,"CtrlOrCmd+ArrowDown":mA,"CtrlOrCmd+Shift+ArrowUp":pA,"CtrlOrCmd+Shift+ArrowDown":qg,"CtrlOrCmd+A":OA,Home:kA,End:wA,"Shift+Home":vA,"Shift+End":yA,PageUp:TA,PageDown:DA,"Shift+PageUp":SA,"Shift+PageDown":LA,"CtrlOrCmd+Z":$T,"CtrlOrCmd+Shift+Z":HT,Enter:ZT,Delete:QT,Backspace:YT,"Shift+Enter":JT,"CtrlOrCmd+Shift+V":KT};function jA(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function UA(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){const l=e.get(s);l&&(i.src=l)}return}const o=t.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=e.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{UA(n,l,e)})})}function zA(n,t,e){if(e.size===0)return;t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,e):UA(t,r,e)})}async function XT(n,t){const e=t.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(e),r=new Map;if(e.length!==o.length)return r;for(let i=0;i<e.length;i++)r.set(e[i],o[i]);return r}function tD(n,t){var i,s;const o=t.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function eD(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(tD(n,t)){const s=Array.from(Object.keys(o));r=await XT(n,s),zA(n,t,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&zA(n,t,i)}async function nD(n,t,e){await eD(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Me(i)){const s=nt(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,t,e);a&&n.selection.selectBlock(a,ut(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=ql(n);n.insertDoc(s,l,t,e)}})}const oD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function rD(n){let t;for(const e of oD)if(t=n[e],t)break;return t||null}function VA(n,t,e){if(t.type==="embed"){const s=t.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))e.add(l);return}const o=t.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&e.add(i.attributes.src)});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{VA(n,l,e)})})}function iD(n,t){const e=new Set;return t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{e.add(s)}):VA(t,r,e)}),Array.from(e)}function Lh(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${ws(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Mh(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=iD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function sD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Th(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Mh(n,o);const i=bh(n,o),s=La(n,o),l=Lh(i,o);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Rh(n,t){const e=Yg(n,t);Mh(n,e);const o=bh(n,e),r=La(n,e),i=Lh(o,e);return Lm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class lD{constructor(t){m(this,"editor");m(this,"handlers",[]);m(this,"onPasteText",async(t,e)=>{const o=new DataTransfer;o.setData("text/plain",t);const r=await this.editor.dataConverter.fromData(this.editor,o,e);r&&this.pasteDocs(r,null)});this.editor=t}onInsertText(t,e){if(!tt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=ql(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,e),this.editor.selection.updateLastCaretRect())}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleChanged&&o.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=ql(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,o,r)}}onUpdateCompositionText(t,e,o){this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=ql(this.editor);for(let l=0;l<this.handlers.length;l++){const a=this.handlers[l];a.handleUpdateCompositionText&&a.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(t){sD(this.editor,t,(e,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Me(o)&&this.editor.deleteBlock(o)}else Og(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{o&&this.pasteDocs(o,t)})}onFocus(){W(this.editor.rootElement,"active")}onBlur(){ot(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,o)=>{var s,l;const r=(s=e.order)!=null?s:1;return((l=o.order)!=null?l:1)-r})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,o,r))return!0}return!1}handleAfterInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,o,r))return!0}return!1}handleBeforeKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,o,r,i){Dg(this.editor,i)}defaultHandleKeydown(t,e){return jA(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await nD(this.editor,t,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,e,t))return}const o=rD(t);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function cD(n,t,e){const o=_r(t,e);return o.remove(),o}S("copy-dom-attributes");const WA=["onabort","onanimationcancel","onanimationend","onanimationiteration","onanimationstart","onauxclick","onblur","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","ongotpointercapture","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onlostpointercapture","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onpause","onplay","onplaying","onpointercancel","onpointerdown","onpointerenter","onpointerleave","onpointermove","onpointerout","onpointerover","onpointerup","onprogress","onratechange","onreset","onresize","onscroll","onsecuritypolicyviolation","onseeked","onseeking","onselect","onselectionchange","onselectstart","onslotchange","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","ontouchcancel","ontouchend","ontouchmove","ontouchstart","ontransitioncancel","ontransitionend","ontransitionrun","ontransitionstart","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","onwheel"];function aD(n,t){for(let l=0;l<WA.length;l++){const a=WA[l];t[a]=n[a]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const a=e[l],d=o.getNamedItem(a.name);d?d.value!==a.value&&(d.value=a.value,i.push(a)):r.push(a)}const s=[];for(let l=0;l<o.length;l++){const a=o[l];e.getNamedItem(a.name)||s.push(a)}r.forEach(l=>{t.setAttribute(l.name,l.value)}),i.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function qA(n){const t=Array.from(n.childNodes).filter(e=>!$C(e));return t.forEach(e=>{e.remove()}),t}function GA(n,t,e){var d;const o=n.getContainerById(t),r=_r(o,e),i=Si(r),s=n.doc.getBlockData(t,e),l=Qt(n,r);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const h=n.editorBlocks.createBlock(i,o,s),p=qA(h);qA(r),p.forEach(v=>{r.appendChild(v)});const A=Yd(h);if(A){const v=Yd(r);v&&v.remove(),r.appendChild(A)}aD(h,r)}o4(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 uD=S("transform-selection");function ZA(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(uD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const d=ln.transformCursor(i.offset,e,o);l=st(t,d,"normal")}let a=s;if(s.blockId===t){const d=ln.transformCursor(s.offset,e,o);a=st(t,d,"normal")}return Ue(n,{anchor:l,focus:a})}const dD=S("handle-block-text-changed");function hD(n,t,e,o,r){const i=n.getContainerById(t),s=_r(i,e),l=n.doc.getBlockData(t,e);if(g(dD,l.text,"no block text"),JC(n,s).setBlockText(n,s,l.text),!r){const a=ZA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function fD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function QA(n,t,e,o){const r=Qt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function mD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{QA(n,i,o,{child:!0})}),QA(n,r,o,{child:!1})}const _o=S("editor-doc");class gD extends ha{constructor(e,o,r){super();m(this,"localEvents",[]);this.editor=e,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}verifyBlockWritable(e,o){const r=this.editor.getBlockByIndex(e,o);g(_o,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(_o,l,`no text, ${e}, ${o}`);const a=ZA(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(e,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(e,o,r,i){g(_o,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,o);if(!this.editor.isBlockWritable(s)){const h=Array.from(r.delete).filter(A=>A!=="comments"),p=Object.keys(r.insert).filter(A=>A!=="comments");(h.length>0||p.length>0)&&g(_o,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(fD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(Li(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(_o,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return this.editor.selection.setRange(Li(this.editor,i),s),l}localDeleteBlock(e,o,r){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const i=mt.default(this.getBlockData(e,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,o,i,r));const s=this.externalDoc.localDeleteBlock(e,o,r);return this.editor.selection.setRange(Li(this.editor,r)),s}localDeleteChildContainers(e){return g(_o,!this.editor.readonly,"editor is readonly"),e.forEach(o=>{const r=mt.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainer(e,o){return g(_o,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,mt.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){_o.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,o,r,i)}),hD(this.editor,e,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,i)}),GA(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);ox(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){mD(this.editor,e,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,r)});const i=this.editor.getContainerById(e);cD(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(e,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,r)})}onDeleteChildContainer(e,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,e)})}onStatusChanged(e){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)})}onError(e){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,e)})}uploadResource(e,o){return this.externalDoc.uploadResource(e,o)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,o){return this.externalDoc.buildResourceUrl(e,o)}request(e,o){return this.externalDoc.request(e,o)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,o,r;return(r=(o=(e=this.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}reset(e){_o.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function YA(n,t){if(n.length===0){n.push(t);return}const e=n[n.length-1];if(!e.combinable(t)){n.push(t);return}e.combine(t)}const Kg=S("undo-action");class Jl{constructor(t,e,o){m(this,"beforeRange");m(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=o}undo(t){return!1}redo(t){return!1}combinable(t){return g(Kg,t,"no other action"),!1}combine(t){g(Kg,!1,"no other")}setAfterRange(t){this.afterRange&&Kg.warn("after range has already set"),this.afterRange=t}}const pD=S("block-action");class JA extends Jl{constructor(e,o,r,i,s){super(e,o,s);m(this,"blockData");m(this,"blockIndex");this.blockData=mt.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(g(pD,this.blockIndex===bt(i),"invalid block index"),kh(e,i,Li(e,o)),!0):!1}insertBlock(e,o){return Zl(e,this.containerId,this.blockIndex,mt.default(this.blockData),o),!0}}class CD extends JA{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class AD extends JA{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class bD extends Jl{constructor(e){super(e,at(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){YA(this.actions,e),this.afterRange=e.afterRange}undo(e){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(e)&&(o=!0)}),o}redo(e){let o=!1;return this.actions.forEach(r=>{r.redo(e)&&(o=!0)}),o}setAfterRange(e){this.afterRange=e;const o=this.actions[this.actions.length-1];!o||o instanceof Jl&&(o.afterRange||o.setAfterRange(e))}}const Hs=S("update-block-data-action");class Oh extends Jl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=r,g(Hs,this.blockId===i.id,"invalid block id"),g(Hs,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(i),this.afterBlockData=mt.default(s),g(Hs,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Eh(e,o,Oh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Eh(e,o,Oh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const Xg=S("update-block-text-action");class Na extends Jl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=r,this.beforeRichTextData=mt.default(i),this.afterRichTextData=mt.default(s),this.type=Na.calType(i,s)}static calType(e,o){g(Xg,e,"no old data"),g(Xg,o,"no new data");const i=ln.diff(e,o),s=new Set;let l=!1;const a=h=>mC(h)?`cjk_${h}`:hC(h)?"number":Hd(h)?"space":fC(h)?"letter":"unknown";let d=!1;return i.forEach(h=>{h.insert?h.insert===" "?s.add("insert_letter"):typeof h.insert=="string"&&h.insert.startsWith(" ")&&h.insert.length>1?(l=!0,d=!0,s.add(`insert_${a(h.insert.substr(1))}`)):s.add(`insert_${a(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Bh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Bh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Na)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const o=e.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(e){g(Xg,e instanceof Na,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class KA extends Jl{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return t.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(t){return t.doc.localInsertChildContainer(this.containerId,mt.default(this.blocks)),!0}}class vD extends KA{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class yD extends KA{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Fo=S("undo");class kD{constructor(t){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(this,"handleSelectionChange",t=>{if(this.currentGroup){this.currentGroup.setAfterRange(t.selection.range.toDocRange());return}const e=this.actions[this.actions.length-1];!e||e.afterRange||e.setAfterRange(t.selection.range.toDocRange())});this.editor=t,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(t){this.currentGroup?this.currentGroup.addAction(t):(YA(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Fo,!this.currentGroup,"current group already exists"),this.currentGroup=new bD(this.editor),this.groupCounter=1):(g(Fo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Fo,this.currentGroup,"current group not exists"),g(Fo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Fo.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw Fo.error(`failed to run action: ${e.message}`),e}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const t=this.actions[this.undoCursor];if(t.undo(this.editor)){try{this.editor.selection.setRange(Li(this.editor,t.beforeRange))}catch(e){Fo.error(`undo: failed to restore caret pos: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const t=this.actions[this.undoCursor];if(this.undoCursor+=1,t.redo(this.editor)){try{const e=t.afterRange;e?this.editor.selection.setRange(Li(this.editor,e)):Fo.warn("no after range")}catch(e){Fo.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),ln.diff(o,r).length!==0&&this.addAction(new Na(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Oh(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Fo,e>=0,"invalid block index"),g(Fo,o,"no block data"),this.addAction(new CD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new AD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new vD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new yD(this.editor,t,e)))}}class wD{async fromData(t,e){const o=e.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class BD{constructor(){m(this,"converters",[]);this.addConverter(new wD)}async fromData(t,e,o){let r={};for(const i of this.converters){const s=await i.fromData(t,e,o);s&&(r={...r,...s})}return r}addConverter(t){this.converters.push(t)}}class ED{constructor(t){m(this,"renders",[]);this.editor=t}registerRender(t){this.renders.push(t)}renderText(t,e){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,t,e);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(t,e,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,e,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(t,e,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,t,e,o,r)})}}class Ce extends ve.TypedEmitter{constructor(e){super();m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"filters",[]);m(this,"finders",[]);m(this,"handleDocumentMouseMove",e=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,e))return}const o=document.elementFromPoint(e.x,e.y);if(!o){this.setHoveringBlock(null,e,null);return}let r=et(o);if((!r||!Kt(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(e),!r)){this.setHoveringBlock(null,e,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,e,i)});this.editor=e,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(e=>e.destroy()),this.filters=[],this.finders.forEach(e=>e.destroy()),this.finders=[]}addFilter(e){this.filters.push(e)}addFinder(e){this.finders.push(e)}hoveringBlockId(){return this.hoveringBlock?it(this.hoveringBlock):""}findBlockByFinders(e){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,e);if(i)return i}return null}setHoveringBlock(e,o,r){if(this.hoveringBlock===e&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==e){const s=this.hoveringBlock&&Kt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&ot(s,"hover"),e&&W(e,"hover"),this.hoveringBlock=e,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(e){return e.addCustom("standard-hovering-block",()=>new Ce(e))}getParentTextContentChild(e,o){if(!tt(this.editor,e))return null;const r=Lt(e);return o.parentElement===r?o:Nm(o)}}const XA="style-color-",tb="style-bg-color-";class xD{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(XA)?i["data-style-color"]=l.substring(XA.length):l.startsWith(tb)?i["data-style-bg-color"]=l.substring(tb.length):l.startsWith("style")&&r.push(l):typeof a=="string"&&(l==="link"&&(r.push("link"),i.link=a),l==="inline-style-color"&&(s.color=a))}),{classes:r,attributes:i,styles:s}}renderBlock(t,e,o){var l,a;const r={};Object.entries(o).filter(d=>d[0].startsWith("style-")).forEach(([d,h])=>{r[`data-${d}`]=`${h}`});const s=[];return((a=(l=t.selection)==null?void 0:l.range)==null?void 0:a.start.blockId)===o.id&&s.push("focused"),typeof o.align=="string"&&o.align&&(r["data-style-align"]=o.align),o.heading&&(r["data-style-heading"]=String(o.heading)),o.quoted&&(r["data-style-quoted"]="true"),Ce.get(t).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(t,e,o,r){var s,l;Array.from(o.attributes).forEach(a=>{a.name.startsWith("data-style-")&&o.removeAttribute(a.name)}),Object.entries(r).filter(a=>a[0].startsWith("style-")||a[0]==="align").forEach(([a,d])=>{a==="align"&&o.setAttribute(a.startsWith("style-")?`data-${a}`:`data-style-${a}`,`${d}`)}),((l=(s=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),Ce.get(t).hoveringBlockId()===r.id&&W(o,"hover")}}function ID(n){n.editorBlocks.registerBlockClass(In),n.editorBlocks.registerBlockClass(w4),n.editorBoxes.registerBoxClass(f6),n.editorBoxes.registerBoxClass(m6),n.editorBoxes.registerBoxClass(C6),n.editorBoxes.registerBoxClass(A6),n.editorInsertions.registerInsertionClass(b6),n.editorBlockRenders.registerRender(new xD)}function TD(n,t){ID(n),t!=null&&t.blocks&&t.blocks.forEach(e=>n.editorBlocks.registerBlockClass(e)),t!=null&&t.boxes&&t.boxes.forEach(e=>n.editorBoxes.registerBoxClass(e)),t!=null&&t.embeds&&t.embeds.forEach(e=>n.editorEmbeds.registerEmbedClass(e)),t!=null&&t.insertions&&t.insertions.forEach(e=>n.editorInsertions.registerInsertionClass(e)),t!=null&&t.decorators&&t.decorators.forEach(e=>n.editorDecorators.registerDecorator(e)),t!=null&&t.dataConverters&&t.dataConverters.forEach(e=>n.dataConverter.addConverter(e)),t!=null&&t.commandProviders&&t.commandProviders.forEach(e=>n.editorCommandProviders.registerCommandProvider(e)),t!=null&&t.textRenders&&t.textRenders.forEach(e=>n.editorBlockRenders.registerRender(e))}const eb=S("range-commands");function nb(n,t){n.forEach(e=>{e.source=t,e.children&&nb(e.children,t)})}function ob(n,t,e){const o=it(t);g(eb,o===e.start.blockId,"invalid start range"),g(eb,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);nb(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),Mt(n,t)&&Rs(n,t,e.start,e.end).forEach(l=>{pe(l).forEach(d=>{const h=ut(n,d),p=Ue(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),A=ob(n,d,p);i.push(...A)})}),i}function rb(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Ue(t,{anchor:r.start,focus:r.end});ob(t,r.block,i).forEach(l=>{o.push(l)})}),o}function ib(n,t,e,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const A=s[p];if(A.beforeExecuteCommand&&A.beforeExecuteCommand(n,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,o,r,{}))return i[it(t)]=a,!0;let d=!1;return Mt(n,t)&&Rs(n,t,e.start,e.end).forEach(A=>{pe(A).forEach(B=>{const D=ut(n,B),x=Ue(n,{anchor:st(B,0,"home"),focus:st(B,D,"end")});ib(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function sb(n,t,e){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(t.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,t,e,r)||n.getSelectedBlocks().forEach(l=>{const a=Ue(o,{anchor:l.start,focus:l.end});ib(o,l.block,a,t,e,r)}),r}const DD=S("command-providers");class lb{constructor(t){m(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(o=>o.id===t);return g(DD,e,`no command provider, id=${t}`),e}getCommands(t){return rb(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>sb(t,e,o))}getEmptyBlockTextAttributes(t,e){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,t,e);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function SD(n,t){const e=nt(t),o=at(e),r=bt(t);GA(n,o,r)}const LD=S("table-scroll");class cb{constructor(t,e,o,r,i){m(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=o,this.handler=r,this.data=i,e.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class MD{constructor(t){m(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(o=>o.destroy()),this.handlers.delete(t)})}addEventListener(t,e,o,r){const i=this.handlers.get(t);if(i){if(i.find(s=>s.handler===o&&s.name===e)){LD.warn(`event has already registered: ${e}`);return}i.push(new cb(this.editor,t,e,o,r))}else{const s=new cb(this.editor,t,e,o,r);this.handlers.set(t,[s])}}removeEventListener(t,e,o){if(!t){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const a=s[l];if(e)e===a.name&&o===a.handler&&s.splice(l,1);else if(o===a.handler){s.splice(l,1),a.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(t);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===e);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const o=this.handlers.get(t);if(o)if(e)for(let r=0;r<o.length;r++){const i=o[r];i.name===e&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(t)}}const ab=S("update-block-text");function RD(n,t){const e=n.getBoxById(t.id),o=et(e);g(ab,o,"no parent block"),g(ab,tt(n,o),"not a text block");const r=n.getBlockText(o),i=r6(r,"id",t.id,t);j6(n,o,i)}function OD(n,t){for(const e of n.blockHooks)if(e.writable){const o=e.writable(n,t);if(typeof o=="boolean")return o}return!0}function _D(n){return n.readonly?!1:!Ro(n).find(o=>!n.isBlockWritable(o.block))}class FD{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}getItem(t){return window.localStorage.getItem(this.getKey(t))}setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class PD{constructor(){m(this,"shortcuts",[])}handleKeyboardEvents(t,e){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(Or(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const qr=S("editor");class ND extends ve.TypedEmitter{constructor(e,o,r){var i,s,l,a,d,h,p;super();m(this,"parent");m(this,"rootElement");m(this,"contentElement");m(this,"rootContainerObject");m(this,"rootContainer");m(this,"input");m(this,"selection");m(this,"selectionHandler");m(this,"doc");m(this,"id");m(this,"clientId");m(this,"compositingText","");m(this,"undoManager");m(this,"shortcuts",new PD);m(this,"dataConverter",new BD);m(this,"editorBlocks",new b4(this));m(this,"editorBoxes",new p6(this));m(this,"editorInsertions",new y6(this));m(this,"editorEmbeds",new y4(this));m(this,"editorDecorators",new k6(this));m(this,"editorCommandProviders",new lb(this));m(this,"editorBlockRenders",new ED(this));m(this,"blockHooks",[]);m(this,"domEvents",new MD(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new lD(this));m(this,"settingsProvider");m(this,"_readonly",!1);qr.debug("create editor"),this.setMaxListeners(100),this.options={colors:(i=r==null?void 0:r.colors)!=null?i:["#9923E9","#4587C2","#8BDB7A","#FB28D3","#CBC619","#10FEEB","#812A1A","#8A3F25","#22D742","#A53E74","#555C87","#57E0AA"],componentsOptions:(l=(s=r==null?void 0:r.components)==null?void 0:s.options)!=null?l:{},scrollContainer:r==null?void 0:r.scrollContainer},this.settingsProvider=(a=r==null?void 0:r.settingsProvider)!=null?a:new FD(this),TD(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 kD(this),this.doc=new gD(this,o,this.undoManager),this.parent=e,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=p4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new ZI(this,this.inputHandlers),this.selection=new _T(this),this.selectionHandler=new NT(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Ke.isMobile&&W(this.rootElement,"mobile"),Ke.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?W(this.rootElement,"readonly"):ot(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:ro(this.rootContainer)}addCustom(e,o){const r=this.customs.get(e);if(r)return r;const i=o(this);return this.customs.set(e,i),i}getCustom(e){const o=this.customs.get(e);return g(qr,o,`${e} does not exists`),o}replaceCustom(e,o){const r=this.customs.get(e);return r&&r.destroy(),this.customs.set(e,o),o}findCustom(e){return this.customs.get(e)}findCustomByType(e){const o=this.customs.values();for(const r of o)if(r instanceof e)return r;return null}destroyCustom(e){const o=this.customs.get(e);o&&(this.customs.delete(e),o.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,o,r){return this.editorBlocks.createBlock(e,o,r)}createBox(e,o){return this.editorBoxes.createBox(e,o)}createInsertion(e,o){return this.editorInsertions.createInsertion(e,o)}destroy(){qr.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(e=>e.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus(),setTimeout(()=>{W(this.rootElement,"active")})}focusToBlock(e,o){_g(this,e,o)}isWritable(){return _D(this)}isBlockWritable(e){return OD(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return g(qr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(qr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return C4(this,e,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(qr,Es(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(qr,Pm(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(qr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(qr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return _r(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return bt(o)}return bt(e)}getContainerById(e){return Hr(this,e)}getParentContainer(e){return nt(e)}reloadBlock(e){SD(this,e)}contains(e){const o=e instanceof Element?e:e.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,o,r,i,s){const l={blockId:r.id,offset:0},a={anchor:l,focus:l};return Zl(this,e,o,r,i!=null?i:a,s)}insertEmbed(e,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){Mg(this,e,o)}mergeTextBlock(e,o){return N6(this,e,o)}breakTextBlock(e,o,r){return Ql(this,e,o,r).newBlock}getTextPosition(){return ql(this)}getBlockString(e,o){const r=this.getBlockText(e);return ie(r,o)}getBlockData(e){return Oi(this,e)}getBoxData(e){return d6(this,e)}getBlockText(e){return mn(this,e)}setBlockText(e,o){j6(this,e,o)}deleteTextFromBlock(e,o,r,i){return Sg(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return L6(this,e,o,r,i)}insertBoxToBlock(e,o,r){return M6(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){V6(this,e,o,r,i)}insertDocAt(e,o,r,i){return Ng(this,e,o,r,i)}deleteChildContainers(e){P6(this,e)}replaceBlockText(e,o){return Bh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Eh(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return U6(this,e,o,r)}updateBoxData(e){RD(this,e)}getSelectedText(){const e=Th(this);return Sa(this,e)}clearSelectedContents(){Og(this)}insertTextBlock(e,o,r,i){const s=lr(e!=null?e:"");return F6(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){O6(this);return}o?(this.compositingText="",Bm()||Dg(this,e)):(this.compositingText=e,R6(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function $a(n,t,e){return new ND(n,t,e)}function $D(n){const t=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=hm.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const HD=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class _h extends ve.TypedEmitter{constructor(e){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=e&&e.length>0?e:HD}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&aa.default(o,e))return;this.cursors.set(e.user.userId,e);const r=new Set([e.range.anchor.blockId,e.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(e){this.addingUser=!0,e.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var o;return(o=this.users.get(e))!=null?o:null}removeUser(e){this.users.delete(e),this.cursors.delete(e),this.emit("change",Array.from(this.users.values()))}updateUsers(e){this.users.clear(),this.addingUser=!0;try{e.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e&&fh(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(fh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===e.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===e.id&&(d.offset=ln.transformCursor(d.offset,o,r))}})}getFixedUserColor(e,o){let r=0;Array.from(e).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const Xe=S("local-doc");class tp extends ha{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[lr("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`);const i=r[o];return g(Xe,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(Xe,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.call(l,e,o,r,!0)}),s}localUpdateBlockData(e,o,r){const i=this.getBlockData(e,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,!0)}),i}localInsertBlock(e,o,r){const i=this.getContainerBlocks(e);return g(Xe,i,`no container data: ${e}`),g(Xe,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,o,r,!0)}),r}localDeleteBlock(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`),g(Xe,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,!0)}),i}localInsertChildContainer(e,o){this.doc.blocks[e]=o,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,e,o,!0)})}localDeleteChildContainers(e){Xe.debug(`delete child containers: ${e}`),e.forEach(o=>{g(Xe,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(e,o){g(Xe,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){g(Xe,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new _h}setDoc(e){this.doc=mt.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class jD{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function ep(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new jD(o)})}const ub=S("find-block");function db(n,t){const e=Ts(t);if(!e){if(io(t))return null;const o=xs(t);return g(ub,o,"no parent block"),db(n,o)}return Mt(n,e)?zl(n,e,{visibleOnly:!0}):e}function hb(n,t){const e=Ds(t);if(!e){if(io(t))return null;const o=xs(t);return g(ub,o,"no parent block"),hb(n,o)}return Mt(n,e)?Xm(n,e,{visibleOnly:!0}):e}const UD=S("remote-cursor");class zD{constructor(){m(this,"remoteUsers",new _h)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):UD.debug(`unknown remote message received: ${t}`)}handleUpdateUsers(t){this.remoteUsers.updateUsers(t)}handleUpdateCaret(t){const e=this.remoteUsers.findUser(t.userId);!e||this.remoteUsers.setCursor({oneseditor:"cursor",user:e,range:t.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function VD(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function WD(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function Ha(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=VD(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function Pi(n){return n==="root"?"blocks":n}function Kl(n){return n==="blocks"?"root":n}const qD={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new on.default(n)},apply(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},compose(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},diff(n,t){const e=new on.default(n),o=new on.default(t);return e.diff(o).ops},transform(n,t,e){const o=new on.default(n);return new on.default(t).transform(o,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const o=new on.default(t),r=this.transformCursor(n.index,o,e),i=this.transformCursor(n.index+n.length,o,e);return{...n,index:r,length:i-r}}}};var ar=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ni={},np=q5.default.EventEmitter;Ni.EventEmitter=np,Ni.mixin=GD;function GD(n){for(var t in np.prototype)n.prototype[t]=np.prototype[t]}var fb=["info","warn","error"];function mb(){var n={};fb.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var ZD=mb;mb.prototype.setMethods=function(n){n=n||{};var t=this;fb.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var QD=ZD,YD=new QD,gb=YD;function js(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,js):this.stack=new Error().stack}js.prototype=Object.create(Error.prototype),js.prototype.constructor=js,js.prototype.name="ShareDBError",js.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 Fh=js,ja={},pb=JD;function JD(n,t,e,o){var r=function(s,l,a,d){t(a,s,l,"left"),t(d,l,s,"right")},i=n.transformX=function(s,l){e(s),e(l);for(var a=[],d=0;d<l.length;d++){for(var h=l[d],p=[],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?t([],s[0],l[0],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var Cb={exports:{}},$i=Cb.exports={name:"text0",uri:"http://sharejs.org/types/textv0",create:function(n){if(n!=null&&typeof n!="string")throw new Error("Initial data must be a string");return n||""}},op=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},rp=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")},Ph=function(n){for(var t=0;t<n.length;t++)rp(n[t])};$i.apply=function(n,t){var e;Ph(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=op(n,r.p,r.i);else{if(e=n.slice(r.p,r.p+r.d.length),r.d!==e)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+e+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var Gr=$i._append=function(n,t){if(!(t.i===""||t.d===""))if(n.length===0)n.push(t);else{var e=n[n.length-1];e.i!=null&&t.i!=null&&e.p<=t.p&&t.p<=e.p+e.i.length?n[n.length-1]={i:op(e.i,t.p-e.p,t.i),p:e.p}:e.d!=null&&t.d!=null&&t.p<=e.p&&e.p<=t.p+t.d.length?n[n.length-1]={d:op(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};$i.compose=function(n,t){Ph(n),Ph(t);for(var e=n.slice(),o=0;o<t.length;o++)Gr(e,t[o]);return e},$i.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=0),Gr(t,o)}return t};var ip=function(n,t,e){return t.i!=null?t.p<n||t.p===n&&e?n+t.i.length:n:n<=t.p?n:n<=t.p+t.d.length?t.p:n-t.d.length};$i.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=ip(n,t[r],o);return n};var KD=$i._tc=function(n,t,e,o){if(rp(t),rp(e),t.i!=null)Gr(n,{i:t.i,p:ip(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Gr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Gr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Gr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Gr(n,t);else{var i={d:"",p:t.p};t.p<e.p&&(i.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(i.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),a=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=ip(i.p,e),Gr(n,i))}return n},XD=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};$i.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=XD(n[t]);return n},pb($i,KD,Ph,Gr);var Nh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},tS=function(n){return!!n&&n.constructor===Object},Po=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Zr={};It.registerSubtype=function(n){Zr[n.name]=n},It.create=function(n){return n===void 0?null:Po(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Zr[n.t]&&(t.t=n.t,t.o=Zr[n.t].invert(n.o)),n.si!==void 0&&(t.sd=n.si),n.sd!==void 0&&(t.si=n.sd),n.oi!==void 0&&(t.od=n.oi),n.od!==void 0&&(t.oi=n.od),n.li!==void 0&&(t.ld=n.li),n.ld!==void 0&&(t.li=n.ld),n.na!==void 0&&(t.na=-n.na),n.lm!==void 0&&(t.lm=n.p[n.p.length-1],t.p=n.p.slice(0,n.p.length-1).concat([n.lm])),t},It.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(It.invertComponent(t[o]));return e},It.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Nh(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!Nh(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!tS(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Ua(n){n.t="text0";var t={p:n.p.pop()};n.si!=null&&(t.i=n.si),n.sd!=null&&(t.d=n.sd),n.o=[t]}function 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}It.apply=function(n,t){It.checkValidOp(t),t=Po(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&Ua(r);for(var i=null,s=e,l="data",a=0;a<r.p.length;a++){var d=r.p[a];if(i=s,s=s[l],l=d,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Zr[r.t])s[l]=Zr[r.t].apply(s[l],r.o);else if(r.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=r.na}else if(r.li!==void 0&&r.ld!==void 0)It.checkList(s),s[l]=r.li;else if(r.li!==void 0)It.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)It.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(It.checkList(s),r.lm!=l){var h=s[l];s.splice(l,1),s.splice(r.lm,0,h)}}else if(r.oi!==void 0)It.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)It.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},It.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},It.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=It.apply(n,r),e(r,n)}return n};var eS=It.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==t[o]&&(!e||o!==n.length-1))return!1;return!0};It.append=function(n,t){if(t=Po(t),n.length===0){n.push(t);return}var e=n[n.length-1];if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Ua(t),Ua(e)),eS(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Zr[t.t]){if(e.o=Zr[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var o=t.p,r=0;r<e.o.length-1;r++)t.o=[e.o.pop()],t.p=o.slice(),za(t),n.push(t);za(e)}}else e.na!=null&&t.na!=null?n[n.length-1]={p:e.p,na:e.na+t.na}:e.li!==void 0&&t.li===void 0&&t.ld===e.li?e.ld!==void 0?delete e.li:n.pop():e.od!==void 0&&e.oi===void 0&&t.oi!==void 0&&t.od===void 0?e.oi=t.oi:e.oi!==void 0&&t.od!==void 0?t.oi!==void 0?e.oi=t.oi:e.od!==void 0?delete e.oi:n.pop():t.lm!==void 0&&t.p[t.p.length-1]===t.lm||n.push(t);else(t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(za(t),za(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=Po(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=Nh(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),It.append(t,o)}return t},It.commonLengthForOps=function(n,t){var e=n.p.length,o=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&o++,e===0)return-1;if(o===0)return null;e--,o--;for(var r=0;r<e;r++){var i=n.p[r];if(r>=o||i!==t.p[r])return null}return e},It.canOpAffectPath=function(n,t){return It.commonLengthForOps({p:t},n)!=null},It.transformComponent=function(n,t,e,o){t=Po(t);var r=It.commonLengthForOps(e,t),i=It.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,i!=null&&l>s&&t.p[i]==e.p[i]){if(t.ld!==void 0){var a=Po(e);a.p=a.p.slice(s),t.ld=It.apply(Po(t.ld),[a])}else if(t.od!==void 0){var a=Po(e);a.p=a.p.slice(s),t.od=It.apply(Po(t.od),[a])}}if(r!=null){var d=s==l,a=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Ua(t),a=Po(e),Ua(a)),a.t&&Zr[a.t]){if(t.t&&t.t===a.t){var h=Zr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,A=0;A<h.length;A++)t.o=[h[A]],t.p=p.slice(),za(t),It.append(n,t);else(!Nh(h)||h.length>0)&&(t.o=h,It.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[r]===t.p[r])if(d){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=Po(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&d&&t.p[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&d&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[r]===t.p[r])return n;var p=e.p[r],v=t.p[r],B=t.lm;(p<B||p===B&&v<B)&&t.lm--}if(e.p[r]<t.p[r])t.p[r]--;else if(e.p[r]===t.p[r]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var v=t.p[r],B=t.lm,D=e.p[r],x=e.lm;if(D!==x)if(v===D)if(o==="left")t.p[r]=x,v===B&&(t.lm=x);else return n;else v>D&&t.p[r]--,v>x?t.p[r]++:v===x&&D>x&&(t.p[r]++,v===B&&t.lm++),(B>D||B===D&&B>v)&&t.lm--,B>x?t.lm++:B===x&&(x>D&&B>v||x<D&&B<v?o==="right"&&t.lm++:B>v?t.lm++:B===D&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var v=e.p[r],B=e.lm;p=t.p[r],p>v&&t.p[r]--,p>B&&t.p[r]++}else{var v=e.p[r],B=e.lm;p=t.p[r],p===v?t.p[r]=B:(p>v&&t.p[r]--,(p>B||p===B&&v>B)&&t.p[r]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[r]===e.p[r])if(t.oi!==void 0&&d){if(o==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[r]===e.p[r])if(o==="left")It.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return It.append(n,t),n},pb(It,It.transformComponent,It.checkValidOp,It.append);var nS=Cb.exports;It.registerSubtype(nS);var oS=It,rS={type:oS};(function(n){n.defaultType=rS.type,n.map={},n.register=function(t){t.name&&(n.map[t.name]=t),t.uri&&(n.map[t.uri]=t)},n.register(n.defaultType)})(ja);var No={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var o in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];e=e[r]||(o===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];e=e[i]||(e[i]=r===arguments.length-2?o():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],o=[e],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!e.hasOwnProperty(i))break;e=e[i],o.push(e)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,o){var r=!1;return e.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){e.apply(null,o)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(No);var Ab=Array.isArray,bb=Object.keys,iS=Object.prototype.hasOwnProperty,sS=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=Ab(t),r=Ab(e),i,s,l;if(o&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!n(t[i],e[i]))return!1;return!0}if(o!=r)return!1;var a=t instanceof Date,d=e instanceof Date;if(a!=d)return!1;if(a&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,p=e instanceof RegExp;if(h!=p)return!1;if(h&&p)return t.toString()==e.toString();var A=bb(t);if(s=A.length,s!==bb(e).length)return!1;for(i=s;i--!==0;)if(!iS.call(e,A[i]))return!1;for(i=s;i--!==0;)if(l=A[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},vb=Ni,lS=gb,qn=Fh,$h=ja,$o=No,cS=$o.clone,aS=sS,Tn=qn.CODES,uS=Ft;function Ft(n,t,e){vb.EventEmitter.call(this),this.connection=n,this.collection=t,this.id=e,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}vb.mixin(Ft),Ft.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this;t.whenNothingPending(function(){t.wantSubscribe?t.unsubscribe(function(e){if(e)return n?n(e):t.emit("error",e);t.connection._destroyDoc(t),n&&n()}):(t.connection._destroyDoc(t),n&&n())})},Ft.prototype._setType=function(n){if(typeof n=="string"&&(n=$h.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new qn(Tn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Ft.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Ft.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new qn(Tn.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return t&&this.once("no write pending",t);var e=new qn(Tn.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var o=n.type===void 0?$h.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},Ft.prototype.whenNothingPending=function(n){var t=this;$o.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Ft.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Ft.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Ft.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Ft.prototype._emitResponseError=function(n,t){if(n&&n.code===Tn.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,t&&t(),this._emitNothingPending();return}if(t){t(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},Ft.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&e.push(o),e.length&&(o=function(r){$o.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],e.callback&&o.push(e.callback);var r;if(o.length&&(r=function(i){$o.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Tn.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq){this._opAcknowledged(t);return}if(this.version==null||t.v>this.version){this.fetch();return}if(!(t.v<this.version)){if(this.inflightOp){var e=Hh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Hh(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},Ft.prototype._onConnectionStateChanged=function(){this.connection.canSend?(this.flush(),this._resubscribe()):(this.inflightOp&&(this.pendingOps.unshift(this.inflightOp),this.inflightOp=null),this.subscribed=!1,this.inflightSubscribe&&(this.inflightSubscribe.wantSubscribe?(this.pendingSubscribe.unshift(this.inflightSubscribe),this.inflightSubscribe=null):this._handleSubscribe()),this.inflightFetch.length&&(this.pendingFetch=this.pendingFetch.concat(this.inflightFetch),this.inflightFetch.length=0))},Ft.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(t){return t.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},Ft.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);dS(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Ft.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Ft.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Ft.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=hS([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Ft.prototype._flushSubscribe=function(){if(!(this.inflightSubscribe||!this.pendingSubscribe.length)){if(this.connection.canSend){this.inflightSubscribe=this.pendingSubscribe.shift(),this.wantSubscribe=this.inflightSubscribe.wantSubscribe,this.wantSubscribe?this.connection.sendSubscribe(this):(this.subscribed=!1,this.connection.sendUnsubscribe(this));return}if(!this.pendingSubscribe[0].wantSubscribe){this.inflightSubscribe=this.pendingSubscribe.shift();var n=this;$o.nextTick(function(){n._handleSubscribe()})}}};function dS(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function hS(n){return n=n.filter($o.truthy),n.length?function(t){$o.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function fS(n){delete n.op,delete n.create,delete n.del}function Hh(n,t){if(n.del)return fS(t);if(t.del)return new qn(Tn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new qn(Tn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new qn(Tn.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var o=n.type.transform(n.op,t.op,"left"),r=n.type.transform(t.op,n.op,"right");n.op=o,t.op=r}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new qn(Tn.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,t),!t&&this.type===$h.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Hh(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",t);return}if(n.del){var a=this.data;this._setType(null),this.emit("del",a,t);return}},Ft.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var t=this.inflightOp;if(!t){var e=new qn(Tn.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",e)}if(t.sentAt=Date.now(),t.retries=t.retries==null?0:t.retries+1,t.seq==null){if(this.connection.seq>=$o.MAX_SAFE_INTEGER)return this.emit("error",new qn(Tn.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));t.seq=this.connection.seq++}this.connection.sendOp(this,t),t.src==null&&(t.src=n)}},Ft.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new qn(Tn.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(i){return this._hardRollback(i)}var r=this;$o.nextTick(function(){r.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},Ft.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var o=this.pendingOps.splice(e),e=0;e<o.length;e++){var t=o[e],r=this._tryCompose(t);r?r.callbacks=r.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},Ft.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!aS(n.source,t.source))){if(t.create&&"op"in n)return t.create.data=this.type.apply(t.create.data,n.op),t;if("op"in t&&"op"in n&&this.type.compose)return t.op=this.type.compose(t.op,n.op),t}}},Ft.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var o={op:n},r=t&&t.source;this._submit(o,r,e)},Ft.prototype.create=function(n,t,e,o){if(typeof t=="function"?(o=t,e=null,t=null):typeof e=="function"&&(o=e,e=null),t||(t=$h.defaultType.uri),this.type){var r=new qn(Tn.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:t,data:n}},s=e&&e.source;this._submit(i,s,o)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new qn(Tn.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var o={del:!0},r=n&&n.source;this._submit(o,r,t)},Ft.prototype.pause=function(){this.paused=!0},Ft.prototype.resume=function(){this.paused=!1,this.flush()},Ft.prototype.toSnapshot=function(){return{v:this.version,data:cS(this.data),type:this.type.uri}},Ft.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return lS.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Ft.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var o=Hh(this.pendingOps[e],t);if(o)return this._hardRollback(o)}try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},Ft.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var o=!!t.length,r=0;r<t.length;r++)o=$o.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=$o.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Us={};Us.ACTIONS={initLegacy:"init",handshake:"hs",queryFetch:"qf",querySubscribe:"qs",queryUnsubscribe:"qu",queryUpdate:"q",bulkFetch:"bf",bulkSubscribe:"bs",bulkUnsubscribe:"bu",fetch:"f",subscribe:"s",unsubscribe:"u",op:"op",snapshotFetch:"nf",snapshotFetchByTimestamp:"nt",pingPong:"pp",presence:"p",presenceSubscribe:"ps",presenceUnsubscribe:"pu",presenceRequest:"pr"};var yb=Ni,kb=Us.ACTIONS,mS=No,gS=Dn;function Dn(n,t,e,o,r,i,s){yb.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}yb.mixin(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 t=[],e=0;e<this.results.length;e++){var o=this.results[e];t.push([o.id,o.version])}n.r=t}this.connection.send(n),this.sent=!0}},Dn.prototype.destroy=function(n){this.connection.canSend&&this.action===kb.querySubscribe&&this.connection.send({a:kb.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&mS.nextTick(n)},Dn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Dn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Dn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Dn.prototype._handleResponse=function(n,t,e){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!t)return this._finishResponse(null,o);var r=this,i=1,s=function(h){if(h)return r._finishResponse(h,o);--i||r._finishResponse(null,o)};if(Array.isArray(t))i+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){i++;var a=t[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Dn.prototype._ingestSnapshots=function(n,t){for(var e=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,t),e.push(i)}return e},Dn.prototype._finishResponse=function(n,t){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),t?t(n):this.emit("error",n);t&&t(null,this.results,this.extra)},Dn.prototype._handleError=function(n){this.emit("error",n)},Dn.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var o=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(o)),this.emit("insert",o,e.index);break;case"remove":var i=e.howMany||1,r=this.results.splice(e.index,i);this.emit("remove",r,e.index);break;case"move":var i=e.howMany||1,s=this.results.splice(e.from,i);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},Dn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var wb=Ni,pS=Us.ACTIONS,CS=No,Bb=ur;function ur(n,t){if(wb.EventEmitter.call(this),!t||typeof t!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=t,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}wb.mixin(ur),ur.prototype.submit=function(n,t){this.value=n,this.send(t)},ur.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},ur.prototype.destroy=function(n){var t=this;this.submit(null,function(e){if(e)return t._callbackOrEmit(e,n);delete t.presence.localPresences[t.presenceId],n&&n()})},ur.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},ur.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},ur.prototype._message=function(){return{a:pS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},ur.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},ur.prototype._callbackOrEmit=function(n,t){if(t)return CS.nextTick(t,n);n&&this.emit("error",n)};var AS=No,Eb=sp;function sp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}sp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},sp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&AS.nextTick(n)};var lp={exports:{}};(function(n,t){(function(e,o){o(t)})(ar,function(e){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 H(k){return function(T){var L=o(arguments,1),F=i(function(U,j){var Z=this;return k(T,function(J,lt){M(J).apply(Z,U.concat(lt))},j)});return L.length?F.apply(this,L):F}}var z=typeof ar=="object"&&ar&&ar.Object===Object&&ar,q=typeof self=="object"&&self&&self.Object===Object&&self,rt=z||q||Function("return this")(),ft=rt.Symbol,Bt=Object.prototype,jt=Bt.hasOwnProperty,Ut=Bt.toString,ee=ft?ft.toStringTag:void 0;function qe(k){var T=jt.call(k,ee),L=k[ee];try{k[ee]=void 0;var F=!0}catch{}var U=Ut.call(k);return F&&(T?k[ee]=L:delete k[ee]),U}var Yn=Object.prototype,$e=Yn.toString;function Mn(k){return $e.call(k)}var yr="[object Null]",bn="[object Undefined]",an=ft?ft.toStringTag:void 0;function kr(k){return k==null?k===void 0?bn:yr:an&&an in Object(k)?qe(k):Mn(k)}var oi="[object AsyncFunction]",po="[object Function]",K2="[object GeneratorFunction]",X2="[object Proxy]";function t3(k){if(!s(k))return!1;var T=kr(k);return T==po||T==K2||T==oi||T==X2}var es=9007199254740991;function nl(k){return typeof k=="number"&&k>-1&&k%1==0&&k<=es}function ol(k){return k!=null&&nl(k.length)&&!t3(k)}var ri={};function Nt(){}function wr(k){return function(){if(k!==null){var T=k;k=null,T.apply(this,arguments)}}}var ns=typeof Symbol=="function"&&Symbol.iterator,Fc=function(k){return ns&&k[ns]&&k[ns]()};function i1(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 rl="[object Arguments]";function s1(k){return un(k)&&kr(k)==rl}var Co=Object.prototype,l1=Co.hasOwnProperty,e3=Co.propertyIsEnumerable,il=s1(function(){return arguments}())?s1:function(k){return un(k)&&l1.call(k,"callee")&&!e3.call(k,"callee")},Ae=Array.isArray;function sl(){return!1}var ll=typeof e=="object"&&e&&!e.nodeType&&e,c1=ll&&!0&&n&&!n.nodeType&&n,cl=c1&&c1.exports===ll,a1=cl?rt.Buffer:void 0,al=a1?a1.isBuffer:void 0,os=al||sl,$u=9007199254740991,Hu=/^(?:0|[1-9]\d*)$/;function ju(k,T){var L=typeof k;return T=T==null?$u:T,!!T&&(L=="number"||L!="symbol"&&Hu.test(k))&&k>-1&&k%1==0&&k<T}var Uu="[object Arguments]",zu="[object Array]",Vu="[object Boolean]",Wu="[object Date]",qu="[object Error]",Gu="[object Function]",n3="[object Map]",o3="[object Number]",r3="[object Object]",u1="[object RegExp]",d1="[object Set]",i3="[object String]",s3="[object WeakMap]",l3="[object ArrayBuffer]",c3="[object DataView]",h1="[object Float32Array]",a3="[object Float64Array]",u3="[object Int8Array]",d3="[object Int16Array]",Zu="[object Int32Array]",h3="[object Uint8Array]",Qu="[object Uint8ClampedArray]",f3="[object Uint16Array]",m3="[object Uint32Array]",se={};se[h1]=se[a3]=se[u3]=se[d3]=se[Zu]=se[h3]=se[Qu]=se[f3]=se[m3]=!0,se[Uu]=se[zu]=se[l3]=se[Vu]=se[c3]=se[Wu]=se[qu]=se[Gu]=se[n3]=se[o3]=se[r3]=se[u1]=se[d1]=se[i3]=se[s3]=!1;function g3(k){return un(k)&&nl(k.length)&&!!se[kr(k)]}function p3(k){return function(T){return k(T)}}var f1=typeof e=="object"&&e&&!e.nodeType&&e,ul=f1&&!0&&n&&!n.nodeType&&n,C3=ul&&ul.exports===f1,Pc=C3&&z.process,m1=function(){try{var k=ul&&ul.require&&ul.require("util").types;return k||Pc&&Pc.binding&&Pc.binding("util")}catch{}}(),g1=m1&&m1.isTypedArray,A3=g1?p3(g1):g3,b3=Object.prototype,v3=b3.hasOwnProperty;function y3(k,T){var L=Ae(k),F=!L&&il(k),U=!L&&!F&&os(k),j=!L&&!F&&!U&&A3(k),Z=L||F||U||j,J=Z?i1(k.length,String):[],lt=J.length;for(var pt in k)(T||v3.call(k,pt))&&!(Z&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||ju(pt,lt)))&&J.push(pt);return J}var Nc=Object.prototype;function k3(k){var T=k&&k.constructor,L=typeof T=="function"&&T.prototype||Nc;return k===L}function $c(k,T){return function(L){return k(T(L))}}var w3=$c(Object.keys,Object),B3=Object.prototype,E3=B3.hasOwnProperty;function p1(k){if(!k3(k))return w3(k);var T=[];for(var L in Object(k))E3.call(k,L)&&L!="constructor"&&T.push(L);return T}function Hc(k){return ol(k)?y3(k):p1(k)}function C1(k){var T=-1,L=k.length;return function(){return++T<L?{value:k[T],key:T}:null}}function x3(k){var T=-1;return function(){var F=k.next();return F.done?null:(T++,{value:F.value,key:T})}}function I3(k){var T=Hc(k),L=-1,F=T.length;return function U(){var j=T[++L];return j==="__proto__"?U():L<F?{value:k[j],key:j}:null}}function T3(k){if(ol(k))return C1(k);var T=Fc(k);return T?x3(T):I3(k)}function Ao(k){return function(){if(k===null)throw new Error("Callback was already called.");var T=k;k=null,T.apply(this,arguments)}}function dl(k){return function(T,L,F){if(F=wr(F||Nt),k<=0||!T)return F(null);var U=T3(T),j=!1,Z=0,J=!1;function lt(ct,At){if(Z-=1,ct)j=!0,F(ct);else{if(At===ri||j&&Z<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;Z<k&&!j;){var ct=U();if(ct===null){j=!0,Z<=0&&F(null);return}Z+=1,L(ct.value,ct.key,Ao(lt))}J=!1}pt()}}function Br(k,T,L,F){dl(T)(k,M(L),F)}function He(k,T){return function(L,F,U){return k(L,T,F,U)}}function Yu(k,T,L){L=wr(L||Nt);var F=0,U=0,j=k.length;j===0&&L(null);function Z(J,lt){J?L(J):(++U===j||lt===ri)&&L(null)}for(;F<j;F++)T(k[F],F,Ao(Z))}var D3=He(Br,1/0),Go=function(k,T,L){var F=ol(k)?Yu:D3;F(k,M(T),L)};function Zo(k){return function(T,L,F){return k(Go,T,M(L),F)}}function Ju(k,T,L,F){F=F||Nt,T=T||[];var U=[],j=0,Z=M(L);k(T,function(J,lt,pt){var ct=j++;Z(J,function(At,Gt){U[ct]=Gt,pt(At)})},function(J){F(J,U)})}var jc=Zo(Ju),Ku=H(jc);function ii(k){return function(T,L,F,U){return k(dl(L),T,M(F),U)}}var Er=ii(Ju),Xu=He(Er,1),td=H(Xu);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,j=Object(T),Z=F(T),J=Z.length;J--;){var lt=Z[k?J:++U];if(L(j[lt],lt,j)===!1)break}return T}}var is=ed();function ss(k,T){return k&&is(k,T,Hc)}function A1(k,T,L,F){for(var U=k.length,j=L+(F?1:-1);F?j--:++j<U;)if(T(k[j],j,k))return j;return-1}function S3(k){return k!==k}function b1(k,T,L){for(var F=L-1,U=k.length;++F<U;)if(k[F]===T)return F;return-1}function hl(k,T,L){return T===T?b1(k,T,L):A1(k,S3,L)}var Uc=function(k,T,L){typeof T=="function"&&(L=T,T=null),L=wr(L||Nt);var F=Hc(k),U=F.length;if(!U)return L(null);T||(T=U);var j={},Z=0,J=!1,lt=Object.create(null),pt=[],ct=[],At={};ss(k,function(de,oe){if(!Ae(de)){Gt(oe,[de]),ct.push(oe);return}var ge=de.slice(0,de.length-1),vo=ge.length;if(vo===0){Gt(oe,de),ct.push(oe);return}At[oe]=vo,rs(ge,function(E){if(!k[E])throw new Error("async.auto task `"+oe+"` has a non-existent dependency `"+E+"` in "+ge.join(", "));en(E,function(){vo--,vo===0&&Gt(oe,de)})})}),K3(),Ie();function Gt(de,oe){pt.push(function(){bo(de,oe)})}function Ie(){if(pt.length===0&&Z===0)return L(null,j);for(;pt.length&&Z<T;){var de=pt.shift();de()}}function en(de,oe){var ge=lt[de];ge||(ge=lt[de]=[]),ge.push(oe)}function _n(de){var oe=lt[de]||[];rs(oe,function(ge){ge()}),Ie()}function bo(de,oe){if(!J){var ge=Ao(function(E,Tr){if(Z--,arguments.length>2&&(Tr=o(arguments,1)),E){var us={};ss(j,function(Fn,Pt){us[Pt]=Fn}),us[de]=Tr,J=!0,lt=Object.create(null),L(E,us)}else j[de]=Tr,_n(de)});Z++;var vo=M(oe[oe.length-1]);oe.length>1?vo(j,ge):vo(ge)}}function K3(){for(var de,oe=0;ct.length;)de=ct.pop(),oe++,rs(X3(de),function(ge){--At[ge]===0&&ct.push(ge)});if(oe!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function X3(de){var oe=[];return ss(k,function(ge,vo){Ae(ge)&&hl(ge,de,0)>=0&&oe.push(vo)}),oe}};function si(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 L3="[object Symbol]";function M3(k){return typeof k=="symbol"||un(k)&&kr(k)==L3}var R3=1/0,nd=ft?ft.prototype:void 0,v1=nd?nd.toString:void 0;function od(k){if(typeof k=="string")return k;if(Ae(k))return si(k,od)+"";if(M3(k))return v1?v1.call(k):"";var T=k+"";return T=="0"&&1/k==-R3?"-0":T}function O3(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 j=Array(U);++F<U;)j[F]=k[F+T];return j}function _3(k,T,L){var F=k.length;return L=L===void 0?F:L,!T&&L>=F?k:O3(k,T,L)}function rd(k,T){for(var L=k.length;L--&&hl(T,k[L],0)>-1;);return L}function F3(k,T){for(var L=-1,F=k.length;++L<F&&hl(T,k[L],0)>-1;);return L}function P3(k){return k.split("")}var N3="\\ud800-\\udfff",$3="\\u0300-\\u036f",H3="\\ufe20-\\ufe2f",le="\\u20d0-\\u20ff",ne=$3+H3+le,j3="\\ufe0e\\ufe0f",U3="\\u200d",z3=RegExp("["+U3+N3+ne+j3+"]");function V3(k){return z3.test(k)}var y1="\\ud800-\\udfff",W3="\\u0300-\\u036f",k1="\\ufe20-\\ufe2f",q3="\\u20d0-\\u20ff",Ge=W3+k1+q3,id="\\ufe0e\\ufe0f",li="["+y1+"]",zc="["+Ge+"]",fl="\\ud83c[\\udffb-\\udfff]",Rn="(?:"+zc+"|"+fl+")",sd="[^"+y1+"]",ld="(?:\\ud83c[\\udde6-\\uddff]){2}",cd="[\\ud800-\\udbff][\\udc00-\\udfff]",w1="\\u200d",ad=Rn+"?",ud="["+id+"]?",vn="(?:"+w1+"(?:"+[sd,ld,cd].join("|")+")"+ud+ad+")*",G3=ud+ad+vn,On="(?:"+[sd+zc+"?",zc,ld,cd,li].join("|")+")",Z3=RegExp(fl+"(?="+fl+")|"+On+G3,"g");function B1(k){return k.match(Z3)||[]}function Qo(k){return V3(k)?B1(k):P3(k)}function Vc(k){return k==null?"":od(k)}var dd=/^\s+|\s+$/g;function ue(k,T,L){if(k=Vc(k),k&&(L||T===void 0))return k.replace(dd,"");if(!k||!(T=od(T)))return k;var F=Qo(k),U=Qo(T),j=F3(F,U),Z=rd(F,U)+1;return _3(F,j,Z).join("")}var xr=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,hd=/,/,Q3=/(=.+)?(\s*)$/,fd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function Y3(k){return k=k.toString().replace(fd,""),k=k.match(xr)[2].replace(" ",""),k=k?k.split(hd):[],k=k.map(function(T){return ue(T.replace(Q3,""))}),k}function E1(k,T){var L={};ss(k,function(F,U){var j,Z=_(F),J=!Z&&F.length===1||Z&&F.length===0;if(Ae(F))j=F.slice(0,-1),F=F[F.length-1],L[U]=j.concat(j.length>0?lt:F);else if(J)L[U]=F;else{if(j=Y3(F),F.length===0&&!Z&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");Z||j.pop(),L[U]=j.concat(lt)}function lt(pt,ct){var At=si(j,function(Gt){return pt[Gt]});At.push(ct),M(F).apply(null,At)}}),Uc(L,T)}function Jn(){this.head=this.tail=null,this.length=0}function md(k,T){k.length=1,k.head=k.tail=T}Jn.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},Jn.prototype.empty=function(){for(;this.head;)this.shift();return this},Jn.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},Jn.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},Jn.prototype.unshift=function(k){this.head?this.insertBefore(this.head,k):md(this,k)},Jn.prototype.push=function(k){this.tail?this.insertAfter(this.tail,k):md(this,k)},Jn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Jn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Jn.prototype.toArray=function(){for(var k=Array(this.length),T=this.head,L=0;L<this.length;L++)k[L]=T.data,T=T.next;return k},Jn.prototype.remove=function(k){for(var T=this.head;T;){var L=T.next;k(T)&&this.removeLink(T),T=L}return this};function ml(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,j=[],Z=!1;function J(At,Gt,Ie){if(Ie!=null&&typeof Ie!="function")throw new Error("task callback must be a function");if(ct.started=!0,Ae(At)||(At=[At]),At.length===0&&ct.idle())return A(function(){ct.drain()});for(var en=0,_n=At.length;en<_n;en++){var bo={data:At[en],callback:Ie||Nt};Gt?ct._tasks.unshift(bo):ct._tasks.push(bo)}Z||(Z=!0,A(function(){Z=!1,ct.process()}))}function lt(At){return function(Gt){U-=1;for(var Ie=0,en=At.length;Ie<en;Ie++){var _n=At[Ie],bo=hl(j,_n,0);bo===0?j.shift():bo>0&&j.splice(bo,1),_n.callback.apply(_n,arguments),Gt!=null&&ct.error(Gt,_n.data)}U<=ct.concurrency-ct.buffer&&ct.unsaturated(),ct.idle()&&ct.drain(),ct.process()}}var pt=!1,ct={_tasks:new Jn,concurrency:T,payload:L,saturated:Nt,unsaturated:Nt,buffer:T/4,empty:Nt,drain:Nt,error:Nt,started:!1,paused:!1,push:function(At,Gt){J(At,!1,Gt)},kill:function(){ct.drain=Nt,ct._tasks.empty()},unshift:function(At,Gt){J(At,!0,Gt)},remove:function(At){ct._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!ct.paused&&U<ct.concurrency&&ct._tasks.length;){var At=[],Gt=[],Ie=ct._tasks.length;ct.payload&&(Ie=Math.min(Ie,ct.payload));for(var en=0;en<Ie;en++){var _n=ct._tasks.shift();At.push(_n),j.push(_n),Gt.push(_n.data)}U+=1,ct._tasks.length===0&&ct.empty(),U===ct.concurrency&&ct.saturated();var bo=Ao(lt(At));F(Gt,bo)}pt=!1}},length:function(){return ct._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return ct._tasks.length+U===0},pause:function(){ct.paused=!0},resume:function(){ct.paused!==!1&&(ct.paused=!1,A(ct.process))}};return ct}function ci(k,T){return ml(k,1,T)}var ls=He(Br,1);function Yo(k,T,L,F){F=wr(F||Nt);var U=M(L);ls(k,function(j,Z,J){U(T,j,function(lt,pt){T=pt,J(lt)})},function(j){F(j,T)})}function Wc(){var k=si(arguments,M);return function(){var T=o(arguments),L=this,F=T[T.length-1];typeof F=="function"?T.pop():F=Nt,Yo(k,T,function(U,j,Z){j.apply(L,U.concat(function(J){var lt=o(arguments,1);Z(J,lt)}))},function(U,j){F.apply(L,[U].concat(j))})}}var qc=function(){return Wc.apply(null,o(arguments).reverse())},gd=Array.prototype.concat,gl=function(k,T,L,F){F=F||Nt;var U=M(L);Er(k,T,function(j,Z){U(j,function(J){return J?Z(J):Z(null,o(arguments,1))})},function(j,Z){for(var J=[],lt=0;lt<Z.length;lt++)Z[lt]&&(J=gd.apply(J,Z[lt]));return F(j,J)})},x1=He(gl,1/0),Gc=He(gl,1),Zc=function(){var k=o(arguments),T=[null].concat(k);return function(){var L=arguments[arguments.length-1];return L.apply(this,T)}};function pl(k){return k}function ai(k,T){return function(L,F,U,j){j=j||Nt;var Z=!1,J;L(F,function(lt,pt,ct){U(lt,function(At,Gt){At?ct(At):k(Gt)&&!J?(Z=!0,J=T(!0,lt),ct(null,ri)):ct()})},function(lt){lt?j(lt):j(null,Z?J:T(!1))})}}function dn(k,T){return T}var cs=Zo(ai(pl,dn)),Jo=ii(ai(pl,dn)),Cl=He(Jo,1);function pd(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(j){console[k](j)}))}),M(T).apply(null,L)}}var I1=pd("dir");function T1(k,T,L){L=Ao(L||Nt);var F=M(k),U=M(T);function j(J){if(J)return L(J);var lt=o(arguments,1);lt.push(Z),U.apply(this,lt)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}Z(null,!0)}function Cd(k,T,L){L=Ao(L||Nt);var F=M(k),U=function(j){if(j)return L(j);var Z=o(arguments,1);if(T.apply(this,Z))return F(U);L.apply(null,[null].concat(Z))};F(U)}function D1(k,T,L){Cd(k,function(){return!T.apply(this,arguments)},L)}function S1(k,T,L){L=Ao(L||Nt);var F=M(T),U=M(k);function j(J){if(J)return L(J);U(Z)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}U(Z)}function ui(k){return function(T,L,F){return k(T,F)}}function Qc(k,T,L){Go(k,ui(M(T)),L)}function Al(k,T,L,F){dl(T)(k,ui(M(L)),F)}var di=He(Al,1);function Yc(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 Kn(k){return!k}var hi=Zo(ai(Kn,Kn)),bl=ii(ai(Kn,Kn)),Jc=He(bl,1);function L1(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(j,Z,J){L(j,function(lt,pt){U[Z]=!!pt,J(lt)})},function(j){if(j)return F(j);for(var Z=[],J=0;J<T.length;J++)U[J]&&Z.push(T[J]);F(null,Z)})}function Xn(k,T,L,F){var U=[];k(T,function(j,Z,J){L(j,function(lt,pt){lt?J(lt):(pt&&U.push({index:Z,value:j}),J())})},function(j){j?F(j):F(null,si(U.sort(function(Z,J){return Z.index-J.index}),L1("value")))})}function Kc(k,T,L,F){var U=ol(T)?as:Xn;U(k,T,M(L),F||Nt)}var Xc=Zo(Kc),vl=ii(Kc),ta=He(vl,1);function M1(k,T){var L=Ao(T||Nt),F=M(Yc(k));function U(j){if(j)return L(j);F(U)}U()}var ea=function(k,T,L,F){F=F||Nt;var U=M(L);Er(k,T,function(j,Z){U(j,function(J,lt){return J?Z(J):Z(null,{key:lt,val:j})})},function(j,Z){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<Z.length;pt++)if(Z[pt]){var ct=Z[pt].key,At=Z[pt].val;lt.call(J,ct)?J[ct].push(At):J[ct]=[At]}return F(j,J)})},fi=He(ea,1/0),N=He(ea,1),G=pd("log");function V(k,T,L,F){F=wr(F||Nt);var U={},j=M(L);Br(k,T,function(Z,J,lt){j(Z,J,function(pt,ct){if(pt)return lt(pt);U[J]=ct,lt()})},function(Z){F(Z,U)})}var ht=He(V,1/0),Et=He(V,1);function Vt(k,T){return T in k}function we(k,T){var L=Object.create(null),F=Object.create(null);T=T||pl;var U=M(k),j=i(function(J,lt){var pt=T.apply(null,J);Vt(L,pt)?A(function(){lt.apply(null,L[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var ct=o(arguments);L[pt]=ct;var At=F[pt];delete F[pt];for(var Gt=0,Ie=At.length;Gt<Ie;Gt++)At[Gt].apply(null,ct)})))});return j.memo=L,j.unmemoized=k,j}var qt;a?qt=process.nextTick:l?qt=setImmediate:qt=d;var na=h(qt);function Ad(k,T,L){L=L||Nt;var F=ol(T)?[]:{};k(T,function(U,j,Z){M(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,Z(J)})},function(U){L(U,F)})}function yn(k,T){Ad(Go,k,T)}function yl(k,T,L){Ad(dl(T),k,L)}var bd=function(k,T){var L=M(k);return ml(function(F,U){L(F[0],U)},T,1)},mi=function(k,T){var L=bd(k,T);return L.push=function(F,U,j){if(j==null&&(j=Nt),typeof j!="function")throw new Error("task callback must be a function");if(L.started=!0,Ae(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,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};Z?L._tasks.insertBefore(Z,pt):L._tasks.push(pt)}A(L.process)},delete L.unshift,L};function kl(k,T){if(T=wr(T||Nt),!Ae(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 gi(k,T,L,F){var U=o(k).reverse();Yo(U,T,L,F)}function Wt(k){var T=M(k);return i(function(F,U){return F.push(function(Z,J){if(Z)U(null,{error:Z});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),T.apply(this,F)})}function R1(k){var T;return Ae(k)?T=si(k,Wt):(T={},ss(k,function(L,F){T[F]=Wt.call(this,L)})),T}function vd(k,T,L,F){Kc(k,T,function(U,j){L(U,function(Z,J){j(Z,!J)})},F)}var wl=Zo(vd),yd=ii(vd),O1=He(yd,1);function _1(k){return function(){return k}}function pi(k,T,L){var F=5,U=0,j={times:F,intervalFunc:_1(U)};function Z(ct,At){if(typeof At=="object")ct.times=+At.times||F,ct.intervalFunc=typeof At.interval=="function"?At.interval:_1(+At.interval||U),ct.errorFilter=At.errorFilter;else if(typeof At=="number"||typeof At=="string")ct.times=+At||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof k=="function"?(L=T||Nt,T=k):(Z(j,k),L=L||Nt),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=M(T),lt=1;function pt(){J(function(ct){ct&<++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(ct))?setTimeout(pt,j.intervalFunc(lt)):L.apply(null,arguments)})}pt()}var Ko=function(k,T){T||(T=k,k=null);var L=M(T);return i(function(F,U){function j(Z){L.apply(null,F.concat(Z))}k?pi(k,j,U):pi(j,U)})};function Bl(k,T){Ad(ls,k,T)}var El=Zo(ai(Boolean,pl)),Ir=ii(ai(Boolean,pl)),xl=He(Ir,1);function kd(k,T,L){var F=M(T);jc(k,function(j,Z){F(j,function(J,lt){if(J)return Z(J);Z(null,{value:j,criteria:lt})})},function(j,Z){if(j)return L(j);L(null,si(Z.sort(U),L1("value")))});function U(j,Z){var J=j.criteria,lt=Z.criteria;return J<lt?-1:J>lt?1:0}}function Il(k,T,L){var F=M(k);return i(function(U,j){var Z=!1,J;function lt(){var pt=k.name||"anonymous",ct=new Error('Callback function "'+pt+'" timed out.');ct.code="ETIMEDOUT",L&&(ct.info=L),Z=!0,j(ct)}U.push(function(){Z||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,T),F.apply(null,U)})}var F1=Math.ceil,Tl=Math.max;function Ci(k,T,L,F){for(var U=-1,j=Tl(F1((T-k)/(L||1)),0),Z=Array(j);j--;)Z[F?j:++U]=k,k+=L;return Z}function Ai(k,T,L,F){var U=M(L);Er(Ci(0,k,1),T,U,F)}var P1=He(Ai,1/0),N1=He(Ai,1);function $1(k,T,L,F){arguments.length<=3&&(F=L,L=T,T=Ae(k)?[]:{}),F=wr(F||Nt);var U=M(L);Go(k,function(j,Z,J){U(T,j,Z,J)},function(j){F(j,T)})}function Dl(k,T){var L=null,F;T=T||Nt,di(k,function(U,j){M(U)(function(Z,J){arguments.length>2?F=o(arguments,1):F=J,L=Z,j(!Z)})},function(){T(L,F)})}function Sl(k){return function(){return(k.unmemoized||k).apply(null,arguments)}}function Ll(k,T,L){L=Ao(L||Nt);var F=M(T);if(!k())return L(null);var U=function(j){if(j)return L(j);if(k())return F(U);var Z=o(arguments,1);L.apply(null,[null].concat(Z))};F(U)}function H1(k,T,L){Ll(function(){return!k.apply(this,arguments)},T,L)}var wd=function(k,T){if(T=wr(T||Nt),!Ae(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(j){var Z=M(k[L++]);j.push(Ao(U)),Z.apply(null,j)}function U(j){if(j||L===k.length)return T.apply(null,arguments);F(o(arguments,1))}F([])},J3={apply:r,applyEach:Ku,applyEachSeries:td,asyncify:v,auto:Uc,autoInject:E1,cargo:ci,compose:qc,concat:x1,concatLimit:gl,concatSeries:Gc,constant:Zc,detect:cs,detectLimit:Jo,detectSeries:Cl,dir:I1,doDuring:T1,doUntil:D1,doWhilst:Cd,during:S1,each:Qc,eachLimit:Al,eachOf:Go,eachOfLimit:Br,eachOfSeries:ls,eachSeries:di,ensureAsync:Yc,every:hi,everyLimit:bl,everySeries:Jc,filter:Xc,filterLimit:vl,filterSeries:ta,forever:M1,groupBy:fi,groupByLimit:ea,groupBySeries:N,log:G,map:jc,mapLimit:Er,mapSeries:Xu,mapValues:ht,mapValuesLimit:V,mapValuesSeries:Et,memoize:we,nextTick:na,parallel:yn,parallelLimit:yl,priorityQueue:mi,queue:bd,race:kl,reduce:Yo,reduceRight:gi,reflect:Wt,reflectAll:R1,reject:wl,rejectLimit:yd,rejectSeries:O1,retry:pi,retryable:Ko,seq:Wc,series:Bl,setImmediate:A,some:El,someLimit:Ir,someSeries:xl,sortBy:kd,timeout:Il,times:P1,timesLimit:Ai,timesSeries:N1,transform:$1,tryEach:Dl,unmemoize:Sl,until:H1,waterfall:wd,whilst:Ll,all:hi,allLimit:bl,allSeries:Jc,any:El,anyLimit:Ir,anySeries:xl,find:cs,findLimit:Jo,findSeries:Cl,forEach:Qc,forEachSeries:di,forEachLimit:Al,forEachOf:Go,forEachOfSeries:ls,forEachOfLimit:Br,inject:Yo,foldl:Yo,foldr:gi,select:Xc,selectLimit:vl,selectSeries:ta,wrapSync:v};e.default=J3,e.apply=r,e.applyEach=Ku,e.applyEachSeries=td,e.asyncify=v,e.auto=Uc,e.autoInject=E1,e.cargo=ci,e.compose=qc,e.concat=x1,e.concatLimit=gl,e.concatSeries=Gc,e.constant=Zc,e.detect=cs,e.detectLimit=Jo,e.detectSeries=Cl,e.dir=I1,e.doDuring=T1,e.doUntil=D1,e.doWhilst=Cd,e.during=S1,e.each=Qc,e.eachLimit=Al,e.eachOf=Go,e.eachOfLimit=Br,e.eachOfSeries=ls,e.eachSeries=di,e.ensureAsync=Yc,e.every=hi,e.everyLimit=bl,e.everySeries=Jc,e.filter=Xc,e.filterLimit=vl,e.filterSeries=ta,e.forever=M1,e.groupBy=fi,e.groupByLimit=ea,e.groupBySeries=N,e.log=G,e.map=jc,e.mapLimit=Er,e.mapSeries=Xu,e.mapValues=ht,e.mapValuesLimit=V,e.mapValuesSeries=Et,e.memoize=we,e.nextTick=na,e.parallel=yn,e.parallelLimit=yl,e.priorityQueue=mi,e.queue=bd,e.race=kl,e.reduce=Yo,e.reduceRight=gi,e.reflect=Wt,e.reflectAll=R1,e.reject=wl,e.rejectLimit=yd,e.rejectSeries=O1,e.retry=pi,e.retryable=Ko,e.seq=Wc,e.series=Bl,e.setImmediate=A,e.some=El,e.someLimit=Ir,e.someSeries=xl,e.sortBy=kd,e.timeout=Il,e.times=P1,e.timesLimit=Ai,e.timesSeries=N1,e.transform=$1,e.tryEach=Dl,e.unmemoize=Sl,e.until=H1,e.waterfall=wd,e.whilst=Ll,e.all=hi,e.allLimit=bl,e.allSeries=Jc,e.any=El,e.anyLimit=Ir,e.anySeries=xl,e.find=cs,e.findLimit=Jo,e.findSeries=Cl,e.forEach=Qc,e.forEachSeries=di,e.forEachLimit=Al,e.forEachOf=Go,e.forEachOfSeries=ls,e.forEachOfLimit=Br,e.inject=Yo,e.foldl=Yo,e.foldr=gi,e.select=Xc,e.selectLimit=vl,e.selectSeries=ta,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(lp,lp.exports);var xb={exports:{}},cp=xb.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),o=2;e===1/0;o*=2)e=Math.log(Math.pow(2,n/o))/Math.log(t)*o;for(var r=e-Math.floor(e),i="",o=0;o<Math.floor(e);o++){var s=Math.floor(Math.random()*t).toString(t);i=s+i}if(r){var l=Math.pow(t,r),s=Math.floor(Math.random()*l).toString(t);i=s+i}var a=parseInt(i,t);return a!==1/0&&a>=Math.pow(2,n)?cp(n,t):i};cp.rack=function(n,t,e){var o=function(i){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=cp(n,t)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=t||16,o};var Ib=Ni,bS=Bb,vS=Eb,jh=No,ap=lp.exports,yS=xb.exports,Tb=Us.ACTIONS,Db=Re;function Re(n,t){if(Ib.EventEmitter.call(this),!t||typeof t!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=t,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}Ib.mixin(Re),Re.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Re.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Re.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||yS();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Re.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(o){if(o)return t._callbackOrEmit(o,n);var r=Object.keys(t._remotePresenceInstances);ap.parallel([function(i){ap.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();ap.each(r,function(s,l){t._remotePresenceInstances[s].destroy(l)},i)}],function(i){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(i,n)})})},Re.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?Tb.presenceSubscribe:Tb.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Re.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._receiveUpdate=function(n,t){var e=jh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=jh.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Re.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Re.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var t in this.localPresences){var e=this.localPresences[t];e.value!==null&&e.send()}},Re.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Re.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Re.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Re.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Re.prototype._callbackOrEmit=function(n,t){if(t)return jh.nextTick(t,n);n&&this.emit("error",n)},Re.prototype._createLocalPresence=function(n){return new bS(this,n)},Re.prototype._createRemotePresence=function(n){return new vS(this,n)},Re.prototype._callEachOrEmit=function(n,t){var e=jh.callEach(n,t);!e&&t&&this.emit("error",t)};var Va=Bb,Sb=Fh,kS=No,Lb=Sb.CODES,wS=Ho;function Ho(n,t){Va.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}Ho.prototype=Object.create(Va.prototype),Ho.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:Lb.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(e,t)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,Va.prototype.submit.call(this,n,t)},Ho.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)},Ho.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},Ho.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)},Ho.prototype._transformAgainstOp=function(n,t){var e=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=e._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=e._transformPresence(r.p,n,t),e._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=e._getCallback(r.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(r){this.emit("error",r)}},Ho.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Ho.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Ho.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},Ho.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!kS.supportsPresence(o))throw new Sb(Lb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var Mb={};(function(n){var t=ja,e=Fh,o=No,r=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var a=l.create.type;if(typeof a!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[a];if(d==null||typeof d!="object")return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(r.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new e(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,a){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=t.map[d.type];if(!h)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(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 e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new e(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new e(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in a||a.create||a.del)||"op"in d&&a.create)return new e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){if(!l)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{a.op=l.transform(a.op,d.op,"left")}catch(h){return h}}}a.v!=null&&a.v++},n.applyOps=function(l,a,d){d=d||{};for(var h=0;h<a.length;h++){var p=a[h];if(d._normalizeLegacyJson0Ops)try{s(l,p)}catch{return new e(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=p.v;var 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=t.map[p]),!p)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(p))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(a.create||a.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:p.transformPresence(l.p,a.op,d)}catch(A){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:A.message||A}}l.v++};function s(l,a){if(l.type===t.defaultType.uri){var d=a.op;if(!!d){var h=l.data;d.length>1&&(h=o.clone(h));for(var p=0;p<d.length;p++){var 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=t.defaultType.apply(h,[A]))}}}}})(Mb);var Wa=Eb,BS=Mb,ES=ao;function ao(n,t){Wa.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._pending=null,this._opCache=null,this._pendingSetPending=!1,this._opHandler=this._handleOp.bind(this),this._createDelHandler=this._handleCreateDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._registerWithDoc()}ao.prototype=Object.create(Wa.prototype),ao.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},ao.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)},ao.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)},ao.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))}})}},ao.prototype._handleOp=function(n,t,e){var o=e===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)},ao.prototype._transformAgainstOp=function(n,t){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,t)}catch(e){return this.presence.emit("error",e)}this.presence._updateRemotePresence(this)}},ao.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],t=n.op,e=n.isOwnOp;t===null?(this._pending.p=null,this._pending.v++):BS.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},ao.prototype._startCachingOps=function(){this._opCache=[]},ao.prototype._stopCachingOps=function(){this._opCache=null},ao.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var Rb=Db,xS=wS,IS=ES;function Xl(n,t,e){var o=Xl.channel(t,e);Rb.call(this,n,o),this.collection=t,this.id=e}var TS=Xl;Xl.prototype=Object.create(Rb.prototype),Xl.channel=function(n,t){return n+"."+t},Xl.prototype._createLocalPresence=function(n){return new xS(this,n)},Xl.prototype._createRemotePresence=function(n){return new IS(this,n)};var DS=SS;function SS(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var LS=DS,Ob=Ni,_b=qa;function qa(n,t,e,o,r){if(Ob.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=o,this.collection=e,this.callback=r,this.sent=!1}Ob.mixin(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,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new LS(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var Fb=_b,MS=No,RS=Us.ACTIONS,OS=up;function up(n,t,e,o,r,i){if(Fb.call(this,n,t,e,o,i),!MS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}up.prototype=Object.create(Fb.prototype),up.prototype._message=function(){return{a:RS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var Pb=_b,_S=No,FS=Us.ACTIONS,PS=dp;function dp(n,t,e,o,r,i){if(Pb.call(this,n,t,e,o,i),!_S.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}dp.prototype=Object.create(Pb.prototype),dp.prototype._message=function(){return{a:FS.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var NS=uS,$S=gS,HS=Db,Nb=TS,jS=OS,US=PS,$b=Ni,tc=Fh,te=Us.ACTIONS,Hb=ja,jo=No,Ga=gb,Za=tc.CODES;function jb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var zS=wt;function wt(n){$b.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.nextSnapshotRequestId=1,this.queries={},this._presences={},this._snapshotRequests={},this.seq=1,this._presenceSeq=1,this.id=null,this.agent=null,this.debug=!1,this.state=jb(n),this.bindToSocket(n)}$b.mixin(wt),wt.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var t=jb(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Ga.warn("Failed to parse message",o);return}e.debug&&Ga.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){jo.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(o){e.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?e._setState("closed",o):o==="stopped"||o==="Stopped by server"?e._setState("stopped",o):e._setState("disconnected",o)}},wt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=Ub(n.error,n),delete n.error),n.a){case te.initLegacy:return this._handleLegacyInit(n);case te.handshake:return this._handleHandshake(t,n);case te.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case te.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case te.queryUnsubscribe:return;case te.queryUpdate:var e=this.queries[n.id];if(!e)return;if(t)return e._handleError(t);n.diff&&e._handleDiff(n.diff),n.hasOwnProperty("extra")&&e._handleExtra(n.extra);return;case te.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case te.bulkSubscribe:case te.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case te.snapshotFetch:case te.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case te.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case te.subscribe:case te.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case te.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case te.presence:return this._handlePresence(t,n);case te.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case te.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case te.presenceRequest:return this._handlePresenceRequest(t,n);case te.pingPong:return this._handlePingPong(t);default:Ga.warn("Ignoring unrecognized message",n)}};function Ub(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}wt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var o in t.data){var r=t.data[o],i=this.getExisting(t.c,o);i&&(n?i[e](n):r.error?i[e](Ub(r.error)):i[e](null,r))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var o=t.b[s],i=this.getExisting(t.c,o);i&&i[e](n)}else if(t.b)for(var o in t.b){var i=this.getExisting(t.c,o);i&&i[e](n)}else Ga.error("Invalid bulk message",t)},wt.prototype._reset=function(){this.agent=null},wt.prototype._setState=function(n,t){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var e=new tc(Za.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var a=this._snapshotRequests[o];a._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},wt.prototype.startBulk=function(){this.bulk||(this.bulk={})},wt.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var t=this.bulk[n];this._sendBulk("f",n,t.f),this._sendBulk("s",n,t.s),this._sendBulk("u",n,t.u)}this.bulk=null},wt.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var a=e[l];a==null?o.push(l):(r[l]=a,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:t,d:l})}else o.length&&this.send({a:"b"+n,c:t,b:o});if(i===1){var d=r[s];this.send({a:n,c:t,d:s,v:d})}else i&&this.send({a:"b"+n,c:t,b:r})}},wt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var o=this.bulk[t.collection]||(this.bulk[t.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(t.id);return r[t.id]=e,i}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},wt.prototype.sendFetch=function(n){return this._sendActions(te.fetch,n,n.version)},wt.prototype.sendSubscribe=function(n){return this._sendActions(te.subscribe,n,n.version)},wt.prototype.sendUnsubscribe=function(n){return this._sendActions(te.unsubscribe,n)},wt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:te.op,c:n.collection,d:n.id,v:n.version,src:t.src,seq:t.seq,x:{}};"op"in t&&(e.op=t.op),t.create&&(e.create=t.create),t.del&&(e.del=t.del),n.submitSource&&(e.x.source=t.source),this.send(e)},wt.prototype.send=function(n){this.debug&&Ga.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},wt.prototype.ping=function(){if(!this.canSend)throw new tc(Za.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:te.pingPong};this.send(n)},wt.prototype.close=function(){this.socket.close()},wt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},wt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new NS(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},wt.prototype._destroyDoc=function(n){!n._wantsDestroy||(jo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},wt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},wt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new $S(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},wt.prototype._destroyQuery=function(n){delete this.queries[n.id]},wt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(te.queryFetch,n,t,e,o)},wt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(te.querySubscribe,n,t,e,o)},wt.prototype.hasPending=function(){return!!(this._firstDoc(Uh)||this._firstQuery(Uh)||this._firstSnapshotRequest())};function Uh(n){return n.hasPending()}wt.prototype.hasWritePending=function(){return!!this._firstDoc(VS)};function VS(n){return n.hasWritePending()}wt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Uh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Uh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}jo.nextTick(n)},wt.prototype._nothingPendingRetry=function(n){var t=this;return function(){jo.nextTick(function(){t.whenNothingPending(n)})}},wt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var o in e){var r=e[o];if(n(r))return r}}},wt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},wt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},wt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new jS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new US(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},wt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},wt.prototype._initializeHandshake=function(){this.send({a:te.handshake,id:this.id})},wt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},wt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},wt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new tc(Za.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(Hb.map[n.type]!==Hb.defaultType)return this.emit("error",new tc(Za.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new tc(Za.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},wt.prototype.getPresence=function(n){var t=this,e=jo.digOrCreate(this._presences,n,function(){return new HS(t,n)});return e._wantsDestroy=!1,e},wt.prototype.getDocPresence=function(n,t){var e=Nb.channel(n,t),o=this,r=jo.digOrCreate(this._presences,e,function(){return new Nb(o,n,t)});return r._wantsDestroy=!1,r},wt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},wt.prototype._addPresence=function(n){jo.digOrCreate(this._presences,n.channel,function(){return n})},wt.prototype._handlePresenceSubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},wt.prototype._handlePresenceUnsubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},wt.prototype._handlePresence=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},wt.prototype._handlePresenceRequest=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var zb=zS,WS=ja;const zh={err:1001,msg:"user auth error",name:"AuthError"},qS={err:1002,msg:"you don't have required permission",name:"PermissionError"},hp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Qa={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},GS={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},ZS={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Ya="x-live-editor-token",Vh="x-live-editor-base-url",gn=S("auth-connection");function QS(n){try{n()}catch(t){gn.error(t)}}class YS{constructor(t,e){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new V5.EventEmitter);m(this,"token",null);m(this,"resourceToken",null);this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return ws(this.getBaseURL())}async auth(t){g(gn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[Ya]:t.token,[Vh]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=t.token,await o.json()}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Vh]:ws(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new WB.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(zb.prototype),g(gn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},zb.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,gn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){gn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else gn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(zh.msg);t.code=zh.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Qa.msg);t.code=Qa.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const o=e.err;if(o===zh.err)gn.warn("auth error"),this.handleAuthError();else if(o===hp.err)gn.warn(hp.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(e)}`),this.emitAuthError()}get(t,e){return g(gn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(gn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(gn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(gn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.reauthFunc=void 0,this.events.removeAllListeners(),QS(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}S("utils/file");function JS(){function n(){return new Promise(t=>{const e=new FileReader;e.onload=()=>{t(e.result)},e.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}JS();async function KS(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new qB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>e&&(a=e);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return ws(i)}const dr=S("sharedb-doc/client");class XS{constructor(t,e,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",K());m(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(dr,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),dr.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;WS.register(Od.type),this.connection=new YS(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(dr,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,o=>{(t==="error"||this.doc)&&e(o)})}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,o,r,i){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const o=`${this.apiServer()}/resources`;let r=[];t.forEach(l=>{const a=l.split("|");r.push(...a)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[Ya]:this.connection.token}));return await Promise.all(i)}async uploadFile(t,e,o,r,i){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=v=>{dr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await KS(e),d=await this.getFileUrlByHash(t,a,e.name,e.size,o);if(d)return r(-1),d;let h=t;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${e.size}`),p.append("file-hash",a),p.append("file",e,e.name);const A=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return dr.info(A),r(100),Array.isArray(A.data)?A.data[0]:A.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(dr,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[Ya]:this.connection.token},e,o);return g(dr,s,"no result"),s}async request(t,e){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const a=e||{};a.url=t,a.headers||(a.headers={}),g(dr,o,"no token"),a.headers={...a.headers,[Ya]:o,[Vh]:this.connection.getBase64BaseURL()};try{return await zB.default(t,a)}catch(d){if(r=d,((i=d==null?void 0:d.response)==null?void 0:i.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;o=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw g(dr,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,r=(await this.request(e)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(t){const o=`${this.apiServer()}/versions/${t}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,o=await this.request(e);return JSON.parse(o.data.data)}async getVersionOps(t,e){let r=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(r+=`&from=${e}`);const i=await this.request(r),s=i.data.ops,l=VB.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(dr,a.create,"no createDoc.create"),d=a.create.data):d=JSON.parse(i.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:i.data.ops}}async updateVersionExtra(t,e,o){const i=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(t){const o=`${this.apiServer()}/versions/revert/${t}`;await this.request(o,{method:"post",data:{}})}async createVersion(t,e){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const o=`${this.apiServer()}/resources/external/${ws(t)}`;return(await this.request(o)).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let r=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const i=[];if(e!=null&&e.withToken&&i.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&i.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function tL(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const fp=S("block-ids");class eL{constructor(){m(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<e.length;r++){const i=e[r];if(i>=t){const s=this.ids.get(i);g(fp,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();this.ids.set(t,o)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<e.length;o++){const r=e[o];if(r>t){const i=this.ids.get(r);g(fp,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(t){let e=this.ids.get(t);return e||(e=K(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class nL{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new eL,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let o=0;o<e.length;o++){const r=e[o],i=r[1].getById(t);if(i)return{containerId:r[0],blockIndex:i[0]}}return g(fp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class Vb{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,o)=>{t[o]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const Wh=S("op-parse-handler");class oL{constructor(t,e){m(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const o={...t,containerId:(r=>r==="blocks"?"root":r)(t.containerId)};this.actions.push(o)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,o){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:o})}onDeleteBlockData(t,e,o){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:o})}onInsertBlockData(t,e,o,r){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:o,value:r})}onUpdateBlockText(t,e,o){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:o})}onDeleteContainer(t){this.pushActions({type:"deleteContainer",containerId:t})}onCreateContainer(t,e){this.pushActions({type:"createContainer",containerId:t,data:e})}onDeleteComment(t){this.pushActions({type:"deleteComment",commentId:t})}onCreateComment(t){this.pushActions({type:"createComment",commentId:t})}onUpdateComment(t){this.pushActions({type:"updateComment",commentId:t})}end(){const t=this.actions,e=new Set,o=new Map,r=new nL,i=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const d=o.get(a);d&&(Wh.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));const h=`${l.containerId}-${l.blockIndex}`;e.add(h),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,a=`${l.containerId}-${l.blockIndex}`;if(e.has(a)){Wh.warn("delete block data after delete block, ignore it");continue}const d=r.getBlockId(l.containerId,l.blockIndex);let h=o.get(d);h||(h=new Vb,o.set(d,h)),h.delete(l.key)}else g(Wh,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);let d=o.get(a);d||(d=new Vb,o.set(a,d)),d.insert(l.key,l.value)}else if(s.type==="updateBlockText"){const l=s;this.outerHandler.onUpdateBlockText(l.containerId,l.blockIndex,l.richTextData,this.local)}else if(s.type==="createComment"){const l=s;this.outerHandler.onCreateComment(l.commentId,this.local)}else if(s.type==="updateComment"){const l=s;this.outerHandler.onUpdateComment(l.commentId,this.local)}}),Array.from(o.entries()).forEach(([s,l])=>{const{containerId:a,blockIndex:d}=r.getBlockIndexById(s);Wh.debug(`update block data: ${a}, ${d}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Oe=S("op-parser");class Wb{}class mp{constructor(t){m(this,"key");this.key=t}}function rL(n,t,e){const o=t.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const a=o[l];if(!Array.isArray(a)||a.length!==2||typeof a[0]!="string")return!1;const h=a[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=i.i;g(Oe,s.id,"block id is required"),g(Oe,s.type,"block type is required");for(let l=1;l<o.length;l++){const a=o[l],d=a[0],h=a[1];s[d]=h.i}return e.onInsertBlock(n,r,s),!0}function gp(n,t,e,o){if(e==="upsert"&&rL(n,t,o))return;g(Oe,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const r=t.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const a=r[1];if(g(Oe,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),g(Oe,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}g(Oe,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Oe,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Oe,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Oe,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&e==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&e==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else e==="remove"&&d.r&&s.push(new mp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;e==="remove"&&a.r&&s.push(new Wb),e==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Oe,typeof l=="string","data is not string"),g(Oe,l!=="text","data !== 'text'"),g(Oe,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];e==="remove"&&d.r&&s.push(new mp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Wb?o.onDeleteBlock(n,i):l instanceof mp?o.onDeleteBlockData(n,i,l.key):g(Oe,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function iL(n,t,e){Oe.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function sL(n,t,e){const o=n[1],r=n[2];g(Oe,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Oe,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Oe.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?t==="upsert"&&e.onUpdateComment(o):r.i?t==="upsert"&&e.onCreateComment(o):r.r?t==="remove"&&e.onDeleteComment(o):Oe.error(`unknown comment op, ${JSON.stringify(n)}`)}function pp(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{pp(s,t,e)});return}const r=o;if(g(Oe,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){iL(n);return}if(r==="comments"){sL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{gp(i,s,t,e)}):n.slice(1).forEach(s=>{gp(i,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(i),s.i&&t==="upsert"&&e.onCreateContainer(i,s.i)}else g(Oe,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),gp(i,n.slice(1),t,e)}function qb(n,t,e){const o=new oL(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=mt.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{pp(a,i,o)}):pp(s,i,o)}o.end()}const lL=S("sharedb-comments");function Cp(n){const t=n.blocks;g(lL,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(e.blocks[o]=r)}),mt.default(e)}function Gb(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function Ap(n,t){const e=WD(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const ae=S("sharedb-doc/doc-container"),Zb="ot-json1";Od.type.registerSubtype(qD.type),Od.type.name=Zb,Od.type.invert=null;class Ja extends ha{constructor(e,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new zD);m(this,"batching",0);m(this,"status","clean");m(this,"disableLogout");m(this,"destroyed",!1);m(this,"handleNothingPending",()=>{this.setStatus("clean")});m(this,"handleCreate",()=>{this.handleReload("doc created")});m(this,"handleDel",()=>{});m(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});m(this,"handleReset",async e=>{const o=new Error(`reset doc: ${e}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});m(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});m(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});m(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});m(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});m(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,a])=>{if(!aa.default(i[l],a))if(i[l]===void 0){if(a!=null){const d={i:a};s.push([l,d])}}else if(a==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:a};s.push([l,d])}}),Object.entries(i).forEach(([l,a])=>{if((r[l]===void 0||r[l]===null)&&a!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});m(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){ae.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(ae.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),ae.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ae.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));m(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,Zb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainer",async(e,o)=>{const r=[Pi(e),{i:o}];return this.submitOp(r)});m(this,"submitDeleteChildContainer",async e=>{const o=[Pi(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[Pi(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[Pi(e),o,{r:!0}];return this.submitOp(r)});m(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[Pi(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a)){const h={r:!0,i:d};i.push([a,h])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(a=>{if(l.has(a))return;const d={r:!0};i.push([a,d])}),Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a))return;const h={i:d};i.push([a,h])}),this.submitOp(i)});m(this,"submitUpdateRichText",async(e,o,r)=>{const i=[Pi(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){ae.warn("handleOp: destroyed");return}qb(e,this,!!o)});this.client=e,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,g(ae,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new XS(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new Ja(o,r,e.disableLogout);if(r.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(e.templateData||tL())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ae.error(o),ae.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((e,o)=>{if(this.localPresence)e();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(K()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return Ha(this.data())}getContainerBlocks(e){const o=this.data();g(ae,o,"no doc data");const r=o[Pi(e)];return g(ae,r,`no container data: ${e}`),mt.default(r)}getBlockData(e,o){const r=this.data();g(ae,r,"no doc data");const i=r[Pi(e)];g(ae,i,`no container data: ${e}`);const s=i[o];return g(ae,s,`no block data: ${o}`),mt.default(s)}localInsertBlock(e,o,r){return this.submitInsertBlock(e,o,r),this.getBlockData(e,o)}localDeleteBlock(e,o){const r=this.getBlockData(e,o);return this.submitDeleteBlock(e,o),r}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(ae,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=ln.apply(s,r);return g(ae,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainer(e,o){this.submitInsertChildContainer(e,o)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>Gb(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return Cp(o)}localCreateComment(e,o){const r=Ap(e,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(e){const o=["comments",e,{r:!0}];return this.submitOp(o)}localUpdateComment(e,o){const r=Ap(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,o,r){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Kl(e),o,r)})}onInsertBlock(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockData(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockText(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Kl(e),o,r,i)})}onDeleteContainer(e,o){g(ae,this.callbacks.length>0,"no callbacks"),g(ae,e!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Kl(e),o)})}onCreateContainer(e,o,r){g(ae,this.callbacks.length>0,"no callbacks"),g(ae,e!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Kl(e),o,r)})}onDeleteComment(e,o){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,e,o)})}onCreateComment(e,o){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,e,o)})}onUpdateComment(e,o){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){const o=e;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:e,clientId:"-"};this.onCustomMessage(r)})}async addResources(e){return await this.client.getFileUrlsByHashes(e)}async uploadResource(e,o){var i;return{resourceId:await this.client.uploadResource(e,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(e,o){return this.client.buildResourceUrl(e,o)}request(e,o){return this.client.request(e,o)}getUser(){const e=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:e,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const o=await this.client.getVersion(e);return Ha(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return Ha(e)}async getHistoryData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:Ha(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:Ha(r),versionData:i}}async updateVersionExtra(e,o,r){await this.client.updateVersionExtra(e,o,r)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,o){return this.client.createVersion(e,o)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,o){qb(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class Qb{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Se.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));m(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const o=this.editor.findBlockById(e);o&&this.editor.reloadBlock(o)})});this.editor=t,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const Yb=S("remote-cursor-decorator");class bp{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];g(Yb,typeof s=="string","invalid path containerId"),g(Yb,typeof l=="number","invalid path blockIndex");const a=t.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,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 Jb extends ve.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Xt(Hr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=et(this.editor.getContainerById(t));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function cL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).addListener("change",t)}function aL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).removeListener("change",t)}const ant="",uL={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",name:"\u6587\u672C\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},dL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},hL={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};R.mergeLang({"zh-CN":uL,"en-US":dL,"js-JP":hL});const unt="";S("button");function uo(n,t,e,o,r){const i=w("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,t),e?typeof e=="string"?e.startsWith("<")?i.innerHTML=e:i.innerText=e:i.appendChild(e):i.innerText=t,o&&(o.indexOf("checked")!==-1&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0),o.indexOf("primary")!==-1&&W(i,"primary")),i}function Kb(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const dnt="",ec=S("ui-command-bar-base"),fL={itemElementTag:"div",tippyArrow:!1},Y2=class extends ve.TypedEmitter{constructor(e,o,r){var i,s;super();m(this,"content");m(this,"items");m(this,"subBar",null);m(this,"parentItem",null);m(this,"closeable",null);m(this,"closeReason",null);m(this,"options");m(this,"id");m(this,"header",null);m(this,"footer",null);m(this,"handleDocumentKeydown",e=>{if(!!this.isVisible&&!e.isComposing&&!Ss(e.target)){if(this.subBar){this.subBar.handleDocumentKeydown(e);return}if(this.items.length!==0){if(e.key==="Escape"){this.close("cancelBar");return}if(e.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(e.key==="ArrowLeft")this.parentItem&&this.close("switchItem");else if(e.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)}}}});m(this,"handleDocumentMouseDown",e=>{if(e.target instanceof Element&&!this.isInCommandBar(e.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,e)===!1)return;this.close("clickBackground")}});m(this,"handleHidden",()=>{this.closeReason!=="fromHover"&&this.emit("close",this),this.close(null),wC(this.id)});m(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&&kC(this.id)});m(this,"lastEnterPauseTime",0);m(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});m(this,"handleItemMouseEnter",e=>{if(Date.now()-this.lastEnterPauseTime<100)return;const o=this.getParentCommandItemElement(e.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)});m(this,"handleItemMouseLeave",e=>{var r,i;const o=this.getParentCommandItemElement(e.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(ot(o,"selected"),this.emit("selectionChange",this,""))});m(this,"handleItemClick",e=>{const o=this.getParentCommandItemElement(e.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"))}});m(this,"handleWheel",e=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=e.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=ro(r);if(!Kt(this.content,i)){e.stopPropagation(),e.preventDefault();return}e.deltaY<0?i.scrollTop===0&&(e.stopPropagation(),e.preventDefault()):e.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(e.stopPropagation(),e.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:K(),this.options={...fL,...r},this.items=e,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(e)}close(e){this.closeReason=e,this.subBar&&this.subBar.close(e),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(e,o){this.emit("click",this,e,o)}createPopperOptions(){var r,i;const e={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=e==null?void 0:e.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),this.options.padding&&((i=e==null?void 0:e.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),e}destroy(){var e;this.close(null),this.removeAllListeners(),(e=this.subBar)==null||e.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(e){var r;this.subBar&&e.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=e;const o=this.createCommandBarContent(e);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const e=this.getSelectedItem();return e?this.items.indexOf(e):-1}getPrevItemIndex(e){if(e<=0)return this.items.length-1;let o=e-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(e){let o=e+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 e=this.getSelectedItem();if(!e)return;const o=this.getItemElementById(e.id);o&&ot(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&ot(s,"selected")}const r=this.getItemElementById(e);r?(W(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(e){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=Y2.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});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,ot(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),W(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Kt(o,e)||Kt(this.content,e)?!0:this.subBar?this.subBar.isInCommandBar(e):!1}createCommandItem(e){var i,s,l,a;let o=(i=this.options.itemElementTag)!=null?i:"div";e.element&&(o="div");const r=w(o,["command-item"],null);return r.setAttribute("data-id",e.id),e.type==="separator"?r.classList.add("separator"):e.type==="section"?(r.classList.add("section","text"),e.element&&(typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element))):((s=e.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=e.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(a=e.states)!=null&&a.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,e.element?typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element):r.classList.add("standard")),this.initItemElement(e,r),r}getItemById(e){const o=this.items.find(r=>r.id===e);return g(ec,o,`can not find command item for id: ${e}`),o}getSelectedItem(){const e=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(e){const o=this.getItemElementId(e),r=this.items.find(i=>i.id===o);return g(ec,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return g(ec,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return g(ec,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(xt(e,"command-item"))return e;const o=e.closest(".command-item");return o||null}createCommandBarContent(e){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(e.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(e){var o;return{placement:(o=e.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(e,o){this.commandBarCreators.set(e,o)}static createSubCommandBar(e,o,r){var l;g(ec,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return g(ec,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Hi=Y2;m(Hi,"commandBarCreators",new Map),S("ui-command-bar");class qh extends Hi{constructor(){super(...arguments);m(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=GB.default(e,{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(e){var o;super.close(e),this.isVisible&&((o=this.tippyInstance)==null||o.hide())}destroy(){var e;(e=this.tippyInstance)==null||e.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var e,o;return(o=(e=this.tippyInstance)==null?void 0:e.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const Xb=S("ui-base");class Ka extends qh{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${K()}`,name:"",element:t}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(t){W(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];g(Xb,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return g(Xb,e,"no item element"),e}}const ji=S("filterable-list");function tv(n){var e,o;const t=w("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(w("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&W(t,"selected"),(o=n.states)!=null&&o.includes("disabled")&&W(t,"disabled"),t}function ev(n){const t=w("div",["list-root"],null);return n.forEach(e=>{t.appendChild(tv(e))}),n.length||t.appendChild(tv({id:"placeholder",states:["disabled"],name:R.t("search.emptyTips")})),t}function nv(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function mL(n,t){const e=w("div",["filterable-list"],null),o=w("div",["filter"],e),r=w("div",["filter-container"],o),i=w("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=w("div",["list"],e),l=ev(nv(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function ov(n,t,e){const o=n.querySelector(".list");g(ji,o,"no list root");const r=ev(nv(t,e)),i=o.querySelector(".list-root");if(g(ji,i,"no exists menu"),pa(i,r),e){const s=o.querySelector(".list-item.selected");s&&(g(ji,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class gL{constructor(t,e){m(this,"root");m(this,"visibleItems");m(this,"selectedId");m(this,"filter","");m(this,"onSelected",null);m(this,"handleKeydown",t=>{this.processKeyDown(t)});m(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");g(ji,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});m(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=mL(t,e),this.bindEvents(),this.selectedId=(o=e==null?void 0:e.initialSelectedId)!=null?o:"",this.visibleItems=t}bindEvents(){const t=this.root.querySelector(".filter-input");g(ji,t,"no input"),t.addEventListener("keyup",this.handleInputChanged),t.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const t=this.root.querySelector(".filter-input");g(ji,t,"no input"),t.removeEventListener("keyup",this.handleInputChanged),t.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(t=>t.id===this.selectedId):-1}setSelectedId(t){this.selectedId=t,ov(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");g(ji,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");g(ji,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),ov(this.root,this.visibleItems,this.selectedId))}processClick(t){var s,l;const e=t.target;if(!(e instanceof HTMLElement))return;const o=e.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(t){var e;if(t.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(t.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(t.key==="Enter"){const o=(e=this.visibleItems.find(r=>r.id===this.selectedId))!=null?e:null;this.onSelected&&this.onSelected(this,o)}}}class pL extends gL{constructor(e,o,r){super(e,r);m(this,"popup");m(this,"onShow",null);m(this,"onHide",null);m(this,"custom",null);m(this,"handleShow",()=>{this.onShow&&this.onShow(this)});m(this,"handleHide",()=>{this.onHide&&this.onHide(this)});m(this,"handleShown",()=>{this.focus()});this.popup=new Ka(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.reset(),this.popup.manualShow(e,{theme:"dropdown-list"}),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.popup.close("cancelBar")}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close("clickItem")}}const hnt="",fnt="";function CL(n,t){const e=document.createElement("div");e.classList.add("toast","show"),t!=null&&t.theme&&e.setAttribute("data-theme",t.theme),t!=null&&t.id&&e.setAttribute("data-id",t.id),t!=null&&t.html?e.innerHTML=n:e.textContent=n,t!=null&&t.position&&(e.style.left=`${t.position.x}px`,e.style.top=`${t.position.y}px`,e.classList.add("positioned")),document.body.appendChild(e),setTimeout(()=>{e.classList.remove("show"),setTimeout(()=>{e.remove()},500)},(t==null?void 0:t.duration)||3e3)}const rv=`<?xml version="1.0" ?>
|
|
27
|
+
`)}const sT=S("get-text-position");function ql(n,t){const e=t!=null?t:n.selection.range.start;e instanceof je||g(sT,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=bt(r),s=nt(r),l=at(s),{offset:a}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const Gl=S("insert-text");function Ig(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(g(Gl,r,"no block data"),g(Gl,r.text,"no block text"),rn(r.text)===0)return g(Gl,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=ze(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function lT(n,t,e){const o=nt(t),r=at(o),i=bt(t);return Ig(n,r,i,e)}function L6(n,t,e,o,r){const i=nt(t),s=at(i),l=bt(t),a=lT(n,t,e),d=ch(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),mn(n,t)}function M6(n,t,e,o){const r=nt(t),i=at(r),s=bt(t),l=ch(e," ",o);return n.doc.localUpdateBlockText(i,s,l),mn(n,t)}function cT(n,t){let e=0;if(t===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(Gl,typeof r.insert=="string","invalid text op, no insert");const i=e+ah(r);if(i===t)return!1;if(i>t)return!0;e=i}return!1}function Tg(n,t,e,o,r){const i=n.doc.getBlockData(e,o);g(Gl,i,"no block data"),g(Gl,i.text,"no block text");const s=Ig(n,e,o,r);s&&Object.keys(s).includes("link")&&(cT(i.text,r)||delete s.link);const l=ch(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),mn(n,n.getBlockById(i.id))}function Dg(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=ql(n);Tg(n,t,e,o,r)}const vh=S("update-composition-text");function R6(n){const t=n.selection.range.start;t instanceof je||g(vh,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(vh,tt(n,o),"not a text kind block");const r=nt(o),i=at(r),s=bt(o),l=n.doc.getBlockData(i,s);g(vh,l,"no block data in doc"),g(vh,l.text,"no text data in text block");const a=Lt(o);rh(n,Si(o),e,a,l.text)}function O6(n){Hx(n)}function Zl(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Ma=S("delete-block-text");function Sg(n,t,e,o,r){if(!n.isBlockWritable(t))return Ma.error("block is not writable"),0;g(Ma,tt(n,t),"block is not a text kind block");const i=nt(t),s=at(i),l=bt(t),a=n.doc.getBlockData(s,l);g(Ma,a,"no block data in doc"),g(Ma,a.text,"no text data in text block");let d=e;sn(t,e)||(d=Mi(t,d));let h=e+o;g(Ma,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),sn(t,h)||(h=Fs(t,h));const p=h-d,A=z4(d,p);return n.doc.localUpdateBlockText(s,l,A,r),p}const Lg=S("break-text-block");function _6(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Ql(n,t,e,o){g(Lg,tt(n,t),`block is not a text kind block: ${Dt(t)}`),g(Lg,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=nt(t),i=at(r),s=bt(t),l=o!=null&&o.copyBlockAttributes?_6(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...lr(""),...l,...o==null?void 0:o.newBlockData},D=ye(n,t.id,0),x=Zl(n,i,v,B,D);return{block:t,newBlock:x}}g(Lg,sn(t,e),"not a valid offset");const a=mn(n,t),{right:d}=xn(a,e),h=rn(d);h>0&&Sg(n,t,e,h);const p={...lr(d),...l,...o==null?void 0:o.newBlockData},A=Zl(n,i,s+1,p,ye(n,p.id,0));return{block:t,newBlock:A}}const aT=S("prepare-insert-new-block");function uT(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=pe(d);return g(aT,e>=0&&e<=h.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(t=at(nt(r)),e=bt(r),!tt(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===ut(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const a=Ql(n,r,s).newBlock;return{containerId:t,blockIndex:bt(a)}}const dT=S("auto-insert-block");function F6(n,t,e,o,r,i){const s=uT(n,e,o);g(dT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},a={anchor:l,focus:l};return Zl(n,s.containerId,s.blockIndex,t,r!=null?r:a,i)}const hT=S("delete-block");function yh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{yh(n,i,e)})}))}function kh(n,t,e){const o=nt(t),r=at(o),i=bt(t),s=n.doc.getBlockData(r,i);return g(hT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ue(n,{anchor:e.start,focus:e.end})),s}function Mg(n,t,e){return n.undoManager.runInGroup(()=>{const o=nt(t);Io(o)===1&&n.insertTextBlock("",at(o),0);let r=e?Li(n,e):null;if(!r){const l=n.selection.range;I6(t,l)?r=T6(n,t):r=l}const i=kh(n,t,r),s=[];return yh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function fT(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{yh(n,r,e)}),n.doc.localDeleteChildContainers(e)}function P6(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{yh(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const Rg=S("merge-text-block");function N6(n,t,e){g(Rg,tt(n,t),"only text block can be merged"),g(Rg,tt(n,e),"only text block can be merged");const o=Oi(n,t),r=Oi(n,e),i=o.text,s=r.text;g(Rg,i&&s,"block data has no text");const l=nt(t),a=at(l),d=bt(t),h=ut(n,t),p=Tg(n,s,a,d,h),A=ye(n,t,rn(i));return Mg(n,e,A),p}const cr=S("clear-selected-contents");function wh(n,t){g(cr,tt(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(cr,e.isSimple(),"not a simple block position"),g(cr,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(cr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function $6(n,t,e){const o=at(t),r=pe(t),i=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});e.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function mT(n,t){const{block:e,start:o,end:r}=t;if(tt(n,e)){wh(n,t);return}if(Me(e)||o.isSimple()){g(cr,r.isSimple(),"invalid range");const s=nt(e),l=bt(e),a=n.insertTextBlock("",at(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(cr,Mt(n,e),"invalid block kind"),g(cr,!o.isSimple()&&!r.isSimple(),"invalid range"),Rs(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{$6(n,s,{focus:l===0})})}function gT(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(cr,e.length>0,"no selected block"),e.length===1){mT(n,e[0]);return}const o=e[0],r=o.block,i=nt(r);g(cr,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(tt(n,r)){wh(n,o);const h=ye(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(A=>n.deleteBlock(A.block)),tt(n,l)){wh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(tt(n,l)){wh(n,s),e.slice(0,e.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(e.length===Io(i)){$6(n,i,{focus:!0});return}const a=ce(r),d=Zt(l);g(cr,a||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function Og(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),gT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const pT=S("core");function H6(n,t,e){const o=nt(t),r=at(o),i=bt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),mn(n,t)}function j6(n,t,e){if(!n.isBlockWritable(t)){pT.error("block is not writable");return}const o=n.getBlockText(t),r=ln.diff(o,e);H6(n,t,r)}function Bh(n,t,e){const o=mn(n,t),r=typeof e=="string"?Ri(e):e,i=ln.diff(o,r);return H6(n,t,i)}const Ra=S("update-block-data");function Eh(n,t,e,o){const r=nt(t),i=at(r),s=bt(t),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(e));return d.forEach(A=>{if(!h.has(A)){if(A==="id"||A==="type"||A==="text")return;Ra.debug(`delete key: ${A}`),a.delete.push(A)}}),Object.entries(e).forEach(([A,v])=>{g(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&&(aa.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),Oi(n,t)}function U6(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function _g(n,t,e){if(!Mt(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=Un(n,t).getChildContainers(n,t)[0],i=Le(r);_g(n,i,e)}function $s(n){const t=[];let e={};return n.forEach(o=>{t.push(...o.blocks.root);const{root:r,...i}=o.blocks;e={...e,...i}}),{blocks:{...e,root:t},meta:{},comments:{}}}const Oa=S("clone-block");function _i(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,p)=>(g(Oa,e!==p,"invalid child block"),_i(n,h,e,o)));let i={};const s=new Map,l=mt.default(e);l.children&&(l.children=l.children.map(h=>{const p=K(),A=t.blocks[h];g(Oa,Array.isArray(A),"invalid child blocks");const v=A.map(_=>_i(n,t,_,o)),B=$s(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(e.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Fg(n,t,e,o){const r=t.blocks[e];g(Oa,Array.isArray(r),"invalid child blocks");const i=r.map(l=>_i(n,t,l,o));return $s(i)}function Pg(n,t,e){const o=t.blocks.root.map(r=>_i(n.editorBlocks,t,r,e));return mt.default($s(o))}const z6=S("insert-doc");function V6(n,t,e,o,r){if(Mt(n,t)){z6.warn("failed to insert doc into a complex block");return}const i=Pg(n,o,r),s=nt(t),l=bt(t),a=at(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var M,H,z;Object.entries(i.blocks).forEach(([q,rt])=>{q!=="root"&&n.doc.localInsertChildContainer(q,rt)});const d=i.blocks.root;if(Me(t)){n.deleteBlock(t);let q;d.reverse().forEach(rt=>{const ft=n.insertBlock(a,l,rt);q||(q=ft)}),q&&n.selection.selectBlock(q,ut(n,q));return}if(g(z6,tt(n,t),"not a text block"),he(n,t)){const q=a==="root"&&n.getBlockByIndex(a,0)===t,rt=bt(t);let ft;d.forEach((Bt,jt)=>{const Ut=n.insertBlock(a,rt+jt,Bt);jt===d.length-1&&(ft=Ut)}),ft&&n.selection.selectBlock(ft,ut(n,ft)),q&&n.deleteBlock(t);return}if(d.length===1){const q=d[0];if(va(n,q.type)){n.insertTextToBlock(t,e,(M=q.text)!=null?M:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,q);return}const h=e===ut(n,t),p=e===0,A=d[0],v=d[d.length-1];let B;!h&&!p?B=n.breakTextBlock(t,e,{forceInsertAfter:!0}):B=t;const D=p?l:l+1;h?(B=n.insertBlock(a,l+1,v),n.selection.selectBlock(B,ut(n,B))):(n.selection.selectBlock(B,0),va(n,v.type)?n.insertTextToBlock(B,0,(H=v.text)!=null?H:[]):n.insertBlock(a,D,v));const x=n.selection.range;let _=D;va(n,A.type)?p?(n.insertBlock(a,D,A),_+=1):n.insertTextToBlock(t,e,(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 Ng(n,t,e,o,r){const i=Pg(n,o,r),s=at(t),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,e,d);l.push(h)})}),l}function W6(n,t,e){const o=Io(t);Ng(n,t,o,e);for(let r=0;r<o;r++){const i=Le(t);n.deleteBlock(i)}}const _a=S("add-text-attribute");function CT(n,t,e,o){const{start:r,end:i}=e;g(_a,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g(_a,o,"invalid attribute name");const s=n.getBlockText(t),l=Wl(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function q6(n,t,e,o,r){const{start:i,end:s}=e;g(_a,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(_a,o,"invalid attribute name");const l=n.getBlockText(t),a=xa(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Yl(n,t,e,o,r){const{start:i,end:s}=e;g(_a,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=X4(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function G6(n,t,e,o){const r=Ro(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!tt(n,s))return;if(he(n,s)){o(n,it(s),t,e);return}const d=Ue(n,{anchor:l,focus:a});t==="color"||t==="backgroundColor"?Yl(n,s,d,t,e):(Yl(n,s,d,"color",null),Yl(n,s,d,"backgroundColor",null))})})}function Z6(n,t,e){const o=Ro(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!tt(n,i))return;if(he(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,it(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,it(i),"backgroundColor",null);return}const a=Ue(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Yl(n,i,a,"color",null),(t==="clearBackground"||t==="clearAll")&&Yl(n,i,a,"backgroundColor",null)})})}function $g(n,t){const e=Ro(n,{simpleBlockOnly:!0}).filter(s=>tt(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(ut(n,s.block)===0)return t(n,it(s.block));const l=s.start,a=s.end,d=n.getBlockText(s.block);return n6(l.offset,a.offset-l.offset,d)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,a]=o(s);l===null||r===null?r=null:r=l===r?r:null,a===null||i===null?i=null:i=a===i?i:null}),[r,i])}const Wn=S("adjust-selection-pos");function Q6(n){const t=[];for(;n;){const e=nt(n);if(t.unshift(e),Xt(e))return t;const o=et(e);g(Wn,o,"child container has not parent container"),n=o}g(Wn,!1,"should not come here: getParentContainers")}function Y6(n,t){for(;t;){const e=nt(t);if(e===n)return t;const o=et(e);g(Wn,o,"could not find parent block for a child container"),t=o}g(Wn,!1,"no parent block in specified container")}function AT(n,t){const e=Q6(n),o=Q6(t);g(Wn,e.length>0&&o.length>0,"block has not parent container"),g(Wn,e[0]===o[0],"root container does not equal");let r=e[0];for(let l=1;l<e.length||o.length;l++)if(e[l]!==o[l]){r=e[l-1];break}const i=Y6(r,n),s=Y6(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function J6(n,t){let e=et(t);for(g(Wn,e,"element is not in a block");e;){const o=nt(e);g(Wn,Lo(o),"not a child container");const r=et(o);if(g(Wn,r,"child container has not parent block"),r===n)return o;e=r}g(Wn,!1,"failed to find parent container in complex block")}function xh(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof je&&e instanceof je?{anchor:t,focus:e}:t instanceof Mo&&e instanceof Mo?nh(n,o,t,e):null;const i=nt(o),s=nt(r);if(i===s)return t instanceof Mo&&(t=st(o,0,"home")),e instanceof Mo&&(e=st(r,ut(n,r),"end")),g(Wn,t instanceof je,"not valid position type"),g(Wn,e instanceof je,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof je&&e instanceof Mo){const B=n.getContainerById(e.childContainerId);if(B===i)return{anchor:e,focus:e};const D=et(i);if(D&&D===et(B)){const x=fe(D,at(i)),_=fe(D,at(B));return nh(n,D,x,_)}}return null}const l=$d(o,r)>0,{newBlock1:a,newBlock2:d}=AT(o,r);if(a===d){const B=a,D=J6(B,o),x=J6(B,r);return t=fe(a,at(D)),e=fe(a,at(x)),Wn.debug(`select in complex block: ${D.id}, ${x.id}`),nh(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof je&&(h=t.offset);let A=l?0:ut(n,d);return d===r&&e instanceof je&&(A=e.offset),t=st(a,h,l?"end":"home"),e=st(d,A,l?"home":"end"),{anchor:t,focus:e}}const bT=S("move-complex-block-position");function vT(n,t,e){const o=n.getBlockById(t.blockId);g(bT,Mt(n,o),"is not a complex block");const r=Un(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?fe(o,at(s)):null}const Fa=S("move-simple-block-position");function K6(n,t){const e=En(n,t,{visibleOnly:!0});g(Fa,e.length>0,"complex block has not any child container");const o=e[0];return Le(o)}function X6(n,t){const e=En(n,t,{visibleOnly:!0});g(Fa,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Ze(o)}function tA(n,t,e){const o=e?K6(n,t):X6(n,t);return Mt(n,o)?tA(n,o,e):o}function yT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===0?K6(n,e):Ds(e)}function kT(n,t){const e=n.getBlockById(t.blockId);return Mt(n,e)&&t.offset===1?X6(n,e):Ts(e)}function Hg(n){return n==="ArrowLeft"||n==="ArrowUp"}function jg(n,t,e){const o=nt(t);if(Xt(o))return null;const r=et(o);g(Fa,r,"child container has not parent block"),g(Fa,Mt(n,r),"is not a complex block");const i=Un(n,r).getNextContainer(n,r,o,e);return i?Hg(e)?Ze(i):Le(i):jg(n,r,e)}function wT(n,t,e){const o=nt(t);if(Xt(o))return null;const r=et(o);if(g(Fa,r,"child container has not parent block"),Hg(e)){const l=ce(r);if(l)return l}else{const l=Zt(r);if(l)return l}const i=jg(n,r,e);if(i)return i;let s=r;for(;!Xt(nt(s));)s=et(nt(s));return Hg(e)?ce(s):Zt(s)}function BT(n,t,e){return!Mt(n,t)||Un(n,t).enableKeyboardSelect?t:tA(n,t,e==="ArrowDown"||e==="ArrowRight")}function ET(n,t,e){const o=n.getBlockById(t.blockId),i=Qt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?yT(n,t):kT(n,t);if(s||(s=jg(n,o,e),s||(s=wT(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Xt(nt(o)))return null;const l=n.insertTextBlock("",at(n.rootContainer),Io(n.rootContainer));return st(l,0,"home")}return null}if(s=BT(n,s,e),tt(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return Kx(n,s,o,t,l);if(e==="ArrowUp")return Jx(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?st(s,ut(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?st(s,0,"home"):null}function xT(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(tt(n,r))return o;const i=Zt(r);if(i)return st(i,0,"home");if(!Xt(nt(r))||n.readonly)return o;const s=n.insertTextBlock("",at(n.rootContainer),Io(n.rootContainer));return st(s,0,"home")}function IT(n,t,e){const o=n.selection.range;let r;if(o instanceof Qe)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=xT(n,t,o):r=ET(n,o.getFocusedPos(),t);else if(r=vT(n,o.focus,t),e==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Ze(s);r=st(l,0,"home")}else{const l=Le(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:xh(n,o.anchor,r):null}function Fi(n,t,e){const o=IT(n,t,e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function eA(n){return Fi(n,"ArrowLeft","move"),!0}function nA(n){return Fi(n,"ArrowRight","move"),!0}function oA(n){return Fi(n,"ArrowUp","move"),!0}function rA(n){if(Fi(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=nt(t);if(Xt(e)||Ze(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",at(o),Io(o)),!0}function iA(n){return Fi(n,"ArrowDown","select"),!0}function sA(n){return Fi(n,"ArrowLeft","select"),!0}function lA(n){return Fi(n,"ArrowRight","select"),!0}function cA(n){return Fi(n,"ArrowUp","select"),!0}const aA=S("word-offset");function Ug(n,t){const e=n.selection.range.focus;g(aA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"home");if(e.offset===0||!tt(n,o)){const s=ce(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&tt(n,s)){const a=bg(n,s,l.offset);return st(s,a,"normal")}return l}const r=bg(n,o,e.offset);return st(o,r,"normal")}function zg(n,t){const e=n.selection.range.focus;g(aA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!tt(n,o)){const s=Zt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&tt(n,s)){const a=vg(n,s,l.offset);return st(s,a,"end")}return l}const r=vg(n,o,e.offset);return st(o,r,"normal")}function uA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ug(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function dA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function hA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ug(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function fA(n){if(!n.selection.range.focus.isSimple())return!1;const e=zg(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function Vg(n,t){if(!Mt(n,t))return t;const o=Un(n,t).getChildContainers(n,t)[0],i=pe(o)[0];return Vg(n,i)}function Wg(n,t){if(!Mt(n,t))return t;const e=Un(n,t).getChildContainers(n,t),o=e[e.length-1],r=pe(o),i=r[r.length-1];return Wg(n,i)}function mA(n){const t=Wg(n,Ze(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function gA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function pA(n){const t=Vg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function qg(n){const t=Wg(n,Ze(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const CA=S("line-offset");function AA(n){const t=n.selection.range.focus;g(CA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!tt(n,e))return st(e,0,"home");let r=N4(e,t).start;const{next:i}=Kd(e,r);return i&&so(i)&&ba(i)==="br"&&(r+=1),st(e,r,"home")}function bA(n){const t=n.selection.range.focus;g(CA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!tt(n,e))return st(e,ut(n,e),"end");const o=N4(e,t);return st(e,o.end,"end")}function vA(n){if(!n.selection.range.focus.isSimple())return!1;const e=AA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function yA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function kA(n){if(!n.selection.range.focus.isSimple())return!1;const e=AA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function wA(n){if(!n.selection.range.focus.isSimple())return!1;const e=bA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const BA=S("find-block-position");function TT(n,t,e,o){g(BA,Mt(n,t),"is not a complex block");const r=Un(n,t).getChildContainers(n,t);g(BA,r.length>0,"complex block has not any child container");const i=So(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=I4(n,t,s,l);return Gg(n,a,e,o)}function Gg(n,t,e,o){if(Mt(n,t))return TT(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=So(n,e,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=st(r,0,"home");const h=ut(n,t);for(let p=0;p<=h;p++){const A=st(r,p,"normal"),v=So(n,t,A),B=nr(v,l,a);B<i&&(i=B,d=A)}return d}const EA=S("page-offset");function DT(n,t){const e=B6(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<KI(n))return n.getFirstBlock();const i=ce(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ce(s)}return n.getFirstBlock()}function ST(n,t){const e=B6(n)*.9,o=t.getBoundingClientRect(),r=XI(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=Zt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Zt(l)}return n.getLastBlock()}function xA(n){const t=n.selection.range.focus;g(EA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=DT(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=Gg(n,o,e,t),r}function IA(n){const t=n.selection.range.focus;g(EA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=ST(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=Gg(n,o,e,t),r}function TA(n){if(!n.selection.range.focus.isSimple())return!1;const e=xA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function DA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function SA(n){if(!n.selection.range.focus.isSimple())return!1;const e=xA(n);if(!e)return!1;const o=xh(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function LA(n){if(!n.selection.range.focus.isSimple())return!1;const e=IA(n);if(!e)return!1;const o=xh(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const Pa=S("select-all");function MA(n,t){const e=Le(n),o=Ze(n);return t.start.offset===0&&t.start.blockId===it(e)&&t.end.offset===ut(t.getEditor(),o)&&t.end.blockId===it(o)}function LT(n,t){const e=t.getEditor(),o=Un(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=it(n);return t.start.blockId===s&&t.start.childContainerId===at(r)&&t.end.blockId===s&&t.end.childContainerId===at(i)}function MT(n,t){g(Pa,t,"no parent block"),g(Pa,Mt(n,t),"not a complex block");const e=Un(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Ue(n,{anchor:fe(t,at(o)),focus:fe(t,at(r))}))}function RA(n,t){const e=nt(t);Zg(n,e)}function OA(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&tt(n,t)){const r=e.start,i=e.end,s=ut(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return W(n.rootContainer,"select-all"),RA(n,Le(n.rootContainer)),!1}return g(Pa,!e.isSimple(),"invalid range type"),LT(t,e)?(RA(n,t),!1):(g(Pa,t,"no parent block"),g(Pa,Mt(n,t),"not a complex block"),MT(n,t),!0)}function Zg(n,t){const e=pe(t),o=e[0],r=e[e.length-1],i=st(o,0,"home"),s=st(r,ut(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function _A(n){qg(n),n.focus()}const Qg=S("selected-block-to-doc");function FA(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{FA(n,i,e)}),e.blocks[o]=mt.default(r)})}function Ih(n,t){const e=Qt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(Oi(n,t.block));if(tt(n,t.block)){const i=t.start,s=t.end;if(g(Qg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=ze(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Me(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(Qg,Mt(n,t.block),"not complex block"),g(Qg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return FA(n,o,r),r}function Yg(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Ih(n,{block:t,start:e,end:o})}const RT=S("block-to-doc");function OT(n,t){g(RT,t.length>0,"invalid params, no blocks");const e=t.map(o=>Yg(n,o));return $s(e)}function Th(n){const e=n.selection.range.getSelectedBlocks().map(o=>Ih(n,o));return $s(e)}function PA(n,t){const e=n.getContainerById(t),i=pe(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Ih(n,s));return $s(i)}const Dh=S("editor-selection");class _T{constructor(t){m(this,"editor");m(this,"caret");m(this,"_range");m(this,"lastCaretRect");m(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(I6(e,i)){Dh.debug("adjust selection because remote deleted current block");const s=T6(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new QI(t);const r=st(o,0,"normal");this._range=Ue(t,{anchor:r,focus:r}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const t=this.range.focus;return this.editor.getBlockById(t.blockId)}getStartBlock(){const t=this.range.start;return this.editor.getBlockById(t.blockId)}getEndBlock(){const t=this.range.end;return this.editor.getBlockById(t.blockId)}selectBlock(t,e,o){const r=st(t,e,"normal");let i;o&&(i=st(t,o,"normal")),this.setSelection(r,i)}setSelection(t,e,o){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const r=Ue(this.editor,{anchor:t,focus:e});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),xt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!oT(this.editor,r))&&ot(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),YI(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(t,e){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const t=this.range.focus;if(!jr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=So(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){nT(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Dh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Dh,!1,"invalid complex block position, no container found")}}updateFocusedBlock(t){if(t&&this.range.start.blockId===t.start.blockId)return;let e;t&&t.start.blockId===t.end.blockId&&(e=this.editor.findBlockById(t.start.blockId));let o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;e&&xt(e,"focused")&&(ot(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=Th(this.editor);return t==="text"?Sa(this.editor,e):t==="markdown"?La(this.editor,e):S6(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{ot(t,"focused"),ot(t,"child-focused")})}setBlockFocused(t){if(xt(t,"focused"))return!1;W(t,"focused");let e=nt(t);for(;Lo(e);){const o=et(e);g(Dh,o,"parent block not found"),W(o,"child-focused"),e=nt(o)}return!0}}function FT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,ut(n,e))}function PT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!tt(n,e))return;let o=Ug(n,"select"),r=zg(n,"select");if(!o||!r)return;const i=t.blockId;o.blockId!==i&&(o=st(e,0,"home")),r.blockId!==i&&(r=st(e,ut(n,e),"end")),n.selection.setSelection(o,r)}class NT{constructor(t){m(this,"editor");m(this,"startPos",null);m(this,"lastCaretRect");m(this,"mouseDownEvent",null);m(this,"autoScroll",null);m(this,"handleMouseDown",(t,e)=>{var r;this.mouseDownEvent=t;const o=S4(this.editor,t.x,t.y);if(o){if(o instanceof rr)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=ro(s[0].block);this.autoScroll=new qd({scrollElement:l,edge:{top:50,bottom:50}})}const i=this.editor.selection.range;if(t.shiftKey&&i.isSimple()){const s=i.anchor;this.editor.selection.setSelection(s,o.focus),this.startPos=o.start}else this.editor.selection.setSelection(o.anchor,o.focus),this.startPos=o.start;this.editor.selection.updateLastCaretRect(),e.autoScroll&&((r=this.autoScroll)==null||r.active())}});m(this,"handleMouseMove",t=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-t.x)<3&&Math.abs(this.mouseDownEvent.y-t.y)<3)return;const e=oh(this.editor,t.x,t.y);if(!e)return;const o=xh(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});m(this,"handleMouseUp",t=>{var e;(e=this.autoScroll)==null||e.inactive(),this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){PT(this.editor)}handleTripleClick(t){FT(this.editor)}}function $T(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function HT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const NA=S("delete-text");function $A(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof je||g(NA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(NA,tt(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!sn(s,l-e)){const a=Mi(s,l);e=l-a}}else if(t==="forward"&&l+e>ut(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function HA(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const jT=S("handle-backspace");function Jg(n,t){if(!he(n,t))return;const e=nt(t);Io(e)!==1&&n.deleteBlock(t)}function UT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===0){if(HA(n,o))return;const r=ce(o);if(r){if(!n.isBlockWritable(r))return;if(tt(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Mt(n,r)){Jg(n,o);const i=zl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else Jg(n,o),g(jT,Me(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=nt(o);if(Lo(i)){const s=B4(n,i);if(s){if(!n.isBlockWritable(s))return;Jg(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else $A(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function zT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===ut(n,o)){const r=Zt(o);if(r){if(!n.isBlockWritable(r))return;tt(n,r)?n.mergeTextBlock(o,r,{focus:!0}):he(n,o)?n.deleteBlock(o,ye(n,r,0)):n.deleteBlock(r)}}else $A(n,"forward",1,null);else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function VT(n){const{range:t}=n.selection,{start:e,end:o}=t,r=n.getBlockById(e.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Mt(n,r))return!1;if(jr(e))return!0;const s=Rs(n,r,e,o),l=En(n,r);return s.length===l.length}function WT(n,t){if(VT(n)){const o=n.getFocusedBlock(),r=bt(o),i=at(nt(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(tt(n,e)){if(he(n,e)&&HA(n,e))return;const o=n.selection.range.start,r=n.breakTextBlock(e,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 qT(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!tt(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const GT=S("input-handler-actions");function ZT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(WT(n),!0))}function QT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(zT(n),!0))}function YT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(UT(n),!0))}function JT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(qT(n),!0))}function KT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{GT.error(t)}),!0)}const Sh={ArrowDown:rA,ArrowUp:oA,ArrowLeft:eA,ArrowRight:nA,"Shift+ArrowDown":iA,"Shift+ArrowUp":cA,"Shift+ArrowLeft":sA,"Shift+ArrowRight":lA,"CtrlOrCmd+ArrowLeft":uA,"CtrlOrCmd+ArrowRight":dA,"CtrlOrCmd+Shift+ArrowLeft":hA,"CtrlOrCmd+Shift+ArrowRight":fA,"CtrlOrCmd+ArrowUp":gA,"CtrlOrCmd+ArrowDown":mA,"CtrlOrCmd+Shift+ArrowUp":pA,"CtrlOrCmd+Shift+ArrowDown":qg,"CtrlOrCmd+A":OA,Home:kA,End:wA,"Shift+Home":vA,"Shift+End":yA,PageUp:TA,PageDown:DA,"Shift+PageUp":SA,"Shift+PageDown":LA,"CtrlOrCmd+Z":$T,"CtrlOrCmd+Shift+Z":HT,Enter:ZT,Delete:QT,Backspace:YT,"Shift+Enter":JT,"CtrlOrCmd+Shift+V":KT};function jA(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function UA(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){const l=e.get(s);l&&(i.src=l)}return}const o=t.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=e.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{UA(n,l,e)})})}function zA(n,t,e){if(e.size===0)return;t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,e):UA(t,r,e)})}async function XT(n,t){const e=t.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(e),r=new Map;if(e.length!==o.length)return r;for(let i=0;i<e.length;i++)r.set(e[i],o[i]);return r}function tD(n,t){var i,s;const o=t.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function eD(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(tD(n,t)){const s=Array.from(Object.keys(o));r=await XT(n,s),zA(n,t,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&zA(n,t,i)}async function nD(n,t,e){await eD(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Me(i)){const s=nt(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,t,e);a&&n.selection.selectBlock(a,ut(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=ql(n);n.insertDoc(s,l,t,e)}})}const oD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function rD(n){let t;for(const e of oD)if(t=n[e],t)break;return t||null}function VA(n,t,e){if(t.type==="embed"){const s=t.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))e.add(l);return}const o=t.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&e.add(i.attributes.src)});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{VA(n,l,e)})})}function iD(n,t){const e=new Set;return t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{e.add(s)}):VA(t,r,e)}),Array.from(e)}function Lh(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${ws(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Mh(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=iD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function sD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Th(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Mh(n,o);const i=bh(n,o),s=La(n,o),l=Lh(i,o);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Rh(n,t){const e=Yg(n,t);Mh(n,e);const o=bh(n,e),r=La(n,e),i=Lh(o,e);return Lm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class lD{constructor(t){m(this,"editor");m(this,"handlers",[]);m(this,"onPasteText",async(t,e)=>{const o=new DataTransfer;o.setData("text/plain",t);const r=await this.editor.dataConverter.fromData(this.editor,o,e);r&&this.pasteDocs(r,null)});this.editor=t}onInsertText(t,e){if(!tt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=ql(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,e),this.editor.selection.updateLastCaretRect())}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleChanged&&o.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=ql(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,o,r)}}onUpdateCompositionText(t,e,o){this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=ql(this.editor);for(let l=0;l<this.handlers.length;l++){const a=this.handlers[l];a.handleUpdateCompositionText&&a.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(t){sD(this.editor,t,(e,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Me(o)&&this.editor.deleteBlock(o)}else Og(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{o&&this.pasteDocs(o,t)})}onFocus(){W(this.editor.rootElement,"active")}onBlur(){ot(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,o)=>{var s,l;const r=(s=e.order)!=null?s:1;return((l=o.order)!=null?l:1)-r})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,o,r))return!0}return!1}handleAfterInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,o,r))return!0}return!1}handleBeforeKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,o,r,i){Dg(this.editor,i)}defaultHandleKeydown(t,e){return jA(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await nD(this.editor,t,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,e,t))return}const o=rD(t);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function cD(n,t,e){const o=_r(t,e);return o.remove(),o}S("copy-dom-attributes");const WA=["onabort","onanimationcancel","onanimationend","onanimationiteration","onanimationstart","onauxclick","onblur","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","ongotpointercapture","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onlostpointercapture","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onpause","onplay","onplaying","onpointercancel","onpointerdown","onpointerenter","onpointerleave","onpointermove","onpointerout","onpointerover","onpointerup","onprogress","onratechange","onreset","onresize","onscroll","onsecuritypolicyviolation","onseeked","onseeking","onselect","onselectionchange","onselectstart","onslotchange","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","ontouchcancel","ontouchend","ontouchmove","ontouchstart","ontransitioncancel","ontransitionend","ontransitionrun","ontransitionstart","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","onwheel"];function aD(n,t){for(let l=0;l<WA.length;l++){const a=WA[l];t[a]=n[a]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const a=e[l],d=o.getNamedItem(a.name);d?d.value!==a.value&&(d.value=a.value,i.push(a)):r.push(a)}const s=[];for(let l=0;l<o.length;l++){const a=o[l];e.getNamedItem(a.name)||s.push(a)}r.forEach(l=>{t.setAttribute(l.name,l.value)}),i.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function qA(n){const t=Array.from(n.childNodes).filter(e=>!$C(e));return t.forEach(e=>{e.remove()}),t}function GA(n,t,e){var d;const o=n.getContainerById(t),r=_r(o,e),i=Si(r),s=n.doc.getBlockData(t,e),l=Qt(n,r);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const h=n.editorBlocks.createBlock(i,o,s),p=qA(h);qA(r),p.forEach(v=>{r.appendChild(v)});const A=Yd(h);if(A){const v=Yd(r);v&&v.remove(),r.appendChild(A)}aD(h,r)}o4(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 uD=S("transform-selection");function ZA(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(uD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const d=ln.transformCursor(i.offset,e,o);l=st(t,d,"normal")}let a=s;if(s.blockId===t){const d=ln.transformCursor(s.offset,e,o);a=st(t,d,"normal")}return Ue(n,{anchor:l,focus:a})}const dD=S("handle-block-text-changed");function hD(n,t,e,o,r){const i=n.getContainerById(t),s=_r(i,e),l=n.doc.getBlockData(t,e);if(g(dD,l.text,"no block text"),JC(n,s).setBlockText(n,s,l.text),!r){const a=ZA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function fD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function QA(n,t,e,o){const r=Qt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function mD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{QA(n,i,o,{child:!0})}),QA(n,r,o,{child:!1})}const _o=S("editor-doc");class gD extends ha{constructor(e,o,r){super();m(this,"localEvents",[]);this.editor=e,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}verifyBlockWritable(e,o){const r=this.editor.getBlockByIndex(e,o);g(_o,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(_o,l,`no text, ${e}, ${o}`);const a=ZA(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(e,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(e,o,r,i){g(_o,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,o);if(!this.editor.isBlockWritable(s)){const h=Array.from(r.delete).filter(A=>A!=="comments"),p=Object.keys(r.insert).filter(A=>A!=="comments");(h.length>0||p.length>0)&&g(_o,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(fD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(Li(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(_o,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return this.editor.selection.setRange(Li(this.editor,i),s),l}localDeleteBlock(e,o,r){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const i=mt.default(this.getBlockData(e,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,o,i,r));const s=this.externalDoc.localDeleteBlock(e,o,r);return this.editor.selection.setRange(Li(this.editor,r)),s}localDeleteChildContainers(e){return g(_o,!this.editor.readonly,"editor is readonly"),e.forEach(o=>{const r=mt.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainer(e,o){return g(_o,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,mt.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){_o.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,o,r,i)}),hD(this.editor,e,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,i)}),GA(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);ox(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){mD(this.editor,e,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,r)});const i=this.editor.getContainerById(e);cD(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(e,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,r)})}onDeleteChildContainer(e,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,e)})}onStatusChanged(e){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)})}onError(e){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,e)})}uploadResource(e,o){return this.externalDoc.uploadResource(e,o)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,o){return this.externalDoc.buildResourceUrl(e,o)}request(e,o){return this.externalDoc.request(e,o)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,o,r;return(r=(o=(e=this.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}reset(e){_o.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function YA(n,t){if(n.length===0){n.push(t);return}const e=n[n.length-1];if(!e.combinable(t)){n.push(t);return}e.combine(t)}const Kg=S("undo-action");class Jl{constructor(t,e,o){m(this,"beforeRange");m(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=o}undo(t){return!1}redo(t){return!1}combinable(t){return g(Kg,t,"no other action"),!1}combine(t){g(Kg,!1,"no other")}setAfterRange(t){this.afterRange&&Kg.warn("after range has already set"),this.afterRange=t}}const pD=S("block-action");class JA extends Jl{constructor(e,o,r,i,s){super(e,o,s);m(this,"blockData");m(this,"blockIndex");this.blockData=mt.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(g(pD,this.blockIndex===bt(i),"invalid block index"),kh(e,i,Li(e,o)),!0):!1}insertBlock(e,o){return Zl(e,this.containerId,this.blockIndex,mt.default(this.blockData),o),!0}}class CD extends JA{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class AD extends JA{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class bD extends Jl{constructor(e){super(e,at(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){YA(this.actions,e),this.afterRange=e.afterRange}undo(e){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(e)&&(o=!0)}),o}redo(e){let o=!1;return this.actions.forEach(r=>{r.redo(e)&&(o=!0)}),o}setAfterRange(e){this.afterRange=e;const o=this.actions[this.actions.length-1];!o||o instanceof Jl&&(o.afterRange||o.setAfterRange(e))}}const Hs=S("update-block-data-action");class Oh extends Jl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=r,g(Hs,this.blockId===i.id,"invalid block id"),g(Hs,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(i),this.afterBlockData=mt.default(s),g(Hs,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Eh(e,o,Oh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Eh(e,o,Oh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const Xg=S("update-block-text-action");class Na extends Jl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=r,this.beforeRichTextData=mt.default(i),this.afterRichTextData=mt.default(s),this.type=Na.calType(i,s)}static calType(e,o){g(Xg,e,"no old data"),g(Xg,o,"no new data");const i=ln.diff(e,o),s=new Set;let l=!1;const a=h=>mC(h)?`cjk_${h}`:hC(h)?"number":Hd(h)?"space":fC(h)?"letter":"unknown";let d=!1;return i.forEach(h=>{h.insert?h.insert===" "?s.add("insert_letter"):typeof h.insert=="string"&&h.insert.startsWith(" ")&&h.insert.length>1?(l=!0,d=!0,s.add(`insert_${a(h.insert.substr(1))}`)):s.add(`insert_${a(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Bh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Bh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Na)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const o=e.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(e){g(Xg,e instanceof Na,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class KA extends Jl{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return t.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(t){return t.doc.localInsertChildContainer(this.containerId,mt.default(this.blocks)),!0}}class vD extends KA{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class yD extends KA{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Fo=S("undo");class kD{constructor(t){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(this,"handleSelectionChange",t=>{if(this.currentGroup){this.currentGroup.setAfterRange(t.selection.range.toDocRange());return}const e=this.actions[this.actions.length-1];!e||e.afterRange||e.setAfterRange(t.selection.range.toDocRange())});this.editor=t,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(t){this.currentGroup?this.currentGroup.addAction(t):(YA(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Fo,!this.currentGroup,"current group already exists"),this.currentGroup=new bD(this.editor),this.groupCounter=1):(g(Fo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Fo,this.currentGroup,"current group not exists"),g(Fo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Fo.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw Fo.error(`failed to run action: ${e.message}`),e}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const t=this.actions[this.undoCursor];if(t.undo(this.editor)){try{this.editor.selection.setRange(Li(this.editor,t.beforeRange))}catch(e){Fo.error(`undo: failed to restore caret pos: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const t=this.actions[this.undoCursor];if(this.undoCursor+=1,t.redo(this.editor)){try{const e=t.afterRange;e?this.editor.selection.setRange(Li(this.editor,e)):Fo.warn("no after range")}catch(e){Fo.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),ln.diff(o,r).length!==0&&this.addAction(new Na(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Oh(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Fo,e>=0,"invalid block index"),g(Fo,o,"no block data"),this.addAction(new CD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new AD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new vD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new yD(this.editor,t,e)))}}class wD{async fromData(t,e){const o=e.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class BD{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new wD)}prepareData(t){const e=new DataTransfer;for(let o=0;o<this.converterTypes.length;o++)e.setData(this.converterTypes[o],t.getData(this.converterTypes[o]));return e}async fromData(t,e,o){let r={};const i=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,i,o);l&&(r={...r,...l})}return r}addConverter(t){this.converters.push(t)}}class ED{constructor(t){m(this,"renders",[]);this.editor=t}registerRender(t){this.renders.push(t)}renderText(t,e){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,t,e);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(t,e,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,e,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(t,e,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,t,e,o,r)})}}class Ce extends ve.TypedEmitter{constructor(e){super();m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"filters",[]);m(this,"finders",[]);m(this,"handleDocumentMouseMove",e=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,e))return}const o=document.elementFromPoint(e.x,e.y);if(!o){this.setHoveringBlock(null,e,null);return}let r=et(o);if((!r||!Kt(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(e),!r)){this.setHoveringBlock(null,e,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,e,i)});this.editor=e,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(e=>e.destroy()),this.filters=[],this.finders.forEach(e=>e.destroy()),this.finders=[]}addFilter(e){this.filters.push(e)}addFinder(e){this.finders.push(e)}hoveringBlockId(){return this.hoveringBlock?it(this.hoveringBlock):""}findBlockByFinders(e){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,e);if(i)return i}return null}setHoveringBlock(e,o,r){if(this.hoveringBlock===e&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==e){const s=this.hoveringBlock&&Kt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&ot(s,"hover"),e&&W(e,"hover"),this.hoveringBlock=e,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(e){return e.addCustom("standard-hovering-block",()=>new Ce(e))}getParentTextContentChild(e,o){if(!tt(this.editor,e))return null;const r=Lt(e);return o.parentElement===r?o:Nm(o)}}const XA="style-color-",tb="style-bg-color-";class xD{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(XA)?i["data-style-color"]=l.substring(XA.length):l.startsWith(tb)?i["data-style-bg-color"]=l.substring(tb.length):l.startsWith("style")&&r.push(l):typeof a=="string"&&(l==="link"&&(r.push("link"),i.link=a),l==="inline-style-color"&&(s.color=a))}),{classes:r,attributes:i,styles:s}}renderBlock(t,e,o){var l,a;const r={};Object.entries(o).filter(d=>d[0].startsWith("style-")).forEach(([d,h])=>{r[`data-${d}`]=`${h}`});const s=[];return((a=(l=t.selection)==null?void 0:l.range)==null?void 0:a.start.blockId)===o.id&&s.push("focused"),typeof o.align=="string"&&o.align&&(r["data-style-align"]=o.align),o.heading&&(r["data-style-heading"]=String(o.heading)),o.quoted&&(r["data-style-quoted"]="true"),Ce.get(t).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(t,e,o,r){var s,l;Array.from(o.attributes).forEach(a=>{a.name.startsWith("data-style-")&&o.removeAttribute(a.name)}),Object.entries(r).filter(a=>a[0].startsWith("style-")||a[0]==="align").forEach(([a,d])=>{a==="align"&&o.setAttribute(a.startsWith("style-")?`data-${a}`:`data-style-${a}`,`${d}`)}),((l=(s=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),Ce.get(t).hoveringBlockId()===r.id&&W(o,"hover")}}function ID(n){n.editorBlocks.registerBlockClass(In),n.editorBlocks.registerBlockClass(w4),n.editorBoxes.registerBoxClass(f6),n.editorBoxes.registerBoxClass(m6),n.editorBoxes.registerBoxClass(C6),n.editorBoxes.registerBoxClass(A6),n.editorInsertions.registerInsertionClass(b6),n.editorBlockRenders.registerRender(new xD)}function TD(n,t){ID(n),t!=null&&t.blocks&&t.blocks.forEach(e=>n.editorBlocks.registerBlockClass(e)),t!=null&&t.boxes&&t.boxes.forEach(e=>n.editorBoxes.registerBoxClass(e)),t!=null&&t.embeds&&t.embeds.forEach(e=>n.editorEmbeds.registerEmbedClass(e)),t!=null&&t.insertions&&t.insertions.forEach(e=>n.editorInsertions.registerInsertionClass(e)),t!=null&&t.decorators&&t.decorators.forEach(e=>n.editorDecorators.registerDecorator(e)),t!=null&&t.dataConverters&&t.dataConverters.forEach(e=>n.dataConverter.addConverter(e)),t!=null&&t.commandProviders&&t.commandProviders.forEach(e=>n.editorCommandProviders.registerCommandProvider(e)),t!=null&&t.textRenders&&t.textRenders.forEach(e=>n.editorBlockRenders.registerRender(e))}const eb=S("range-commands");function nb(n,t){n.forEach(e=>{e.source=t,e.children&&nb(e.children,t)})}function ob(n,t,e){const o=it(t);g(eb,o===e.start.blockId,"invalid start range"),g(eb,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);nb(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),Mt(n,t)&&Rs(n,t,e.start,e.end).forEach(l=>{pe(l).forEach(d=>{const h=ut(n,d),p=Ue(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),A=ob(n,d,p);i.push(...A)})}),i}function rb(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Ue(t,{anchor:r.start,focus:r.end});ob(t,r.block,i).forEach(l=>{o.push(l)})}),o}function ib(n,t,e,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const A=s[p];if(A.beforeExecuteCommand&&A.beforeExecuteCommand(n,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,o,r,{}))return i[it(t)]=a,!0;let d=!1;return Mt(n,t)&&Rs(n,t,e.start,e.end).forEach(A=>{pe(A).forEach(B=>{const D=ut(n,B),x=Ue(n,{anchor:st(B,0,"home"),focus:st(B,D,"end")});ib(n,B,x,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function sb(n,t,e){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(t.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,t,e,r)||n.getSelectedBlocks().forEach(l=>{const a=Ue(o,{anchor:l.start,focus:l.end});ib(o,l.block,a,t,e,r)}),r}const DD=S("command-providers");class lb{constructor(t){m(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(o=>o.id===t);return g(DD,e,`no command provider, id=${t}`),e}getCommands(t){return rb(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>sb(t,e,o))}getEmptyBlockTextAttributes(t,e){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,t,e);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function SD(n,t){const e=nt(t),o=at(e),r=bt(t);GA(n,o,r)}const LD=S("table-scroll");class cb{constructor(t,e,o,r,i){m(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=o,this.handler=r,this.data=i,e.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class MD{constructor(t){m(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(o=>o.destroy()),this.handlers.delete(t)})}addEventListener(t,e,o,r){const i=this.handlers.get(t);if(i){if(i.find(s=>s.handler===o&&s.name===e)){LD.warn(`event has already registered: ${e}`);return}i.push(new cb(this.editor,t,e,o,r))}else{const s=new cb(this.editor,t,e,o,r);this.handlers.set(t,[s])}}removeEventListener(t,e,o){if(!t){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const a=s[l];if(e)e===a.name&&o===a.handler&&s.splice(l,1);else if(o===a.handler){s.splice(l,1),a.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(t);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===e);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const o=this.handlers.get(t);if(o)if(e)for(let r=0;r<o.length;r++){const i=o[r];i.name===e&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(t)}}const ab=S("update-block-text");function RD(n,t){const e=n.getBoxById(t.id),o=et(e);g(ab,o,"no parent block"),g(ab,tt(n,o),"not a text block");const r=n.getBlockText(o),i=r6(r,"id",t.id,t);j6(n,o,i)}function OD(n,t){for(const e of n.blockHooks)if(e.writable){const o=e.writable(n,t);if(typeof o=="boolean")return o}return!0}function _D(n){return n.readonly?!1:!Ro(n).find(o=>!n.isBlockWritable(o.block))}class FD{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}getItem(t){return window.localStorage.getItem(this.getKey(t))}setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class PD{constructor(){m(this,"shortcuts",[])}handleKeyboardEvents(t,e){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(Or(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const qr=S("editor");class ND extends ve.TypedEmitter{constructor(e,o,r){var i,s,l,a,d,h,p;super();m(this,"parent");m(this,"rootElement");m(this,"contentElement");m(this,"rootContainerObject");m(this,"rootContainer");m(this,"input");m(this,"selection");m(this,"selectionHandler");m(this,"doc");m(this,"id");m(this,"clientId");m(this,"compositingText","");m(this,"undoManager");m(this,"shortcuts",new PD);m(this,"dataConverter",new BD);m(this,"editorBlocks",new b4(this));m(this,"editorBoxes",new p6(this));m(this,"editorInsertions",new y6(this));m(this,"editorEmbeds",new y4(this));m(this,"editorDecorators",new k6(this));m(this,"editorCommandProviders",new lb(this));m(this,"editorBlockRenders",new ED(this));m(this,"blockHooks",[]);m(this,"domEvents",new MD(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new lD(this));m(this,"settingsProvider");m(this,"_readonly",!1);qr.debug("create editor"),this.setMaxListeners(100),this.options={colors:(i=r==null?void 0:r.colors)!=null?i:["#9923E9","#4587C2","#8BDB7A","#FB28D3","#CBC619","#10FEEB","#812A1A","#8A3F25","#22D742","#A53E74","#555C87","#57E0AA"],componentsOptions:(l=(s=r==null?void 0:r.components)==null?void 0:s.options)!=null?l:{},scrollContainer:r==null?void 0:r.scrollContainer},this.settingsProvider=(a=r==null?void 0:r.settingsProvider)!=null?a:new FD(this),TD(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 kD(this),this.doc=new gD(this,o,this.undoManager),this.parent=e,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=p4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new ZI(this,this.inputHandlers),this.selection=new _T(this),this.selectionHandler=new NT(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Ke.isMobile&&W(this.rootElement,"mobile"),Ke.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?W(this.rootElement,"readonly"):ot(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:ro(this.rootContainer)}addCustom(e,o){const r=this.customs.get(e);if(r)return r;const i=o(this);return this.customs.set(e,i),i}getCustom(e){const o=this.customs.get(e);return g(qr,o,`${e} does not exists`),o}replaceCustom(e,o){const r=this.customs.get(e);return r&&r.destroy(),this.customs.set(e,o),o}findCustom(e){return this.customs.get(e)}findCustomByType(e){const o=this.customs.values();for(const r of o)if(r instanceof e)return r;return null}destroyCustom(e){const o=this.customs.get(e);o&&(this.customs.delete(e),o.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,o,r){return this.editorBlocks.createBlock(e,o,r)}createBox(e,o){return this.editorBoxes.createBox(e,o)}createInsertion(e,o){return this.editorInsertions.createInsertion(e,o)}destroy(){qr.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(e=>e.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus(),setTimeout(()=>{W(this.rootElement,"active")})}focusToBlock(e,o){_g(this,e,o)}isWritable(){return _D(this)}isBlockWritable(e){return OD(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return g(qr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(qr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return C4(this,e,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(qr,Es(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(qr,Pm(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(qr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(qr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return _r(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return bt(o)}return bt(e)}getContainerById(e){return Hr(this,e)}getParentContainer(e){return nt(e)}reloadBlock(e){SD(this,e)}contains(e){const o=e instanceof Element?e:e.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,o,r,i,s){const l={blockId:r.id,offset:0},a={anchor:l,focus:l};return Zl(this,e,o,r,i!=null?i:a,s)}insertEmbed(e,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){Mg(this,e,o)}mergeTextBlock(e,o){return N6(this,e,o)}breakTextBlock(e,o,r){return Ql(this,e,o,r).newBlock}getTextPosition(){return ql(this)}getBlockString(e,o){const r=this.getBlockText(e);return ie(r,o)}getBlockData(e){return Oi(this,e)}getBoxData(e){return d6(this,e)}getBlockText(e){return mn(this,e)}setBlockText(e,o){j6(this,e,o)}deleteTextFromBlock(e,o,r,i){return Sg(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return L6(this,e,o,r,i)}insertBoxToBlock(e,o,r){return M6(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){V6(this,e,o,r,i)}insertDocAt(e,o,r,i){return Ng(this,e,o,r,i)}deleteChildContainers(e){P6(this,e)}replaceBlockText(e,o){return Bh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Eh(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return U6(this,e,o,r)}updateBoxData(e){RD(this,e)}getSelectedText(){const e=Th(this);return Sa(this,e)}clearSelectedContents(){Og(this)}insertTextBlock(e,o,r,i){const s=lr(e!=null?e:"");return F6(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){O6(this);return}o?(this.compositingText="",Bm()||Dg(this,e)):(this.compositingText=e,R6(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function $a(n,t,e){return new ND(n,t,e)}function $D(n){const t=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=hm.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const HD=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class _h extends ve.TypedEmitter{constructor(e){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=e&&e.length>0?e:HD}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&aa.default(o,e))return;this.cursors.set(e.user.userId,e);const r=new Set([e.range.anchor.blockId,e.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(e){this.addingUser=!0,e.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var o;return(o=this.users.get(e))!=null?o:null}removeUser(e){this.users.delete(e),this.cursors.delete(e),this.emit("change",Array.from(this.users.values()))}updateUsers(e){this.users.clear(),this.addingUser=!0;try{e.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e&&fh(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(fh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===e.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===e.id&&(d.offset=ln.transformCursor(d.offset,o,r))}})}getFixedUserColor(e,o){let r=0;Array.from(e).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const Xe=S("local-doc");class tp extends ha{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[lr("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`);const i=r[o];return g(Xe,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(Xe,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.call(l,e,o,r,!0)}),s}localUpdateBlockData(e,o,r){const i=this.getBlockData(e,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,!0)}),i}localInsertBlock(e,o,r){const i=this.getContainerBlocks(e);return g(Xe,i,`no container data: ${e}`),g(Xe,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,o,r,!0)}),r}localDeleteBlock(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`),g(Xe,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,!0)}),i}localInsertChildContainer(e,o){this.doc.blocks[e]=o,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,e,o,!0)})}localDeleteChildContainers(e){Xe.debug(`delete child containers: ${e}`),e.forEach(o=>{g(Xe,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(e,o){g(Xe,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){g(Xe,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new _h}setDoc(e){this.doc=mt.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class jD{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function ep(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new jD(o)})}const ub=S("find-block");function db(n,t){const e=Ts(t);if(!e){if(io(t))return null;const o=xs(t);return g(ub,o,"no parent block"),db(n,o)}return Mt(n,e)?zl(n,e,{visibleOnly:!0}):e}function hb(n,t){const e=Ds(t);if(!e){if(io(t))return null;const o=xs(t);return g(ub,o,"no parent block"),hb(n,o)}return Mt(n,e)?Xm(n,e,{visibleOnly:!0}):e}const UD=S("remote-cursor");class zD{constructor(){m(this,"remoteUsers",new _h)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):UD.debug(`unknown remote message received: ${t}`)}handleUpdateUsers(t){this.remoteUsers.updateUsers(t)}handleUpdateCaret(t){const e=this.remoteUsers.findUser(t.userId);!e||this.remoteUsers.setCursor({oneseditor:"cursor",user:e,range:t.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function VD(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function WD(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function Ha(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=VD(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function Pi(n){return n==="root"?"blocks":n}function Kl(n){return n==="blocks"?"root":n}const qD={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new on.default(n)},apply(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},compose(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},diff(n,t){const e=new on.default(n),o=new on.default(t);return e.diff(o).ops},transform(n,t,e){const o=new on.default(n);return new on.default(t).transform(o,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const o=new on.default(t),r=this.transformCursor(n.index,o,e),i=this.transformCursor(n.index+n.length,o,e);return{...n,index:r,length:i-r}}}};var ar=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ni={},np=q5.default.EventEmitter;Ni.EventEmitter=np,Ni.mixin=GD;function GD(n){for(var t in np.prototype)n.prototype[t]=np.prototype[t]}var fb=["info","warn","error"];function mb(){var n={};fb.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var ZD=mb;mb.prototype.setMethods=function(n){n=n||{};var t=this;fb.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var QD=ZD,YD=new QD,gb=YD;function js(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,js):this.stack=new Error().stack}js.prototype=Object.create(Error.prototype),js.prototype.constructor=js,js.prototype.name="ShareDBError",js.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 Fh=js,ja={},pb=JD;function JD(n,t,e,o){var r=function(s,l,a,d){t(a,s,l,"left"),t(d,l,s,"right")},i=n.transformX=function(s,l){e(s),e(l);for(var a=[],d=0;d<l.length;d++){for(var h=l[d],p=[],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?t([],s[0],l[0],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var Cb={exports:{}},$i=Cb.exports={name:"text0",uri:"http://sharejs.org/types/textv0",create:function(n){if(n!=null&&typeof n!="string")throw new Error("Initial data must be a string");return n||""}},op=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},rp=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")},Ph=function(n){for(var t=0;t<n.length;t++)rp(n[t])};$i.apply=function(n,t){var e;Ph(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=op(n,r.p,r.i);else{if(e=n.slice(r.p,r.p+r.d.length),r.d!==e)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+e+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var Gr=$i._append=function(n,t){if(!(t.i===""||t.d===""))if(n.length===0)n.push(t);else{var e=n[n.length-1];e.i!=null&&t.i!=null&&e.p<=t.p&&t.p<=e.p+e.i.length?n[n.length-1]={i:op(e.i,t.p-e.p,t.i),p:e.p}:e.d!=null&&t.d!=null&&t.p<=e.p&&e.p<=t.p+t.d.length?n[n.length-1]={d:op(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};$i.compose=function(n,t){Ph(n),Ph(t);for(var e=n.slice(),o=0;o<t.length;o++)Gr(e,t[o]);return e},$i.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=0),Gr(t,o)}return t};var ip=function(n,t,e){return t.i!=null?t.p<n||t.p===n&&e?n+t.i.length:n:n<=t.p?n:n<=t.p+t.d.length?t.p:n-t.d.length};$i.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=ip(n,t[r],o);return n};var KD=$i._tc=function(n,t,e,o){if(rp(t),rp(e),t.i!=null)Gr(n,{i:t.i,p:ip(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Gr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Gr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Gr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Gr(n,t);else{var i={d:"",p:t.p};t.p<e.p&&(i.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(i.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),a=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=ip(i.p,e),Gr(n,i))}return n},XD=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};$i.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=XD(n[t]);return n},pb($i,KD,Ph,Gr);var Nh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},tS=function(n){return!!n&&n.constructor===Object},Po=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Zr={};It.registerSubtype=function(n){Zr[n.name]=n},It.create=function(n){return n===void 0?null:Po(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Zr[n.t]&&(t.t=n.t,t.o=Zr[n.t].invert(n.o)),n.si!==void 0&&(t.sd=n.si),n.sd!==void 0&&(t.si=n.sd),n.oi!==void 0&&(t.od=n.oi),n.od!==void 0&&(t.oi=n.od),n.li!==void 0&&(t.ld=n.li),n.ld!==void 0&&(t.li=n.ld),n.na!==void 0&&(t.na=-n.na),n.lm!==void 0&&(t.lm=n.p[n.p.length-1],t.p=n.p.slice(0,n.p.length-1).concat([n.lm])),t},It.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(It.invertComponent(t[o]));return e},It.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Nh(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!Nh(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!tS(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Ua(n){n.t="text0";var t={p:n.p.pop()};n.si!=null&&(t.i=n.si),n.sd!=null&&(t.d=n.sd),n.o=[t]}function 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}It.apply=function(n,t){It.checkValidOp(t),t=Po(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&Ua(r);for(var i=null,s=e,l="data",a=0;a<r.p.length;a++){var d=r.p[a];if(i=s,s=s[l],l=d,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Zr[r.t])s[l]=Zr[r.t].apply(s[l],r.o);else if(r.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=r.na}else if(r.li!==void 0&&r.ld!==void 0)It.checkList(s),s[l]=r.li;else if(r.li!==void 0)It.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)It.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(It.checkList(s),r.lm!=l){var h=s[l];s.splice(l,1),s.splice(r.lm,0,h)}}else if(r.oi!==void 0)It.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)It.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},It.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},It.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=It.apply(n,r),e(r,n)}return n};var eS=It.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==t[o]&&(!e||o!==n.length-1))return!1;return!0};It.append=function(n,t){if(t=Po(t),n.length===0){n.push(t);return}var e=n[n.length-1];if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Ua(t),Ua(e)),eS(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Zr[t.t]){if(e.o=Zr[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var o=t.p,r=0;r<e.o.length-1;r++)t.o=[e.o.pop()],t.p=o.slice(),za(t),n.push(t);za(e)}}else e.na!=null&&t.na!=null?n[n.length-1]={p:e.p,na:e.na+t.na}:e.li!==void 0&&t.li===void 0&&t.ld===e.li?e.ld!==void 0?delete e.li:n.pop():e.od!==void 0&&e.oi===void 0&&t.oi!==void 0&&t.od===void 0?e.oi=t.oi:e.oi!==void 0&&t.od!==void 0?t.oi!==void 0?e.oi=t.oi:e.od!==void 0?delete e.oi:n.pop():t.lm!==void 0&&t.p[t.p.length-1]===t.lm||n.push(t);else(t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(za(t),za(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=Po(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=Nh(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),It.append(t,o)}return t},It.commonLengthForOps=function(n,t){var e=n.p.length,o=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&o++,e===0)return-1;if(o===0)return null;e--,o--;for(var r=0;r<e;r++){var i=n.p[r];if(r>=o||i!==t.p[r])return null}return e},It.canOpAffectPath=function(n,t){return It.commonLengthForOps({p:t},n)!=null},It.transformComponent=function(n,t,e,o){t=Po(t);var r=It.commonLengthForOps(e,t),i=It.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,i!=null&&l>s&&t.p[i]==e.p[i]){if(t.ld!==void 0){var a=Po(e);a.p=a.p.slice(s),t.ld=It.apply(Po(t.ld),[a])}else if(t.od!==void 0){var a=Po(e);a.p=a.p.slice(s),t.od=It.apply(Po(t.od),[a])}}if(r!=null){var d=s==l,a=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Ua(t),a=Po(e),Ua(a)),a.t&&Zr[a.t]){if(t.t&&t.t===a.t){var h=Zr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,A=0;A<h.length;A++)t.o=[h[A]],t.p=p.slice(),za(t),It.append(n,t);else(!Nh(h)||h.length>0)&&(t.o=h,It.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[r]===t.p[r])if(d){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=Po(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&d&&t.p[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&d&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[r]===t.p[r])return n;var p=e.p[r],v=t.p[r],B=t.lm;(p<B||p===B&&v<B)&&t.lm--}if(e.p[r]<t.p[r])t.p[r]--;else if(e.p[r]===t.p[r]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var v=t.p[r],B=t.lm,D=e.p[r],x=e.lm;if(D!==x)if(v===D)if(o==="left")t.p[r]=x,v===B&&(t.lm=x);else return n;else v>D&&t.p[r]--,v>x?t.p[r]++:v===x&&D>x&&(t.p[r]++,v===B&&t.lm++),(B>D||B===D&&B>v)&&t.lm--,B>x?t.lm++:B===x&&(x>D&&B>v||x<D&&B<v?o==="right"&&t.lm++:B>v?t.lm++:B===D&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var v=e.p[r],B=e.lm;p=t.p[r],p>v&&t.p[r]--,p>B&&t.p[r]++}else{var v=e.p[r],B=e.lm;p=t.p[r],p===v?t.p[r]=B:(p>v&&t.p[r]--,(p>B||p===B&&v>B)&&t.p[r]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[r]===e.p[r])if(t.oi!==void 0&&d){if(o==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[r]===e.p[r])if(o==="left")It.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return It.append(n,t),n},pb(It,It.transformComponent,It.checkValidOp,It.append);var nS=Cb.exports;It.registerSubtype(nS);var oS=It,rS={type:oS};(function(n){n.defaultType=rS.type,n.map={},n.register=function(t){t.name&&(n.map[t.name]=t),t.uri&&(n.map[t.uri]=t)},n.register(n.defaultType)})(ja);var No={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var o in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];e=e[r]||(o===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];e=e[i]||(e[i]=r===arguments.length-2?o():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],o=[e],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!e.hasOwnProperty(i))break;e=e[i],o.push(e)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,o){var r=!1;return e.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){e.apply(null,o)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(No);var Ab=Array.isArray,bb=Object.keys,iS=Object.prototype.hasOwnProperty,sS=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=Ab(t),r=Ab(e),i,s,l;if(o&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!n(t[i],e[i]))return!1;return!0}if(o!=r)return!1;var a=t instanceof Date,d=e instanceof Date;if(a!=d)return!1;if(a&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,p=e instanceof RegExp;if(h!=p)return!1;if(h&&p)return t.toString()==e.toString();var A=bb(t);if(s=A.length,s!==bb(e).length)return!1;for(i=s;i--!==0;)if(!iS.call(e,A[i]))return!1;for(i=s;i--!==0;)if(l=A[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},vb=Ni,lS=gb,qn=Fh,$h=ja,$o=No,cS=$o.clone,aS=sS,Tn=qn.CODES,uS=Ft;function Ft(n,t,e){vb.EventEmitter.call(this),this.connection=n,this.collection=t,this.id=e,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}vb.mixin(Ft),Ft.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this;t.whenNothingPending(function(){t.wantSubscribe?t.unsubscribe(function(e){if(e)return n?n(e):t.emit("error",e);t.connection._destroyDoc(t),n&&n()}):(t.connection._destroyDoc(t),n&&n())})},Ft.prototype._setType=function(n){if(typeof n=="string"&&(n=$h.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new qn(Tn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Ft.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Ft.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new qn(Tn.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return t&&this.once("no write pending",t);var e=new qn(Tn.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var o=n.type===void 0?$h.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},Ft.prototype.whenNothingPending=function(n){var t=this;$o.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Ft.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Ft.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Ft.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Ft.prototype._emitResponseError=function(n,t){if(n&&n.code===Tn.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,t&&t(),this._emitNothingPending();return}if(t){t(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},Ft.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&e.push(o),e.length&&(o=function(r){$o.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],e.callback&&o.push(e.callback);var r;if(o.length&&(r=function(i){$o.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Tn.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq){this._opAcknowledged(t);return}if(this.version==null||t.v>this.version){this.fetch();return}if(!(t.v<this.version)){if(this.inflightOp){var e=Hh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Hh(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},Ft.prototype._onConnectionStateChanged=function(){this.connection.canSend?(this.flush(),this._resubscribe()):(this.inflightOp&&(this.pendingOps.unshift(this.inflightOp),this.inflightOp=null),this.subscribed=!1,this.inflightSubscribe&&(this.inflightSubscribe.wantSubscribe?(this.pendingSubscribe.unshift(this.inflightSubscribe),this.inflightSubscribe=null):this._handleSubscribe()),this.inflightFetch.length&&(this.pendingFetch=this.pendingFetch.concat(this.inflightFetch),this.inflightFetch.length=0))},Ft.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(t){return t.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},Ft.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);dS(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Ft.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Ft.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Ft.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=hS([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Ft.prototype._flushSubscribe=function(){if(!(this.inflightSubscribe||!this.pendingSubscribe.length)){if(this.connection.canSend){this.inflightSubscribe=this.pendingSubscribe.shift(),this.wantSubscribe=this.inflightSubscribe.wantSubscribe,this.wantSubscribe?this.connection.sendSubscribe(this):(this.subscribed=!1,this.connection.sendUnsubscribe(this));return}if(!this.pendingSubscribe[0].wantSubscribe){this.inflightSubscribe=this.pendingSubscribe.shift();var n=this;$o.nextTick(function(){n._handleSubscribe()})}}};function dS(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function hS(n){return n=n.filter($o.truthy),n.length?function(t){$o.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function fS(n){delete n.op,delete n.create,delete n.del}function Hh(n,t){if(n.del)return fS(t);if(t.del)return new qn(Tn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new qn(Tn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new qn(Tn.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var o=n.type.transform(n.op,t.op,"left"),r=n.type.transform(t.op,n.op,"right");n.op=o,t.op=r}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new qn(Tn.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,t),!t&&this.type===$h.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Hh(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",t);return}if(n.del){var a=this.data;this._setType(null),this.emit("del",a,t);return}},Ft.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var t=this.inflightOp;if(!t){var e=new qn(Tn.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",e)}if(t.sentAt=Date.now(),t.retries=t.retries==null?0:t.retries+1,t.seq==null){if(this.connection.seq>=$o.MAX_SAFE_INTEGER)return this.emit("error",new qn(Tn.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));t.seq=this.connection.seq++}this.connection.sendOp(this,t),t.src==null&&(t.src=n)}},Ft.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new qn(Tn.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(i){return this._hardRollback(i)}var r=this;$o.nextTick(function(){r.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},Ft.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var o=this.pendingOps.splice(e),e=0;e<o.length;e++){var t=o[e],r=this._tryCompose(t);r?r.callbacks=r.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},Ft.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!aS(n.source,t.source))){if(t.create&&"op"in n)return t.create.data=this.type.apply(t.create.data,n.op),t;if("op"in t&&"op"in n&&this.type.compose)return t.op=this.type.compose(t.op,n.op),t}}},Ft.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var o={op:n},r=t&&t.source;this._submit(o,r,e)},Ft.prototype.create=function(n,t,e,o){if(typeof t=="function"?(o=t,e=null,t=null):typeof e=="function"&&(o=e,e=null),t||(t=$h.defaultType.uri),this.type){var r=new qn(Tn.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:t,data:n}},s=e&&e.source;this._submit(i,s,o)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new qn(Tn.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var o={del:!0},r=n&&n.source;this._submit(o,r,t)},Ft.prototype.pause=function(){this.paused=!0},Ft.prototype.resume=function(){this.paused=!1,this.flush()},Ft.prototype.toSnapshot=function(){return{v:this.version,data:cS(this.data),type:this.type.uri}},Ft.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return lS.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Ft.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var o=Hh(this.pendingOps[e],t);if(o)return this._hardRollback(o)}try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},Ft.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var o=!!t.length,r=0;r<t.length;r++)o=$o.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=$o.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Us={};Us.ACTIONS={initLegacy:"init",handshake:"hs",queryFetch:"qf",querySubscribe:"qs",queryUnsubscribe:"qu",queryUpdate:"q",bulkFetch:"bf",bulkSubscribe:"bs",bulkUnsubscribe:"bu",fetch:"f",subscribe:"s",unsubscribe:"u",op:"op",snapshotFetch:"nf",snapshotFetchByTimestamp:"nt",pingPong:"pp",presence:"p",presenceSubscribe:"ps",presenceUnsubscribe:"pu",presenceRequest:"pr"};var yb=Ni,kb=Us.ACTIONS,mS=No,gS=Dn;function Dn(n,t,e,o,r,i,s){yb.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}yb.mixin(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 t=[],e=0;e<this.results.length;e++){var o=this.results[e];t.push([o.id,o.version])}n.r=t}this.connection.send(n),this.sent=!0}},Dn.prototype.destroy=function(n){this.connection.canSend&&this.action===kb.querySubscribe&&this.connection.send({a:kb.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&mS.nextTick(n)},Dn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Dn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Dn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Dn.prototype._handleResponse=function(n,t,e){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!t)return this._finishResponse(null,o);var r=this,i=1,s=function(h){if(h)return r._finishResponse(h,o);--i||r._finishResponse(null,o)};if(Array.isArray(t))i+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){i++;var a=t[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Dn.prototype._ingestSnapshots=function(n,t){for(var e=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,t),e.push(i)}return e},Dn.prototype._finishResponse=function(n,t){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),t?t(n):this.emit("error",n);t&&t(null,this.results,this.extra)},Dn.prototype._handleError=function(n){this.emit("error",n)},Dn.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var o=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(o)),this.emit("insert",o,e.index);break;case"remove":var i=e.howMany||1,r=this.results.splice(e.index,i);this.emit("remove",r,e.index);break;case"move":var i=e.howMany||1,s=this.results.splice(e.from,i);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},Dn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var wb=Ni,pS=Us.ACTIONS,CS=No,Bb=ur;function ur(n,t){if(wb.EventEmitter.call(this),!t||typeof t!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=t,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}wb.mixin(ur),ur.prototype.submit=function(n,t){this.value=n,this.send(t)},ur.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},ur.prototype.destroy=function(n){var t=this;this.submit(null,function(e){if(e)return t._callbackOrEmit(e,n);delete t.presence.localPresences[t.presenceId],n&&n()})},ur.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},ur.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},ur.prototype._message=function(){return{a:pS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},ur.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},ur.prototype._callbackOrEmit=function(n,t){if(t)return CS.nextTick(t,n);n&&this.emit("error",n)};var AS=No,Eb=sp;function sp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}sp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},sp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&AS.nextTick(n)};var lp={exports:{}};(function(n,t){(function(e,o){o(t)})(ar,function(e){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 H(k){return function(T){var L=o(arguments,1),F=i(function(U,j){var Z=this;return k(T,function(J,lt){M(J).apply(Z,U.concat(lt))},j)});return L.length?F.apply(this,L):F}}var z=typeof ar=="object"&&ar&&ar.Object===Object&&ar,q=typeof self=="object"&&self&&self.Object===Object&&self,rt=z||q||Function("return this")(),ft=rt.Symbol,Bt=Object.prototype,jt=Bt.hasOwnProperty,Ut=Bt.toString,ee=ft?ft.toStringTag:void 0;function qe(k){var T=jt.call(k,ee),L=k[ee];try{k[ee]=void 0;var F=!0}catch{}var U=Ut.call(k);return F&&(T?k[ee]=L:delete k[ee]),U}var Yn=Object.prototype,$e=Yn.toString;function Mn(k){return $e.call(k)}var yr="[object Null]",bn="[object Undefined]",an=ft?ft.toStringTag:void 0;function kr(k){return k==null?k===void 0?bn:yr:an&&an in Object(k)?qe(k):Mn(k)}var oi="[object AsyncFunction]",po="[object Function]",K2="[object GeneratorFunction]",X2="[object Proxy]";function t3(k){if(!s(k))return!1;var T=kr(k);return T==po||T==K2||T==oi||T==X2}var es=9007199254740991;function nl(k){return typeof k=="number"&&k>-1&&k%1==0&&k<=es}function ol(k){return k!=null&&nl(k.length)&&!t3(k)}var ri={};function Nt(){}function wr(k){return function(){if(k!==null){var T=k;k=null,T.apply(this,arguments)}}}var ns=typeof Symbol=="function"&&Symbol.iterator,Fc=function(k){return ns&&k[ns]&&k[ns]()};function i1(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 rl="[object Arguments]";function s1(k){return un(k)&&kr(k)==rl}var Co=Object.prototype,l1=Co.hasOwnProperty,e3=Co.propertyIsEnumerable,il=s1(function(){return arguments}())?s1:function(k){return un(k)&&l1.call(k,"callee")&&!e3.call(k,"callee")},Ae=Array.isArray;function sl(){return!1}var ll=typeof e=="object"&&e&&!e.nodeType&&e,c1=ll&&!0&&n&&!n.nodeType&&n,cl=c1&&c1.exports===ll,a1=cl?rt.Buffer:void 0,al=a1?a1.isBuffer:void 0,os=al||sl,$u=9007199254740991,Hu=/^(?:0|[1-9]\d*)$/;function ju(k,T){var L=typeof k;return T=T==null?$u:T,!!T&&(L=="number"||L!="symbol"&&Hu.test(k))&&k>-1&&k%1==0&&k<T}var Uu="[object Arguments]",zu="[object Array]",Vu="[object Boolean]",Wu="[object Date]",qu="[object Error]",Gu="[object Function]",n3="[object Map]",o3="[object Number]",r3="[object Object]",u1="[object RegExp]",d1="[object Set]",i3="[object String]",s3="[object WeakMap]",l3="[object ArrayBuffer]",c3="[object DataView]",h1="[object Float32Array]",a3="[object Float64Array]",u3="[object Int8Array]",d3="[object Int16Array]",Zu="[object Int32Array]",h3="[object Uint8Array]",Qu="[object Uint8ClampedArray]",f3="[object Uint16Array]",m3="[object Uint32Array]",se={};se[h1]=se[a3]=se[u3]=se[d3]=se[Zu]=se[h3]=se[Qu]=se[f3]=se[m3]=!0,se[Uu]=se[zu]=se[l3]=se[Vu]=se[c3]=se[Wu]=se[qu]=se[Gu]=se[n3]=se[o3]=se[r3]=se[u1]=se[d1]=se[i3]=se[s3]=!1;function g3(k){return un(k)&&nl(k.length)&&!!se[kr(k)]}function p3(k){return function(T){return k(T)}}var f1=typeof e=="object"&&e&&!e.nodeType&&e,ul=f1&&!0&&n&&!n.nodeType&&n,C3=ul&&ul.exports===f1,Pc=C3&&z.process,m1=function(){try{var k=ul&&ul.require&&ul.require("util").types;return k||Pc&&Pc.binding&&Pc.binding("util")}catch{}}(),g1=m1&&m1.isTypedArray,A3=g1?p3(g1):g3,b3=Object.prototype,v3=b3.hasOwnProperty;function y3(k,T){var L=Ae(k),F=!L&&il(k),U=!L&&!F&&os(k),j=!L&&!F&&!U&&A3(k),Z=L||F||U||j,J=Z?i1(k.length,String):[],lt=J.length;for(var pt in k)(T||v3.call(k,pt))&&!(Z&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||ju(pt,lt)))&&J.push(pt);return J}var Nc=Object.prototype;function k3(k){var T=k&&k.constructor,L=typeof T=="function"&&T.prototype||Nc;return k===L}function $c(k,T){return function(L){return k(T(L))}}var w3=$c(Object.keys,Object),B3=Object.prototype,E3=B3.hasOwnProperty;function p1(k){if(!k3(k))return w3(k);var T=[];for(var L in Object(k))E3.call(k,L)&&L!="constructor"&&T.push(L);return T}function Hc(k){return ol(k)?y3(k):p1(k)}function C1(k){var T=-1,L=k.length;return function(){return++T<L?{value:k[T],key:T}:null}}function x3(k){var T=-1;return function(){var F=k.next();return F.done?null:(T++,{value:F.value,key:T})}}function I3(k){var T=Hc(k),L=-1,F=T.length;return function U(){var j=T[++L];return j==="__proto__"?U():L<F?{value:k[j],key:j}:null}}function T3(k){if(ol(k))return C1(k);var T=Fc(k);return T?x3(T):I3(k)}function Ao(k){return function(){if(k===null)throw new Error("Callback was already called.");var T=k;k=null,T.apply(this,arguments)}}function dl(k){return function(T,L,F){if(F=wr(F||Nt),k<=0||!T)return F(null);var U=T3(T),j=!1,Z=0,J=!1;function lt(ct,At){if(Z-=1,ct)j=!0,F(ct);else{if(At===ri||j&&Z<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;Z<k&&!j;){var ct=U();if(ct===null){j=!0,Z<=0&&F(null);return}Z+=1,L(ct.value,ct.key,Ao(lt))}J=!1}pt()}}function Br(k,T,L,F){dl(T)(k,M(L),F)}function He(k,T){return function(L,F,U){return k(L,T,F,U)}}function Yu(k,T,L){L=wr(L||Nt);var F=0,U=0,j=k.length;j===0&&L(null);function Z(J,lt){J?L(J):(++U===j||lt===ri)&&L(null)}for(;F<j;F++)T(k[F],F,Ao(Z))}var D3=He(Br,1/0),Go=function(k,T,L){var F=ol(k)?Yu:D3;F(k,M(T),L)};function Zo(k){return function(T,L,F){return k(Go,T,M(L),F)}}function Ju(k,T,L,F){F=F||Nt,T=T||[];var U=[],j=0,Z=M(L);k(T,function(J,lt,pt){var ct=j++;Z(J,function(At,Gt){U[ct]=Gt,pt(At)})},function(J){F(J,U)})}var jc=Zo(Ju),Ku=H(jc);function ii(k){return function(T,L,F,U){return k(dl(L),T,M(F),U)}}var Er=ii(Ju),Xu=He(Er,1),td=H(Xu);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,j=Object(T),Z=F(T),J=Z.length;J--;){var lt=Z[k?J:++U];if(L(j[lt],lt,j)===!1)break}return T}}var is=ed();function ss(k,T){return k&&is(k,T,Hc)}function A1(k,T,L,F){for(var U=k.length,j=L+(F?1:-1);F?j--:++j<U;)if(T(k[j],j,k))return j;return-1}function S3(k){return k!==k}function b1(k,T,L){for(var F=L-1,U=k.length;++F<U;)if(k[F]===T)return F;return-1}function hl(k,T,L){return T===T?b1(k,T,L):A1(k,S3,L)}var Uc=function(k,T,L){typeof T=="function"&&(L=T,T=null),L=wr(L||Nt);var F=Hc(k),U=F.length;if(!U)return L(null);T||(T=U);var j={},Z=0,J=!1,lt=Object.create(null),pt=[],ct=[],At={};ss(k,function(de,oe){if(!Ae(de)){Gt(oe,[de]),ct.push(oe);return}var ge=de.slice(0,de.length-1),vo=ge.length;if(vo===0){Gt(oe,de),ct.push(oe);return}At[oe]=vo,rs(ge,function(E){if(!k[E])throw new Error("async.auto task `"+oe+"` has a non-existent dependency `"+E+"` in "+ge.join(", "));en(E,function(){vo--,vo===0&&Gt(oe,de)})})}),K3(),Ie();function Gt(de,oe){pt.push(function(){bo(de,oe)})}function Ie(){if(pt.length===0&&Z===0)return L(null,j);for(;pt.length&&Z<T;){var de=pt.shift();de()}}function en(de,oe){var ge=lt[de];ge||(ge=lt[de]=[]),ge.push(oe)}function _n(de){var oe=lt[de]||[];rs(oe,function(ge){ge()}),Ie()}function bo(de,oe){if(!J){var ge=Ao(function(E,Tr){if(Z--,arguments.length>2&&(Tr=o(arguments,1)),E){var us={};ss(j,function(Fn,Pt){us[Pt]=Fn}),us[de]=Tr,J=!0,lt=Object.create(null),L(E,us)}else j[de]=Tr,_n(de)});Z++;var vo=M(oe[oe.length-1]);oe.length>1?vo(j,ge):vo(ge)}}function K3(){for(var de,oe=0;ct.length;)de=ct.pop(),oe++,rs(X3(de),function(ge){--At[ge]===0&&ct.push(ge)});if(oe!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function X3(de){var oe=[];return ss(k,function(ge,vo){Ae(ge)&&hl(ge,de,0)>=0&&oe.push(vo)}),oe}};function si(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 L3="[object Symbol]";function M3(k){return typeof k=="symbol"||un(k)&&kr(k)==L3}var R3=1/0,nd=ft?ft.prototype:void 0,v1=nd?nd.toString:void 0;function od(k){if(typeof k=="string")return k;if(Ae(k))return si(k,od)+"";if(M3(k))return v1?v1.call(k):"";var T=k+"";return T=="0"&&1/k==-R3?"-0":T}function O3(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 j=Array(U);++F<U;)j[F]=k[F+T];return j}function _3(k,T,L){var F=k.length;return L=L===void 0?F:L,!T&&L>=F?k:O3(k,T,L)}function rd(k,T){for(var L=k.length;L--&&hl(T,k[L],0)>-1;);return L}function F3(k,T){for(var L=-1,F=k.length;++L<F&&hl(T,k[L],0)>-1;);return L}function P3(k){return k.split("")}var N3="\\ud800-\\udfff",$3="\\u0300-\\u036f",H3="\\ufe20-\\ufe2f",le="\\u20d0-\\u20ff",ne=$3+H3+le,j3="\\ufe0e\\ufe0f",U3="\\u200d",z3=RegExp("["+U3+N3+ne+j3+"]");function V3(k){return z3.test(k)}var y1="\\ud800-\\udfff",W3="\\u0300-\\u036f",k1="\\ufe20-\\ufe2f",q3="\\u20d0-\\u20ff",Ge=W3+k1+q3,id="\\ufe0e\\ufe0f",li="["+y1+"]",zc="["+Ge+"]",fl="\\ud83c[\\udffb-\\udfff]",Rn="(?:"+zc+"|"+fl+")",sd="[^"+y1+"]",ld="(?:\\ud83c[\\udde6-\\uddff]){2}",cd="[\\ud800-\\udbff][\\udc00-\\udfff]",w1="\\u200d",ad=Rn+"?",ud="["+id+"]?",vn="(?:"+w1+"(?:"+[sd,ld,cd].join("|")+")"+ud+ad+")*",G3=ud+ad+vn,On="(?:"+[sd+zc+"?",zc,ld,cd,li].join("|")+")",Z3=RegExp(fl+"(?="+fl+")|"+On+G3,"g");function B1(k){return k.match(Z3)||[]}function Qo(k){return V3(k)?B1(k):P3(k)}function Vc(k){return k==null?"":od(k)}var dd=/^\s+|\s+$/g;function ue(k,T,L){if(k=Vc(k),k&&(L||T===void 0))return k.replace(dd,"");if(!k||!(T=od(T)))return k;var F=Qo(k),U=Qo(T),j=F3(F,U),Z=rd(F,U)+1;return _3(F,j,Z).join("")}var xr=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,hd=/,/,Q3=/(=.+)?(\s*)$/,fd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function Y3(k){return k=k.toString().replace(fd,""),k=k.match(xr)[2].replace(" ",""),k=k?k.split(hd):[],k=k.map(function(T){return ue(T.replace(Q3,""))}),k}function E1(k,T){var L={};ss(k,function(F,U){var j,Z=_(F),J=!Z&&F.length===1||Z&&F.length===0;if(Ae(F))j=F.slice(0,-1),F=F[F.length-1],L[U]=j.concat(j.length>0?lt:F);else if(J)L[U]=F;else{if(j=Y3(F),F.length===0&&!Z&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");Z||j.pop(),L[U]=j.concat(lt)}function lt(pt,ct){var At=si(j,function(Gt){return pt[Gt]});At.push(ct),M(F).apply(null,At)}}),Uc(L,T)}function Jn(){this.head=this.tail=null,this.length=0}function md(k,T){k.length=1,k.head=k.tail=T}Jn.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},Jn.prototype.empty=function(){for(;this.head;)this.shift();return this},Jn.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},Jn.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},Jn.prototype.unshift=function(k){this.head?this.insertBefore(this.head,k):md(this,k)},Jn.prototype.push=function(k){this.tail?this.insertAfter(this.tail,k):md(this,k)},Jn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Jn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Jn.prototype.toArray=function(){for(var k=Array(this.length),T=this.head,L=0;L<this.length;L++)k[L]=T.data,T=T.next;return k},Jn.prototype.remove=function(k){for(var T=this.head;T;){var L=T.next;k(T)&&this.removeLink(T),T=L}return this};function ml(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,j=[],Z=!1;function J(At,Gt,Ie){if(Ie!=null&&typeof Ie!="function")throw new Error("task callback must be a function");if(ct.started=!0,Ae(At)||(At=[At]),At.length===0&&ct.idle())return A(function(){ct.drain()});for(var en=0,_n=At.length;en<_n;en++){var bo={data:At[en],callback:Ie||Nt};Gt?ct._tasks.unshift(bo):ct._tasks.push(bo)}Z||(Z=!0,A(function(){Z=!1,ct.process()}))}function lt(At){return function(Gt){U-=1;for(var Ie=0,en=At.length;Ie<en;Ie++){var _n=At[Ie],bo=hl(j,_n,0);bo===0?j.shift():bo>0&&j.splice(bo,1),_n.callback.apply(_n,arguments),Gt!=null&&ct.error(Gt,_n.data)}U<=ct.concurrency-ct.buffer&&ct.unsaturated(),ct.idle()&&ct.drain(),ct.process()}}var pt=!1,ct={_tasks:new Jn,concurrency:T,payload:L,saturated:Nt,unsaturated:Nt,buffer:T/4,empty:Nt,drain:Nt,error:Nt,started:!1,paused:!1,push:function(At,Gt){J(At,!1,Gt)},kill:function(){ct.drain=Nt,ct._tasks.empty()},unshift:function(At,Gt){J(At,!0,Gt)},remove:function(At){ct._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!ct.paused&&U<ct.concurrency&&ct._tasks.length;){var At=[],Gt=[],Ie=ct._tasks.length;ct.payload&&(Ie=Math.min(Ie,ct.payload));for(var en=0;en<Ie;en++){var _n=ct._tasks.shift();At.push(_n),j.push(_n),Gt.push(_n.data)}U+=1,ct._tasks.length===0&&ct.empty(),U===ct.concurrency&&ct.saturated();var bo=Ao(lt(At));F(Gt,bo)}pt=!1}},length:function(){return ct._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return ct._tasks.length+U===0},pause:function(){ct.paused=!0},resume:function(){ct.paused!==!1&&(ct.paused=!1,A(ct.process))}};return ct}function ci(k,T){return ml(k,1,T)}var ls=He(Br,1);function Yo(k,T,L,F){F=wr(F||Nt);var U=M(L);ls(k,function(j,Z,J){U(T,j,function(lt,pt){T=pt,J(lt)})},function(j){F(j,T)})}function Wc(){var k=si(arguments,M);return function(){var T=o(arguments),L=this,F=T[T.length-1];typeof F=="function"?T.pop():F=Nt,Yo(k,T,function(U,j,Z){j.apply(L,U.concat(function(J){var lt=o(arguments,1);Z(J,lt)}))},function(U,j){F.apply(L,[U].concat(j))})}}var qc=function(){return Wc.apply(null,o(arguments).reverse())},gd=Array.prototype.concat,gl=function(k,T,L,F){F=F||Nt;var U=M(L);Er(k,T,function(j,Z){U(j,function(J){return J?Z(J):Z(null,o(arguments,1))})},function(j,Z){for(var J=[],lt=0;lt<Z.length;lt++)Z[lt]&&(J=gd.apply(J,Z[lt]));return F(j,J)})},x1=He(gl,1/0),Gc=He(gl,1),Zc=function(){var k=o(arguments),T=[null].concat(k);return function(){var L=arguments[arguments.length-1];return L.apply(this,T)}};function pl(k){return k}function ai(k,T){return function(L,F,U,j){j=j||Nt;var Z=!1,J;L(F,function(lt,pt,ct){U(lt,function(At,Gt){At?ct(At):k(Gt)&&!J?(Z=!0,J=T(!0,lt),ct(null,ri)):ct()})},function(lt){lt?j(lt):j(null,Z?J:T(!1))})}}function dn(k,T){return T}var cs=Zo(ai(pl,dn)),Jo=ii(ai(pl,dn)),Cl=He(Jo,1);function pd(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(j){console[k](j)}))}),M(T).apply(null,L)}}var I1=pd("dir");function T1(k,T,L){L=Ao(L||Nt);var F=M(k),U=M(T);function j(J){if(J)return L(J);var lt=o(arguments,1);lt.push(Z),U.apply(this,lt)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}Z(null,!0)}function Cd(k,T,L){L=Ao(L||Nt);var F=M(k),U=function(j){if(j)return L(j);var Z=o(arguments,1);if(T.apply(this,Z))return F(U);L.apply(null,[null].concat(Z))};F(U)}function D1(k,T,L){Cd(k,function(){return!T.apply(this,arguments)},L)}function S1(k,T,L){L=Ao(L||Nt);var F=M(T),U=M(k);function j(J){if(J)return L(J);U(Z)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}U(Z)}function ui(k){return function(T,L,F){return k(T,F)}}function Qc(k,T,L){Go(k,ui(M(T)),L)}function Al(k,T,L,F){dl(T)(k,ui(M(L)),F)}var di=He(Al,1);function Yc(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 Kn(k){return!k}var hi=Zo(ai(Kn,Kn)),bl=ii(ai(Kn,Kn)),Jc=He(bl,1);function L1(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(j,Z,J){L(j,function(lt,pt){U[Z]=!!pt,J(lt)})},function(j){if(j)return F(j);for(var Z=[],J=0;J<T.length;J++)U[J]&&Z.push(T[J]);F(null,Z)})}function Xn(k,T,L,F){var U=[];k(T,function(j,Z,J){L(j,function(lt,pt){lt?J(lt):(pt&&U.push({index:Z,value:j}),J())})},function(j){j?F(j):F(null,si(U.sort(function(Z,J){return Z.index-J.index}),L1("value")))})}function Kc(k,T,L,F){var U=ol(T)?as:Xn;U(k,T,M(L),F||Nt)}var Xc=Zo(Kc),vl=ii(Kc),ta=He(vl,1);function M1(k,T){var L=Ao(T||Nt),F=M(Yc(k));function U(j){if(j)return L(j);F(U)}U()}var ea=function(k,T,L,F){F=F||Nt;var U=M(L);Er(k,T,function(j,Z){U(j,function(J,lt){return J?Z(J):Z(null,{key:lt,val:j})})},function(j,Z){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<Z.length;pt++)if(Z[pt]){var ct=Z[pt].key,At=Z[pt].val;lt.call(J,ct)?J[ct].push(At):J[ct]=[At]}return F(j,J)})},fi=He(ea,1/0),N=He(ea,1),G=pd("log");function V(k,T,L,F){F=wr(F||Nt);var U={},j=M(L);Br(k,T,function(Z,J,lt){j(Z,J,function(pt,ct){if(pt)return lt(pt);U[J]=ct,lt()})},function(Z){F(Z,U)})}var ht=He(V,1/0),Et=He(V,1);function Vt(k,T){return T in k}function we(k,T){var L=Object.create(null),F=Object.create(null);T=T||pl;var U=M(k),j=i(function(J,lt){var pt=T.apply(null,J);Vt(L,pt)?A(function(){lt.apply(null,L[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var ct=o(arguments);L[pt]=ct;var At=F[pt];delete F[pt];for(var Gt=0,Ie=At.length;Gt<Ie;Gt++)At[Gt].apply(null,ct)})))});return j.memo=L,j.unmemoized=k,j}var qt;a?qt=process.nextTick:l?qt=setImmediate:qt=d;var na=h(qt);function Ad(k,T,L){L=L||Nt;var F=ol(T)?[]:{};k(T,function(U,j,Z){M(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,Z(J)})},function(U){L(U,F)})}function yn(k,T){Ad(Go,k,T)}function yl(k,T,L){Ad(dl(T),k,L)}var bd=function(k,T){var L=M(k);return ml(function(F,U){L(F[0],U)},T,1)},mi=function(k,T){var L=bd(k,T);return L.push=function(F,U,j){if(j==null&&(j=Nt),typeof j!="function")throw new Error("task callback must be a function");if(L.started=!0,Ae(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,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};Z?L._tasks.insertBefore(Z,pt):L._tasks.push(pt)}A(L.process)},delete L.unshift,L};function kl(k,T){if(T=wr(T||Nt),!Ae(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 gi(k,T,L,F){var U=o(k).reverse();Yo(U,T,L,F)}function Wt(k){var T=M(k);return i(function(F,U){return F.push(function(Z,J){if(Z)U(null,{error:Z});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),T.apply(this,F)})}function R1(k){var T;return Ae(k)?T=si(k,Wt):(T={},ss(k,function(L,F){T[F]=Wt.call(this,L)})),T}function vd(k,T,L,F){Kc(k,T,function(U,j){L(U,function(Z,J){j(Z,!J)})},F)}var wl=Zo(vd),yd=ii(vd),O1=He(yd,1);function _1(k){return function(){return k}}function pi(k,T,L){var F=5,U=0,j={times:F,intervalFunc:_1(U)};function Z(ct,At){if(typeof At=="object")ct.times=+At.times||F,ct.intervalFunc=typeof At.interval=="function"?At.interval:_1(+At.interval||U),ct.errorFilter=At.errorFilter;else if(typeof At=="number"||typeof At=="string")ct.times=+At||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof k=="function"?(L=T||Nt,T=k):(Z(j,k),L=L||Nt),typeof T!="function")throw new Error("Invalid arguments for async.retry");var J=M(T),lt=1;function pt(){J(function(ct){ct&<++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(ct))?setTimeout(pt,j.intervalFunc(lt)):L.apply(null,arguments)})}pt()}var Ko=function(k,T){T||(T=k,k=null);var L=M(T);return i(function(F,U){function j(Z){L.apply(null,F.concat(Z))}k?pi(k,j,U):pi(j,U)})};function Bl(k,T){Ad(ls,k,T)}var El=Zo(ai(Boolean,pl)),Ir=ii(ai(Boolean,pl)),xl=He(Ir,1);function kd(k,T,L){var F=M(T);jc(k,function(j,Z){F(j,function(J,lt){if(J)return Z(J);Z(null,{value:j,criteria:lt})})},function(j,Z){if(j)return L(j);L(null,si(Z.sort(U),L1("value")))});function U(j,Z){var J=j.criteria,lt=Z.criteria;return J<lt?-1:J>lt?1:0}}function Il(k,T,L){var F=M(k);return i(function(U,j){var Z=!1,J;function lt(){var pt=k.name||"anonymous",ct=new Error('Callback function "'+pt+'" timed out.');ct.code="ETIMEDOUT",L&&(ct.info=L),Z=!0,j(ct)}U.push(function(){Z||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,T),F.apply(null,U)})}var F1=Math.ceil,Tl=Math.max;function Ci(k,T,L,F){for(var U=-1,j=Tl(F1((T-k)/(L||1)),0),Z=Array(j);j--;)Z[F?j:++U]=k,k+=L;return Z}function Ai(k,T,L,F){var U=M(L);Er(Ci(0,k,1),T,U,F)}var P1=He(Ai,1/0),N1=He(Ai,1);function $1(k,T,L,F){arguments.length<=3&&(F=L,L=T,T=Ae(k)?[]:{}),F=wr(F||Nt);var U=M(L);Go(k,function(j,Z,J){U(T,j,Z,J)},function(j){F(j,T)})}function Dl(k,T){var L=null,F;T=T||Nt,di(k,function(U,j){M(U)(function(Z,J){arguments.length>2?F=o(arguments,1):F=J,L=Z,j(!Z)})},function(){T(L,F)})}function Sl(k){return function(){return(k.unmemoized||k).apply(null,arguments)}}function Ll(k,T,L){L=Ao(L||Nt);var F=M(T);if(!k())return L(null);var U=function(j){if(j)return L(j);if(k())return F(U);var Z=o(arguments,1);L.apply(null,[null].concat(Z))};F(U)}function H1(k,T,L){Ll(function(){return!k.apply(this,arguments)},T,L)}var wd=function(k,T){if(T=wr(T||Nt),!Ae(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(j){var Z=M(k[L++]);j.push(Ao(U)),Z.apply(null,j)}function U(j){if(j||L===k.length)return T.apply(null,arguments);F(o(arguments,1))}F([])},J3={apply:r,applyEach:Ku,applyEachSeries:td,asyncify:v,auto:Uc,autoInject:E1,cargo:ci,compose:qc,concat:x1,concatLimit:gl,concatSeries:Gc,constant:Zc,detect:cs,detectLimit:Jo,detectSeries:Cl,dir:I1,doDuring:T1,doUntil:D1,doWhilst:Cd,during:S1,each:Qc,eachLimit:Al,eachOf:Go,eachOfLimit:Br,eachOfSeries:ls,eachSeries:di,ensureAsync:Yc,every:hi,everyLimit:bl,everySeries:Jc,filter:Xc,filterLimit:vl,filterSeries:ta,forever:M1,groupBy:fi,groupByLimit:ea,groupBySeries:N,log:G,map:jc,mapLimit:Er,mapSeries:Xu,mapValues:ht,mapValuesLimit:V,mapValuesSeries:Et,memoize:we,nextTick:na,parallel:yn,parallelLimit:yl,priorityQueue:mi,queue:bd,race:kl,reduce:Yo,reduceRight:gi,reflect:Wt,reflectAll:R1,reject:wl,rejectLimit:yd,rejectSeries:O1,retry:pi,retryable:Ko,seq:Wc,series:Bl,setImmediate:A,some:El,someLimit:Ir,someSeries:xl,sortBy:kd,timeout:Il,times:P1,timesLimit:Ai,timesSeries:N1,transform:$1,tryEach:Dl,unmemoize:Sl,until:H1,waterfall:wd,whilst:Ll,all:hi,allLimit:bl,allSeries:Jc,any:El,anyLimit:Ir,anySeries:xl,find:cs,findLimit:Jo,findSeries:Cl,forEach:Qc,forEachSeries:di,forEachLimit:Al,forEachOf:Go,forEachOfSeries:ls,forEachOfLimit:Br,inject:Yo,foldl:Yo,foldr:gi,select:Xc,selectLimit:vl,selectSeries:ta,wrapSync:v};e.default=J3,e.apply=r,e.applyEach=Ku,e.applyEachSeries=td,e.asyncify=v,e.auto=Uc,e.autoInject=E1,e.cargo=ci,e.compose=qc,e.concat=x1,e.concatLimit=gl,e.concatSeries=Gc,e.constant=Zc,e.detect=cs,e.detectLimit=Jo,e.detectSeries=Cl,e.dir=I1,e.doDuring=T1,e.doUntil=D1,e.doWhilst=Cd,e.during=S1,e.each=Qc,e.eachLimit=Al,e.eachOf=Go,e.eachOfLimit=Br,e.eachOfSeries=ls,e.eachSeries=di,e.ensureAsync=Yc,e.every=hi,e.everyLimit=bl,e.everySeries=Jc,e.filter=Xc,e.filterLimit=vl,e.filterSeries=ta,e.forever=M1,e.groupBy=fi,e.groupByLimit=ea,e.groupBySeries=N,e.log=G,e.map=jc,e.mapLimit=Er,e.mapSeries=Xu,e.mapValues=ht,e.mapValuesLimit=V,e.mapValuesSeries=Et,e.memoize=we,e.nextTick=na,e.parallel=yn,e.parallelLimit=yl,e.priorityQueue=mi,e.queue=bd,e.race=kl,e.reduce=Yo,e.reduceRight=gi,e.reflect=Wt,e.reflectAll=R1,e.reject=wl,e.rejectLimit=yd,e.rejectSeries=O1,e.retry=pi,e.retryable=Ko,e.seq=Wc,e.series=Bl,e.setImmediate=A,e.some=El,e.someLimit=Ir,e.someSeries=xl,e.sortBy=kd,e.timeout=Il,e.times=P1,e.timesLimit=Ai,e.timesSeries=N1,e.transform=$1,e.tryEach=Dl,e.unmemoize=Sl,e.until=H1,e.waterfall=wd,e.whilst=Ll,e.all=hi,e.allLimit=bl,e.allSeries=Jc,e.any=El,e.anyLimit=Ir,e.anySeries=xl,e.find=cs,e.findLimit=Jo,e.findSeries=Cl,e.forEach=Qc,e.forEachSeries=di,e.forEachLimit=Al,e.forEachOf=Go,e.forEachOfSeries=ls,e.forEachOfLimit=Br,e.inject=Yo,e.foldl=Yo,e.foldr=gi,e.select=Xc,e.selectLimit=vl,e.selectSeries=ta,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(lp,lp.exports);var xb={exports:{}},cp=xb.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),o=2;e===1/0;o*=2)e=Math.log(Math.pow(2,n/o))/Math.log(t)*o;for(var r=e-Math.floor(e),i="",o=0;o<Math.floor(e);o++){var s=Math.floor(Math.random()*t).toString(t);i=s+i}if(r){var l=Math.pow(t,r),s=Math.floor(Math.random()*l).toString(t);i=s+i}var a=parseInt(i,t);return a!==1/0&&a>=Math.pow(2,n)?cp(n,t):i};cp.rack=function(n,t,e){var o=function(i){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=cp(n,t)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=t||16,o};var Ib=Ni,bS=Bb,vS=Eb,jh=No,ap=lp.exports,yS=xb.exports,Tb=Us.ACTIONS,Db=Re;function Re(n,t){if(Ib.EventEmitter.call(this),!t||typeof t!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=t,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}Ib.mixin(Re),Re.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Re.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Re.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||yS();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Re.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(o){if(o)return t._callbackOrEmit(o,n);var r=Object.keys(t._remotePresenceInstances);ap.parallel([function(i){ap.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();ap.each(r,function(s,l){t._remotePresenceInstances[s].destroy(l)},i)}],function(i){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(i,n)})})},Re.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?Tb.presenceSubscribe:Tb.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Re.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Re.prototype._receiveUpdate=function(n,t){var e=jh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=jh.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Re.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Re.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var t in this.localPresences){var e=this.localPresences[t];e.value!==null&&e.send()}},Re.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Re.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Re.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Re.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Re.prototype._callbackOrEmit=function(n,t){if(t)return jh.nextTick(t,n);n&&this.emit("error",n)},Re.prototype._createLocalPresence=function(n){return new bS(this,n)},Re.prototype._createRemotePresence=function(n){return new vS(this,n)},Re.prototype._callEachOrEmit=function(n,t){var e=jh.callEach(n,t);!e&&t&&this.emit("error",t)};var Va=Bb,Sb=Fh,kS=No,Lb=Sb.CODES,wS=Ho;function Ho(n,t){Va.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}Ho.prototype=Object.create(Va.prototype),Ho.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:Lb.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(e,t)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,Va.prototype.submit.call(this,n,t)},Ho.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)},Ho.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},Ho.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)},Ho.prototype._transformAgainstOp=function(n,t){var e=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=e._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=e._transformPresence(r.p,n,t),e._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=e._getCallback(r.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(r){this.emit("error",r)}},Ho.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Ho.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Ho.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},Ho.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!kS.supportsPresence(o))throw new Sb(Lb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var Mb={};(function(n){var t=ja,e=Fh,o=No,r=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var a=l.create.type;if(typeof a!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[a];if(d==null||typeof d!="object")return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(r.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new e(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,a){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=t.map[d.type];if(!h)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(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 e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new e(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new e(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in a||a.create||a.del)||"op"in d&&a.create)return new e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){if(!l)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{a.op=l.transform(a.op,d.op,"left")}catch(h){return h}}}a.v!=null&&a.v++},n.applyOps=function(l,a,d){d=d||{};for(var h=0;h<a.length;h++){var p=a[h];if(d._normalizeLegacyJson0Ops)try{s(l,p)}catch{return new e(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=p.v;var 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=t.map[p]),!p)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(p))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(a.create||a.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:p.transformPresence(l.p,a.op,d)}catch(A){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:A.message||A}}l.v++};function s(l,a){if(l.type===t.defaultType.uri){var d=a.op;if(!!d){var h=l.data;d.length>1&&(h=o.clone(h));for(var p=0;p<d.length;p++){var 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=t.defaultType.apply(h,[A]))}}}}})(Mb);var Wa=Eb,BS=Mb,ES=ao;function ao(n,t){Wa.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._pending=null,this._opCache=null,this._pendingSetPending=!1,this._opHandler=this._handleOp.bind(this),this._createDelHandler=this._handleCreateDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._registerWithDoc()}ao.prototype=Object.create(Wa.prototype),ao.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},ao.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)},ao.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)},ao.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))}})}},ao.prototype._handleOp=function(n,t,e){var o=e===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)},ao.prototype._transformAgainstOp=function(n,t){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,t)}catch(e){return this.presence.emit("error",e)}this.presence._updateRemotePresence(this)}},ao.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],t=n.op,e=n.isOwnOp;t===null?(this._pending.p=null,this._pending.v++):BS.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},ao.prototype._startCachingOps=function(){this._opCache=[]},ao.prototype._stopCachingOps=function(){this._opCache=null},ao.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var Rb=Db,xS=wS,IS=ES;function Xl(n,t,e){var o=Xl.channel(t,e);Rb.call(this,n,o),this.collection=t,this.id=e}var TS=Xl;Xl.prototype=Object.create(Rb.prototype),Xl.channel=function(n,t){return n+"."+t},Xl.prototype._createLocalPresence=function(n){return new xS(this,n)},Xl.prototype._createRemotePresence=function(n){return new IS(this,n)};var DS=SS;function SS(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var LS=DS,Ob=Ni,_b=qa;function qa(n,t,e,o,r){if(Ob.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=o,this.collection=e,this.callback=r,this.sent=!1}Ob.mixin(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,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new LS(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var Fb=_b,MS=No,RS=Us.ACTIONS,OS=up;function up(n,t,e,o,r,i){if(Fb.call(this,n,t,e,o,i),!MS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}up.prototype=Object.create(Fb.prototype),up.prototype._message=function(){return{a:RS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var Pb=_b,_S=No,FS=Us.ACTIONS,PS=dp;function dp(n,t,e,o,r,i){if(Pb.call(this,n,t,e,o,i),!_S.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}dp.prototype=Object.create(Pb.prototype),dp.prototype._message=function(){return{a:FS.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var NS=uS,$S=gS,HS=Db,Nb=TS,jS=OS,US=PS,$b=Ni,tc=Fh,te=Us.ACTIONS,Hb=ja,jo=No,Ga=gb,Za=tc.CODES;function jb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var zS=wt;function wt(n){$b.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.nextSnapshotRequestId=1,this.queries={},this._presences={},this._snapshotRequests={},this.seq=1,this._presenceSeq=1,this.id=null,this.agent=null,this.debug=!1,this.state=jb(n),this.bindToSocket(n)}$b.mixin(wt),wt.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var t=jb(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Ga.warn("Failed to parse message",o);return}e.debug&&Ga.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){jo.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(o){e.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?e._setState("closed",o):o==="stopped"||o==="Stopped by server"?e._setState("stopped",o):e._setState("disconnected",o)}},wt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=Ub(n.error,n),delete n.error),n.a){case te.initLegacy:return this._handleLegacyInit(n);case te.handshake:return this._handleHandshake(t,n);case te.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case te.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case te.queryUnsubscribe:return;case te.queryUpdate:var e=this.queries[n.id];if(!e)return;if(t)return e._handleError(t);n.diff&&e._handleDiff(n.diff),n.hasOwnProperty("extra")&&e._handleExtra(n.extra);return;case te.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case te.bulkSubscribe:case te.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case te.snapshotFetch:case te.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case te.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case te.subscribe:case te.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case te.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case te.presence:return this._handlePresence(t,n);case te.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case te.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case te.presenceRequest:return this._handlePresenceRequest(t,n);case te.pingPong:return this._handlePingPong(t);default:Ga.warn("Ignoring unrecognized message",n)}};function Ub(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}wt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var o in t.data){var r=t.data[o],i=this.getExisting(t.c,o);i&&(n?i[e](n):r.error?i[e](Ub(r.error)):i[e](null,r))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var o=t.b[s],i=this.getExisting(t.c,o);i&&i[e](n)}else if(t.b)for(var o in t.b){var i=this.getExisting(t.c,o);i&&i[e](n)}else Ga.error("Invalid bulk message",t)},wt.prototype._reset=function(){this.agent=null},wt.prototype._setState=function(n,t){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var e=new tc(Za.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var a=this._snapshotRequests[o];a._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},wt.prototype.startBulk=function(){this.bulk||(this.bulk={})},wt.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var t=this.bulk[n];this._sendBulk("f",n,t.f),this._sendBulk("s",n,t.s),this._sendBulk("u",n,t.u)}this.bulk=null},wt.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var a=e[l];a==null?o.push(l):(r[l]=a,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:t,d:l})}else o.length&&this.send({a:"b"+n,c:t,b:o});if(i===1){var d=r[s];this.send({a:n,c:t,d:s,v:d})}else i&&this.send({a:"b"+n,c:t,b:r})}},wt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var o=this.bulk[t.collection]||(this.bulk[t.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(t.id);return r[t.id]=e,i}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},wt.prototype.sendFetch=function(n){return this._sendActions(te.fetch,n,n.version)},wt.prototype.sendSubscribe=function(n){return this._sendActions(te.subscribe,n,n.version)},wt.prototype.sendUnsubscribe=function(n){return this._sendActions(te.unsubscribe,n)},wt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:te.op,c:n.collection,d:n.id,v:n.version,src:t.src,seq:t.seq,x:{}};"op"in t&&(e.op=t.op),t.create&&(e.create=t.create),t.del&&(e.del=t.del),n.submitSource&&(e.x.source=t.source),this.send(e)},wt.prototype.send=function(n){this.debug&&Ga.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},wt.prototype.ping=function(){if(!this.canSend)throw new tc(Za.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:te.pingPong};this.send(n)},wt.prototype.close=function(){this.socket.close()},wt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},wt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new NS(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},wt.prototype._destroyDoc=function(n){!n._wantsDestroy||(jo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},wt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},wt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new $S(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},wt.prototype._destroyQuery=function(n){delete this.queries[n.id]},wt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(te.queryFetch,n,t,e,o)},wt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(te.querySubscribe,n,t,e,o)},wt.prototype.hasPending=function(){return!!(this._firstDoc(Uh)||this._firstQuery(Uh)||this._firstSnapshotRequest())};function Uh(n){return n.hasPending()}wt.prototype.hasWritePending=function(){return!!this._firstDoc(VS)};function VS(n){return n.hasWritePending()}wt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Uh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Uh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}jo.nextTick(n)},wt.prototype._nothingPendingRetry=function(n){var t=this;return function(){jo.nextTick(function(){t.whenNothingPending(n)})}},wt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var o in e){var r=e[o];if(n(r))return r}}},wt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},wt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},wt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new jS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new US(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},wt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},wt.prototype._initializeHandshake=function(){this.send({a:te.handshake,id:this.id})},wt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},wt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},wt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new tc(Za.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(Hb.map[n.type]!==Hb.defaultType)return this.emit("error",new tc(Za.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new tc(Za.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},wt.prototype.getPresence=function(n){var t=this,e=jo.digOrCreate(this._presences,n,function(){return new HS(t,n)});return e._wantsDestroy=!1,e},wt.prototype.getDocPresence=function(n,t){var e=Nb.channel(n,t),o=this,r=jo.digOrCreate(this._presences,e,function(){return new Nb(o,n,t)});return r._wantsDestroy=!1,r},wt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},wt.prototype._addPresence=function(n){jo.digOrCreate(this._presences,n.channel,function(){return n})},wt.prototype._handlePresenceSubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},wt.prototype._handlePresenceUnsubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},wt.prototype._handlePresence=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},wt.prototype._handlePresenceRequest=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var zb=zS,WS=ja;const zh={err:1001,msg:"user auth error",name:"AuthError"},qS={err:1002,msg:"you don't have required permission",name:"PermissionError"},hp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Qa={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},GS={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},ZS={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Ya="x-live-editor-token",Vh="x-live-editor-base-url",gn=S("auth-connection");function QS(n){try{n()}catch(t){gn.error(t)}}class YS{constructor(t,e){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new V5.EventEmitter);m(this,"token",null);m(this,"resourceToken",null);this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return ws(this.getBaseURL())}async auth(t){g(gn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[Ya]:t.token,[Vh]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=t.token,await o.json()}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Vh]:ws(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new WB.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(zb.prototype),g(gn,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},zb.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,gn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){gn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else gn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(zh.msg);t.code=zh.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Qa.msg);t.code=Qa.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const o=e.err;if(o===zh.err)gn.warn("auth error"),this.handleAuthError();else if(o===hp.err)gn.warn(hp.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(e)}`),this.emitAuthError()}get(t,e){return g(gn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(gn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(gn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(gn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.reauthFunc=void 0,this.events.removeAllListeners(),QS(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}S("utils/file");function JS(){function n(){return new Promise(t=>{const e=new FileReader;e.onload=()=>{t(e.result)},e.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}JS();async function KS(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new qB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>e&&(a=e);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return ws(i)}const dr=S("sharedb-doc/client");class XS{constructor(t,e,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",K());m(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(dr,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),dr.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;WS.register(Od.type),this.connection=new YS(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(dr,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,o=>{(t==="error"||this.doc)&&e(o)})}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,o,r,i){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const o=`${this.apiServer()}/resources`;let r=[];t.forEach(l=>{const a=l.split("|");r.push(...a)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[Ya]:this.connection.token}));return await Promise.all(i)}async uploadFile(t,e,o,r,i){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=v=>{dr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await KS(e),d=await this.getFileUrlByHash(t,a,e.name,e.size,o);if(d)return r(-1),d;let h=t;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${e.size}`),p.append("file-hash",a),p.append("file",e,e.name);const A=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return dr.info(A),r(100),Array.isArray(A.data)?A.data[0]:A.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(dr,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[Ya]:this.connection.token},e,o);return g(dr,s,"no result"),s}async request(t,e){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const a=e||{};a.url=t,a.headers||(a.headers={}),g(dr,o,"no token"),a.headers={...a.headers,[Ya]:o,[Vh]:this.connection.getBase64BaseURL()};try{return await zB.default(t,a)}catch(d){if(r=d,((i=d==null?void 0:d.response)==null?void 0:i.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;o=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw g(dr,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,r=(await this.request(e)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(t){const o=`${this.apiServer()}/versions/${t}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,o=await this.request(e);return JSON.parse(o.data.data)}async getVersionOps(t,e){let r=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(r+=`&from=${e}`);const i=await this.request(r),s=i.data.ops,l=VB.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(dr,a.create,"no createDoc.create"),d=a.create.data):d=JSON.parse(i.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:i.data.ops}}async updateVersionExtra(t,e,o){const i=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(t){const o=`${this.apiServer()}/versions/revert/${t}`;await this.request(o,{method:"post",data:{}})}async createVersion(t,e){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const o=`${this.apiServer()}/resources/external/${ws(t)}`;return(await this.request(o)).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let r=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const i=[];if(e!=null&&e.withToken&&i.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&i.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function tL(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const fp=S("block-ids");class eL{constructor(){m(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<e.length;r++){const i=e[r];if(i>=t){const s=this.ids.get(i);g(fp,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();this.ids.set(t,o)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<e.length;o++){const r=e[o];if(r>t){const i=this.ids.get(r);g(fp,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(t){let e=this.ids.get(t);return e||(e=K(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class nL{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new eL,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let o=0;o<e.length;o++){const r=e[o],i=r[1].getById(t);if(i)return{containerId:r[0],blockIndex:i[0]}}return g(fp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class Vb{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,o)=>{t[o]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const Wh=S("op-parse-handler");class oL{constructor(t,e){m(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const o={...t,containerId:(r=>r==="blocks"?"root":r)(t.containerId)};this.actions.push(o)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,o){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:o})}onDeleteBlockData(t,e,o){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:o})}onInsertBlockData(t,e,o,r){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:o,value:r})}onUpdateBlockText(t,e,o){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:o})}onDeleteContainer(t){this.pushActions({type:"deleteContainer",containerId:t})}onCreateContainer(t,e){this.pushActions({type:"createContainer",containerId:t,data:e})}onDeleteComment(t){this.pushActions({type:"deleteComment",commentId:t})}onCreateComment(t){this.pushActions({type:"createComment",commentId:t})}onUpdateComment(t){this.pushActions({type:"updateComment",commentId:t})}end(){const t=this.actions,e=new Set,o=new Map,r=new nL,i=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const d=o.get(a);d&&(Wh.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));const h=`${l.containerId}-${l.blockIndex}`;e.add(h),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,a=`${l.containerId}-${l.blockIndex}`;if(e.has(a)){Wh.warn("delete block data after delete block, ignore it");continue}const d=r.getBlockId(l.containerId,l.blockIndex);let h=o.get(d);h||(h=new Vb,o.set(d,h)),h.delete(l.key)}else g(Wh,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);let d=o.get(a);d||(d=new Vb,o.set(a,d)),d.insert(l.key,l.value)}else if(s.type==="updateBlockText"){const l=s;this.outerHandler.onUpdateBlockText(l.containerId,l.blockIndex,l.richTextData,this.local)}else if(s.type==="createComment"){const l=s;this.outerHandler.onCreateComment(l.commentId,this.local)}else if(s.type==="updateComment"){const l=s;this.outerHandler.onUpdateComment(l.commentId,this.local)}}),Array.from(o.entries()).forEach(([s,l])=>{const{containerId:a,blockIndex:d}=r.getBlockIndexById(s);Wh.debug(`update block data: ${a}, ${d}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Oe=S("op-parser");class Wb{}class mp{constructor(t){m(this,"key");this.key=t}}function rL(n,t,e){const o=t.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const a=o[l];if(!Array.isArray(a)||a.length!==2||typeof a[0]!="string")return!1;const h=a[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=i.i;g(Oe,s.id,"block id is required"),g(Oe,s.type,"block type is required");for(let l=1;l<o.length;l++){const a=o[l],d=a[0],h=a[1];s[d]=h.i}return e.onInsertBlock(n,r,s),!0}function gp(n,t,e,o){if(e==="upsert"&&rL(n,t,o))return;g(Oe,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const r=t.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const a=r[1];if(g(Oe,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),g(Oe,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}g(Oe,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Oe,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Oe,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Oe,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&e==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&e==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else e==="remove"&&d.r&&s.push(new mp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;e==="remove"&&a.r&&s.push(new Wb),e==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Oe,typeof l=="string","data is not string"),g(Oe,l!=="text","data !== 'text'"),g(Oe,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];e==="remove"&&d.r&&s.push(new mp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Wb?o.onDeleteBlock(n,i):l instanceof mp?o.onDeleteBlockData(n,i,l.key):g(Oe,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function iL(n,t,e){Oe.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function sL(n,t,e){const o=n[1],r=n[2];g(Oe,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Oe,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Oe.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?t==="upsert"&&e.onUpdateComment(o):r.i?t==="upsert"&&e.onCreateComment(o):r.r?t==="remove"&&e.onDeleteComment(o):Oe.error(`unknown comment op, ${JSON.stringify(n)}`)}function pp(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{pp(s,t,e)});return}const r=o;if(g(Oe,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){iL(n);return}if(r==="comments"){sL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{gp(i,s,t,e)}):n.slice(1).forEach(s=>{gp(i,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(i),s.i&&t==="upsert"&&e.onCreateContainer(i,s.i)}else g(Oe,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),gp(i,n.slice(1),t,e)}function qb(n,t,e){const o=new oL(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=mt.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{pp(a,i,o)}):pp(s,i,o)}o.end()}const lL=S("sharedb-comments");function Cp(n){const t=n.blocks;g(lL,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(e.blocks[o]=r)}),mt.default(e)}function Gb(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function Ap(n,t){const e=WD(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const ae=S("sharedb-doc/doc-container"),Zb="ot-json1";Od.type.registerSubtype(qD.type),Od.type.name=Zb,Od.type.invert=null;class Ja extends ha{constructor(e,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new zD);m(this,"batching",0);m(this,"status","clean");m(this,"disableLogout");m(this,"destroyed",!1);m(this,"handleNothingPending",()=>{this.setStatus("clean")});m(this,"handleCreate",()=>{this.handleReload("doc created")});m(this,"handleDel",()=>{});m(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});m(this,"handleReset",async e=>{const o=new Error(`reset doc: ${e}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});m(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});m(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});m(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});m(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});m(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,a])=>{if(!aa.default(i[l],a))if(i[l]===void 0){if(a!=null){const d={i:a};s.push([l,d])}}else if(a==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:a};s.push([l,d])}}),Object.entries(i).forEach(([l,a])=>{if((r[l]===void 0||r[l]===null)&&a!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});m(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){ae.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(ae.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),ae.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ae.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));m(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,Zb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainer",async(e,o)=>{const r=[Pi(e),{i:o}];return this.submitOp(r)});m(this,"submitDeleteChildContainer",async e=>{const o=[Pi(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[Pi(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[Pi(e),o,{r:!0}];return this.submitOp(r)});m(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[Pi(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a)){const h={r:!0,i:d};i.push([a,h])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(a=>{if(l.has(a))return;const d={r:!0};i.push([a,d])}),Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a))return;const h={i:d};i.push([a,h])}),this.submitOp(i)});m(this,"submitUpdateRichText",async(e,o,r)=>{const i=[Pi(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){ae.warn("handleOp: destroyed");return}qb(e,this,!!o)});this.client=e,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,g(ae,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new XS(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new Ja(o,r,e.disableLogout);if(r.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(e.templateData||tL())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ae.error(o),ae.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((e,o)=>{if(this.localPresence)e();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(K()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return Ha(this.data())}getContainerBlocks(e){const o=this.data();g(ae,o,"no doc data");const r=o[Pi(e)];return g(ae,r,`no container data: ${e}`),mt.default(r)}getBlockData(e,o){const r=this.data();g(ae,r,"no doc data");const i=r[Pi(e)];g(ae,i,`no container data: ${e}`);const s=i[o];return g(ae,s,`no block data: ${o}`),mt.default(s)}localInsertBlock(e,o,r){return this.submitInsertBlock(e,o,r),this.getBlockData(e,o)}localDeleteBlock(e,o){const r=this.getBlockData(e,o);return this.submitDeleteBlock(e,o),r}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(ae,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=ln.apply(s,r);return g(ae,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainer(e,o){this.submitInsertChildContainer(e,o)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>Gb(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return Cp(o)}localCreateComment(e,o){const r=Ap(e,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(e){const o=["comments",e,{r:!0}];return this.submitOp(o)}localUpdateComment(e,o){const r=Ap(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,o,r){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Kl(e),o,r)})}onInsertBlock(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockData(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Kl(e),o,r,i)})}onUpdateBlockText(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Kl(e),o,r,i)})}onDeleteContainer(e,o){g(ae,this.callbacks.length>0,"no callbacks"),g(ae,e!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Kl(e),o)})}onCreateContainer(e,o,r){g(ae,this.callbacks.length>0,"no callbacks"),g(ae,e!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Kl(e),o,r)})}onDeleteComment(e,o){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,e,o)})}onCreateComment(e,o){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,e,o)})}onUpdateComment(e,o){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){const o=e;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:e,clientId:"-"};this.onCustomMessage(r)})}async addResources(e){return await this.client.getFileUrlsByHashes(e)}async uploadResource(e,o){var i;return{resourceId:await this.client.uploadResource(e,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(e,o){return this.client.buildResourceUrl(e,o)}request(e,o){return this.client.request(e,o)}getUser(){const e=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:e,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const o=await this.client.getVersion(e);return Ha(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return Ha(e)}async getHistoryData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:Ha(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:Ha(r),versionData:i}}async updateVersionExtra(e,o,r){await this.client.updateVersionExtra(e,o,r)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,o){return this.client.createVersion(e,o)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,o){qb(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class Qb{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Se.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));m(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const o=this.editor.findBlockById(e);o&&this.editor.reloadBlock(o)})});this.editor=t,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const Yb=S("remote-cursor-decorator");class bp{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];g(Yb,typeof s=="string","invalid path containerId"),g(Yb,typeof l=="number","invalid path blockIndex");const a=t.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,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 Jb extends ve.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Xt(Hr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=et(this.editor.getContainerById(t));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function cL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).addListener("change",t)}function aL(n,t){n.addCustom("child-block-tracker",()=>new Jb(n)).removeListener("change",t)}const ant="",uL={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",name:"\u6587\u672C\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},dL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},hL={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};R.mergeLang({"zh-CN":uL,"en-US":dL,"js-JP":hL});const unt="";S("button");function uo(n,t,e,o,r){const i=w("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,t),e?typeof e=="string"?e.startsWith("<")?i.innerHTML=e:i.innerText=e:i.appendChild(e):i.innerText=t,o&&(o.indexOf("checked")!==-1&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0),o.indexOf("primary")!==-1&&W(i,"primary")),i}function Kb(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const dnt="",ec=S("ui-command-bar-base"),fL={itemElementTag:"div",tippyArrow:!1},Y2=class extends ve.TypedEmitter{constructor(e,o,r){var i,s;super();m(this,"content");m(this,"items");m(this,"subBar",null);m(this,"parentItem",null);m(this,"closeable",null);m(this,"closeReason",null);m(this,"options");m(this,"id");m(this,"header",null);m(this,"footer",null);m(this,"handleDocumentKeydown",e=>{if(!!this.isVisible&&!e.isComposing&&!Ss(e.target)){if(this.subBar){this.subBar.handleDocumentKeydown(e);return}if(this.items.length!==0){if(e.key==="Escape"){this.close("cancelBar");return}if(e.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(e.key==="ArrowLeft")this.parentItem&&this.close("switchItem");else if(e.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)}}}});m(this,"handleDocumentMouseDown",e=>{if(e.target instanceof Element&&!this.isInCommandBar(e.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,e)===!1)return;this.close("clickBackground")}});m(this,"handleHidden",()=>{this.closeReason!=="fromHover"&&this.emit("close",this),this.close(null),wC(this.id)});m(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&&kC(this.id)});m(this,"lastEnterPauseTime",0);m(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});m(this,"handleItemMouseEnter",e=>{if(Date.now()-this.lastEnterPauseTime<100)return;const o=this.getParentCommandItemElement(e.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)});m(this,"handleItemMouseLeave",e=>{var r,i;const o=this.getParentCommandItemElement(e.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(ot(o,"selected"),this.emit("selectionChange",this,""))});m(this,"handleItemClick",e=>{const o=this.getParentCommandItemElement(e.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"))}});m(this,"handleWheel",e=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=e.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=ro(r);if(!Kt(this.content,i)){e.stopPropagation(),e.preventDefault();return}e.deltaY<0?i.scrollTop===0&&(e.stopPropagation(),e.preventDefault()):e.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(e.stopPropagation(),e.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:K(),this.options={...fL,...r},this.items=e,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(e)}close(e){this.closeReason=e,this.subBar&&this.subBar.close(e),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(e,o){this.emit("click",this,e,o)}createPopperOptions(){var r,i;const e={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=e==null?void 0:e.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),this.options.padding&&((i=e==null?void 0:e.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),e}destroy(){var e;this.close(null),this.removeAllListeners(),(e=this.subBar)==null||e.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(e){var r;this.subBar&&e.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=e;const o=this.createCommandBarContent(e);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const e=this.getSelectedItem();return e?this.items.indexOf(e):-1}getPrevItemIndex(e){if(e<=0)return this.items.length-1;let o=e-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(e){let o=e+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 e=this.getSelectedItem();if(!e)return;const o=this.getItemElementById(e.id);o&&ot(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&ot(s,"selected")}const r=this.getItemElementById(e);r?(W(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(e){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=Y2.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});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,ot(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),W(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Kt(o,e)||Kt(this.content,e)?!0:this.subBar?this.subBar.isInCommandBar(e):!1}createCommandItem(e){var i,s,l,a;let o=(i=this.options.itemElementTag)!=null?i:"div";e.element&&(o="div");const r=w(o,["command-item"],null);return r.setAttribute("data-id",e.id),e.type==="separator"?r.classList.add("separator"):e.type==="section"?(r.classList.add("section","text"),e.element&&(typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element))):((s=e.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=e.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(a=e.states)!=null&&a.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,e.element?typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element):r.classList.add("standard")),this.initItemElement(e,r),r}getItemById(e){const o=this.items.find(r=>r.id===e);return g(ec,o,`can not find command item for id: ${e}`),o}getSelectedItem(){const e=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(e){const o=this.getItemElementId(e),r=this.items.find(i=>i.id===o);return g(ec,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return g(ec,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return g(ec,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(xt(e,"command-item"))return e;const o=e.closest(".command-item");return o||null}createCommandBarContent(e){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(e.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(e){var o;return{placement:(o=e.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(e,o){this.commandBarCreators.set(e,o)}static createSubCommandBar(e,o,r){var l;g(ec,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return g(ec,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Hi=Y2;m(Hi,"commandBarCreators",new Map),S("ui-command-bar");class qh extends Hi{constructor(){super(...arguments);m(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=GB.default(e,{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(e){var o;super.close(e),this.isVisible&&((o=this.tippyInstance)==null||o.hide())}destroy(){var e;(e=this.tippyInstance)==null||e.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var e,o;return(o=(e=this.tippyInstance)==null?void 0:e.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const Xb=S("ui-base");class Ka extends qh{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${K()}`,name:"",element:t}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(t){W(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];g(Xb,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return g(Xb,e,"no item element"),e}}const ji=S("filterable-list");function tv(n){var e,o;const t=w("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(w("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&W(t,"selected"),(o=n.states)!=null&&o.includes("disabled")&&W(t,"disabled"),t}function ev(n){const t=w("div",["list-root"],null);return n.forEach(e=>{t.appendChild(tv(e))}),n.length||t.appendChild(tv({id:"placeholder",states:["disabled"],name:R.t("search.emptyTips")})),t}function nv(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function mL(n,t){const e=w("div",["filterable-list"],null),o=w("div",["filter"],e),r=w("div",["filter-container"],o),i=w("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=w("div",["list"],e),l=ev(nv(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function ov(n,t,e){const o=n.querySelector(".list");g(ji,o,"no list root");const r=ev(nv(t,e)),i=o.querySelector(".list-root");if(g(ji,i,"no exists menu"),pa(i,r),e){const s=o.querySelector(".list-item.selected");s&&(g(ji,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class gL{constructor(t,e){m(this,"root");m(this,"visibleItems");m(this,"selectedId");m(this,"filter","");m(this,"onSelected",null);m(this,"handleKeydown",t=>{this.processKeyDown(t)});m(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");g(ji,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});m(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=mL(t,e),this.bindEvents(),this.selectedId=(o=e==null?void 0:e.initialSelectedId)!=null?o:"",this.visibleItems=t}bindEvents(){const t=this.root.querySelector(".filter-input");g(ji,t,"no input"),t.addEventListener("keyup",this.handleInputChanged),t.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const t=this.root.querySelector(".filter-input");g(ji,t,"no input"),t.removeEventListener("keyup",this.handleInputChanged),t.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(t=>t.id===this.selectedId):-1}setSelectedId(t){this.selectedId=t,ov(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");g(ji,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");g(ji,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),ov(this.root,this.visibleItems,this.selectedId))}processClick(t){var s,l;const e=t.target;if(!(e instanceof HTMLElement))return;const o=e.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(t){var e;if(t.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(t.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(t.key==="Enter"){const o=(e=this.visibleItems.find(r=>r.id===this.selectedId))!=null?e:null;this.onSelected&&this.onSelected(this,o)}}}class pL extends gL{constructor(e,o,r){super(e,r);m(this,"popup");m(this,"onShow",null);m(this,"onHide",null);m(this,"custom",null);m(this,"handleShow",()=>{this.onShow&&this.onShow(this)});m(this,"handleHide",()=>{this.onHide&&this.onHide(this)});m(this,"handleShown",()=>{this.focus()});this.popup=new Ka(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.reset(),this.popup.manualShow(e,{theme:"dropdown-list"}),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.popup.close("cancelBar")}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close("clickItem")}}const hnt="",fnt="";function CL(n,t){const e=document.createElement("div");e.classList.add("toast","show"),t!=null&&t.theme&&e.setAttribute("data-theme",t.theme),t!=null&&t.id&&e.setAttribute("data-id",t.id),t!=null&&t.html?e.innerHTML=n:e.textContent=n,t!=null&&t.position&&(e.style.left=`${t.position.x}px`,e.style.top=`${t.position.y}px`,e.classList.add("positioned")),document.body.appendChild(e),setTimeout(()=>{e.classList.remove("show"),setTimeout(()=>{e.remove()},500)},(t==null?void 0:t.duration)||3e3)}const rv=`<?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">
|