@ones-editor/editor 0.0.3-beta.124 → 0.0.3-beta.126
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/@ones-editor/tsconfig.tsbuildinfo +1 -1
- package/@ones-editor/ui-base/src/auto-suggest/auto-suggest-menu.d.ts +2 -2
- package/@ones-editor/ui-base/src/auto-suggest/auto-suggest.d.ts +2 -2
- package/@ones-editor/ui-base/src/command-bar/command-bar.d.ts +2 -0
- package/@ones-editor/ui-base/src/command-bar/types.d.ts +2 -2
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -24,7 +24,7 @@ Available method signatures are:
|
|
|
24
24
|
`:""}const Pp={boxType:"br",updateBoxContent:Dv,convertTo:Sv},Fp=w("editor-boxes");class Np{constructor(e){h(this,"boxes",new Map);this.editor=e}registerBoxClass(e){const t=e.boxType,o=this.boxes.get(t);d(Fp,!o,`duplicated box type: ${t}`),this.boxes.set(t,e)}getBoxClass(e){const t=this.boxes.get(e);return d(Fp,t,`unknown box type: ${e}`),t}createBox(e,t){const o=hg(t),r=mg(o);return this.getBoxClass(t.type).updateBoxContent(this.editor,o,r,t),o}}function Lv(n,e,t,o){const r=o,{width:i,height:s,src:l}=r,c=["editor-box-image"];r.link&&c.push("editor-box-image-link");const a=A("img",c,t);i&&(a.style.width=`${i}px`),s&&(a.style.height=`${s}px`),a.src=n.doc.buildResourceUrl(l)}const $p={boxType:"image",updateBoxContent:Lv},Mv="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9InJnYigxNzgsIDE4OCwgMjA1KSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0ibTE3IDE1IDEuNTUgMS41NWMtLjk2IDEuNjktMy4zMyAzLjA0LTUuNTUgMy4zN1YxMWgzVjloLTNWNy44MkMxNC4xNiA3LjQgMTUgNi4zIDE1IDVjMC0xLjY1LTEuMzUtMy0zLTNTOSAzLjM1IDkgNWMwIDEuMy44NCAyLjQgMiAyLjgyVjlIOHYyaDN2OC45MmMtMi4yMi0uMzMtNC41OS0xLjY4LTUuNTUtMy4zN0w3IDE1bC00LTN2M2MwIDMuODggNC45MiA3IDkgN3M5LTMuMTIgOS03di0zbC00IDN6TTEyIDRjLjU1IDAgMSAuNDUgMSAxcy0uNDUgMS0xIDEtMS0uNDUtMS0xIC40NS0xIDEtMXoiPjwvcGF0aD4KPC9zdmc+Cg==";function Rv(n,e,t){R(t,"editor-box-anchor"),mu(Mv,[],t)}const _p={boxType:"anchor",updateBoxContent:Rv};function Ov(n,e,t,o){A("span",[],t,o.text)}const jp={insertionType:"inputting",updateInsertionContent:Ov},Hp=w("editor-insertion");class zp{constructor(e){h(this,"insertions",new Map);this.editor=e}registerInsertionClass(e){const t=e.insertionType,o=this.insertions.get(t);d(Hp,!o,`duplicated insertion type: ${t}`),this.insertions.set(t,e)}getInsertionClass(e){const t=this.insertions.get(e);return d(Hp,t,`unknown insertion type: ${e}`),t}createInsertion(e,t){const o=gg(t.type,t.id),r=Cg(o);return this.getInsertionClass(t.type).updateInsertionContent(this.editor,o,r,t),o}}class Pv{constructor(e){h(this,"cursors",new Map);h(this,"timer");this.editor=e,this.timer=this.startTimer()}add(e,t){this.cursors.set(e,t)}startTimer(){return setInterval(()=>{const e=Date.now();Array.from(this.cursors).forEach(([t,o])=>{if(e-o>3e3){const r=pg(this.editor,t);r&&j(r,"active"),this.cursors.delete(t)}})},1e3)}destroy(){clearInterval(this.timer)}}function Fv(n,e,t,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",a=>new Pv(a)).add(r.id,r.time),R(e,"active")),A("span",[],t,"|").setAttribute("data-cursor-name",r.name),e.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const wd={insertionType:"remote-cursor",updateInsertionContent:Fv};class Up{constructor(e){h(this,"decorators",[]);this.editor=e}registerDecorator(e){this.decorators.push(e)}decorateBlock(e,t){let o=t;return this.decorators.forEach(r=>{if(r.decorateBlock){const i=r.decorateBlock(this.editor,e,t);i&&(o=Q.default(i))}}),o}decorateText(e,t){let o=t;const r=new Map;return this.decorators.forEach(i=>{if(i.decorateText){const s=i.decorateText(this.editor,e,t);if(s){const{insertions:l,text:c}=s;l&&Array.from(l.entries()).forEach(([a,u])=>{const f=r.get(a);f?f.push(...u):r.set(a,u)}),c&&(o=Q.default(c))}}}),{insertions:r,text:o}}}const Bd=w("editor-input");class Nv{constructor(e,t){h(this,"editor");h(this,"composing",!1);h(this,"callbacks");h(this,"inputElement");h(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var t;const e=(t=document.getSelection())==null?void 0:t.focusNode;e&&this.editor.contains(e)&&!Nr(e)?(this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus()):(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});h(this,"handleEditorSelectionChanged",()=>{const t=!this.editor.isWritable();this.inputElement.readOnly=t});h(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});h(this,"handleCompositionstart",e=>{this.composing=!0,this.callbacks.onCompositionStart(e)});h(this,"handleCompositionend",e=>{this.composing=!1,this.callbacks.onUpdateCompositionText(e,this.inputElement.value,!0),this.inputElement.value=""});h(this,"handleInput",e=>{if(e instanceof InputEvent&&!!e.data){if(this.editor.readonly){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(e,e.data,!1):(this.callbacks.onInsertText(e,e.data),this.inputElement.value="")}});h(this,"handleKeyDown",e=>{if(!this.composing){if(this.callbacks.onKeyDown(e)){e.preventDefault(),e.stopPropagation();return}!this.editor.isWritable()||setTimeout(()=>{this.composing||(this.inputElement.value="")})}});h(this,"handleCopy",e=>{this.callbacks.onCopy(e)});h(this,"handleCut",e=>{if(this.editor.readonly){e.stopPropagation(),e.preventDefault();return}this.callbacks.onCut(e),Bd.debug("on cut")});h(this,"handlePaste",e=>{if(this.editor.readonly){e.stopPropagation(),e.preventDefault();return}this.callbacks.onPaste(e)});h(this,"handlePasteText",e=>{this.callbacks.onPasteText(e)});this.editor=e,this.callbacks=t;const o=A("input",["editor-input"],e.contentElement);o.type="text",o.name="editor-input",o.onkeydown=this.handleKeyDown,o.oninput=this.handleInput,o.oncopy=this.handleCopy,o.onpaste=this.handlePaste,o.oncut=this.handleCut,o.addEventListener("compositionstart",this.handleCompositionstart),o.addEventListener("compositionend",this.handleCompositionend),this.inputElement=o,document.addEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.removeListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged);const e=this.inputElement;e.removeEventListener("compositionstart",this.handleCompositionstart),e.removeEventListener("compositionend",this.handleCompositionend),e.onkeydown=null,e.oninput=null,e.oncopy=null,e.onpaste=null,e.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),ot.isMobileSafari?this.inputElement.focus():setTimeout(()=>{this.inputElement.focus()})}handleChanged(e){this.callbacks.onChanged(e)}handleRemoteChanged(e){this.callbacks.onRemoteChanged(e)}addHandler(e){this.callbacks.addHandler(e)}removeHandler(e){this.callbacks.removeHandler(e)}defaultInsertText(e,t,o,r,i){d(Bd,e===this.editor,"invalid editor"),this.callbacks.defaultInsertText(e,t,o,r,i)}defaultHandleKeydown(e,t){return d(Bd,e===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(e,t)}}function Vp(n){const e=n.rootElement,t=e.getBoundingClientRect(),o=Qo(e),r=window.innerWidth,i=window.innerHeight,s=t.left<0?0:t.left,l=t.top<0?0:t.top,c=t.right>r?r:t.right,a=t.bottom>i?i:t.bottom,u=(s+c)/2,f=(l+a)/2,m=0-t.left+u,p=0-t.top+f,b=n.input.inputElement;b.style.left=`${m/o}px`,b.style.top=`${p/o}px`}const Ed=w("editor-caret");class $v{constructor(e){h(this,"editor");h(this,"caretElem");h(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=e,this.caretElem=A("div",["editor-cursor"],this.editor.contentElement),this.editor.on("readonlyChanged",this.handleReadOnlyChanged)}destroy(){this.editor.off("readonlyChanged",this.handleReadOnlyChanged)}visible(){const e=window.getComputedStyle(this.caretElem);return e.display!=="none"&&e.opacity!=="0"}hasCaret(){if(this.editor.readonly||!this.editor.selection.range.isCollapsed())return!1;const e=this.editor.selection.range.start;if(!(e instanceof We))return!1;const t=this.editor.getBlockById(e.blockId);return!!$(this.editor,t)}update(){if(xm(this.editor.rootElement))return;const e=this.caretElem;if(this.hasCaret())e.style.display="";else{e.style.display="none",Vp(this.editor);return}const{range:t}=this.editor.selection;d(Ed,t.isCollapsed,"range is not collapsed");const o=t.start;d(Ed,o instanceof We,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);d(Ed,$(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=Go(s),i=new DOMRect(i.right,i.top,1,i.height)):i=St(r,o);const l=this.editor.contentElement.getBoundingClientRect(),c=i.left-l.left,a=i.top-l.top;e.style.left=`${c}px`,e.style.top=`${a}px`,e.style.height=`${i.height}px`;const u=this.editor.input.inputElement;u.style.left=`${c}px`,u.style.top=`${a+i.height-24}px`,ot.isMobileSafari&&(u.style.left=`${c-4}px`,u.style.height=`${i.height}px`);const m=Qt(r,{horizontal:!0}).getBoundingClientRect(),p=m.left-l.left,b=p+m.width;c<p||c>b?(Vp(this.editor),e.style.display="none"):e.style.display=""}}function _v(n){kg(n),n.selection.range.getSelectedBlocks().forEach(e=>wg(n,e.block,e.start,e.end))}const jv=w("editor-dom");function qp(n){return Qt(n.rootContainer).clientHeight}function Hv(n){return n.getFirstBlock().getBoundingClientRect().top}function zv(n){return n.getLastBlock().getBoundingClientRect().bottom}function Id(n){const t=Qt(n.rootContainer).getBoundingClientRect(),o=t.x<0?0:t.x,r=t.y<0?0:t.y,i=t.right>window.innerWidth?window.innerWidth:t.right,s=t.bottom>window.innerHeight?window.innerHeight:t.bottom;return new DOMRect(o,r,i-o,s-r)}function Uv(n,e){const t=Id(n),o=n.getBlockById(e.blockId),i=Xt(n,o,e);return Yo(t,i.x,i.y)&&Yo(t,i.right,i.bottom)}function Wp(n,e){const t=Id(n),o=e.getBoundingClientRect();return o.top>=t.top&&o.top<=t.bottom||o.bottom<=t.bottom&&o.bottom>=t.top}function Vv(n,e){const t=Id(n),o=e.getBoundingClientRect();return Yo(t,o.x,o.y)||Yo(t,o.right,o.bottom)}function qv(n){if(!bu(n.rootContainer)){jv.warn("editorScrollIntoView: editor is not visible");return}const e=n.rootContainer.getBoundingClientRect();if(e.height<1&&e.width<1)return;const t=n.selection,o=t.range.focus;if(!o.isSimple()){const u=o,f=n.getContainerById(u.childContainerId);Vv(n,f)||f.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const u=n.getBlockById(t.range.start.blockId);if(qe(u)&&Wp(n,u)||ce(n,u)&&Wp(n,u))return}const r=o,i=n.getBlockById(r.blockId);if(Uv(n,r))return;const s=Xt(n,i,r),l=i.getBoundingClientRect(),c=Pe(i),a=A("div",["editor-block-anchor"],c);a.style.top=`${s.top-l.top}px`,vu(a,{elementToScroll:Qt(n.rootContainer)}),setTimeout(()=>{a.remove()},200)}function Wv(n,e){if(e.isCollapsed())return!1;const t=$e(n.rootContainer),o=Ke(n.rootContainer),{start:r,end:i}=e;return r.blockId===z(t)&&r.offset===0&&i.blockId===z(o)&&i.offset===G(n,o)}const Gp=w("range-in-block");function Zp(n,e){const t=e.getEditor(),o=t.getBlockById(e.start.blockId),r=t.getBlockById(e.end.blockId),i=o===n||Ce(n,o),s=r===n||Ce(n,r);return!!(i||s)}function Qp(n,e){const t=n.doc.toJSON(),o=new Set(Object.values(t.blocks).map(s=>s.map(l=>l.id)).flat());let r,i=ye(e);if(i){for(;i&&!o.has(z(i));)i=ye(i);d(Gp,i,"no prev block while deleting a block"),r=Fe(n,i,G(n,i))}else{const s=fe(e);d(Gp,s,"no prev and next block while deleting a block"),r=Fe(n,s,0)}return r}const Gv=w("block-to-html");function xd(n,e,t,o){const r=$r(n,e.type);if(r.convertTo)return r.convertTo(n,e,t,"html",o);if(r.blockKind!=="text")return`[${e.type}]`;d(Gv,e.text,"no text");const i=ve(e.text);return`<div>${Lm(i)}</div>`}const Yp=w("block-to-text");function Zv(n,e,t){let o="";return e.forEach(r=>{if(d(Yp,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const i=r.attributes,s=n.editorBoxes.getBoxClass(i.type);if(s!=null&&s.convertTo){o+=s.convertTo(n,i,t,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}function rc(n,e,t,o){const r=$r(n,e.type);return r.convertTo?r.convertTo(n,e,t,"text",o):r.blockKind!=="text"?`[${e.type}]`:(d(Yp,e.text,"no text"),Zv(n,e.text,t))}function Td(n,e,t,o){const r=$r(n,e.type);return r.convertTo?r.convertTo(n,e,t,"markdown",o):rc(n,e,t,o)}function ic(n,e){return e.blocks.root.map((r,i)=>xd(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
|
|
25
25
|
`)}function Jp(n,e){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${ic(n,e)}</body></html>`}function is(n,e){return e.blocks.root.map((r,i)=>rc(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
|
|
26
26
|
`)}function ss(n,e){return e.blocks.root.map((r,i)=>Td(n,r,e,[{containerId:"root",blockIndex:i}])).join(`
|
|
27
|
-
`)}const Qv=w("get-text-position");function Ur(n,e){const t=e!=null?e:n.selection.range.start;t instanceof We||d(Qv,!1,`invalid insert pos type: ${typeof t}`);const{blockId:o}=t,r=n.getBlockById(o),i=K(r),s=_(r),l=q(s),{offset:c}=t;return{block:r,container:s,containerId:l,blockIndex:i,offset:c}}const ls=w("insert-text");function Kp(n,e,t,o){var s;const r=n.doc.getBlockData(e,t);if(d(ls,r,"no block data"),d(ls,r.text,"no block text"),at(r.text)===0)return d(ls,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 Yv(n,e,t){const o=_(e),r=q(o),i=K(e);return Kp(n,r,i,t)}function Xp(n,e,t,o,r){const i=_(e),s=q(i),l=K(e),c=Yv(n,e,t),a=Ql(t,o,c!=null?c:null);return n.doc.localUpdateBlockText(s,l,a,r),pt(n,e)}function e0(n,e,t,o){const r=_(e),i=q(r),s=K(e),l=Ql(t," ",o);return n.doc.localUpdateBlockText(i,s,l),pt(n,e)}function Dd(n,e,t,o,r){const i=n.doc.getBlockData(t,o);d(ls,i,"no block data"),d(ls,i.text,"no block text");const s=Kp(n,t,o,r),l=Ql(r,e,s!=null?s:null);return n.doc.localUpdateBlockText(t,o,l),pt(n,n.getBlockById(i.id))}function Sd(n,e){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:t,blockIndex:o,offset:r}=Ur(n);Dd(n,e,t,o,r)}const sc=w("update-composition-text");function t0(n){const e=n.selection.range.start;e instanceof We||d(sc,!1,`invalid insert pos type: ${typeof e}`);const{blockId:t}=e,o=n.getBlockById(t);d(sc,$(n,o),"not a text kind block");const r=_(o),i=q(r),s=K(o),l=n.doc.getBlockData(i,s);d(sc,l,"no block data in doc"),d(sc,l.text,"no text data in text block");const c=le(o);ql(n,fo(o),t,c,l.text)}function n0(n){Tb(n)}function Vr(n,e,t,o,r,i){return n.doc.localInsertBlock(e,t,o,r,i),n.getBlockById(o.id)}const cs=w("delete-block-text");function Ld(n,e,t,o,r){if(!n.isBlockWritable(e))return cs.error("block is not writable"),0;d(cs,$(n,e),"block is not a text kind block");const i=_(e),s=q(i),l=K(e),c=n.doc.getBlockData(s,l);d(cs,c,"no block data in doc"),d(cs,c.text,"no text data in text block");let a=t;ut(e,t)||(a=Co(e,a));let u=t+o;d(cs,u<=G(n,e),`invalid offset and count: ${t}, ${o}`),ut(e,u)||(u=cr(e,u));const f=u-a,m=dp(a,f);return n.doc.localUpdateBlockText(s,l,m,r),f}const Md=w("break-text-block");function o0(n,e){const o=n.getBlockData(e).quoted;return o?{quoted:o}:{}}function qr(n,e,t,o){d(Md,$(n,e),`block is not a text kind block: ${ie(e)}`),d(Md,t>=0&&t<=G(n,e),`invalid offset: ${t}`);const r=_(e),i=q(r),s=K(e),l=o!=null&&o.copyBlockAttributes?o0(n,e):{};if(!(o!=null&&o.forceInsertAfter)&&(t===0||t===G(n,e))){const p=t===0?s:s+1,b={...Gn(""),...l,...o==null?void 0:o.newBlockData},y=Fe(n,e.id,0),v=Vr(n,i,p,b,y);return{block:e,newBlock:v}}d(Md,ut(e,t),"not a valid offset");const c=pt(n,e),{right:a}=kt(c,t),u=at(a);u>0&&Ld(n,e,t,u);const f={...Gn(a),...l,...o==null?void 0:o.newBlockData},m=Vr(n,i,s+1,f,Fe(n,f.id,0));return{block:e,newBlock:m}}const Jv=w("prepare-insert-new-block");function Kv(n,e,t){if(e&&t!==void 0&&t!==null){const a=n.getContainerById(e),u=Me(a);return d(Jv,t>=0&&t<=u.length,`invalid blockIndex: ${t}`),{containerId:e,blockIndex:t}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(e=q(_(r)),t=K(r),!$(n,r))return{containerId:e,blockIndex:t+1};const s=o.offset;if(s===0||s===G(n,r))return{containerId:e,blockIndex:s===0?t:t+1};const c=qr(n,r,s).newBlock;return{containerId:e,blockIndex:K(c)}}const Xv=w("auto-insert-block");function r0(n,e,t,o,r,i){const s=Kv(n,t,o);d(Xv,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:e.id,offset:0},c={anchor:l,focus:l};return Vr(n,s.containerId,s.blockIndex,e,r!=null?r:c,i)}const ey=w("delete-block");function lc(n,e,t){e.children&&(t.push(...e.children),e.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{lc(n,i,t)})}))}function Rd(n,e,t){const o=_(e),r=q(o),i=K(e),s=n.doc.getBlockData(r,i);return d(ey,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ge(n,{anchor:t.start,focus:t.end})),s}function Od(n,e,t){return n.undoManager.runInGroup(()=>{const o=_(e);Yt(o)===1&&n.insertTextBlock("",q(o),0);let r=t?mo(n,t):null;if(!r){const l=n.selection.range;Zp(e,l)?r=Qp(n,e):r=l}const i=Rd(n,e,r),s=[];return lc(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function ty(n,e){const t=[e];n.doc.getContainerBlocks(e).forEach(r=>{lc(n,r,t)}),n.doc.localDeleteChildContainers(t)}function i0(n,e){const t=[...e];e.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{lc(n,i,t)})}),n.doc.localDeleteChildContainers(t)}const Pd=w("merge-text-block");function s0(n,e,t){d(Pd,$(n,e),"only text block can be merged"),d(Pd,$(n,t),"only text block can be merged");const o=vo(n,e),r=vo(n,t),i=o.text,s=r.text;d(Pd,i&&s,"block data has no text");const l=_(e),c=q(l),a=K(e),u=G(n,e),f=Dd(n,s,c,a,u),m=Fe(n,e,at(i));return Od(n,t,m),f}const En=w("clear-selected-contents");function cc(n,e){d(En,$(n,e.block),"not a text kind block");const{start:t,end:o}=e;d(En,t.isSimple(),"not a simple block position"),d(En,o.isSimple(),"not a simple block position");const r=t.offset,i=o.offset;d(En,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(e.block,r,i-r)}function l0(n,e,t){const o=q(e),r=Me(e),i=t.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});t.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function ny(n,e){const{block:t,start:o,end:r}=e;if($(n,t)){cc(n,e);return}if(qe(t)||o.isSimple()){d(En,r.isSimple(),"invalid range");const s=_(t),l=K(t),c=n.insertTextBlock("",q(s),l);n.selection.selectBlock(c,0),n.deleteBlock(t);return}d(En,ce(n,t),"invalid block kind"),d(En,!o.isSimple()&&!r.isSimple(),"invalid range"),sr(n,t,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{l0(n,s,{focus:l===0})})}function oy(n){if(!n.isWritable())return;const e=n.selection.range;if(e.isCollapsed())return;const t=e.getSelectedBlocks();if(d(En,t.length>0,"no selected block"),t.length===1){ny(n,t[0]);return}const o=t[0],r=o.block,i=_(r);d(En,t.length>1,"no selected block");const s=t[t.length-1],l=s.block;if($(n,r)){cc(n,o);const u=Fe(n,o.block,o.start.offset);if(t.slice(1,t.length-1).reverse().forEach(m=>n.deleteBlock(m.block)),$(n,l)){cc(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(u);return}n.deleteBlock(l),n.selection.setRange(u);return}if($(n,l)){cc(n,s),t.slice(0,t.length-1).reverse().forEach(u=>n.deleteBlock(u.block)),n.selection.selectBlock(s.block,0);return}if(t.length===Yt(i)){l0(n,i,{focus:!0});return}const c=ye(r),a=fe(l);d(En,c||a,"no prev or next block"),t.forEach(u=>n.deleteBlock(u.block))}function Fd(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),oy(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const ry=w("core");function c0(n,e,t){const o=_(e),r=q(o),i=K(e);return n.doc.localUpdateBlockText(r,i,t),setTimeout(()=>{n.selection.updateSelection(null)}),pt(n,e)}function a0(n,e,t){if(!n.isBlockWritable(e)){ry.error("block is not writable");return}const o=n.getBlockText(e),r=dt.diff(o,t);c0(n,e,r)}function ac(n,e,t){const o=pt(n,e),r=typeof t=="string"?Ao(t):t,i=dt.diff(o,r);return c0(n,e,i)}const as=w("update-block-data");function uc(n,e,t,o){const r=_(e),i=q(r),s=K(e),l=n.doc.getBlockData(i,s),c={insert:{},delete:[]},a=new Set(Object.keys(l)),u=new Set(Object.keys(t));return a.forEach(m=>{if(!u.has(m)){if(m==="id"||m==="type"||m==="text")return;as.debug(`delete key: ${m}`),c.delete.push(m)}}),Object.entries(t).forEach(([m,p])=>{d(as,m!=="id"&&m!=="type",`invalid block data delta, ${m}`);const b=l[m];if(p==null){b!=null&&(as.debug(`delete key: ${m}`),c.delete.push(m));return}b!==p&&(_i.default(b,p)||m==="text"&&dt.diff(b,p).length===0||(a.has(m)?(as.debug(`replace key: ${m}`),c.delete.push(m)):as.debug(`insert key: ${m}`),c.insert[m]=p))}),n.doc.localUpdateBlockData(i,s,c,o),vo(n,e)}function u0(n,e,t,o){const i={...n.getBlockData(e),embedData:t};return n.updateBlockData(e,i,o)}function Nd(n,e,t){if(!ce(n,e)||!(t!=null&&t.tryFocusToChildSimpleBlock)){n.selection.selectBlock(e,0);return}const r=Tt(n,e).getChildContainers(n,e)[0],i=$e(r);Nd(n,i,t)}function dr(n){const e=[];let t={};return n.forEach(o=>{e.push(...o.blocks.root);const{root:r,...i}=o.blocks;t={...t,...i}}),{blocks:{...t,root:e},meta:{},comments:{}}}const us=w("clone-block");function yo(n,e,t,o){const r=n.getBlockClass(t.type);if(r.blockToDoc)return r.blockToDoc(e,t,(u,f)=>(d(us,t!==f,"invalid child block"),yo(n,u,t,o)));let i={};const s=new Map,l=Q.default(t);l.children&&(l.children=l.children.map(u=>{const f=N(),m=e.blocks[u];d(us,Array.isArray(m),"invalid child blocks");const p=m.map(x=>yo(n,e,x,o)),b=dr(p),{root:y,...v}=b.blocks;return i={...i,...v},i[f]=b.blocks.root,s.set(u,f),f}));const c=Array.from(s.entries()),a=u=>{for(const f of c){const[m,p]=f;{const b=`${m}/`;if(u.startsWith(b)){const y=u.substring(b.length),v=`${p}/${y}`;return us.debug(`replace key: ${u} -> ${v}`),v}}{const b=`${m}_`;if(u.startsWith(b)){const y=u.substring(b.length),v=`${p}_${y}`;return us.debug(`replace key: ${u} -> ${v}`),v}}}return u};return Array.from(Object.entries(l)).forEach(([u,f])=>{const m=a(u);m!==u&&delete l.key,l[m]=f}),l.id=N(),o&&(o.blockIdMap.set(t.id,l.id),s.forEach((u,f)=>o.containerIdMap.set(f,u))),{blocks:{root:[l],...i},meta:{},comments:{}}}function $d(n,e,t,o){const r=e.blocks[t];d(us,Array.isArray(r),"invalid child blocks");const i=r.map(l=>yo(n,e,l,o));return dr(i)}function _d(n,e,t){const o=e.blocks.root.map(r=>yo(n.editorBlocks,e,r,t));return Q.default(dr(o))}const d0=w("insert-doc");function h0(n,e,t,o,r){if(ce(n,e)){d0.warn("failed to insert doc into a complex block");return}const i=_d(n,o,r),s=_(e),l=K(e),c=q(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var E,M,L;Object.entries(i.blocks).forEach(([O,V])=>{O!=="root"&&n.doc.localInsertChildContainer(O,V)});const a=i.blocks.root;if(qe(e)){n.deleteBlock(e);let O;a.reverse().forEach(V=>{const ee=n.insertBlock(c,l,V);O||(O=ee)}),O&&n.selection.selectBlock(O,G(n,O));return}if(d(d0,$(n,e),"not a text block"),Ie(n,e)){const O=K(e);let V;a.forEach((ee,se)=>{const pe=n.insertBlock(c,O+se,ee);se===a.length-1&&(V=pe)}),V&&n.selection.selectBlock(V,G(n,V));return}if(a.length===1){const O=a[0];if(Qi(n,O.type)){n.insertTextToBlock(e,t,(E=O.text)!=null?E:[]);return}n.breakTextBlock(e,t),n.insertBlock(c,l+1,O);return}const u=t===G(n,e),f=t===0,m=a[0],p=a[a.length-1];let b;!u&&!f?b=n.breakTextBlock(e,t,{forceInsertAfter:!0}):b=e;const y=f?l:l+1;u?(b=n.insertBlock(c,l+1,p),n.selection.selectBlock(b,G(n,b))):(n.selection.selectBlock(b,0),Qi(n,p.type)?n.insertTextToBlock(b,0,(M=p.text)!=null?M:[]):n.insertBlock(c,y,p));const v=n.selection.range;let x=y;Qi(n,m.type)?f?(n.insertBlock(c,y,m),x+=1):n.insertTextToBlock(e,t,(L=m.text)!=null?L:[]):(n.insertBlock(c,y,m),x+=1),a.slice(1,a.length-1).reverse().forEach(O=>{n.insertBlock(c,x,O)}),n.selection.setRange(v)}),n.doc.endBatchUpdate()}function jd(n,e,t,o,r){const i=_d(n,o,r),s=q(e),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([a,u])=>{a!=="root"&&n.doc.localInsertChildContainer(a,u)}),i.blocks.root.reverse().forEach(a=>{const u=n.insertBlock(s,t,a);l.push(u)})}),l}function f0(n,e,t){const o=Yt(e);jd(n,e,o,t);for(let r=0;r<o;r++){const i=$e(e);n.deleteBlock(i)}}const ds=w("add-text-attribute");function iy(n,e,t,o){const{start:r,end:i}=t;d(ds,r.blockId===i.blockId&&r.blockId===z(e),"invalid range"),d(ds,o,"invalid attribute name");const s=n.getBlockText(e),l=zr(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(e,l),l}function m0(n,e,t,o,r){const{start:i,end:s}=t;d(ds,i.blockId===s.blockId&&i.blockId===z(e),"invalid range"),d(ds,o,"invalid attribute name");const l=n.getBlockText(e),c=ts(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,c),c}function Wr(n,e,t,o,r){const{start:i,end:s}=t;d(ds,i.blockId===s.blockId&&i.blockId===z(e),"invalid range");const l=n.getBlockText(e),c=vp(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,c),c}function g0(n,e,t,o){const r=nn(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:c}=i;if(!$(n,s))return;if(Ie(n,s)){o(n,z(s),e,t);return}const a=Ge(n,{anchor:l,focus:c});e==="color"||e==="backgroundColor"?Wr(n,s,a,e,t):(Wr(n,s,a,"color",null),Wr(n,s,a,"backgroundColor",null))})})}function p0(n,e,t){const o=nn(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!$(n,i))return;if(Ie(n,i)){(e==="clearColor"||e==="clearAll")&&t(n,z(i),"color",null),(e==="clearBackground"||e==="clearAll")&&t(n,z(i),"backgroundColor",null);return}const c=Ge(n,{anchor:s,focus:l});(e==="clearColor"||e==="clearAll")&&Wr(n,i,c,"color",null),(e==="clearBackground"||e==="clearAll")&&Wr(n,i,c,"backgroundColor",null)})})}function Hd(n,e){const t=nn(n,{simpleBlockOnly:!0}).filter(s=>$(n,s.block));if(t.length===0)return[null,null];const o=s=>{if(G(n,s.block)===0)return e(n,z(s.block));const l=s.start,c=s.end,a=n.getBlockText(s.block);return wp(l.offset,c.offset-l.offset,a)};let[r,i]=o(t[0]);return r===null&&i===null?[r,i]:(t.forEach(s=>{const[l,c]=o(s);l===null||r===null?r=null:r=l===r?r:null,c===null||i===null?i=null:i=c===i?i:null}),[r,i])}const Lt=w("adjust-selection-pos");function C0(n){const e=[];for(;n;){const t=_(n);if(e.unshift(t),Ae(t))return e;const o=H(t);d(Lt,o,"child container has not parent container"),n=o}d(Lt,!1,"should not come here: getParentContainers")}function A0(n,e){for(;e;){const t=_(e);if(t===n)return e;const o=H(t);d(Lt,o,"could not find parent block for a child container"),e=o}d(Lt,!1,"no parent block in specified container")}function sy(n,e){const t=C0(n),o=C0(e);d(Lt,t.length>0&&o.length>0,"block has not parent container"),d(Lt,t[0]===o[0],"root container does not equal");let r=t[0];for(let l=1;l<t.length||o.length;l++)if(t[l]!==o[l]){r=t[l-1];break}const i=A0(r,n),s=A0(r,e);return{parentContainer:r,newBlock1:i,newBlock2:s}}function b0(n,e){let t=H(e);for(d(Lt,t,"element is not in a block");t;){const o=_(t);d(Lt,en(o),"not a child container");const r=H(o);if(d(Lt,r,"child container has not parent block"),r===n)return o;t=r}d(Lt,!1,"failed to find parent container in complex block")}function dc(n,e,t){const o=n.getBlockById(e.blockId),r=n.getBlockById(t.blockId);if(o===r)return e instanceof We&&t instanceof We?{anchor:e,focus:t}:e instanceof tn&&t instanceof tn?Ul(n,o,e,t):null;const i=_(o),s=_(r);if(i===s)return e instanceof tn&&(e=U(o,0,"home")),t instanceof tn&&(t=U(r,G(n,r),"end")),d(Lt,e instanceof We,"not valid position type"),d(Lt,t instanceof We,"not valid position type"),{anchor:e,focus:t};if(o.contains(s))return null;if(r.contains(i)){if(e instanceof We&&t instanceof tn){const b=n.getContainerById(t.childContainerId);if(b===i)return{anchor:t,focus:t};const y=H(i);if(y&&y===H(b)){const v=xe(y,q(i)),x=xe(y,q(b));return Ul(n,y,v,x)}}return null}const l=Sl(o,r)>0,{newBlock1:c,newBlock2:a}=sy(o,r);if(c===a){const b=c,y=b0(b,o),v=b0(b,r);return e=xe(c,q(y)),t=xe(c,q(v)),Lt.debug(`select in complex block: ${y.id}, ${v.id}`),Ul(n,b,e,t)}let u=l?G(n,c):0;c===o&&e instanceof We&&(u=e.offset);let m=l?0:G(n,a);return a===r&&t instanceof We&&(m=t.offset),e=U(c,u,l?"end":"home"),t=U(a,m,l?"home":"end"),{anchor:e,focus:t}}const ly=w("move-complex-block-position");function cy(n,e,t){const o=n.getBlockById(e.blockId);d(ly,ce(n,o),"is not a complex block");const r=Tt(n,o),i=n.getContainerById(e.childContainerId),s=r.getNextContainer(n,o,i,t,{noWrap:!0});return s?xe(o,q(s)):null}const hs=w("move-simple-block-position");function v0(n,e){const t=yt(n,e,{visibleOnly:!0});d(hs,t.length>0,"complex block has not any child container");const o=t[0];return $e(o)}function y0(n,e){const t=yt(n,e,{visibleOnly:!0});d(hs,t.length>0,"complex block has not any child container");const o=t[t.length-1];return Ke(o)}function k0(n,e,t){const o=t?v0(n,e):y0(n,e);return ce(n,o)?k0(n,o,t):o}function ay(n,e){const t=n.getBlockById(e.blockId);return ce(n,t)&&e.offset===0?v0(n,t):rr(t)}function uy(n,e){const t=n.getBlockById(e.blockId);return ce(n,t)&&e.offset===1?y0(n,t):or(t)}function zd(n){return n==="ArrowLeft"||n==="ArrowUp"}function Ud(n,e,t){const o=_(e);if(Ae(o))return null;const r=H(o);d(hs,r,"child container has not parent block"),d(hs,ce(n,r),"is not a complex block");const i=Tt(n,r).getNextContainer(n,r,o,t);return i?zd(t)?Ke(i):$e(i):Ud(n,r,t)}function dy(n,e,t){const o=_(e);if(Ae(o))return null;const r=H(o);if(d(hs,r,"child container has not parent block"),zd(t)){const l=ye(r);if(l)return l}else{const l=fe(r);if(l)return l}const i=Ud(n,r,t);if(i)return i;let s=r;for(;!Ae(_(s));)s=H(_(s));return zd(t)?ye(s):fe(s)}function hy(n,e,t){return!ce(n,e)||Tt(n,e).enableKeyboardSelect?e:k0(n,e,t==="ArrowDown"||t==="ArrowRight")}function fy(n,e,t){const o=n.getBlockById(e.blockId),i=me(n,o).moveCaret(n,o,e,t);if(i)return i;let s=t==="ArrowDown"||t==="ArrowRight"?ay(n,e):uy(n,e);if(s||(s=Ud(n,o,t),s||(s=dy(n,o,t))),!s){if(t==="ArrowDown"||t==="ArrowRight"){if(n.readonly||!Ae(_(o)))return null;const l=n.insertTextBlock("",q(n.rootContainer),Yt(n.rootContainer));return U(l,0,"home")}return null}if(s=hy(n,s,t),$(n,s)){const l=n.selection.getSuggestedCaretX();if(t==="ArrowDown")return jb(n,s,o,e,l);if(t==="ArrowUp")return _b(n,s,o,e,l)}return t==="ArrowLeft"||t==="ArrowUp"?U(s,G(n,s),"end"):t==="ArrowRight"||t==="ArrowDown"?U(s,0,"home"):null}function my(n,e,t){if(e==="ArrowLeft")return t.start;const o=t.end,r=n.getBlockById(o.blockId);if($(n,r))return o;const i=fe(r);if(i)return U(i,0,"home");if(!Ae(_(r))||n.readonly)return o;const s=n.insertTextBlock("",q(n.rootContainer),Yt(n.rootContainer));return U(s,0,"home")}function gy(n,e,t){const o=n.selection.range;let r;if(o instanceof Xe)t==="move"&&!o.isCollapsed()&&(e==="ArrowLeft"||e==="ArrowRight")?r=my(n,e,o):r=fy(n,o.getFocusedPos(),e);else if(r=cy(n,o.focus,e),t==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(e==="ArrowLeft"||e==="ArrowUp"){const l=Ke(s);r=U(l,0,"home")}else{const l=$e(s);r=U(l,G(n,l),"end")}}return r?t==="move"?{anchor:r,focus:r}:dc(n,o.anchor,r):null}function ko(n,e,t){const o=gy(n,e,t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(e==="ArrowLeft"||e==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function w0(n){return ko(n,"ArrowLeft","move"),!0}function B0(n){return ko(n,"ArrowRight","move"),!0}function E0(n){return ko(n,"ArrowUp","move"),!0}function I0(n){if(ko(n,"ArrowDown","move")||n.readonly)return!0;const e=n.getFocusedBlock(),t=_(e);if(Ae(t)||Ke(t)!==e)return!0;const o=n.rootContainer;return n.insertTextBlock("",q(o),Yt(o)),!0}function x0(n){return ko(n,"ArrowDown","select"),!0}function T0(n){return ko(n,"ArrowLeft","select"),!0}function D0(n){return ko(n,"ArrowRight","select"),!0}function S0(n){return ko(n,"ArrowUp","select"),!0}const L0=w("word-offset");function Vd(n,e){const t=n.selection.range.focus;d(L0,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(Ie(n,o))return U(o,0,"home");if(t.offset===0||!$(n,o)){const s=ye(o);if(!s)return null;const l=U(s,G(n,s),"end");if(e==="select"&&$(n,s)){const c=yd(n,s,l.offset);return U(s,c,"normal")}return l}const r=yd(n,o,t.offset);return U(o,r,"normal")}function qd(n,e){const t=n.selection.range.focus;d(L0,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(Ie(n,o))return U(o,0,"end");if(t.offset===G(n,o)||!$(n,o)){const s=fe(o);if(!s)return null;const l=U(s,0,"home");if(e==="select"&&$(n,s)){const c=kd(n,s,l.offset);return U(s,c,"end")}return l}const r=kd(n,o,t.offset);return U(o,r,"normal")}function M0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Vd(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function R0(n){if(!n.selection.range.focus.isSimple())return!1;const t=qd(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function O0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Vd(n,"select");return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function P0(n){if(!n.selection.range.focus.isSimple())return!1;const t=qd(n,"select");return t?(n.selection.setSelection(n.selection.range.anchor,t),n.selection.updateLastCaretRect(),!0):!1}w("find-block");function Wd(n,e){if(!ce(n,e))return e;const o=Tt(n,e).getChildContainers(n,e)[0],i=Me(o)[0];return Wd(n,i)}function Gd(n,e){if(!ce(n,e))return e;const t=Tt(n,e).getChildContainers(n,e),o=t[t.length-1],r=Me(o),i=r[r.length-1];return Gd(n,i)}function F0(n){const e=Gd(n,Ke(n.rootContainer)),t=U(e,G(n,e),"end");return n.selection.setSelection(t),!0}function N0(n){const e=Wd(n,n.getFirstBlock()),t=U(e,0,"home");return n.selection.setSelection(t),!0}function $0(n){const e=Wd(n,n.getFirstBlock()),t=U(e,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}function Zd(n){const e=Gd(n,Ke(n.rootContainer)),t=U(e,G(n,e),"end");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}const _0=w("line-offset");function j0(n){const e=n.selection.range.focus;d(_0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===0||!$(n,t))return U(t,0,"home");let r=sp(t,e).start;const{next:i}=jl(t,r);return i&&Nt(i)&&Zi(i)==="br"&&(r+=1),U(t,r,"home")}function H0(n){const e=n.selection.range.focus;d(_0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===G(n,t)||!$(n,t))return U(t,G(n,t),"end");const o=sp(t,e);return U(t,o.end,"end")}function z0(n){if(!n.selection.range.focus.isSimple())return!1;const t=j0(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function U0(n){if(!n.selection.range.focus.isSimple())return!1;const t=H0(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function V0(n){if(!n.selection.range.focus.isSimple())return!1;const t=j0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function q0(n){if(!n.selection.range.focus.isSimple())return!1;const t=H0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}const W0=w("find-block-position");function py(n,e,t,o){d(W0,ce(n,e),"is not a complex block");const r=Tt(n,e).getChildContainers(n,e);d(W0,r.length>0,"complex block has not any child container");const i=Xt(n,t,o),s=i.left+i.width/2,l=i.top+i.height/2,c=Qg(n,e,s,l);return Qd(n,c,t,o)}function Qd(n,e,t,o){if(ce(n,e))return py(n,e,t,o);const r=z(e);let i=Number.MAX_SAFE_INTEGER;const s=Xt(n,t,o),l=s.left+s.width/2,c=s.top+s.height/2;let a=U(r,0,"home");const u=G(n,e);for(let f=0;f<=u;f++){const m=U(r,f,"normal"),p=Xt(n,e,m),b=vn(p,l,c);b<i&&(i=b,a=m)}return a}const G0=w("page-offset");function Cy(n,e){const t=qp(n)*.9,r=e.getBoundingClientRect().bottom-t;if(r<Hv(n))return n.getFirstBlock();const i=ye(e);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ye(s)}return n.getFirstBlock()}function Ay(n,e){const t=qp(n)*.9,o=e.getBoundingClientRect(),r=zv(n),i=o.top+t;if(i>r)return n.getLastBlock();const s=fe(e);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=fe(l)}return n.getLastBlock()}function Z0(n){const e=n.selection.range.focus;d(G0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=Cy(n,t);let r;return o===n.getFirstBlock()?r=U(o,0,"home"):r=Qd(n,o,t,e),r}function Q0(n){const e=n.selection.range.focus;d(G0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=Ay(n,t);let r;return o===n.getLastBlock()?r=U(o,G(n,o),"end"):r=Qd(n,o,t,e),r}function Y0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Z0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function J0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Q0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function K0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Z0(n);if(!t)return!1;const o=dc(n,n.selection.getAnchorPos(),t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function X0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Q0(n);if(!t)return!1;const o=dc(n,n.selection.getAnchorPos(),t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const fs=w("select-all");function e2(n,e){const t=$e(n),o=Ke(n);return e.start.offset===0&&e.start.blockId===z(t)&&e.end.offset===G(e.getEditor(),o)&&e.end.blockId===z(o)}function by(n,e){const t=e.getEditor(),o=Tt(t,n).getChildContainers(t,n),r=o[0],i=o[o.length-1],s=z(n);return e.start.blockId===s&&e.start.childContainerId===q(r)&&e.end.blockId===s&&e.end.childContainerId===q(i)}function vy(n,e){d(fs,e,"no parent block"),d(fs,ce(n,e),"not a complex block");const t=Tt(n,e).getChildContainers(n,e),o=t[0],r=t[t.length-1];n.selection.setRange(Ge(n,{anchor:xe(e,q(o)),focus:xe(e,q(r))}))}function t2(n,e){const t=_(e);Yd(n,t)}function n2(n){const e=n.getFocusedBlock(),t=n.selection.range;if(t.start.isSimple()){if(t.start.blockId===t.end.blockId&&$(n,e)){const r=t.start,i=t.end,s=G(n,e);if(r.offset>0||i.offset<s)return n.selection.selectBlock(e,0,s),!1}return R(n.rootContainer,"select-all"),t2(n,$e(n.rootContainer)),!1}return d(fs,!t.isSimple(),"invalid range type"),by(e,t)?(t2(n,e),!1):(d(fs,e,"no parent block"),d(fs,ce(n,e),"not a complex block"),vy(n,e),!0)}function Yd(n,e){const t=Me(e),o=t[0],r=t[t.length-1],i=U(o,0,"home"),s=U(r,G(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function o2(n){Zd(n),n.focus()}const Jd=w("selected-block-to-doc");function r2(n,e,t){!e.children||e.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{r2(n,i,t)}),t.blocks[o]=Q.default(r)})}function hc(n,e){const t=me(n,e.block);if(t.selectionToDoc)return t.selectionToDoc(n,e);const o=Q.default(vo(n,e.block));if($(n,e.block)){const i=e.start,s=e.end;if(d(Jd,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(qe(e.block))return{blocks:{root:[o]},meta:{},comments:{}};d(Jd,ce(n,e.block),"not complex block"),d(Jd,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return r2(n,o,r),r}function Kd(n,e){const t=U(e,0,"normal"),o=U(e,G(n,e),"end");return hc(n,{block:e,start:t,end:o})}const yy=w("block-to-doc");function ky(n,e){d(yy,e.length>0,"invalid params, no blocks");const t=e.map(o=>Kd(n,o));return dr(t)}function fc(n){const t=n.selection.range.getSelectedBlocks().map(o=>hc(n,o));return dr(t)}function i2(n,e){const t=n.getContainerById(e),i=Me(t).map(s=>({start:U(s,0,"home"),end:U(s,G(n,s),"end"),block:s})).map(s=>hc(n,s));return dr(i)}const mc=w("editor-selection");class wy{constructor(e){h(this,"editor");h(this,"caret");h(this,"_range");h(this,"lastCaretRect");h(this,"handleBlockDelete",(e,t,o,r)=>{if(o||r.child)return;const i=this.range;if(Zp(t,i)){mc.debug("adjust selection because remote deleted current block");const s=Qp(e,t);this.setRange(s,{noScroll:!0})}});this.editor=e;const t=e.getFirstBlock(),o=z(t);this.caret=new $v(e);const r=U(o,0,"normal");this._range=Ge(e,{anchor:r,focus:r}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const e=this.range.focus;return this.editor.getBlockById(e.blockId)}getStartBlock(){const e=this.range.start;return this.editor.getBlockById(e.blockId)}getEndBlock(){const e=this.range.end;return this.editor.getBlockById(e.blockId)}selectBlock(e,t,o){const r=U(e,t,"normal");let i;o&&(i=U(e,o,"normal")),this.setSelection(r,i)}setSelection(e,t,o){if(t||(t=e),this.verifyPos(e),this.verifyPos(t),!this.selectionChanging(e,t))return this.range;const r=Ge(this.editor,{anchor:e,focus:t});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),ne(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!Wv(this.editor,r))&&j(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(e,t){return this.setSelection(e.anchor,e.focus,t)}updateSelection(){this.caret.update(),_v(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(e,t){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const e=this.range.focus;if(!qn(e))return;const t=this.editor.getBlockById(e.blockId);this.lastCaretRect=Xt(this.editor,t,e)}getSuggestedCaretX(){var e;return(e=this.lastCaretRect)==null?void 0:e.x}scrollIntoView(){qv(this.editor)}verifyPos(e){const t=this.editor.getBlockById(e.blockId);if(e.isSimple())e.offset>=0&&e.offset<=G(this.editor,t)||d(mc,!1,"invalid block position, out of range");else{const o=e.childContainerId;!!this.editor.getContainerById(o)||d(mc,!1,"invalid complex block position, no container found")}}updateFocusedBlock(e){if(e&&this.range.start.blockId===e.start.blockId)return;let t;e&&e.start.blockId===e.end.blockId&&(t=this.editor.findBlockById(e.start.blockId));let o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;t&&ne(t,"focused")&&(j(t,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,t!=null?t:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(e){const t=fc(this.editor);return e==="text"?is(this.editor,t):e==="markdown"?ss(this.editor,t):Jp(this.editor,t)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(e=>{j(e,"focused"),j(e,"child-focused")})}setBlockFocused(e){if(ne(e,"focused"))return!1;R(e,"focused");let t=_(e);for(;en(t);){const o=H(t);d(mc,o,"parent block not found"),R(o,"child-focused"),t=_(o)}return!0}}function By(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);!t||n.selection.selectBlock(t,0,G(n,t))}function Ey(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);if(!t||!$(n,t))return;let o=Vd(n,"select"),r=qd(n,"select");if(!o||!r)return;const i=e.blockId;o.blockId!==i&&(o=U(t,0,"home")),r.blockId!==i&&(r=U(t,G(n,t),"end")),n.selection.setSelection(o,r)}class Iy{constructor(e){h(this,"editor");h(this,"startPos",null);h(this,"lastCaretRect");h(this,"mouseDownEvent",null);h(this,"handleMouseDown",e=>{this.mouseDownEvent=e;const t=Kg(this.editor,e.x,e.y);if(t){if(t instanceof kn)return;const o=this.editor.selection.range;if(e.shiftKey&&o.isSimple()){const r=o.anchor;this.editor.selection.setSelection(r,t.focus),this.startPos=t.start}else this.editor.selection.setSelection(t.anchor,t.focus),this.startPos=t.start;this.editor.selection.updateLastCaretRect()}});h(this,"handleMouseMove",e=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-e.x)<3&&Math.abs(this.mouseDownEvent.y-e.y)<3)return;const t=Vl(this.editor,e.x,e.y);if(!t)return;const o=dc(this.editor,this.startPos,t.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});h(this,"handleMouseUp",e=>{this.startPos=null});this.editor=e,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(e){Ey(this.editor)}handleTripleClick(e){By(this.editor)}}function xy(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function Ty(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const s2=w("delete-text");function l2(n,e,t,o){const r=o!=null?o:n.selection.range.start;r instanceof We||d(s2,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(s2,$(n,s),"block is not a text kind block");let{offset:l}=r;if(e==="backward"){if(l-t<0)return 0;if(!ut(s,l-t)){const c=Co(s,l);t=l-c}}else if(e==="forward"&&l+t>G(n,s))return 0;return e==="backward"&&(l-=t),n.deleteTextFromBlock(s,l,t)}function c2(n,e){if(n.getBlockData(e).quoted){const t={quoted:null};return n.updateBlockData(e,t),!0}return!1}const Dy=w("handle-backspace");function Xd(n,e){if(!Ie(n,e))return;const t=_(e);Yt(t)!==1&&n.deleteBlock(e)}function Sy(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if($(n,o))if(t.offset===0){if(c2(n,o))return;const r=ye(o);if(r){if(!n.isBlockWritable(r))return;if($(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(ce(n,r)){Xd(n,o);const i=jr(n,r);i?n.selection.selectBlock(i,G(n,i)):n.selection.selectBlock(r,0,G(n,r))}else Xd(n,o),d(Dy,qe(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=_(o);if(en(i)){const s=Wg(n,i);if(s){if(!n.isBlockWritable(s))return;Xd(n,o),n.selection.selectBlock(s,G(n,s))}}}}else l2(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=K(o),i=_(o);n.insertTextBlock("",q(i),r),n.deleteBlock(o)}}function Ly(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if($(n,o))if(t.offset===G(n,o)){const r=fe(o);if(r){if(!n.isBlockWritable(r))return;$(n,r)?n.mergeTextBlock(o,r,{focus:!0}):Ie(n,o)?n.deleteBlock(o,Fe(n,r,0)):n.deleteBlock(r)}}else l2(n,"forward",1,null);else{const r=K(o),i=_(o);n.insertTextBlock("",q(i),r),n.deleteBlock(o)}}function My(n){const{range:e}=n.selection,{start:t,end:o}=e,r=n.getBlockById(t.blockId),i=n.getBlockById(o.blockId);if(r!==i||!ce(n,r))return!1;if(qn(t))return!0;const s=sr(n,r,t,o),l=yt(n,r);return s.length===l.length}function Ry(n,e){if(My(n)){const o=n.getFocusedBlock(),r=K(o),i=q(_(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const t=n.getFocusedBlock();if($(n,t)){if(Ie(n,t)&&c2(n,t))return;const o=n.selection.range.start,r=n.breakTextBlock(t,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function Oy(n,e){const t=n.selection.range.getSelectedBlocks()[0],{block:o}=t;if(!$(n,o))return!1;const r=t.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:N(),box:!0,created:Date.now()}),!0}const Py=w("input-handler-actions");function Fy(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Ry(n),!0))}function Ny(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Ly(n),!0))}function $y(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Sy(n),!0))}function _y(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Oy(n),!0))}function jy(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(e=>{n.input.handlePasteText(e)}).catch(e=>{Py.error(e)}),!0)}const gc={ArrowDown:I0,ArrowUp:E0,ArrowLeft:w0,ArrowRight:B0,"Shift+ArrowDown":x0,"Shift+ArrowUp":S0,"Shift+ArrowLeft":T0,"Shift+ArrowRight":D0,"CtrlOrCmd+ArrowLeft":M0,"CtrlOrCmd+ArrowRight":R0,"CtrlOrCmd+Shift+ArrowLeft":O0,"CtrlOrCmd+Shift+ArrowRight":P0,"CtrlOrCmd+ArrowUp":N0,"CtrlOrCmd+ArrowDown":F0,"CtrlOrCmd+Shift+ArrowUp":$0,"CtrlOrCmd+Shift+ArrowDown":Zd,"CtrlOrCmd+A":n2,Home:V0,End:q0,"Shift+Home":z0,"Shift+End":U0,PageUp:Y0,PageDown:J0,"Shift+PageUp":K0,"Shift+PageDown":X0,"CtrlOrCmd+Z":xy,"CtrlOrCmd+Shift+Z":Ty,Enter:Fy,Delete:Ny,Backspace:$y,"Shift+Enter":_y,"CtrlOrCmd+Shift+V":jy};function a2(n,e){return n.shortcuts.handleKeyboardEvents(n,e)!==void 0}function u2(n,e,t){if(e.type==="embed"){const i=e.embedData,s=i.src;if(s&&typeof s=="string"){const l=t.get(s);l&&(i.src=l)}return}const o=e.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=t.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=e.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{u2(n,l,t)})})}function d2(n,e,t){if(t.size===0)return;e.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,t):u2(e,r,t)})}async function Hy(n,e){const t=e.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(t),r=new Map;if(t.length!==o.length)return r;for(let i=0;i<t.length;i++)r.set(t[i],o[i]);return r}function zy(n,e){var i,s;const o=e.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function Uy(n,e){const o=e.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(zy(n,e)){const s=Array.from(Object.keys(o));r=await Hy(n,s),d2(n,e,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&d2(n,e,i)}async function Vy(n,e,t){await Uy(n,e),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&qe(i)){const s=_(i),l=n.getBlockIndex(i),[c]=n.insertDocAt(s,l+1,e,t);c&&n.selection.selectBlock(c,G(n,c))}else{n.clearSelectedContents();const{block:s,offset:l}=Ur(n);n.insertDoc(s,l,e,t)}})}const qy=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function Wy(n){let e;for(const t of qy)if(e=n[t],e)break;return e||null}function h2(n,e,t){if(e.type==="embed"){const s=e.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))t.add(l);return}const o=e.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&t.add(i.attributes.src)});const r=e.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{h2(n,l,t)})})}function Gy(n,e){const t=new Set;return e.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{t.add(s)}):h2(e,r,t)}),Array.from(t)}function pc(n,e){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Ko(JSON.stringify(e))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Cc(n,e){var i,s,l;const t=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=Gy(n,e),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),e.meta={...t,resources:r}}function Zy(n,e,t){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;let o=fc(n);const r=t==null?void 0:t(n,e,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Cc(n,o);const i=ic(n,o),s=ss(n,o),l=pc(i,o);e.clipboardData.setData("text/html",l),e.clipboardData.setData("text/plain",s),e.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Ac(n,e){const t=Kd(n,e);Cc(n,t);const o=ic(n,t),r=ss(n,t),i=pc(o,t);return Su([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class Qy{constructor(e){h(this,"editor");h(this,"handlers",[]);h(this,"onPasteText",async e=>{const t=new DataTransfer;t.setData("text/plain",e);const o=await this.editor.dataConverter.fromData(this.editor,t);o&&this.pasteDocs(o,null)});this.editor=e}onInsertText(e,t){if(!$(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Ur(this.editor);this.handleBeforeInsertText(o,r,i,t)||(this.defaultInsertText(this.editor,o,r,i,t),this.handleAfterInsertText(o,r,i,t),this.editor.selection.updateLastCaretRect())}onKeyDown(e){if(this.handleBeforeKeyDown(e))return!0;const t=this.defaultHandleKeydown(this.editor,e);return this.handleAfterKeyDown(e)?!0:t}onChanged(e){for(let t=0;t<this.handlers.length;t++){const o=this.handlers[t];o.handleChanged&&o.handleChanged(this.editor,e)}}onRemoteChanged(e){for(let t=0;t<this.handlers.length;t++){const o=this.handlers[t];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,e)}}onCompositionStart(e){this.editor.updateCompositionText("",!1);const{containerId:t,blockIndex:o,offset:r}=Ur(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,t,o,r)}}onUpdateCompositionText(e,t,o){this.editor.updateCompositionText(t,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=Ur(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(e){Zy(this.editor,e,(t,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,e)===!0)return}if(this.onCopy(e),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;qe(o)&&this.editor.deleteBlock(o)}else Fd(this.editor)}onPaste(e){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;this.editor.dataConverter.fromData(this.editor,e.clipboardData).then(async o=>{o&&this.pasteDocs(o,e)})}onFocus(){R(this.editor.rootElement,"active")}onBlur(){j(this.editor.rootElement,"active")}addHandler(e){this.handlers.push(e)}removeHandler(e){const t=this.handlers.indexOf(e);t!==-1&&this.handlers.splice(t)}handleBeforeInsertText(e,t,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,e,t,o,r))return!0}return!1}handleAfterInsertText(e,t,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,e,t,o,r))return!0}return!1}handleBeforeKeyDown(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,e))return!0}const t=this.defaultHandleKeydown(this.editor,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,e))return!0}return t}handleAfterKeyDown(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,e))return!0}const t=this.defaultHandleKeydown(this.editor,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,e))return!0}return t}defaultInsertText(e,t,o,r,i){Sd(this.editor,i)}defaultHandleKeydown(e,t){return a2(this.editor,t)?(t.preventDefault(),t.stopPropagation(),!0):!1}async pasteDoc(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,e))return}const t={blockIdMap:new Map,containerIdMap:new Map};await Vy(this.editor,e,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,e,t))return}}async pasteDocs(e,t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,t,e))return}const o=Wy(e);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,t,e))return}}}destroy(){this.handlers.forEach(e=>{var t;(t=e.destroy)==null||t.call(e,this.editor)}),this.handlers=[]}}function Yy(n,e,t){const o=Fr(e,t);return o.remove(),o}w("copy-dom-attributes");const f2=["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 Jy(n,e){for(let l=0;l<f2.length;l++){const c=f2[l];e[c]=n[c]}const t=n.attributes,o=e.attributes,r=[],i=[];for(let l=0;l<t.length;l++){const c=t[l],a=o.getNamedItem(c.name);a?a.value!==c.value&&(a.value=c.value,i.push(c)):r.push(c)}const s=[];for(let l=0;l<o.length;l++){const c=o[l];t.getNamedItem(c.name)||s.push(c)}r.forEach(l=>{e.setAttribute(l.name,l.value)}),i.forEach(l=>{e.setAttribute(l.name,l.value)}),s.forEach(l=>{e.removeAttribute(l.name)})}function m2(n){const e=Array.from(n.childNodes).filter(t=>!lg(t));return e.forEach(t=>{t.remove()}),e}function g2(n,e,t){var a;const o=n.getContainerById(e),r=Fr(o,t),i=fo(r),s=n.doc.getBlockData(e,t),l=me(n,r);if((a=l==null?void 0:l.handleUpdateBlock)==null?void 0:a.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const u=n.editorBlocks.createBlock(i,o,s),f=m2(u);m2(r),f.forEach(p=>{r.appendChild(p)});const m=$l(u);if(m){const p=$l(r);p&&p.remove(),r.appendChild(m)}Jy(u,r)}Eg(n,r,s),n.blockHooks.forEach(u=>{var f;(f=u.update)==null||f.call(u,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const Ky=w("transform-selection");function p2(n,e,t,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==e&&s.blockId!==e)return r;d(Ky,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===e){const a=dt.transformCursor(i.offset,t,o);l=U(e,a,"normal")}let c=s;if(s.blockId===e){const a=dt.transformCursor(s.offset,t,o);c=U(e,a,"normal")}return Ge(n,{anchor:l,focus:c})}const Xy=w("handle-block-text-changed");function ek(n,e,t,o,r){const i=n.getContainerById(e),s=Fr(i,t),l=n.doc.getBlockData(e,t);if(d(Xy,l.text,"no block text"),bg(n,s).setBlockText(n,s,l.text),!r){const c=p2(n,l.id,o,r);n.selection.setRange(c,{noScroll:!0})}}function tk(n,e){const t=Q.default(n);return e.delete.forEach(r=>{delete t[r]}),{...t,...e.insert}}function C2(n,e,t,o){const r=me(n,e);r.handleDeleteBlock&&r.handleDeleteBlock(n,e,t,o),n.emit("blockDeleted",n,e,t,o)}function nk(n,e,t,o){const r=n.getBlockByIndex(e,t);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{C2(n,i,o,{child:!0})}),C2(n,r,o,{child:!1})}const rn=w("editor-doc");class ok extends zi{constructor(t,o,r){super();h(this,"localEvents",[]);this.editor=t,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(t){this.localEvents.push(t)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(t){return this.externalDoc.getContainerBlocks(t)}getBlockData(t,o){return this.externalDoc.getBlockData(t,o)}verifyBlockWritable(t,o){const r=this.editor.getBlockByIndex(t,o);d(rn,this.editor.isBlockWritable(r),`block is not writable, ${t}, ${o}`)}localUpdateBlockText(t,o,r,i){d(rn,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const s=this.getBlockData(t,o),l=s.text;d(rn,l,`no text, ${t}, ${o}`);const c=p2(this.editor,s.id,r,!0),a=dt.apply(l,r);this.localEvents.forEach(f=>f.onBeforeUpdateBlockText(t,s.id,l,a,c.toDocRange()));const u=this.externalDoc.localUpdateBlockText(t,o,r);return this.editor.selection.setRange(c,i),u}localUpdateBlockData(t,o,r,i){d(rn,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(t,o);if(!this.editor.isBlockWritable(s)){const u=Array.from(r.delete).filter(m=>m!=="comments"),f=Object.keys(r.insert).filter(m=>m!=="comments");(u.length>0||f.length>0)&&d(rn,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=Q.default(this.getBlockData(t,o)),c=Q.default(tk(l,r));this.localEvents.forEach(u=>u.onBeforeUpdateBlockData(t,l.id,l,c,i));const a=this.externalDoc.localUpdateBlockData(t,o,r,i);return this.editor.selection.setRange(mo(this.editor,i)),a}localInsertBlock(t,o,r,i,s){d(rn,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(t,o,r,i));const l=this.externalDoc.localInsertBlock(t,o,r,i);return this.editor.selection.setRange(mo(this.editor,i),s),l}localDeleteBlock(t,o,r){d(rn,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const i=Q.default(this.getBlockData(t,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(t,o,i,r));const s=this.externalDoc.localDeleteBlock(t,o,r);return this.editor.selection.setRange(mo(this.editor,r)),s}localDeleteChildContainers(t){return d(rn,!this.editor.readonly,"editor is readonly"),t.forEach(o=>{const r=Q.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(t)}localInsertChildContainer(t,o){return d(rn,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(t,Q.default(o))),this.externalDoc.localInsertChildContainer(t,o)}onRequestReload(t){rn.debug(`reload doc: ${t}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,t)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(t,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,t,o,r,i)}),ek(this.editor,t,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(t,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,t,o,r,i)}),g2(this.editor,t,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(t,o,r,i){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,t,o,r,i)});const s=this.editor.getContainerById(t);qA(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(t,o,r){nk(this.editor,t,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,t,o,r)});const i=this.editor.getContainerById(t);Yy(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(t,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,t,o,r)})}onDeleteChildContainer(t,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,t,o)})}onCustomMessage(t){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,t)})}onStatusChanged(t){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,t)})}onError(t){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,t)})}uploadResource(t,o){return this.externalDoc.uploadResource(t,o)}addResources(t){return this.externalDoc.addResources(t)}buildResourceUrl(t,o){return this.externalDoc.buildResourceUrl(t,o)}request(t,o){return this.externalDoc.request(t,o)}broadcastMessage(t){return this.externalDoc.broadcastMessage(t)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var t,o,r;return(r=(o=(t=this.externalDoc).getServerMeta)==null?void 0:o.call(t))!=null?r:{}}reset(t){rn.log("reset doc"),this.externalDoc=t,this.externalDoc.registerCallback(this),this.editor.reload()}}function A2(n,e){if(n.length===0){n.push(e);return}const t=n[n.length-1];if(!t.combinable(e)){n.push(e);return}t.combine(e)}const eh=w("undo-action");class Gr{constructor(e,t,o){h(this,"beforeRange");h(this,"afterRange");this.containerId=t,this.beforeRange=e.selection.range.clone().toDocRange(),this.afterRange=o}undo(e){return!1}redo(e){return!1}combinable(e){return d(eh,e,"no other action"),!1}combine(e){d(eh,!1,"no other")}setAfterRange(e){this.afterRange&&eh.warn("after range has already set"),this.afterRange=e}}const rk=w("block-action");class b2 extends Gr{constructor(t,o,r,i,s){super(t,o,s);h(this,"blockData");h(this,"blockIndex");this.blockData=Q.default(i),this.blockIndex=r}deleteBlock(t,o){if(!t.getContainerById(this.containerId))return!1;const i=t.getBlockById(this.blockData.id);return i?(d(rk,this.blockIndex===K(i),"invalid block index"),Rd(t,i,mo(t,o)),!0):!1}insertBlock(t,o){return Vr(t,this.containerId,this.blockIndex,Q.default(this.blockData),o),!0}}class ik extends b2{undo(e){return this.deleteBlock(e,this.beforeRange)}redo(e){return this.insertBlock(e,this.afterRange)}}class sk extends b2{undo(e){return this.insertBlock(e,this.beforeRange)}redo(e){return this.deleteBlock(e,this.afterRange)}}class lk extends Gr{constructor(t){super(t,q(t.rootContainer),t.selection.range.toDocRange());h(this,"actions",[])}addAction(t){A2(this.actions,t),this.afterRange=t.afterRange}undo(t){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(t)&&(o=!0)}),o}redo(t){let o=!1;return this.actions.forEach(r=>{r.redo(t)&&(o=!0)}),o}setAfterRange(t){this.afterRange=t;const o=this.actions[this.actions.length-1];!o||o instanceof Gr&&(o.afterRange||o.setAfterRange(t))}}const hr=w("update-block-data-action");class bc extends Gr{constructor(t,o,r,i,s,l){super(t,o,l);h(this,"beforeBlockData");h(this,"afterBlockData");h(this,"blockId");this.blockId=r,d(hr,this.blockId===i.id,"invalid block id"),d(hr,this.blockId===s.id,"invalid block id"),this.beforeBlockData=Q.default(i),this.afterBlockData=Q.default(s),d(hr,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(t){d(hr,t,"no editor");const o=t.getBlockById(this.blockId);if(!o)return!1;const r=t.getContainerById(this.containerId);return d(hr,r,"no container"),uc(t,o,bc.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(t){d(hr,t,"no editor");const o=t.getBlockById(this.blockId);if(!o)return!1;const r=t.getContainerById(this.containerId);return d(hr,r,"no container"),uc(t,o,bc.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(t){const o=Q.default(t);return delete o.id,delete o.type,o}}const th=w("update-block-text-action");class ms extends Gr{constructor(t,o,r,i,s,l){super(t,o,l);h(this,"beforeRichTextData");h(this,"afterRichTextData");h(this,"blockId");h(this,"type");this.blockId=r,this.beforeRichTextData=Q.default(i),this.afterRichTextData=Q.default(s),this.type=ms.calType(i,s)}static calType(t,o){d(th,t,"no old data"),d(th,o,"no new data");const i=dt.diff(t,o),s=new Set;let l=!1;const c=u=>jm(u)?`cjk_${u}`:$m(u)?"number":Ll(u)?"space":_m(u)?"letter":"unknown";let a=!1;return i.forEach(u=>{u.insert?u.insert===" "?s.add("insert_letter"):typeof u.insert=="string"&&u.insert.startsWith(" ")&&u.insert.length>1?(l=!0,a=!0,s.add(`insert_${c(u.insert.substr(1))}`)):s.add(`insert_${c(u.insert)}`):u.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:a}}undo(t){if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(ac(t,r,this.beforeRichTextData),!0):!1}redo(t){if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(ac(t,r,this.afterRichTextData),!0):!1}combinable(t){if(!(t instanceof ms)||t.type.begin||this.type.textType!==t.type.textType||t.blockId!==this.blockId)return!1;const o=t.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(t){d(th,t instanceof ms,"invalid action type");const o=t;this.afterRichTextData=o.afterRichTextData,this.afterRange=t.afterRange}}class v2 extends Gr{constructor(e,t,o){super(e,t,e.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(e){return e.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(e){return e.doc.localInsertChildContainer(this.containerId,Q.default(this.blocks)),!0}}class ck extends v2{undo(e){return this.deleteChildContainer(e)}redo(e){return this.insertChildContainer(e)}}class ak extends v2{undo(e){return this.insertChildContainer(e)}redo(e){return this.deleteChildContainer(e)}}const sn=w("undo");class uk{constructor(e){h(this,"editor");h(this,"actions",[]);h(this,"undoCursor");h(this,"currentGroup",null);h(this,"groupCounter",0);h(this,"undoRedoing",!1);h(this,"handleSelectionChange",e=>{if(this.currentGroup){this.currentGroup.setAfterRange(e.selection.range.toDocRange());return}const t=this.actions[this.actions.length-1];!t||t.afterRange||t.setAfterRange(e.selection.range.toDocRange())});this.editor=e,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(e){this.currentGroup?this.currentGroup.addAction(e):(A2(this.actions,e),setTimeout(()=>{this.editor.input.handleChanged(e)}))}beginGroup(){this.groupCounter===0?(d(sn,!this.currentGroup,"current group already exists"),this.currentGroup=new lk(this.editor),this.groupCounter=1):(d(sn,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(sn,this.currentGroup,"current group not exists"),d(sn,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?sn.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(e){this.beginGroup();try{const t=e();return setTimeout(()=>this.editor.selection.caret.update()),t}catch(t){throw sn.error(`failed to run action: ${t.message}`),t}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const e=this.actions[this.undoCursor];if(e.undo(this.editor)){try{this.editor.selection.setRange(mo(this.editor,e.beforeRange))}catch(t){sn.error(`undo: failed to restore caret pos: ${t.message}`)}return this.editor.input.handleChanged(e),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const e=this.actions[this.undoCursor];if(this.undoCursor+=1,e.redo(this.editor)){try{const t=e.afterRange;t?this.editor.selection.setRange(mo(this.editor,t)):sn.warn("no after range")}catch(t){sn.error(`redo: failed to set caret pos after redo: ${t.message}`)}return this.editor.input.handleChanged(e),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var t;const e=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(t=this.actions[e])!=null?t:null}undoTo(e){for(;;){const t=this.lastAction();if(!t||t===e)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(e,t,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),dt.diff(o,r).length!==0&&this.addAction(new ms(this.editor,e,t,o,r,i)))}onBeforeUpdateBlockData(e,t,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new bc(this.editor,e,t,o,r,i);this.addAction(s)}onBeforeInsertBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(sn,t>=0,"invalid block index"),d(sn,o,"no block data"),this.addAction(new ik(this.editor,e,t,o,r)))}onBeforeDeleteBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new sk(this.editor,e,t,o,r)))}onBeforeInsertChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new ck(this.editor,e,t)))}onBeforeDeleteChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new ak(this.editor,e,t)))}}class dk{async fromData(e,t){const o=t.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class hk{constructor(){h(this,"converters",[]);this.addConverter(new dk)}async fromData(e,t){let o={};for(const r of this.converters){const i=await r.fromData(e,t);i&&(o={...o,...i})}return o}addConverter(e){this.converters.push(e)}}class fk{constructor(e){h(this,"renders",[]);this.editor=e}registerRender(e){this.renders.push(e)}renderText(e,t){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,e,t);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(e,t,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,t,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(e,t,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,e,t,o,r)})}}class Se extends Ve.TypedEmitter{constructor(t){super();h(this,"hoveringBlock",null);h(this,"hoveringTextChild",null);h(this,"filters",[]);h(this,"finders",[]);h(this,"handleDocumentMouseMove",t=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,t))return}const o=document.elementFromPoint(t.x,t.y);if(!o){this.setHoveringBlock(null,t,null);return}let r=H(o);if((!r||!Ce(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(t),!r)){this.setHoveringBlock(null,t,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,t,i)});this.editor=t,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(t=>t.destroy()),this.filters=[],this.finders.forEach(t=>t.destroy()),this.finders=[]}addFilter(t){this.filters.push(t)}addFinder(t){this.finders.push(t)}hoveringBlockId(){return this.hoveringBlock?z(this.hoveringBlock):""}findBlockByFinders(t){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,t);if(i)return i}return null}setHoveringBlock(t,o,r){if(this.hoveringBlock===t&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==t){const s=this.hoveringBlock&&Ce(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&j(s,"hover"),t&&R(t,"hover"),this.hoveringBlock=t,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(t){return t.addCustom("standard-hovering-block",()=>new Se(t))}getParentTextContentChild(t,o){if(!$(this.editor,t))return null;const r=le(t);return o.parentElement===r?o:$u(o)}}const y2="style-color-",k2="style-bg-color-";class mk{renderText(e,t,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,c])=>{c===!0?l.startsWith(y2)?i["data-style-color"]=l.substring(y2.length):l.startsWith(k2)?i["data-style-bg-color"]=l.substring(k2.length):l.startsWith("style")&&r.push(l):typeof c=="string"&&(l==="link"&&(r.push("link"),i.link=c),l==="inline-style-color"&&(s.color=c))}),{classes:r,attributes:i,styles:s}}renderBlock(e,t,o){var l,c;const r={};Object.entries(o).filter(a=>a[0].startsWith("style-")).forEach(([a,u])=>{r[`data-${a}`]=`${u}`});const s=[];return((c=(l=e.selection)==null?void 0:l.range)==null?void 0:c.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"),Se.get(e).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(e,t,o,r){var s,l;Array.from(o.attributes).forEach(c=>{c.name.startsWith("data-style-")&&o.removeAttribute(c.name)}),Object.entries(r).filter(c=>c[0].startsWith("style-")).forEach(([c,a])=>{o.setAttribute(`data-${c}`,`${a}`)}),((l=(s=e.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&R(o,"focused"),Se.get(e).hoveringBlockId()===r.id&&R(o,"hover")}}function gk(n){n.editorBlocks.registerBlockClass(wt),n.editorBlocks.registerBlockClass(qg),n.editorBoxes.registerBoxClass(Op),n.editorBoxes.registerBoxClass(Pp),n.editorBoxes.registerBoxClass($p),n.editorBoxes.registerBoxClass(_p),n.editorInsertions.registerInsertionClass(jp),n.editorBlockRenders.registerRender(new mk)}function pk(n,e){gk(n),e!=null&&e.blocks&&e.blocks.forEach(t=>n.editorBlocks.registerBlockClass(t)),e!=null&&e.boxes&&e.boxes.forEach(t=>n.editorBoxes.registerBoxClass(t)),e!=null&&e.embeds&&e.embeds.forEach(t=>n.editorEmbeds.registerEmbedClass(t)),e!=null&&e.insertions&&e.insertions.forEach(t=>n.editorInsertions.registerInsertionClass(t)),e!=null&&e.decorators&&e.decorators.forEach(t=>n.editorDecorators.registerDecorator(t)),e!=null&&e.dataConverters&&e.dataConverters.forEach(t=>n.dataConverter.addConverter(t)),e!=null&&e.commandProviders&&e.commandProviders.forEach(t=>n.editorCommandProviders.registerCommandProvider(t)),e!=null&&e.textRenders&&e.textRenders.forEach(t=>n.editorBlockRenders.registerRender(t))}const w2=w("range-commands");function B2(n,e){n.forEach(t=>{t.source=e,t.children&&B2(t.children,e)})}function E2(n,e,t){const o=z(e);d(w2,o===t.start.blockId,"invalid start range"),d(w2,o===t.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,e,t);B2(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,e,t,i);l&&(i=l)}}),ce(n,e)&&sr(n,e,t.start,t.end).forEach(l=>{Me(l).forEach(a=>{const u=G(n,a),f=Ge(n,{anchor:U(a,0,"home"),focus:U(a,u,"end")}),m=E2(n,a,f);i.push(...m)})}),i}function I2(n){const e=n.getEditor(),t=n.getSelectedBlocks(),o=[];return t.forEach(r=>{const i=Ge(e,{anchor:r.start,focus:r.end});E2(e,r.block,i).forEach(l=>{o.push(l)})}),o}function x2(n,e,t,o,r,i){var u;const s=n.editorCommandProviders.getCommandProviders();for(let f=0;f<s.length;f++){const m=s[f];if(m.beforeExecuteCommand&&m.beforeExecuteCommand(n,e,t,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),c={};if((u=l.executeCommand)!=null&&u.call(l,n,e,t,o,r,{}))return i[z(e)]=c,!0;let a=!1;return ce(n,e)&&sr(n,e,t.start,t.end).forEach(m=>{Me(m).forEach(b=>{const y=G(n,b),v=Ge(n,{anchor:U(b,0,"home"),focus:U(b,y,"end")});x2(n,b,v,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,e,t,o,r,i)}),a}function T2(n,e,t){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(e.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,e,t,r)||n.getSelectedBlocks().forEach(l=>{const c=Ge(o,{anchor:l.start,focus:l.end});x2(o,l.block,c,e,t,r)}),r}const Ck=w("command-providers");class D2{constructor(e){h(this,"providers",[]);this.editor=e}registerCommandProvider(e){this.providers.push(e)}getCommandProviders(){return this.providers}getCommandProvider(e){const t=this.providers.find(o=>o.id===e);return d(Ck,t,`no command provider, id=${e}`),t}getCommands(e){return I2(e)}executeCommand(e,t,o){return this.editor.undoManager.runInGroup(()=>T2(e,t,o))}getEmptyBlockTextAttributes(e,t){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,e,t);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function Ak(n,e){const t=_(e),o=q(t),r=K(e);g2(n,o,r)}const bk=w("table-scroll");class S2{constructor(e,t,o,r,i){h(this,"handleEvent",e=>{this.handler(this.editor,e,this.data)});this.editor=e,this.dom=t,this.name=o,this.handler=r,this.data=i,t.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class vk{constructor(e){h(this,"handlers",new Map);this.editor=e}destroy(){Array.from(this.handlers.entries()).forEach(([e,t])=>{t.forEach(o=>o.destroy()),this.handlers.delete(e)})}addEventListener(e,t,o,r){const i=this.handlers.get(e);if(i){if(i.find(s=>s.handler===o&&s.name===t)){bk.warn(`event has already registered: ${t}`);return}i.push(new S2(this.editor,e,t,o,r))}else{const s=new S2(this.editor,e,t,o,r);this.handlers.set(e,[s])}}removeEventListener(e,t,o){if(!e){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(t)t===c.name&&o===c.handler&&s.splice(l,1);else if(o===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(e);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===t);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(e)}}}removeAllListeners(e,t){const o=this.handlers.get(e);if(o)if(t)for(let r=0;r<o.length;r++){const i=o[r];i.name===t&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(e)}}const L2=w("update-block-text");function yk(n,e){const t=n.getBoxById(e.id),o=H(t);d(L2,o,"no parent block"),d(L2,$(n,o),"not a text block");const r=n.getBlockText(o),i=Ep(r,"id",e.id,e);a0(n,o,i)}function kk(n,e){for(const t of n.blockHooks)if(t.writable){const o=t.writable(n,e);if(typeof o=="boolean")return o}return!0}function wk(n){return n.readonly?!1:!nn(n).find(o=>!n.isBlockWritable(o.block))}class Bk{constructor(e){this.editor=e}getKey(e){return`${this.editor.id}-${e}`}getItem(e){return window.localStorage.getItem(this.getKey(e))}setItem(e,t){if(!t){this.removeItem(e);return}window.localStorage.setItem(this.getKey(e),t)}removeItem(e){window.localStorage.removeItem(this.getKey(e))}}class Ek{constructor(){h(this,"shortcuts",[])}handleKeyboardEvents(e,t){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(Hn(t,s)){const c=l(e,t);if(c!==void 0)return c}}}}const Qn=w("editor");class Ik extends Ve.TypedEmitter{constructor(t,o,r){var i,s,l,c,a,u,f;super();h(this,"parent");h(this,"rootElement");h(this,"contentElement");h(this,"rootContainerObject");h(this,"rootContainer");h(this,"input");h(this,"selection");h(this,"selectionHandler");h(this,"doc");h(this,"id");h(this,"clientId");h(this,"compositingText","");h(this,"undoManager");h(this,"shortcuts",new Ek);h(this,"dataConverter",new hk);h(this,"editorBlocks",new Hg(this));h(this,"editorBoxes",new Np(this));h(this,"editorInsertions",new zp(this));h(this,"editorEmbeds",new Ug(this));h(this,"editorDecorators",new Up(this));h(this,"editorCommandProviders",new D2(this));h(this,"editorBlockRenders",new fk(this));h(this,"blockHooks",[]);h(this,"domEvents",new vk(this));h(this,"customs",new Map);h(this,"options");h(this,"inputHandlers",new Qy(this));h(this,"settingsProvider");h(this,"_readonly",!1);Qn.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=(c=r==null?void 0:r.settingsProvider)!=null?c:new Bk(this),pk(this,r==null?void 0:r.components),this.blockHooks.push(...(u=(a=r==null?void 0:r.components)==null?void 0:a.blockHooks)!=null?u:[]),this.id=(f=r==null?void 0:r.id)!=null?f:N(),this.clientId=N(),this.undoManager=new uk(this),this.doc=new ok(this,o,this.undoManager),this.parent=t,this.rootElement=A("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=A("div",["editor-content"],this.rootElement),this.rootContainerObject=$g(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new Nv(this,this.inputHandlers),this.selection=new wy(this),this.selectionHandler=new Iy(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),ot.isMobile&&R(this.rootElement,"mobile"),ot.isSafari&&R(this.rootElement,"safari"),this._readonly&&R(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(t){this._readonly=t,t?R(this.rootElement,"readonly"):j(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:Qt(this.rootContainer)}addCustom(t,o){const r=this.customs.get(t);if(r)return r;const i=o(this);return this.customs.set(t,i),i}getCustom(t){const o=this.customs.get(t);return d(Qn,o,`${t} does not exists`),o}replaceCustom(t,o){const r=this.customs.get(t);return r&&r.destroy(),this.customs.set(t,o),o}findCustom(t){return this.customs.get(t)}findCustomByType(t){const o=this.customs.values();for(const r of o)if(r instanceof t)return r;return null}destroyCustom(t){const o=this.customs.get(t);o&&(this.customs.delete(t),o.destroy())}getComponentOptions(t){return this.options.componentsOptions[t]}registerLocalEvents(t){this.doc.registerLocalEvents(t)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(t,o,r){return this.editorBlocks.createBlock(t,o,r)}createBox(t,o){return this.editorBoxes.createBox(t,o)}createInsertion(t,o){return this.editorInsertions.createInsertion(t,o)}destroy(){Qn.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(t=>t.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(t,o){Nd(this,t,o)}isWritable(){return wk(this)}isBlockWritable(t){return kk(this,t)}getChildContainerData(t){const o=this.doc.getContainerBlocks(t);return d(Qn,o,`no child container data: ${t}, ${JSON.stringify(this.doc)}`),d(Qn,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(t,o,r){return _g(this,t,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const t=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return t[t.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&d(Qn,er(o),"not an valid block element"),o!=null?o:null}findBoxById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&d(Qn,Nu(o),"not an valid box element"),o!=null?o:null}getBlockById(t){const o=this.findBlockById(t);return d(Qn,o,`no block, id=${t}`),o}getBoxById(t){const o=this.findBoxById(t);return d(Qn,o,`no box, id=${t}`),o}getBlockByIndex(t,o){const r=this.getContainerById(t);return Fr(r,o)}getBlockIndex(t){if(typeof t=="string"){const o=this.getBlockById(t);return K(o)}return K(t)}getContainerById(t){return _r(this,t)}getParentContainer(t){return _(t)}reloadBlock(t){Ak(this,t)}contains(t){const o=t instanceof Element?t:t.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(t,o,r,i,s){const l={blockId:r.id,offset:0},c={anchor:l,focus:l};return Vr(this,t,o,r,i!=null?i:c,s)}insertEmbed(t,o,r,i,s){const l={id:N(),type:"embed",embedType:r,embedData:i};return this.insertBlock(t,o,l,s)}deleteBlock(t,o){Od(this,t,o)}mergeTextBlock(t,o){return s0(this,t,o)}breakTextBlock(t,o,r){return qr(this,t,o,r).newBlock}getTextPosition(){return Ur(this)}getBlockString(t,o){const r=this.getBlockText(t);return ve(r,o)}getBlockData(t){return vo(this,t)}getBoxData(t){return Mp(this,t)}getBlockText(t){return pt(this,t)}setBlockText(t,o){a0(this,t,o)}deleteTextFromBlock(t,o,r,i){return Ld(this,t,o,r,i)}insertTextToBlock(t,o,r,i){return Xp(this,t,o,r,i)}insertBoxToBlock(t,o,r){return e0(this,t,o,r)}pasteDoc(t){return this.inputHandlers.pasteDoc(t)}insertDoc(t,o,r,i){h0(this,t,o,r,i)}insertDocAt(t,o,r,i){return jd(this,t,o,r,i)}deleteChildContainers(t){i0(this,t)}replaceBlockText(t,o){return ac(this,t,o)}updateBlockData(t,o,r){const i={...this.getBlockData(t),...o},{id:s,type:l,...c}=i;return uc(this,t,c,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(t,o,r){return u0(this,t,o,r)}updateBoxData(t){yk(this,t)}getSelectedText(){const t=fc(this);return is(this,t)}clearSelectedContents(){Fd(this)}insertTextBlock(t,o,r,i){const s=Gn(t!=null?t:"");return r0(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(t,o){if(t&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!t&&!o){n0(this);return}o?(this.compositingText="",wu()||Sd(this,t)):(this.compositingText=t,t0(this))}getColor(t){const o=this.options.colors;return o.length===0?"#FF1A75":o[t%o.length]}}function gs(n,e,t){return new Ik(n,e,t)}function xk(n){const e=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=du.default(s.states,r.states)}},t=[];return n.forEach(o=>{o.forEach(r=>{e(t,r)})}),t}const Tk=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class vc extends Ve.TypedEmitter{constructor(t){super();h(this,"users",new Map);h(this,"cursors",new Map);h(this,"addingUser",!1);h(this,"colors");this.colors=t&&t.length>0?t:Tk}setCursor(t){this.addUser(t.user);const o=this.cursors.get(t.user.userId);if(o&&_i.default(o,t))return;this.cursors.set(t.user.userId,t);const r=new Set([t.range.anchor.blockId,t.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(t){this.addingUser=!0,t.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(t){this.users.set(t.userId,t),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(t){var o;return(o=this.users.get(t))!=null?o:null}removeUser(t){this.users.delete(t),this.cursors.delete(t),this.emit("change",Array.from(this.users.values()))}updateUsers(t){this.users.clear(),this.addingUser=!0;try{t.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(t){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===t&&Xl(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(t){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===t||o.range.focus.blockId===t)}onUpdateBlockText(t,o,r){if(!t.text)return;this.getCursors(t.id).forEach(l=>{if(Xl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===t.id&&(c.offset=dt.transformCursor(c.offset,o,r)),a.blockId===t.id&&(a.offset=dt.transformCursor(a.offset,o,r))}})}getFixedUserColor(t,o){let r=0;Array.from(t).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const rt=w("local-doc");class nh extends zi{constructor(t,o){super();h(this,"doc");h(this,"serviceUrl");t?this.doc=t:this.doc={meta:{},comments:{},blocks:{root:[Gn("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return Q.default(this.doc)}getContainerBlocks(t){return this.doc.blocks[t]}getBlockData(t,o){const r=this.getContainerBlocks(t);d(rt,r,`no container data: ${t}`);const i=r[o];return d(rt,i,`no block data: ${o}`),i}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);d(rt,i.text,"no text for data");const s=dt.apply(i.text,r);return i.text=s,d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,t,o,r,!0)}),s}localUpdateBlockData(t,o,r){const i=this.getBlockData(t,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,t,o,r,!0)}),i}localInsertBlock(t,o,r){const i=this.getContainerBlocks(t);return d(rt,i,`no container data: ${t}`),d(rt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,t,o,r,!0)}),r}localDeleteBlock(t,o){const r=this.getContainerBlocks(t);d(rt,r,`no container data: ${t}`),d(rt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,t,o,!0)}),i}localInsertChildContainer(t,o){this.doc.blocks[t]=o,d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,t,o,!0)})}localDeleteChildContainers(t){rt.debug(`delete child containers: ${t}`),t.forEach(o=>{d(rt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),t.forEach(o=>{d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(t,o){d(rt,!1,"not implemented")}async addResources(t){return t}buildResourceUrl(t){return t}request(t,o){d(rt,!1,"not implemented")}broadcastMessage(t){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new vc}setDoc(t){this.doc=Q.default(t),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class Dk{constructor(e){this.cleanup=e}destroy(){var e;(e=this.cleanup)==null||e.call(this)}}function oh(n,e,t){n.addCustom(e,()=>{var i;const o=(i=t())!=null?i:void 0;return new Dk(o)})}const M2=w("find-block");function R2(n,e){const t=or(e);if(!t){if(Ft(e))return null;const o=tr(e);return d(M2,o,"no parent block"),R2(n,o)}return ce(n,t)?jr(n,t,{visibleOnly:!0}):t}function O2(n,e){const t=rr(e);if(!t){if(Ft(e))return null;const o=tr(e);return d(M2,o,"no parent block"),O2(n,o)}return ce(n,t)?ed(n,t,{visibleOnly:!0}):t}const Sk=w("remote-cursor");class Lk{constructor(){h(this,"remoteUsers",new vc)}onCustomMessage(e){const t=e;if(t.type==="onlineUsers"){const o=t;this.handleUpdateUsers(o.users)}else t.type==="caret"?this.handleUpdateCaret(t):Sk.debug(`unknown remote message received: ${e}`)}handleUpdateUsers(e){this.remoteUsers.updateUsers(e)}handleUpdateCaret(e){const t=this.remoteUsers.findUser(e.userId);!t||this.remoteUsers.setCursor({oneseditor:"cursor",user:t,range:e.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function Mk(n){const{blocks:e,meta:t,comments:o,...r}=n;return{rootBlocks:e,meta:t,comments:o,childBlocks:r}}function Rk(n){const{blocks:e,meta:t,comments:o}=n,{root:r,...i}=e;return{blocks:r,meta:t,comments:o,...i}}function ps(n){const{childBlocks:e,meta:t,comments:o,rootBlocks:r}=Mk(Q.default(n));return{blocks:{root:r,...e},meta:t,comments:o}}function wo(n){return n==="root"?"blocks":n}function Zr(n){return n==="blocks"?"root":n}const Ok={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ct.default(n)},apply(n,e){const t=new ct.default(n),o=new ct.default(e);return t.compose(o).ops},compose(n,e){const t=new ct.default(n),o=new ct.default(e);return t.compose(o).ops},diff(n,e){const t=new ct.default(n),o=new ct.default(e);return t.diff(o).ops},transform(n,e,t){const o=new ct.default(n);return new ct.default(e).transform(o,t==="left").ops},transformCursor(n,e,t){return e.transformPosition(n,!t)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,e,t){if(!n)return null;const o=new ct.default(e),r=this.transformCursor(n.index,o,t),i=this.transformCursor(n.index+n.length,o,t);return{...n,index:r,length:i-r}}}};var Cs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Bo={},rh=Am.default.EventEmitter;Bo.EventEmitter=rh,Bo.mixin=Pk;function Pk(n){for(var e in rh.prototype)n.prototype[e]=rh.prototype[e]}var P2=["info","warn","error"];function F2(){var n={};P2.forEach(function(e){n[e]=console[e].bind(console)}),this.setMethods(n)}var Fk=F2;F2.prototype.setMethods=function(n){n=n||{};var e=this;P2.forEach(function(t){typeof n[t]=="function"&&(e[t]=n[t])})};var Nk=Fk,$k=new Nk,N2=$k;function fr(n,e){this.code=n,this.message=e||"",Error.captureStackTrace?Error.captureStackTrace(this,fr):this.stack=new Error().stack}fr.prototype=Object.create(Error.prototype),fr.prototype.constructor=fr,fr.prototype.name="ShareDBError",fr.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 yc=fr,As={},$2=_k;function _k(n,e,t,o){var r=function(s,l,c,a){e(c,s,l,"left"),e(a,l,s,"right")},i=n.transformX=function(s,l){t(s),t(l);for(var c=[],a=0;a<l.length;a++){for(var u=l[a],f=[],m=0;m<s.length;){var p=[];if(r(s[m],u,f,p),m++,p.length===1)u=p[0];else if(p.length===0){for(var b=m;b<s.length;b++)o(f,s[b]);u=null;break}else{for(var y=i(s.slice(m),p),v=0;v<y[0].length;v++)o(f,y[0][v]);for(var x=0;x<y[1].length;x++)o(c,y[1][x]);u=null;break}}u!=null&&o(c,u),s=f}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?e([],s[0],l[0],c):c==="left"?i(s,l)[0]:i(l,s)[1]}}var _2={exports:{}},Eo=_2.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||""}},ih=function(n,e,t){return n.slice(0,e)+t+n.slice(e)},sh=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")},kc=function(n){for(var e=0;e<n.length;e++)sh(n[e])};Eo.apply=function(n,e){var t;kc(e);for(var o=0;o<e.length;o++){var r=e[o];if(r.i!=null)n=ih(n,r.p,r.i);else{if(t=n.slice(r.p,r.p+r.d.length),r.d!==t)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+t+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var Yn=Eo._append=function(n,e){if(!(e.i===""||e.d===""))if(n.length===0)n.push(e);else{var t=n[n.length-1];t.i!=null&&e.i!=null&&t.p<=e.p&&e.p<=t.p+t.i.length?n[n.length-1]={i:ih(t.i,e.p-t.p,e.i),p:t.p}:t.d!=null&&e.d!=null&&e.p<=t.p&&t.p<=e.p+e.d.length?n[n.length-1]={d:ih(e.d,t.p-e.p,t.d),p:e.p}:n.push(e)}};Eo.compose=function(n,e){kc(n),kc(e);for(var t=n.slice(),o=0;o<e.length;o++)Yn(t,e[o]);return t},Eo.normalize=function(n){var e=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=0),Yn(e,o)}return e};var lh=function(n,e,t){return e.i!=null?e.p<n||e.p===n&&t?n+e.i.length:n:n<=e.p?n:n<=e.p+e.d.length?e.p:n-e.d.length};Eo.transformCursor=function(n,e,t){for(var o=t==="right",r=0;r<e.length;r++)n=lh(n,e[r],o);return n};var jk=Eo._tc=function(n,e,t,o){if(sh(e),sh(t),e.i!=null)Yn(n,{i:e.i,p:lh(e.p,t,o==="right")});else if(t.i!=null){var r=e.d;e.p<t.p&&(Yn(n,{d:r.slice(0,t.p-e.p),p:e.p}),r=r.slice(t.p-e.p)),r!==""&&Yn(n,{d:r,p:e.p+t.i.length})}else if(e.p>=t.p+t.d.length)Yn(n,{d:e.d,p:e.p-t.d.length});else if(e.p+e.d.length<=t.p)Yn(n,e);else{var i={d:"",p:e.p};e.p<t.p&&(i.d=e.d.slice(0,t.p-e.p)),e.p+e.d.length>t.p+t.d.length&&(i.d+=e.d.slice(t.p+t.d.length-e.p));var s=Math.max(e.p,t.p),l=Math.min(e.p+e.d.length,t.p+t.d.length),c=e.d.slice(s-e.p,l-e.p),a=t.d.slice(s-t.p,l-t.p);if(c!==a)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=lh(i.p,t),Yn(n,i))}return n},Hk=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Eo.invert=function(n){n=n.slice().reverse();for(var e=0;e<n.length;e++)n[e]=Hk(n[e]);return n},$2(Eo,jk,kc,Yn);var wc=function(n){return Object.prototype.toString.call(n)=="[object Array]"},zk=function(n){return!!n&&n.constructor===Object},ln=function(n){return JSON.parse(JSON.stringify(n))},oe={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Jn={};oe.registerSubtype=function(n){Jn[n.name]=n},oe.create=function(n){return n===void 0?null:ln(n)},oe.invertComponent=function(n){var e={p:n.p};return n.t&&Jn[n.t]&&(e.t=n.t,e.o=Jn[n.t].invert(n.o)),n.si!==void 0&&(e.sd=n.si),n.sd!==void 0&&(e.si=n.sd),n.oi!==void 0&&(e.od=n.oi),n.od!==void 0&&(e.oi=n.od),n.li!==void 0&&(e.ld=n.li),n.ld!==void 0&&(e.li=n.ld),n.na!==void 0&&(e.na=-n.na),n.lm!==void 0&&(e.lm=n.p[n.p.length-1],e.p=n.p.slice(0,n.p.length-1).concat([n.lm])),e},oe.invert=function(n){for(var e=n.slice().reverse(),t=[],o=0;o<e.length;o++)t.push(oe.invertComponent(e[o]));return t},oe.checkValidOp=function(n){for(var e=0;e<n.length;e++)if(!wc(n[e].p))throw new Error("Missing path")},oe.checkList=function(n){if(!wc(n))throw new Error("Referenced element not a list")},oe.checkObj=function(n){if(!zk(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function bs(n){n.t="text0";var e={p:n.p.pop()};n.si!=null&&(e.i=n.si),n.sd!=null&&(e.d=n.sd),n.o=[e]}function vs(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}oe.apply=function(n,e){oe.checkValidOp(e),e=ln(e);for(var t={data:n},o=0;o<e.length;o++){var r=e[o];(r.si!=null||r.sd!=null)&&bs(r);for(var i=null,s=t,l="data",c=0;c<r.p.length;c++){var a=r.p[c];if(i=s,s=s[l],l=a,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Jn[r.t])s[l]=Jn[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)oe.checkList(s),s[l]=r.li;else if(r.li!==void 0)oe.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)oe.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(oe.checkList(s),r.lm!=l){var u=s[l];s.splice(l,1),s.splice(r.lm,0,u)}}else if(r.oi!==void 0)oe.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)oe.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return t.data},oe.shatter=function(n){for(var e=[],t=0;t<n.length;t++)e.push([n[t]]);return e},oe.incrementalApply=function(n,e,t){for(var o=0;o<e.length;o++){var r=[e[o]];n=oe.apply(n,r),t(r,n)}return n};var Uk=oe.pathMatches=function(n,e,t){if(n.length!=e.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==e[o]&&(!t||o!==n.length-1))return!1;return!0};oe.append=function(n,e){if(e=ln(e),n.length===0){n.push(e);return}var t=n[n.length-1];if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(bs(e),bs(t)),Uk(e.p,t.p))if(e.t&&t.t&&e.t===t.t&&Jn[e.t]){if(t.o=Jn[e.t].compose(t.o,e.o),e.si!=null||e.sd!=null){for(var o=e.p,r=0;r<t.o.length-1;r++)e.o=[t.o.pop()],e.p=o.slice(),vs(e),n.push(e);vs(t)}}else t.na!=null&&e.na!=null?n[n.length-1]={p:t.p,na:t.na+e.na}:t.li!==void 0&&e.li===void 0&&e.ld===t.li?t.ld!==void 0?delete t.li:n.pop():t.od!==void 0&&t.oi===void 0&&e.oi!==void 0&&e.od===void 0?t.oi=e.oi:t.oi!==void 0&&e.od!==void 0?e.oi!==void 0?t.oi=e.oi:t.od!==void 0?delete t.oi:n.pop():e.lm!==void 0&&e.p[e.p.length-1]===e.lm||n.push(e);else(e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(vs(e),vs(t)),n.push(e)},oe.compose=function(n,e){oe.checkValidOp(n),oe.checkValidOp(e);for(var t=ln(n),o=0;o<e.length;o++)oe.append(t,e[o]);return t},oe.normalize=function(n){var e=[];n=wc(n)?n:[n];for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=[]),oe.append(e,o)}return e},oe.commonLengthForOps=function(n,e){var t=n.p.length,o=e.p.length;if((n.na!=null||n.t)&&t++,(e.na!=null||e.t)&&o++,t===0)return-1;if(o===0)return null;t--,o--;for(var r=0;r<t;r++){var i=n.p[r];if(r>=o||i!==e.p[r])return null}return t},oe.canOpAffectPath=function(n,e){return oe.commonLengthForOps({p:e},n)!=null},oe.transformComponent=function(n,e,t,o){e=ln(e);var r=oe.commonLengthForOps(t,e),i=oe.commonLengthForOps(e,t),s=e.p.length,l=t.p.length;if((e.na!=null||e.t)&&s++,(t.na!=null||t.t)&&l++,i!=null&&l>s&&e.p[i]==t.p[i]){if(e.ld!==void 0){var c=ln(t);c.p=c.p.slice(s),e.ld=oe.apply(ln(e.ld),[c])}else if(e.od!==void 0){var c=ln(t);c.p=c.p.slice(s),e.od=oe.apply(ln(e.od),[c])}}if(r!=null){var a=s==l,c=t;if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(bs(e),c=ln(t),bs(c)),c.t&&Jn[c.t]){if(e.t&&e.t===c.t){var u=Jn[e.t].transform(e.o,c.o,o);if(e.si!=null||e.sd!=null)for(var f=e.p,m=0;m<u.length;m++)e.o=[u[m]],e.p=f.slice(),vs(e),oe.append(n,e);else(!wc(u)||u.length>0)&&(e.o=u,oe.append(n,e));return n}}else if(t.na===void 0){if(t.li!==void 0&&t.ld!==void 0){if(t.p[r]===e.p[r])if(a){if(e.ld!==void 0)if(e.li!==void 0&&o==="left")e.ld=ln(t.li);else return n}else return n}else if(t.li!==void 0)e.li!==void 0&&e.ld===void 0&&a&&e.p[r]===t.p[r]?o==="right"&&e.p[r]++:t.p[r]<=e.p[r]&&e.p[r]++,e.lm!==void 0&&a&&t.p[r]<=e.lm&&e.lm++;else if(t.ld!==void 0){if(e.lm!==void 0&&a){if(t.p[r]===e.p[r])return n;var f=t.p[r],p=e.p[r],b=e.lm;(f<b||f===b&&p<b)&&e.lm--}if(t.p[r]<e.p[r])e.p[r]--;else if(t.p[r]===e.p[r]){if(l<s)return n;if(e.ld!==void 0)if(e.li!==void 0)delete e.ld;else return n}}else if(t.lm!==void 0)if(e.lm!==void 0&&s===l){var p=e.p[r],b=e.lm,y=t.p[r],v=t.lm;if(y!==v)if(p===y)if(o==="left")e.p[r]=v,p===b&&(e.lm=v);else return n;else p>y&&e.p[r]--,p>v?e.p[r]++:p===v&&y>v&&(e.p[r]++,p===b&&e.lm++),(b>y||b===y&&b>p)&&e.lm--,b>v?e.lm++:b===v&&(v>y&&b>p||v<y&&b<p?o==="right"&&e.lm++:b>p?e.lm++:b===y&&e.lm--)}else if(e.li!==void 0&&e.ld===void 0&&a){var p=t.p[r],b=t.lm;f=e.p[r],f>p&&e.p[r]--,f>b&&e.p[r]++}else{var p=t.p[r],b=t.lm;f=e.p[r],f===p?e.p[r]=b:(f>p&&e.p[r]--,(f>b||f===b&&p>b)&&e.p[r]++)}else if(t.oi!==void 0&&t.od!==void 0){if(e.p[r]===t.p[r])if(e.oi!==void 0&&a){if(o==="right")return n;e.od=t.oi}else return n}else if(t.oi!==void 0){if(e.oi!==void 0&&e.p[r]===t.p[r])if(o==="left")oe.append(n,{p:e.p,od:t.oi});else return n}else if(t.od!==void 0&&e.p[r]==t.p[r]){if(!a)return n;if(e.oi!==void 0)delete e.od;else return n}}}return oe.append(n,e),n},$2(oe,oe.transformComponent,oe.checkValidOp,oe.append);var Vk=_2.exports;oe.registerSubtype(Vk);var qk=oe,Wk={type:qk};(function(n){n.defaultType=Wk.type,n.map={},n.register=function(e){e.name&&(n.map[e.name]=e),e.uri&&(n.map[e.uri]=e)},n.register(n.defaultType)})(As);var cn={};(function(n){n.doNothing=e;function e(){}n.hasKeys=function(t){for(var o in t)return!0;return!1},n.isInteger=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t},n.isValidVersion=function(t){return t===null?!0:n.isInteger(t)&&t>=0},n.isValidTimestamp=function(t){return n.isValidVersion(t)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var t=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];t=t[r]||(o===arguments.length-1?void 0:{})}return t},n.digOrCreate=function(){for(var t=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];t=t[i]||(t[i]=r===arguments.length-2?o():{})}return t},n.digAndRemove=function(){for(var t=arguments[0],o=[t],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!t.hasOwnProperty(i))break;t=t[i],o.push(t)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(t){return t&&typeof t.transformPresence=="function"},n.callEach=function(t,o){var r=!1;return t.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(t){return!!t},n.nextTick=function(t){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){t.apply(null,o)})},n.clone=function(t){return t===void 0?void 0:JSON.parse(JSON.stringify(t))}})(cn);var j2=Array.isArray,H2=Object.keys,Gk=Object.prototype.hasOwnProperty,Zk=function n(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var o=j2(e),r=j2(t),i,s,l;if(o&&r){if(s=e.length,s!=t.length)return!1;for(i=s;i--!==0;)if(!n(e[i],t[i]))return!1;return!0}if(o!=r)return!1;var c=e instanceof Date,a=t instanceof Date;if(c!=a)return!1;if(c&&a)return e.getTime()==t.getTime();var u=e instanceof RegExp,f=t instanceof RegExp;if(u!=f)return!1;if(u&&f)return e.toString()==t.toString();var m=H2(e);if(s=m.length,s!==H2(t).length)return!1;for(i=s;i--!==0;)if(!Gk.call(t,m[i]))return!1;for(i=s;i--!==0;)if(l=m[i],!n(e[l],t[l]))return!1;return!0}return e!==e&&t!==t},z2=Bo,Qk=N2,Mt=yc,Bc=As,an=cn,Yk=an.clone,Jk=Zk,Bt=Mt.CODES,Kk=ae;function ae(n,e,t){z2.EventEmitter.call(this),this.connection=n,this.collection=e,this.id=t,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}z2.mixin(ae),ae.prototype.destroy=function(n){this._wantsDestroy=!0;var e=this;e.whenNothingPending(function(){e.wantSubscribe?e.unsubscribe(function(t){if(t)return n?n(t):e.emit("error",t);e.connection._destroyDoc(e),n&&n()}):(e.connection._destroyDoc(e),n&&n())})},ae.prototype._setType=function(n){if(typeof n=="string"&&(n=Bc.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var e=new Mt(Bt.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",e)}},ae.prototype._setData=function(n){this.data=n,this._dataStateVersion++},ae.prototype.ingestSnapshot=function(n,e){if(!n)return e&&e();if(typeof n.v!="number"){var t=new Mt(Bt.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return e?e(t):this.emit("error",t)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return e&&this.once("no write pending",e);var t=new Mt(Bt.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return e?e(t):this.emit("error",t)}return n.v>this.version?this.fetch(e):e&&e()}if(this.version>n.v)return e&&e();this.version=n.v;var o=n.type===void 0?Bc.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),e&&e()},ae.prototype.whenNothingPending=function(n){var e=this;an.nextTick(function(){if(e.hasPending()){e.once("nothing pending",n);return}n()})},ae.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},ae.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},ae.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},ae.prototype._emitResponseError=function(n,e){if(n&&n.code===Bt.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,e&&e(),this._emitNothingPending();return}if(e){e(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},ae.prototype._handleFetch=function(n,e){var t=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&t.push(o),t.length&&(o=function(r){an.callEach(t,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(e,o),this._emitNothingPending()},ae.prototype._handleSubscribe=function(n,e){var t=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],t.callback&&o.push(t.callback);var r;if(o.length&&(r=function(i){an.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=t.wantSubscribe,this.subscribed?this.ingestSnapshot(e,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},ae.prototype._handleOp=function(n,e){if(n)return this.inflightOp?(n.code===Bt.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&e.src===this.inflightOp.src&&e.seq===this.inflightOp.seq){this._opAcknowledged(e);return}if(this.version==null||e.v>this.version){this.fetch();return}if(!(e.v<this.version)){if(this.inflightOp){var t=Ec(this.inflightOp,e);if(t)return this._hardRollback(t)}for(var o=0;o<this.pendingOps.length;o++){var t=Ec(this.pendingOps[o],e);if(t)return this._hardRollback(t)}this.version++;try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}}},ae.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))},ae.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(e){return e.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},ae.prototype.fetch=function(n){if(this.connection.canSend){var e=this.connection.sendFetch(this);Xk(this.inflightFetch,e,n);return}this.pendingFetch.push(n)},ae.prototype.subscribe=function(n){var e=!0;this._queueSubscribe(e,n)},ae.prototype.unsubscribe=function(n){var e=!1;this._queueSubscribe(e,n)},ae.prototype._queueSubscribe=function(n,e){var t=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=t&&t.wantSubscribe===n;if(o){t.callback=ew([t.callback,e]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:e}),this._flushSubscribe()},ae.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;an.nextTick(function(){n._handleSubscribe()})}}};function Xk(n,e,t){if(e){var o=n.pop();n.push(function(r){o&&o(r),t&&t(r)})}else n.push(t)}function ew(n){return n=n.filter(an.truthy),n.length?function(e){an.callEach(n,e)}:null}ae.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function tw(n){delete n.op,delete n.create,delete n.del}function Ec(n,e){if(n.del)return tw(e);if(e.del)return new Mt(Bt.ERR_DOC_WAS_DELETED,"Document was deleted");if(e.create)return new Mt(Bt.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in e){if(n.create)return new Mt(Bt.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var t=n.type.transformX(n.op,e.op);n.op=t[0],e.op=t[1]}else{var o=n.type.transform(n.op,e.op,"left"),r=n.type.transform(e.op,n.op,"right");n.op=o,e.op=r}}}ae.prototype._otApply=function(n,e){if("op"in n){if(!this.type)throw new Mt(Bt.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,e),!e&&this.type===Bc.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var t=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,e,n.src);for(var s=t;s<this.applyStack.length;s++){var l=Ec(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,e,n.src)}this.emit("op batch",n.op,e),this._popApplyStack(t);return}this.emit("before op",n.op,e,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,e,n.src),this.emit("op batch",n.op,e);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",e);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,e);return}},ae.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var e=this.inflightOp;if(!e){var t=new Mt(Bt.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",t)}if(e.sentAt=Date.now(),e.retries=e.retries==null?0:e.retries+1,e.seq==null){if(this.connection.seq>=an.MAX_SAFE_INTEGER)return this.emit("error",new Mt(Bt.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));e.seq=this.connection.seq++}this.connection.sendOp(this,e),e.src==null&&(e.src=n)}},ae.prototype._submit=function(n,e,t){if(e||(e=!0),"op"in n){if(!this.type){var o=new Mt(Bt.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return t?t(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,e,t),this._otApply(n,e)}catch(i){return this._hardRollback(i)}var r=this;an.nextTick(function(){r.flush()})},ae.prototype._pushOp=function(n,e,t){if(n.source=e,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(t);return}}n.type=this.type,n.callbacks=[t],this.pendingOps.push(n)},ae.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var e=this.applyStack[0];if(this.applyStack=null,!!e){var t=this.pendingOps.indexOf(e);if(t!==-1)for(var o=this.pendingOps.splice(t),t=0;t<o.length;t++){var e=o[t],r=this._tryCompose(e);r?r.callbacks=r.callbacks.concat(e.callbacks):this.pendingOps.push(e)}}},ae.prototype._tryCompose=function(n){if(!this.preventCompose){var e=this.pendingOps[this.pendingOps.length-1];if(!(!e||e.sentAt)&&!(this.submitSource&&!Jk(n.source,e.source))){if(e.create&&"op"in n)return e.create.data=this.type.apply(e.create.data,n.op),e;if("op"in e&&"op"in n&&this.type.compose)return e.op=this.type.compose(e.op,n.op),e}}},ae.prototype.submitOp=function(n,e,t){typeof e=="function"&&(t=e,e=null);var o={op:n},r=e&&e.source;this._submit(o,r,t)},ae.prototype.create=function(n,e,t,o){if(typeof e=="function"?(o=e,t=null,e=null):typeof t=="function"&&(o=t,t=null),e||(e=Bc.defaultType.uri),this.type){var r=new Mt(Bt.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:e,data:n}},s=t&&t.source;this._submit(i,s,o)},ae.prototype.del=function(n,e){if(typeof n=="function"&&(e=n,n=null),!this.type){var t=new Mt(Bt.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return e?e(t):this.emit("error",t)}var o={del:!0},r=n&&n.source;this._submit(o,r,e)},ae.prototype.pause=function(){this.paused=!0},ae.prototype.resume=function(){this.paused=!1,this.flush()},ae.prototype.toSnapshot=function(){return{v:this.version,data:Yk(this.data),type:this.type.uri}},ae.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return Qk.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},ae.prototype._rollback=function(n){var e=this.inflightOp;if("op"in e&&e.type.invert){try{e.op=e.type.invert(e.op)}catch{return this._hardRollback(n)}for(var t=0;t<this.pendingOps.length;t++){var o=Ec(this.pendingOps[t],e);if(o)return this._hardRollback(o)}try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},ae.prototype._hardRollback=function(n){var e=[];this.inflightOp&&e.push(this.inflightOp),e=e.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var t=this;this.fetch(function(){for(var o=!!e.length,r=0;r<e.length;r++)o=an.callEach(e[r].callbacks,n)&&o;if(n&&!o)return t.emit("error",n)})},ae.prototype._clearInflightOp=function(n){var e=this.inflightOp;this.inflightOp=null;var t=an.callEach(e.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!t)return this.emit("error",n)};var mr={};mr.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 U2=Bo,V2=mr.ACTIONS,nw=cn,ow=Et;function Et(n,e,t,o,r,i,s){U2.EventEmitter.call(this),this.action=n,this.connection=e,this.id=t,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}U2.mixin(Et),Et.prototype.hasPending=function(){return!this.ready},Et.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var e=[],t=0;t<this.results.length;t++){var o=this.results[t];e.push([o.id,o.version])}n.r=e}this.connection.send(n),this.sent=!0}},Et.prototype.destroy=function(n){this.connection.canSend&&this.action===V2.querySubscribe&&this.connection.send({a:V2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&nw.nextTick(n)},Et.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Et.prototype._handleFetch=function(n,e,t){this.connection._destroyQuery(this),this._handleResponse(n,e,t)},Et.prototype._handleSubscribe=function(n,e,t){this._handleResponse(n,e,t)},Et.prototype._handleResponse=function(n,e,t){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!e)return this._finishResponse(null,o);var r=this,i=1,s=function(u){if(u)return r._finishResponse(u,o);--i||r._finishResponse(null,o)};if(Array.isArray(e))i+=e.length,this.results=this._ingestSnapshots(e,s),this.extra=t;else for(var l in e){i++;var c=e[l],a=this.connection.get(c.c||this.collection,l);a.ingestSnapshot(c,s)}s()},Et.prototype._ingestSnapshots=function(n,e){for(var t=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,e),t.push(i)}return t},Et.prototype._finishResponse=function(n,e){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),e?e(n):this.emit("error",n);e&&e(null,this.results,this.extra)},Et.prototype._handleError=function(n){this.emit("error",n)},Et.prototype._handleDiff=function(n){for(var e=0;e<n.length;e++){var t=n[e];t.type==="insert"&&(t.values=this._ingestSnapshots(t.values))}for(var e=0;e<n.length;e++){var t=n[e];switch(t.type){case"insert":var o=t.values;Array.prototype.splice.apply(this.results,[t.index,0].concat(o)),this.emit("insert",o,t.index);break;case"remove":var i=t.howMany||1,r=this.results.splice(t.index,i);this.emit("remove",r,t.index);break;case"move":var i=t.howMany||1,s=this.results.splice(t.from,i);Array.prototype.splice.apply(this.results,[t.to,0].concat(s)),this.emit("move",s,t.from,t.to);break}}this.emit("changed",this.results)},Et.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var q2=Bo,rw=mr.ACTIONS,iw=cn,W2=In;function In(n,e){if(q2.EventEmitter.call(this),!e||typeof e!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=e,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}q2.mixin(In),In.prototype.submit=function(n,e){this.value=n,this.send(e)},In.prototype.send=function(n){var e=this._message();this._pendingMessages.push(e),this._callbacksByPresenceVersion[e.pv]=n,this._sendPending()},In.prototype.destroy=function(n){var e=this;this.submit(null,function(t){if(t)return e._callbackOrEmit(t,n);delete e.presence.localPresences[e.presenceId],n&&n()})},In.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(e){n.connection.send(e)}),this._pendingMessages=[]}},In.prototype._ack=function(n,e){var t=this._getCallback(e);this._callbackOrEmit(n,t)},In.prototype._message=function(){return{a:rw.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},In.prototype._getCallback=function(n){var e=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],e},In.prototype._callbackOrEmit=function(n,e){if(e)return iw.nextTick(e,n);n&&this.emit("error",n)};var sw=cn,G2=ch;function ch(n,e){this.presence=n,this.presenceId=e,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}ch.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},ch.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&sw.nextTick(n)};var ah={exports:{}};(function(n,e){(function(t,o){o(e)})(Cs,function(t){function o(C,k){k=k|0;for(var B=Math.max(C.length-k,0),T=Array(B),S=0;S<B;S++)T[S]=C[k+S];return T}var r=function(C){var k=o(arguments,1);return function(){var B=o(arguments);return C.apply(null,k.concat(B))}},i=function(C){return function(){var k=o(arguments),B=k.pop();C.call(this,k,B)}};function s(C){var k=typeof C;return C!=null&&(k=="object"||k=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function a(C){setTimeout(C,0)}function u(C){return function(k){var B=o(arguments,1);C(function(){k.apply(null,B)})}}var f;l?f=setImmediate:c?f=process.nextTick:f=a;var m=u(f);function p(C){return i(function(k,B){var T;try{T=C.apply(this,k)}catch(S){return B(S)}s(T)&&typeof T.then=="function"?T.then(function(S){b(B,null,S)},function(S){b(B,S.message?S:new Error(S))}):B(null,T)})}function b(C,k,B){try{C(k,B)}catch(T){m(y,T)}}function y(C){throw C}var v=typeof Symbol=="function";function x(C){return v&&C[Symbol.toStringTag]==="AsyncFunction"}function E(C){return x(C)?p(C):C}function M(C){return function(k){var B=o(arguments,1),T=i(function(S,D){var P=this;return C(k,function(F,W){E(F).apply(P,S.concat(W))},D)});return B.length?T.apply(this,B):T}}var L=typeof Cs=="object"&&Cs&&Cs.Object===Object&&Cs,O=typeof self=="object"&&self&&self.Object===Object&&self,V=L||O||Function("return this")(),ee=V.Symbol,se=Object.prototype,pe=se.hasOwnProperty,de=se.toString,we=ee?ee.toStringTag:void 0;function ft(C){var k=pe.call(C,we),B=C[we];try{C[we]=void 0;var T=!0}catch{}var S=de.call(C);return T&&(k?C[we]=B:delete C[we]),S}var lo=Object.prototype,st=lo.toString;function qt(C){return st.call(C)}var jo="[object Null]",Dr="[object Undefined]",Sr=ee?ee.toStringTag:void 0;function Ho(C){return C==null?C===void 0?Dr:jo:Sr&&Sr in Object(C)?ft(C):qt(C)}var $a="[object AsyncFunction]",wH="[object Function]",BH="[object GeneratorFunction]",EH="[object Proxy]";function IH(C){if(!s(C))return!1;var k=Ho(C);return k==wH||k==BH||k==$a||k==EH}var xH=9007199254740991;function e7(C){return typeof C=="number"&&C>-1&&C%1==0&&C<=xH}function ml(C){return C!=null&&e7(C.length)&&!IH(C)}var Jf={};function he(){}function zo(C){return function(){if(C!==null){var k=C;C=null,k.apply(this,arguments)}}}var Kf=typeof Symbol=="function"&&Symbol.iterator,TH=function(C){return Kf&&C[Kf]&&C[Kf]()};function DH(C,k){for(var B=-1,T=Array(C);++B<C;)T[B]=k(B);return T}function _a(C){return C!=null&&typeof C=="object"}var SH="[object Arguments]";function t7(C){return _a(C)&&Ho(C)==SH}var n7=Object.prototype,LH=n7.hasOwnProperty,MH=n7.propertyIsEnumerable,RH=t7(function(){return arguments}())?t7:function(C){return _a(C)&&LH.call(C,"callee")&&!MH.call(C,"callee")},An=Array.isArray;function OH(){return!1}var o7=typeof t=="object"&&t&&!t.nodeType&&t,r7=o7&&!0&&n&&!n.nodeType&&n,PH=r7&&r7.exports===o7,i7=PH?V.Buffer:void 0,FH=i7?i7.isBuffer:void 0,NH=FH||OH,$H=9007199254740991,_H=/^(?:0|[1-9]\d*)$/;function jH(C,k){var B=typeof C;return k=k==null?$H:k,!!k&&(B=="number"||B!="symbol"&&_H.test(C))&&C>-1&&C%1==0&&C<k}var HH="[object Arguments]",zH="[object Array]",UH="[object Boolean]",VH="[object Date]",qH="[object Error]",WH="[object Function]",GH="[object Map]",ZH="[object Number]",QH="[object Object]",YH="[object RegExp]",JH="[object Set]",KH="[object String]",XH="[object WeakMap]",ez="[object ArrayBuffer]",tz="[object DataView]",nz="[object Float32Array]",oz="[object Float64Array]",rz="[object Int8Array]",iz="[object Int16Array]",sz="[object Int32Array]",lz="[object Uint8Array]",cz="[object Uint8ClampedArray]",az="[object Uint16Array]",uz="[object Uint32Array]",Be={};Be[nz]=Be[oz]=Be[rz]=Be[iz]=Be[sz]=Be[lz]=Be[cz]=Be[az]=Be[uz]=!0,Be[HH]=Be[zH]=Be[ez]=Be[UH]=Be[tz]=Be[VH]=Be[qH]=Be[WH]=Be[GH]=Be[ZH]=Be[QH]=Be[YH]=Be[JH]=Be[KH]=Be[XH]=!1;function dz(C){return _a(C)&&e7(C.length)&&!!Be[Ho(C)]}function hz(C){return function(k){return C(k)}}var s7=typeof t=="object"&&t&&!t.nodeType&&t,gl=s7&&!0&&n&&!n.nodeType&&n,fz=gl&&gl.exports===s7,Xf=fz&&L.process,l7=function(){try{var C=gl&&gl.require&&gl.require("util").types;return C||Xf&&Xf.binding&&Xf.binding("util")}catch{}}(),c7=l7&&l7.isTypedArray,mz=c7?hz(c7):dz,gz=Object.prototype,pz=gz.hasOwnProperty;function Cz(C,k){var B=An(C),T=!B&&RH(C),S=!B&&!T&&NH(C),D=!B&&!T&&!S&&mz(C),P=B||T||S||D,F=P?DH(C.length,String):[],W=F.length;for(var J in C)(k||pz.call(C,J))&&!(P&&(J=="length"||S&&(J=="offset"||J=="parent")||D&&(J=="buffer"||J=="byteLength"||J=="byteOffset")||jH(J,W)))&&F.push(J);return F}var Az=Object.prototype;function bz(C){var k=C&&C.constructor,B=typeof k=="function"&&k.prototype||Az;return C===B}function vz(C,k){return function(B){return C(k(B))}}var yz=vz(Object.keys,Object),kz=Object.prototype,wz=kz.hasOwnProperty;function Bz(C){if(!bz(C))return yz(C);var k=[];for(var B in Object(C))wz.call(C,B)&&B!="constructor"&&k.push(B);return k}function em(C){return ml(C)?Cz(C):Bz(C)}function Ez(C){var k=-1,B=C.length;return function(){return++k<B?{value:C[k],key:k}:null}}function Iz(C){var k=-1;return function(){var T=C.next();return T.done?null:(k++,{value:T.value,key:k})}}function xz(C){var k=em(C),B=-1,T=k.length;return function S(){var D=k[++B];return D==="__proto__"?S():B<T?{value:C[D],key:D}:null}}function Tz(C){if(ml(C))return Ez(C);var k=TH(C);return k?Iz(k):xz(C)}function Fn(C){return function(){if(C===null)throw new Error("Callback was already called.");var k=C;C=null,k.apply(this,arguments)}}function ja(C){return function(k,B,T){if(T=zo(T||he),C<=0||!k)return T(null);var S=Tz(k),D=!1,P=0,F=!1;function W(Z,te){if(P-=1,Z)D=!0,T(Z);else{if(te===Jf||D&&P<=0)return D=!0,T(null);F||J()}}function J(){for(F=!0;P<C&&!D;){var Z=S();if(Z===null){D=!0,P<=0&&T(null);return}P+=1,B(Z.value,Z.key,Fn(W))}F=!1}J()}}function Lr(C,k,B,T){ja(k)(C,E(B),T)}function lt(C,k){return function(B,T,S){return C(B,k,T,S)}}function Dz(C,k,B){B=zo(B||he);var T=0,S=0,D=C.length;D===0&&B(null);function P(F,W){F?B(F):(++S===D||W===Jf)&&B(null)}for(;T<D;T++)k(C[T],T,Fn(P))}var Sz=lt(Lr,1/0),Uo=function(C,k,B){var T=ml(C)?Dz:Sz;T(C,E(k),B)};function Li(C){return function(k,B,T){return C(Uo,k,E(B),T)}}function a7(C,k,B,T){T=T||he,k=k||[];var S=[],D=0,P=E(B);C(k,function(F,W,J){var Z=D++;P(F,function(te,Ee){S[Z]=Ee,J(te)})},function(F){T(F,S)})}var Ha=Li(a7),u7=M(Ha);function Mi(C){return function(k,B,T,S){return C(ja(B),k,E(T),S)}}var Ri=Mi(a7),tm=lt(Ri,1),d7=M(tm);function za(C,k){for(var B=-1,T=C==null?0:C.length;++B<T&&k(C[B],B,C)!==!1;);return C}function Lz(C){return function(k,B,T){for(var S=-1,D=Object(k),P=T(k),F=P.length;F--;){var W=P[C?F:++S];if(B(D[W],W,D)===!1)break}return k}}var Mz=Lz();function pl(C,k){return C&&Mz(C,k,em)}function Rz(C,k,B,T){for(var S=C.length,D=B+(T?1:-1);T?D--:++D<S;)if(k(C[D],D,C))return D;return-1}function Oz(C){return C!==C}function Pz(C,k,B){for(var T=B-1,S=C.length;++T<S;)if(C[T]===k)return T;return-1}function Ua(C,k,B){return k===k?Pz(C,k,B):Rz(C,Oz,B)}var nm=function(C,k,B){typeof k=="function"&&(B=k,k=null),B=zo(B||he);var T=em(C),S=T.length;if(!S)return B(null);k||(k=S);var D={},P=0,F=!1,W=Object.create(null),J=[],Z=[],te={};pl(C,function(De,Le){if(!An(De)){Ee(Le,[De]),Z.push(Le);return}var tt=De.slice(0,De.length-1),co=tt.length;if(co===0){Ee(Le,De),Z.push(Le);return}te[Le]=co,za(tt,function(Ni){if(!C[Ni])throw new Error("async.auto task `"+Le+"` has a non-existent dependency `"+Ni+"` in "+tt.join(", "));Nn(Ni,function(){co--,co===0&&Ee(Le,De)})})}),xU(),mt();function Ee(De,Le){J.push(function(){$n(De,Le)})}function mt(){if(J.length===0&&P===0)return B(null,D);for(;J.length&&P<k;){var De=J.shift();De()}}function Nn(De,Le){var tt=W[De];tt||(tt=W[De]=[]),tt.push(Le)}function Wt(De){var Le=W[De]||[];za(Le,function(tt){tt()}),mt()}function $n(De,Le){if(!F){var tt=Fn(function(Ni,mm){if(P--,arguments.length>2&&(mm=o(arguments,1)),Ni){var gm={};pl(D,function(DU,SU){gm[SU]=DU}),gm[De]=mm,F=!0,W=Object.create(null),B(Ni,gm)}else D[De]=mm,Wt(De)});P++;var co=E(Le[Le.length-1]);Le.length>1?co(D,tt):co(tt)}}function xU(){for(var De,Le=0;Z.length;)De=Z.pop(),Le++,za(TU(De),function(tt){--te[tt]===0&&Z.push(tt)});if(Le!==S)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function TU(De){var Le=[];return pl(C,function(tt,co){An(tt)&&Ua(tt,De,0)>=0&&Le.push(co)}),Le}};function Oi(C,k){for(var B=-1,T=C==null?0:C.length,S=Array(T);++B<T;)S[B]=k(C[B],B,C);return S}var Fz="[object Symbol]";function Nz(C){return typeof C=="symbol"||_a(C)&&Ho(C)==Fz}var $z=1/0,h7=ee?ee.prototype:void 0,f7=h7?h7.toString:void 0;function om(C){if(typeof C=="string")return C;if(An(C))return Oi(C,om)+"";if(Nz(C))return f7?f7.call(C):"";var k=C+"";return k=="0"&&1/C==-$z?"-0":k}function _z(C,k,B){var T=-1,S=C.length;k<0&&(k=-k>S?0:S+k),B=B>S?S:B,B<0&&(B+=S),S=k>B?0:B-k>>>0,k>>>=0;for(var D=Array(S);++T<S;)D[T]=C[T+k];return D}function jz(C,k,B){var T=C.length;return B=B===void 0?T:B,!k&&B>=T?C:_z(C,k,B)}function Hz(C,k){for(var B=C.length;B--&&Ua(k,C[B],0)>-1;);return B}function zz(C,k){for(var B=-1,T=C.length;++B<T&&Ua(k,C[B],0)>-1;);return B}function Uz(C){return C.split("")}var Vz="\\ud800-\\udfff",qz="\\u0300-\\u036f",Wz="\\ufe20-\\ufe2f",Gz="\\u20d0-\\u20ff",Zz=qz+Wz+Gz,Qz="\\ufe0e\\ufe0f",Yz="\\u200d",Jz=RegExp("["+Yz+Vz+Zz+Qz+"]");function Kz(C){return Jz.test(C)}var m7="\\ud800-\\udfff",Xz="\\u0300-\\u036f",eU="\\ufe20-\\ufe2f",tU="\\u20d0-\\u20ff",nU=Xz+eU+tU,oU="\\ufe0e\\ufe0f",rU="["+m7+"]",rm="["+nU+"]",im="\\ud83c[\\udffb-\\udfff]",iU="(?:"+rm+"|"+im+")",g7="[^"+m7+"]",p7="(?:\\ud83c[\\udde6-\\uddff]){2}",C7="[\\ud800-\\udbff][\\udc00-\\udfff]",sU="\\u200d",A7=iU+"?",b7="["+oU+"]?",lU="(?:"+sU+"(?:"+[g7,p7,C7].join("|")+")"+b7+A7+")*",cU=b7+A7+lU,aU="(?:"+[g7+rm+"?",rm,p7,C7,rU].join("|")+")",uU=RegExp(im+"(?="+im+")|"+aU+cU,"g");function dU(C){return C.match(uU)||[]}function v7(C){return Kz(C)?dU(C):Uz(C)}function hU(C){return C==null?"":om(C)}var fU=/^\s+|\s+$/g;function mU(C,k,B){if(C=hU(C),C&&(B||k===void 0))return C.replace(fU,"");if(!C||!(k=om(k)))return C;var T=v7(C),S=v7(k),D=zz(T,S),P=Hz(T,S)+1;return jz(T,D,P).join("")}var gU=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,pU=/,/,CU=/(=.+)?(\s*)$/,AU=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function bU(C){return C=C.toString().replace(AU,""),C=C.match(gU)[2].replace(" ",""),C=C?C.split(pU):[],C=C.map(function(k){return mU(k.replace(CU,""))}),C}function y7(C,k){var B={};pl(C,function(T,S){var D,P=x(T),F=!P&&T.length===1||P&&T.length===0;if(An(T))D=T.slice(0,-1),T=T[T.length-1],B[S]=D.concat(D.length>0?W:T);else if(F)B[S]=T;else{if(D=bU(T),T.length===0&&!P&&D.length===0)throw new Error("autoInject task functions require explicit parameters.");P||D.pop(),B[S]=D.concat(W)}function W(J,Z){var te=Oi(D,function(Ee){return J[Ee]});te.push(Z),E(T).apply(null,te)}}),nm(B,k)}function bn(){this.head=this.tail=null,this.length=0}function k7(C,k){C.length=1,C.head=C.tail=k}bn.prototype.removeLink=function(C){return C.prev?C.prev.next=C.next:this.head=C.next,C.next?C.next.prev=C.prev:this.tail=C.prev,C.prev=C.next=null,this.length-=1,C},bn.prototype.empty=function(){for(;this.head;)this.shift();return this},bn.prototype.insertAfter=function(C,k){k.prev=C,k.next=C.next,C.next?C.next.prev=k:this.tail=k,C.next=k,this.length+=1},bn.prototype.insertBefore=function(C,k){k.prev=C.prev,k.next=C,C.prev?C.prev.next=k:this.head=k,C.prev=k,this.length+=1},bn.prototype.unshift=function(C){this.head?this.insertBefore(this.head,C):k7(this,C)},bn.prototype.push=function(C){this.tail?this.insertAfter(this.tail,C):k7(this,C)},bn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},bn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},bn.prototype.toArray=function(){for(var C=Array(this.length),k=this.head,B=0;B<this.length;B++)C[B]=k.data,k=k.next;return C},bn.prototype.remove=function(C){for(var k=this.head;k;){var B=k.next;C(k)&&this.removeLink(k),k=B}return this};function w7(C,k,B){if(k==null)k=1;else if(k===0)throw new Error("Concurrency must not be zero");var T=E(C),S=0,D=[],P=!1;function F(te,Ee,mt){if(mt!=null&&typeof mt!="function")throw new Error("task callback must be a function");if(Z.started=!0,An(te)||(te=[te]),te.length===0&&Z.idle())return m(function(){Z.drain()});for(var Nn=0,Wt=te.length;Nn<Wt;Nn++){var $n={data:te[Nn],callback:mt||he};Ee?Z._tasks.unshift($n):Z._tasks.push($n)}P||(P=!0,m(function(){P=!1,Z.process()}))}function W(te){return function(Ee){S-=1;for(var mt=0,Nn=te.length;mt<Nn;mt++){var Wt=te[mt],$n=Ua(D,Wt,0);$n===0?D.shift():$n>0&&D.splice($n,1),Wt.callback.apply(Wt,arguments),Ee!=null&&Z.error(Ee,Wt.data)}S<=Z.concurrency-Z.buffer&&Z.unsaturated(),Z.idle()&&Z.drain(),Z.process()}}var J=!1,Z={_tasks:new bn,concurrency:k,payload:B,saturated:he,unsaturated:he,buffer:k/4,empty:he,drain:he,error:he,started:!1,paused:!1,push:function(te,Ee){F(te,!1,Ee)},kill:function(){Z.drain=he,Z._tasks.empty()},unshift:function(te,Ee){F(te,!0,Ee)},remove:function(te){Z._tasks.remove(te)},process:function(){if(!J){for(J=!0;!Z.paused&&S<Z.concurrency&&Z._tasks.length;){var te=[],Ee=[],mt=Z._tasks.length;Z.payload&&(mt=Math.min(mt,Z.payload));for(var Nn=0;Nn<mt;Nn++){var Wt=Z._tasks.shift();te.push(Wt),D.push(Wt),Ee.push(Wt.data)}S+=1,Z._tasks.length===0&&Z.empty(),S===Z.concurrency&&Z.saturated();var $n=Fn(W(te));T(Ee,$n)}J=!1}},length:function(){return Z._tasks.length},running:function(){return S},workersList:function(){return D},idle:function(){return Z._tasks.length+S===0},pause:function(){Z.paused=!0},resume:function(){Z.paused!==!1&&(Z.paused=!1,m(Z.process))}};return Z}function B7(C,k){return w7(C,1,k)}var Pi=lt(Lr,1);function Vo(C,k,B,T){T=zo(T||he);var S=E(B);Pi(C,function(D,P,F){S(k,D,function(W,J){k=J,F(W)})},function(D){T(D,k)})}function sm(){var C=Oi(arguments,E);return function(){var k=o(arguments),B=this,T=k[k.length-1];typeof T=="function"?k.pop():T=he,Vo(C,k,function(S,D,P){D.apply(B,S.concat(function(F){var W=o(arguments,1);P(F,W)}))},function(S,D){T.apply(B,[S].concat(D))})}}var E7=function(){return sm.apply(null,o(arguments).reverse())},vU=Array.prototype.concat,Va=function(C,k,B,T){T=T||he;var S=E(B);Ri(C,k,function(D,P){S(D,function(F){return F?P(F):P(null,o(arguments,1))})},function(D,P){for(var F=[],W=0;W<P.length;W++)P[W]&&(F=vU.apply(F,P[W]));return T(D,F)})},I7=lt(Va,1/0),x7=lt(Va,1),T7=function(){var C=o(arguments),k=[null].concat(C);return function(){var B=arguments[arguments.length-1];return B.apply(this,k)}};function Cl(C){return C}function Fi(C,k){return function(B,T,S,D){D=D||he;var P=!1,F;B(T,function(W,J,Z){S(W,function(te,Ee){te?Z(te):C(Ee)&&!F?(P=!0,F=k(!0,W),Z(null,Jf)):Z()})},function(W){W?D(W):D(null,P?F:k(!1))})}}function D7(C,k){return k}var qa=Li(Fi(Cl,D7)),Al=Mi(Fi(Cl,D7)),Wa=lt(Al,1);function S7(C){return function(k){var B=o(arguments,1);B.push(function(T){var S=o(arguments,1);typeof console=="object"&&(T?console.error&&console.error(T):console[C]&&za(S,function(D){console[C](D)}))}),E(k).apply(null,B)}}var L7=S7("dir");function M7(C,k,B){B=Fn(B||he);var T=E(C),S=E(k);function D(F){if(F)return B(F);var W=o(arguments,1);W.push(P),S.apply(this,W)}function P(F,W){if(F)return B(F);if(!W)return B(null);T(D)}P(null,!0)}function lm(C,k,B){B=Fn(B||he);var T=E(C),S=function(D){if(D)return B(D);var P=o(arguments,1);if(k.apply(this,P))return T(S);B.apply(null,[null].concat(P))};T(S)}function R7(C,k,B){lm(C,function(){return!k.apply(this,arguments)},B)}function O7(C,k,B){B=Fn(B||he);var T=E(k),S=E(C);function D(F){if(F)return B(F);S(P)}function P(F,W){if(F)return B(F);if(!W)return B(null);T(D)}S(P)}function P7(C){return function(k,B,T){return C(k,T)}}function Ga(C,k,B){Uo(C,P7(E(k)),B)}function bl(C,k,B,T){ja(k)(C,P7(E(B)),T)}var vl=lt(bl,1);function cm(C){return x(C)?C:i(function(k,B){var T=!0;k.push(function(){var S=arguments;T?m(function(){B.apply(null,S)}):B.apply(null,S)}),C.apply(this,k),T=!1})}function Za(C){return!C}var Qa=Li(Fi(Za,Za)),yl=Mi(Fi(Za,Za)),Ya=lt(yl,1);function F7(C){return function(k){return k==null?void 0:k[C]}}function yU(C,k,B,T){var S=new Array(k.length);C(k,function(D,P,F){B(D,function(W,J){S[P]=!!J,F(W)})},function(D){if(D)return T(D);for(var P=[],F=0;F<k.length;F++)S[F]&&P.push(k[F]);T(null,P)})}function kU(C,k,B,T){var S=[];C(k,function(D,P,F){B(D,function(W,J){W?F(W):(J&&S.push({index:P,value:D}),F())})},function(D){D?T(D):T(null,Oi(S.sort(function(P,F){return P.index-F.index}),F7("value")))})}function am(C,k,B,T){var S=ml(k)?yU:kU;S(C,k,E(B),T||he)}var Ja=Li(am),kl=Mi(am),Ka=lt(kl,1);function N7(C,k){var B=Fn(k||he),T=E(cm(C));function S(D){if(D)return B(D);T(S)}S()}var Xa=function(C,k,B,T){T=T||he;var S=E(B);Ri(C,k,function(D,P){S(D,function(F,W){return F?P(F):P(null,{key:W,val:D})})},function(D,P){for(var F={},W=Object.prototype.hasOwnProperty,J=0;J<P.length;J++)if(P[J]){var Z=P[J].key,te=P[J].val;W.call(F,Z)?F[Z].push(te):F[Z]=[te]}return T(D,F)})},$7=lt(Xa,1/0),_7=lt(Xa,1),j7=S7("log");function eu(C,k,B,T){T=zo(T||he);var S={},D=E(B);Lr(C,k,function(P,F,W){D(P,F,function(J,Z){if(J)return W(J);S[F]=Z,W()})},function(P){T(P,S)})}var H7=lt(eu,1/0),z7=lt(eu,1);function U7(C,k){return k in C}function V7(C,k){var B=Object.create(null),T=Object.create(null);k=k||Cl;var S=E(C),D=i(function(F,W){var J=k.apply(null,F);U7(B,J)?m(function(){W.apply(null,B[J])}):U7(T,J)?T[J].push(W):(T[J]=[W],S.apply(null,F.concat(function(){var Z=o(arguments);B[J]=Z;var te=T[J];delete T[J];for(var Ee=0,mt=te.length;Ee<mt;Ee++)te[Ee].apply(null,Z)})))});return D.memo=B,D.unmemoized=C,D}var tu;c?tu=process.nextTick:l?tu=setImmediate:tu=a;var q7=u(tu);function um(C,k,B){B=B||he;var T=ml(k)?[]:{};C(k,function(S,D,P){E(S)(function(F,W){arguments.length>2&&(W=o(arguments,1)),T[D]=W,P(F)})},function(S){B(S,T)})}function W7(C,k){um(Uo,C,k)}function G7(C,k,B){um(ja(k),C,B)}var dm=function(C,k){var B=E(C);return w7(function(T,S){B(T[0],S)},k,1)},Z7=function(C,k){var B=dm(C,k);return B.push=function(T,S,D){if(D==null&&(D=he),typeof D!="function")throw new Error("task callback must be a function");if(B.started=!0,An(T)||(T=[T]),T.length===0)return m(function(){B.drain()});S=S||0;for(var P=B._tasks.head;P&&S>=P.priority;)P=P.next;for(var F=0,W=T.length;F<W;F++){var J={data:T[F],priority:S,callback:D};P?B._tasks.insertBefore(P,J):B._tasks.push(J)}m(B.process)},delete B.unshift,B};function Q7(C,k){if(k=zo(k||he),!An(C))return k(new TypeError("First argument to race must be an array of functions"));if(!C.length)return k();for(var B=0,T=C.length;B<T;B++)E(C[B])(k)}function nu(C,k,B,T){var S=o(C).reverse();Vo(S,k,B,T)}function ou(C){var k=E(C);return i(function(T,S){return T.push(function(P,F){if(P)S(null,{error:P});else{var W;arguments.length<=2?W=F:W=o(arguments,1),S(null,{value:W})}}),k.apply(this,T)})}function Y7(C){var k;return An(C)?k=Oi(C,ou):(k={},pl(C,function(B,T){k[T]=ou.call(this,B)})),k}function J7(C,k,B,T){am(C,k,function(S,D){B(S,function(P,F){D(P,!F)})},T)}var K7=Li(J7),hm=Mi(J7),X7=lt(hm,1);function e8(C){return function(){return C}}function ru(C,k,B){var T=5,S=0,D={times:T,intervalFunc:e8(S)};function P(Z,te){if(typeof te=="object")Z.times=+te.times||T,Z.intervalFunc=typeof te.interval=="function"?te.interval:e8(+te.interval||S),Z.errorFilter=te.errorFilter;else if(typeof te=="number"||typeof te=="string")Z.times=+te||T;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof C=="function"?(B=k||he,k=C):(P(D,C),B=B||he),typeof k!="function")throw new Error("Invalid arguments for async.retry");var F=E(k),W=1;function J(){F(function(Z){Z&&W++<D.times&&(typeof D.errorFilter!="function"||D.errorFilter(Z))?setTimeout(J,D.intervalFunc(W)):B.apply(null,arguments)})}J()}var t8=function(C,k){k||(k=C,C=null);var B=E(k);return i(function(T,S){function D(P){B.apply(null,T.concat(P))}C?ru(C,D,S):ru(D,S)})};function n8(C,k){um(Pi,C,k)}var iu=Li(Fi(Boolean,Cl)),wl=Mi(Fi(Boolean,Cl)),su=lt(wl,1);function o8(C,k,B){var T=E(k);Ha(C,function(D,P){T(D,function(F,W){if(F)return P(F);P(null,{value:D,criteria:W})})},function(D,P){if(D)return B(D);B(null,Oi(P.sort(S),F7("value")))});function S(D,P){var F=D.criteria,W=P.criteria;return F<W?-1:F>W?1:0}}function r8(C,k,B){var T=E(C);return i(function(S,D){var P=!1,F;function W(){var J=C.name||"anonymous",Z=new Error('Callback function "'+J+'" timed out.');Z.code="ETIMEDOUT",B&&(Z.info=B),P=!0,D(Z)}S.push(function(){P||(D.apply(null,arguments),clearTimeout(F))}),F=setTimeout(W,k),T.apply(null,S)})}var wU=Math.ceil,BU=Math.max;function EU(C,k,B,T){for(var S=-1,D=BU(wU((k-C)/(B||1)),0),P=Array(D);D--;)P[T?D:++S]=C,C+=B;return P}function lu(C,k,B,T){var S=E(B);Ri(EU(0,C,1),k,S,T)}var i8=lt(lu,1/0),s8=lt(lu,1);function l8(C,k,B,T){arguments.length<=3&&(T=B,B=k,k=An(C)?[]:{}),T=zo(T||he);var S=E(B);Uo(C,function(D,P,F){S(k,D,P,F)},function(D){T(D,k)})}function c8(C,k){var B=null,T;k=k||he,vl(C,function(S,D){E(S)(function(P,F){arguments.length>2?T=o(arguments,1):T=F,B=P,D(!P)})},function(){k(B,T)})}function a8(C){return function(){return(C.unmemoized||C).apply(null,arguments)}}function fm(C,k,B){B=Fn(B||he);var T=E(k);if(!C())return B(null);var S=function(D){if(D)return B(D);if(C())return T(S);var P=o(arguments,1);B.apply(null,[null].concat(P))};T(S)}function u8(C,k,B){fm(function(){return!C.apply(this,arguments)},k,B)}var d8=function(C,k){if(k=zo(k||he),!An(C))return k(new Error("First argument to waterfall must be an array of functions"));if(!C.length)return k();var B=0;function T(D){var P=E(C[B++]);D.push(Fn(S)),P.apply(null,D)}function S(D){if(D||B===C.length)return k.apply(null,arguments);T(o(arguments,1))}T([])},IU={apply:r,applyEach:u7,applyEachSeries:d7,asyncify:p,auto:nm,autoInject:y7,cargo:B7,compose:E7,concat:I7,concatLimit:Va,concatSeries:x7,constant:T7,detect:qa,detectLimit:Al,detectSeries:Wa,dir:L7,doDuring:M7,doUntil:R7,doWhilst:lm,during:O7,each:Ga,eachLimit:bl,eachOf:Uo,eachOfLimit:Lr,eachOfSeries:Pi,eachSeries:vl,ensureAsync:cm,every:Qa,everyLimit:yl,everySeries:Ya,filter:Ja,filterLimit:kl,filterSeries:Ka,forever:N7,groupBy:$7,groupByLimit:Xa,groupBySeries:_7,log:j7,map:Ha,mapLimit:Ri,mapSeries:tm,mapValues:H7,mapValuesLimit:eu,mapValuesSeries:z7,memoize:V7,nextTick:q7,parallel:W7,parallelLimit:G7,priorityQueue:Z7,queue:dm,race:Q7,reduce:Vo,reduceRight:nu,reflect:ou,reflectAll:Y7,reject:K7,rejectLimit:hm,rejectSeries:X7,retry:ru,retryable:t8,seq:sm,series:n8,setImmediate:m,some:iu,someLimit:wl,someSeries:su,sortBy:o8,timeout:r8,times:i8,timesLimit:lu,timesSeries:s8,transform:l8,tryEach:c8,unmemoize:a8,until:u8,waterfall:d8,whilst:fm,all:Qa,allLimit:yl,allSeries:Ya,any:iu,anyLimit:wl,anySeries:su,find:qa,findLimit:Al,findSeries:Wa,forEach:Ga,forEachSeries:vl,forEachLimit:bl,forEachOf:Uo,forEachOfSeries:Pi,forEachOfLimit:Lr,inject:Vo,foldl:Vo,foldr:nu,select:Ja,selectLimit:kl,selectSeries:Ka,wrapSync:p};t.default=IU,t.apply=r,t.applyEach=u7,t.applyEachSeries=d7,t.asyncify=p,t.auto=nm,t.autoInject=y7,t.cargo=B7,t.compose=E7,t.concat=I7,t.concatLimit=Va,t.concatSeries=x7,t.constant=T7,t.detect=qa,t.detectLimit=Al,t.detectSeries=Wa,t.dir=L7,t.doDuring=M7,t.doUntil=R7,t.doWhilst=lm,t.during=O7,t.each=Ga,t.eachLimit=bl,t.eachOf=Uo,t.eachOfLimit=Lr,t.eachOfSeries=Pi,t.eachSeries=vl,t.ensureAsync=cm,t.every=Qa,t.everyLimit=yl,t.everySeries=Ya,t.filter=Ja,t.filterLimit=kl,t.filterSeries=Ka,t.forever=N7,t.groupBy=$7,t.groupByLimit=Xa,t.groupBySeries=_7,t.log=j7,t.map=Ha,t.mapLimit=Ri,t.mapSeries=tm,t.mapValues=H7,t.mapValuesLimit=eu,t.mapValuesSeries=z7,t.memoize=V7,t.nextTick=q7,t.parallel=W7,t.parallelLimit=G7,t.priorityQueue=Z7,t.queue=dm,t.race=Q7,t.reduce=Vo,t.reduceRight=nu,t.reflect=ou,t.reflectAll=Y7,t.reject=K7,t.rejectLimit=hm,t.rejectSeries=X7,t.retry=ru,t.retryable=t8,t.seq=sm,t.series=n8,t.setImmediate=m,t.some=iu,t.someLimit=wl,t.someSeries=su,t.sortBy=o8,t.timeout=r8,t.times=i8,t.timesLimit=lu,t.timesSeries=s8,t.transform=l8,t.tryEach=c8,t.unmemoize=a8,t.until=u8,t.waterfall=d8,t.whilst=fm,t.all=Qa,t.allLimit=yl,t.allSeries=Ya,t.any=iu,t.anyLimit=wl,t.anySeries=su,t.find=qa,t.findLimit=Al,t.findSeries=Wa,t.forEach=Ga,t.forEachSeries=vl,t.forEachLimit=bl,t.forEachOf=Uo,t.forEachOfSeries=Pi,t.forEachOfLimit=Lr,t.inject=Vo,t.foldl=Vo,t.foldr=nu,t.select=Ja,t.selectLimit=kl,t.selectSeries=Ka,t.wrapSync=p,Object.defineProperty(t,"__esModule",{value:!0})})})(ah,ah.exports);var Z2={exports:{}},uh=Z2.exports=function(n,e){if(e||(e=16),n===void 0&&(n=128),n<=0)return"0";for(var t=Math.log(Math.pow(2,n))/Math.log(e),o=2;t===1/0;o*=2)t=Math.log(Math.pow(2,n/o))/Math.log(e)*o;for(var r=t-Math.floor(t),i="",o=0;o<Math.floor(t);o++){var s=Math.floor(Math.random()*e).toString(e);i=s+i}if(r){var l=Math.pow(e,r),s=Math.floor(Math.random()*l).toString(e);i=s+i}var c=parseInt(i,e);return c!==1/0&&c>=Math.pow(2,n)?uh(n,e):i};uh.rack=function(n,e,t){var o=function(i){var s=0;do{if(s++>10)if(t)n+=t;else throw new Error("too many ID collisions, use more bits");var l=uh(n,e)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=e||16,o};var Q2=Bo,lw=W2,cw=G2,Ic=cn,dh=ah.exports,aw=Z2.exports,Y2=mr.ACTIONS,J2=_e;function _e(n,e){if(Q2.EventEmitter.call(this),!e||typeof e!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=e,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}Q2.mixin(_e),_e.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},_e.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},_e.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||aw();var e=this._createLocalPresence(n);return this.localPresences[n]=e,e},_e.prototype.destroy=function(n){this._wantsDestroy=!0;var e=this,t=Object.keys(e.localPresences);this.unsubscribe(function(o){if(o)return e._callbackOrEmit(o,n);var r=Object.keys(e._remotePresenceInstances);dh.parallel([function(i){dh.each(t,function(s,l){e.localPresences[s].destroy(l)},i)},function(i){if(!e._wantsDestroy)return i();dh.each(r,function(s,l){e._remotePresenceInstances[s].destroy(l)},i)}],function(i){e._wantsDestroy&&delete e.connection._presences[e.channel],e._callbackOrEmit(i,n)})})},_e.prototype._sendSubscriptionAction=function(n,e){this.wantSubscribe=!!n;var t=this.wantSubscribe?Y2.presenceSubscribe:Y2.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=e,this.connection.canSend&&this.connection._sendPresenceAction(t,o,this)},_e.prototype._handleSubscribe=function(n,e){this.wantSubscribe&&(this.subscribed=!0);var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},_e.prototype._handleUnsubscribe=function(n,e){this.subscribed=!1;var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},_e.prototype._receiveUpdate=function(n,e){var t=Ic.dig(this.localPresences,e.id);if(t)return t._ack(n,e.pv);if(n)return this.emit("error",n);var o=this,r=Ic.digOrCreate(this._remotePresenceInstances,e.id,function(){return o._createRemotePresence(e.id)});r.receiveUpdate(e)},_e.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},_e.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var e in this.localPresences){var t=this.localPresences[e];t.value!==null&&t.send()}},_e.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},_e.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},_e.prototype._resubscribe=function(){var n=[];for(var e in this._subscriptionCallbacksBySeq){var t=this._subscriptionCallback(e);n.push(t)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},_e.prototype._subscriptionCallback=function(n){var e=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],e},_e.prototype._callbackOrEmit=function(n,e){if(e)return Ic.nextTick(e,n);n&&this.emit("error",n)},_e.prototype._createLocalPresence=function(n){return new lw(this,n)},_e.prototype._createRemotePresence=function(n){return new cw(this,n)},_e.prototype._callEachOrEmit=function(n,e){var t=Ic.callEach(n,e);!t&&e&&this.emit("error",e)};var ys=W2,K2=yc,uw=cn,X2=K2.CODES,dw=un;function un(n,e){ys.call(this,n,e),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}un.prototype=Object.create(ys.prototype),un.prototype.submit=function(n,e){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,e);var t={code:X2.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(t,e)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,ys.prototype.submit.call(this,n,e)},un.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),ys.prototype.destroy.call(this,n)},un.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(e){e.t=n._doc.type.uri,e.v=n._doc.version,n.connection.send(e)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},un.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)},un.prototype._transformAgainstOp=function(n,e){var t=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=t._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=t._transformPresence(r.p,n,e),t._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=t._getCallback(r.pv);t._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,e)}catch(r){this.emit("error",r)}},un.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},un.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},un.prototype._message=function(){var n=ys.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},un.prototype._transformPresence=function(n,e,t){var o=this._doc.type;if(!uw.supportsPresence(o))throw new K2(X2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,e,t)};var e5={};(function(n){var e=As,t=yc,o=cn,r=t.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var a=e.map[c];if(a==null||typeof a!="object")return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new t(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new t(r.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new t(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return e.map[l]&&e.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new t(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new t(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new t(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var a=c.create,u=e.map[a.type];if(!u)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=u.create(a.data),l.type=u.uri,l.v++}catch(m){return m}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var f=i(l,c.op);if(f)return f;l.v++}else l.v++};function i(l,c){if(!l.type)return new t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new t(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var a=e.map[l.type];if(!a)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=a.apply(l.data,c)}catch(u){return new t(r.ERR_OT_OP_NOT_APPLIED,u.message)}}n.transform=function(l,c,a){if(c.v!=null&&c.v!==a.v)return new t(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(a.del){if(c.create||"op"in c)return new t(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(a.create&&("op"in c||c.create||c.del)||"op"in a&&c.create)return new t(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in a&&"op"in c){if(!l)return new t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=e.map[l],!l))return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,a.op,"left")}catch(u){return u}}}c.v!=null&&c.v++},n.applyOps=function(l,c,a){a=a||{};for(var u=0;u<c.length;u++){var f=c[u];if(a._normalizeLegacyJson0Ops)try{s(l,f)}catch{return new t(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=f.v;var m=n.apply(l,f);if(m)return m}},n.transformPresence=function(l,c,a){var u=this.checkOp(c);if(u)return u;var f=l.t;if(typeof f=="string"&&(f=e.map[f]),!f)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(f))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:f.transformPresence(l.p,c.op,a)}catch(m){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:m.message||m}}l.v++};function s(l,c){if(l.type===e.defaultType.uri){var a=c.op;if(!!a){var u=l.data;a.length>1&&(u=o.clone(u));for(var f=0;f<a.length;f++){var m=a[f];typeof m.lm=="string"&&(m.lm=+m.lm);for(var p=m.p,b=u,y=0;y<p.length;y++){var v=p[y];Object.prototype.toString.call(b)=="[object Array]"?p[y]=+v:b.constructor===Object&&(p[y]=v.toString()),b=b[v]}f<a.length-1&&(u=e.defaultType.apply(u,[m]))}}}}})(e5);var ks=G2,hw=e5,fw=jt;function jt(n,e){ks.call(this,n,e),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._pending=null,this._opCache=null,this._pendingSetPending=!1,this._opHandler=this._handleOp.bind(this),this._createDelHandler=this._handleCreateDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._registerWithDoc()}jt.prototype=Object.create(ks.prototype),jt.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},jt.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),ks.prototype.destroy.call(this,n)},jt.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)},jt.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))}})}},jt.prototype._handleOp=function(n,e,t){var o=t===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},ks.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},ks.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},jt.prototype._transformAgainstOp=function(n,e){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,e)}catch(t){return this.presence.emit("error",t)}this.presence._updateRemotePresence(this)}},jt.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],e=n.op,t=n.isOwnOp;e===null?(this._pending.p=null,this._pending.v++):hw.transformPresence(this._pending,e,t)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},jt.prototype._startCachingOps=function(){this._opCache=[]},jt.prototype._stopCachingOps=function(){this._opCache=null},jt.prototype._cacheOp=function(n,e){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:e})};var t5=J2,mw=dw,gw=fw;function Qr(n,e,t){var o=Qr.channel(e,t);t5.call(this,n,o),this.collection=e,this.id=t}var pw=Qr;Qr.prototype=Object.create(t5.prototype),Qr.channel=function(n,e){return n+"."+e},Qr.prototype._createLocalPresence=function(n){return new mw(this,n)},Qr.prototype._createRemotePresence=function(n){return new gw(this,n)};var Cw=Aw;function Aw(n,e,t,o,r){this.id=n,this.v=e,this.type=t,this.data=o,this.m=r}var bw=Cw,n5=Bo,o5=ws;function ws(n,e,t,o,r){if(n5.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=e,this.connection=n,this.id=o,this.collection=t,this.callback=r,this.sent=!1}n5.mixin(ws),ws.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},ws.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},ws.prototype._handleResponse=function(n,e){if(this.emit("ready"),n)return this.callback(n);var t=e.meta?e.meta:null,o=new bw(this.id,e.v,e.type,e.data,t);this.callback(null,o)};var r5=o5,vw=cn,yw=mr.ACTIONS,kw=hh;function hh(n,e,t,o,r,i){if(r5.call(this,n,e,t,o,i),!vw.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}hh.prototype=Object.create(r5.prototype),hh.prototype._message=function(){return{a:yw.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var i5=o5,ww=cn,Bw=mr.ACTIONS,Ew=fh;function fh(n,e,t,o,r,i){if(i5.call(this,n,e,t,o,i),!ww.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}fh.prototype=Object.create(i5.prototype),fh.prototype._message=function(){return{a:Bw.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var Iw=Kk,xw=ow,Tw=J2,s5=pw,Dw=kw,Sw=Ew,l5=Bo,Yr=yc,be=mr.ACTIONS,c5=As,dn=cn,Bs=N2,Es=Yr.CODES;function a5(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var Lw=X;function X(n){l5.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=a5(n),this.bindToSocket(n)}l5.mixin(X),X.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var e=a5(n);this._setState(e),this.canSend=!1;var t=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Bs.warn("Failed to parse message",o);return}t.debug&&Bs.info("RECV",JSON.stringify(r));var i={data:r};if(t.emit("receive",i),!!i.data)try{t.handleMessage(i.data)}catch(s){dn.nextTick(function(){t.emit("error",s)})}},n.readyState===1&&t._initializeHandshake(),n.onopen=function(){t._setState("connecting"),t._initializeHandshake()},n.onerror=function(o){t.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?t._setState("closed",o):o==="stopped"||o==="Stopped by server"?t._setState("stopped",o):t._setState("disconnected",o)}},X.prototype.handleMessage=function(n){var e=null;switch(n.error&&(e=u5(n.error,n),delete n.error),n.a){case be.initLegacy:return this._handleLegacyInit(n);case be.handshake:return this._handleHandshake(e,n);case be.queryFetch:var t=this.queries[n.id];t&&t._handleFetch(e,n.data,n.extra);return;case be.querySubscribe:var t=this.queries[n.id];t&&t._handleSubscribe(e,n.data,n.extra);return;case be.queryUnsubscribe:return;case be.queryUpdate:var t=this.queries[n.id];if(!t)return;if(e)return t._handleError(e);n.diff&&t._handleDiff(n.diff),n.hasOwnProperty("extra")&&t._handleExtra(n.extra);return;case be.bulkFetch:return this._handleBulkMessage(e,n,"_handleFetch");case be.bulkSubscribe:case be.bulkUnsubscribe:return this._handleBulkMessage(e,n,"_handleSubscribe");case be.snapshotFetch:case be.snapshotFetchByTimestamp:return this._handleSnapshotFetch(e,n);case be.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(e,n.data);return;case be.subscribe:case be.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(e,n.data);return;case be.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(e,n);return;case be.presence:return this._handlePresence(e,n);case be.presenceSubscribe:return this._handlePresenceSubscribe(e,n);case be.presenceUnsubscribe:return this._handlePresenceUnsubscribe(e,n);case be.presenceRequest:return this._handlePresenceRequest(e,n);case be.pingPong:return this._handlePingPong(e);default:Bs.warn("Ignoring unrecognized message",n)}};function u5(n,e){var t=new Error(n.message);return t.code=n.code,e&&(t.data=e),t}X.prototype._handleBulkMessage=function(n,e,t){if(e.data)for(var o in e.data){var r=e.data[o],i=this.getExisting(e.c,o);i&&(n?i[t](n):r.error?i[t](u5(r.error)):i[t](null,r))}else if(Array.isArray(e.b))for(var s=0;s<e.b.length;s++){var o=e.b[s],i=this.getExisting(e.c,o);i&&i[t](n)}else if(e.b)for(var o in e.b){var i=this.getExisting(e.c,o);i&&i[t](n)}else Bs.error("Invalid bulk message",e)},X.prototype._reset=function(){this.agent=null},X.prototype._setState=function(n,e){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var t=new Yr(Es.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",t)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var c=this._snapshotRequests[o];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,e),this.emit("state",n,e)}},X.prototype.startBulk=function(){this.bulk||(this.bulk={})},X.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var e=this.bulk[n];this._sendBulk("f",n,e.f),this._sendBulk("s",n,e.s),this._sendBulk("u",n,e.u)}this.bulk=null},X.prototype._sendBulk=function(n,e,t){if(!!t){var o=[],r={},i=0,s;for(var l in t){var c=t[l];c==null?o.push(l):(r[l]=c,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:e,d:l})}else o.length&&this.send({a:"b"+n,c:e,b:o});if(i===1){var a=r[s];this.send({a:n,c:e,d:s,v:a})}else i&&this.send({a:"b"+n,c:e,b:r})}},X.prototype._sendActions=function(n,e,t){if(this._addDoc(e),this.bulk){var o=this.bulk[e.collection]||(this.bulk[e.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(e.id);return r[e.id]=t,i}else{var s={a:n,c:e.collection,d:e.id,v:t};this.send(s)}},X.prototype.sendFetch=function(n){return this._sendActions(be.fetch,n,n.version)},X.prototype.sendSubscribe=function(n){return this._sendActions(be.subscribe,n,n.version)},X.prototype.sendUnsubscribe=function(n){return this._sendActions(be.unsubscribe,n)},X.prototype.sendOp=function(n,e){this._addDoc(n);var t={a:be.op,c:n.collection,d:n.id,v:n.version,src:e.src,seq:e.seq,x:{}};"op"in e&&(t.op=e.op),e.create&&(t.create=e.create),e.del&&(t.del=e.del),n.submitSource&&(t.x.source=e.source),this.send(t)},X.prototype.send=function(n){this.debug&&Bs.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},X.prototype.ping=function(){if(!this.canSend)throw new Yr(Es.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:be.pingPong};this.send(n)},X.prototype.close=function(){this.socket.close()},X.prototype.getExisting=function(n,e){if(this.collections[n])return this.collections[n][e]},X.prototype.get=function(n,e){var t=this.collections[n]||(this.collections[n]={}),o=t[e];return o||(o=t[e]=new Iw(this,n,e),this.emit("doc",o)),o._wantsDestroy=!1,o},X.prototype._destroyDoc=function(n){!n._wantsDestroy||(dn.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},X.prototype._addDoc=function(n){var e=this.collections[n.collection];e||(e=this.collections[n.collection]={}),e[n.id]!==n&&(e[n.id]=n)},X.prototype._createQuery=function(n,e,t,o,r){var i=this.nextQueryId++,s=new xw(n,this,i,e,t,o,r);return this.queries[i]=s,s.send(),s},X.prototype._destroyQuery=function(n){delete this.queries[n.id]},X.prototype.createFetchQuery=function(n,e,t,o){return this._createQuery(be.queryFetch,n,e,t,o)},X.prototype.createSubscribeQuery=function(n,e,t,o){return this._createQuery(be.querySubscribe,n,e,t,o)},X.prototype.hasPending=function(){return!!(this._firstDoc(xc)||this._firstQuery(xc)||this._firstSnapshotRequest())};function xc(n){return n.hasPending()}X.prototype.hasWritePending=function(){return!!this._firstDoc(Mw)};function Mw(n){return n.hasWritePending()}X.prototype.whenNothingPending=function(n){var e=this._firstDoc(xc);if(e){e.once("nothing pending",this._nothingPendingRetry(n));return}var t=this._firstQuery(xc);if(t){t.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}dn.nextTick(n)},X.prototype._nothingPendingRetry=function(n){var e=this;return function(){dn.nextTick(function(){e.whenNothingPending(n)})}},X.prototype._firstDoc=function(n){for(var e in this.collections){var t=this.collections[e];for(var o in t){var r=t[o];if(n(r))return r}}},X.prototype._firstQuery=function(n){for(var e in this.queries){var t=this.queries[e];if(n(t))return t}},X.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},X.prototype.fetchSnapshot=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new Dw(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},X.prototype.fetchSnapshotByTimestamp=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new Sw(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},X.prototype._handleSnapshotFetch=function(n,e){var t=this._snapshotRequests[e.id];!t||(delete this._snapshotRequests[e.id],t._handleResponse(n,e))},X.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},X.prototype._initializeHandshake=function(){this.send({a:be.handshake,id:this.id})},X.prototype._handleHandshake=function(n,e){if(n)return this.emit("error",n);this._initialize(e)},X.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},X.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Yr(Es.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(c5.map[n.type]!==c5.defaultType)return this.emit("error",new Yr(Es.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Yr(Es.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},X.prototype.getPresence=function(n){var e=this,t=dn.digOrCreate(this._presences,n,function(){return new Tw(e,n)});return t._wantsDestroy=!1,t},X.prototype.getDocPresence=function(n,e){var t=s5.channel(n,e),o=this,r=dn.digOrCreate(this._presences,t,function(){return new s5(o,n,e)});return r._wantsDestroy=!1,r},X.prototype._sendPresenceAction=function(n,e,t){this._addPresence(t);var o={a:n,ch:t.channel,seq:e};return this.send(o),o.seq},X.prototype._addPresence=function(n){dn.digOrCreate(this._presences,n.channel,function(){return n})},X.prototype._handlePresenceSubscribe=function(n,e){var t=dn.dig(this._presences,e.ch);t&&t._handleSubscribe(n,e.seq)},X.prototype._handlePresenceUnsubscribe=function(n,e){var t=dn.dig(this._presences,e.ch);t&&t._handleUnsubscribe(n,e.seq)},X.prototype._handlePresence=function(n,e){var t=dn.dig(this._presences,e.ch);t&&t._receiveUpdate(n,e)},X.prototype._handlePresenceRequest=function(n,e){var t=dn.dig(this._presences,e.ch);t&&t._broadcastAllLocalPresence(n,e)};var d5=Lw,Rw=As;const Tc={err:1001,msg:"user auth error",name:"AuthError"},Ow={err:1002,msg:"you don't have required permission",name:"PermissionError"},mh={err:1003,msg:"Too many user connected",name:"MaxUserError"},Is={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},Pw={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},Fw={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},xs="x-live-editor-token",Dc="x-live-editor-base-url",Ct=w("auth-connection");function Nw(n){try{n()}catch(e){Ct.error(e)}}class $w{constructor(e,t){h(this,"connection");h(this,"ws");h(this,"retryCount");h(this,"events",new pm.EventEmitter);h(this,"token",null);h(this,"resourceToken",null);this.url=e,this.reauthFunc=t,this.retryCount=0}getBaseURL(){const e=new URL(this.url);return`${e.protocol==="wss:"?"https:":"http:"}//${e.host}${e.pathname}`}getBase64BaseURL(){return Ko(this.getBaseURL())}async auth(e){d(Ct,e.token,"no auth token");const t=`${this.getBaseURL()}/auth`,o=await window.fetch(t,{method:"GET",headers:{[xs]:e.token,[Dc]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=e.token,await o.json()}async logout(){if(!this.token)return;const e=`${this.getBaseURL()}/logout`;await window.fetch(e,{method:"GET",headers:{[Dc]:Ko(this.getBaseURL())}})}async init(e){const t=await this.auth(e);this.resourceToken=t.read,this.ws=new _8.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(d5.prototype),d(Ct,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:e})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},d5.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,Ct.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const e=await this.reauthFunc();await this.auth(e),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:e})}}}catch(e){Ct.error(e),setTimeout(()=>this.handleAuthError(),0)}}else Ct.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const e=new Error(Tc.msg);e.code=Tc.err,this.events.emit("error",e)}emitRequestReloadError(){const e=new Error(Is.msg);e.code=Is.err,this.events.emit("requestReloadError",e)}emitWriteConflictError(e,t){e.orgMsg=t,this.events.emit("writeConflictError",e)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(e){const t=e;if(t.a==="pong")return;const o=t.err;if(o===Tc.err)Ct.warn("auth error"),this.handleAuthError();else if(o===mh.err)Ct.warn(mh.msg),this.emitMaxUsersError();else if(o===Is.err){Ct.warn(Is.msg);try{this.emitRequestReloadError()}catch(r){Ct.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else Ct.error(`unknown message received: ${JSON.stringify(t)}`),this.emitAuthError()}get(e,t){return d(Ct,this.connection,"no this.connection"),this.connection.get(e,t)}addEventListener(e,t){e==="error"?this.events.addListener(e,t):(d(Ct,this.ws,"no this.ws"),this.ws.addEventListener(e,t))}onWriteConflictError(e){this.events.addListener("writeConflictError",e)}onMaxUsersError(e){d(Ct,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",e)}onRequestReloadError(e){d(Ct,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",e)}end(e){var t;this.reauthFunc=void 0,this.events.removeAllListeners(),Nw(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(t=this.ws)==null||t.close(),this.ws=void 0,e&&this.logout()}}w("utils/file");function _w(){function n(){return new Promise(e=>{const t=new FileReader;t.onload=()=>{e(t.result)},t.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}_w();async function jw(n){const t=n.size,o=Math.floor((t+102400-1)/102400),r=new j8.Hash;for(let s=0;s<o;s++){const l=s*102400;let c=l+102400;c>t&&(c=t);const u=await n.slice(l,c,n.type).arrayBuffer();r.update(new Uint8Array(u))}const i=r.digest();return Ko(i)}const xn=w("sharedb-doc/client");class Hw{constructor(e,t,o){h(this,"connection");h(this,"auth");h(this,"doc",null);h(this,"reauthFunc");h(this,"clientId",N());h(this,"getDoc",async()=>{const e=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});d(xn,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const t=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=t,await e(t),xn.debug(t),t});this.auth=e;const r=`${t}/${this.auth.appId}/${this.auth.docId}`;Rw.register(El.type),this.connection=new $w(r,o),this.reauthFunc=o}editorServer(){const e=this.apiServer(),t=`/${this.auth.appId}/${this.auth.docId}`;return d(xn,e.endsWith(t),`invalid api server: ${e}, ${t}`),e.substr(0,e.length-t.length)}close(e){this.connection.end(e),this.doc=null}on(e,t){this.connection.addEventListener(e,o=>{(e==="error"||this.doc)&&t(o)})}onWriteConflictError(e){this.connection.onWriteConflictError(e)}onMaxUsersError(e){this.connection.onMaxUsersError(e)}onRequestReloadError(e){this.connection.onRequestReloadError(e)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const e=this.connection.url;if(e.startsWith("ws://"))return`http://${e.substring(5)}`;if(e.startsWith("wss://"))return`https://${e.substring(6)}`;throw new Error(`invalid server url: ${e}`)}async getFileUrlByHash(e,t,o,r,i){try{const s=`${e}/${t}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(e){const o=`${this.apiServer()}/resources`;let r=[];e.forEach(l=>{const c=l.split("|");r.push(...c)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[xs]:this.connection.token}));return await Promise.all(i)}async uploadFile(e,t,o,r,i){let s=t.size;if(s===0)throw new Error("file is empty");s+=500;const l=p=>{xn.info(`on progress: ${p.loaded}`);let b=p.loaded*100/s;b>100&&(b=100),r(b)},c=await jw(t),a=await this.getFileUrlByHash(e,c,t.name,t.size,o);if(a)return r(-1),a;let u=e;i!=null&&i.thumbnail&&(u+="/thumbnail");const f=new FormData;f.append("file-size",`${t.size}`),f.append("file-hash",c),f.append("file",t,t.name);const m=await this.request(u,{method:"post",data:f,withCredentials:!0,headers:{...o},onUploadProgress:l});return xn.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(e,t=()=>{},o){const i=`${this.apiServer()}/resources`;d(xn,this.connection.token,"no connection token");const s=await this.uploadFile(i,e,{[xs]:this.connection.token},t,o);return d(xn,s,"no result"),s}async request(e,t){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const c=t||{};c.url=e,c.headers||(c.headers={}),d(xn,o,"no token"),c.headers={...c.headers,[xs]:o,[Dc]:this.connection.getBase64BaseURL()};try{return await N8.default(e,c)}catch(a){if(r=a,((i=a==null?void 0:a.response)==null?void 0:i.status)===403&&this.reauthFunc){const u=await this.reauthFunc();if(await this.connection.auth(u),!u.token)throw a;o=u.token;continue}throw(s=a.response)!=null&&s.data&&(a.responseData=a.response.data),a}}throw d(xn,r,"no error"),r}async getVersions(){const t=`${this.apiServer()}/versions`,r=(await this.request(t)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(e){const o=`${this.apiServer()}/versions/${e}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const t=`${this.apiServer()}/versions/latest`,o=await this.request(t);return JSON.parse(o.data.data)}async getVersionOps(e,t){let r=`${this.apiServer()}/versions/before/${e}?withOp=true`;t!==void 0&&t!==0&&(r+=`&from=${t}`);const i=await this.request(r),s=i.data.ops,l=$8.default(s,u=>!!u.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(xn,c.create,"no createDoc.create"),a=c.create.data):a=JSON.parse(i.data.data),a.blocks||(a.blocks=[]),{doc:a,ops:i.data.ops}}async updateVersionExtra(e,t,o){const i=`${this.apiServer()}/versions/${e}/tags/${t}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(e){const o=`${this.apiServer()}/versions/revert/${e}`;await this.request(o,{method:"post",data:{}})}async createVersion(e,t){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:t,tag:e}})).data}async recognizeLink(e){const o=`${this.apiServer()}/resources/external/${Ko(e)}`;return(await this.request(o)).data}buildResourceUrl(e,t){if(!e)return"";if(e.startsWith("https:")||e.startsWith("http:")||e.startsWith("file:")||e.startsWith("data:")||e.startsWith("blob:"))return e;let r=`${this.apiServer()}/resources/${encodeURIComponent(e)}`;const i=[];if(t!=null&&t.withToken&&i.push(`token=${this.getResourceToken()}`),t!=null&&t.downloadFileName&&i.push(`&fileName=${encodeURIComponent(t.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function zw(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const gh=w("block-ids");class Uw{constructor(){h(this,"ids",new Map)}onInsertBlock(e){const t=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<t.length;r++){const i=t[r];if(i>=e){const s=this.ids.get(i);d(gh,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=N();this.ids.set(e,o)}onDeleteBlock(e){this.ids.delete(e);const t=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<t.length;o++){const r=t[o];if(r>e){const i=this.ids.get(r);d(gh,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(e){let t=this.ids.get(e);return t||(t=N(),this.ids.set(e,t)),t}getById(e){return Array.from(this.ids.entries()).find(([,t])=>t===e)}}class Vw{constructor(){h(this,"ids",new Map)}getContainerIds(e){let t=this.ids.get(e);return t||(t=new Uw,this.ids.set(e,t)),t}onInsertBlock(e,t){this.getContainerIds(e).onInsertBlock(t)}onDeleteBlock(e,t){this.getContainerIds(e).onDeleteBlock(t)}getBlockId(e,t){return this.getContainerIds(e).getId(t)}getBlockIndexById(e){const t=Array.from(this.ids.entries());for(let o=0;o<t.length;o++){const r=t[o],i=r[1].getById(e);if(i)return{containerId:r[0],blockIndex:i[0]}}return d(gh,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class h5{constructor(e=new Set,t=new Map){this.deletedKeys=e,this.insertedValues=t}insert(e,t){this.insertedValues.set(e,t)}delete(e){this.deletedKeys.add(e)}toDocBlockDelta(){const e={};return this.insertedValues.forEach((t,o)=>{e[o]=t}),{insert:e,delete:Array.from(this.deletedKeys)}}}const Sc=w("op-parse-handler");class qw{constructor(e,t){h(this,"actions",[]);this.outerHandler=e,this.local=t}pushActions(e){if(!e.containerId){this.actions.push(e);return}const o={...e,containerId:(r=>r==="blocks"?"root":r)(e.containerId)};this.actions.push(o)}onDeleteBlock(e,t){this.pushActions({type:"deleteBlock",containerId:e,blockIndex:t})}onInsertBlock(e,t,o){this.pushActions({type:"insertBlock",containerId:e,blockIndex:t,data:o})}onDeleteBlockData(e,t,o){this.pushActions({type:"deleteBlockData",containerId:e,blockIndex:t,key:o})}onInsertBlockData(e,t,o,r){this.pushActions({type:"insertBlockData",containerId:e,blockIndex:t,key:o,value:r})}onUpdateBlockText(e,t,o){this.pushActions({type:"updateBlockText",containerId:e,blockIndex:t,richTextData:o})}onDeleteContainer(e){this.pushActions({type:"deleteContainer",containerId:e})}onCreateContainer(e,t){this.pushActions({type:"createContainer",containerId:e,data:t})}onDeleteComment(e){this.pushActions({type:"deleteComment",commentId:e})}onCreateComment(e){this.pushActions({type:"createComment",commentId:e})}onUpdateComment(e){this.pushActions({type:"updateComment",commentId:e})}end(){const e=this.actions,t=new Set,o=new Map,r=new Vw,i=e.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,c=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const a=o.get(c);a&&(Sc.debug(`ignore update object data before delete block: ${JSON.stringify(a)}`),o.delete(c));const u=`${l.containerId}-${l.blockIndex}`;t.add(u),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,c=`${l.containerId}-${l.blockIndex}`;if(t.has(c)){Sc.warn("delete block data after delete block, ignore it");continue}const a=r.getBlockId(l.containerId,l.blockIndex);let u=o.get(a);u||(u=new h5,o.set(a,u)),u.delete(l.key)}else d(Sc,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,c=r.getBlockId(l.containerId,l.blockIndex);let a=o.get(c);a||(a=new h5,o.set(c,a)),a.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:c,blockIndex:a}=r.getBlockIndexById(s);Sc.debug(`update block data: ${c}, ${a}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(c,a,l.toDocBlockDelta(),this.local)})}}const je=w("op-parser");class f5{}class ph{constructor(e){h(this,"key");this.key=e}}function Ww(n,e,t){const o=e.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const c=o[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const u=c[1];if(typeof u!="object"||u.i===void 0||Object.keys(u).length!==1)return!1}const s=i.i;d(je,s.id,"block id is required"),d(je,s.type,"block type is required");for(let l=1;l<o.length;l++){const c=o[l],a=c[0],u=c[1];s[a]=u.i}return t.onInsertBlock(n,r,s),!0}function Ch(n,e,t,o){if(t==="upsert"&&Ww(n,e,o))return;d(je,Array.isArray(e),`invalid block op: ${n}, ${JSON.stringify(e)}`);const r=e.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const c=r[1];if(d(je,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(e)}`),d(je,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(e)}`),r.splice(0,2),t==="upsert"){const u=c.e;o.onUpdateBlockText(n,i,u)}d(je,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){d(je,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];d(je,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const a=l[1];if(c==="text"){if(d(je,typeof a=="object",`invalid opData type, ${JSON.stringify(a)}`),a.i&&t==="upsert"&&o.onInsertBlockData(n,i,c,a.i),a.r&&t==="remove"&&o.onDeleteBlockData(n,i,c),a.et==="rich-text"&&t==="upsert"){const f=a.e;o.onUpdateBlockText(n,i,f)}}else t==="remove"&&a.r&&s.push(new ph(c)),t==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i);r.shift()}else if(typeof l=="object"){const c=l;t==="remove"&&c.r&&s.push(new f5),t==="upsert"&&c.i&&o.onInsertBlock(n,i,c.i),r.shift()}else{d(je,typeof l=="string","data is not string"),d(je,l!=="text","data !== 'text'"),d(je,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const c=l,a=r[1];t==="remove"&&a.r&&s.push(new ph(c)),t==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof f5?o.onDeleteBlock(n,i):l instanceof ph?o.onDeleteBlockData(n,i,l.key):d(je,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function Gw(n,e,t){je.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function Zw(n,e,t){const o=n[1],r=n[2];d(je,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),d(je,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?je.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?e==="upsert"&&t.onUpdateComment(o):r.i?e==="upsert"&&t.onCreateComment(o):r.r?e==="remove"&&t.onDeleteComment(o):je.error(`unknown comment op, ${JSON.stringify(n)}`)}function Ah(n,e,t){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{Ah(s,e,t)});return}const r=o;if(d(je,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){Gw(n);return}if(r==="comments"){Zw(n,e,t);return}const i=r;if(Array.isArray(n[1]))e==="remove"?n.slice(1).reverse().forEach(s=>{Ch(i,s,e,t)}):n.slice(1).forEach(s=>{Ch(i,s,e,t)});else if(typeof n[1]=="object"){const s=n[1];s.r&&e==="remove"&&t.onDeleteContainer(i),s.i&&e==="upsert"&&t.onCreateContainer(i,s.i)}else d(je,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Ch(i,n.slice(1),e,t)}function m5(n,e,t){const o=new qw(e,t);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=Q.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{Ah(c,i,o)}):Ah(s,i,o)}o.end()}const Qw=w("sharedb-comments");function bh(n){const e=n.blocks;d(Qw,e,"no comment blocks");const t={blocks:{root:e},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(t.blocks[o]=r)}),Q.default(t)}function g5(n){const{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}=n;return{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}}function vh(n,e){const t=Rk(e),{comments:o,meta:r,blocks:i,...s}=t,l={...n,blocks:i,...s},c=Q.default(l);return delete c.children,c}const ke=w("sharedb-doc/doc-container"),p5="ot-json1";El.type.registerSubtype(Ok.type),El.type.name=p5,El.type.invert=null;class Ts extends zi{constructor(t,o,r=!0){super();h(this,"doc");h(this,"client");h(this,"localPresence");h(this,"remoteCaretHandler",new Lk);h(this,"batching",0);h(this,"status","clean");h(this,"disableLogout");h(this,"destroyed",!1);h(this,"handleNothingPending",()=>{this.setStatus("clean")});h(this,"handleCreate",()=>{this.handleReload("doc created")});h(this,"handleDel",()=>{});h(this,"handleReload",t=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,t)})});h(this,"handleReset",async t=>{const o=new Error(`reset doc: ${t}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});h(this,"handleWriteConflictError",t=>{this.handleReset(`write conflict: ${t.message}, ${JSON.stringify(t.orgMsg)}`)});h(this,"insertObject",async(t,o,r)=>{const i=[t,o,{i:r}];return this.submitOp(i)});h(this,"deleteObject",async(t,o)=>{const r=[t,o,{r:!0}];return this.submitOp(r)});h(this,"replaceObject",async(t,o,r)=>{const i=[t,o,{r:!0,i:r}];return this.submitOp(i)});h(this,"updateObject",async(t,o,r)=>{const i=this.data()[t][o],s=[t,o];return Object.entries(r).forEach(([l,c])=>{if(!_i.default(i[l],c))if(i[l]===void 0){if(c!=null){const a={i:c};s.push([l,a])}}else if(c==null){const a={r:!0};s.push([l,a])}else{const a={r:!0,i:c};s.push([l,a])}}),Object.entries(i).forEach(([l,c])=>{if((r[l]===void 0||r[l]===null)&&c!==void 0){const a={r:!0};s.push([l,a])}}),s.length<=2?Promise.resolve():this.submitOp(s)});h(this,"broadcastMessage",async t=>{const o={type:"custom",data:t,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});h(this,"data",()=>this.doc.data);h(this,"submitOp",async t=>new Promise((o,r)=>{if(this.destroyed){ke.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(t,{},i=>{i?(ke.error(`invalid op, ${i.message}, ${JSON.stringify(t)}`),r(i),ke.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ke.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(t)}`))}));h(this,"createDoc",async t=>new Promise((o,r)=>{this.doc.create(t,p5,i=>{i?r(i):o()})}));h(this,"submitInsertChildContainer",async(t,o)=>{const r=[wo(t),{i:o}];return this.submitOp(r)});h(this,"submitDeleteChildContainer",async t=>{const o=[wo(t),{r:!0}];return this.submitOp(o)});h(this,"submitInsertBlock",async(t,o,r)=>{const i=[wo(t),o,{i:r}];return this.submitOp(i)});h(this,"submitDeleteBlock",async(t,o)=>{const r=[wo(t),o,{r:!0}];return this.submitOp(r)});h(this,"submitUpdateBlockData",async(t,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[wo(t),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c)){const u={r:!0,i:a};i.push([c,u])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(c=>{if(l.has(c))return;const a={r:!0};i.push([c,a])}),Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c))return;const u={i:a};i.push([c,u])}),this.submitOp(i)});h(this,"submitUpdateRichText",async(t,o,r)=>{const i=[wo(t),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});h(this,"handleOp",(t,o,r)=>{if(this.destroyed){ke.warn("handleOp: destroyed");return}m5(t,this,!!o)});this.client=t,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,d(ke,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(t){try{const o=new Hw(t.auth,t.serverUrl,t.reauthFunc),r=await o.getDoc(),i=new Ts(o,r,t.disableLogout);if(r.type===null){if(t.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(t.templateData||zw())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ke.error(o),ke.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,t)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((t,o)=>{if(this.localPresence)t();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(N()),t())})}})}subscribe(){return new Promise((t,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),t())})})}toJSON(){return ps(this.data())}getContainerBlocks(t){const o=this.data();d(ke,o,"no doc data");const r=o[wo(t)];return d(ke,r,`no container data: ${t}`),Q.default(r)}getBlockData(t,o){const r=this.data();d(ke,r,"no doc data");const i=r[wo(t)];d(ke,i,`no container data: ${t}`);const s=i[o];return d(ke,s,`no block data: ${o}`),Q.default(s)}localInsertBlock(t,o,r){return this.submitInsertBlock(t,o,r),this.getBlockData(t,o)}localDeleteBlock(t,o){const r=this.getBlockData(t,o);return this.submitDeleteBlock(t,o),r}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);d(ke,i.text,"no block text");const s=Q.default(i.text);this.submitUpdateRichText(t,o,r);const l=dt.apply(s,r);return d(ke,l,"no block text"),l}localUpdateBlockData(t,o,r){const i=Q.default(this.getBlockData(t,o));return this.submitUpdateBlockData(t,o,r),i}localInsertChildContainer(t,o){this.submitInsertChildContainer(t,o)}localDeleteChildContainers(t){this.beginBatchUpdate(),t.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>g5(o))}getComment(t){return this.data().comments[t]}getCommentDoc(t){const o=this.data().comments[t];return bh(o)}localCreateComment(t,o){const r=vh(t,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(t){const o=["comments",t,{r:!0}];return this.submitOp(o)}localUpdateComment(t,o){const r=vh(t,o),i=["comments",t.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var t;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(t=this.localPresence)==null||t.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(t,o,r){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Zr(t),o,r)})}onInsertBlock(t,o,r,i){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Zr(t),o,r,i)})}onUpdateBlockData(t,o,r,i){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Zr(t),o,r,i)})}onUpdateBlockText(t,o,r,i){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Zr(t),o,r,i)})}onDeleteContainer(t,o){d(ke,this.callbacks.length>0,"no callbacks"),d(ke,t!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Zr(t),o)})}onCreateContainer(t,o,r){d(ke,this.callbacks.length>0,"no callbacks"),d(ke,t!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Zr(t),o,r)})}onDeleteComment(t,o){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,t,o)})}onCreateComment(t,o){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,t,o)})}onUpdateComment(t,o){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,t,o)})}onCustomMessage(t){const o=t;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:t,clientId:"-"};this.onCustomMessage(r)})}async addResources(t){return await this.client.getFileUrlsByHashes(t)}async uploadResource(t,o){var i;return{resourceId:await this.client.uploadResource(t,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(t,o){return this.client.buildResourceUrl(t,o)}request(t,o){return this.client.request(t,o)}getUser(){const t=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:t,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(t){const o=await this.client.getVersion(t);return ps(o)}async getLatestVersion(){const t=await this.client.getLatestVersion();return ps(t)}async getHistoryData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:ps(r),historyData:s}}async getVersionData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o);return{doc:ps(r),versionData:i}}async updateVersionExtra(t,o,r){await this.client.updateVersionExtra(t,o,r)}revertVersion(t){return this.client.revertVersion(t)}createVersion(t,o){return this.client.createVersion(t,o)}async recognizeLink(t){return this.client.recognizeLink(t)}parseHistoryData(t,o){m5(t.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}w("remote-cursor");class C5{constructor(e){h(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});h(this,"broadcastCaretPos",nt.default(()=>{const e={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(e)},300));h(this,"handleRemoteCaretsChanged",e=>{e.forEach(t=>{const o=this.editor.findBlockById(t);o&&this.editor.reloadBlock(o)})});this.editor=e,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const A5=w("remote-cursor-decorator");class yh{decorateText(e,t,o){const r=e.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=t[t.length-1];d(A5,typeof s=="string","invalid path containerId"),d(A5,typeof l=="number","invalid path blockIndex");const c=e.doc.getBlockData(s,l),a=at(o);return r.getSimpleCursors(c.id).forEach((f,m)=>{m>a&&(m=a);const p=f.map(y=>({id:N(),type:"remote-cursor",name:y.user.displayName,time:y.time,rainbowIndex:y.user.rainbowIndex})),b=i.get(m);b?b.push(...p):i.set(m,p)}),{insertions:i}}}class b5 extends Ve.TypedEmitter{constructor(e){super(),this.editor=e,this.editor.doc.registerCallback(this)}handleChild(e,t,o){if(Ae(_r(this.editor,e)))return;const r=this.editor.getBlockByIndex(e,t),i=H(this.editor.getContainerById(e));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(e,t){this.handleChild(e,t,"data-change")}onUpdateBlockText(e,t){this.handleChild(e,t,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function Yw(n,e){n.addCustom("child-block-tracker",()=>new b5(n)).addListener("change",e)}function Jw(n,e){n.addCustom("child-block-tracker",()=>new b5(n)).removeListener("change",e)}const QV="",Kw={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4",name:"\u6587\u672C\u989C\u8272"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},Xw={colorPalette:{colorDesc:"Text Color",name:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},eB={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};I.mergeLang({"zh-CN":Kw,"en-US":Xw,"js-JP":eB});const YV="";w("button");function Io(n,e,t,o,r){const i=A("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,e),t?typeof t=="string"?t.startsWith("<")?i.innerHTML=t:i.innerText=t:i.appendChild(t):i.innerText=e,o&&(o.indexOf("checked")!==-1&&R(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function v5(n,e,t){t?n.setAttribute(`data-editor-tooltip-${t}`,e):n.innerText=e}const JV="",Jr=w("ui-command-bar-base"),tB={itemElementTag:"div",tippyArrow:!1},Qf=class extends Ve.TypedEmitter{constructor(t,o,r){var i,s;super();h(this,"content");h(this,"items");h(this,"subBar",null);h(this,"parentItem",null);h(this,"closeable",null);h(this,"closeReason",null);h(this,"options");h(this,"id");h(this,"handleDocumentKeydown",t=>{if(!!this.isVisible&&!t.isComposing&&!Nr(t.target)){if(this.subBar){this.subBar.handleDocumentKeydown(t);return}if(this.items.length!==0){if(t.key==="Escape"){this.close("cancelBar");return}if(t.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),t.preventDefault(),t.stopPropagation()}else if(t.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),t.preventDefault(),t.stopPropagation()}else if(t.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(t.key==="ArrowLeft")this.parentItem&&this.close("switchItem");else if(t.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});h(this,"handleDocumentMouseDown",t=>{if(t.target instanceof Element&&!this.isInCommandBar(t.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,t)===!1)return;this.close("clickBackground")}});h(this,"handleHidden",()=>{this.closeReason!=="fromHover"&&this.emit("close",this),this.close(null),Qm(this.id)});h(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&R(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&Zm(this.id)});h(this,"lastEnterPauseTime",0);h(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});h(this,"handleItemMouseEnter",t=>{if(Date.now()-this.lastEnterPauseTime<100)return;const o=this.getParentCommandItemElement(t.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});h(this,"handleItemMouseLeave",t=>{var r,i;const o=this.getParentCommandItemElement(t.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(j(o,"selected"),this.emit("selectionChange",this,""))});h(this,"handleItemClick",t=>{const o=this.getParentCommandItemElement(t.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close("clickItem"))}});h(this,"handleWheel",t=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=t.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=Qt(r);if(!Ce(this.content,i)){t.stopPropagation(),t.preventDefault();return}t.deltaY<0?i.scrollTop===0&&(t.stopPropagation(),t.preventDefault()):t.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(t.stopPropagation(),t.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:N(),this.options={...tB,...r},this.items=t,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(t)}close(t){this.closeReason=t,this.subBar&&this.subBar.close(t),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(t,o){this.emit("click",this,t,o)}createPopperOptions(){var r,i;const t={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=t==null?void 0:t.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),this.options.padding&&((i=t==null?void 0:t.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),t}destroy(){var t;this.close(null),this.removeAllListeners(),(t=this.subBar)==null||t.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(t){var r;this.subBar&&t.findIndex(s=>{var l,c;return s.id===((c=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:c.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=t;const o=this.createCommandBarContent(t);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const t=this.getSelectedItem();return t?this.items.indexOf(t):-1}getPrevItemIndex(t){if(t<=0)return this.items.length-1;let o=t-1;for(;;){const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(t){let o=t+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const t=this.getSelectedItem();if(!t)return;const o=this.getItemElementById(t.id);o&&j(o,"selected")}selectItem(t){const o=this.getSelectedItem();if(o){if(o.id===t)return;const i=o.id,s=this.getItemElementById(i);s&&j(s,"selected")}const r=this.getItemElementById(t);r?(R(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(t){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close("switchItem");return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=Qf.createSubCommandBar(o,(l=this.closeable)!=null?l:this,t?{id:t}:{});this.subBar=i,this.subBar.on("click",(c,a,u)=>{this.emit("click",c,a,u)}),this.subBar.on("close",()=>{var c;(c=this.subBar)==null||c.destroy(),this.subBar=null,j(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),R(r,"active")}isInCommandBar(t){if(!t||!(t instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Ce(o,t)||Ce(this.content,t)?!0:this.subBar?this.subBar.isInCommandBar(t):!1}createCommandItem(t){var i,s,l,c;let o=(i=this.options.itemElementTag)!=null?i:"div";t.element&&(o="div");const r=A(o,["command-item"],null);return r.setAttribute("data-id",t.id),t.type==="separator"?r.classList.add("separator"):t.type==="section"?(r.classList.add("section","text"),t.element&&(typeof t.element=="function"?r.appendChild(t.element(t)):r.appendChild(t.element))):((s=t.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=t.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(c=t.states)!=null&&c.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,t.element?typeof t.element=="function"?r.appendChild(t.element(t)):r.appendChild(t.element):r.classList.add("standard")),this.initItemElement(t,r),r}getItemById(t){const o=this.items.find(r=>r.id===t);return d(Jr,o,`can not find command item for id: ${t}`),o}getSelectedItem(){const t=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(t){const o=this.getItemElementId(t),r=this.items.find(i=>i.id===o);return d(Jr,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(t){const o=t.getAttribute("data-id");return d(Jr,o,"no data-id attribute"),o}getItemElementById(t){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${t}"]`);return d(Jr,o,`no exists command item, id=${t}`),o}getParentCommandItemElement(t){if(!t||!(t instanceof Element))return null;if(ne(t,"command-item"))return t;const o=t.closest(".command-item");return o||null}createCommandBarContent(t){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=A("div",["editor-command-bar-root"],null);this.options.header&&A("div",["editor-command-bar-header"],o).appendChild(this.options.header);const r=A("div",["editor-command-bar"],o);return t.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.options.footer&&A("div",["menu-item","editor-command-bar","footer"],o).appendChild(this.options.footer),this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(t){var o;return{placement:(o=t.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(t,o){this.commandBarCreators.set(t,o)}static createSubCommandBar(t,o,r){var l;d(Jr,t.children&&t.children.length>0,"no item children");const i=(l=t.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return d(Jr,s,`no creator for command type: ${i}`),s(t,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let xo=Qf;h(xo,"commandBarCreators",new Map),w("ui-command-bar");class Lc extends xo{constructor(){super(...arguments);h(this,"tippyInstance",null)}manualShow(t,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=H8.default(t,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(t){var o;super.close(t),this.isVisible&&((o=this.tippyInstance)==null||o.hide())}destroy(){var t;(t=this.tippyInstance)==null||t.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var t,o;return(o=(t=this.tippyInstance)==null?void 0:t.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const y5=w("ui-base");class Ds extends Lc{constructor(e,t){var i;const r=[{id:(i=t==null?void 0:t.id)!=null?i:`popup-${N()}`,name:"",element:e}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(e){R(e,"popper")}initItemElement(e,t){}get popupContent(){const e=this.items[0];d(y5,e,"no dialog item");const t=typeof e.element=="function"?e.element(e):e.element;return d(y5,t,"no item element"),t}}const To=w("filterable-list");function k5(n){var t,o;const e=A("div",["list-item"],null);return e.setAttribute("data-id",n.id),e.appendChild(A("div",["list-item-text"],null,n.name)),(t=n.states)!=null&&t.includes("selected")&&R(e,"selected"),(o=n.states)!=null&&o.includes("disabled")&&R(e,"disabled"),e}function w5(n){const e=A("div",["list-root"],null);return n.forEach(t=>{e.appendChild(k5(t))}),n.length||e.appendChild(k5({id:"placeholder",states:["disabled"],name:I.t("search.emptyTips")})),e}function B5(n,e){let t=n;return e&&(t=n.map(o=>({...o,states:o.id===e?["selected"]:void 0}))),t}function nB(n,e){const t=A("div",["filterable-list"],null),o=A("div",["filter"],t),r=A("div",["filter-container"],o),i=A("input",["filter-input"],r);e&&e.placeholder&&(i.placeholder=e.placeholder);const s=A("div",["list"],t),l=w5(B5(n,e==null?void 0:e.initialSelectedId));return s.appendChild(l),t}function E5(n,e,t){const o=n.querySelector(".list");d(To,o,"no list root");const r=w5(B5(e,t)),i=o.querySelector(".list-root");if(d(To,i,"no exists menu"),Wi(i,r),t){const s=o.querySelector(".list-item.selected");s&&(d(To,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class oB{constructor(e,t){h(this,"root");h(this,"visibleItems");h(this,"selectedId");h(this,"filter","");h(this,"onSelected",null);h(this,"handleKeydown",e=>{this.processKeyDown(e)});h(this,"handleInputChanged",()=>{const e=this.root.querySelector(".filter-input");d(To,e,"no input");const t=e.value.toLocaleLowerCase();this.setFilter(t)});h(this,"handleClick",e=>{this.processClick(e)});var o;this.items=e,this.options=t,this.root=nB(e,t),this.bindEvents(),this.selectedId=(o=t==null?void 0:t.initialSelectedId)!=null?o:"",this.visibleItems=e}bindEvents(){const e=this.root.querySelector(".filter-input");d(To,e,"no input"),e.addEventListener("keyup",this.handleInputChanged),e.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const e=this.root.querySelector(".filter-input");d(To,e,"no input"),e.removeEventListener("keyup",this.handleInputChanged),e.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(e=>e.id===this.selectedId):-1}setSelectedId(e){this.selectedId=e,E5(this.root,this.visibleItems,e)}focus(){const e=this.root.querySelector(".filter-input");d(To,e,"no input"),e.focus()}reset(){this.setFilter("");const e=this.root.querySelector(".filter-input");d(To,e,"no input"),e.value=""}setFilter(e){this.filter!==e&&(this.filter=e,this.visibleItems=this.items.filter(t=>t.name.toLocaleLowerCase().includes(e)),E5(this.root,this.visibleItems,this.selectedId))}processClick(e){var s,l;const t=e.target;if(!(t instanceof HTMLElement))return;const o=t.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(c=>c.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(e){var t;if(e.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(e.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(e.key==="Enter"){const o=(t=this.visibleItems.find(r=>r.id===this.selectedId))!=null?t:null;this.onSelected&&this.onSelected(this,o)}}}class rB extends oB{constructor(t,o,r){super(t,r);h(this,"popup");h(this,"onShow",null);h(this,"onHide",null);h(this,"custom",null);h(this,"handleShow",()=>{this.onShow&&this.onShow(this)});h(this,"handleHide",()=>{this.onHide&&this.onHide(this)});h(this,"handleShown",()=>{this.focus()});this.popup=new Ds(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(t){this.reset(),this.popup.manualShow(t,{theme:"dropdown-list"}),this.focus()}processKeyDown(t){super.processKeyDown(t),(t.key==="Esc"||t.key==="Enter")&&this.popup.close("cancelBar")}processClick(t){super.processClick(t);const o=t.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close("clickItem")}}const KV="",XV="";function iB(n,e){const t=document.createElement("div");t.classList.add("toast","show"),e!=null&&e.theme&&t.setAttribute("data-theme",e.theme),e!=null&&e.id&&t.setAttribute("data-id",e.id),e!=null&&e.html?t.innerHTML=n:t.textContent=n,e!=null&&e.position&&(t.style.left=`${e.position.x}px`,t.style.top=`${e.position.y}px`,t.classList.add("positioned")),document.body.appendChild(t),setTimeout(()=>{t.classList.remove("show"),setTimeout(()=>{t.remove()},500)},(e==null?void 0:e.duration)||3e3)}const I5=`<?xml version="1.0" ?>
|
|
27
|
+
`)}const Qv=w("get-text-position");function Ur(n,e){const t=e!=null?e:n.selection.range.start;t instanceof We||d(Qv,!1,`invalid insert pos type: ${typeof t}`);const{blockId:o}=t,r=n.getBlockById(o),i=K(r),s=_(r),l=q(s),{offset:c}=t;return{block:r,container:s,containerId:l,blockIndex:i,offset:c}}const ls=w("insert-text");function Kp(n,e,t,o){var s;const r=n.doc.getBlockData(e,t);if(d(ls,r,"no block data"),d(ls,r.text,"no block text"),at(r.text)===0)return d(ls,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 Yv(n,e,t){const o=_(e),r=q(o),i=K(e);return Kp(n,r,i,t)}function Xp(n,e,t,o,r){const i=_(e),s=q(i),l=K(e),c=Yv(n,e,t),a=Ql(t,o,c!=null?c:null);return n.doc.localUpdateBlockText(s,l,a,r),pt(n,e)}function e0(n,e,t,o){const r=_(e),i=q(r),s=K(e),l=Ql(t," ",o);return n.doc.localUpdateBlockText(i,s,l),pt(n,e)}function Dd(n,e,t,o,r){const i=n.doc.getBlockData(t,o);d(ls,i,"no block data"),d(ls,i.text,"no block text");const s=Kp(n,t,o,r),l=Ql(r,e,s!=null?s:null);return n.doc.localUpdateBlockText(t,o,l),pt(n,n.getBlockById(i.id))}function Sd(n,e){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:t,blockIndex:o,offset:r}=Ur(n);Dd(n,e,t,o,r)}const sc=w("update-composition-text");function t0(n){const e=n.selection.range.start;e instanceof We||d(sc,!1,`invalid insert pos type: ${typeof e}`);const{blockId:t}=e,o=n.getBlockById(t);d(sc,$(n,o),"not a text kind block");const r=_(o),i=q(r),s=K(o),l=n.doc.getBlockData(i,s);d(sc,l,"no block data in doc"),d(sc,l.text,"no text data in text block");const c=le(o);ql(n,fo(o),t,c,l.text)}function n0(n){Tb(n)}function Vr(n,e,t,o,r,i){return n.doc.localInsertBlock(e,t,o,r,i),n.getBlockById(o.id)}const cs=w("delete-block-text");function Ld(n,e,t,o,r){if(!n.isBlockWritable(e))return cs.error("block is not writable"),0;d(cs,$(n,e),"block is not a text kind block");const i=_(e),s=q(i),l=K(e),c=n.doc.getBlockData(s,l);d(cs,c,"no block data in doc"),d(cs,c.text,"no text data in text block");let a=t;ut(e,t)||(a=Co(e,a));let u=t+o;d(cs,u<=G(n,e),`invalid offset and count: ${t}, ${o}`),ut(e,u)||(u=cr(e,u));const f=u-a,m=dp(a,f);return n.doc.localUpdateBlockText(s,l,m,r),f}const Md=w("break-text-block");function o0(n,e){const o=n.getBlockData(e).quoted;return o?{quoted:o}:{}}function qr(n,e,t,o){d(Md,$(n,e),`block is not a text kind block: ${ie(e)}`),d(Md,t>=0&&t<=G(n,e),`invalid offset: ${t}`);const r=_(e),i=q(r),s=K(e),l=o!=null&&o.copyBlockAttributes?o0(n,e):{};if(!(o!=null&&o.forceInsertAfter)&&(t===0||t===G(n,e))){const p=t===0?s:s+1,b={...Gn(""),...l,...o==null?void 0:o.newBlockData},y=Fe(n,e.id,0),v=Vr(n,i,p,b,y);return{block:e,newBlock:v}}d(Md,ut(e,t),"not a valid offset");const c=pt(n,e),{right:a}=kt(c,t),u=at(a);u>0&&Ld(n,e,t,u);const f={...Gn(a),...l,...o==null?void 0:o.newBlockData},m=Vr(n,i,s+1,f,Fe(n,f.id,0));return{block:e,newBlock:m}}const Jv=w("prepare-insert-new-block");function Kv(n,e,t){if(e&&t!==void 0&&t!==null){const a=n.getContainerById(e),u=Me(a);return d(Jv,t>=0&&t<=u.length,`invalid blockIndex: ${t}`),{containerId:e,blockIndex:t}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(e=q(_(r)),t=K(r),!$(n,r))return{containerId:e,blockIndex:t+1};const s=o.offset;if(s===0||s===G(n,r))return{containerId:e,blockIndex:s===0?t:t+1};const c=qr(n,r,s).newBlock;return{containerId:e,blockIndex:K(c)}}const Xv=w("auto-insert-block");function r0(n,e,t,o,r,i){const s=Kv(n,t,o);d(Xv,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:e.id,offset:0},c={anchor:l,focus:l};return Vr(n,s.containerId,s.blockIndex,e,r!=null?r:c,i)}const ey=w("delete-block");function lc(n,e,t){e.children&&(t.push(...e.children),e.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{lc(n,i,t)})}))}function Rd(n,e,t){const o=_(e),r=q(o),i=K(e),s=n.doc.getBlockData(r,i);return d(ey,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ge(n,{anchor:t.start,focus:t.end})),s}function Od(n,e,t){return n.undoManager.runInGroup(()=>{const o=_(e);Yt(o)===1&&n.insertTextBlock("",q(o),0);let r=t?mo(n,t):null;if(!r){const l=n.selection.range;Zp(e,l)?r=Qp(n,e):r=l}const i=Rd(n,e,r),s=[];return lc(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function ty(n,e){const t=[e];n.doc.getContainerBlocks(e).forEach(r=>{lc(n,r,t)}),n.doc.localDeleteChildContainers(t)}function i0(n,e){const t=[...e];e.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{lc(n,i,t)})}),n.doc.localDeleteChildContainers(t)}const Pd=w("merge-text-block");function s0(n,e,t){d(Pd,$(n,e),"only text block can be merged"),d(Pd,$(n,t),"only text block can be merged");const o=vo(n,e),r=vo(n,t),i=o.text,s=r.text;d(Pd,i&&s,"block data has no text");const l=_(e),c=q(l),a=K(e),u=G(n,e),f=Dd(n,s,c,a,u),m=Fe(n,e,at(i));return Od(n,t,m),f}const En=w("clear-selected-contents");function cc(n,e){d(En,$(n,e.block),"not a text kind block");const{start:t,end:o}=e;d(En,t.isSimple(),"not a simple block position"),d(En,o.isSimple(),"not a simple block position");const r=t.offset,i=o.offset;d(En,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(e.block,r,i-r)}function l0(n,e,t){const o=q(e),r=Me(e),i=t.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});t.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function ny(n,e){const{block:t,start:o,end:r}=e;if($(n,t)){cc(n,e);return}if(qe(t)||o.isSimple()){d(En,r.isSimple(),"invalid range");const s=_(t),l=K(t),c=n.insertTextBlock("",q(s),l);n.selection.selectBlock(c,0),n.deleteBlock(t);return}d(En,ce(n,t),"invalid block kind"),d(En,!o.isSimple()&&!r.isSimple(),"invalid range"),sr(n,t,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{l0(n,s,{focus:l===0})})}function oy(n){if(!n.isWritable())return;const e=n.selection.range;if(e.isCollapsed())return;const t=e.getSelectedBlocks();if(d(En,t.length>0,"no selected block"),t.length===1){ny(n,t[0]);return}const o=t[0],r=o.block,i=_(r);d(En,t.length>1,"no selected block");const s=t[t.length-1],l=s.block;if($(n,r)){cc(n,o);const u=Fe(n,o.block,o.start.offset);if(t.slice(1,t.length-1).reverse().forEach(m=>n.deleteBlock(m.block)),$(n,l)){cc(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(u);return}n.deleteBlock(l),n.selection.setRange(u);return}if($(n,l)){cc(n,s),t.slice(0,t.length-1).reverse().forEach(u=>n.deleteBlock(u.block)),n.selection.selectBlock(s.block,0);return}if(t.length===Yt(i)){l0(n,i,{focus:!0});return}const c=ye(r),a=fe(l);d(En,c||a,"no prev or next block"),t.forEach(u=>n.deleteBlock(u.block))}function Fd(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),oy(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const ry=w("core");function c0(n,e,t){const o=_(e),r=q(o),i=K(e);return n.doc.localUpdateBlockText(r,i,t),setTimeout(()=>{n.selection.updateSelection(null)}),pt(n,e)}function a0(n,e,t){if(!n.isBlockWritable(e)){ry.error("block is not writable");return}const o=n.getBlockText(e),r=dt.diff(o,t);c0(n,e,r)}function ac(n,e,t){const o=pt(n,e),r=typeof t=="string"?Ao(t):t,i=dt.diff(o,r);return c0(n,e,i)}const as=w("update-block-data");function uc(n,e,t,o){const r=_(e),i=q(r),s=K(e),l=n.doc.getBlockData(i,s),c={insert:{},delete:[]},a=new Set(Object.keys(l)),u=new Set(Object.keys(t));return a.forEach(m=>{if(!u.has(m)){if(m==="id"||m==="type"||m==="text")return;as.debug(`delete key: ${m}`),c.delete.push(m)}}),Object.entries(t).forEach(([m,p])=>{d(as,m!=="id"&&m!=="type",`invalid block data delta, ${m}`);const b=l[m];if(p==null){b!=null&&(as.debug(`delete key: ${m}`),c.delete.push(m));return}b!==p&&(_i.default(b,p)||m==="text"&&dt.diff(b,p).length===0||(a.has(m)?(as.debug(`replace key: ${m}`),c.delete.push(m)):as.debug(`insert key: ${m}`),c.insert[m]=p))}),n.doc.localUpdateBlockData(i,s,c,o),vo(n,e)}function u0(n,e,t,o){const i={...n.getBlockData(e),embedData:t};return n.updateBlockData(e,i,o)}function Nd(n,e,t){if(!ce(n,e)||!(t!=null&&t.tryFocusToChildSimpleBlock)){n.selection.selectBlock(e,0);return}const r=Tt(n,e).getChildContainers(n,e)[0],i=$e(r);Nd(n,i,t)}function dr(n){const e=[];let t={};return n.forEach(o=>{e.push(...o.blocks.root);const{root:r,...i}=o.blocks;t={...t,...i}}),{blocks:{...t,root:e},meta:{},comments:{}}}const us=w("clone-block");function yo(n,e,t,o){const r=n.getBlockClass(t.type);if(r.blockToDoc)return r.blockToDoc(e,t,(u,f)=>(d(us,t!==f,"invalid child block"),yo(n,u,t,o)));let i={};const s=new Map,l=Q.default(t);l.children&&(l.children=l.children.map(u=>{const f=N(),m=e.blocks[u];d(us,Array.isArray(m),"invalid child blocks");const p=m.map(x=>yo(n,e,x,o)),b=dr(p),{root:y,...v}=b.blocks;return i={...i,...v},i[f]=b.blocks.root,s.set(u,f),f}));const c=Array.from(s.entries()),a=u=>{for(const f of c){const[m,p]=f;{const b=`${m}/`;if(u.startsWith(b)){const y=u.substring(b.length),v=`${p}/${y}`;return us.debug(`replace key: ${u} -> ${v}`),v}}{const b=`${m}_`;if(u.startsWith(b)){const y=u.substring(b.length),v=`${p}_${y}`;return us.debug(`replace key: ${u} -> ${v}`),v}}}return u};return Array.from(Object.entries(l)).forEach(([u,f])=>{const m=a(u);m!==u&&delete l.key,l[m]=f}),l.id=N(),o&&(o.blockIdMap.set(t.id,l.id),s.forEach((u,f)=>o.containerIdMap.set(f,u))),{blocks:{root:[l],...i},meta:{},comments:{}}}function $d(n,e,t,o){const r=e.blocks[t];d(us,Array.isArray(r),"invalid child blocks");const i=r.map(l=>yo(n,e,l,o));return dr(i)}function _d(n,e,t){const o=e.blocks.root.map(r=>yo(n.editorBlocks,e,r,t));return Q.default(dr(o))}const d0=w("insert-doc");function h0(n,e,t,o,r){if(ce(n,e)){d0.warn("failed to insert doc into a complex block");return}const i=_d(n,o,r),s=_(e),l=K(e),c=q(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var E,M,L;Object.entries(i.blocks).forEach(([O,V])=>{O!=="root"&&n.doc.localInsertChildContainer(O,V)});const a=i.blocks.root;if(qe(e)){n.deleteBlock(e);let O;a.reverse().forEach(V=>{const ee=n.insertBlock(c,l,V);O||(O=ee)}),O&&n.selection.selectBlock(O,G(n,O));return}if(d(d0,$(n,e),"not a text block"),Ie(n,e)){const O=K(e);let V;a.forEach((ee,se)=>{const pe=n.insertBlock(c,O+se,ee);se===a.length-1&&(V=pe)}),V&&n.selection.selectBlock(V,G(n,V));return}if(a.length===1){const O=a[0];if(Qi(n,O.type)){n.insertTextToBlock(e,t,(E=O.text)!=null?E:[]);return}n.breakTextBlock(e,t),n.insertBlock(c,l+1,O);return}const u=t===G(n,e),f=t===0,m=a[0],p=a[a.length-1];let b;!u&&!f?b=n.breakTextBlock(e,t,{forceInsertAfter:!0}):b=e;const y=f?l:l+1;u?(b=n.insertBlock(c,l+1,p),n.selection.selectBlock(b,G(n,b))):(n.selection.selectBlock(b,0),Qi(n,p.type)?n.insertTextToBlock(b,0,(M=p.text)!=null?M:[]):n.insertBlock(c,y,p));const v=n.selection.range;let x=y;Qi(n,m.type)?f?(n.insertBlock(c,y,m),x+=1):n.insertTextToBlock(e,t,(L=m.text)!=null?L:[]):(n.insertBlock(c,y,m),x+=1),a.slice(1,a.length-1).reverse().forEach(O=>{n.insertBlock(c,x,O)}),n.selection.setRange(v)}),n.doc.endBatchUpdate()}function jd(n,e,t,o,r){const i=_d(n,o,r),s=q(e),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([a,u])=>{a!=="root"&&n.doc.localInsertChildContainer(a,u)}),i.blocks.root.reverse().forEach(a=>{const u=n.insertBlock(s,t,a);l.push(u)})}),l}function f0(n,e,t){const o=Yt(e);jd(n,e,o,t);for(let r=0;r<o;r++){const i=$e(e);n.deleteBlock(i)}}const ds=w("add-text-attribute");function iy(n,e,t,o){const{start:r,end:i}=t;d(ds,r.blockId===i.blockId&&r.blockId===z(e),"invalid range"),d(ds,o,"invalid attribute name");const s=n.getBlockText(e),l=zr(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(e,l),l}function m0(n,e,t,o,r){const{start:i,end:s}=t;d(ds,i.blockId===s.blockId&&i.blockId===z(e),"invalid range"),d(ds,o,"invalid attribute name");const l=n.getBlockText(e),c=ts(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,c),c}function Wr(n,e,t,o,r){const{start:i,end:s}=t;d(ds,i.blockId===s.blockId&&i.blockId===z(e),"invalid range");const l=n.getBlockText(e),c=vp(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(e,c),c}function g0(n,e,t,o){const r=nn(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:c}=i;if(!$(n,s))return;if(Ie(n,s)){o(n,z(s),e,t);return}const a=Ge(n,{anchor:l,focus:c});e==="color"||e==="backgroundColor"?Wr(n,s,a,e,t):(Wr(n,s,a,"color",null),Wr(n,s,a,"backgroundColor",null))})})}function p0(n,e,t){const o=nn(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!$(n,i))return;if(Ie(n,i)){(e==="clearColor"||e==="clearAll")&&t(n,z(i),"color",null),(e==="clearBackground"||e==="clearAll")&&t(n,z(i),"backgroundColor",null);return}const c=Ge(n,{anchor:s,focus:l});(e==="clearColor"||e==="clearAll")&&Wr(n,i,c,"color",null),(e==="clearBackground"||e==="clearAll")&&Wr(n,i,c,"backgroundColor",null)})})}function Hd(n,e){const t=nn(n,{simpleBlockOnly:!0}).filter(s=>$(n,s.block));if(t.length===0)return[null,null];const o=s=>{if(G(n,s.block)===0)return e(n,z(s.block));const l=s.start,c=s.end,a=n.getBlockText(s.block);return wp(l.offset,c.offset-l.offset,a)};let[r,i]=o(t[0]);return r===null&&i===null?[r,i]:(t.forEach(s=>{const[l,c]=o(s);l===null||r===null?r=null:r=l===r?r:null,c===null||i===null?i=null:i=c===i?i:null}),[r,i])}const Lt=w("adjust-selection-pos");function C0(n){const e=[];for(;n;){const t=_(n);if(e.unshift(t),Ae(t))return e;const o=H(t);d(Lt,o,"child container has not parent container"),n=o}d(Lt,!1,"should not come here: getParentContainers")}function A0(n,e){for(;e;){const t=_(e);if(t===n)return e;const o=H(t);d(Lt,o,"could not find parent block for a child container"),e=o}d(Lt,!1,"no parent block in specified container")}function sy(n,e){const t=C0(n),o=C0(e);d(Lt,t.length>0&&o.length>0,"block has not parent container"),d(Lt,t[0]===o[0],"root container does not equal");let r=t[0];for(let l=1;l<t.length||o.length;l++)if(t[l]!==o[l]){r=t[l-1];break}const i=A0(r,n),s=A0(r,e);return{parentContainer:r,newBlock1:i,newBlock2:s}}function b0(n,e){let t=H(e);for(d(Lt,t,"element is not in a block");t;){const o=_(t);d(Lt,en(o),"not a child container");const r=H(o);if(d(Lt,r,"child container has not parent block"),r===n)return o;t=r}d(Lt,!1,"failed to find parent container in complex block")}function dc(n,e,t){const o=n.getBlockById(e.blockId),r=n.getBlockById(t.blockId);if(o===r)return e instanceof We&&t instanceof We?{anchor:e,focus:t}:e instanceof tn&&t instanceof tn?Ul(n,o,e,t):null;const i=_(o),s=_(r);if(i===s)return e instanceof tn&&(e=U(o,0,"home")),t instanceof tn&&(t=U(r,G(n,r),"end")),d(Lt,e instanceof We,"not valid position type"),d(Lt,t instanceof We,"not valid position type"),{anchor:e,focus:t};if(o.contains(s))return null;if(r.contains(i)){if(e instanceof We&&t instanceof tn){const b=n.getContainerById(t.childContainerId);if(b===i)return{anchor:t,focus:t};const y=H(i);if(y&&y===H(b)){const v=xe(y,q(i)),x=xe(y,q(b));return Ul(n,y,v,x)}}return null}const l=Sl(o,r)>0,{newBlock1:c,newBlock2:a}=sy(o,r);if(c===a){const b=c,y=b0(b,o),v=b0(b,r);return e=xe(c,q(y)),t=xe(c,q(v)),Lt.debug(`select in complex block: ${y.id}, ${v.id}`),Ul(n,b,e,t)}let u=l?G(n,c):0;c===o&&e instanceof We&&(u=e.offset);let m=l?0:G(n,a);return a===r&&t instanceof We&&(m=t.offset),e=U(c,u,l?"end":"home"),t=U(a,m,l?"home":"end"),{anchor:e,focus:t}}const ly=w("move-complex-block-position");function cy(n,e,t){const o=n.getBlockById(e.blockId);d(ly,ce(n,o),"is not a complex block");const r=Tt(n,o),i=n.getContainerById(e.childContainerId),s=r.getNextContainer(n,o,i,t,{noWrap:!0});return s?xe(o,q(s)):null}const hs=w("move-simple-block-position");function v0(n,e){const t=yt(n,e,{visibleOnly:!0});d(hs,t.length>0,"complex block has not any child container");const o=t[0];return $e(o)}function y0(n,e){const t=yt(n,e,{visibleOnly:!0});d(hs,t.length>0,"complex block has not any child container");const o=t[t.length-1];return Ke(o)}function k0(n,e,t){const o=t?v0(n,e):y0(n,e);return ce(n,o)?k0(n,o,t):o}function ay(n,e){const t=n.getBlockById(e.blockId);return ce(n,t)&&e.offset===0?v0(n,t):rr(t)}function uy(n,e){const t=n.getBlockById(e.blockId);return ce(n,t)&&e.offset===1?y0(n,t):or(t)}function zd(n){return n==="ArrowLeft"||n==="ArrowUp"}function Ud(n,e,t){const o=_(e);if(Ae(o))return null;const r=H(o);d(hs,r,"child container has not parent block"),d(hs,ce(n,r),"is not a complex block");const i=Tt(n,r).getNextContainer(n,r,o,t);return i?zd(t)?Ke(i):$e(i):Ud(n,r,t)}function dy(n,e,t){const o=_(e);if(Ae(o))return null;const r=H(o);if(d(hs,r,"child container has not parent block"),zd(t)){const l=ye(r);if(l)return l}else{const l=fe(r);if(l)return l}const i=Ud(n,r,t);if(i)return i;let s=r;for(;!Ae(_(s));)s=H(_(s));return zd(t)?ye(s):fe(s)}function hy(n,e,t){return!ce(n,e)||Tt(n,e).enableKeyboardSelect?e:k0(n,e,t==="ArrowDown"||t==="ArrowRight")}function fy(n,e,t){const o=n.getBlockById(e.blockId),i=me(n,o).moveCaret(n,o,e,t);if(i)return i;let s=t==="ArrowDown"||t==="ArrowRight"?ay(n,e):uy(n,e);if(s||(s=Ud(n,o,t),s||(s=dy(n,o,t))),!s){if(t==="ArrowDown"||t==="ArrowRight"){if(n.readonly||!Ae(_(o)))return null;const l=n.insertTextBlock("",q(n.rootContainer),Yt(n.rootContainer));return U(l,0,"home")}return null}if(s=hy(n,s,t),$(n,s)){const l=n.selection.getSuggestedCaretX();if(t==="ArrowDown")return jb(n,s,o,e,l);if(t==="ArrowUp")return _b(n,s,o,e,l)}return t==="ArrowLeft"||t==="ArrowUp"?U(s,G(n,s),"end"):t==="ArrowRight"||t==="ArrowDown"?U(s,0,"home"):null}function my(n,e,t){if(e==="ArrowLeft")return t.start;const o=t.end,r=n.getBlockById(o.blockId);if($(n,r))return o;const i=fe(r);if(i)return U(i,0,"home");if(!Ae(_(r))||n.readonly)return o;const s=n.insertTextBlock("",q(n.rootContainer),Yt(n.rootContainer));return U(s,0,"home")}function gy(n,e,t){const o=n.selection.range;let r;if(o instanceof Xe)t==="move"&&!o.isCollapsed()&&(e==="ArrowLeft"||e==="ArrowRight")?r=my(n,e,o):r=fy(n,o.getFocusedPos(),e);else if(r=cy(n,o.focus,e),t==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(e==="ArrowLeft"||e==="ArrowUp"){const l=Ke(s);r=U(l,0,"home")}else{const l=$e(s);r=U(l,G(n,l),"end")}}return r?t==="move"?{anchor:r,focus:r}:dc(n,o.anchor,r):null}function ko(n,e,t){const o=gy(n,e,t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(e==="ArrowLeft"||e==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function w0(n){return ko(n,"ArrowLeft","move"),!0}function B0(n){return ko(n,"ArrowRight","move"),!0}function E0(n){return ko(n,"ArrowUp","move"),!0}function I0(n){if(ko(n,"ArrowDown","move")||n.readonly)return!0;const e=n.getFocusedBlock(),t=_(e);if(Ae(t)||Ke(t)!==e)return!0;const o=n.rootContainer;return n.insertTextBlock("",q(o),Yt(o)),!0}function x0(n){return ko(n,"ArrowDown","select"),!0}function T0(n){return ko(n,"ArrowLeft","select"),!0}function D0(n){return ko(n,"ArrowRight","select"),!0}function S0(n){return ko(n,"ArrowUp","select"),!0}const L0=w("word-offset");function Vd(n,e){const t=n.selection.range.focus;d(L0,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(Ie(n,o))return U(o,0,"home");if(t.offset===0||!$(n,o)){const s=ye(o);if(!s)return null;const l=U(s,G(n,s),"end");if(e==="select"&&$(n,s)){const c=yd(n,s,l.offset);return U(s,c,"normal")}return l}const r=yd(n,o,t.offset);return U(o,r,"normal")}function qd(n,e){const t=n.selection.range.focus;d(L0,t.isSimple(),"invalid range type");const o=n.getBlockById(t.blockId);if(Ie(n,o))return U(o,0,"end");if(t.offset===G(n,o)||!$(n,o)){const s=fe(o);if(!s)return null;const l=U(s,0,"home");if(e==="select"&&$(n,s)){const c=kd(n,s,l.offset);return U(s,c,"end")}return l}const r=kd(n,o,t.offset);return U(o,r,"normal")}function M0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Vd(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function R0(n){if(!n.selection.range.focus.isSimple())return!1;const t=qd(n,"move");return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function O0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Vd(n,"select");return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function P0(n){if(!n.selection.range.focus.isSimple())return!1;const t=qd(n,"select");return t?(n.selection.setSelection(n.selection.range.anchor,t),n.selection.updateLastCaretRect(),!0):!1}w("find-block");function Wd(n,e){if(!ce(n,e))return e;const o=Tt(n,e).getChildContainers(n,e)[0],i=Me(o)[0];return Wd(n,i)}function Gd(n,e){if(!ce(n,e))return e;const t=Tt(n,e).getChildContainers(n,e),o=t[t.length-1],r=Me(o),i=r[r.length-1];return Gd(n,i)}function F0(n){const e=Gd(n,Ke(n.rootContainer)),t=U(e,G(n,e),"end");return n.selection.setSelection(t),!0}function N0(n){const e=Wd(n,n.getFirstBlock()),t=U(e,0,"home");return n.selection.setSelection(t),!0}function $0(n){const e=Wd(n,n.getFirstBlock()),t=U(e,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}function Zd(n){const e=Gd(n,Ke(n.rootContainer)),t=U(e,G(n,e),"end");return n.selection.setSelection(n.selection.getAnchorPos(),t),!0}const _0=w("line-offset");function j0(n){const e=n.selection.range.focus;d(_0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===0||!$(n,t))return U(t,0,"home");let r=sp(t,e).start;const{next:i}=jl(t,r);return i&&Nt(i)&&Zi(i)==="br"&&(r+=1),U(t,r,"home")}function H0(n){const e=n.selection.range.focus;d(_0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId);if(e.offset===G(n,t)||!$(n,t))return U(t,G(n,t),"end");const o=sp(t,e);return U(t,o.end,"end")}function z0(n){if(!n.selection.range.focus.isSimple())return!1;const t=j0(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function U0(n){if(!n.selection.range.focus.isSimple())return!1;const t=H0(n);return t?(n.selection.setSelection(n.selection.getAnchorPos(),t),n.selection.updateLastCaretRect(),!0):!1}function V0(n){if(!n.selection.range.focus.isSimple())return!1;const t=j0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function q0(n){if(!n.selection.range.focus.isSimple())return!1;const t=H0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}const W0=w("find-block-position");function py(n,e,t,o){d(W0,ce(n,e),"is not a complex block");const r=Tt(n,e).getChildContainers(n,e);d(W0,r.length>0,"complex block has not any child container");const i=Xt(n,t,o),s=i.left+i.width/2,l=i.top+i.height/2,c=Qg(n,e,s,l);return Qd(n,c,t,o)}function Qd(n,e,t,o){if(ce(n,e))return py(n,e,t,o);const r=z(e);let i=Number.MAX_SAFE_INTEGER;const s=Xt(n,t,o),l=s.left+s.width/2,c=s.top+s.height/2;let a=U(r,0,"home");const u=G(n,e);for(let f=0;f<=u;f++){const m=U(r,f,"normal"),p=Xt(n,e,m),b=vn(p,l,c);b<i&&(i=b,a=m)}return a}const G0=w("page-offset");function Cy(n,e){const t=qp(n)*.9,r=e.getBoundingClientRect().bottom-t;if(r<Hv(n))return n.getFirstBlock();const i=ye(e);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ye(s)}return n.getFirstBlock()}function Ay(n,e){const t=qp(n)*.9,o=e.getBoundingClientRect(),r=zv(n),i=o.top+t;if(i>r)return n.getLastBlock();const s=fe(e);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=fe(l)}return n.getLastBlock()}function Z0(n){const e=n.selection.range.focus;d(G0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=Cy(n,t);let r;return o===n.getFirstBlock()?r=U(o,0,"home"):r=Qd(n,o,t,e),r}function Q0(n){const e=n.selection.range.focus;d(G0,e.isSimple(),"invalid range type");const t=n.getBlockById(e.blockId),o=Ay(n,t);let r;return o===n.getLastBlock()?r=U(o,G(n,o),"end"):r=Qd(n,o,t,e),r}function Y0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Z0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function J0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Q0(n);return t?(n.selection.setSelection(t),n.selection.updateLastCaretRect(),!0):!1}function K0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Z0(n);if(!t)return!1;const o=dc(n,n.selection.getAnchorPos(),t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function X0(n){if(!n.selection.range.focus.isSimple())return!1;const t=Q0(n);if(!t)return!1;const o=dc(n,n.selection.getAnchorPos(),t);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const fs=w("select-all");function e2(n,e){const t=$e(n),o=Ke(n);return e.start.offset===0&&e.start.blockId===z(t)&&e.end.offset===G(e.getEditor(),o)&&e.end.blockId===z(o)}function by(n,e){const t=e.getEditor(),o=Tt(t,n).getChildContainers(t,n),r=o[0],i=o[o.length-1],s=z(n);return e.start.blockId===s&&e.start.childContainerId===q(r)&&e.end.blockId===s&&e.end.childContainerId===q(i)}function vy(n,e){d(fs,e,"no parent block"),d(fs,ce(n,e),"not a complex block");const t=Tt(n,e).getChildContainers(n,e),o=t[0],r=t[t.length-1];n.selection.setRange(Ge(n,{anchor:xe(e,q(o)),focus:xe(e,q(r))}))}function t2(n,e){const t=_(e);Yd(n,t)}function n2(n){const e=n.getFocusedBlock(),t=n.selection.range;if(t.start.isSimple()){if(t.start.blockId===t.end.blockId&&$(n,e)){const r=t.start,i=t.end,s=G(n,e);if(r.offset>0||i.offset<s)return n.selection.selectBlock(e,0,s),!1}return R(n.rootContainer,"select-all"),t2(n,$e(n.rootContainer)),!1}return d(fs,!t.isSimple(),"invalid range type"),by(e,t)?(t2(n,e),!1):(d(fs,e,"no parent block"),d(fs,ce(n,e),"not a complex block"),vy(n,e),!0)}function Yd(n,e){const t=Me(e),o=t[0],r=t[t.length-1],i=U(o,0,"home"),s=U(r,G(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function o2(n){Zd(n),n.focus()}const Jd=w("selected-block-to-doc");function r2(n,e,t){!e.children||e.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{r2(n,i,t)}),t.blocks[o]=Q.default(r)})}function hc(n,e){const t=me(n,e.block);if(t.selectionToDoc)return t.selectionToDoc(n,e);const o=Q.default(vo(n,e.block));if($(n,e.block)){const i=e.start,s=e.end;if(d(Jd,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(qe(e.block))return{blocks:{root:[o]},meta:{},comments:{}};d(Jd,ce(n,e.block),"not complex block"),d(Jd,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return r2(n,o,r),r}function Kd(n,e){const t=U(e,0,"normal"),o=U(e,G(n,e),"end");return hc(n,{block:e,start:t,end:o})}const yy=w("block-to-doc");function ky(n,e){d(yy,e.length>0,"invalid params, no blocks");const t=e.map(o=>Kd(n,o));return dr(t)}function fc(n){const t=n.selection.range.getSelectedBlocks().map(o=>hc(n,o));return dr(t)}function i2(n,e){const t=n.getContainerById(e),i=Me(t).map(s=>({start:U(s,0,"home"),end:U(s,G(n,s),"end"),block:s})).map(s=>hc(n,s));return dr(i)}const mc=w("editor-selection");class wy{constructor(e){h(this,"editor");h(this,"caret");h(this,"_range");h(this,"lastCaretRect");h(this,"handleBlockDelete",(e,t,o,r)=>{if(o||r.child)return;const i=this.range;if(Zp(t,i)){mc.debug("adjust selection because remote deleted current block");const s=Qp(e,t);this.setRange(s,{noScroll:!0})}});this.editor=e;const t=e.getFirstBlock(),o=z(t);this.caret=new $v(e);const r=U(o,0,"normal");this._range=Ge(e,{anchor:r,focus:r}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const e=this.range.focus;return this.editor.getBlockById(e.blockId)}getStartBlock(){const e=this.range.start;return this.editor.getBlockById(e.blockId)}getEndBlock(){const e=this.range.end;return this.editor.getBlockById(e.blockId)}selectBlock(e,t,o){const r=U(e,t,"normal");let i;o&&(i=U(e,o,"normal")),this.setSelection(r,i)}setSelection(e,t,o){if(t||(t=e),this.verifyPos(e),this.verifyPos(t),!this.selectionChanging(e,t))return this.range;const r=Ge(this.editor,{anchor:e,focus:t});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),ne(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!Wv(this.editor,r))&&j(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(e,t){return this.setSelection(e.anchor,e.focus,t)}updateSelection(){this.caret.update(),_v(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(e,t){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const e=this.range.focus;if(!qn(e))return;const t=this.editor.getBlockById(e.blockId);this.lastCaretRect=Xt(this.editor,t,e)}getSuggestedCaretX(){var e;return(e=this.lastCaretRect)==null?void 0:e.x}scrollIntoView(){qv(this.editor)}verifyPos(e){const t=this.editor.getBlockById(e.blockId);if(e.isSimple())e.offset>=0&&e.offset<=G(this.editor,t)||d(mc,!1,"invalid block position, out of range");else{const o=e.childContainerId;!!this.editor.getContainerById(o)||d(mc,!1,"invalid complex block position, no container found")}}updateFocusedBlock(e){if(e&&this.range.start.blockId===e.start.blockId)return;let t;e&&e.start.blockId===e.end.blockId&&(t=this.editor.findBlockById(e.start.blockId));let o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;t&&ne(t,"focused")&&(j(t,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,t!=null?t:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(e){const t=fc(this.editor);return e==="text"?is(this.editor,t):e==="markdown"?ss(this.editor,t):Jp(this.editor,t)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(e=>{j(e,"focused"),j(e,"child-focused")})}setBlockFocused(e){if(ne(e,"focused"))return!1;R(e,"focused");let t=_(e);for(;en(t);){const o=H(t);d(mc,o,"parent block not found"),R(o,"child-focused"),t=_(o)}return!0}}function By(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);!t||n.selection.selectBlock(t,0,G(n,t))}function Ey(n){const e=n.selection.range.focus;if(!e.isSimple())return;const t=n.findBlockById(e.blockId);if(!t||!$(n,t))return;let o=Vd(n,"select"),r=qd(n,"select");if(!o||!r)return;const i=e.blockId;o.blockId!==i&&(o=U(t,0,"home")),r.blockId!==i&&(r=U(t,G(n,t),"end")),n.selection.setSelection(o,r)}class Iy{constructor(e){h(this,"editor");h(this,"startPos",null);h(this,"lastCaretRect");h(this,"mouseDownEvent",null);h(this,"handleMouseDown",e=>{this.mouseDownEvent=e;const t=Kg(this.editor,e.x,e.y);if(t){if(t instanceof kn)return;const o=this.editor.selection.range;if(e.shiftKey&&o.isSimple()){const r=o.anchor;this.editor.selection.setSelection(r,t.focus),this.startPos=t.start}else this.editor.selection.setSelection(t.anchor,t.focus),this.startPos=t.start;this.editor.selection.updateLastCaretRect()}});h(this,"handleMouseMove",e=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-e.x)<3&&Math.abs(this.mouseDownEvent.y-e.y)<3)return;const t=Vl(this.editor,e.x,e.y);if(!t)return;const o=dc(this.editor,this.startPos,t.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});h(this,"handleMouseUp",e=>{this.startPos=null});this.editor=e,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(e){Ey(this.editor)}handleTripleClick(e){By(this.editor)}}function xy(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function Ty(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const s2=w("delete-text");function l2(n,e,t,o){const r=o!=null?o:n.selection.range.start;r instanceof We||d(s2,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(s2,$(n,s),"block is not a text kind block");let{offset:l}=r;if(e==="backward"){if(l-t<0)return 0;if(!ut(s,l-t)){const c=Co(s,l);t=l-c}}else if(e==="forward"&&l+t>G(n,s))return 0;return e==="backward"&&(l-=t),n.deleteTextFromBlock(s,l,t)}function c2(n,e){if(n.getBlockData(e).quoted){const t={quoted:null};return n.updateBlockData(e,t),!0}return!1}const Dy=w("handle-backspace");function Xd(n,e){if(!Ie(n,e))return;const t=_(e);Yt(t)!==1&&n.deleteBlock(e)}function Sy(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if($(n,o))if(t.offset===0){if(c2(n,o))return;const r=ye(o);if(r){if(!n.isBlockWritable(r))return;if($(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(ce(n,r)){Xd(n,o);const i=jr(n,r);i?n.selection.selectBlock(i,G(n,i)):n.selection.selectBlock(r,0,G(n,r))}else Xd(n,o),d(Dy,qe(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=_(o);if(en(i)){const s=Wg(n,i);if(s){if(!n.isBlockWritable(s))return;Xd(n,o),n.selection.selectBlock(s,G(n,s))}}}}else l2(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=K(o),i=_(o);n.insertTextBlock("",q(i),r),n.deleteBlock(o)}}function Ly(n,e){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const t=n.selection.range.start,o=n.getBlockById(t.blockId);if($(n,o))if(t.offset===G(n,o)){const r=fe(o);if(r){if(!n.isBlockWritable(r))return;$(n,r)?n.mergeTextBlock(o,r,{focus:!0}):Ie(n,o)?n.deleteBlock(o,Fe(n,r,0)):n.deleteBlock(r)}}else l2(n,"forward",1,null);else{const r=K(o),i=_(o);n.insertTextBlock("",q(i),r),n.deleteBlock(o)}}function My(n){const{range:e}=n.selection,{start:t,end:o}=e,r=n.getBlockById(t.blockId),i=n.getBlockById(o.blockId);if(r!==i||!ce(n,r))return!1;if(qn(t))return!0;const s=sr(n,r,t,o),l=yt(n,r);return s.length===l.length}function Ry(n,e){if(My(n)){const o=n.getFocusedBlock(),r=K(o),i=q(_(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const t=n.getFocusedBlock();if($(n,t)){if(Ie(n,t)&&c2(n,t))return;const o=n.selection.range.start,r=n.breakTextBlock(t,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function Oy(n,e){const t=n.selection.range.getSelectedBlocks()[0],{block:o}=t;if(!$(n,o))return!1;const r=t.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:N(),box:!0,created:Date.now()}),!0}const Py=w("input-handler-actions");function Fy(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Ry(n),!0))}function Ny(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Ly(n),!0))}function $y(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Sy(n),!0))}function _y(n,e){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Oy(n),!0))}function jy(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(e=>{n.input.handlePasteText(e)}).catch(e=>{Py.error(e)}),!0)}const gc={ArrowDown:I0,ArrowUp:E0,ArrowLeft:w0,ArrowRight:B0,"Shift+ArrowDown":x0,"Shift+ArrowUp":S0,"Shift+ArrowLeft":T0,"Shift+ArrowRight":D0,"CtrlOrCmd+ArrowLeft":M0,"CtrlOrCmd+ArrowRight":R0,"CtrlOrCmd+Shift+ArrowLeft":O0,"CtrlOrCmd+Shift+ArrowRight":P0,"CtrlOrCmd+ArrowUp":N0,"CtrlOrCmd+ArrowDown":F0,"CtrlOrCmd+Shift+ArrowUp":$0,"CtrlOrCmd+Shift+ArrowDown":Zd,"CtrlOrCmd+A":n2,Home:V0,End:q0,"Shift+Home":z0,"Shift+End":U0,PageUp:Y0,PageDown:J0,"Shift+PageUp":K0,"Shift+PageDown":X0,"CtrlOrCmd+Z":xy,"CtrlOrCmd+Shift+Z":Ty,Enter:Fy,Delete:Ny,Backspace:$y,"Shift+Enter":_y,"CtrlOrCmd+Shift+V":jy};function a2(n,e){return n.shortcuts.handleKeyboardEvents(n,e)!==void 0}function u2(n,e,t){if(e.type==="embed"){const i=e.embedData,s=i.src;if(s&&typeof s=="string"){const l=t.get(s);l&&(i.src=l)}return}const o=e.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=t.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=e.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{u2(n,l,t)})})}function d2(n,e,t){if(t.size===0)return;e.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,t):u2(e,r,t)})}async function Hy(n,e){const t=e.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(t),r=new Map;if(t.length!==o.length)return r;for(let i=0;i<t.length;i++)r.set(t[i],o[i]);return r}function zy(n,e){var i,s;const o=e.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function Uy(n,e){const o=e.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(zy(n,e)){const s=Array.from(Object.keys(o));r=await Hy(n,s),d2(n,e,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&d2(n,e,i)}async function Vy(n,e,t){await Uy(n,e),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&qe(i)){const s=_(i),l=n.getBlockIndex(i),[c]=n.insertDocAt(s,l+1,e,t);c&&n.selection.selectBlock(c,G(n,c))}else{n.clearSelectedContents();const{block:s,offset:l}=Ur(n);n.insertDoc(s,l,e,t)}})}const qy=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function Wy(n){let e;for(const t of qy)if(e=n[t],e)break;return e||null}function h2(n,e,t){if(e.type==="embed"){const s=e.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))t.add(l);return}const o=e.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&t.add(i.attributes.src)});const r=e.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{h2(n,l,t)})})}function Gy(n,e){const t=new Set;return e.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{t.add(s)}):h2(e,r,t)}),Array.from(t)}function pc(n,e){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Ko(JSON.stringify(e))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Cc(n,e){var i,s,l;const t=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=Gy(n,e),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),e.meta={...t,resources:r}}function Zy(n,e,t){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;let o=fc(n);const r=t==null?void 0:t(n,e,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Cc(n,o);const i=ic(n,o),s=ss(n,o),l=pc(i,o);e.clipboardData.setData("text/html",l),e.clipboardData.setData("text/plain",s),e.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Ac(n,e){const t=Kd(n,e);Cc(n,t);const o=ic(n,t),r=ss(n,t),i=pc(o,t);return Su([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class Qy{constructor(e){h(this,"editor");h(this,"handlers",[]);h(this,"onPasteText",async e=>{const t=new DataTransfer;t.setData("text/plain",e);const o=await this.editor.dataConverter.fromData(this.editor,t);o&&this.pasteDocs(o,null)});this.editor=e}onInsertText(e,t){if(!$(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Ur(this.editor);this.handleBeforeInsertText(o,r,i,t)||(this.defaultInsertText(this.editor,o,r,i,t),this.handleAfterInsertText(o,r,i,t),this.editor.selection.updateLastCaretRect())}onKeyDown(e){if(this.handleBeforeKeyDown(e))return!0;const t=this.defaultHandleKeydown(this.editor,e);return this.handleAfterKeyDown(e)?!0:t}onChanged(e){for(let t=0;t<this.handlers.length;t++){const o=this.handlers[t];o.handleChanged&&o.handleChanged(this.editor,e)}}onRemoteChanged(e){for(let t=0;t<this.handlers.length;t++){const o=this.handlers[t];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,e)}}onCompositionStart(e){this.editor.updateCompositionText("",!1);const{containerId:t,blockIndex:o,offset:r}=Ur(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,t,o,r)}}onUpdateCompositionText(e,t,o){this.editor.updateCompositionText(t,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=Ur(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(e){Zy(this.editor,e,(t,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,e)===!0)return}if(this.onCopy(e),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;qe(o)&&this.editor.deleteBlock(o)}else Fd(this.editor)}onPaste(e){if(e.preventDefault(),e.stopPropagation(),!e.clipboardData)return;this.editor.dataConverter.fromData(this.editor,e.clipboardData).then(async o=>{o&&this.pasteDocs(o,e)})}onFocus(){R(this.editor.rootElement,"active")}onBlur(){j(this.editor.rootElement,"active")}addHandler(e){this.handlers.push(e)}removeHandler(e){const t=this.handlers.indexOf(e);t!==-1&&this.handlers.splice(t)}handleBeforeInsertText(e,t,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,e,t,o,r))return!0}return!1}handleAfterInsertText(e,t,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,e,t,o,r))return!0}return!1}handleBeforeKeyDown(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,e))return!0}const t=this.defaultHandleKeydown(this.editor,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,e))return!0}return t}handleAfterKeyDown(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,e))return!0}const t=this.defaultHandleKeydown(this.editor,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,e))return!0}return t}defaultInsertText(e,t,o,r,i){Sd(this.editor,i)}defaultHandleKeydown(e,t){return a2(this.editor,t)?(t.preventDefault(),t.stopPropagation(),!0):!1}async pasteDoc(e){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,e))return}const t={blockIdMap:new Map,containerIdMap:new Map};await Vy(this.editor,e,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,e,t))return}}async pasteDocs(e,t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,t,e))return}const o=Wy(e);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,t,e))return}}}destroy(){this.handlers.forEach(e=>{var t;(t=e.destroy)==null||t.call(e,this.editor)}),this.handlers=[]}}function Yy(n,e,t){const o=Fr(e,t);return o.remove(),o}w("copy-dom-attributes");const f2=["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 Jy(n,e){for(let l=0;l<f2.length;l++){const c=f2[l];e[c]=n[c]}const t=n.attributes,o=e.attributes,r=[],i=[];for(let l=0;l<t.length;l++){const c=t[l],a=o.getNamedItem(c.name);a?a.value!==c.value&&(a.value=c.value,i.push(c)):r.push(c)}const s=[];for(let l=0;l<o.length;l++){const c=o[l];t.getNamedItem(c.name)||s.push(c)}r.forEach(l=>{e.setAttribute(l.name,l.value)}),i.forEach(l=>{e.setAttribute(l.name,l.value)}),s.forEach(l=>{e.removeAttribute(l.name)})}function m2(n){const e=Array.from(n.childNodes).filter(t=>!lg(t));return e.forEach(t=>{t.remove()}),e}function g2(n,e,t){var a;const o=n.getContainerById(e),r=Fr(o,t),i=fo(r),s=n.doc.getBlockData(e,t),l=me(n,r);if((a=l==null?void 0:l.handleUpdateBlock)==null?void 0:a.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const u=n.editorBlocks.createBlock(i,o,s),f=m2(u);m2(r),f.forEach(p=>{r.appendChild(p)});const m=$l(u);if(m){const p=$l(r);p&&p.remove(),r.appendChild(m)}Jy(u,r)}Eg(n,r,s),n.blockHooks.forEach(u=>{var f;(f=u.update)==null||f.call(u,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const Ky=w("transform-selection");function p2(n,e,t,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==e&&s.blockId!==e)return r;d(Ky,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===e){const a=dt.transformCursor(i.offset,t,o);l=U(e,a,"normal")}let c=s;if(s.blockId===e){const a=dt.transformCursor(s.offset,t,o);c=U(e,a,"normal")}return Ge(n,{anchor:l,focus:c})}const Xy=w("handle-block-text-changed");function ek(n,e,t,o,r){const i=n.getContainerById(e),s=Fr(i,t),l=n.doc.getBlockData(e,t);if(d(Xy,l.text,"no block text"),bg(n,s).setBlockText(n,s,l.text),!r){const c=p2(n,l.id,o,r);n.selection.setRange(c,{noScroll:!0})}}function tk(n,e){const t=Q.default(n);return e.delete.forEach(r=>{delete t[r]}),{...t,...e.insert}}function C2(n,e,t,o){const r=me(n,e);r.handleDeleteBlock&&r.handleDeleteBlock(n,e,t,o),n.emit("blockDeleted",n,e,t,o)}function nk(n,e,t,o){const r=n.getBlockByIndex(e,t);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{C2(n,i,o,{child:!0})}),C2(n,r,o,{child:!1})}const rn=w("editor-doc");class ok extends zi{constructor(t,o,r){super();h(this,"localEvents",[]);this.editor=t,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(t){this.localEvents.push(t)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(t){return this.externalDoc.getContainerBlocks(t)}getBlockData(t,o){return this.externalDoc.getBlockData(t,o)}verifyBlockWritable(t,o){const r=this.editor.getBlockByIndex(t,o);d(rn,this.editor.isBlockWritable(r),`block is not writable, ${t}, ${o}`)}localUpdateBlockText(t,o,r,i){d(rn,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const s=this.getBlockData(t,o),l=s.text;d(rn,l,`no text, ${t}, ${o}`);const c=p2(this.editor,s.id,r,!0),a=dt.apply(l,r);this.localEvents.forEach(f=>f.onBeforeUpdateBlockText(t,s.id,l,a,c.toDocRange()));const u=this.externalDoc.localUpdateBlockText(t,o,r);return this.editor.selection.setRange(c,i),u}localUpdateBlockData(t,o,r,i){d(rn,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(t,o);if(!this.editor.isBlockWritable(s)){const u=Array.from(r.delete).filter(m=>m!=="comments"),f=Object.keys(r.insert).filter(m=>m!=="comments");(u.length>0||f.length>0)&&d(rn,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=Q.default(this.getBlockData(t,o)),c=Q.default(tk(l,r));this.localEvents.forEach(u=>u.onBeforeUpdateBlockData(t,l.id,l,c,i));const a=this.externalDoc.localUpdateBlockData(t,o,r,i);return this.editor.selection.setRange(mo(this.editor,i)),a}localInsertBlock(t,o,r,i,s){d(rn,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(t,o,r,i));const l=this.externalDoc.localInsertBlock(t,o,r,i);return this.editor.selection.setRange(mo(this.editor,i),s),l}localDeleteBlock(t,o,r){d(rn,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(t,o);const i=Q.default(this.getBlockData(t,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(t,o,i,r));const s=this.externalDoc.localDeleteBlock(t,o,r);return this.editor.selection.setRange(mo(this.editor,r)),s}localDeleteChildContainers(t){return d(rn,!this.editor.readonly,"editor is readonly"),t.forEach(o=>{const r=Q.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(t)}localInsertChildContainer(t,o){return d(rn,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(t,Q.default(o))),this.externalDoc.localInsertChildContainer(t,o)}onRequestReload(t){rn.debug(`reload doc: ${t}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,t)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(t,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,t,o,r,i)}),ek(this.editor,t,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(t,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,t,o,r,i)}),g2(this.editor,t,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(t,o,r,i){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,t,o,r,i)});const s=this.editor.getContainerById(t);qA(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(t,o,r){nk(this.editor,t,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,t,o,r)});const i=this.editor.getContainerById(t);Yy(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(t,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,t,o,r)})}onDeleteChildContainer(t,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,t,o)})}onCustomMessage(t){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,t)})}onStatusChanged(t){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,t)})}onError(t){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,t)})}uploadResource(t,o){return this.externalDoc.uploadResource(t,o)}addResources(t){return this.externalDoc.addResources(t)}buildResourceUrl(t,o){return this.externalDoc.buildResourceUrl(t,o)}request(t,o){return this.externalDoc.request(t,o)}broadcastMessage(t){return this.externalDoc.broadcastMessage(t)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var t,o,r;return(r=(o=(t=this.externalDoc).getServerMeta)==null?void 0:o.call(t))!=null?r:{}}reset(t){rn.log("reset doc"),this.externalDoc=t,this.externalDoc.registerCallback(this),this.editor.reload()}}function A2(n,e){if(n.length===0){n.push(e);return}const t=n[n.length-1];if(!t.combinable(e)){n.push(e);return}t.combine(e)}const eh=w("undo-action");class Gr{constructor(e,t,o){h(this,"beforeRange");h(this,"afterRange");this.containerId=t,this.beforeRange=e.selection.range.clone().toDocRange(),this.afterRange=o}undo(e){return!1}redo(e){return!1}combinable(e){return d(eh,e,"no other action"),!1}combine(e){d(eh,!1,"no other")}setAfterRange(e){this.afterRange&&eh.warn("after range has already set"),this.afterRange=e}}const rk=w("block-action");class b2 extends Gr{constructor(t,o,r,i,s){super(t,o,s);h(this,"blockData");h(this,"blockIndex");this.blockData=Q.default(i),this.blockIndex=r}deleteBlock(t,o){if(!t.getContainerById(this.containerId))return!1;const i=t.getBlockById(this.blockData.id);return i?(d(rk,this.blockIndex===K(i),"invalid block index"),Rd(t,i,mo(t,o)),!0):!1}insertBlock(t,o){return Vr(t,this.containerId,this.blockIndex,Q.default(this.blockData),o),!0}}class ik extends b2{undo(e){return this.deleteBlock(e,this.beforeRange)}redo(e){return this.insertBlock(e,this.afterRange)}}class sk extends b2{undo(e){return this.insertBlock(e,this.beforeRange)}redo(e){return this.deleteBlock(e,this.afterRange)}}class lk extends Gr{constructor(t){super(t,q(t.rootContainer),t.selection.range.toDocRange());h(this,"actions",[])}addAction(t){A2(this.actions,t),this.afterRange=t.afterRange}undo(t){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(t)&&(o=!0)}),o}redo(t){let o=!1;return this.actions.forEach(r=>{r.redo(t)&&(o=!0)}),o}setAfterRange(t){this.afterRange=t;const o=this.actions[this.actions.length-1];!o||o instanceof Gr&&(o.afterRange||o.setAfterRange(t))}}const hr=w("update-block-data-action");class bc extends Gr{constructor(t,o,r,i,s,l){super(t,o,l);h(this,"beforeBlockData");h(this,"afterBlockData");h(this,"blockId");this.blockId=r,d(hr,this.blockId===i.id,"invalid block id"),d(hr,this.blockId===s.id,"invalid block id"),this.beforeBlockData=Q.default(i),this.afterBlockData=Q.default(s),d(hr,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(t){d(hr,t,"no editor");const o=t.getBlockById(this.blockId);if(!o)return!1;const r=t.getContainerById(this.containerId);return d(hr,r,"no container"),uc(t,o,bc.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(t){d(hr,t,"no editor");const o=t.getBlockById(this.blockId);if(!o)return!1;const r=t.getContainerById(this.containerId);return d(hr,r,"no container"),uc(t,o,bc.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(t){const o=Q.default(t);return delete o.id,delete o.type,o}}const th=w("update-block-text-action");class ms extends Gr{constructor(t,o,r,i,s,l){super(t,o,l);h(this,"beforeRichTextData");h(this,"afterRichTextData");h(this,"blockId");h(this,"type");this.blockId=r,this.beforeRichTextData=Q.default(i),this.afterRichTextData=Q.default(s),this.type=ms.calType(i,s)}static calType(t,o){d(th,t,"no old data"),d(th,o,"no new data");const i=dt.diff(t,o),s=new Set;let l=!1;const c=u=>jm(u)?`cjk_${u}`:$m(u)?"number":Ll(u)?"space":_m(u)?"letter":"unknown";let a=!1;return i.forEach(u=>{u.insert?u.insert===" "?s.add("insert_letter"):typeof u.insert=="string"&&u.insert.startsWith(" ")&&u.insert.length>1?(l=!0,a=!0,s.add(`insert_${c(u.insert.substr(1))}`)):s.add(`insert_${c(u.insert)}`):u.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:a}}undo(t){if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(ac(t,r,this.beforeRichTextData),!0):!1}redo(t){if(!t.getContainerById(this.containerId))return!1;const r=t.getBlockById(this.blockId);return r?(ac(t,r,this.afterRichTextData),!0):!1}combinable(t){if(!(t instanceof ms)||t.type.begin||this.type.textType!==t.type.textType||t.blockId!==this.blockId)return!1;const o=t.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(t){d(th,t instanceof ms,"invalid action type");const o=t;this.afterRichTextData=o.afterRichTextData,this.afterRange=t.afterRange}}class v2 extends Gr{constructor(e,t,o){super(e,t,e.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(e){return e.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(e){return e.doc.localInsertChildContainer(this.containerId,Q.default(this.blocks)),!0}}class ck extends v2{undo(e){return this.deleteChildContainer(e)}redo(e){return this.insertChildContainer(e)}}class ak extends v2{undo(e){return this.insertChildContainer(e)}redo(e){return this.deleteChildContainer(e)}}const sn=w("undo");class uk{constructor(e){h(this,"editor");h(this,"actions",[]);h(this,"undoCursor");h(this,"currentGroup",null);h(this,"groupCounter",0);h(this,"undoRedoing",!1);h(this,"handleSelectionChange",e=>{if(this.currentGroup){this.currentGroup.setAfterRange(e.selection.range.toDocRange());return}const t=this.actions[this.actions.length-1];!t||t.afterRange||t.setAfterRange(e.selection.range.toDocRange())});this.editor=e,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(e){this.currentGroup?this.currentGroup.addAction(e):(A2(this.actions,e),setTimeout(()=>{this.editor.input.handleChanged(e)}))}beginGroup(){this.groupCounter===0?(d(sn,!this.currentGroup,"current group already exists"),this.currentGroup=new lk(this.editor),this.groupCounter=1):(d(sn,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(sn,this.currentGroup,"current group not exists"),d(sn,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?sn.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(e){this.beginGroup();try{const t=e();return setTimeout(()=>this.editor.selection.caret.update()),t}catch(t){throw sn.error(`failed to run action: ${t.message}`),t}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const e=this.actions[this.undoCursor];if(e.undo(this.editor)){try{this.editor.selection.setRange(mo(this.editor,e.beforeRange))}catch(t){sn.error(`undo: failed to restore caret pos: ${t.message}`)}return this.editor.input.handleChanged(e),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const e=this.actions[this.undoCursor];if(this.undoCursor+=1,e.redo(this.editor)){try{const t=e.afterRange;t?this.editor.selection.setRange(mo(this.editor,t)):sn.warn("no after range")}catch(t){sn.error(`redo: failed to set caret pos after redo: ${t.message}`)}return this.editor.input.handleChanged(e),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var t;const e=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(t=this.actions[e])!=null?t:null}undoTo(e){for(;;){const t=this.lastAction();if(!t||t===e)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(e,t,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),dt.diff(o,r).length!==0&&this.addAction(new ms(this.editor,e,t,o,r,i)))}onBeforeUpdateBlockData(e,t,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new bc(this.editor,e,t,o,r,i);this.addAction(s)}onBeforeInsertBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(sn,t>=0,"invalid block index"),d(sn,o,"no block data"),this.addAction(new ik(this.editor,e,t,o,r)))}onBeforeDeleteBlock(e,t,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new sk(this.editor,e,t,o,r)))}onBeforeInsertChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new ck(this.editor,e,t)))}onBeforeDeleteChildContainer(e,t){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new ak(this.editor,e,t)))}}class dk{async fromData(e,t){const o=t.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class hk{constructor(){h(this,"converters",[]);this.addConverter(new dk)}async fromData(e,t){let o={};for(const r of this.converters){const i=await r.fromData(e,t);i&&(o={...o,...i})}return o}addConverter(e){this.converters.push(e)}}class fk{constructor(e){h(this,"renders",[]);this.editor=e}registerRender(e){this.renders.push(e)}renderText(e,t){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,e,t);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(e,t,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,t,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(e,t,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,e,t,o,r)})}}class Se extends Ve.TypedEmitter{constructor(t){super();h(this,"hoveringBlock",null);h(this,"hoveringTextChild",null);h(this,"filters",[]);h(this,"finders",[]);h(this,"handleDocumentMouseMove",t=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,t))return}const o=document.elementFromPoint(t.x,t.y);if(!o){this.setHoveringBlock(null,t,null);return}let r=H(o);if((!r||!Ce(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(t),!r)){this.setHoveringBlock(null,t,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,t,i)});this.editor=t,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(t=>t.destroy()),this.filters=[],this.finders.forEach(t=>t.destroy()),this.finders=[]}addFilter(t){this.filters.push(t)}addFinder(t){this.finders.push(t)}hoveringBlockId(){return this.hoveringBlock?z(this.hoveringBlock):""}findBlockByFinders(t){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,t);if(i)return i}return null}setHoveringBlock(t,o,r){if(this.hoveringBlock===t&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==t){const s=this.hoveringBlock&&Ce(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&j(s,"hover"),t&&R(t,"hover"),this.hoveringBlock=t,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(t){return t.addCustom("standard-hovering-block",()=>new Se(t))}getParentTextContentChild(t,o){if(!$(this.editor,t))return null;const r=le(t);return o.parentElement===r?o:$u(o)}}const y2="style-color-",k2="style-bg-color-";class mk{renderText(e,t,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,c])=>{c===!0?l.startsWith(y2)?i["data-style-color"]=l.substring(y2.length):l.startsWith(k2)?i["data-style-bg-color"]=l.substring(k2.length):l.startsWith("style")&&r.push(l):typeof c=="string"&&(l==="link"&&(r.push("link"),i.link=c),l==="inline-style-color"&&(s.color=c))}),{classes:r,attributes:i,styles:s}}renderBlock(e,t,o){var l,c;const r={};Object.entries(o).filter(a=>a[0].startsWith("style-")).forEach(([a,u])=>{r[`data-${a}`]=`${u}`});const s=[];return((c=(l=e.selection)==null?void 0:l.range)==null?void 0:c.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"),Se.get(e).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(e,t,o,r){var s,l;Array.from(o.attributes).forEach(c=>{c.name.startsWith("data-style-")&&o.removeAttribute(c.name)}),Object.entries(r).filter(c=>c[0].startsWith("style-")).forEach(([c,a])=>{o.setAttribute(`data-${c}`,`${a}`)}),((l=(s=e.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&R(o,"focused"),Se.get(e).hoveringBlockId()===r.id&&R(o,"hover")}}function gk(n){n.editorBlocks.registerBlockClass(wt),n.editorBlocks.registerBlockClass(qg),n.editorBoxes.registerBoxClass(Op),n.editorBoxes.registerBoxClass(Pp),n.editorBoxes.registerBoxClass($p),n.editorBoxes.registerBoxClass(_p),n.editorInsertions.registerInsertionClass(jp),n.editorBlockRenders.registerRender(new mk)}function pk(n,e){gk(n),e!=null&&e.blocks&&e.blocks.forEach(t=>n.editorBlocks.registerBlockClass(t)),e!=null&&e.boxes&&e.boxes.forEach(t=>n.editorBoxes.registerBoxClass(t)),e!=null&&e.embeds&&e.embeds.forEach(t=>n.editorEmbeds.registerEmbedClass(t)),e!=null&&e.insertions&&e.insertions.forEach(t=>n.editorInsertions.registerInsertionClass(t)),e!=null&&e.decorators&&e.decorators.forEach(t=>n.editorDecorators.registerDecorator(t)),e!=null&&e.dataConverters&&e.dataConverters.forEach(t=>n.dataConverter.addConverter(t)),e!=null&&e.commandProviders&&e.commandProviders.forEach(t=>n.editorCommandProviders.registerCommandProvider(t)),e!=null&&e.textRenders&&e.textRenders.forEach(t=>n.editorBlockRenders.registerRender(t))}const w2=w("range-commands");function B2(n,e){n.forEach(t=>{t.source=e,t.children&&B2(t.children,e)})}function E2(n,e,t){const o=z(e);d(w2,o===t.start.blockId,"invalid start range"),d(w2,o===t.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,e,t);B2(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,e,t,i);l&&(i=l)}}),ce(n,e)&&sr(n,e,t.start,t.end).forEach(l=>{Me(l).forEach(a=>{const u=G(n,a),f=Ge(n,{anchor:U(a,0,"home"),focus:U(a,u,"end")}),m=E2(n,a,f);i.push(...m)})}),i}function I2(n){const e=n.getEditor(),t=n.getSelectedBlocks(),o=[];return t.forEach(r=>{const i=Ge(e,{anchor:r.start,focus:r.end});E2(e,r.block,i).forEach(l=>{o.push(l)})}),o}function x2(n,e,t,o,r,i){var u;const s=n.editorCommandProviders.getCommandProviders();for(let f=0;f<s.length;f++){const m=s[f];if(m.beforeExecuteCommand&&m.beforeExecuteCommand(n,e,t,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),c={};if((u=l.executeCommand)!=null&&u.call(l,n,e,t,o,r,{}))return i[z(e)]=c,!0;let a=!1;return ce(n,e)&&sr(n,e,t.start,t.end).forEach(m=>{Me(m).forEach(b=>{const y=G(n,b),v=Ge(n,{anchor:U(b,0,"home"),focus:U(b,y,"end")});x2(n,b,v,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,e,t,o,r,i)}),a}function T2(n,e,t){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(e.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,e,t,r)||n.getSelectedBlocks().forEach(l=>{const c=Ge(o,{anchor:l.start,focus:l.end});x2(o,l.block,c,e,t,r)}),r}const Ck=w("command-providers");class D2{constructor(e){h(this,"providers",[]);this.editor=e}registerCommandProvider(e){this.providers.push(e)}getCommandProviders(){return this.providers}getCommandProvider(e){const t=this.providers.find(o=>o.id===e);return d(Ck,t,`no command provider, id=${e}`),t}getCommands(e){return I2(e)}executeCommand(e,t,o){return this.editor.undoManager.runInGroup(()=>T2(e,t,o))}getEmptyBlockTextAttributes(e,t){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,e,t);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function Ak(n,e){const t=_(e),o=q(t),r=K(e);g2(n,o,r)}const bk=w("table-scroll");class S2{constructor(e,t,o,r,i){h(this,"handleEvent",e=>{this.handler(this.editor,e,this.data)});this.editor=e,this.dom=t,this.name=o,this.handler=r,this.data=i,t.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class vk{constructor(e){h(this,"handlers",new Map);this.editor=e}destroy(){Array.from(this.handlers.entries()).forEach(([e,t])=>{t.forEach(o=>o.destroy()),this.handlers.delete(e)})}addEventListener(e,t,o,r){const i=this.handlers.get(e);if(i){if(i.find(s=>s.handler===o&&s.name===t)){bk.warn(`event has already registered: ${t}`);return}i.push(new S2(this.editor,e,t,o,r))}else{const s=new S2(this.editor,e,t,o,r);this.handlers.set(e,[s])}}removeEventListener(e,t,o){if(!e){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(t)t===c.name&&o===c.handler&&s.splice(l,1);else if(o===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(e);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===t);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(e)}}}removeAllListeners(e,t){const o=this.handlers.get(e);if(o)if(t)for(let r=0;r<o.length;r++){const i=o[r];i.name===t&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(e)}}const L2=w("update-block-text");function yk(n,e){const t=n.getBoxById(e.id),o=H(t);d(L2,o,"no parent block"),d(L2,$(n,o),"not a text block");const r=n.getBlockText(o),i=Ep(r,"id",e.id,e);a0(n,o,i)}function kk(n,e){for(const t of n.blockHooks)if(t.writable){const o=t.writable(n,e);if(typeof o=="boolean")return o}return!0}function wk(n){return n.readonly?!1:!nn(n).find(o=>!n.isBlockWritable(o.block))}class Bk{constructor(e){this.editor=e}getKey(e){return`${this.editor.id}-${e}`}getItem(e){return window.localStorage.getItem(this.getKey(e))}setItem(e,t){if(!t){this.removeItem(e);return}window.localStorage.setItem(this.getKey(e),t)}removeItem(e){window.localStorage.removeItem(this.getKey(e))}}class Ek{constructor(){h(this,"shortcuts",[])}handleKeyboardEvents(e,t){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(Hn(t,s)){const c=l(e,t);if(c!==void 0)return c}}}}const Qn=w("editor");class Ik extends Ve.TypedEmitter{constructor(t,o,r){var i,s,l,c,a,u,f;super();h(this,"parent");h(this,"rootElement");h(this,"contentElement");h(this,"rootContainerObject");h(this,"rootContainer");h(this,"input");h(this,"selection");h(this,"selectionHandler");h(this,"doc");h(this,"id");h(this,"clientId");h(this,"compositingText","");h(this,"undoManager");h(this,"shortcuts",new Ek);h(this,"dataConverter",new hk);h(this,"editorBlocks",new Hg(this));h(this,"editorBoxes",new Np(this));h(this,"editorInsertions",new zp(this));h(this,"editorEmbeds",new Ug(this));h(this,"editorDecorators",new Up(this));h(this,"editorCommandProviders",new D2(this));h(this,"editorBlockRenders",new fk(this));h(this,"blockHooks",[]);h(this,"domEvents",new vk(this));h(this,"customs",new Map);h(this,"options");h(this,"inputHandlers",new Qy(this));h(this,"settingsProvider");h(this,"_readonly",!1);Qn.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=(c=r==null?void 0:r.settingsProvider)!=null?c:new Bk(this),pk(this,r==null?void 0:r.components),this.blockHooks.push(...(u=(a=r==null?void 0:r.components)==null?void 0:a.blockHooks)!=null?u:[]),this.id=(f=r==null?void 0:r.id)!=null?f:N(),this.clientId=N(),this.undoManager=new uk(this),this.doc=new ok(this,o,this.undoManager),this.parent=t,this.rootElement=A("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=A("div",["editor-content"],this.rootElement),this.rootContainerObject=$g(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new Nv(this,this.inputHandlers),this.selection=new wy(this),this.selectionHandler=new Iy(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),ot.isMobile&&R(this.rootElement,"mobile"),ot.isSafari&&R(this.rootElement,"safari"),this._readonly&&R(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(t){this._readonly=t,t?R(this.rootElement,"readonly"):j(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:Qt(this.rootContainer)}addCustom(t,o){const r=this.customs.get(t);if(r)return r;const i=o(this);return this.customs.set(t,i),i}getCustom(t){const o=this.customs.get(t);return d(Qn,o,`${t} does not exists`),o}replaceCustom(t,o){const r=this.customs.get(t);return r&&r.destroy(),this.customs.set(t,o),o}findCustom(t){return this.customs.get(t)}findCustomByType(t){const o=this.customs.values();for(const r of o)if(r instanceof t)return r;return null}destroyCustom(t){const o=this.customs.get(t);o&&(this.customs.delete(t),o.destroy())}getComponentOptions(t){return this.options.componentsOptions[t]}registerLocalEvents(t){this.doc.registerLocalEvents(t)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(t,o,r){return this.editorBlocks.createBlock(t,o,r)}createBox(t,o){return this.editorBoxes.createBox(t,o)}createInsertion(t,o){return this.editorInsertions.createInsertion(t,o)}destroy(){Qn.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(t=>t.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(t,o){Nd(this,t,o)}isWritable(){return wk(this)}isBlockWritable(t){return kk(this,t)}getChildContainerData(t){const o=this.doc.getContainerBlocks(t);return d(Qn,o,`no child container data: ${t}, ${JSON.stringify(this.doc)}`),d(Qn,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(t,o,r){return _g(this,t,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const t=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return t[t.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&d(Qn,er(o),"not an valid block element"),o!=null?o:null}findBoxById(t){const o=this.rootContainer.querySelector(`#${t}`);return o&&d(Qn,Nu(o),"not an valid box element"),o!=null?o:null}getBlockById(t){const o=this.findBlockById(t);return d(Qn,o,`no block, id=${t}`),o}getBoxById(t){const o=this.findBoxById(t);return d(Qn,o,`no box, id=${t}`),o}getBlockByIndex(t,o){const r=this.getContainerById(t);return Fr(r,o)}getBlockIndex(t){if(typeof t=="string"){const o=this.getBlockById(t);return K(o)}return K(t)}getContainerById(t){return _r(this,t)}getParentContainer(t){return _(t)}reloadBlock(t){Ak(this,t)}contains(t){const o=t instanceof Element?t:t.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(t,o,r,i,s){const l={blockId:r.id,offset:0},c={anchor:l,focus:l};return Vr(this,t,o,r,i!=null?i:c,s)}insertEmbed(t,o,r,i,s){const l={id:N(),type:"embed",embedType:r,embedData:i};return this.insertBlock(t,o,l,s)}deleteBlock(t,o){Od(this,t,o)}mergeTextBlock(t,o){return s0(this,t,o)}breakTextBlock(t,o,r){return qr(this,t,o,r).newBlock}getTextPosition(){return Ur(this)}getBlockString(t,o){const r=this.getBlockText(t);return ve(r,o)}getBlockData(t){return vo(this,t)}getBoxData(t){return Mp(this,t)}getBlockText(t){return pt(this,t)}setBlockText(t,o){a0(this,t,o)}deleteTextFromBlock(t,o,r,i){return Ld(this,t,o,r,i)}insertTextToBlock(t,o,r,i){return Xp(this,t,o,r,i)}insertBoxToBlock(t,o,r){return e0(this,t,o,r)}pasteDoc(t){return this.inputHandlers.pasteDoc(t)}insertDoc(t,o,r,i){h0(this,t,o,r,i)}insertDocAt(t,o,r,i){return jd(this,t,o,r,i)}deleteChildContainers(t){i0(this,t)}replaceBlockText(t,o){return ac(this,t,o)}updateBlockData(t,o,r){const i={...this.getBlockData(t),...o},{id:s,type:l,...c}=i;return uc(this,t,c,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(t,o,r){return u0(this,t,o,r)}updateBoxData(t){yk(this,t)}getSelectedText(){const t=fc(this);return is(this,t)}clearSelectedContents(){Fd(this)}insertTextBlock(t,o,r,i){const s=Gn(t!=null?t:"");return r0(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(t,o){if(t&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!t&&!o){n0(this);return}o?(this.compositingText="",wu()||Sd(this,t)):(this.compositingText=t,t0(this))}getColor(t){const o=this.options.colors;return o.length===0?"#FF1A75":o[t%o.length]}}function gs(n,e,t){return new Ik(n,e,t)}function xk(n){const e=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=du.default(s.states,r.states)}},t=[];return n.forEach(o=>{o.forEach(r=>{e(t,r)})}),t}const Tk=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class vc extends Ve.TypedEmitter{constructor(t){super();h(this,"users",new Map);h(this,"cursors",new Map);h(this,"addingUser",!1);h(this,"colors");this.colors=t&&t.length>0?t:Tk}setCursor(t){this.addUser(t.user);const o=this.cursors.get(t.user.userId);if(o&&_i.default(o,t))return;this.cursors.set(t.user.userId,t);const r=new Set([t.range.anchor.blockId,t.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(t){this.addingUser=!0,t.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(t){this.users.set(t.userId,t),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(t){var o;return(o=this.users.get(t))!=null?o:null}removeUser(t){this.users.delete(t),this.cursors.delete(t),this.emit("change",Array.from(this.users.values()))}updateUsers(t){this.users.clear(),this.addingUser=!0;try{t.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(t){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===t&&Xl(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(t){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===t||o.range.focus.blockId===t)}onUpdateBlockText(t,o,r){if(!t.text)return;this.getCursors(t.id).forEach(l=>{if(Xl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===t.id&&(c.offset=dt.transformCursor(c.offset,o,r)),a.blockId===t.id&&(a.offset=dt.transformCursor(a.offset,o,r))}})}getFixedUserColor(t,o){let r=0;Array.from(t).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const rt=w("local-doc");class nh extends zi{constructor(t,o){super();h(this,"doc");h(this,"serviceUrl");t?this.doc=t:this.doc={meta:{},comments:{},blocks:{root:[Gn("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return Q.default(this.doc)}getContainerBlocks(t){return this.doc.blocks[t]}getBlockData(t,o){const r=this.getContainerBlocks(t);d(rt,r,`no container data: ${t}`);const i=r[o];return d(rt,i,`no block data: ${o}`),i}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);d(rt,i.text,"no text for data");const s=dt.apply(i.text,r);return i.text=s,d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,t,o,r,!0)}),s}localUpdateBlockData(t,o,r){const i=this.getBlockData(t,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,t,o,r,!0)}),i}localInsertBlock(t,o,r){const i=this.getContainerBlocks(t);return d(rt,i,`no container data: ${t}`),d(rt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,t,o,r,!0)}),r}localDeleteBlock(t,o){const r=this.getContainerBlocks(t);d(rt,r,`no container data: ${t}`),d(rt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,t,o,!0)}),i}localInsertChildContainer(t,o){this.doc.blocks[t]=o,d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,t,o,!0)})}localDeleteChildContainers(t){rt.debug(`delete child containers: ${t}`),t.forEach(o=>{d(rt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),t.forEach(o=>{d(rt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(t,o){d(rt,!1,"not implemented")}async addResources(t){return t}buildResourceUrl(t){return t}request(t,o){d(rt,!1,"not implemented")}broadcastMessage(t){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new vc}setDoc(t){this.doc=Q.default(t),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class Dk{constructor(e){this.cleanup=e}destroy(){var e;(e=this.cleanup)==null||e.call(this)}}function oh(n,e,t){n.addCustom(e,()=>{var i;const o=(i=t())!=null?i:void 0;return new Dk(o)})}const M2=w("find-block");function R2(n,e){const t=or(e);if(!t){if(Ft(e))return null;const o=tr(e);return d(M2,o,"no parent block"),R2(n,o)}return ce(n,t)?jr(n,t,{visibleOnly:!0}):t}function O2(n,e){const t=rr(e);if(!t){if(Ft(e))return null;const o=tr(e);return d(M2,o,"no parent block"),O2(n,o)}return ce(n,t)?ed(n,t,{visibleOnly:!0}):t}const Sk=w("remote-cursor");class Lk{constructor(){h(this,"remoteUsers",new vc)}onCustomMessage(e){const t=e;if(t.type==="onlineUsers"){const o=t;this.handleUpdateUsers(o.users)}else t.type==="caret"?this.handleUpdateCaret(t):Sk.debug(`unknown remote message received: ${e}`)}handleUpdateUsers(e){this.remoteUsers.updateUsers(e)}handleUpdateCaret(e){const t=this.remoteUsers.findUser(e.userId);!t||this.remoteUsers.setCursor({oneseditor:"cursor",user:t,range:e.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function Mk(n){const{blocks:e,meta:t,comments:o,...r}=n;return{rootBlocks:e,meta:t,comments:o,childBlocks:r}}function Rk(n){const{blocks:e,meta:t,comments:o}=n,{root:r,...i}=e;return{blocks:r,meta:t,comments:o,...i}}function ps(n){const{childBlocks:e,meta:t,comments:o,rootBlocks:r}=Mk(Q.default(n));return{blocks:{root:r,...e},meta:t,comments:o}}function wo(n){return n==="root"?"blocks":n}function Zr(n){return n==="blocks"?"root":n}const Ok={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ct.default(n)},apply(n,e){const t=new ct.default(n),o=new ct.default(e);return t.compose(o).ops},compose(n,e){const t=new ct.default(n),o=new ct.default(e);return t.compose(o).ops},diff(n,e){const t=new ct.default(n),o=new ct.default(e);return t.diff(o).ops},transform(n,e,t){const o=new ct.default(n);return new ct.default(e).transform(o,t==="left").ops},transformCursor(n,e,t){return e.transformPosition(n,!t)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,e,t){if(!n)return null;const o=new ct.default(e),r=this.transformCursor(n.index,o,t),i=this.transformCursor(n.index+n.length,o,t);return{...n,index:r,length:i-r}}}};var Cs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Bo={},rh=Am.default.EventEmitter;Bo.EventEmitter=rh,Bo.mixin=Pk;function Pk(n){for(var e in rh.prototype)n.prototype[e]=rh.prototype[e]}var P2=["info","warn","error"];function F2(){var n={};P2.forEach(function(e){n[e]=console[e].bind(console)}),this.setMethods(n)}var Fk=F2;F2.prototype.setMethods=function(n){n=n||{};var e=this;P2.forEach(function(t){typeof n[t]=="function"&&(e[t]=n[t])})};var Nk=Fk,$k=new Nk,N2=$k;function fr(n,e){this.code=n,this.message=e||"",Error.captureStackTrace?Error.captureStackTrace(this,fr):this.stack=new Error().stack}fr.prototype=Object.create(Error.prototype),fr.prototype.constructor=fr,fr.prototype.name="ShareDBError",fr.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 yc=fr,As={},$2=_k;function _k(n,e,t,o){var r=function(s,l,c,a){e(c,s,l,"left"),e(a,l,s,"right")},i=n.transformX=function(s,l){t(s),t(l);for(var c=[],a=0;a<l.length;a++){for(var u=l[a],f=[],m=0;m<s.length;){var p=[];if(r(s[m],u,f,p),m++,p.length===1)u=p[0];else if(p.length===0){for(var b=m;b<s.length;b++)o(f,s[b]);u=null;break}else{for(var y=i(s.slice(m),p),v=0;v<y[0].length;v++)o(f,y[0][v]);for(var x=0;x<y[1].length;x++)o(c,y[1][x]);u=null;break}}u!=null&&o(c,u),s=f}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?e([],s[0],l[0],c):c==="left"?i(s,l)[0]:i(l,s)[1]}}var _2={exports:{}},Eo=_2.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||""}},ih=function(n,e,t){return n.slice(0,e)+t+n.slice(e)},sh=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")},kc=function(n){for(var e=0;e<n.length;e++)sh(n[e])};Eo.apply=function(n,e){var t;kc(e);for(var o=0;o<e.length;o++){var r=e[o];if(r.i!=null)n=ih(n,r.p,r.i);else{if(t=n.slice(r.p,r.p+r.d.length),r.d!==t)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+t+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var Yn=Eo._append=function(n,e){if(!(e.i===""||e.d===""))if(n.length===0)n.push(e);else{var t=n[n.length-1];t.i!=null&&e.i!=null&&t.p<=e.p&&e.p<=t.p+t.i.length?n[n.length-1]={i:ih(t.i,e.p-t.p,e.i),p:t.p}:t.d!=null&&e.d!=null&&e.p<=t.p&&t.p<=e.p+e.d.length?n[n.length-1]={d:ih(e.d,t.p-e.p,t.d),p:e.p}:n.push(e)}};Eo.compose=function(n,e){kc(n),kc(e);for(var t=n.slice(),o=0;o<e.length;o++)Yn(t,e[o]);return t},Eo.normalize=function(n){var e=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=0),Yn(e,o)}return e};var lh=function(n,e,t){return e.i!=null?e.p<n||e.p===n&&t?n+e.i.length:n:n<=e.p?n:n<=e.p+e.d.length?e.p:n-e.d.length};Eo.transformCursor=function(n,e,t){for(var o=t==="right",r=0;r<e.length;r++)n=lh(n,e[r],o);return n};var jk=Eo._tc=function(n,e,t,o){if(sh(e),sh(t),e.i!=null)Yn(n,{i:e.i,p:lh(e.p,t,o==="right")});else if(t.i!=null){var r=e.d;e.p<t.p&&(Yn(n,{d:r.slice(0,t.p-e.p),p:e.p}),r=r.slice(t.p-e.p)),r!==""&&Yn(n,{d:r,p:e.p+t.i.length})}else if(e.p>=t.p+t.d.length)Yn(n,{d:e.d,p:e.p-t.d.length});else if(e.p+e.d.length<=t.p)Yn(n,e);else{var i={d:"",p:e.p};e.p<t.p&&(i.d=e.d.slice(0,t.p-e.p)),e.p+e.d.length>t.p+t.d.length&&(i.d+=e.d.slice(t.p+t.d.length-e.p));var s=Math.max(e.p,t.p),l=Math.min(e.p+e.d.length,t.p+t.d.length),c=e.d.slice(s-e.p,l-e.p),a=t.d.slice(s-t.p,l-t.p);if(c!==a)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=lh(i.p,t),Yn(n,i))}return n},Hk=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Eo.invert=function(n){n=n.slice().reverse();for(var e=0;e<n.length;e++)n[e]=Hk(n[e]);return n},$2(Eo,jk,kc,Yn);var wc=function(n){return Object.prototype.toString.call(n)=="[object Array]"},zk=function(n){return!!n&&n.constructor===Object},ln=function(n){return JSON.parse(JSON.stringify(n))},oe={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Jn={};oe.registerSubtype=function(n){Jn[n.name]=n},oe.create=function(n){return n===void 0?null:ln(n)},oe.invertComponent=function(n){var e={p:n.p};return n.t&&Jn[n.t]&&(e.t=n.t,e.o=Jn[n.t].invert(n.o)),n.si!==void 0&&(e.sd=n.si),n.sd!==void 0&&(e.si=n.sd),n.oi!==void 0&&(e.od=n.oi),n.od!==void 0&&(e.oi=n.od),n.li!==void 0&&(e.ld=n.li),n.ld!==void 0&&(e.li=n.ld),n.na!==void 0&&(e.na=-n.na),n.lm!==void 0&&(e.lm=n.p[n.p.length-1],e.p=n.p.slice(0,n.p.length-1).concat([n.lm])),e},oe.invert=function(n){for(var e=n.slice().reverse(),t=[],o=0;o<e.length;o++)t.push(oe.invertComponent(e[o]));return t},oe.checkValidOp=function(n){for(var e=0;e<n.length;e++)if(!wc(n[e].p))throw new Error("Missing path")},oe.checkList=function(n){if(!wc(n))throw new Error("Referenced element not a list")},oe.checkObj=function(n){if(!zk(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function bs(n){n.t="text0";var e={p:n.p.pop()};n.si!=null&&(e.i=n.si),n.sd!=null&&(e.d=n.sd),n.o=[e]}function vs(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}oe.apply=function(n,e){oe.checkValidOp(e),e=ln(e);for(var t={data:n},o=0;o<e.length;o++){var r=e[o];(r.si!=null||r.sd!=null)&&bs(r);for(var i=null,s=t,l="data",c=0;c<r.p.length;c++){var a=r.p[c];if(i=s,s=s[l],l=a,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Jn[r.t])s[l]=Jn[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)oe.checkList(s),s[l]=r.li;else if(r.li!==void 0)oe.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)oe.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(oe.checkList(s),r.lm!=l){var u=s[l];s.splice(l,1),s.splice(r.lm,0,u)}}else if(r.oi!==void 0)oe.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)oe.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return t.data},oe.shatter=function(n){for(var e=[],t=0;t<n.length;t++)e.push([n[t]]);return e},oe.incrementalApply=function(n,e,t){for(var o=0;o<e.length;o++){var r=[e[o]];n=oe.apply(n,r),t(r,n)}return n};var Uk=oe.pathMatches=function(n,e,t){if(n.length!=e.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==e[o]&&(!t||o!==n.length-1))return!1;return!0};oe.append=function(n,e){if(e=ln(e),n.length===0){n.push(e);return}var t=n[n.length-1];if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(bs(e),bs(t)),Uk(e.p,t.p))if(e.t&&t.t&&e.t===t.t&&Jn[e.t]){if(t.o=Jn[e.t].compose(t.o,e.o),e.si!=null||e.sd!=null){for(var o=e.p,r=0;r<t.o.length-1;r++)e.o=[t.o.pop()],e.p=o.slice(),vs(e),n.push(e);vs(t)}}else t.na!=null&&e.na!=null?n[n.length-1]={p:t.p,na:t.na+e.na}:t.li!==void 0&&e.li===void 0&&e.ld===t.li?t.ld!==void 0?delete t.li:n.pop():t.od!==void 0&&t.oi===void 0&&e.oi!==void 0&&e.od===void 0?t.oi=e.oi:t.oi!==void 0&&e.od!==void 0?e.oi!==void 0?t.oi=e.oi:t.od!==void 0?delete t.oi:n.pop():e.lm!==void 0&&e.p[e.p.length-1]===e.lm||n.push(e);else(e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(vs(e),vs(t)),n.push(e)},oe.compose=function(n,e){oe.checkValidOp(n),oe.checkValidOp(e);for(var t=ln(n),o=0;o<e.length;o++)oe.append(t,e[o]);return t},oe.normalize=function(n){var e=[];n=wc(n)?n:[n];for(var t=0;t<n.length;t++){var o=n[t];o.p==null&&(o.p=[]),oe.append(e,o)}return e},oe.commonLengthForOps=function(n,e){var t=n.p.length,o=e.p.length;if((n.na!=null||n.t)&&t++,(e.na!=null||e.t)&&o++,t===0)return-1;if(o===0)return null;t--,o--;for(var r=0;r<t;r++){var i=n.p[r];if(r>=o||i!==e.p[r])return null}return t},oe.canOpAffectPath=function(n,e){return oe.commonLengthForOps({p:e},n)!=null},oe.transformComponent=function(n,e,t,o){e=ln(e);var r=oe.commonLengthForOps(t,e),i=oe.commonLengthForOps(e,t),s=e.p.length,l=t.p.length;if((e.na!=null||e.t)&&s++,(t.na!=null||t.t)&&l++,i!=null&&l>s&&e.p[i]==t.p[i]){if(e.ld!==void 0){var c=ln(t);c.p=c.p.slice(s),e.ld=oe.apply(ln(e.ld),[c])}else if(e.od!==void 0){var c=ln(t);c.p=c.p.slice(s),e.od=oe.apply(ln(e.od),[c])}}if(r!=null){var a=s==l,c=t;if((e.si!=null||e.sd!=null)&&(t.si!=null||t.sd!=null)&&(bs(e),c=ln(t),bs(c)),c.t&&Jn[c.t]){if(e.t&&e.t===c.t){var u=Jn[e.t].transform(e.o,c.o,o);if(e.si!=null||e.sd!=null)for(var f=e.p,m=0;m<u.length;m++)e.o=[u[m]],e.p=f.slice(),vs(e),oe.append(n,e);else(!wc(u)||u.length>0)&&(e.o=u,oe.append(n,e));return n}}else if(t.na===void 0){if(t.li!==void 0&&t.ld!==void 0){if(t.p[r]===e.p[r])if(a){if(e.ld!==void 0)if(e.li!==void 0&&o==="left")e.ld=ln(t.li);else return n}else return n}else if(t.li!==void 0)e.li!==void 0&&e.ld===void 0&&a&&e.p[r]===t.p[r]?o==="right"&&e.p[r]++:t.p[r]<=e.p[r]&&e.p[r]++,e.lm!==void 0&&a&&t.p[r]<=e.lm&&e.lm++;else if(t.ld!==void 0){if(e.lm!==void 0&&a){if(t.p[r]===e.p[r])return n;var f=t.p[r],p=e.p[r],b=e.lm;(f<b||f===b&&p<b)&&e.lm--}if(t.p[r]<e.p[r])e.p[r]--;else if(t.p[r]===e.p[r]){if(l<s)return n;if(e.ld!==void 0)if(e.li!==void 0)delete e.ld;else return n}}else if(t.lm!==void 0)if(e.lm!==void 0&&s===l){var p=e.p[r],b=e.lm,y=t.p[r],v=t.lm;if(y!==v)if(p===y)if(o==="left")e.p[r]=v,p===b&&(e.lm=v);else return n;else p>y&&e.p[r]--,p>v?e.p[r]++:p===v&&y>v&&(e.p[r]++,p===b&&e.lm++),(b>y||b===y&&b>p)&&e.lm--,b>v?e.lm++:b===v&&(v>y&&b>p||v<y&&b<p?o==="right"&&e.lm++:b>p?e.lm++:b===y&&e.lm--)}else if(e.li!==void 0&&e.ld===void 0&&a){var p=t.p[r],b=t.lm;f=e.p[r],f>p&&e.p[r]--,f>b&&e.p[r]++}else{var p=t.p[r],b=t.lm;f=e.p[r],f===p?e.p[r]=b:(f>p&&e.p[r]--,(f>b||f===b&&p>b)&&e.p[r]++)}else if(t.oi!==void 0&&t.od!==void 0){if(e.p[r]===t.p[r])if(e.oi!==void 0&&a){if(o==="right")return n;e.od=t.oi}else return n}else if(t.oi!==void 0){if(e.oi!==void 0&&e.p[r]===t.p[r])if(o==="left")oe.append(n,{p:e.p,od:t.oi});else return n}else if(t.od!==void 0&&e.p[r]==t.p[r]){if(!a)return n;if(e.oi!==void 0)delete e.od;else return n}}}return oe.append(n,e),n},$2(oe,oe.transformComponent,oe.checkValidOp,oe.append);var Vk=_2.exports;oe.registerSubtype(Vk);var qk=oe,Wk={type:qk};(function(n){n.defaultType=Wk.type,n.map={},n.register=function(e){e.name&&(n.map[e.name]=e),e.uri&&(n.map[e.uri]=e)},n.register(n.defaultType)})(As);var cn={};(function(n){n.doNothing=e;function e(){}n.hasKeys=function(t){for(var o in t)return!0;return!1},n.isInteger=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t},n.isValidVersion=function(t){return t===null?!0:n.isInteger(t)&&t>=0},n.isValidTimestamp=function(t){return n.isValidVersion(t)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var t=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];t=t[r]||(o===arguments.length-1?void 0:{})}return t},n.digOrCreate=function(){for(var t=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];t=t[i]||(t[i]=r===arguments.length-2?o():{})}return t},n.digAndRemove=function(){for(var t=arguments[0],o=[t],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!t.hasOwnProperty(i))break;t=t[i],o.push(t)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(t){return t&&typeof t.transformPresence=="function"},n.callEach=function(t,o){var r=!1;return t.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(t){return!!t},n.nextTick=function(t){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){t.apply(null,o)})},n.clone=function(t){return t===void 0?void 0:JSON.parse(JSON.stringify(t))}})(cn);var j2=Array.isArray,H2=Object.keys,Gk=Object.prototype.hasOwnProperty,Zk=function n(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var o=j2(e),r=j2(t),i,s,l;if(o&&r){if(s=e.length,s!=t.length)return!1;for(i=s;i--!==0;)if(!n(e[i],t[i]))return!1;return!0}if(o!=r)return!1;var c=e instanceof Date,a=t instanceof Date;if(c!=a)return!1;if(c&&a)return e.getTime()==t.getTime();var u=e instanceof RegExp,f=t instanceof RegExp;if(u!=f)return!1;if(u&&f)return e.toString()==t.toString();var m=H2(e);if(s=m.length,s!==H2(t).length)return!1;for(i=s;i--!==0;)if(!Gk.call(t,m[i]))return!1;for(i=s;i--!==0;)if(l=m[i],!n(e[l],t[l]))return!1;return!0}return e!==e&&t!==t},z2=Bo,Qk=N2,Mt=yc,Bc=As,an=cn,Yk=an.clone,Jk=Zk,Bt=Mt.CODES,Kk=ae;function ae(n,e,t){z2.EventEmitter.call(this),this.connection=n,this.collection=e,this.id=t,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}z2.mixin(ae),ae.prototype.destroy=function(n){this._wantsDestroy=!0;var e=this;e.whenNothingPending(function(){e.wantSubscribe?e.unsubscribe(function(t){if(t)return n?n(t):e.emit("error",t);e.connection._destroyDoc(e),n&&n()}):(e.connection._destroyDoc(e),n&&n())})},ae.prototype._setType=function(n){if(typeof n=="string"&&(n=Bc.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var e=new Mt(Bt.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",e)}},ae.prototype._setData=function(n){this.data=n,this._dataStateVersion++},ae.prototype.ingestSnapshot=function(n,e){if(!n)return e&&e();if(typeof n.v!="number"){var t=new Mt(Bt.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return e?e(t):this.emit("error",t)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return e&&this.once("no write pending",e);var t=new Mt(Bt.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return e?e(t):this.emit("error",t)}return n.v>this.version?this.fetch(e):e&&e()}if(this.version>n.v)return e&&e();this.version=n.v;var o=n.type===void 0?Bc.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),e&&e()},ae.prototype.whenNothingPending=function(n){var e=this;an.nextTick(function(){if(e.hasPending()){e.once("nothing pending",n);return}n()})},ae.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},ae.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},ae.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},ae.prototype._emitResponseError=function(n,e){if(n&&n.code===Bt.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,e&&e(),this._emitNothingPending();return}if(e){e(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},ae.prototype._handleFetch=function(n,e){var t=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&t.push(o),t.length&&(o=function(r){an.callEach(t,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(e,o),this._emitNothingPending()},ae.prototype._handleSubscribe=function(n,e){var t=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],t.callback&&o.push(t.callback);var r;if(o.length&&(r=function(i){an.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=t.wantSubscribe,this.subscribed?this.ingestSnapshot(e,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},ae.prototype._handleOp=function(n,e){if(n)return this.inflightOp?(n.code===Bt.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&e.src===this.inflightOp.src&&e.seq===this.inflightOp.seq){this._opAcknowledged(e);return}if(this.version==null||e.v>this.version){this.fetch();return}if(!(e.v<this.version)){if(this.inflightOp){var t=Ec(this.inflightOp,e);if(t)return this._hardRollback(t)}for(var o=0;o<this.pendingOps.length;o++){var t=Ec(this.pendingOps[o],e);if(t)return this._hardRollback(t)}this.version++;try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}}},ae.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))},ae.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(e){return e.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},ae.prototype.fetch=function(n){if(this.connection.canSend){var e=this.connection.sendFetch(this);Xk(this.inflightFetch,e,n);return}this.pendingFetch.push(n)},ae.prototype.subscribe=function(n){var e=!0;this._queueSubscribe(e,n)},ae.prototype.unsubscribe=function(n){var e=!1;this._queueSubscribe(e,n)},ae.prototype._queueSubscribe=function(n,e){var t=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=t&&t.wantSubscribe===n;if(o){t.callback=ew([t.callback,e]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:e}),this._flushSubscribe()},ae.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;an.nextTick(function(){n._handleSubscribe()})}}};function Xk(n,e,t){if(e){var o=n.pop();n.push(function(r){o&&o(r),t&&t(r)})}else n.push(t)}function ew(n){return n=n.filter(an.truthy),n.length?function(e){an.callEach(n,e)}:null}ae.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function tw(n){delete n.op,delete n.create,delete n.del}function Ec(n,e){if(n.del)return tw(e);if(e.del)return new Mt(Bt.ERR_DOC_WAS_DELETED,"Document was deleted");if(e.create)return new Mt(Bt.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in e){if(n.create)return new Mt(Bt.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var t=n.type.transformX(n.op,e.op);n.op=t[0],e.op=t[1]}else{var o=n.type.transform(n.op,e.op,"left"),r=n.type.transform(e.op,n.op,"right");n.op=o,e.op=r}}}ae.prototype._otApply=function(n,e){if("op"in n){if(!this.type)throw new Mt(Bt.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,e),!e&&this.type===Bc.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var t=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,e,n.src);for(var s=t;s<this.applyStack.length;s++){var l=Ec(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,e,n.src)}this.emit("op batch",n.op,e),this._popApplyStack(t);return}this.emit("before op",n.op,e,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,e,n.src),this.emit("op batch",n.op,e);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",e);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,e);return}},ae.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var e=this.inflightOp;if(!e){var t=new Mt(Bt.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",t)}if(e.sentAt=Date.now(),e.retries=e.retries==null?0:e.retries+1,e.seq==null){if(this.connection.seq>=an.MAX_SAFE_INTEGER)return this.emit("error",new Mt(Bt.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));e.seq=this.connection.seq++}this.connection.sendOp(this,e),e.src==null&&(e.src=n)}},ae.prototype._submit=function(n,e,t){if(e||(e=!0),"op"in n){if(!this.type){var o=new Mt(Bt.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return t?t(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,e,t),this._otApply(n,e)}catch(i){return this._hardRollback(i)}var r=this;an.nextTick(function(){r.flush()})},ae.prototype._pushOp=function(n,e,t){if(n.source=e,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(t);return}}n.type=this.type,n.callbacks=[t],this.pendingOps.push(n)},ae.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var e=this.applyStack[0];if(this.applyStack=null,!!e){var t=this.pendingOps.indexOf(e);if(t!==-1)for(var o=this.pendingOps.splice(t),t=0;t<o.length;t++){var e=o[t],r=this._tryCompose(e);r?r.callbacks=r.callbacks.concat(e.callbacks):this.pendingOps.push(e)}}},ae.prototype._tryCompose=function(n){if(!this.preventCompose){var e=this.pendingOps[this.pendingOps.length-1];if(!(!e||e.sentAt)&&!(this.submitSource&&!Jk(n.source,e.source))){if(e.create&&"op"in n)return e.create.data=this.type.apply(e.create.data,n.op),e;if("op"in e&&"op"in n&&this.type.compose)return e.op=this.type.compose(e.op,n.op),e}}},ae.prototype.submitOp=function(n,e,t){typeof e=="function"&&(t=e,e=null);var o={op:n},r=e&&e.source;this._submit(o,r,t)},ae.prototype.create=function(n,e,t,o){if(typeof e=="function"?(o=e,t=null,e=null):typeof t=="function"&&(o=t,t=null),e||(e=Bc.defaultType.uri),this.type){var r=new Mt(Bt.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:e,data:n}},s=t&&t.source;this._submit(i,s,o)},ae.prototype.del=function(n,e){if(typeof n=="function"&&(e=n,n=null),!this.type){var t=new Mt(Bt.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return e?e(t):this.emit("error",t)}var o={del:!0},r=n&&n.source;this._submit(o,r,e)},ae.prototype.pause=function(){this.paused=!0},ae.prototype.resume=function(){this.paused=!1,this.flush()},ae.prototype.toSnapshot=function(){return{v:this.version,data:Yk(this.data),type:this.type.uri}},ae.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return Qk.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},ae.prototype._rollback=function(n){var e=this.inflightOp;if("op"in e&&e.type.invert){try{e.op=e.type.invert(e.op)}catch{return this._hardRollback(n)}for(var t=0;t<this.pendingOps.length;t++){var o=Ec(this.pendingOps[t],e);if(o)return this._hardRollback(o)}try{this._otApply(e,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},ae.prototype._hardRollback=function(n){var e=[];this.inflightOp&&e.push(this.inflightOp),e=e.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var t=this;this.fetch(function(){for(var o=!!e.length,r=0;r<e.length;r++)o=an.callEach(e[r].callbacks,n)&&o;if(n&&!o)return t.emit("error",n)})},ae.prototype._clearInflightOp=function(n){var e=this.inflightOp;this.inflightOp=null;var t=an.callEach(e.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!t)return this.emit("error",n)};var mr={};mr.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 U2=Bo,V2=mr.ACTIONS,nw=cn,ow=Et;function Et(n,e,t,o,r,i,s){U2.EventEmitter.call(this),this.action=n,this.connection=e,this.id=t,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}U2.mixin(Et),Et.prototype.hasPending=function(){return!this.ready},Et.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var e=[],t=0;t<this.results.length;t++){var o=this.results[t];e.push([o.id,o.version])}n.r=e}this.connection.send(n),this.sent=!0}},Et.prototype.destroy=function(n){this.connection.canSend&&this.action===V2.querySubscribe&&this.connection.send({a:V2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&nw.nextTick(n)},Et.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Et.prototype._handleFetch=function(n,e,t){this.connection._destroyQuery(this),this._handleResponse(n,e,t)},Et.prototype._handleSubscribe=function(n,e,t){this._handleResponse(n,e,t)},Et.prototype._handleResponse=function(n,e,t){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!e)return this._finishResponse(null,o);var r=this,i=1,s=function(u){if(u)return r._finishResponse(u,o);--i||r._finishResponse(null,o)};if(Array.isArray(e))i+=e.length,this.results=this._ingestSnapshots(e,s),this.extra=t;else for(var l in e){i++;var c=e[l],a=this.connection.get(c.c||this.collection,l);a.ingestSnapshot(c,s)}s()},Et.prototype._ingestSnapshots=function(n,e){for(var t=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,e),t.push(i)}return t},Et.prototype._finishResponse=function(n,e){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),e?e(n):this.emit("error",n);e&&e(null,this.results,this.extra)},Et.prototype._handleError=function(n){this.emit("error",n)},Et.prototype._handleDiff=function(n){for(var e=0;e<n.length;e++){var t=n[e];t.type==="insert"&&(t.values=this._ingestSnapshots(t.values))}for(var e=0;e<n.length;e++){var t=n[e];switch(t.type){case"insert":var o=t.values;Array.prototype.splice.apply(this.results,[t.index,0].concat(o)),this.emit("insert",o,t.index);break;case"remove":var i=t.howMany||1,r=this.results.splice(t.index,i);this.emit("remove",r,t.index);break;case"move":var i=t.howMany||1,s=this.results.splice(t.from,i);Array.prototype.splice.apply(this.results,[t.to,0].concat(s)),this.emit("move",s,t.from,t.to);break}}this.emit("changed",this.results)},Et.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var q2=Bo,rw=mr.ACTIONS,iw=cn,W2=In;function In(n,e){if(q2.EventEmitter.call(this),!e||typeof e!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=e,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}q2.mixin(In),In.prototype.submit=function(n,e){this.value=n,this.send(e)},In.prototype.send=function(n){var e=this._message();this._pendingMessages.push(e),this._callbacksByPresenceVersion[e.pv]=n,this._sendPending()},In.prototype.destroy=function(n){var e=this;this.submit(null,function(t){if(t)return e._callbackOrEmit(t,n);delete e.presence.localPresences[e.presenceId],n&&n()})},In.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(e){n.connection.send(e)}),this._pendingMessages=[]}},In.prototype._ack=function(n,e){var t=this._getCallback(e);this._callbackOrEmit(n,t)},In.prototype._message=function(){return{a:rw.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},In.prototype._getCallback=function(n){var e=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],e},In.prototype._callbackOrEmit=function(n,e){if(e)return iw.nextTick(e,n);n&&this.emit("error",n)};var sw=cn,G2=ch;function ch(n,e){this.presence=n,this.presenceId=e,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}ch.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},ch.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&sw.nextTick(n)};var ah={exports:{}};(function(n,e){(function(t,o){o(e)})(Cs,function(t){function o(C,k){k=k|0;for(var B=Math.max(C.length-k,0),T=Array(B),S=0;S<B;S++)T[S]=C[k+S];return T}var r=function(C){var k=o(arguments,1);return function(){var B=o(arguments);return C.apply(null,k.concat(B))}},i=function(C){return function(){var k=o(arguments),B=k.pop();C.call(this,k,B)}};function s(C){var k=typeof C;return C!=null&&(k=="object"||k=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function a(C){setTimeout(C,0)}function u(C){return function(k){var B=o(arguments,1);C(function(){k.apply(null,B)})}}var f;l?f=setImmediate:c?f=process.nextTick:f=a;var m=u(f);function p(C){return i(function(k,B){var T;try{T=C.apply(this,k)}catch(S){return B(S)}s(T)&&typeof T.then=="function"?T.then(function(S){b(B,null,S)},function(S){b(B,S.message?S:new Error(S))}):B(null,T)})}function b(C,k,B){try{C(k,B)}catch(T){m(y,T)}}function y(C){throw C}var v=typeof Symbol=="function";function x(C){return v&&C[Symbol.toStringTag]==="AsyncFunction"}function E(C){return x(C)?p(C):C}function M(C){return function(k){var B=o(arguments,1),T=i(function(S,D){var P=this;return C(k,function(F,W){E(F).apply(P,S.concat(W))},D)});return B.length?T.apply(this,B):T}}var L=typeof Cs=="object"&&Cs&&Cs.Object===Object&&Cs,O=typeof self=="object"&&self&&self.Object===Object&&self,V=L||O||Function("return this")(),ee=V.Symbol,se=Object.prototype,pe=se.hasOwnProperty,de=se.toString,we=ee?ee.toStringTag:void 0;function ft(C){var k=pe.call(C,we),B=C[we];try{C[we]=void 0;var T=!0}catch{}var S=de.call(C);return T&&(k?C[we]=B:delete C[we]),S}var lo=Object.prototype,st=lo.toString;function qt(C){return st.call(C)}var jo="[object Null]",Dr="[object Undefined]",Sr=ee?ee.toStringTag:void 0;function Ho(C){return C==null?C===void 0?Dr:jo:Sr&&Sr in Object(C)?ft(C):qt(C)}var $a="[object AsyncFunction]",wH="[object Function]",BH="[object GeneratorFunction]",EH="[object Proxy]";function IH(C){if(!s(C))return!1;var k=Ho(C);return k==wH||k==BH||k==$a||k==EH}var xH=9007199254740991;function e7(C){return typeof C=="number"&&C>-1&&C%1==0&&C<=xH}function ml(C){return C!=null&&e7(C.length)&&!IH(C)}var Jf={};function he(){}function zo(C){return function(){if(C!==null){var k=C;C=null,k.apply(this,arguments)}}}var Kf=typeof Symbol=="function"&&Symbol.iterator,TH=function(C){return Kf&&C[Kf]&&C[Kf]()};function DH(C,k){for(var B=-1,T=Array(C);++B<C;)T[B]=k(B);return T}function _a(C){return C!=null&&typeof C=="object"}var SH="[object Arguments]";function t7(C){return _a(C)&&Ho(C)==SH}var n7=Object.prototype,LH=n7.hasOwnProperty,MH=n7.propertyIsEnumerable,RH=t7(function(){return arguments}())?t7:function(C){return _a(C)&&LH.call(C,"callee")&&!MH.call(C,"callee")},An=Array.isArray;function OH(){return!1}var o7=typeof t=="object"&&t&&!t.nodeType&&t,r7=o7&&!0&&n&&!n.nodeType&&n,PH=r7&&r7.exports===o7,i7=PH?V.Buffer:void 0,FH=i7?i7.isBuffer:void 0,NH=FH||OH,$H=9007199254740991,_H=/^(?:0|[1-9]\d*)$/;function jH(C,k){var B=typeof C;return k=k==null?$H:k,!!k&&(B=="number"||B!="symbol"&&_H.test(C))&&C>-1&&C%1==0&&C<k}var HH="[object Arguments]",zH="[object Array]",UH="[object Boolean]",VH="[object Date]",qH="[object Error]",WH="[object Function]",GH="[object Map]",ZH="[object Number]",QH="[object Object]",YH="[object RegExp]",JH="[object Set]",KH="[object String]",XH="[object WeakMap]",ez="[object ArrayBuffer]",tz="[object DataView]",nz="[object Float32Array]",oz="[object Float64Array]",rz="[object Int8Array]",iz="[object Int16Array]",sz="[object Int32Array]",lz="[object Uint8Array]",cz="[object Uint8ClampedArray]",az="[object Uint16Array]",uz="[object Uint32Array]",Be={};Be[nz]=Be[oz]=Be[rz]=Be[iz]=Be[sz]=Be[lz]=Be[cz]=Be[az]=Be[uz]=!0,Be[HH]=Be[zH]=Be[ez]=Be[UH]=Be[tz]=Be[VH]=Be[qH]=Be[WH]=Be[GH]=Be[ZH]=Be[QH]=Be[YH]=Be[JH]=Be[KH]=Be[XH]=!1;function dz(C){return _a(C)&&e7(C.length)&&!!Be[Ho(C)]}function hz(C){return function(k){return C(k)}}var s7=typeof t=="object"&&t&&!t.nodeType&&t,gl=s7&&!0&&n&&!n.nodeType&&n,fz=gl&&gl.exports===s7,Xf=fz&&L.process,l7=function(){try{var C=gl&&gl.require&&gl.require("util").types;return C||Xf&&Xf.binding&&Xf.binding("util")}catch{}}(),c7=l7&&l7.isTypedArray,mz=c7?hz(c7):dz,gz=Object.prototype,pz=gz.hasOwnProperty;function Cz(C,k){var B=An(C),T=!B&&RH(C),S=!B&&!T&&NH(C),D=!B&&!T&&!S&&mz(C),P=B||T||S||D,F=P?DH(C.length,String):[],W=F.length;for(var J in C)(k||pz.call(C,J))&&!(P&&(J=="length"||S&&(J=="offset"||J=="parent")||D&&(J=="buffer"||J=="byteLength"||J=="byteOffset")||jH(J,W)))&&F.push(J);return F}var Az=Object.prototype;function bz(C){var k=C&&C.constructor,B=typeof k=="function"&&k.prototype||Az;return C===B}function vz(C,k){return function(B){return C(k(B))}}var yz=vz(Object.keys,Object),kz=Object.prototype,wz=kz.hasOwnProperty;function Bz(C){if(!bz(C))return yz(C);var k=[];for(var B in Object(C))wz.call(C,B)&&B!="constructor"&&k.push(B);return k}function em(C){return ml(C)?Cz(C):Bz(C)}function Ez(C){var k=-1,B=C.length;return function(){return++k<B?{value:C[k],key:k}:null}}function Iz(C){var k=-1;return function(){var T=C.next();return T.done?null:(k++,{value:T.value,key:k})}}function xz(C){var k=em(C),B=-1,T=k.length;return function S(){var D=k[++B];return D==="__proto__"?S():B<T?{value:C[D],key:D}:null}}function Tz(C){if(ml(C))return Ez(C);var k=TH(C);return k?Iz(k):xz(C)}function Fn(C){return function(){if(C===null)throw new Error("Callback was already called.");var k=C;C=null,k.apply(this,arguments)}}function ja(C){return function(k,B,T){if(T=zo(T||he),C<=0||!k)return T(null);var S=Tz(k),D=!1,P=0,F=!1;function W(Z,te){if(P-=1,Z)D=!0,T(Z);else{if(te===Jf||D&&P<=0)return D=!0,T(null);F||J()}}function J(){for(F=!0;P<C&&!D;){var Z=S();if(Z===null){D=!0,P<=0&&T(null);return}P+=1,B(Z.value,Z.key,Fn(W))}F=!1}J()}}function Lr(C,k,B,T){ja(k)(C,E(B),T)}function lt(C,k){return function(B,T,S){return C(B,k,T,S)}}function Dz(C,k,B){B=zo(B||he);var T=0,S=0,D=C.length;D===0&&B(null);function P(F,W){F?B(F):(++S===D||W===Jf)&&B(null)}for(;T<D;T++)k(C[T],T,Fn(P))}var Sz=lt(Lr,1/0),Uo=function(C,k,B){var T=ml(C)?Dz:Sz;T(C,E(k),B)};function Li(C){return function(k,B,T){return C(Uo,k,E(B),T)}}function a7(C,k,B,T){T=T||he,k=k||[];var S=[],D=0,P=E(B);C(k,function(F,W,J){var Z=D++;P(F,function(te,Ee){S[Z]=Ee,J(te)})},function(F){T(F,S)})}var Ha=Li(a7),u7=M(Ha);function Mi(C){return function(k,B,T,S){return C(ja(B),k,E(T),S)}}var Ri=Mi(a7),tm=lt(Ri,1),d7=M(tm);function za(C,k){for(var B=-1,T=C==null?0:C.length;++B<T&&k(C[B],B,C)!==!1;);return C}function Lz(C){return function(k,B,T){for(var S=-1,D=Object(k),P=T(k),F=P.length;F--;){var W=P[C?F:++S];if(B(D[W],W,D)===!1)break}return k}}var Mz=Lz();function pl(C,k){return C&&Mz(C,k,em)}function Rz(C,k,B,T){for(var S=C.length,D=B+(T?1:-1);T?D--:++D<S;)if(k(C[D],D,C))return D;return-1}function Oz(C){return C!==C}function Pz(C,k,B){for(var T=B-1,S=C.length;++T<S;)if(C[T]===k)return T;return-1}function Ua(C,k,B){return k===k?Pz(C,k,B):Rz(C,Oz,B)}var nm=function(C,k,B){typeof k=="function"&&(B=k,k=null),B=zo(B||he);var T=em(C),S=T.length;if(!S)return B(null);k||(k=S);var D={},P=0,F=!1,W=Object.create(null),J=[],Z=[],te={};pl(C,function(De,Le){if(!An(De)){Ee(Le,[De]),Z.push(Le);return}var tt=De.slice(0,De.length-1),co=tt.length;if(co===0){Ee(Le,De),Z.push(Le);return}te[Le]=co,za(tt,function(Ni){if(!C[Ni])throw new Error("async.auto task `"+Le+"` has a non-existent dependency `"+Ni+"` in "+tt.join(", "));Nn(Ni,function(){co--,co===0&&Ee(Le,De)})})}),xU(),mt();function Ee(De,Le){J.push(function(){$n(De,Le)})}function mt(){if(J.length===0&&P===0)return B(null,D);for(;J.length&&P<k;){var De=J.shift();De()}}function Nn(De,Le){var tt=W[De];tt||(tt=W[De]=[]),tt.push(Le)}function Wt(De){var Le=W[De]||[];za(Le,function(tt){tt()}),mt()}function $n(De,Le){if(!F){var tt=Fn(function(Ni,mm){if(P--,arguments.length>2&&(mm=o(arguments,1)),Ni){var gm={};pl(D,function(DU,SU){gm[SU]=DU}),gm[De]=mm,F=!0,W=Object.create(null),B(Ni,gm)}else D[De]=mm,Wt(De)});P++;var co=E(Le[Le.length-1]);Le.length>1?co(D,tt):co(tt)}}function xU(){for(var De,Le=0;Z.length;)De=Z.pop(),Le++,za(TU(De),function(tt){--te[tt]===0&&Z.push(tt)});if(Le!==S)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function TU(De){var Le=[];return pl(C,function(tt,co){An(tt)&&Ua(tt,De,0)>=0&&Le.push(co)}),Le}};function Oi(C,k){for(var B=-1,T=C==null?0:C.length,S=Array(T);++B<T;)S[B]=k(C[B],B,C);return S}var Fz="[object Symbol]";function Nz(C){return typeof C=="symbol"||_a(C)&&Ho(C)==Fz}var $z=1/0,h7=ee?ee.prototype:void 0,f7=h7?h7.toString:void 0;function om(C){if(typeof C=="string")return C;if(An(C))return Oi(C,om)+"";if(Nz(C))return f7?f7.call(C):"";var k=C+"";return k=="0"&&1/C==-$z?"-0":k}function _z(C,k,B){var T=-1,S=C.length;k<0&&(k=-k>S?0:S+k),B=B>S?S:B,B<0&&(B+=S),S=k>B?0:B-k>>>0,k>>>=0;for(var D=Array(S);++T<S;)D[T]=C[T+k];return D}function jz(C,k,B){var T=C.length;return B=B===void 0?T:B,!k&&B>=T?C:_z(C,k,B)}function Hz(C,k){for(var B=C.length;B--&&Ua(k,C[B],0)>-1;);return B}function zz(C,k){for(var B=-1,T=C.length;++B<T&&Ua(k,C[B],0)>-1;);return B}function Uz(C){return C.split("")}var Vz="\\ud800-\\udfff",qz="\\u0300-\\u036f",Wz="\\ufe20-\\ufe2f",Gz="\\u20d0-\\u20ff",Zz=qz+Wz+Gz,Qz="\\ufe0e\\ufe0f",Yz="\\u200d",Jz=RegExp("["+Yz+Vz+Zz+Qz+"]");function Kz(C){return Jz.test(C)}var m7="\\ud800-\\udfff",Xz="\\u0300-\\u036f",eU="\\ufe20-\\ufe2f",tU="\\u20d0-\\u20ff",nU=Xz+eU+tU,oU="\\ufe0e\\ufe0f",rU="["+m7+"]",rm="["+nU+"]",im="\\ud83c[\\udffb-\\udfff]",iU="(?:"+rm+"|"+im+")",g7="[^"+m7+"]",p7="(?:\\ud83c[\\udde6-\\uddff]){2}",C7="[\\ud800-\\udbff][\\udc00-\\udfff]",sU="\\u200d",A7=iU+"?",b7="["+oU+"]?",lU="(?:"+sU+"(?:"+[g7,p7,C7].join("|")+")"+b7+A7+")*",cU=b7+A7+lU,aU="(?:"+[g7+rm+"?",rm,p7,C7,rU].join("|")+")",uU=RegExp(im+"(?="+im+")|"+aU+cU,"g");function dU(C){return C.match(uU)||[]}function v7(C){return Kz(C)?dU(C):Uz(C)}function hU(C){return C==null?"":om(C)}var fU=/^\s+|\s+$/g;function mU(C,k,B){if(C=hU(C),C&&(B||k===void 0))return C.replace(fU,"");if(!C||!(k=om(k)))return C;var T=v7(C),S=v7(k),D=zz(T,S),P=Hz(T,S)+1;return jz(T,D,P).join("")}var gU=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,pU=/,/,CU=/(=.+)?(\s*)$/,AU=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function bU(C){return C=C.toString().replace(AU,""),C=C.match(gU)[2].replace(" ",""),C=C?C.split(pU):[],C=C.map(function(k){return mU(k.replace(CU,""))}),C}function y7(C,k){var B={};pl(C,function(T,S){var D,P=x(T),F=!P&&T.length===1||P&&T.length===0;if(An(T))D=T.slice(0,-1),T=T[T.length-1],B[S]=D.concat(D.length>0?W:T);else if(F)B[S]=T;else{if(D=bU(T),T.length===0&&!P&&D.length===0)throw new Error("autoInject task functions require explicit parameters.");P||D.pop(),B[S]=D.concat(W)}function W(J,Z){var te=Oi(D,function(Ee){return J[Ee]});te.push(Z),E(T).apply(null,te)}}),nm(B,k)}function bn(){this.head=this.tail=null,this.length=0}function k7(C,k){C.length=1,C.head=C.tail=k}bn.prototype.removeLink=function(C){return C.prev?C.prev.next=C.next:this.head=C.next,C.next?C.next.prev=C.prev:this.tail=C.prev,C.prev=C.next=null,this.length-=1,C},bn.prototype.empty=function(){for(;this.head;)this.shift();return this},bn.prototype.insertAfter=function(C,k){k.prev=C,k.next=C.next,C.next?C.next.prev=k:this.tail=k,C.next=k,this.length+=1},bn.prototype.insertBefore=function(C,k){k.prev=C.prev,k.next=C,C.prev?C.prev.next=k:this.head=k,C.prev=k,this.length+=1},bn.prototype.unshift=function(C){this.head?this.insertBefore(this.head,C):k7(this,C)},bn.prototype.push=function(C){this.tail?this.insertAfter(this.tail,C):k7(this,C)},bn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},bn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},bn.prototype.toArray=function(){for(var C=Array(this.length),k=this.head,B=0;B<this.length;B++)C[B]=k.data,k=k.next;return C},bn.prototype.remove=function(C){for(var k=this.head;k;){var B=k.next;C(k)&&this.removeLink(k),k=B}return this};function w7(C,k,B){if(k==null)k=1;else if(k===0)throw new Error("Concurrency must not be zero");var T=E(C),S=0,D=[],P=!1;function F(te,Ee,mt){if(mt!=null&&typeof mt!="function")throw new Error("task callback must be a function");if(Z.started=!0,An(te)||(te=[te]),te.length===0&&Z.idle())return m(function(){Z.drain()});for(var Nn=0,Wt=te.length;Nn<Wt;Nn++){var $n={data:te[Nn],callback:mt||he};Ee?Z._tasks.unshift($n):Z._tasks.push($n)}P||(P=!0,m(function(){P=!1,Z.process()}))}function W(te){return function(Ee){S-=1;for(var mt=0,Nn=te.length;mt<Nn;mt++){var Wt=te[mt],$n=Ua(D,Wt,0);$n===0?D.shift():$n>0&&D.splice($n,1),Wt.callback.apply(Wt,arguments),Ee!=null&&Z.error(Ee,Wt.data)}S<=Z.concurrency-Z.buffer&&Z.unsaturated(),Z.idle()&&Z.drain(),Z.process()}}var J=!1,Z={_tasks:new bn,concurrency:k,payload:B,saturated:he,unsaturated:he,buffer:k/4,empty:he,drain:he,error:he,started:!1,paused:!1,push:function(te,Ee){F(te,!1,Ee)},kill:function(){Z.drain=he,Z._tasks.empty()},unshift:function(te,Ee){F(te,!0,Ee)},remove:function(te){Z._tasks.remove(te)},process:function(){if(!J){for(J=!0;!Z.paused&&S<Z.concurrency&&Z._tasks.length;){var te=[],Ee=[],mt=Z._tasks.length;Z.payload&&(mt=Math.min(mt,Z.payload));for(var Nn=0;Nn<mt;Nn++){var Wt=Z._tasks.shift();te.push(Wt),D.push(Wt),Ee.push(Wt.data)}S+=1,Z._tasks.length===0&&Z.empty(),S===Z.concurrency&&Z.saturated();var $n=Fn(W(te));T(Ee,$n)}J=!1}},length:function(){return Z._tasks.length},running:function(){return S},workersList:function(){return D},idle:function(){return Z._tasks.length+S===0},pause:function(){Z.paused=!0},resume:function(){Z.paused!==!1&&(Z.paused=!1,m(Z.process))}};return Z}function B7(C,k){return w7(C,1,k)}var Pi=lt(Lr,1);function Vo(C,k,B,T){T=zo(T||he);var S=E(B);Pi(C,function(D,P,F){S(k,D,function(W,J){k=J,F(W)})},function(D){T(D,k)})}function sm(){var C=Oi(arguments,E);return function(){var k=o(arguments),B=this,T=k[k.length-1];typeof T=="function"?k.pop():T=he,Vo(C,k,function(S,D,P){D.apply(B,S.concat(function(F){var W=o(arguments,1);P(F,W)}))},function(S,D){T.apply(B,[S].concat(D))})}}var E7=function(){return sm.apply(null,o(arguments).reverse())},vU=Array.prototype.concat,Va=function(C,k,B,T){T=T||he;var S=E(B);Ri(C,k,function(D,P){S(D,function(F){return F?P(F):P(null,o(arguments,1))})},function(D,P){for(var F=[],W=0;W<P.length;W++)P[W]&&(F=vU.apply(F,P[W]));return T(D,F)})},I7=lt(Va,1/0),x7=lt(Va,1),T7=function(){var C=o(arguments),k=[null].concat(C);return function(){var B=arguments[arguments.length-1];return B.apply(this,k)}};function Cl(C){return C}function Fi(C,k){return function(B,T,S,D){D=D||he;var P=!1,F;B(T,function(W,J,Z){S(W,function(te,Ee){te?Z(te):C(Ee)&&!F?(P=!0,F=k(!0,W),Z(null,Jf)):Z()})},function(W){W?D(W):D(null,P?F:k(!1))})}}function D7(C,k){return k}var qa=Li(Fi(Cl,D7)),Al=Mi(Fi(Cl,D7)),Wa=lt(Al,1);function S7(C){return function(k){var B=o(arguments,1);B.push(function(T){var S=o(arguments,1);typeof console=="object"&&(T?console.error&&console.error(T):console[C]&&za(S,function(D){console[C](D)}))}),E(k).apply(null,B)}}var L7=S7("dir");function M7(C,k,B){B=Fn(B||he);var T=E(C),S=E(k);function D(F){if(F)return B(F);var W=o(arguments,1);W.push(P),S.apply(this,W)}function P(F,W){if(F)return B(F);if(!W)return B(null);T(D)}P(null,!0)}function lm(C,k,B){B=Fn(B||he);var T=E(C),S=function(D){if(D)return B(D);var P=o(arguments,1);if(k.apply(this,P))return T(S);B.apply(null,[null].concat(P))};T(S)}function R7(C,k,B){lm(C,function(){return!k.apply(this,arguments)},B)}function O7(C,k,B){B=Fn(B||he);var T=E(k),S=E(C);function D(F){if(F)return B(F);S(P)}function P(F,W){if(F)return B(F);if(!W)return B(null);T(D)}S(P)}function P7(C){return function(k,B,T){return C(k,T)}}function Ga(C,k,B){Uo(C,P7(E(k)),B)}function bl(C,k,B,T){ja(k)(C,P7(E(B)),T)}var vl=lt(bl,1);function cm(C){return x(C)?C:i(function(k,B){var T=!0;k.push(function(){var S=arguments;T?m(function(){B.apply(null,S)}):B.apply(null,S)}),C.apply(this,k),T=!1})}function Za(C){return!C}var Qa=Li(Fi(Za,Za)),yl=Mi(Fi(Za,Za)),Ya=lt(yl,1);function F7(C){return function(k){return k==null?void 0:k[C]}}function yU(C,k,B,T){var S=new Array(k.length);C(k,function(D,P,F){B(D,function(W,J){S[P]=!!J,F(W)})},function(D){if(D)return T(D);for(var P=[],F=0;F<k.length;F++)S[F]&&P.push(k[F]);T(null,P)})}function kU(C,k,B,T){var S=[];C(k,function(D,P,F){B(D,function(W,J){W?F(W):(J&&S.push({index:P,value:D}),F())})},function(D){D?T(D):T(null,Oi(S.sort(function(P,F){return P.index-F.index}),F7("value")))})}function am(C,k,B,T){var S=ml(k)?yU:kU;S(C,k,E(B),T||he)}var Ja=Li(am),kl=Mi(am),Ka=lt(kl,1);function N7(C,k){var B=Fn(k||he),T=E(cm(C));function S(D){if(D)return B(D);T(S)}S()}var Xa=function(C,k,B,T){T=T||he;var S=E(B);Ri(C,k,function(D,P){S(D,function(F,W){return F?P(F):P(null,{key:W,val:D})})},function(D,P){for(var F={},W=Object.prototype.hasOwnProperty,J=0;J<P.length;J++)if(P[J]){var Z=P[J].key,te=P[J].val;W.call(F,Z)?F[Z].push(te):F[Z]=[te]}return T(D,F)})},$7=lt(Xa,1/0),_7=lt(Xa,1),j7=S7("log");function eu(C,k,B,T){T=zo(T||he);var S={},D=E(B);Lr(C,k,function(P,F,W){D(P,F,function(J,Z){if(J)return W(J);S[F]=Z,W()})},function(P){T(P,S)})}var H7=lt(eu,1/0),z7=lt(eu,1);function U7(C,k){return k in C}function V7(C,k){var B=Object.create(null),T=Object.create(null);k=k||Cl;var S=E(C),D=i(function(F,W){var J=k.apply(null,F);U7(B,J)?m(function(){W.apply(null,B[J])}):U7(T,J)?T[J].push(W):(T[J]=[W],S.apply(null,F.concat(function(){var Z=o(arguments);B[J]=Z;var te=T[J];delete T[J];for(var Ee=0,mt=te.length;Ee<mt;Ee++)te[Ee].apply(null,Z)})))});return D.memo=B,D.unmemoized=C,D}var tu;c?tu=process.nextTick:l?tu=setImmediate:tu=a;var q7=u(tu);function um(C,k,B){B=B||he;var T=ml(k)?[]:{};C(k,function(S,D,P){E(S)(function(F,W){arguments.length>2&&(W=o(arguments,1)),T[D]=W,P(F)})},function(S){B(S,T)})}function W7(C,k){um(Uo,C,k)}function G7(C,k,B){um(ja(k),C,B)}var dm=function(C,k){var B=E(C);return w7(function(T,S){B(T[0],S)},k,1)},Z7=function(C,k){var B=dm(C,k);return B.push=function(T,S,D){if(D==null&&(D=he),typeof D!="function")throw new Error("task callback must be a function");if(B.started=!0,An(T)||(T=[T]),T.length===0)return m(function(){B.drain()});S=S||0;for(var P=B._tasks.head;P&&S>=P.priority;)P=P.next;for(var F=0,W=T.length;F<W;F++){var J={data:T[F],priority:S,callback:D};P?B._tasks.insertBefore(P,J):B._tasks.push(J)}m(B.process)},delete B.unshift,B};function Q7(C,k){if(k=zo(k||he),!An(C))return k(new TypeError("First argument to race must be an array of functions"));if(!C.length)return k();for(var B=0,T=C.length;B<T;B++)E(C[B])(k)}function nu(C,k,B,T){var S=o(C).reverse();Vo(S,k,B,T)}function ou(C){var k=E(C);return i(function(T,S){return T.push(function(P,F){if(P)S(null,{error:P});else{var W;arguments.length<=2?W=F:W=o(arguments,1),S(null,{value:W})}}),k.apply(this,T)})}function Y7(C){var k;return An(C)?k=Oi(C,ou):(k={},pl(C,function(B,T){k[T]=ou.call(this,B)})),k}function J7(C,k,B,T){am(C,k,function(S,D){B(S,function(P,F){D(P,!F)})},T)}var K7=Li(J7),hm=Mi(J7),X7=lt(hm,1);function e8(C){return function(){return C}}function ru(C,k,B){var T=5,S=0,D={times:T,intervalFunc:e8(S)};function P(Z,te){if(typeof te=="object")Z.times=+te.times||T,Z.intervalFunc=typeof te.interval=="function"?te.interval:e8(+te.interval||S),Z.errorFilter=te.errorFilter;else if(typeof te=="number"||typeof te=="string")Z.times=+te||T;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof C=="function"?(B=k||he,k=C):(P(D,C),B=B||he),typeof k!="function")throw new Error("Invalid arguments for async.retry");var F=E(k),W=1;function J(){F(function(Z){Z&&W++<D.times&&(typeof D.errorFilter!="function"||D.errorFilter(Z))?setTimeout(J,D.intervalFunc(W)):B.apply(null,arguments)})}J()}var t8=function(C,k){k||(k=C,C=null);var B=E(k);return i(function(T,S){function D(P){B.apply(null,T.concat(P))}C?ru(C,D,S):ru(D,S)})};function n8(C,k){um(Pi,C,k)}var iu=Li(Fi(Boolean,Cl)),wl=Mi(Fi(Boolean,Cl)),su=lt(wl,1);function o8(C,k,B){var T=E(k);Ha(C,function(D,P){T(D,function(F,W){if(F)return P(F);P(null,{value:D,criteria:W})})},function(D,P){if(D)return B(D);B(null,Oi(P.sort(S),F7("value")))});function S(D,P){var F=D.criteria,W=P.criteria;return F<W?-1:F>W?1:0}}function r8(C,k,B){var T=E(C);return i(function(S,D){var P=!1,F;function W(){var J=C.name||"anonymous",Z=new Error('Callback function "'+J+'" timed out.');Z.code="ETIMEDOUT",B&&(Z.info=B),P=!0,D(Z)}S.push(function(){P||(D.apply(null,arguments),clearTimeout(F))}),F=setTimeout(W,k),T.apply(null,S)})}var wU=Math.ceil,BU=Math.max;function EU(C,k,B,T){for(var S=-1,D=BU(wU((k-C)/(B||1)),0),P=Array(D);D--;)P[T?D:++S]=C,C+=B;return P}function lu(C,k,B,T){var S=E(B);Ri(EU(0,C,1),k,S,T)}var i8=lt(lu,1/0),s8=lt(lu,1);function l8(C,k,B,T){arguments.length<=3&&(T=B,B=k,k=An(C)?[]:{}),T=zo(T||he);var S=E(B);Uo(C,function(D,P,F){S(k,D,P,F)},function(D){T(D,k)})}function c8(C,k){var B=null,T;k=k||he,vl(C,function(S,D){E(S)(function(P,F){arguments.length>2?T=o(arguments,1):T=F,B=P,D(!P)})},function(){k(B,T)})}function a8(C){return function(){return(C.unmemoized||C).apply(null,arguments)}}function fm(C,k,B){B=Fn(B||he);var T=E(k);if(!C())return B(null);var S=function(D){if(D)return B(D);if(C())return T(S);var P=o(arguments,1);B.apply(null,[null].concat(P))};T(S)}function u8(C,k,B){fm(function(){return!C.apply(this,arguments)},k,B)}var d8=function(C,k){if(k=zo(k||he),!An(C))return k(new Error("First argument to waterfall must be an array of functions"));if(!C.length)return k();var B=0;function T(D){var P=E(C[B++]);D.push(Fn(S)),P.apply(null,D)}function S(D){if(D||B===C.length)return k.apply(null,arguments);T(o(arguments,1))}T([])},IU={apply:r,applyEach:u7,applyEachSeries:d7,asyncify:p,auto:nm,autoInject:y7,cargo:B7,compose:E7,concat:I7,concatLimit:Va,concatSeries:x7,constant:T7,detect:qa,detectLimit:Al,detectSeries:Wa,dir:L7,doDuring:M7,doUntil:R7,doWhilst:lm,during:O7,each:Ga,eachLimit:bl,eachOf:Uo,eachOfLimit:Lr,eachOfSeries:Pi,eachSeries:vl,ensureAsync:cm,every:Qa,everyLimit:yl,everySeries:Ya,filter:Ja,filterLimit:kl,filterSeries:Ka,forever:N7,groupBy:$7,groupByLimit:Xa,groupBySeries:_7,log:j7,map:Ha,mapLimit:Ri,mapSeries:tm,mapValues:H7,mapValuesLimit:eu,mapValuesSeries:z7,memoize:V7,nextTick:q7,parallel:W7,parallelLimit:G7,priorityQueue:Z7,queue:dm,race:Q7,reduce:Vo,reduceRight:nu,reflect:ou,reflectAll:Y7,reject:K7,rejectLimit:hm,rejectSeries:X7,retry:ru,retryable:t8,seq:sm,series:n8,setImmediate:m,some:iu,someLimit:wl,someSeries:su,sortBy:o8,timeout:r8,times:i8,timesLimit:lu,timesSeries:s8,transform:l8,tryEach:c8,unmemoize:a8,until:u8,waterfall:d8,whilst:fm,all:Qa,allLimit:yl,allSeries:Ya,any:iu,anyLimit:wl,anySeries:su,find:qa,findLimit:Al,findSeries:Wa,forEach:Ga,forEachSeries:vl,forEachLimit:bl,forEachOf:Uo,forEachOfSeries:Pi,forEachOfLimit:Lr,inject:Vo,foldl:Vo,foldr:nu,select:Ja,selectLimit:kl,selectSeries:Ka,wrapSync:p};t.default=IU,t.apply=r,t.applyEach=u7,t.applyEachSeries=d7,t.asyncify=p,t.auto=nm,t.autoInject=y7,t.cargo=B7,t.compose=E7,t.concat=I7,t.concatLimit=Va,t.concatSeries=x7,t.constant=T7,t.detect=qa,t.detectLimit=Al,t.detectSeries=Wa,t.dir=L7,t.doDuring=M7,t.doUntil=R7,t.doWhilst=lm,t.during=O7,t.each=Ga,t.eachLimit=bl,t.eachOf=Uo,t.eachOfLimit=Lr,t.eachOfSeries=Pi,t.eachSeries=vl,t.ensureAsync=cm,t.every=Qa,t.everyLimit=yl,t.everySeries=Ya,t.filter=Ja,t.filterLimit=kl,t.filterSeries=Ka,t.forever=N7,t.groupBy=$7,t.groupByLimit=Xa,t.groupBySeries=_7,t.log=j7,t.map=Ha,t.mapLimit=Ri,t.mapSeries=tm,t.mapValues=H7,t.mapValuesLimit=eu,t.mapValuesSeries=z7,t.memoize=V7,t.nextTick=q7,t.parallel=W7,t.parallelLimit=G7,t.priorityQueue=Z7,t.queue=dm,t.race=Q7,t.reduce=Vo,t.reduceRight=nu,t.reflect=ou,t.reflectAll=Y7,t.reject=K7,t.rejectLimit=hm,t.rejectSeries=X7,t.retry=ru,t.retryable=t8,t.seq=sm,t.series=n8,t.setImmediate=m,t.some=iu,t.someLimit=wl,t.someSeries=su,t.sortBy=o8,t.timeout=r8,t.times=i8,t.timesLimit=lu,t.timesSeries=s8,t.transform=l8,t.tryEach=c8,t.unmemoize=a8,t.until=u8,t.waterfall=d8,t.whilst=fm,t.all=Qa,t.allLimit=yl,t.allSeries=Ya,t.any=iu,t.anyLimit=wl,t.anySeries=su,t.find=qa,t.findLimit=Al,t.findSeries=Wa,t.forEach=Ga,t.forEachSeries=vl,t.forEachLimit=bl,t.forEachOf=Uo,t.forEachOfSeries=Pi,t.forEachOfLimit=Lr,t.inject=Vo,t.foldl=Vo,t.foldr=nu,t.select=Ja,t.selectLimit=kl,t.selectSeries=Ka,t.wrapSync=p,Object.defineProperty(t,"__esModule",{value:!0})})})(ah,ah.exports);var Z2={exports:{}},uh=Z2.exports=function(n,e){if(e||(e=16),n===void 0&&(n=128),n<=0)return"0";for(var t=Math.log(Math.pow(2,n))/Math.log(e),o=2;t===1/0;o*=2)t=Math.log(Math.pow(2,n/o))/Math.log(e)*o;for(var r=t-Math.floor(t),i="",o=0;o<Math.floor(t);o++){var s=Math.floor(Math.random()*e).toString(e);i=s+i}if(r){var l=Math.pow(e,r),s=Math.floor(Math.random()*l).toString(e);i=s+i}var c=parseInt(i,e);return c!==1/0&&c>=Math.pow(2,n)?uh(n,e):i};uh.rack=function(n,e,t){var o=function(i){var s=0;do{if(s++>10)if(t)n+=t;else throw new Error("too many ID collisions, use more bits");var l=uh(n,e)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=e||16,o};var Q2=Bo,lw=W2,cw=G2,Ic=cn,dh=ah.exports,aw=Z2.exports,Y2=mr.ACTIONS,J2=_e;function _e(n,e){if(Q2.EventEmitter.call(this),!e||typeof e!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=e,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}Q2.mixin(_e),_e.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},_e.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},_e.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||aw();var e=this._createLocalPresence(n);return this.localPresences[n]=e,e},_e.prototype.destroy=function(n){this._wantsDestroy=!0;var e=this,t=Object.keys(e.localPresences);this.unsubscribe(function(o){if(o)return e._callbackOrEmit(o,n);var r=Object.keys(e._remotePresenceInstances);dh.parallel([function(i){dh.each(t,function(s,l){e.localPresences[s].destroy(l)},i)},function(i){if(!e._wantsDestroy)return i();dh.each(r,function(s,l){e._remotePresenceInstances[s].destroy(l)},i)}],function(i){e._wantsDestroy&&delete e.connection._presences[e.channel],e._callbackOrEmit(i,n)})})},_e.prototype._sendSubscriptionAction=function(n,e){this.wantSubscribe=!!n;var t=this.wantSubscribe?Y2.presenceSubscribe:Y2.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=e,this.connection.canSend&&this.connection._sendPresenceAction(t,o,this)},_e.prototype._handleSubscribe=function(n,e){this.wantSubscribe&&(this.subscribed=!0);var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},_e.prototype._handleUnsubscribe=function(n,e){this.subscribed=!1;var t=this._subscriptionCallback(e);this._callbackOrEmit(n,t)},_e.prototype._receiveUpdate=function(n,e){var t=Ic.dig(this.localPresences,e.id);if(t)return t._ack(n,e.pv);if(n)return this.emit("error",n);var o=this,r=Ic.digOrCreate(this._remotePresenceInstances,e.id,function(){return o._createRemotePresence(e.id)});r.receiveUpdate(e)},_e.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},_e.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var e in this.localPresences){var t=this.localPresences[e];t.value!==null&&t.send()}},_e.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},_e.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},_e.prototype._resubscribe=function(){var n=[];for(var e in this._subscriptionCallbacksBySeq){var t=this._subscriptionCallback(e);n.push(t)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},_e.prototype._subscriptionCallback=function(n){var e=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],e},_e.prototype._callbackOrEmit=function(n,e){if(e)return Ic.nextTick(e,n);n&&this.emit("error",n)},_e.prototype._createLocalPresence=function(n){return new lw(this,n)},_e.prototype._createRemotePresence=function(n){return new cw(this,n)},_e.prototype._callEachOrEmit=function(n,e){var t=Ic.callEach(n,e);!t&&e&&this.emit("error",e)};var ys=W2,K2=yc,uw=cn,X2=K2.CODES,dw=un;function un(n,e){ys.call(this,n,e),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}un.prototype=Object.create(ys.prototype),un.prototype.submit=function(n,e){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,e);var t={code:X2.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(t,e)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,ys.prototype.submit.call(this,n,e)},un.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),ys.prototype.destroy.call(this,n)},un.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(e){e.t=n._doc.type.uri,e.v=n._doc.version,n.connection.send(e)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},un.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)},un.prototype._transformAgainstOp=function(n,e){var t=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=t._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=t._transformPresence(r.p,n,e),t._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=t._getCallback(r.pv);t._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,e)}catch(r){this.emit("error",r)}},un.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},un.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},un.prototype._message=function(){var n=ys.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},un.prototype._transformPresence=function(n,e,t){var o=this._doc.type;if(!uw.supportsPresence(o))throw new K2(X2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,e,t)};var e5={};(function(n){var e=As,t=yc,o=cn,r=t.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var a=e.map[c];if(a==null||typeof a!="object")return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new t(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new t(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new t(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new t(r.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new t(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new t(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return e.map[l]&&e.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new t(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new t(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new t(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var a=c.create,u=e.map[a.type];if(!u)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=u.create(a.data),l.type=u.uri,l.v++}catch(m){return m}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var f=i(l,c.op);if(f)return f;l.v++}else l.v++};function i(l,c){if(!l.type)return new t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new t(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var a=e.map[l.type];if(!a)return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=a.apply(l.data,c)}catch(u){return new t(r.ERR_OT_OP_NOT_APPLIED,u.message)}}n.transform=function(l,c,a){if(c.v!=null&&c.v!==a.v)return new t(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(a.del){if(c.create||"op"in c)return new t(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(a.create&&("op"in c||c.create||c.del)||"op"in a&&c.create)return new t(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in a&&"op"in c){if(!l)return new t(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=e.map[l],!l))return new t(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,a.op,"left")}catch(u){return u}}}c.v!=null&&c.v++},n.applyOps=function(l,c,a){a=a||{};for(var u=0;u<c.length;u++){var f=c[u];if(a._normalizeLegacyJson0Ops)try{s(l,f)}catch{return new t(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=f.v;var m=n.apply(l,f);if(m)return m}},n.transformPresence=function(l,c,a){var u=this.checkOp(c);if(u)return u;var f=l.t;if(typeof f=="string"&&(f=e.map[f]),!f)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(f))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:f.transformPresence(l.p,c.op,a)}catch(m){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:m.message||m}}l.v++};function s(l,c){if(l.type===e.defaultType.uri){var a=c.op;if(!!a){var u=l.data;a.length>1&&(u=o.clone(u));for(var f=0;f<a.length;f++){var m=a[f];typeof m.lm=="string"&&(m.lm=+m.lm);for(var p=m.p,b=u,y=0;y<p.length;y++){var v=p[y];Object.prototype.toString.call(b)=="[object Array]"?p[y]=+v:b.constructor===Object&&(p[y]=v.toString()),b=b[v]}f<a.length-1&&(u=e.defaultType.apply(u,[m]))}}}}})(e5);var ks=G2,hw=e5,fw=jt;function jt(n,e){ks.call(this,n,e),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._pending=null,this._opCache=null,this._pendingSetPending=!1,this._opHandler=this._handleOp.bind(this),this._createDelHandler=this._handleCreateDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._registerWithDoc()}jt.prototype=Object.create(ks.prototype),jt.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},jt.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),ks.prototype.destroy.call(this,n)},jt.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)},jt.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))}})}},jt.prototype._handleOp=function(n,e,t){var o=t===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},ks.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},ks.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},jt.prototype._transformAgainstOp=function(n,e){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,e)}catch(t){return this.presence.emit("error",t)}this.presence._updateRemotePresence(this)}},jt.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],e=n.op,t=n.isOwnOp;e===null?(this._pending.p=null,this._pending.v++):hw.transformPresence(this._pending,e,t)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},jt.prototype._startCachingOps=function(){this._opCache=[]},jt.prototype._stopCachingOps=function(){this._opCache=null},jt.prototype._cacheOp=function(n,e){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:e})};var t5=J2,mw=dw,gw=fw;function Qr(n,e,t){var o=Qr.channel(e,t);t5.call(this,n,o),this.collection=e,this.id=t}var pw=Qr;Qr.prototype=Object.create(t5.prototype),Qr.channel=function(n,e){return n+"."+e},Qr.prototype._createLocalPresence=function(n){return new mw(this,n)},Qr.prototype._createRemotePresence=function(n){return new gw(this,n)};var Cw=Aw;function Aw(n,e,t,o,r){this.id=n,this.v=e,this.type=t,this.data=o,this.m=r}var bw=Cw,n5=Bo,o5=ws;function ws(n,e,t,o,r){if(n5.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=e,this.connection=n,this.id=o,this.collection=t,this.callback=r,this.sent=!1}n5.mixin(ws),ws.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},ws.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},ws.prototype._handleResponse=function(n,e){if(this.emit("ready"),n)return this.callback(n);var t=e.meta?e.meta:null,o=new bw(this.id,e.v,e.type,e.data,t);this.callback(null,o)};var r5=o5,vw=cn,yw=mr.ACTIONS,kw=hh;function hh(n,e,t,o,r,i){if(r5.call(this,n,e,t,o,i),!vw.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}hh.prototype=Object.create(r5.prototype),hh.prototype._message=function(){return{a:yw.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var i5=o5,ww=cn,Bw=mr.ACTIONS,Ew=fh;function fh(n,e,t,o,r,i){if(i5.call(this,n,e,t,o,i),!ww.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}fh.prototype=Object.create(i5.prototype),fh.prototype._message=function(){return{a:Bw.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var Iw=Kk,xw=ow,Tw=J2,s5=pw,Dw=kw,Sw=Ew,l5=Bo,Yr=yc,be=mr.ACTIONS,c5=As,dn=cn,Bs=N2,Es=Yr.CODES;function a5(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var Lw=X;function X(n){l5.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=a5(n),this.bindToSocket(n)}l5.mixin(X),X.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var e=a5(n);this._setState(e),this.canSend=!1;var t=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{Bs.warn("Failed to parse message",o);return}t.debug&&Bs.info("RECV",JSON.stringify(r));var i={data:r};if(t.emit("receive",i),!!i.data)try{t.handleMessage(i.data)}catch(s){dn.nextTick(function(){t.emit("error",s)})}},n.readyState===1&&t._initializeHandshake(),n.onopen=function(){t._setState("connecting"),t._initializeHandshake()},n.onerror=function(o){t.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?t._setState("closed",o):o==="stopped"||o==="Stopped by server"?t._setState("stopped",o):t._setState("disconnected",o)}},X.prototype.handleMessage=function(n){var e=null;switch(n.error&&(e=u5(n.error,n),delete n.error),n.a){case be.initLegacy:return this._handleLegacyInit(n);case be.handshake:return this._handleHandshake(e,n);case be.queryFetch:var t=this.queries[n.id];t&&t._handleFetch(e,n.data,n.extra);return;case be.querySubscribe:var t=this.queries[n.id];t&&t._handleSubscribe(e,n.data,n.extra);return;case be.queryUnsubscribe:return;case be.queryUpdate:var t=this.queries[n.id];if(!t)return;if(e)return t._handleError(e);n.diff&&t._handleDiff(n.diff),n.hasOwnProperty("extra")&&t._handleExtra(n.extra);return;case be.bulkFetch:return this._handleBulkMessage(e,n,"_handleFetch");case be.bulkSubscribe:case be.bulkUnsubscribe:return this._handleBulkMessage(e,n,"_handleSubscribe");case be.snapshotFetch:case be.snapshotFetchByTimestamp:return this._handleSnapshotFetch(e,n);case be.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(e,n.data);return;case be.subscribe:case be.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(e,n.data);return;case be.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(e,n);return;case be.presence:return this._handlePresence(e,n);case be.presenceSubscribe:return this._handlePresenceSubscribe(e,n);case be.presenceUnsubscribe:return this._handlePresenceUnsubscribe(e,n);case be.presenceRequest:return this._handlePresenceRequest(e,n);case be.pingPong:return this._handlePingPong(e);default:Bs.warn("Ignoring unrecognized message",n)}};function u5(n,e){var t=new Error(n.message);return t.code=n.code,e&&(t.data=e),t}X.prototype._handleBulkMessage=function(n,e,t){if(e.data)for(var o in e.data){var r=e.data[o],i=this.getExisting(e.c,o);i&&(n?i[t](n):r.error?i[t](u5(r.error)):i[t](null,r))}else if(Array.isArray(e.b))for(var s=0;s<e.b.length;s++){var o=e.b[s],i=this.getExisting(e.c,o);i&&i[t](n)}else if(e.b)for(var o in e.b){var i=this.getExisting(e.c,o);i&&i[t](n)}else Bs.error("Invalid bulk message",e)},X.prototype._reset=function(){this.agent=null},X.prototype._setState=function(n,e){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var t=new Yr(Es.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",t)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var c=this._snapshotRequests[o];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,e),this.emit("state",n,e)}},X.prototype.startBulk=function(){this.bulk||(this.bulk={})},X.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var e=this.bulk[n];this._sendBulk("f",n,e.f),this._sendBulk("s",n,e.s),this._sendBulk("u",n,e.u)}this.bulk=null},X.prototype._sendBulk=function(n,e,t){if(!!t){var o=[],r={},i=0,s;for(var l in t){var c=t[l];c==null?o.push(l):(r[l]=c,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:e,d:l})}else o.length&&this.send({a:"b"+n,c:e,b:o});if(i===1){var a=r[s];this.send({a:n,c:e,d:s,v:a})}else i&&this.send({a:"b"+n,c:e,b:r})}},X.prototype._sendActions=function(n,e,t){if(this._addDoc(e),this.bulk){var o=this.bulk[e.collection]||(this.bulk[e.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(e.id);return r[e.id]=t,i}else{var s={a:n,c:e.collection,d:e.id,v:t};this.send(s)}},X.prototype.sendFetch=function(n){return this._sendActions(be.fetch,n,n.version)},X.prototype.sendSubscribe=function(n){return this._sendActions(be.subscribe,n,n.version)},X.prototype.sendUnsubscribe=function(n){return this._sendActions(be.unsubscribe,n)},X.prototype.sendOp=function(n,e){this._addDoc(n);var t={a:be.op,c:n.collection,d:n.id,v:n.version,src:e.src,seq:e.seq,x:{}};"op"in e&&(t.op=e.op),e.create&&(t.create=e.create),e.del&&(t.del=e.del),n.submitSource&&(t.x.source=e.source),this.send(t)},X.prototype.send=function(n){this.debug&&Bs.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},X.prototype.ping=function(){if(!this.canSend)throw new Yr(Es.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:be.pingPong};this.send(n)},X.prototype.close=function(){this.socket.close()},X.prototype.getExisting=function(n,e){if(this.collections[n])return this.collections[n][e]},X.prototype.get=function(n,e){var t=this.collections[n]||(this.collections[n]={}),o=t[e];return o||(o=t[e]=new Iw(this,n,e),this.emit("doc",o)),o._wantsDestroy=!1,o},X.prototype._destroyDoc=function(n){!n._wantsDestroy||(dn.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},X.prototype._addDoc=function(n){var e=this.collections[n.collection];e||(e=this.collections[n.collection]={}),e[n.id]!==n&&(e[n.id]=n)},X.prototype._createQuery=function(n,e,t,o,r){var i=this.nextQueryId++,s=new xw(n,this,i,e,t,o,r);return this.queries[i]=s,s.send(),s},X.prototype._destroyQuery=function(n){delete this.queries[n.id]},X.prototype.createFetchQuery=function(n,e,t,o){return this._createQuery(be.queryFetch,n,e,t,o)},X.prototype.createSubscribeQuery=function(n,e,t,o){return this._createQuery(be.querySubscribe,n,e,t,o)},X.prototype.hasPending=function(){return!!(this._firstDoc(xc)||this._firstQuery(xc)||this._firstSnapshotRequest())};function xc(n){return n.hasPending()}X.prototype.hasWritePending=function(){return!!this._firstDoc(Mw)};function Mw(n){return n.hasWritePending()}X.prototype.whenNothingPending=function(n){var e=this._firstDoc(xc);if(e){e.once("nothing pending",this._nothingPendingRetry(n));return}var t=this._firstQuery(xc);if(t){t.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}dn.nextTick(n)},X.prototype._nothingPendingRetry=function(n){var e=this;return function(){dn.nextTick(function(){e.whenNothingPending(n)})}},X.prototype._firstDoc=function(n){for(var e in this.collections){var t=this.collections[e];for(var o in t){var r=t[o];if(n(r))return r}}},X.prototype._firstQuery=function(n){for(var e in this.queries){var t=this.queries[e];if(n(t))return t}},X.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},X.prototype.fetchSnapshot=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new Dw(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},X.prototype.fetchSnapshotByTimestamp=function(n,e,t,o){typeof t=="function"&&(o=t,t=null);var r=this.nextSnapshotRequestId++,i=new Sw(this,r,n,e,t,o);this._snapshotRequests[i.requestId]=i,i.send()},X.prototype._handleSnapshotFetch=function(n,e){var t=this._snapshotRequests[e.id];!t||(delete this._snapshotRequests[e.id],t._handleResponse(n,e))},X.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},X.prototype._initializeHandshake=function(){this.send({a:be.handshake,id:this.id})},X.prototype._handleHandshake=function(n,e){if(n)return this.emit("error",n);this._initialize(e)},X.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},X.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Yr(Es.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(c5.map[n.type]!==c5.defaultType)return this.emit("error",new Yr(Es.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Yr(Es.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},X.prototype.getPresence=function(n){var e=this,t=dn.digOrCreate(this._presences,n,function(){return new Tw(e,n)});return t._wantsDestroy=!1,t},X.prototype.getDocPresence=function(n,e){var t=s5.channel(n,e),o=this,r=dn.digOrCreate(this._presences,t,function(){return new s5(o,n,e)});return r._wantsDestroy=!1,r},X.prototype._sendPresenceAction=function(n,e,t){this._addPresence(t);var o={a:n,ch:t.channel,seq:e};return this.send(o),o.seq},X.prototype._addPresence=function(n){dn.digOrCreate(this._presences,n.channel,function(){return n})},X.prototype._handlePresenceSubscribe=function(n,e){var t=dn.dig(this._presences,e.ch);t&&t._handleSubscribe(n,e.seq)},X.prototype._handlePresenceUnsubscribe=function(n,e){var t=dn.dig(this._presences,e.ch);t&&t._handleUnsubscribe(n,e.seq)},X.prototype._handlePresence=function(n,e){var t=dn.dig(this._presences,e.ch);t&&t._receiveUpdate(n,e)},X.prototype._handlePresenceRequest=function(n,e){var t=dn.dig(this._presences,e.ch);t&&t._broadcastAllLocalPresence(n,e)};var d5=Lw,Rw=As;const Tc={err:1001,msg:"user auth error",name:"AuthError"},Ow={err:1002,msg:"you don't have required permission",name:"PermissionError"},mh={err:1003,msg:"Too many user connected",name:"MaxUserError"},Is={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},Pw={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},Fw={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},xs="x-live-editor-token",Dc="x-live-editor-base-url",Ct=w("auth-connection");function Nw(n){try{n()}catch(e){Ct.error(e)}}class $w{constructor(e,t){h(this,"connection");h(this,"ws");h(this,"retryCount");h(this,"events",new pm.EventEmitter);h(this,"token",null);h(this,"resourceToken",null);this.url=e,this.reauthFunc=t,this.retryCount=0}getBaseURL(){const e=new URL(this.url);return`${e.protocol==="wss:"?"https:":"http:"}//${e.host}${e.pathname}`}getBase64BaseURL(){return Ko(this.getBaseURL())}async auth(e){d(Ct,e.token,"no auth token");const t=`${this.getBaseURL()}/auth`,o=await window.fetch(t,{method:"GET",headers:{[xs]:e.token,[Dc]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=e.token,await o.json()}async logout(){if(!this.token)return;const e=`${this.getBaseURL()}/logout`;await window.fetch(e,{method:"GET",headers:{[Dc]:Ko(this.getBaseURL())}})}async init(e){const t=await this.auth(e);this.resourceToken=t.read,this.ws=new _8.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(d5.prototype),d(Ct,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:e})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},d5.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,Ct.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const e=await this.reauthFunc();await this.auth(e),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:e})}}}catch(e){Ct.error(e),setTimeout(()=>this.handleAuthError(),0)}}else Ct.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const e=new Error(Tc.msg);e.code=Tc.err,this.events.emit("error",e)}emitRequestReloadError(){const e=new Error(Is.msg);e.code=Is.err,this.events.emit("requestReloadError",e)}emitWriteConflictError(e,t){e.orgMsg=t,this.events.emit("writeConflictError",e)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(e){const t=e;if(t.a==="pong")return;const o=t.err;if(o===Tc.err)Ct.warn("auth error"),this.handleAuthError();else if(o===mh.err)Ct.warn(mh.msg),this.emitMaxUsersError();else if(o===Is.err){Ct.warn(Is.msg);try{this.emitRequestReloadError()}catch(r){Ct.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else Ct.error(`unknown message received: ${JSON.stringify(t)}`),this.emitAuthError()}get(e,t){return d(Ct,this.connection,"no this.connection"),this.connection.get(e,t)}addEventListener(e,t){e==="error"?this.events.addListener(e,t):(d(Ct,this.ws,"no this.ws"),this.ws.addEventListener(e,t))}onWriteConflictError(e){this.events.addListener("writeConflictError",e)}onMaxUsersError(e){d(Ct,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",e)}onRequestReloadError(e){d(Ct,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",e)}end(e){var t;this.reauthFunc=void 0,this.events.removeAllListeners(),Nw(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(t=this.ws)==null||t.close(),this.ws=void 0,e&&this.logout()}}w("utils/file");function _w(){function n(){return new Promise(e=>{const t=new FileReader;t.onload=()=>{e(t.result)},t.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}_w();async function jw(n){const t=n.size,o=Math.floor((t+102400-1)/102400),r=new j8.Hash;for(let s=0;s<o;s++){const l=s*102400;let c=l+102400;c>t&&(c=t);const u=await n.slice(l,c,n.type).arrayBuffer();r.update(new Uint8Array(u))}const i=r.digest();return Ko(i)}const xn=w("sharedb-doc/client");class Hw{constructor(e,t,o){h(this,"connection");h(this,"auth");h(this,"doc",null);h(this,"reauthFunc");h(this,"clientId",N());h(this,"getDoc",async()=>{const e=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});d(xn,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const t=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=t,await e(t),xn.debug(t),t});this.auth=e;const r=`${t}/${this.auth.appId}/${this.auth.docId}`;Rw.register(El.type),this.connection=new $w(r,o),this.reauthFunc=o}editorServer(){const e=this.apiServer(),t=`/${this.auth.appId}/${this.auth.docId}`;return d(xn,e.endsWith(t),`invalid api server: ${e}, ${t}`),e.substr(0,e.length-t.length)}close(e){this.connection.end(e),this.doc=null}on(e,t){this.connection.addEventListener(e,o=>{(e==="error"||this.doc)&&t(o)})}onWriteConflictError(e){this.connection.onWriteConflictError(e)}onMaxUsersError(e){this.connection.onMaxUsersError(e)}onRequestReloadError(e){this.connection.onRequestReloadError(e)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const e=this.connection.url;if(e.startsWith("ws://"))return`http://${e.substring(5)}`;if(e.startsWith("wss://"))return`https://${e.substring(6)}`;throw new Error(`invalid server url: ${e}`)}async getFileUrlByHash(e,t,o,r,i){try{const s=`${e}/${t}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(e){const o=`${this.apiServer()}/resources`;let r=[];e.forEach(l=>{const c=l.split("|");r.push(...c)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[xs]:this.connection.token}));return await Promise.all(i)}async uploadFile(e,t,o,r,i){let s=t.size;if(s===0)throw new Error("file is empty");s+=500;const l=p=>{xn.info(`on progress: ${p.loaded}`);let b=p.loaded*100/s;b>100&&(b=100),r(b)},c=await jw(t),a=await this.getFileUrlByHash(e,c,t.name,t.size,o);if(a)return r(-1),a;let u=e;i!=null&&i.thumbnail&&(u+="/thumbnail");const f=new FormData;f.append("file-size",`${t.size}`),f.append("file-hash",c),f.append("file",t,t.name);const m=await this.request(u,{method:"post",data:f,withCredentials:!0,headers:{...o},onUploadProgress:l});return xn.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(e,t=()=>{},o){const i=`${this.apiServer()}/resources`;d(xn,this.connection.token,"no connection token");const s=await this.uploadFile(i,e,{[xs]:this.connection.token},t,o);return d(xn,s,"no result"),s}async request(e,t){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const c=t||{};c.url=e,c.headers||(c.headers={}),d(xn,o,"no token"),c.headers={...c.headers,[xs]:o,[Dc]:this.connection.getBase64BaseURL()};try{return await N8.default(e,c)}catch(a){if(r=a,((i=a==null?void 0:a.response)==null?void 0:i.status)===403&&this.reauthFunc){const u=await this.reauthFunc();if(await this.connection.auth(u),!u.token)throw a;o=u.token;continue}throw(s=a.response)!=null&&s.data&&(a.responseData=a.response.data),a}}throw d(xn,r,"no error"),r}async getVersions(){const t=`${this.apiServer()}/versions`,r=(await this.request(t)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),r}async getVersion(e){const o=`${this.apiServer()}/versions/${e}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const t=`${this.apiServer()}/versions/latest`,o=await this.request(t);return JSON.parse(o.data.data)}async getVersionOps(e,t){let r=`${this.apiServer()}/versions/before/${e}?withOp=true`;t!==void 0&&t!==0&&(r+=`&from=${t}`);const i=await this.request(r),s=i.data.ops,l=$8.default(s,u=>!!u.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(xn,c.create,"no createDoc.create"),a=c.create.data):a=JSON.parse(i.data.data),a.blocks||(a.blocks=[]),{doc:a,ops:i.data.ops}}async updateVersionExtra(e,t,o){const i=`${this.apiServer()}/versions/${e}/tags/${t}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}async revertVersion(e){const o=`${this.apiServer()}/versions/revert/${e}`;await this.request(o,{method:"post",data:{}})}async createVersion(e,t){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:t,tag:e}})).data}async recognizeLink(e){const o=`${this.apiServer()}/resources/external/${Ko(e)}`;return(await this.request(o)).data}buildResourceUrl(e,t){if(!e)return"";if(e.startsWith("https:")||e.startsWith("http:")||e.startsWith("file:")||e.startsWith("data:")||e.startsWith("blob:"))return e;let r=`${this.apiServer()}/resources/${encodeURIComponent(e)}`;const i=[];if(t!=null&&t.withToken&&i.push(`token=${this.getResourceToken()}`),t!=null&&t.downloadFileName&&i.push(`&fileName=${encodeURIComponent(t.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function zw(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const gh=w("block-ids");class Uw{constructor(){h(this,"ids",new Map)}onInsertBlock(e){const t=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<t.length;r++){const i=t[r];if(i>=e){const s=this.ids.get(i);d(gh,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=N();this.ids.set(e,o)}onDeleteBlock(e){this.ids.delete(e);const t=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<t.length;o++){const r=t[o];if(r>e){const i=this.ids.get(r);d(gh,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(e){let t=this.ids.get(e);return t||(t=N(),this.ids.set(e,t)),t}getById(e){return Array.from(this.ids.entries()).find(([,t])=>t===e)}}class Vw{constructor(){h(this,"ids",new Map)}getContainerIds(e){let t=this.ids.get(e);return t||(t=new Uw,this.ids.set(e,t)),t}onInsertBlock(e,t){this.getContainerIds(e).onInsertBlock(t)}onDeleteBlock(e,t){this.getContainerIds(e).onDeleteBlock(t)}getBlockId(e,t){return this.getContainerIds(e).getId(t)}getBlockIndexById(e){const t=Array.from(this.ids.entries());for(let o=0;o<t.length;o++){const r=t[o],i=r[1].getById(e);if(i)return{containerId:r[0],blockIndex:i[0]}}return d(gh,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class h5{constructor(e=new Set,t=new Map){this.deletedKeys=e,this.insertedValues=t}insert(e,t){this.insertedValues.set(e,t)}delete(e){this.deletedKeys.add(e)}toDocBlockDelta(){const e={};return this.insertedValues.forEach((t,o)=>{e[o]=t}),{insert:e,delete:Array.from(this.deletedKeys)}}}const Sc=w("op-parse-handler");class qw{constructor(e,t){h(this,"actions",[]);this.outerHandler=e,this.local=t}pushActions(e){if(!e.containerId){this.actions.push(e);return}const o={...e,containerId:(r=>r==="blocks"?"root":r)(e.containerId)};this.actions.push(o)}onDeleteBlock(e,t){this.pushActions({type:"deleteBlock",containerId:e,blockIndex:t})}onInsertBlock(e,t,o){this.pushActions({type:"insertBlock",containerId:e,blockIndex:t,data:o})}onDeleteBlockData(e,t,o){this.pushActions({type:"deleteBlockData",containerId:e,blockIndex:t,key:o})}onInsertBlockData(e,t,o,r){this.pushActions({type:"insertBlockData",containerId:e,blockIndex:t,key:o,value:r})}onUpdateBlockText(e,t,o){this.pushActions({type:"updateBlockText",containerId:e,blockIndex:t,richTextData:o})}onDeleteContainer(e){this.pushActions({type:"deleteContainer",containerId:e})}onCreateContainer(e,t){this.pushActions({type:"createContainer",containerId:e,data:t})}onDeleteComment(e){this.pushActions({type:"deleteComment",commentId:e})}onCreateComment(e){this.pushActions({type:"createComment",commentId:e})}onUpdateComment(e){this.pushActions({type:"updateComment",commentId:e})}end(){const e=this.actions,t=new Set,o=new Map,r=new Vw,i=e.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,c=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const a=o.get(c);a&&(Sc.debug(`ignore update object data before delete block: ${JSON.stringify(a)}`),o.delete(c));const u=`${l.containerId}-${l.blockIndex}`;t.add(u),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,c=`${l.containerId}-${l.blockIndex}`;if(t.has(c)){Sc.warn("delete block data after delete block, ignore it");continue}const a=r.getBlockId(l.containerId,l.blockIndex);let u=o.get(a);u||(u=new h5,o.set(a,u)),u.delete(l.key)}else d(Sc,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,c=r.getBlockId(l.containerId,l.blockIndex);let a=o.get(c);a||(a=new h5,o.set(c,a)),a.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:c,blockIndex:a}=r.getBlockIndexById(s);Sc.debug(`update block data: ${c}, ${a}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(c,a,l.toDocBlockDelta(),this.local)})}}const je=w("op-parser");class f5{}class ph{constructor(e){h(this,"key");this.key=e}}function Ww(n,e,t){const o=e.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const c=o[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const u=c[1];if(typeof u!="object"||u.i===void 0||Object.keys(u).length!==1)return!1}const s=i.i;d(je,s.id,"block id is required"),d(je,s.type,"block type is required");for(let l=1;l<o.length;l++){const c=o[l],a=c[0],u=c[1];s[a]=u.i}return t.onInsertBlock(n,r,s),!0}function Ch(n,e,t,o){if(t==="upsert"&&Ww(n,e,o))return;d(je,Array.isArray(e),`invalid block op: ${n}, ${JSON.stringify(e)}`);const r=e.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const c=r[1];if(d(je,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(e)}`),d(je,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(e)}`),r.splice(0,2),t==="upsert"){const u=c.e;o.onUpdateBlockText(n,i,u)}d(je,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){d(je,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];d(je,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const a=l[1];if(c==="text"){if(d(je,typeof a=="object",`invalid opData type, ${JSON.stringify(a)}`),a.i&&t==="upsert"&&o.onInsertBlockData(n,i,c,a.i),a.r&&t==="remove"&&o.onDeleteBlockData(n,i,c),a.et==="rich-text"&&t==="upsert"){const f=a.e;o.onUpdateBlockText(n,i,f)}}else t==="remove"&&a.r&&s.push(new ph(c)),t==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i);r.shift()}else if(typeof l=="object"){const c=l;t==="remove"&&c.r&&s.push(new f5),t==="upsert"&&c.i&&o.onInsertBlock(n,i,c.i),r.shift()}else{d(je,typeof l=="string","data is not string"),d(je,l!=="text","data !== 'text'"),d(je,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const c=l,a=r[1];t==="remove"&&a.r&&s.push(new ph(c)),t==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof f5?o.onDeleteBlock(n,i):l instanceof ph?o.onDeleteBlockData(n,i,l.key):d(je,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function Gw(n,e,t){je.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function Zw(n,e,t){const o=n[1],r=n[2];d(je,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),d(je,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?je.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?e==="upsert"&&t.onUpdateComment(o):r.i?e==="upsert"&&t.onCreateComment(o):r.r?e==="remove"&&t.onDeleteComment(o):je.error(`unknown comment op, ${JSON.stringify(n)}`)}function Ah(n,e,t){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{Ah(s,e,t)});return}const r=o;if(d(je,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){Gw(n);return}if(r==="comments"){Zw(n,e,t);return}const i=r;if(Array.isArray(n[1]))e==="remove"?n.slice(1).reverse().forEach(s=>{Ch(i,s,e,t)}):n.slice(1).forEach(s=>{Ch(i,s,e,t)});else if(typeof n[1]=="object"){const s=n[1];s.r&&e==="remove"&&t.onDeleteContainer(i),s.i&&e==="upsert"&&t.onCreateContainer(i,s.i)}else d(je,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Ch(i,n.slice(1),e,t)}function m5(n,e,t){const o=new qw(e,t);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=Q.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{Ah(c,i,o)}):Ah(s,i,o)}o.end()}const Qw=w("sharedb-comments");function bh(n){const e=n.blocks;d(Qw,e,"no comment blocks");const t={blocks:{root:e},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(t.blocks[o]=r)}),Q.default(t)}function g5(n){const{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}=n;return{id:e,groupId:t,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}}function vh(n,e){const t=Rk(e),{comments:o,meta:r,blocks:i,...s}=t,l={...n,blocks:i,...s},c=Q.default(l);return delete c.children,c}const ke=w("sharedb-doc/doc-container"),p5="ot-json1";El.type.registerSubtype(Ok.type),El.type.name=p5,El.type.invert=null;class Ts extends zi{constructor(t,o,r=!0){super();h(this,"doc");h(this,"client");h(this,"localPresence");h(this,"remoteCaretHandler",new Lk);h(this,"batching",0);h(this,"status","clean");h(this,"disableLogout");h(this,"destroyed",!1);h(this,"handleNothingPending",()=>{this.setStatus("clean")});h(this,"handleCreate",()=>{this.handleReload("doc created")});h(this,"handleDel",()=>{});h(this,"handleReload",t=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,t)})});h(this,"handleReset",async t=>{const o=new Error(`reset doc: ${t}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});h(this,"handleWriteConflictError",t=>{this.handleReset(`write conflict: ${t.message}, ${JSON.stringify(t.orgMsg)}`)});h(this,"insertObject",async(t,o,r)=>{const i=[t,o,{i:r}];return this.submitOp(i)});h(this,"deleteObject",async(t,o)=>{const r=[t,o,{r:!0}];return this.submitOp(r)});h(this,"replaceObject",async(t,o,r)=>{const i=[t,o,{r:!0,i:r}];return this.submitOp(i)});h(this,"updateObject",async(t,o,r)=>{const i=this.data()[t][o],s=[t,o];return Object.entries(r).forEach(([l,c])=>{if(!_i.default(i[l],c))if(i[l]===void 0){if(c!=null){const a={i:c};s.push([l,a])}}else if(c==null){const a={r:!0};s.push([l,a])}else{const a={r:!0,i:c};s.push([l,a])}}),Object.entries(i).forEach(([l,c])=>{if((r[l]===void 0||r[l]===null)&&c!==void 0){const a={r:!0};s.push([l,a])}}),s.length<=2?Promise.resolve():this.submitOp(s)});h(this,"broadcastMessage",async t=>{const o={type:"custom",data:t,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});h(this,"data",()=>this.doc.data);h(this,"submitOp",async t=>new Promise((o,r)=>{if(this.destroyed){ke.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(t,{},i=>{i?(ke.error(`invalid op, ${i.message}, ${JSON.stringify(t)}`),r(i),ke.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ke.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(t)}`))}));h(this,"createDoc",async t=>new Promise((o,r)=>{this.doc.create(t,p5,i=>{i?r(i):o()})}));h(this,"submitInsertChildContainer",async(t,o)=>{const r=[wo(t),{i:o}];return this.submitOp(r)});h(this,"submitDeleteChildContainer",async t=>{const o=[wo(t),{r:!0}];return this.submitOp(o)});h(this,"submitInsertBlock",async(t,o,r)=>{const i=[wo(t),o,{i:r}];return this.submitOp(i)});h(this,"submitDeleteBlock",async(t,o)=>{const r=[wo(t),o,{r:!0}];return this.submitOp(r)});h(this,"submitUpdateBlockData",async(t,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[wo(t),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c)){const u={r:!0,i:a};i.push([c,u])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(c=>{if(l.has(c))return;const a={r:!0};i.push([c,a])}),Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c))return;const u={i:a};i.push([c,u])}),this.submitOp(i)});h(this,"submitUpdateRichText",async(t,o,r)=>{const i=[wo(t),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});h(this,"handleOp",(t,o,r)=>{if(this.destroyed){ke.warn("handleOp: destroyed");return}m5(t,this,!!o)});this.client=t,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,d(ke,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(t){try{const o=new Hw(t.auth,t.serverUrl,t.reauthFunc),r=await o.getDoc(),i=new Ts(o,r,t.disableLogout);if(r.type===null){if(t.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(t.templateData||zw())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ke.error(o),ke.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,t)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((t,o)=>{if(this.localPresence)t();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(N()),t())})}})}subscribe(){return new Promise((t,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),t())})})}toJSON(){return ps(this.data())}getContainerBlocks(t){const o=this.data();d(ke,o,"no doc data");const r=o[wo(t)];return d(ke,r,`no container data: ${t}`),Q.default(r)}getBlockData(t,o){const r=this.data();d(ke,r,"no doc data");const i=r[wo(t)];d(ke,i,`no container data: ${t}`);const s=i[o];return d(ke,s,`no block data: ${o}`),Q.default(s)}localInsertBlock(t,o,r){return this.submitInsertBlock(t,o,r),this.getBlockData(t,o)}localDeleteBlock(t,o){const r=this.getBlockData(t,o);return this.submitDeleteBlock(t,o),r}localUpdateBlockText(t,o,r){const i=this.getBlockData(t,o);d(ke,i.text,"no block text");const s=Q.default(i.text);this.submitUpdateRichText(t,o,r);const l=dt.apply(s,r);return d(ke,l,"no block text"),l}localUpdateBlockData(t,o,r){const i=Q.default(this.getBlockData(t,o));return this.submitUpdateBlockData(t,o,r),i}localInsertChildContainer(t,o){this.submitInsertChildContainer(t,o)}localDeleteChildContainers(t){this.beginBatchUpdate(),t.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>g5(o))}getComment(t){return this.data().comments[t]}getCommentDoc(t){const o=this.data().comments[t];return bh(o)}localCreateComment(t,o){const r=vh(t,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(t){const o=["comments",t,{r:!0}];return this.submitOp(o)}localUpdateComment(t,o){const r=vh(t,o),i=["comments",t.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var t;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(t=this.localPresence)==null||t.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(t,o,r){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Zr(t),o,r)})}onInsertBlock(t,o,r,i){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Zr(t),o,r,i)})}onUpdateBlockData(t,o,r,i){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Zr(t),o,r,i)})}onUpdateBlockText(t,o,r,i){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Zr(t),o,r,i)})}onDeleteContainer(t,o){d(ke,this.callbacks.length>0,"no callbacks"),d(ke,t!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,Zr(t),o)})}onCreateContainer(t,o,r){d(ke,this.callbacks.length>0,"no callbacks"),d(ke,t!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,Zr(t),o,r)})}onDeleteComment(t,o){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,t,o)})}onCreateComment(t,o){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,t,o)})}onUpdateComment(t,o){d(ke,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,t,o)})}onCustomMessage(t){const o=t;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:t,clientId:"-"};this.onCustomMessage(r)})}async addResources(t){return await this.client.getFileUrlsByHashes(t)}async uploadResource(t,o){var i;return{resourceId:await this.client.uploadResource(t,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(t,o){return this.client.buildResourceUrl(t,o)}request(t,o){return this.client.request(t,o)}getUser(){const t=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:t,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(t){const o=await this.client.getVersion(t);return ps(o)}async getLatestVersion(){const t=await this.client.getLatestVersion();return ps(t)}async getHistoryData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:ps(r),historyData:s}}async getVersionData(t,o){const{doc:r,ops:i}=await this.client.getVersionOps(t,o);return{doc:ps(r),versionData:i}}async updateVersionExtra(t,o,r){await this.client.updateVersionExtra(t,o,r)}revertVersion(t){return this.client.revertVersion(t)}createVersion(t,o){return this.client.createVersion(t,o)}async recognizeLink(t){return this.client.recognizeLink(t)}parseHistoryData(t,o){m5(t.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}w("remote-cursor");class C5{constructor(e){h(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});h(this,"broadcastCaretPos",nt.default(()=>{const e={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(e)},300));h(this,"handleRemoteCaretsChanged",e=>{e.forEach(t=>{const o=this.editor.findBlockById(t);o&&this.editor.reloadBlock(o)})});this.editor=e,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const A5=w("remote-cursor-decorator");class yh{decorateText(e,t,o){const r=e.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=t[t.length-1];d(A5,typeof s=="string","invalid path containerId"),d(A5,typeof l=="number","invalid path blockIndex");const c=e.doc.getBlockData(s,l),a=at(o);return r.getSimpleCursors(c.id).forEach((f,m)=>{m>a&&(m=a);const p=f.map(y=>({id:N(),type:"remote-cursor",name:y.user.displayName,time:y.time,rainbowIndex:y.user.rainbowIndex})),b=i.get(m);b?b.push(...p):i.set(m,p)}),{insertions:i}}}class b5 extends Ve.TypedEmitter{constructor(e){super(),this.editor=e,this.editor.doc.registerCallback(this)}handleChild(e,t,o){if(Ae(_r(this.editor,e)))return;const r=this.editor.getBlockByIndex(e,t),i=H(this.editor.getContainerById(e));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(e,t){this.handleChild(e,t,"data-change")}onUpdateBlockText(e,t){this.handleChild(e,t,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function Yw(n,e){n.addCustom("child-block-tracker",()=>new b5(n)).addListener("change",e)}function Jw(n,e){n.addCustom("child-block-tracker",()=>new b5(n)).removeListener("change",e)}const QV="",Kw={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4",name:"\u6587\u672C\u989C\u8272"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},Xw={colorPalette:{colorDesc:"Text Color",name:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},eB={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};I.mergeLang({"zh-CN":Kw,"en-US":Xw,"js-JP":eB});const YV="";w("button");function Io(n,e,t,o,r){const i=A("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,e),t?typeof t=="string"?t.startsWith("<")?i.innerHTML=t:i.innerText=t:i.appendChild(t):i.innerText=e,o&&(o.indexOf("checked")!==-1&&R(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function v5(n,e,t){t?n.setAttribute(`data-editor-tooltip-${t}`,e):n.innerText=e}const JV="",Jr=w("ui-command-bar-base"),tB={itemElementTag:"div",tippyArrow:!1},Qf=class extends Ve.TypedEmitter{constructor(t,o,r){var i,s;super();h(this,"content");h(this,"items");h(this,"subBar",null);h(this,"parentItem",null);h(this,"closeable",null);h(this,"closeReason",null);h(this,"options");h(this,"id");h(this,"header",null);h(this,"footer",null);h(this,"handleDocumentKeydown",t=>{if(!!this.isVisible&&!t.isComposing&&!Nr(t.target)){if(this.subBar){this.subBar.handleDocumentKeydown(t);return}if(this.items.length!==0){if(t.key==="Escape"){this.close("cancelBar");return}if(t.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),t.preventDefault(),t.stopPropagation()}else if(t.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),t.preventDefault(),t.stopPropagation()}else if(t.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(t.key==="ArrowLeft")this.parentItem&&this.close("switchItem");else if(t.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});h(this,"handleDocumentMouseDown",t=>{if(t.target instanceof Element&&!this.isInCommandBar(t.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,t)===!1)return;this.close("clickBackground")}});h(this,"handleHidden",()=>{this.closeReason!=="fromHover"&&this.emit("close",this),this.close(null),Qm(this.id)});h(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&R(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&Zm(this.id)});h(this,"lastEnterPauseTime",0);h(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});h(this,"handleItemMouseEnter",t=>{if(Date.now()-this.lastEnterPauseTime<100)return;const o=this.getParentCommandItemElement(t.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});h(this,"handleItemMouseLeave",t=>{var r,i;const o=this.getParentCommandItemElement(t.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(j(o,"selected"),this.emit("selectionChange",this,""))});h(this,"handleItemClick",t=>{const o=this.getParentCommandItemElement(t.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close("clickItem"))}});h(this,"handleWheel",t=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=t.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=Qt(r);if(!Ce(this.content,i)){t.stopPropagation(),t.preventDefault();return}t.deltaY<0?i.scrollTop===0&&(t.stopPropagation(),t.preventDefault()):t.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(t.stopPropagation(),t.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:N(),this.options={...tB,...r},this.items=t,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(t)}close(t){this.closeReason=t,this.subBar&&this.subBar.close(t),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(t,o){this.emit("click",this,t,o)}createPopperOptions(){var r,i;const t={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=t==null?void 0:t.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),this.options.padding&&((i=t==null?void 0:t.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),t}destroy(){var t;this.close(null),this.removeAllListeners(),(t=this.subBar)==null||t.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(t){var r;this.subBar&&t.findIndex(s=>{var l,c;return s.id===((c=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:c.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=t;const o=this.createCommandBarContent(t);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const t=this.getSelectedItem();return t?this.items.indexOf(t):-1}getPrevItemIndex(t){if(t<=0)return this.items.length-1;let o=t-1;for(;;){const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(t){let o=t+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const t=this.getSelectedItem();if(!t)return;const o=this.getItemElementById(t.id);o&&j(o,"selected")}selectItem(t){const o=this.getSelectedItem();if(o){if(o.id===t)return;const i=o.id,s=this.getItemElementById(i);s&&j(s,"selected")}const r=this.getItemElementById(t);r?(R(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(t){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close("switchItem");return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=Qf.createSubCommandBar(o,(l=this.closeable)!=null?l:this,t?{id:t}:{});this.subBar=i,this.subBar.on("click",(c,a,u)=>{this.emit("click",c,a,u)}),this.subBar.on("close",()=>{var c;(c=this.subBar)==null||c.destroy(),this.subBar=null,j(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),R(r,"active")}isInCommandBar(t){if(!t||!(t instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Ce(o,t)||Ce(this.content,t)?!0:this.subBar?this.subBar.isInCommandBar(t):!1}createCommandItem(t){var i,s,l,c;let o=(i=this.options.itemElementTag)!=null?i:"div";t.element&&(o="div");const r=A(o,["command-item"],null);return r.setAttribute("data-id",t.id),t.type==="separator"?r.classList.add("separator"):t.type==="section"?(r.classList.add("section","text"),t.element&&(typeof t.element=="function"?r.appendChild(t.element(t)):r.appendChild(t.element))):((s=t.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=t.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(c=t.states)!=null&&c.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,t.element?typeof t.element=="function"?r.appendChild(t.element(t)):r.appendChild(t.element):r.classList.add("standard")),this.initItemElement(t,r),r}getItemById(t){const o=this.items.find(r=>r.id===t);return d(Jr,o,`can not find command item for id: ${t}`),o}getSelectedItem(){const t=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(t){const o=this.getItemElementId(t),r=this.items.find(i=>i.id===o);return d(Jr,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(t){const o=t.getAttribute("data-id");return d(Jr,o,"no data-id attribute"),o}getItemElementById(t){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${t}"]`);return d(Jr,o,`no exists command item, id=${t}`),o}getParentCommandItemElement(t){if(!t||!(t instanceof Element))return null;if(ne(t,"command-item"))return t;const o=t.closest(".command-item");return o||null}createCommandBarContent(t){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=A("div",["editor-command-bar-root"],null);if(this.options.header){const i=A("div",["editor-command-bar-header"],o);this.options.header instanceof Function?i.appendChild(this.options.header()):this.header||i.appendChild(this.options.header),this.header=i}const r=A("div",["editor-command-bar"],o);if(t.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.options.footer){const i=A("div",["menu-item","editor-command-bar","footer"],o);this.options.footer instanceof Function?i.appendChild(this.options.footer()):this.footer||i.appendChild(this.options.footer),this.footer=i}return this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(t){var o;return{placement:(o=t.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(t,o){this.commandBarCreators.set(t,o)}static createSubCommandBar(t,o,r){var l;d(Jr,t.children&&t.children.length>0,"no item children");const i=(l=t.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return d(Jr,s,`no creator for command type: ${i}`),s(t,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let xo=Qf;h(xo,"commandBarCreators",new Map),w("ui-command-bar");class Lc extends xo{constructor(){super(...arguments);h(this,"tippyInstance",null)}manualShow(t,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=H8.default(t,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(t){var o;super.close(t),this.isVisible&&((o=this.tippyInstance)==null||o.hide())}destroy(){var t;(t=this.tippyInstance)==null||t.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var t,o;return(o=(t=this.tippyInstance)==null?void 0:t.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const y5=w("ui-base");class Ds extends Lc{constructor(e,t){var i;const r=[{id:(i=t==null?void 0:t.id)!=null?i:`popup-${N()}`,name:"",element:e}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(e){R(e,"popper")}initItemElement(e,t){}get popupContent(){const e=this.items[0];d(y5,e,"no dialog item");const t=typeof e.element=="function"?e.element(e):e.element;return d(y5,t,"no item element"),t}}const To=w("filterable-list");function k5(n){var t,o;const e=A("div",["list-item"],null);return e.setAttribute("data-id",n.id),e.appendChild(A("div",["list-item-text"],null,n.name)),(t=n.states)!=null&&t.includes("selected")&&R(e,"selected"),(o=n.states)!=null&&o.includes("disabled")&&R(e,"disabled"),e}function w5(n){const e=A("div",["list-root"],null);return n.forEach(t=>{e.appendChild(k5(t))}),n.length||e.appendChild(k5({id:"placeholder",states:["disabled"],name:I.t("search.emptyTips")})),e}function B5(n,e){let t=n;return e&&(t=n.map(o=>({...o,states:o.id===e?["selected"]:void 0}))),t}function nB(n,e){const t=A("div",["filterable-list"],null),o=A("div",["filter"],t),r=A("div",["filter-container"],o),i=A("input",["filter-input"],r);e&&e.placeholder&&(i.placeholder=e.placeholder);const s=A("div",["list"],t),l=w5(B5(n,e==null?void 0:e.initialSelectedId));return s.appendChild(l),t}function E5(n,e,t){const o=n.querySelector(".list");d(To,o,"no list root");const r=w5(B5(e,t)),i=o.querySelector(".list-root");if(d(To,i,"no exists menu"),Wi(i,r),t){const s=o.querySelector(".list-item.selected");s&&(d(To,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class oB{constructor(e,t){h(this,"root");h(this,"visibleItems");h(this,"selectedId");h(this,"filter","");h(this,"onSelected",null);h(this,"handleKeydown",e=>{this.processKeyDown(e)});h(this,"handleInputChanged",()=>{const e=this.root.querySelector(".filter-input");d(To,e,"no input");const t=e.value.toLocaleLowerCase();this.setFilter(t)});h(this,"handleClick",e=>{this.processClick(e)});var o;this.items=e,this.options=t,this.root=nB(e,t),this.bindEvents(),this.selectedId=(o=t==null?void 0:t.initialSelectedId)!=null?o:"",this.visibleItems=e}bindEvents(){const e=this.root.querySelector(".filter-input");d(To,e,"no input"),e.addEventListener("keyup",this.handleInputChanged),e.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const e=this.root.querySelector(".filter-input");d(To,e,"no input"),e.removeEventListener("keyup",this.handleInputChanged),e.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(e=>e.id===this.selectedId):-1}setSelectedId(e){this.selectedId=e,E5(this.root,this.visibleItems,e)}focus(){const e=this.root.querySelector(".filter-input");d(To,e,"no input"),e.focus()}reset(){this.setFilter("");const e=this.root.querySelector(".filter-input");d(To,e,"no input"),e.value=""}setFilter(e){this.filter!==e&&(this.filter=e,this.visibleItems=this.items.filter(t=>t.name.toLocaleLowerCase().includes(e)),E5(this.root,this.visibleItems,this.selectedId))}processClick(e){var s,l;const t=e.target;if(!(t instanceof HTMLElement))return;const o=t.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(c=>c.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(e){var t;if(e.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(e.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(e.key==="Enter"){const o=(t=this.visibleItems.find(r=>r.id===this.selectedId))!=null?t:null;this.onSelected&&this.onSelected(this,o)}}}class rB extends oB{constructor(t,o,r){super(t,r);h(this,"popup");h(this,"onShow",null);h(this,"onHide",null);h(this,"custom",null);h(this,"handleShow",()=>{this.onShow&&this.onShow(this)});h(this,"handleHide",()=>{this.onHide&&this.onHide(this)});h(this,"handleShown",()=>{this.focus()});this.popup=new Ds(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(t){this.reset(),this.popup.manualShow(t,{theme:"dropdown-list"}),this.focus()}processKeyDown(t){super.processKeyDown(t),(t.key==="Esc"||t.key==="Enter")&&this.popup.close("cancelBar")}processClick(t){super.processClick(t);const o=t.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close("clickItem")}}const KV="",XV="";function iB(n,e){const t=document.createElement("div");t.classList.add("toast","show"),e!=null&&e.theme&&t.setAttribute("data-theme",e.theme),e!=null&&e.id&&t.setAttribute("data-id",e.id),e!=null&&e.html?t.innerHTML=n:t.textContent=n,e!=null&&e.position&&(t.style.left=`${e.position.x}px`,t.style.top=`${e.position.y}px`,t.classList.add("positioned")),document.body.appendChild(t),setTimeout(()=>{t.classList.remove("show"),setTimeout(()=>{t.remove()},500)},(e==null?void 0:e.duration)||3e3)}const I5=`<?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">
|