@ones-editor/editor 1.1.8-beta.18 → 1.1.8-beta.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@ Available method signatures are:
28
28
  ${t}
29
29
  \`\`\`
30
30
  `:""}function wp(n){if(!window.isSecureContext||n.selection.range.isCollapsed())return!1;const t=wa(n);yu(n,t);const e=Cu(n,t);Tu(e,t);let r="";if(dT(n)){const i=n.selection.range.getSelectedBlocks()[0],o=it(i.block);J(o)&&(r=hT(n,Go(n,t)))}else{const i=[];t.blocks.root.forEach((o,s)=>{i.push(Th(n,o,t,[{containerId:"root",blockIndex:s}]))}),i[i.length-1]=i[i.length-1].trimEnd(),r=i.join(`
31
- `)}return Xc([{type:"text/plain",data:new Blob([r],{type:"text/plain"})}]),!0}const $U=Object.freeze(Object.defineProperty({__proto__:null,editorHandleEnter:lT,editorHandleDelete:aT,editorHandleBackspace:cT,editorHandleInsertBr:uT,editorHandlePastePlainText:fT,isSelectedCodeTextBlock:dT,getSelectedCodeBlockMarkdown:hT,editorHandleCopyMarkdown:wp},Symbol.toStringTag,{value:"Module"})),Nh={ArrowDown:T5,ArrowUp:B5,ArrowLeft:b5,ArrowRight:v5,"Shift+ArrowDown":y5,"Shift+ArrowUp":w5,"Shift+ArrowLeft":k5,"Shift+ArrowRight":R5,"CtrlOrCmd+ArrowLeft":L5,"CtrlOrCmd+ArrowRight":I5,"CtrlOrCmd+Shift+ArrowLeft":D5,"CtrlOrCmd+Shift+ArrowRight":_5,"CtrlOrCmd+ArrowUp":M5,"CtrlOrCmd+ArrowDown":Ap,"CtrlOrCmd+Shift+ArrowUp":U5,"CtrlOrCmd+Shift+ArrowDown":xp,"CtrlOrCmd+A":bp,Home:V5,End:$5,"Shift+Home":F5,"Shift+End":K5,PageUp:W5,PageDown:q5,"Shift+PageUp":Y5,"Shift+PageDown":Q5,"CtrlOrCmd+Z":LU,"CtrlOrCmd+Shift+Z":IU,Enter:lT,Delete:aT,Backspace:cT,"Shift+Enter":uT,"CtrlOrCmd+Shift+V":fT,"CtrlOrCmd+Shift+C":wp};function mT(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function gT(n,t,e){if(t.type==="embed"){const o=t.embedData,s=o.src;if(s&&typeof s=="string"){const l=e.get(s);if(l)o.src=l;else{let c="";s.split("|").forEach(h=>{const C=e.get(h);C&&(c+=c?`|${C}`:`${C}`)}),c&&(o.src=c)}}return}const r=t.text;r&&r.forEach(o=>{if(o.attributes&&o.attributes.src&&typeof o.attributes.src=="string"){const s=e.get(o.attributes.src);s&&(o.attributes.src=s)}});const i=t.children;i&&i.forEach(o=>{n.blocks[o].forEach(l=>{gT(n,l,e)})})}function pT(n,t,e){if(e.size===0)return;t.blocks.root.forEach(i=>{const o=n.editorBlocks.getBlockClass(i.type);o.replaceResources?o.replaceResources(i,e):gT(t,i,e)})}async function HU(n,t){let e=t.filter(s=>s.indexOf(":")===-1);const r=[];e.forEach(s=>{const l=s.split("|");r.push(...l)}),e=Array.from(new Set(r)),e=r;const i=await n.doc.addResources(e),o=new Map;if(e.length!==i.length)return o;for(let s=0;s<e.length;s++)o.set(e[s],i[s]);return o}function jU(n,t){var l,c,d,h;const r=t.meta.serverId;if(!r||typeof r!="string")return!1;const i=(c=(l=n.doc).getServerMeta)==null?void 0:c.call(l);if(!i)return!1;const o=/.*(?=\/)/;return((d=(i.serverId||"").match(o))==null?void 0:d[0])===((h=r.match(o))==null?void 0:h[0])}async function Sp(n,t){const r=t.meta.resources;if(!r||Object.keys(r).length===0)return;let i=new Map;if(jU(n,t)){const s=Array.from(Object.keys(r));i=await HU(n,s),pT(n,t,i)}const o=new Map;Object.entries(r).forEach(([s,l])=>{i.get(s)===void 0&&s!==l&&o.set(s,l)}),o.size!==0&&pT(n,t,o)}async function zU(n,t,e){await Sp(n,t),n.undoManager.runInGroup(()=>{const{start:r,end:i}=n.selection.range,o=n.getBlockById(r.blockId);if(r.blockId===i.blockId&&ge(o)){const s=it(o),l=n.getBlockIndex(o),[c]=n.insertDocAt(s,l+1,t,e);c&&n.selection.selectBlock(c,dt(n,c))}else{n.clearSelectedContents();const{block:s,offset:l}=Ba(n);n.insertDoc(s,l,t,e)}})}const GU=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function WU(n){let t;for(const e of GU)if(t=n[e],t)break;return t||null}class qU{constructor(t){m(this,"editor");m(this,"handlers",[]);m(this,"hookExecutionAttempt",(t,e,r)=>{for(let i=0;i<this.handlers.length;i++){const o=this.handlers[i];if(o.handleBeforeCopy){const s=o.handleBeforeCopy(this.editor,e,r);if(s===!0)return!0;if(typeof s=="object"&&s!=null)return s}}});m(this,"onPasteText",async(t,e)=>{const r=new DataTransfer;r.setData("text/plain",t);const i=await this.editor.dataConverter.fromData(this.editor,r,e);if(i){const o=[];this.pasteDocs(i,null,o)}});this.editor=t}onInsertText(t,e){if(!nt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:r,blockIndex:i,offset:o}=Ba(this.editor);this.handleBeforeInsertText(r,i,o,e)||(this.defaultInsertText(this.editor,r,i,o,e),this.handleAfterInsertText(r,i,o,e),this.editor.selection.updateLastCaretRect())}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const r=this.handlers[e];r.handleChanged&&r.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const r=this.handlers[e];r.handleRemoteChanged&&r.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){if(!nt(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:r,offset:i}=Ba(this.editor);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,r,i)}}onUpdateCompositionText(t,e,r){if(!nt(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText(e,r),this.editor.selection.caret.update();const{containerId:i,blockIndex:o,offset:s}=Ba(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,i,o,s,r)}this.editor.selection.updateLastCaretRect()}onCopy(t){FU(this.editor,t,this.hookExecutionAttempt)}onCopyWithoutEvent(){KU(this.editor,this.hookExecutionAttempt)}onCut(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeCut&&i.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const r=this.editor.selection.focusedBlock;ge(r)&&this.editor.deleteBlock(r)}else Sh(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;const e=this.editor.dataConverter.fromData(this.editor,t.clipboardData),r=Array.from(t.clipboardData.files);e.then(async i=>{i&&this.pasteDocs(i,t,r)})}onFocus(){z(this.editor.rootElement,"active")}onBlur(){ot(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,r)=>{var s,l;const i=(s=e.order)!=null?s:1;return((l=r.order)!=null?l:1)-i})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,r,i))return!0}return!1}handleAfterInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,r,i))return!0}return!1}handleBeforeKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,r,i,o){rp(this.editor,o)}defaultHandleKeydown(t,e){return mT(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePasteDoc&&await i.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await zU(this.editor,t,e);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPasteDoc&&await i.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e,r){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,e,t,r))return}const i=WU(t);if(!!i){await this.pasteDoc(i);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}forEach(t){this.handlers.forEach(t)}}function XU(n,t,e){const r=Hi(t,e);return r.remove(),r}I("copy-dom-attributes");const CT=["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 YU(n,t){for(let l=0;l<CT.length;l++){const c=CT[l];t[c]=n[c]}const e=n.attributes,r=t.attributes,i=[],o=[];for(let l=0;l<e.length;l++){const c=e[l],d=r.getNamedItem(c.name);d?d.value!==c.value&&(d.value=c.value,o.push(c)):i.push(c)}const s=[];for(let l=0;l<r.length;l++){const c=r[l];e.getNamedItem(c.name)||s.push(c)}i.forEach(l=>{t.setAttribute(l.name,l.value)}),o.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function ET(n){const t=Array.from(n.childNodes).filter(e=>!Mv(e));return t.forEach(e=>{e.remove()}),t}function AT(n,t,e){var d;const r=n.getContainerById(t),i=Hi(r,e),o=Ko(i),s=n.doc.getBlockData(t,e),l=Jt(n,i);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,i,s))n.editorBlockRenders.updateBlock(n,o,i,s);else{const h=n.editorBlocks.createBlock(o,r,s),C=ET(h);ET(i),C.forEach(x=>{i.appendChild(x)});const E=Yd(h);if(E){const x=Yd(i);x&&x.remove(),i.appendChild(E)}YU(h,i)}Xv(n,i,s),n.blockHooks.forEach(h=>{var C;(C=h.update)==null||C.call(h,n,o,r,i,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const QU=I("transform-selection");function xT(n,t,e,r){const{range:i}=n.selection,{anchor:o,focus:s}=i;if(o.blockId!==t&&s.blockId!==t)return i;p(QU,o.isSimple()&&s.isSimple(),"invalid text pos type");let l=o;if(o.blockId===t){const d=hn.transformCursor(o.offset,e,r);l=ct(t,d,"normal")}let c=s;if(s.blockId===t){const d=hn.transformCursor(s.offset,e,r);c=ct(t,d,"normal")}return Xe(n,{anchor:l,focus:c})}const JU=I("handle-block-text-changed");function ZU(n,t,e,r,i){const o=n.getContainerById(t),s=Hi(o,e),l=n.doc.getBlockData(t,e);if(p(JU,l.text,"no block text"),Lv(n,s).setBlockText(n,s,l.text),!i){const c=xT(n,l.id,r,i);n.selection.setRange(c,{noScroll:!0})}}function tO(n,t){const e=mt.default(n);return t.delete.forEach(i=>{delete e[i]}),{...e,...t.insert}}function bT(n,t,e,r){const i=Jt(n,t);i.handleDeleteBlock&&i.handleDeleteBlock(n,t,e,r),n.emit("blockDeleted",n,t,e,r)}function eO(n,t,e,r){const i=n.getBlockByIndex(t,e);i.querySelectorAll('[data-type="editor-block"]').forEach(o=>{bT(n,o,r,{child:!0})}),bT(n,i,r,{child:!1})}const Nr=I("editor-doc");class nO extends aa{constructor(e,r,i){super();m(this,"localEvents",[]);this.editor=e,this.externalDoc=r,this.externalDoc.registerCallback(this),this.registerLocalEvents(i)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var r,i;return(i=(r=this.externalDoc).getVersionHelper)==null?void 0:i.call(r)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}findContainerBlocks(e){return this.externalDoc.findContainerBlocks(e)}getBlockData(e,r){return this.externalDoc.getBlockData(e,r)}verifyBlockWritable(e,r){const i=this.editor.getBlockByIndex(e,r);p(Nr,this.editor.isBlockWritable(i),`block is not writable, ${e}, ${r}`)}localUpdateBlockText(e,r,i,o){p(Nr,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const s=this.getBlockData(e,r),l=s.text;p(Nr,l,`no text, ${e}, ${r}`);const c=xT(this.editor,s.id,i,!0),d=hn.apply(l,i);this.localEvents.forEach(C=>C.onBeforeUpdateBlockText(e,s.id,l,d,c.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,r,i);return this.editor.selection.setRange(c,o),h}localUpdateBlockData(e,r,i,o){p(Nr,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,r);if(!this.editor.isBlockWritable(s)){const h=Array.from(i.delete).filter(E=>E!=="comments"),C=Object.keys(i.insert).filter(E=>E!=="comments");(h.length>0||C.length>0)&&p(Nr,!1,`block is not writable, comment supported only, ${JSON.stringify(i)}}`)}const l=mt.default(this.getBlockData(e,r)),c=mt.default(tO(l,i));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,c,o));const d=this.externalDoc.localUpdateBlockData(e,r,i,o);return this.editor.selection.setRange(Vo(this.editor,o)),d}localInsertBlock(e,r,i,o,s){p(Nr,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(e,r,i,o));const l=this.externalDoc.localInsertBlock(e,r,i,o);return s!=null&&s.noFocus||this.editor.selection.setRange(Vo(this.editor,o),s),l}localDeleteBlock(e,r,i){p(Nr,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const o=mt.default(this.getBlockData(e,r));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,r,o,i));const s=this.externalDoc.localDeleteBlock(e,r,i);return this.editor.selection.setRange(Vo(this.editor,i)),s}localDeleteChildContainers(e){return p(Nr,!this.editor.readonly,"editor is readonly"),e.forEach(r=>{const i=mt.default(this.getContainerBlocks(r));this.localEvents.forEach(o=>o.onBeforeDeleteChildContainer(r,i))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainers(e){p(Nr,!this.editor.readonly,"editor is readonly");const r=mt.default(e);r.forEach(i=>{this.localEvents.forEach(o=>o.onBeforeInsertChildContainer(i.containerId,i.blocks))}),this.externalDoc.localInsertChildContainers(r)}onRequestReload(e){Nr.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(i=>{var o;return(o=i.onRequestReload)==null?void 0:o.call(i,e)});const r=!1;this.editor.emit("docChanged",this.editor,r)}onUpdateBlockText(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,r,i,o)}),ZU(this.editor,e,r,i,o),this.editor.emit("docChanged",this.editor,o)}onUpdateBlockData(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,o)}),AT(this.editor,e,r),this.editor.emit("docChanged",this.editor,o)}onInsertBlock(e,r,i,o){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,e,r,i,o)});const s=this.editor.getContainerById(e);NI(this.editor,s,r,i),this.editor.emit("docChanged",this.editor,o)}onDeleteBlock(e,r,i){eO(this.editor,e,r,i),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,i)});const o=this.editor.getContainerById(e);XU(this.editor,o,r),this.editor.emit("docChanged",this.editor,i)}onInsertChildContainer(e,r,i){this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,e,r,i)})}onDeleteChildContainer(e,r){this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,e)})}onStatusChanged(e){this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)})}onError(e){this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}uploadResource(e,r){return this.externalDoc.uploadResource(e,r)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,r){return this.externalDoc.buildResourceUrl(e,r)}request(e,r){return this.externalDoc.request(e,r)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}triggerReAuth(){var e,r;return(r=(e=this.externalDoc).triggerReAuth)==null?void 0:r.call(e)}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,r,i;return(i=(r=(e=this.externalDoc).getServerMeta)==null?void 0:r.call(e))!=null?i:{}}reset(e){Nr.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function vT(n,t){if(n.length===0){n.push(t);return}const e=n[n.length-1];if(!e.combinable(t)){n.push(t);return}e.combine(t)}const Ph=I("undo-action");class Sa{constructor(t,e,r){m(this,"beforeRange");m(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=r}undo(t){return!1}redo(t){return!1}combinable(t){return p(Ph,t,"no other action"),!1}combine(t){p(Ph,!1,"no other")}setAfterRange(t){this.afterRange&&Ph.warn("after range has already set"),this.afterRange=t}findContainerById(t,e){return!!t.doc.findContainerBlocks(e)}findBlockById(t,e){const r=t.doc.findContainerBlocks(this.containerId);return r?r.some(i=>i.id===e):!1}checkBlockData(t,e){if(Array.isArray(e.children)){const r=t.doc.toJSON();for(let i=0;i<e.children.length;i++){const o=e.children[i];if(!r.blocks[o])return Ph.warn(`container (${o}) not found, deleted by others?`),!1}}return!0}}const La=I("block-action");class BT extends Sa{constructor(e,r,i,o,s){super(e,r,s);m(this,"blockData");m(this,"blockIndex");this.blockData=mt.default(o),this.blockIndex=i}deleteBlock(e,r){if(!this.findContainerById(e,this.containerId))return La.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockData.id))return La.warn(`block (${this.blockData.id}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const o=e.getBlockById(this.blockData.id);if(!o)return!1;try{p(La,this.blockIndex===Bt(o),"invalid block index"),Rh(e,o,Vo(e,r))}catch(s){La.warn(s.message),e.selection.selectBlock(o,0)}return!0}insertBlock(e,r){if(!this.findContainerById(e,this.containerId))return La.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.checkBlockData(e,this.blockData))return!1;try{ya(e,this.containerId,this.blockIndex,mt.default(this.blockData),r)}catch(i){La.warn(i.message);const o=e.doc.getContainerBlocks(this.containerId),s=Math.min(o.length-1,this.blockIndex),l=e.getBlockByIndex(this.containerId,s);e.selection.selectBlock(l,0)}return!0}}I("insert-block-action");class rO extends BT{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class iO extends BT{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class oO extends Sa{constructor(e){super(e,at(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){vT(this.actions,e),this.afterRange=e.afterRange}undo(e){let r=!1;return this.actions.concat().reverse().forEach(i=>{i.undo(e)&&(r=!0)}),r}redo(e){let r=!1;return this.actions.forEach(i=>{i.redo(e)&&(r=!0)}),r}setAfterRange(e){this.afterRange=e;const r=this.actions[this.actions.length-1];!r||r instanceof Sa&&(r.afterRange||r.setAfterRange(e))}}const Xo=I("update-block-data-action");class Fh extends Sa{constructor(e,r,i,o,s,l){super(e,r,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=i,p(Xo,this.blockId===o.id,"invalid block id"),p(Xo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(o),this.afterBlockData=mt.default(s),p(Xo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return Xo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(Xo,i,"no container"),Ih(e,r,Fh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return Xo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;p(Xo,e,"no editor");const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(Xo,i,"no container"),Ih(e,r,Fh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const r=mt.default(e);return delete r.id,delete r.type,r}}const rl=I("update-block-text-action");class ku extends Sa{constructor(e,r,i,o,s,l){super(e,r,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=i,this.beforeRichTextData=mt.default(o),this.afterRichTextData=mt.default(s),this.type=ku.calType(o,s)}static calType(e,r){p(rl,e,"no old data"),p(rl,r,"no new data");const o=hn.diff(e,r),s=new Set;let l=!1;const c=h=>ov(h)?`cjk_${h}`:rv(h)?"number":$d(h)?"space":iv(h)?"letter":"unknown";let d=!1;return o.forEach(h=>{h.insert?h.insert===" "?s.add("insert_letter"):typeof h.insert=="string"&&h.insert.startsWith(" ")&&h.insert.length>1?(l=!0,d=!0,s.add(`insert_${c(h.insert.substr(1))}`)):s.add(`insert_${c(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!this.findContainerById(e,this.containerId))return rl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return rl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(Lh(e,i,this.beforeRichTextData),!0):!1}redo(e){if(!this.findContainerById(e,this.containerId))return rl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return rl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(Lh(e,i,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof ku)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const r=e.beforeRange,i=r.anchor;if(!i.isSimple())return!1;const o=this.afterRange;if(!o)return!1;const s=o.anchor;return!(!s.isSimple()||s.blockId!==r.anchor.blockId||s.offset!==i.offset)}combine(e){p(rl,e instanceof ku,"invalid action type");const r=e;this.afterRichTextData=r.afterRichTextData,this.afterRange=e.afterRange}}const TT=I("child-container-action");class yT extends Sa{constructor(t,e,r){super(t,e,t.selection.range.toDocRange()),this.blocks=r}deleteChildContainer(t){return this.findContainerById(t,this.containerId)?(t.doc.localDeleteChildContainers([this.containerId]),!0):(TT.warn(`container (${this.containerId}) not found, deleted by others?`),!1)}insertChildContainer(t){return this.findContainerById(t,this.containerId)?(TT.warn(`container (${this.containerId}) already exists`),!1):(t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:mt.default(this.blocks)}]),!0)}}class sO extends yT{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class lO extends yT{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Pr=I("undo");class aO{constructor(t){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(this,"handleSelectionChange",t=>{if(this.currentGroup){this.currentGroup.setAfterRange(t.selection.range.toDocRange());return}const e=this.actions[this.actions.length-1];!e||e.afterRange||e.setAfterRange(t.selection.range.toDocRange())});this.editor=t,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(t){this.currentGroup?this.currentGroup.addAction(t):(vT(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(p(Pr,!this.currentGroup,"current group already exists"),this.currentGroup=new oO(this.editor),this.groupCounter=1):(p(Pr,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){p(Pr,this.currentGroup,"current group not exists"),p(Pr,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Pr.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw Pr.error(`failed to run action: ${e.message}`),e}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const t=this.actions[this.undoCursor];if(t.undo(this.editor)){try{this.editor.selection.setRange(Vo(this.editor,t.beforeRange))}catch(e){Pr.error(`undo: failed to restore caret pos: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const t=this.actions[this.undoCursor];if(this.undoCursor+=1,t.redo(this.editor)){try{const e=t.afterRange;e?this.editor.selection.setRange(Vo(this.editor,e)):Pr.warn("no after range")}catch(e){Pr.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,r,i,o){this.undoRedoing||(this.prepareSaveUndoState(),hn.diff(r,i).length!==0&&this.addAction(new ku(this.editor,t,e,r,i,o)))}onBeforeUpdateBlockData(t,e,r,i,o){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Fh(this.editor,t,e,r,i,o);this.addAction(s)}onBeforeInsertBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),p(Pr,e>=0,"invalid block index"),p(Pr,r,"no block data"),this.addAction(new rO(this.editor,t,e,r,i)))}onBeforeDeleteBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new iO(this.editor,t,e,r,i)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new sO(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new lO(this.editor,t,e)))}}class cO{async fromData(t,e){const r=e.getData("text/x-ones-editor-doc");if(r)return{"text/x-ones-editor-doc":JSON.parse(r)}}}class uO{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new cO)}prepareData(t){const e=new DataTransfer;for(let r=0;r<this.converterTypes.length;r++)e.setData(this.converterTypes[r],t.getData(this.converterTypes[r]));return e}async fromData(t,e,r){let i={};const o=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,o,r);l&&(i={...i,...l})}return i}addConverter(t){this.converters.push(t)}}function fO(n){n.editorBlocks.registerBlockClass(On),n.editorBlocks.registerBlockClass(h3),n.editorBoxes.registerBoxClass(_B),n.editorBoxes.registerBoxClass(MB),n.editorBoxes.registerBoxClass(NB),n.editorBoxes.registerBoxClass(PB),n.editorInsertions.registerInsertionClass(FB),n.editorBlockRenders.registerRender(new _v)}function dO(n,t){fO(n),t!=null&&t.blocks&&t.blocks.forEach(e=>n.editorBlocks.registerBlockClass(e)),t!=null&&t.boxes&&t.boxes.forEach(e=>n.editorBoxes.registerBoxClass(e)),t!=null&&t.embeds&&t.embeds.forEach(e=>n.editorEmbeds.registerEmbedClass(e)),t!=null&&t.insertions&&t.insertions.forEach(e=>n.editorInsertions.registerInsertionClass(e)),t!=null&&t.decorators&&t.decorators.forEach(e=>n.editorDecorators.registerDecorator(e)),t!=null&&t.dataConverters&&t.dataConverters.forEach(e=>n.dataConverter.addConverter(e)),t!=null&&t.commandProviders&&t.commandProviders.forEach(e=>n.editorCommandProviders.registerCommandProvider(e)),t!=null&&t.textRenders&&t.textRenders.forEach(e=>n.editorBlockRenders.registerRender(e))}const Kh=I("range-commands");function kT(n,t){n.forEach(e=>{e.source=t,e.children&&kT(e.children,t)})}function RT(n,t){n.forEach(e=>{e.group=t,e.children&&RT(e.children,t)})}function wT(n,t,e,r){const i=lt(t);p(Kh,i===e.start.blockId,"invalid start range"),p(Kh,i===e.end.blockId,"invalid end range");const o=n.editorCommandProviders.getCommandProviders();let s=[];if(o.forEach(l=>{const c=l.getAvailableCommands(n,t,e);kT(c,r),RT(c,l.id),s.push(...c)}),o.forEach(l=>{if(l.filterCommands){const c=l.filterCommands(n,t,e,s);c&&(s=c)}}),Mt(n,t)){if(!ga(e.start))return s;p(Kh,!e.start.isSimple(),"invalid start pos"),p(Kh,!e.end.isSimple(),"invalid end pos");const l=e.start.childContainerId,c=Lr(n,l),h=fe(c)[0];if(h){const C=dt(n,h),E=Xe(n,{anchor:ct(h,0,"home"),focus:ct(h,C,"end")}),x=wT(n,h,E,r);s.push(...x)}}return s}function ST(n,t){const e=n.getEditor(),r=n.getSelectedBlocks(),i=[],o=n.isReverse()?r[0]:r[r.length-1],s=Xe(e,{anchor:o.start,focus:o.end});return wT(e,o.block,s,t).forEach(c=>{i.push(c)}),i}function LT(n,t,e,r,i,o){var h;const s=n.editorCommandProviders.getCommandProviders();for(let C=0;C<s.length;C++){const E=s[C];if(E.beforeExecuteCommand&&E.beforeExecuteCommand(n,t,e,r,i))return!1}const l=n.editorCommandProviders.getCommandProvider(r.group),c={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,r,i,{}))return o[lt(t)]=c,!0;let d=!1;return Mt(n,t)&&pa(n,t,e.start,e.end).forEach(E=>{fe(E).forEach(v=>{const k=dt(n,v),L=Xe(n,{anchor:ct(v,0,"home"),focus:ct(v,k,"end")});LT(n,v,L,r,i,o)&&(d=!0)})}),s.forEach(C=>{C.afterExecuteCommand&&C.afterExecuteCommand(n,t,e,r,i,o)}),d}function IT(n,t,e){const r=n.getEditor(),i={},o=r.editorCommandProviders.getCommandProvider(t.group);return o.executeRangeCommand&&o.executeRangeCommand(r,n,t,e,i)||(n.getSelectedBlocks().forEach(l=>{const c=Xe(r,{anchor:l.start,focus:l.end});LT(r,l.block,c,t,e,i)}),r.focus()),i}const hO=I("command-providers");class DT{constructor(t){m(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(r=>r.id===t);return p(hO,e,`no command provider, id=${t}`),e}getCommands(t,e){return ST(t,e)}executeCommand(t,e,r){return this.editor.emit("beforeExecCommand",this.editor,e,{source:e.source}),this.editor.undoManager.runInGroup(()=>IT(t,e,r))}getEmptyBlockTextAttributes(t,e){let r={};if(this.providers.forEach(i=>{var s;const o=(s=i.getEmptyBlockTextAttributes)==null?void 0:s.call(i,t,e);o&&(r={...r,...o})}),Object.keys(r).length!==0)return r}}function mO(n,t){const e=it(t),r=at(e),i=Bt(t);AT(n,r,i)}const _T=I("update-block-text");function gO(n,t){const e=n.getBoxById(t.id),r=J(e);p(_T,r,"no parent block"),p(_T,nt(n,r),"not a text block");const i=n.getBlockText(r),o=yB(i,"id",t.id,t);s5(n,r,o)}function pO(n,t){for(const e of n.blockHooks)if(e.writable){const r=e.writable(n,t);if(typeof r=="boolean")return r}return!0}function CO(n){if(n.readonly)return!1;const t=fi(n);return!!n.isBlockWritable(t.map(e=>e.block))}class EO{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}getItem(t){return window.localStorage.getItem(this.getKey(t))}setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class AO{constructor(){m(this,"shortcuts",[])}handleKeyboardEvents(t,e){const r=this.shortcuts;for(const i of r){const o=Object.entries(i);for(const[s,l]of o)if(si(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const eo=I("editor");class xO extends Be.TypedEmitter{constructor(e,r,i){var o,s,l,c,d,h,C,E;super();m(this,"parent");m(this,"rootElement");m(this,"contentElement");m(this,"rootContainerObject");m(this,"rootContainer");m(this,"input");m(this,"selection");m(this,"selectionHandler");m(this,"doc");m(this,"id");m(this,"clientId");m(this,"compositingText","");m(this,"undoManager");m(this,"shortcuts",new AO);m(this,"dataConverter",new uO);m(this,"editorBlocks",new c3(this));m(this,"editorBoxes",new OB(this));m(this,"editorInsertions",new VB(this));m(this,"editorEmbeds",new f3(this));m(this,"editorDecorators",new $B(this));m(this,"editorCommandProviders",new DT(this));m(this,"editorBlockRenders",new RI(this));m(this,"blockHooks",[]);m(this,"domEvents",new xU(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new qU(this));m(this,"settingsProvider");m(this,"_readonly",!1);m(this,"getColor",e=>{const r=this.options.colors;return r.length===0?"#FF1A75":r[e%r.length]});eo.debug("create editor"),this.setMaxListeners(100),this.options={colors:(o=i==null?void 0:i.colors)!=null?o:["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"],componentsOptions:(l=(s=i==null?void 0:i.components)==null?void 0:s.options)!=null?l:{},scrollContainer:i==null?void 0:i.scrollContainer,enableComments:(c=i==null?void 0:i.enableComments)!=null?c:!0},this.settingsProvider=(d=i==null?void 0:i.settingsProvider)!=null?d:new EO(this),dO(this,i==null?void 0:i.components),this.blockHooks.push(...(C=(h=i==null?void 0:i.components)==null?void 0:h.blockHooks)!=null?C:[]),this.id=(E=i==null?void 0:i.id)!=null?E:tt(),this.clientId=tt(),this.undoManager=new aO(this),this.doc=new nO(this,r,this.undoManager),this.parent=e,this.rootElement=B("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=B("div",["editor-content"],this.rootElement),this.rootContainerObject=s3(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new PM(this,this.inputHandlers),this.selection=new kU(this),this.selectionHandler=new SU(this),i!=null&&i.shortcuts&&this.shortcuts.shortcuts.push(...i.shortcuts),ue.isMobile&&z(this.rootElement,"mobile"),ue.isSafari&&z(this.rootElement,"safari"),this._readonly&&z(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?z(this.rootElement,"readonly"):ot(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:Ge(this.rootContainer)}addCustom(e,r){const i=this.customs.get(e);if(i)return i;const o=r(this);return this.customs.set(e,o),o}getCustom(e){const r=this.customs.get(e);return p(eo,r,`${e} does not exists`),r}replaceCustom(e,r){const i=this.customs.get(e);return i&&i.destroy(),this.customs.set(e,r),r}findCustom(e){return this.customs.get(e)}findCustomByType(e){const r=this.customs.values();for(const i of r)if(i instanceof e)return i;return null}destroyCustom(e){const r=this.customs.get(e);r&&(this.customs.delete(e),r.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,r,i){return this.editorBlocks.createBlock(e,r,i)}createBox(e,r){return this.editorBoxes.createBox(e,r)}createInsertion(e,r){return this.editorInsertions.createInsertion(e,r)}destroy(){eo.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(e=>e.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(e,r){cp(this,e,r)}isWritable(){return CO(this)}isBlockWritable(e){return pO(this,e)}getChildContainerData(e){const r=this.doc.getContainerBlocks(e);return(!r||!Array.isArray(r))&&(p(eo,r,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),p(eo,Array.isArray(r),`container data is not an array: ${JSON.stringify(r)}`)),r}createChildContainer(e,r,i){return l3(this,e,r,i)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const r=this.rootContainer.querySelector(`#${e}`);return r&&p(eo,$s(r),"not an valid block element"),r!=null?r:null}findBoxById(e){const r=this.rootContainer.querySelector(`#${e}`);return r&&p(eo,Qd(r),"not an valid box element"),r!=null?r:null}getBlockById(e){const r=this.findBlockById(e);return p(eo,r,`no block, id=${e}`),r}getBoxById(e){const r=this.findBoxById(e);return p(eo,r,`no box, id=${e}`),r}getBlockByIndex(e,r){const i=this.getContainerById(e);return Hi(i,r)}findBlockByIndex(e,r){const i=this.getContainerById(e);return wv(i,r)}getBlockIndex(e){if(typeof e=="string"){const r=this.getBlockById(e);return Bt(r)}return Bt(e)}getContainerById(e){return Lr(this,e)}getParentContainer(e){return it(e)}reloadBlock(e){mO(this,e)}contains(e){const r=e instanceof Element?e:e.parentElement;return r?r.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,r,i,o,s){const l={blockId:i.id,offset:0},c={anchor:l,focus:l};return ya(this,e,r,i,o!=null?o:c,s)}insertEmbed(e,r,i,o,s){const l={id:tt(),type:"embed",embedType:i,embedData:o};return this.insertBlock(e,r,l,s)}deleteBlock(e,r){lp(this,e,r)}mergeTextBlock(e,r){return r5(this,e,r)}breakTextBlock(e,r,i){return ka(this,e,r,i).newBlock}getTextPosition(){return Ba(this)}getBlockString(e,r){const i=this.getBlockText(e);return de(i,r)}getBlockData(e){return zo(this,e)}getBoxData(e){return IB(this,e)}getBlockText(e){return Tn(this,e)}setBlockText(e,r){s5(this,e,r)}deleteTextFromBlock(e,r,i,o){return op(this,e,r,i,o)}insertTextToBlock(e,r,i,o){return QB(this,e,r,i,o)}insertBoxToBlock(e,r,i){return JB(this,e,r,i)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,r,i,o){c5(this,e,r,i,o)}insertDocAt(e,r,i,o){return dp(this,e,r,i,o)}deleteChildContainers(e){n5(this,e)}replaceBlockText(e,r){return Lh(this,e,r)}updateBlockData(e,r,i){const o={...this.getBlockData(e),...r},{id:s,type:l,...c}=o;return Ih(this,e,c,(i!=null?i:this.selection.range).toDocRange())}updateEmbedData(e,r,i){return l5(this,e,r,i)}updateBoxData(e){gO(this,e)}getSelectedText(){const e=wa(this);return Go(this,e)}clearSelectedContents(){Sh(this)}insertTextBlock(e,r,i,o){const s=mi(e!=null?e:"");return e5(this,s,r,i,o==null?void 0:o.newRange,o==null?void 0:o.insertBlockOptions)}updateCompositionText(e,r){if(e&&!r&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!r){ip(this);return}r?(this.compositingText="",Gc()?e||ip(this):rp(this,e)):(this.compositingText=e,ZB(this))}}function Ru(n,t,e){return new xO(n,t,e)}function bO(n){const t=(r,i)=>{const o=r.findIndex(l=>l.id===i.id);if(o===-1){r.push(i);return}const s=r[o];if(s.value!==i.value){r.splice(o,1);return}if(!!s.states){if(!i.states){s.states=[];return}s.states=wg.default(s.states,i.states)}},e=[];return n.forEach(r=>{r.forEach(i=>{t(e,i)})}),e}const vO=["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"];class wu extends Be.TypedEmitter{constructor(e){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=e&&e.length>0?e:vO}setCursor(e){this.addUser(e.user);const r=this.cursors.get(e.user.userId);if(r&&$c.default(r,e))return;this.cursors.set(e.user.userId,e);const i=new Set([e.range.anchor.blockId,e.range.focus.blockId]),o=new Set(i);r&&new Set([r.range.anchor.blockId,r.range.focus.blockId]).forEach(l=>{i.has(l)||o.add(l)}),this.emit("remote-carets-change",[...o])}addUsers(e){this.addingUser=!0,e.forEach(r=>this.addUser(r)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var r;return(r=this.users.get(e))!=null?r:null}removeUser(e){this.users.delete(e),this.emit("change",Array.from(this.users.values()));const r=this.cursors.get(e);if(r){const i=new Set(new Set([r==null?void 0:r.range.anchor.blockId,r==null?void 0:r.range.focus.blockId]));this.cursors.delete(e),this.emit("remote-carets-change",[...i])}}updateUsers(e){this.users.forEach(r=>{e.find(i=>i.userId===r.userId)||this.removeUser(r.userId)}),this.users.clear(),this.addingUser=!0;try{e.forEach(r=>{this.addUser(r)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const r=new Map;return Array.from(this.cursors.values()).filter(i=>i.range.anchor.blockId===e&&Ch(i.range)).forEach(i=>{const o=i.range.focus.offset;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}),r}getCursors(e){return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e||r.range.focus.blockId===e)}onUpdateBlockText(e,r,i){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(Ch(l.range)){const{anchor:c,focus:d}=l.range;c.blockId===e.id&&(c.offset=hn.transformCursor(c.offset,r,i)),d.blockId===e.id&&(d.offset=hn.transformCursor(d.offset,r,i))}})}getFixedUserColor(e,r){let i=0;Array.from(e).forEach(s=>{i+=s.charCodeAt(0)});const o=i%this.colors.length;return this.colors[o]}destroy(){this.removeAllListeners()}}const on=I("local-doc");class Lp extends aa{constructor(e,r){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[mi("")]}},this.serviceUrl=(r==null?void 0:r.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}findContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,r){const i=this.getContainerBlocks(e);p(on,i,`no container data: ${e}`);const o=i[r];return p(on,o,`no block data: ${r}`),o}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(on,o.text,"no text for data");const s=hn.apply(o.text,i);return o.text=s,p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,e,r,i,!0)}),s}localUpdateBlockData(e,r,i){const o=this.getBlockData(e,r);return i.delete.forEach(s=>delete o[s]),Object.entries(i.insert).forEach(([s,l])=>{o[s]=l}),p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,!0)}),o}localInsertBlock(e,r,i){const o=this.getContainerBlocks(e);return p(on,o,`no container data: ${e}`),p(on,r>=0&&r<=o.length,`invalid block index: ${r}, ${o.length}`),o.splice(r,0,i),p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,r,i,!0)}),i}localDeleteBlock(e,r){const i=this.getContainerBlocks(e);p(on,i,`no container data: ${e}`),p(on,r>=0&&r<=i.length,`invalid block index: ${r}, ${i.length}`);const o=i[r];return i.splice(r,1),p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,!0)}),o}localInsertChildContainers(e){e.forEach(({containerId:r,blocks:i})=>{this.doc.blocks[r]=i,p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,r,i,!0)})})}localDeleteChildContainers(e){on.debug(`delete child containers: ${e}`),e.forEach(r=>{p(on,this.doc.blocks[r],`no child container: ${r}`),delete this.doc.blocks[r]}),e.forEach(r=>{p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,r,!0)})})}uploadResource(e,r){p(on,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,r){p(on,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new wu}setDoc(e){this.doc=mt.default(e),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,"change doc")})}destroy(){this.clearCallbacks()}}class BO{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function Ip(n,t,e){n.addCustom(t,()=>{var o;const r=(o=e())!=null?o:void 0;return new BO(r)})}const MT=I("find-block");function UT(n,t){const e=zs(t);if(!e){if(dr(t))return null;const r=Hs(t);return p(MT,r,"no parent block"),UT(n,r)}return Mt(n,e)?Ca(n,e,{visibleOnly:!0}):e}function OT(n,t){const e=Gs(t);if(!e){if(dr(t))return null;const r=Hs(t);return p(MT,r,"no parent block"),OT(n,r)}return Mt(n,e)?g1(n,e,{visibleOnly:!0}):e}const TO=I("remote-cursor");class yO{constructor(){m(this,"remoteUsers",new wu)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const r=e;this.handleUpdateUsers(r.users)}else e.type==="caret"?this.handleUpdateCaret(e):TO.debug(`unknown remote message received: ${t}`)}handleUpdateUsers(t){this.remoteUsers.updateUsers(t)}handleUpdateCaret(t){const e=this.remoteUsers.findUser(t.userId);!e||this.remoteUsers.setCursor({oneseditor:"cursor",user:e,range:t.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function kO(n){const{blocks:t,meta:e,comments:r,...i}=n;return{rootBlocks:t,meta:e,comments:r,childBlocks:i}}function RO(n){const{blocks:t,meta:e,comments:r}=n,{root:i,...o}=t;return{blocks:i,meta:e,comments:r,...o}}function no(n){const{childBlocks:t,meta:e,comments:r,rootBlocks:i}=kO(mt.default(n));return{blocks:{root:i,...t},meta:e,comments:r}}function ro(n){return n==="root"?"blocks":n}function Ia(n){return n==="blocks"?"root":n}const wO={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new fn.default(n)},apply(n,t){const e=new fn.default(n),r=new fn.default(t);return e.compose(r).ops},compose(n,t){const e=new fn.default(n),r=new fn.default(t);return e.compose(r).ops},diff(n,t){const e=new fn.default(n),r=new fn.default(t);return e.diff(r).ops},transform(n,t,e){const r=new fn.default(n);return new fn.default(t).transform(r,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const r=new fn.default(t),i=this.transformCursor(n.index,r,e),o=this.transformCursor(n.index+n.length,r,e);return{...n,index:i,length:o-i}}}};var Yo={},Dp=Rg.default.EventEmitter;Yo.EventEmitter=Dp,Yo.mixin=SO;function SO(n){for(var t in Dp.prototype)n.prototype[t]=Dp.prototype[t]}var NT=["info","warn","error"];function PT(){var n={};NT.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var LO=PT;PT.prototype.setMethods=function(n){n=n||{};var t=this;NT.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var IO=LO,DO=new IO,FT=DO;function il(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,il):this.stack=new Error().stack}il.prototype=Object.create(Error.prototype),il.prototype.constructor=il,il.prototype.name="ShareDBError",il.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_FIXUP_IS_ONLY_VALID_ON_APPLY:"ERR_FIXUP_IS_ONLY_VALID_ON_APPLY",ERR_CANNOT_FIXUP_DELETION:"ERR_CANNOT_FIXUP_DELETION",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_CHANNEL_MISSING:"ERR_QUERY_CHANNEL_MISSING",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_COMPOSE:"ERR_TYPE_DOES_NOT_SUPPORT_COMPOSE",ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE:"ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE",ERR_UNKNOWN_ERROR:"ERR_UNKNOWN_ERROR"};var Vh=il,Su={},KT=_O;function _O(n,t,e,r){var i=function(s,l,c,d){t(c,s,l,"left"),t(d,l,s,"right")},o=n.transformX=function(s,l){e(s),e(l);for(var c=[],d=0;d<l.length;d++){for(var h=l[d],C=[],E=0;E<s.length;){var x=[];if(i(s[E],h,C,x),E++,x.length===1)h=x[0];else if(x.length===0){for(var v=E;v<s.length;v++)r(C,s[v]);h=null;break}else{for(var k=o(s.slice(E),x),L=0;L<k[0].length;L++)r(C,k[0][L]);for(var M=0;M<k[1].length;M++)r(c,k[1][M]);h=null;break}}h!=null&&r(c,h),s=C}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?t([],s[0],l[0],c):c==="left"?o(s,l)[0]:o(l,s)[1]}}var VT={exports:{}},Qo=VT.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||""}},_p=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Mp=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")},$h=function(n){for(var t=0;t<n.length;t++)Mp(n[t])};Qo.apply=function(n,t){var e;$h(t);for(var r=0;r<t.length;r++){var i=t[r];if(i.i!=null)n=_p(n,i.p,i.i);else{if(e=n.slice(i.p,i.p+i.d.length),i.d!==e)throw new Error("Delete component '"+i.d+"' does not match deleted text '"+e+"'");n=n.slice(0,i.p)+n.slice(i.p+i.d.length)}}return n};var io=Qo._append=function(n,t){if(!(t.i===""||t.d===""))if(n.length===0)n.push(t);else{var e=n[n.length-1];e.i!=null&&t.i!=null&&e.p<=t.p&&t.p<=e.p+e.i.length?n[n.length-1]={i:_p(e.i,t.p-e.p,t.i),p:e.p}:e.d!=null&&t.d!=null&&t.p<=e.p&&e.p<=t.p+t.d.length?n[n.length-1]={d:_p(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};Qo.compose=function(n,t){$h(n),$h(t);for(var e=n.slice(),r=0;r<t.length;r++)io(e,t[r]);return e},Qo.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=0),io(t,r)}return t};var Up=function(n,t,e){return t.i!=null?t.p<n||t.p===n&&e?n+t.i.length:n:n<=t.p?n:n<=t.p+t.d.length?t.p:n-t.d.length};Qo.transformCursor=function(n,t,e){for(var r=e==="right",i=0;i<t.length;i++)n=Up(n,t[i],r);return n};var MO=Qo._tc=function(n,t,e,r){if(Mp(t),Mp(e),t.i!=null)io(n,{i:t.i,p:Up(t.p,e,r==="right")});else if(e.i!=null){var i=t.d;t.p<e.p&&(io(n,{d:i.slice(0,e.p-t.p),p:t.p}),i=i.slice(e.p-t.p)),i!==""&&io(n,{d:i,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)io(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)io(n,t);else{var o={d:"",p:t.p};t.p<e.p&&(o.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(o.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),c=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(c!==d)throw new Error("Delete ops delete different text in the same region of the document");o.d!==""&&(o.p=Up(o.p,e),io(n,o))}return n},UO=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Qo.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=UO(n[t]);return n},KT(Qo,MO,$h,io);var Hh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},OO=function(n){return!!n&&n.constructor===Object},Fr=function(n){return JSON.parse(JSON.stringify(n))},Lt={name:"json0",uri:"http://sharejs.org/types/JSONv0"},oo={};Lt.registerSubtype=function(n){oo[n.name]=n},Lt.create=function(n){return n===void 0?null:Fr(n)},Lt.invertComponent=function(n){var t={p:n.p};return n.t&&oo[n.t]&&(t.t=n.t,t.o=oo[n.t].invert(n.o)),n.si!==void 0&&(t.sd=n.si),n.sd!==void 0&&(t.si=n.sd),n.oi!==void 0&&(t.od=n.oi),n.od!==void 0&&(t.oi=n.od),n.li!==void 0&&(t.ld=n.li),n.ld!==void 0&&(t.li=n.ld),n.na!==void 0&&(t.na=-n.na),n.lm!==void 0&&(t.lm=n.p[n.p.length-1],t.p=n.p.slice(0,n.p.length-1).concat([n.lm])),t},Lt.invert=function(n){for(var t=n.slice().reverse(),e=[],r=0;r<t.length;r++)e.push(Lt.invertComponent(t[r]));return e},Lt.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Hh(n[t].p))throw new Error("Missing path")},Lt.checkList=function(n){if(!Hh(n))throw new Error("Referenced element not a list")},Lt.checkObj=function(n){if(!OO(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Lu(n){n.t="text0";var t={p:n.p.pop()};n.si!=null&&(t.i=n.si),n.sd!=null&&(t.d=n.sd),n.o=[t]}function Iu(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}Lt.apply=function(n,t){Lt.checkValidOp(t),t=Fr(t);for(var e={data:n},r=0;r<t.length;r++){var i=t[r];(i.si!=null||i.sd!=null)&&Lu(i);for(var o=null,s=e,l="data",c=0;c<i.p.length;c++){var d=i.p[c];if(o=s,s=s[l],l=d,o==null)throw new Error("Path invalid")}if(i.t&&i.o!==void 0&&oo[i.t])s[l]=oo[i.t].apply(s[l],i.o);else if(i.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=i.na}else if(i.li!==void 0&&i.ld!==void 0)Lt.checkList(s),s[l]=i.li;else if(i.li!==void 0)Lt.checkList(s),s.splice(l,0,i.li);else if(i.ld!==void 0)Lt.checkList(s),s.splice(l,1);else if(i.lm!==void 0){if(Lt.checkList(s),i.lm!=l){var h=s[l];s.splice(l,1),s.splice(i.lm,0,h)}}else if(i.oi!==void 0)Lt.checkObj(s),s[l]=i.oi;else if(i.od!==void 0)Lt.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},Lt.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},Lt.incrementalApply=function(n,t,e){for(var r=0;r<t.length;r++){var i=[t[r]];n=Lt.apply(n,i),e(i,n)}return n};var NO=Lt.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var r=0;r<n.length;r++)if(n[r]!==t[r]&&(!e||r!==n.length-1))return!1;return!0};Lt.append=function(n,t){if(t=Fr(t),n.length===0){n.push(t);return}var e=n[n.length-1];if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Lu(t),Lu(e)),NO(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&oo[t.t]){if(e.o=oo[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var r=t.p,i=0;i<e.o.length-1;i++)t.o=[e.o.pop()],t.p=r.slice(),Iu(t),n.push(t);Iu(e)}}else e.na!=null&&t.na!=null?n[n.length-1]={p:e.p,na:e.na+t.na}:e.li!==void 0&&t.li===void 0&&t.ld===e.li?e.ld!==void 0?delete e.li:n.pop():e.od!==void 0&&e.oi===void 0&&t.oi!==void 0&&t.od===void 0?e.oi=t.oi:e.oi!==void 0&&t.od!==void 0?t.oi!==void 0?e.oi=t.oi:e.od!==void 0?delete e.oi:n.pop():t.lm!==void 0&&t.p[t.p.length-1]===t.lm||n.push(t);else(t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Iu(t),Iu(e)),n.push(t)},Lt.compose=function(n,t){Lt.checkValidOp(n),Lt.checkValidOp(t);for(var e=Fr(n),r=0;r<t.length;r++)Lt.append(e,t[r]);return e},Lt.normalize=function(n){var t=[];n=Hh(n)?n:[n];for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=[]),Lt.append(t,r)}return t},Lt.commonLengthForOps=function(n,t){var e=n.p.length,r=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&r++,e===0)return-1;if(r===0)return null;e--,r--;for(var i=0;i<e;i++){var o=n.p[i];if(i>=r||o!==t.p[i])return null}return e},Lt.canOpAffectPath=function(n,t){return Lt.commonLengthForOps({p:t},n)!=null},Lt.transformComponent=function(n,t,e,r){t=Fr(t);var i=Lt.commonLengthForOps(e,t),o=Lt.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,o!=null&&l>s&&t.p[o]==e.p[o]){if(t.ld!==void 0){var c=Fr(e);c.p=c.p.slice(s),t.ld=Lt.apply(Fr(t.ld),[c])}else if(t.od!==void 0){var c=Fr(e);c.p=c.p.slice(s),t.od=Lt.apply(Fr(t.od),[c])}}if(i!=null){var d=s==l,c=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Lu(t),c=Fr(e),Lu(c)),c.t&&oo[c.t]){if(t.t&&t.t===c.t){var h=oo[t.t].transform(t.o,c.o,r);if(t.si!=null||t.sd!=null)for(var C=t.p,E=0;E<h.length;E++)t.o=[h[E]],t.p=C.slice(),Iu(t),Lt.append(n,t);else(!Hh(h)||h.length>0)&&(t.o=h,Lt.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[i]===t.p[i])if(d){if(t.ld!==void 0)if(t.li!==void 0&&r==="left")t.ld=Fr(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&d&&t.p[i]===e.p[i]?r==="right"&&t.p[i]++:e.p[i]<=t.p[i]&&t.p[i]++,t.lm!==void 0&&d&&e.p[i]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[i]===t.p[i])return n;var C=e.p[i],x=t.p[i],v=t.lm;(C<v||C===v&&x<v)&&t.lm--}if(e.p[i]<t.p[i])t.p[i]--;else if(e.p[i]===t.p[i]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var x=t.p[i],v=t.lm,k=e.p[i],L=e.lm;if(k!==L)if(x===k)if(r==="left")t.p[i]=L,x===v&&(t.lm=L);else return n;else x>k&&t.p[i]--,x>L?t.p[i]++:x===L&&k>L&&(t.p[i]++,x===v&&t.lm++),(v>k||v===k&&v>x)&&t.lm--,v>L?t.lm++:v===L&&(L>k&&v>x||L<k&&v<x?r==="right"&&t.lm++:v>x?t.lm++:v===k&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var x=e.p[i],v=e.lm;C=t.p[i],C>x&&t.p[i]--,C>v&&t.p[i]++}else{var x=e.p[i],v=e.lm;C=t.p[i],C===x?t.p[i]=v:(C>x&&t.p[i]--,(C>v||C===v&&x>v)&&t.p[i]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[i]===e.p[i])if(t.oi!==void 0&&d){if(r==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[i]===e.p[i])if(r==="left")Lt.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[i]==e.p[i]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return Lt.append(n,t),n},KT(Lt,Lt.transformComponent,Lt.checkValidOp,Lt.append);var PO=VT.exports;Lt.registerSubtype(PO);var FO=Lt,KO={type:FO};(function(n){n.defaultType=KO.type,n.map={},n.register=function(t){t.name&&(n.map[t.name]=t),t.uri&&(n.map[t.uri]=t)},n.register(n.defaultType)})(Su);var gr={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var r in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],r=1;r<arguments.length;r++){var i=arguments[r];e=e[i]||(r===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],r=arguments[arguments.length-1],i=1;i<arguments.length-1;i++){var o=arguments[i];e=e[o]||(e[o]=i===arguments.length-2?r():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],r=[e],i=1;i<arguments.length-1;i++){var o=arguments[i];if(!e.hasOwnProperty(o))break;e=e[o],r.push(e)}for(var i=r.length-1;i>=0;i--){var s=r[i],o=arguments[i+1],l=s[o];(i===r.length-1||!n.hasKeys(l))&&delete s[o]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,r){var i=!1;return e.forEach(function(o){o&&(o(r),i=!0)}),i},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];setTimeout(function(){e.apply(null,r)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(gr);var $T=Array.isArray,HT=Object.keys,VO=Object.prototype.hasOwnProperty,$O=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=$T(t),i=$T(e),o,s,l;if(r&&i){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!n(t[o],e[o]))return!1;return!0}if(r!=i)return!1;var c=t instanceof Date,d=e instanceof Date;if(c!=d)return!1;if(c&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,C=e instanceof RegExp;if(h!=C)return!1;if(h&&C)return t.toString()==e.toString();var E=HT(t);if(s=E.length,s!==HT(e).length)return!1;for(o=s;o--!==0;)if(!VO.call(e,E[o]))return!1;for(o=s;o--!==0;)if(l=E[o],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},Jo={};Jo.ACTIONS={initLegacy:"init",handshake:"hs",queryFetch:"qf",querySubscribe:"qs",queryUnsubscribe:"qu",queryUpdate:"q",bulkFetch:"bf",bulkSubscribe:"bs",bulkUnsubscribe:"bu",fetch:"f",fixup:"fixup",subscribe:"s",unsubscribe:"u",op:"op",snapshotFetch:"nf",snapshotFetchByTimestamp:"nt",pingPong:"pp",presence:"p",presenceSubscribe:"ps",presenceUnsubscribe:"pu",presenceRequest:"pr"};var jT=Yo,HO=FT,Zn=Vh,jh=Su,Kr=gr,jO=Kr.clone,zO=$O,Op=Jo.ACTIONS,Nn=Zn.CODES,GO=Ft;function Ft(n,t,e){jT.EventEmitter.call(this),this.connection=n,this.collection=t,this.id=e,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}jT.mixin(Ft),Ft.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this;t.whenNothingPending(function(){t.wantSubscribe?t.unsubscribe(function(e){if(e)return n?n(e):t.emit("error",e);t.connection._destroyDoc(t),n&&n()}):(t.connection._destroyDoc(t),n&&n())})},Ft.prototype._setType=function(n){if(typeof n=="string"&&(n=jh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Zn(Nn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Ft.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Ft.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Zn(Nn.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return t&&this.once("no write pending",t);var e=new Zn(Nn.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var r=n.type===void 0?jh.defaultType:n.type;this._setType(r),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},Ft.prototype.whenNothingPending=function(n){var t=this;Kr.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Ft.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Ft.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Ft.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Ft.prototype._emitResponseError=function(n,t){if(n&&n.code===Nn.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,t&&t(),this._emitNothingPending();return}if(t){t(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},Ft.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var r=this.inflightFetch.shift();if(r&&e.push(r),e.length&&(r=function(i){Kr.callEach(e,i)}),n)return this._emitResponseError(n,r);this.ingestSnapshot(t,r),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var r=this.pendingFetch;this.pendingFetch=[],e.callback&&r.push(e.callback);var i;if(r.length&&(i=function(o){Kr.callEach(r,o)}),n)return this._emitResponseError(n,i);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,i):i&&i(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Nn.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq){this._opAcknowledged(t);return}if(this.version==null||t.v>this.version){this.fetch();return}if(!(t.v<this.version)){if(this.inflightOp){var e=Du(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var r=0;r<this.pendingOps.length;r++){var e=Du(this.pendingOps[r],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}}},Ft.prototype._onConnectionStateChanged=function(){this.connection.canSend?(this.flush(),this._resubscribe()):(this.inflightOp&&(this.pendingOps.unshift(this.inflightOp),this.inflightOp=null),this.subscribed=!1,this.inflightSubscribe&&(this.inflightSubscribe.wantSubscribe?(this.pendingSubscribe.unshift(this.inflightSubscribe),this.inflightSubscribe=null):this._handleSubscribe()),this.inflightFetch.length&&(this.pendingFetch=this.pendingFetch.concat(this.inflightFetch),this.inflightFetch.length=0))},Ft.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(t){return t.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},Ft.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);WO(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Ft.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Ft.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Ft.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,r=e&&e.wantSubscribe===n;if(r){e.callback=qO([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Ft.prototype._flushSubscribe=function(){if(!(this.inflightSubscribe||!this.pendingSubscribe.length)){if(this.connection.canSend){this.inflightSubscribe=this.pendingSubscribe.shift(),this.wantSubscribe=this.inflightSubscribe.wantSubscribe,this.wantSubscribe?this.connection.sendSubscribe(this):(this.subscribed=!1,this.connection.sendUnsubscribe(this));return}if(!this.pendingSubscribe[0].wantSubscribe){this.inflightSubscribe=this.pendingSubscribe.shift();var n=this;Kr.nextTick(function(){n._handleSubscribe()})}}};function WO(n,t,e){if(t){var r=n.pop();n.push(function(i){r&&r(i),e&&e(i)})}else n.push(e)}function qO(n){return n=n.filter(Kr.truthy),n.length?function(t){Kr.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function XO(n){delete n.op,delete n.create,delete n.del}function Du(n,t){if(n.del)return XO(t);if(t.del)return new Zn(Nn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Zn(Nn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Zn(Nn.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var r=n.type.transform(n.op,t.op,"left"),i=n.type.transform(t.op,n.op,"right");n.op=r,t.op=i}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Zn(Nn.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,t),!t&&this.type===jh.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,r=0;r<n.op.length;r++){var i=n.op[r],o={op:[i]};this.emit("before op",o.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Du(this.applyStack[s],o);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,o.op)),this.emit("op",o.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",t);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,t);return}},Ft.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var t=this.inflightOp;if(!t){var e=new Zn(Nn.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",e)}if(t.sentAt=Date.now(),t.retries=t.retries==null?0:t.retries+1,t.seq==null){if(this.connection.seq>=Kr.MAX_SAFE_INTEGER)return this.emit("error",new Zn(Nn.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));t.seq=this.connection.seq++}this.connection.sendOp(this,t),t.src==null&&(t.src=n)}},Ft.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var r=new Zn(Nn.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(r):this.emit("error",r)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(o){return this._hardRollback(o)}var i=this;Kr.nextTick(function(){i.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var r=this._tryCompose(n);if(r){r.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},Ft.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var r=this.pendingOps.splice(e),e=0;e<r.length;e++){var t=r[e],i=this._tryCompose(t);i?i.callbacks=i.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},Ft.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!zO(n.source,t.source))){if(t.create&&"op"in n)return t.create.data=this.type.apply(t.create.data,n.op),t;if("op"in t&&"op"in n&&this.type.compose)return t.op=this.type.compose(t.op,n.op),t}}},Ft.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var r={op:n},i=t&&t.source;this._submit(r,i,e)},Ft.prototype.create=function(n,t,e,r){if(typeof t=="function"?(r=t,e=null,t=null):typeof e=="function"&&(r=e,e=null),t||(t=jh.defaultType.uri),this.type){var i=new Zn(Nn.ERR_DOC_ALREADY_CREATED,"Document already exists");return r?r(i):this.emit("error",i)}var o={create:{type:t,data:n}},s=e&&e.source;this._submit(o,s,r)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Zn(Nn.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var r={del:!0},i=n&&n.source;this._submit(r,i,t)},Ft.prototype.pause=function(){this.paused=!0},Ft.prototype.resume=function(){this.paused=!1,this.flush()},Ft.prototype.toSnapshot=function(){return{v:this.version,data:jO(this.data),type:this.type.uri}},Ft.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return HO.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();if(n[Op.fixup])for(var t=0;t<n[Op.fixup].length;t++){for(var e=n[Op.fixup][t],r=0;r<this.pendingOps.length;r++){var i=Du(this.pendingOps[t],e);if(i)return this._hardRollback(i)}try{this._otApply(e,!1)}catch(o){return this._hardRollback(o)}}this.version++,this._clearInflightOp()},Ft.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var r=Du(this.pendingOps[e],t);if(r)return this._hardRollback(r)}try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}this._clearInflightOp(n);return}this._hardRollback(n)},Ft.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var r=!!t.length,i=0;i<t.length;i++)r=Kr.callEach(t[i].callbacks,n)&&r;if(n&&!r)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Kr.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var zT=Yo,GT=Jo.ACTIONS,YO=gr,QO=Pn;function Pn(n,t,e,r,i,o,s){zT.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=r,this.query=i,this.results=null,o&&o.results&&(this.results=o.results,delete o.results),this.extra=void 0,this.options=o,this.callback=s,this.ready=!1,this.sent=!1}zT.mixin(Pn),Pn.prototype.hasPending=function(){return!this.ready},Pn.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var t=[],e=0;e<this.results.length;e++){var r=this.results[e];t.push([r.id,r.version])}n.r=t}this.connection.send(n),this.sent=!0}},Pn.prototype.destroy=function(n){this.connection.canSend&&this.action===GT.querySubscribe&&this.connection.send({a:GT.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&YO.nextTick(n)},Pn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Pn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Pn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Pn.prototype._handleResponse=function(n,t,e){var r=this.callback;if(this.callback=null,n)return this._finishResponse(n,r);if(!t)return this._finishResponse(null,r);var i=this,o=1,s=function(h){if(h)return i._finishResponse(h,r);--o||i._finishResponse(null,r)};if(Array.isArray(t))o+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){o++;var c=t[l],d=this.connection.get(c.c||this.collection,l);d.ingestSnapshot(c,s)}s()},Pn.prototype._ingestSnapshots=function(n,t){for(var e=[],r=0;r<n.length;r++){var i=n[r],o=this.connection.get(i.c||this.collection,i.d);o.ingestSnapshot(i,t),e.push(o)}return e},Pn.prototype._finishResponse=function(n,t){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),t?t(n):this.emit("error",n);t&&t(null,this.results,this.extra)},Pn.prototype._handleError=function(n){this.emit("error",n)},Pn.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var r=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(r)),this.emit("insert",r,e.index);break;case"remove":var o=e.howMany||1,i=this.results.splice(e.index,o);this.emit("remove",i,e.index);break;case"move":var o=e.howMany||1,s=this.results.splice(e.from,o);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},Pn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var WT=Yo,JO=Jo.ACTIONS,ZO=gr,qT=pi;function pi(n,t){if(WT.EventEmitter.call(this),!t||typeof t!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=t,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}WT.mixin(pi),pi.prototype.submit=function(n,t){this.value=n,this.send(t)},pi.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},pi.prototype.destroy=function(n){var t=this;this.submit(null,function(e){if(e)return t._callbackOrEmit(e,n);delete t.presence.localPresences[t.presenceId],n&&n()})},pi.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},pi.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},pi.prototype._message=function(){return{a:JO.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},pi.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},pi.prototype._callbackOrEmit=function(n,t){if(t)return ZO.nextTick(t,n);n&&this.emit("error",n)};var tN=gr,XT=Np;function Np(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}Np.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},Np.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&tN.nextTick(n)};var Pp={exports:{}};(function(n,t){(function(e,r){r(t)})(Mn,function(e){function r(y,S){S=S|0;for(var _=Math.max(y.length-S,0),N=Array(_),H=0;H<_;H++)N[H]=y[S+H];return N}var i=function(y){var S=r(arguments,1);return function(){var _=r(arguments);return y.apply(null,S.concat(_))}},o=function(y){return function(){var S=r(arguments),_=S.pop();y.call(this,S,_)}};function s(y){var S=typeof y;return y!=null&&(S=="object"||S=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function d(y){setTimeout(y,0)}function h(y){return function(S){var _=r(arguments,1);y(function(){S.apply(null,_)})}}var C;l?C=setImmediate:c?C=process.nextTick:C=d;var E=h(C);function x(y){return o(function(S,_){var N;try{N=y.apply(this,S)}catch(H){return _(H)}s(N)&&typeof N.then=="function"?N.then(function(H){v(_,null,H)},function(H){v(_,H.message?H:new Error(H))}):_(null,N)})}function v(y,S,_){try{y(S,_)}catch(N){E(k,N)}}function k(y){throw y}var L=typeof Symbol=="function";function M(y){return L&&y[Symbol.toStringTag]==="AsyncFunction"}function U(y){return M(y)?x(y):y}function F(y){return function(S){var _=r(arguments,1),N=o(function(H,$){var X=this;return y(S,function(Z,ut){U(Z).apply(X,H.concat(ut))},$)});return _.length?N.apply(this,_):N}}var G=typeof Mn=="object"&&Mn&&Mn.Object===Object&&Mn,q=typeof self=="object"&&self&&self.Object===Object&&self,rt=G||q||Function("return this")(),st=rt.Symbol,Et=Object.prototype,gt=Et.hasOwnProperty,At=Et.toString,Vt=st?st.toStringTag:void 0;function Gt(y){var S=gt.call(y,Vt),_=y[Vt];try{y[Vt]=void 0;var N=!0}catch{}var H=At.call(y);return N&&(S?y[Vt]=_:delete y[Vt]),H}var an=Object.prototype,be=an.toString;function Kn(y){return be.call(y)}var Li="[object Null]",Rn="[object Undefined]",En=st?st.toStringTag:void 0;function Ii(y){return y==null?y===void 0?Rn:Li:En&&En in Object(y)?Gt(y):Kn(y)}var fo="[object AsyncFunction]",xr="[object Function]",NA="[object GeneratorFunction]",PA="[object Proxy]";function FA(y){if(!s(y))return!1;var S=Ii(y);return S==xr||S==NA||S==fo||S==PA}var ps=9007199254740991;function Bl(y){return typeof y=="number"&&y>-1&&y%1==0&&y<=ps}function Tl(y){return y!=null&&Bl(y.length)&&!FA(y)}var ho={};function jt(){}function Di(y){return function(){if(y!==null){var S=y;y=null,S.apply(this,arguments)}}}var Cs=typeof Symbol=="function"&&Symbol.iterator,gc=function(y){return Cs&&y[Cs]&&y[Cs]()};function Am(y,S){for(var _=-1,N=Array(y);++_<y;)N[_]=S(_);return N}function An(y){return y!=null&&typeof y=="object"}var yl="[object Arguments]";function xm(y){return An(y)&&Ii(y)==yl}var br=Object.prototype,bm=br.hasOwnProperty,KA=br.propertyIsEnumerable,kl=xm(function(){return arguments}())?xm:function(y){return An(y)&&bm.call(y,"callee")&&!KA.call(y,"callee")},ke=Array.isArray;function Rl(){return!1}var wl=typeof e=="object"&&e&&!e.nodeType&&e,vm=wl&&!0&&n&&!n.nodeType&&n,Sl=vm&&vm.exports===wl,Bm=Sl?rt.Buffer:void 0,Ll=Bm?Bm.isBuffer:void 0,Es=Ll||Rl,Of=9007199254740991,Nf=/^(?:0|[1-9]\d*)$/;function Pf(y,S){var _=typeof y;return S=S==null?Of:S,!!S&&(_=="number"||_!="symbol"&&Nf.test(y))&&y>-1&&y%1==0&&y<S}var Ff="[object Arguments]",Kf="[object Array]",Vf="[object Boolean]",$f="[object Date]",Hf="[object Error]",jf="[object Function]",VA="[object Map]",$A="[object Number]",HA="[object Object]",Tm="[object RegExp]",ym="[object Set]",jA="[object String]",zA="[object WeakMap]",GA="[object ArrayBuffer]",WA="[object DataView]",km="[object Float32Array]",qA="[object Float64Array]",XA="[object Int8Array]",YA="[object Int16Array]",zf="[object Int32Array]",QA="[object Uint8Array]",Gf="[object Uint8ClampedArray]",JA="[object Uint16Array]",ZA="[object Uint32Array]",he={};he[km]=he[qA]=he[XA]=he[YA]=he[zf]=he[QA]=he[Gf]=he[JA]=he[ZA]=!0,he[Ff]=he[Kf]=he[GA]=he[Vf]=he[WA]=he[$f]=he[Hf]=he[jf]=he[VA]=he[$A]=he[HA]=he[Tm]=he[ym]=he[jA]=he[zA]=!1;function tx(y){return An(y)&&Bl(y.length)&&!!he[Ii(y)]}function ex(y){return function(S){return y(S)}}var Rm=typeof e=="object"&&e&&!e.nodeType&&e,Il=Rm&&!0&&n&&!n.nodeType&&n,nx=Il&&Il.exports===Rm,pc=nx&&G.process,wm=function(){try{var y=Il&&Il.require&&Il.require("util").types;return y||pc&&pc.binding&&pc.binding("util")}catch{}}(),Sm=wm&&wm.isTypedArray,rx=Sm?ex(Sm):tx,ix=Object.prototype,ox=ix.hasOwnProperty;function sx(y,S){var _=ke(y),N=!_&&kl(y),H=!_&&!N&&Es(y),$=!_&&!N&&!H&&rx(y),X=_||N||H||$,Z=X?Am(y.length,String):[],ut=Z.length;for(var xt in y)(S||ox.call(y,xt))&&!(X&&(xt=="length"||H&&(xt=="offset"||xt=="parent")||$&&(xt=="buffer"||xt=="byteLength"||xt=="byteOffset")||Pf(xt,ut)))&&Z.push(xt);return Z}var Cc=Object.prototype;function lx(y){var S=y&&y.constructor,_=typeof S=="function"&&S.prototype||Cc;return y===_}function Ec(y,S){return function(_){return y(S(_))}}var ax=Ec(Object.keys,Object),cx=Object.prototype,ux=cx.hasOwnProperty;function Lm(y){if(!lx(y))return ax(y);var S=[];for(var _ in Object(y))ux.call(y,_)&&_!="constructor"&&S.push(_);return S}function Ac(y){return Tl(y)?sx(y):Lm(y)}function Im(y){var S=-1,_=y.length;return function(){return++S<_?{value:y[S],key:S}:null}}function fx(y){var S=-1;return function(){var N=y.next();return N.done?null:(S++,{value:N.value,key:S})}}function dx(y){var S=Ac(y),_=-1,N=S.length;return function H(){var $=S[++_];return $==="__proto__"?H():_<N?{value:y[$],key:$}:null}}function hx(y){if(Tl(y))return Im(y);var S=gc(y);return S?fx(S):dx(y)}function vr(y){return function(){if(y===null)throw new Error("Callback was already called.");var S=y;y=null,S.apply(this,arguments)}}function Dl(y){return function(S,_,N){if(N=Di(N||jt),y<=0||!S)return N(null);var H=hx(S),$=!1,X=0,Z=!1;function ut(ft,vt){if(X-=1,ft)$=!0,N(ft);else{if(vt===ho||$&&X<=0)return $=!0,N(null);Z||xt()}}function xt(){for(Z=!0;X<y&&!$;){var ft=H();if(ft===null){$=!0,X<=0&&N(null);return}X+=1,_(ft.value,ft.key,vr(ut))}Z=!1}xt()}}function _i(y,S,_,N){Dl(S)(y,U(_),N)}function je(y,S){return function(_,N,H){return y(_,S,N,H)}}function Wf(y,S,_){_=Di(_||jt);var N=0,H=0,$=y.length;$===0&&_(null);function X(Z,ut){Z?_(Z):(++H===$||ut===ho)&&_(null)}for(;N<$;N++)S(y[N],N,vr(X))}var mx=je(_i,1/0),Yr=function(y,S,_){var N=Tl(y)?Wf:mx;N(y,U(S),_)};function Qr(y){return function(S,_,N){return y(Yr,S,U(_),N)}}function qf(y,S,_,N){N=N||jt,S=S||[];var H=[],$=0,X=U(_);y(S,function(Z,ut,xt){var ft=$++;X(Z,function(vt,te){H[ft]=te,xt(vt)})},function(Z){N(Z,H)})}var xc=Qr(qf),Xf=F(xc);function mo(y){return function(S,_,N,H){return y(Dl(_),S,U(N),H)}}var Mi=mo(qf),Yf=je(Mi,1),Qf=F(Yf);function As(y,S){for(var _=-1,N=y==null?0:y.length;++_<N&&S(y[_],_,y)!==!1;);return y}function Jf(y){return function(S,_,N){for(var H=-1,$=Object(S),X=N(S),Z=X.length;Z--;){var ut=X[y?Z:++H];if(_($[ut],ut,$)===!1)break}return S}}var xs=Jf();function bs(y,S){return y&&xs(y,S,Ac)}function Dm(y,S,_,N){for(var H=y.length,$=_+(N?1:-1);N?$--:++$<H;)if(S(y[$],$,y))return $;return-1}function gx(y){return y!==y}function _m(y,S,_){for(var N=_-1,H=y.length;++N<H;)if(y[N]===S)return N;return-1}function _l(y,S,_){return S===S?_m(y,S,_):Dm(y,gx,_)}var bc=function(y,S,_){typeof S=="function"&&(_=S,S=null),_=Di(_||jt);var N=Ac(y),H=N.length;if(!H)return _(null);S||(S=H);var $={},X=0,Z=!1,ut=Object.create(null),xt=[],ft=[],vt={};bs(y,function(Ce,ce){if(!ke(Ce)){te(ce,[Ce]),ft.push(ce);return}var ve=Ce.slice(0,Ce.length-1),Tr=ve.length;if(Tr===0){te(ce,Ce),ft.push(ce);return}vt[ce]=Tr,As(ve,function(R){if(!y[R])throw new Error("async.auto task `"+ce+"` has a non-existent dependency `"+R+"` in "+ve.join(", "));cn(R,function(){Tr--,Tr===0&&te(ce,Ce)})})}),Nx(),Oe();function te(Ce,ce){xt.push(function(){Br(Ce,ce)})}function Oe(){if(xt.length===0&&X===0)return _(null,$);for(;xt.length&&X<S;){var Ce=xt.shift();Ce()}}function cn(Ce,ce){var ve=ut[Ce];ve||(ve=ut[Ce]=[]),ve.push(ce)}function Hn(Ce){var ce=ut[Ce]||[];As(ce,function(ve){ve()}),Oe()}function Br(Ce,ce){if(!Z){var ve=vr(function(R,Ni){if(X--,arguments.length>2&&(Ni=r(arguments,1)),R){var ys={};bs($,function(jn,$t){ys[$t]=jn}),ys[Ce]=Ni,Z=!0,ut=Object.create(null),_(R,ys)}else $[Ce]=Ni,Hn(Ce)});X++;var Tr=U(ce[ce.length-1]);ce.length>1?Tr($,ve):Tr(ve)}}function Nx(){for(var Ce,ce=0;ft.length;)Ce=ft.pop(),ce++,As(Px(Ce),function(ve){--vt[ve]===0&&ft.push(ve)});if(ce!==H)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function Px(Ce){var ce=[];return bs(y,function(ve,Tr){ke(ve)&&_l(ve,Ce,0)>=0&&ce.push(Tr)}),ce}};function go(y,S){for(var _=-1,N=y==null?0:y.length,H=Array(N);++_<N;)H[_]=S(y[_],_,y);return H}var px="[object Symbol]";function Cx(y){return typeof y=="symbol"||An(y)&&Ii(y)==px}var Ex=1/0,Zf=st?st.prototype:void 0,Mm=Zf?Zf.toString:void 0;function td(y){if(typeof y=="string")return y;if(ke(y))return go(y,td)+"";if(Cx(y))return Mm?Mm.call(y):"";var S=y+"";return S=="0"&&1/y==-Ex?"-0":S}function Ax(y,S,_){var N=-1,H=y.length;S<0&&(S=-S>H?0:H+S),_=_>H?H:_,_<0&&(_+=H),H=S>_?0:_-S>>>0,S>>>=0;for(var $=Array(H);++N<H;)$[N]=y[N+S];return $}function xx(y,S,_){var N=y.length;return _=_===void 0?N:_,!S&&_>=N?y:Ax(y,S,_)}function ed(y,S){for(var _=y.length;_--&&_l(S,y[_],0)>-1;);return _}function bx(y,S){for(var _=-1,N=y.length;++_<N&&_l(S,y[_],0)>-1;);return _}function vx(y){return y.split("")}var Bx="\\ud800-\\udfff",Tx="\\u0300-\\u036f",yx="\\ufe20-\\ufe2f",me="\\u20d0-\\u20ff",ae=Tx+yx+me,kx="\\ufe0e\\ufe0f",Rx="\\u200d",wx=RegExp("["+Rx+Bx+ae+kx+"]");function Sx(y){return wx.test(y)}var Um="\\ud800-\\udfff",Lx="\\u0300-\\u036f",Om="\\ufe20-\\ufe2f",Ix="\\u20d0-\\u20ff",Ze=Lx+Om+Ix,nd="\\ufe0e\\ufe0f",po="["+Um+"]",vc="["+Ze+"]",Ml="\\ud83c[\\udffb-\\udfff]",Vn="(?:"+vc+"|"+Ml+")",rd="[^"+Um+"]",id="(?:\\ud83c[\\udde6-\\uddff]){2}",od="[\\ud800-\\udbff][\\udc00-\\udfff]",Nm="\\u200d",sd=Vn+"?",ld="["+nd+"]?",wn="(?:"+Nm+"(?:"+[rd,id,od].join("|")+")"+ld+sd+")*",Dx=ld+sd+wn,$n="(?:"+[rd+vc+"?",vc,id,od,po].join("|")+")",_x=RegExp(Ml+"(?="+Ml+")|"+$n+Dx,"g");function Pm(y){return y.match(_x)||[]}function Jr(y){return Sx(y)?Pm(y):vx(y)}function Bc(y){return y==null?"":td(y)}var ad=/^\s+|\s+$/g;function pe(y,S,_){if(y=Bc(y),y&&(_||S===void 0))return y.replace(ad,"");if(!y||!(S=td(S)))return y;var N=Jr(y),H=Jr(S),$=bx(N,H),X=ed(N,H)+1;return xx(N,$,X).join("")}var Ui=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,cd=/,/,Mx=/(=.+)?(\s*)$/,ud=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function Ux(y){return y=y.toString().replace(ud,""),y=y.match(Ui)[2].replace(" ",""),y=y?y.split(cd):[],y=y.map(function(S){return pe(S.replace(Mx,""))}),y}function Fm(y,S){var _={};bs(y,function(N,H){var $,X=M(N),Z=!X&&N.length===1||X&&N.length===0;if(ke(N))$=N.slice(0,-1),N=N[N.length-1],_[H]=$.concat($.length>0?ut:N);else if(Z)_[H]=N;else{if($=Ux(N),N.length===0&&!X&&$.length===0)throw new Error("autoInject task functions require explicit parameters.");X||$.pop(),_[H]=$.concat(ut)}function ut(xt,ft){var vt=go($,function(te){return xt[te]});vt.push(ft),U(N).apply(null,vt)}}),bc(_,S)}function rr(){this.head=this.tail=null,this.length=0}function fd(y,S){y.length=1,y.head=y.tail=S}rr.prototype.removeLink=function(y){return y.prev?y.prev.next=y.next:this.head=y.next,y.next?y.next.prev=y.prev:this.tail=y.prev,y.prev=y.next=null,this.length-=1,y},rr.prototype.empty=function(){for(;this.head;)this.shift();return this},rr.prototype.insertAfter=function(y,S){S.prev=y,S.next=y.next,y.next?y.next.prev=S:this.tail=S,y.next=S,this.length+=1},rr.prototype.insertBefore=function(y,S){S.prev=y.prev,S.next=y,y.prev?y.prev.next=S:this.head=S,y.prev=S,this.length+=1},rr.prototype.unshift=function(y){this.head?this.insertBefore(this.head,y):fd(this,y)},rr.prototype.push=function(y){this.tail?this.insertAfter(this.tail,y):fd(this,y)},rr.prototype.shift=function(){return this.head&&this.removeLink(this.head)},rr.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},rr.prototype.toArray=function(){for(var y=Array(this.length),S=this.head,_=0;_<this.length;_++)y[_]=S.data,S=S.next;return y},rr.prototype.remove=function(y){for(var S=this.head;S;){var _=S.next;y(S)&&this.removeLink(S),S=_}return this};function Ul(y,S,_){if(S==null)S=1;else if(S===0)throw new Error("Concurrency must not be zero");var N=U(y),H=0,$=[],X=!1;function Z(vt,te,Oe){if(Oe!=null&&typeof Oe!="function")throw new Error("task callback must be a function");if(ft.started=!0,ke(vt)||(vt=[vt]),vt.length===0&&ft.idle())return E(function(){ft.drain()});for(var cn=0,Hn=vt.length;cn<Hn;cn++){var Br={data:vt[cn],callback:Oe||jt};te?ft._tasks.unshift(Br):ft._tasks.push(Br)}X||(X=!0,E(function(){X=!1,ft.process()}))}function ut(vt){return function(te){H-=1;for(var Oe=0,cn=vt.length;Oe<cn;Oe++){var Hn=vt[Oe],Br=_l($,Hn,0);Br===0?$.shift():Br>0&&$.splice(Br,1),Hn.callback.apply(Hn,arguments),te!=null&&ft.error(te,Hn.data)}H<=ft.concurrency-ft.buffer&&ft.unsaturated(),ft.idle()&&ft.drain(),ft.process()}}var xt=!1,ft={_tasks:new rr,concurrency:S,payload:_,saturated:jt,unsaturated:jt,buffer:S/4,empty:jt,drain:jt,error:jt,started:!1,paused:!1,push:function(vt,te){Z(vt,!1,te)},kill:function(){ft.drain=jt,ft._tasks.empty()},unshift:function(vt,te){Z(vt,!0,te)},remove:function(vt){ft._tasks.remove(vt)},process:function(){if(!xt){for(xt=!0;!ft.paused&&H<ft.concurrency&&ft._tasks.length;){var vt=[],te=[],Oe=ft._tasks.length;ft.payload&&(Oe=Math.min(Oe,ft.payload));for(var cn=0;cn<Oe;cn++){var Hn=ft._tasks.shift();vt.push(Hn),$.push(Hn),te.push(Hn.data)}H+=1,ft._tasks.length===0&&ft.empty(),H===ft.concurrency&&ft.saturated();var Br=vr(ut(vt));N(te,Br)}xt=!1}},length:function(){return ft._tasks.length},running:function(){return H},workersList:function(){return $},idle:function(){return ft._tasks.length+H===0},pause:function(){ft.paused=!0},resume:function(){ft.paused!==!1&&(ft.paused=!1,E(ft.process))}};return ft}function Co(y,S){return Ul(y,1,S)}var vs=je(_i,1);function Zr(y,S,_,N){N=Di(N||jt);var H=U(_);vs(y,function($,X,Z){H(S,$,function(ut,xt){S=xt,Z(ut)})},function($){N($,S)})}function Tc(){var y=go(arguments,U);return function(){var S=r(arguments),_=this,N=S[S.length-1];typeof N=="function"?S.pop():N=jt,Zr(y,S,function(H,$,X){$.apply(_,H.concat(function(Z){var ut=r(arguments,1);X(Z,ut)}))},function(H,$){N.apply(_,[H].concat($))})}}var yc=function(){return Tc.apply(null,r(arguments).reverse())},dd=Array.prototype.concat,Ol=function(y,S,_,N){N=N||jt;var H=U(_);Mi(y,S,function($,X){H($,function(Z){return Z?X(Z):X(null,r(arguments,1))})},function($,X){for(var Z=[],ut=0;ut<X.length;ut++)X[ut]&&(Z=dd.apply(Z,X[ut]));return N($,Z)})},Km=je(Ol,1/0),kc=je(Ol,1),Rc=function(){var y=r(arguments),S=[null].concat(y);return function(){var _=arguments[arguments.length-1];return _.apply(this,S)}};function Nl(y){return y}function Eo(y,S){return function(_,N,H,$){$=$||jt;var X=!1,Z;_(N,function(ut,xt,ft){H(ut,function(vt,te){vt?ft(vt):y(te)&&!Z?(X=!0,Z=S(!0,ut),ft(null,ho)):ft()})},function(ut){ut?$(ut):$(null,X?Z:S(!1))})}}function xn(y,S){return S}var Bs=Qr(Eo(Nl,xn)),ti=mo(Eo(Nl,xn)),Pl=je(ti,1);function hd(y){return function(S){var _=r(arguments,1);_.push(function(N){var H=r(arguments,1);typeof console=="object"&&(N?console.error&&console.error(N):console[y]&&As(H,function($){console[y]($)}))}),U(S).apply(null,_)}}var Vm=hd("dir");function $m(y,S,_){_=vr(_||jt);var N=U(y),H=U(S);function $(Z){if(Z)return _(Z);var ut=r(arguments,1);ut.push(X),H.apply(this,ut)}function X(Z,ut){if(Z)return _(Z);if(!ut)return _(null);N($)}X(null,!0)}function md(y,S,_){_=vr(_||jt);var N=U(y),H=function($){if($)return _($);var X=r(arguments,1);if(S.apply(this,X))return N(H);_.apply(null,[null].concat(X))};N(H)}function Hm(y,S,_){md(y,function(){return!S.apply(this,arguments)},_)}function jm(y,S,_){_=vr(_||jt);var N=U(S),H=U(y);function $(Z){if(Z)return _(Z);H(X)}function X(Z,ut){if(Z)return _(Z);if(!ut)return _(null);N($)}H(X)}function Ao(y){return function(S,_,N){return y(S,N)}}function wc(y,S,_){Yr(y,Ao(U(S)),_)}function Fl(y,S,_,N){Dl(S)(y,Ao(U(_)),N)}var xo=je(Fl,1);function Sc(y){return M(y)?y:o(function(S,_){var N=!0;S.push(function(){var H=arguments;N?E(function(){_.apply(null,H)}):_.apply(null,H)}),y.apply(this,S),N=!1})}function ir(y){return!y}var bo=Qr(Eo(ir,ir)),Kl=mo(Eo(ir,ir)),Lc=je(Kl,1);function zm(y){return function(S){return S==null?void 0:S[y]}}function Ts(y,S,_,N){var H=new Array(S.length);y(S,function($,X,Z){_($,function(ut,xt){H[X]=!!xt,Z(ut)})},function($){if($)return N($);for(var X=[],Z=0;Z<S.length;Z++)H[Z]&&X.push(S[Z]);N(null,X)})}function or(y,S,_,N){var H=[];y(S,function($,X,Z){_($,function(ut,xt){ut?Z(ut):(xt&&H.push({index:X,value:$}),Z())})},function($){$?N($):N(null,go(H.sort(function(X,Z){return X.index-Z.index}),zm("value")))})}function Ic(y,S,_,N){var H=Tl(S)?Ts:or;H(y,S,U(_),N||jt)}var Dc=Qr(Ic),Vl=mo(Ic),_c=je(Vl,1);function Gm(y,S){var _=vr(S||jt),N=U(Sc(y));function H($){if($)return _($);N(H)}H()}var Mc=function(y,S,_,N){N=N||jt;var H=U(_);Mi(y,S,function($,X){H($,function(Z,ut){return Z?X(Z):X(null,{key:ut,val:$})})},function($,X){for(var Z={},ut=Object.prototype.hasOwnProperty,xt=0;xt<X.length;xt++)if(X[xt]){var ft=X[xt].key,vt=X[xt].val;ut.call(Z,ft)?Z[ft].push(vt):Z[ft]=[vt]}return N($,Z)})},vo=je(Mc,1/0),K=je(Mc,1),W=hd("log");function j(y,S,_,N){N=Di(N||jt);var H={},$=U(_);_i(y,S,function(X,Z,ut){$(X,Z,function(xt,ft){if(xt)return ut(xt);H[Z]=ft,ut()})},function(X){N(X,H)})}var pt=je(j,1/0),St=je(j,1);function qt(y,S){return S in y}function Ie(y,S){var _=Object.create(null),N=Object.create(null);S=S||Nl;var H=U(y),$=o(function(Z,ut){var xt=S.apply(null,Z);qt(_,xt)?E(function(){ut.apply(null,_[xt])}):qt(N,xt)?N[xt].push(ut):(N[xt]=[ut],H.apply(null,Z.concat(function(){var ft=r(arguments);_[xt]=ft;var vt=N[xt];delete N[xt];for(var te=0,Oe=vt.length;te<Oe;te++)vt[te].apply(null,ft)})))});return $.memo=_,$.unmemoized=y,$}var Zt;c?Zt=process.nextTick:l?Zt=setImmediate:Zt=d;var Uc=h(Zt);function gd(y,S,_){_=_||jt;var N=Tl(S)?[]:{};y(S,function(H,$,X){U(H)(function(Z,ut){arguments.length>2&&(ut=r(arguments,1)),N[$]=ut,X(Z)})},function(H){_(H,N)})}function Sn(y,S){gd(Yr,y,S)}function $l(y,S,_){gd(Dl(S),y,_)}var pd=function(y,S){var _=U(y);return Ul(function(N,H){_(N[0],H)},S,1)},Bo=function(y,S){var _=pd(y,S);return _.push=function(N,H,$){if($==null&&($=jt),typeof $!="function")throw new Error("task callback must be a function");if(_.started=!0,ke(N)||(N=[N]),N.length===0)return E(function(){_.drain()});H=H||0;for(var X=_._tasks.head;X&&H>=X.priority;)X=X.next;for(var Z=0,ut=N.length;Z<ut;Z++){var xt={data:N[Z],priority:H,callback:$};X?_._tasks.insertBefore(X,xt):_._tasks.push(xt)}E(_.process)},delete _.unshift,_};function Hl(y,S){if(S=Di(S||jt),!ke(y))return S(new TypeError("First argument to race must be an array of functions"));if(!y.length)return S();for(var _=0,N=y.length;_<N;_++)U(y[_])(S)}function To(y,S,_,N){var H=r(y).reverse();Zr(H,S,_,N)}function Xt(y){var S=U(y);return o(function(N,H){return N.push(function(X,Z){if(X)H(null,{error:X});else{var ut;arguments.length<=2?ut=Z:ut=r(arguments,1),H(null,{value:ut})}}),S.apply(this,N)})}function Wm(y){var S;return ke(y)?S=go(y,Xt):(S={},bs(y,function(_,N){S[N]=Xt.call(this,_)})),S}function Cd(y,S,_,N){Ic(y,S,function(H,$){_(H,function(X,Z){$(X,!Z)})},N)}var jl=Qr(Cd),Ed=mo(Cd),qm=je(Ed,1);function Xm(y){return function(){return y}}function yo(y,S,_){var N=5,H=0,$={times:N,intervalFunc:Xm(H)};function X(ft,vt){if(typeof vt=="object")ft.times=+vt.times||N,ft.intervalFunc=typeof vt.interval=="function"?vt.interval:Xm(+vt.interval||H),ft.errorFilter=vt.errorFilter;else if(typeof vt=="number"||typeof vt=="string")ft.times=+vt||N;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof y=="function"?(_=S||jt,S=y):(X($,y),_=_||jt),typeof S!="function")throw new Error("Invalid arguments for async.retry");var Z=U(S),ut=1;function xt(){Z(function(ft){ft&&ut++<$.times&&(typeof $.errorFilter!="function"||$.errorFilter(ft))?setTimeout(xt,$.intervalFunc(ut)):_.apply(null,arguments)})}xt()}var ei=function(y,S){S||(S=y,y=null);var _=U(S);return o(function(N,H){function $(X){_.apply(null,N.concat(X))}y?yo(y,$,H):yo($,H)})};function zl(y,S){gd(vs,y,S)}var Gl=Qr(Eo(Boolean,Nl)),Oi=mo(Eo(Boolean,Nl)),Wl=je(Oi,1);function Ad(y,S,_){var N=U(S);xc(y,function($,X){N($,function(Z,ut){if(Z)return X(Z);X(null,{value:$,criteria:ut})})},function($,X){if($)return _($);_(null,go(X.sort(H),zm("value")))});function H($,X){var Z=$.criteria,ut=X.criteria;return Z<ut?-1:Z>ut?1:0}}function ql(y,S,_){var N=U(y);return o(function(H,$){var X=!1,Z;function ut(){var xt=y.name||"anonymous",ft=new Error('Callback function "'+xt+'" timed out.');ft.code="ETIMEDOUT",_&&(ft.info=_),X=!0,$(ft)}H.push(function(){X||($.apply(null,arguments),clearTimeout(Z))}),Z=setTimeout(ut,S),N.apply(null,H)})}var Ym=Math.ceil,Xl=Math.max;function ko(y,S,_,N){for(var H=-1,$=Xl(Ym((S-y)/(_||1)),0),X=Array($);$--;)X[N?$:++H]=y,y+=_;return X}function Ro(y,S,_,N){var H=U(_);Mi(ko(0,y,1),S,H,N)}var Qm=je(Ro,1/0),Jm=je(Ro,1);function Zm(y,S,_,N){arguments.length<=3&&(N=_,_=S,S=ke(y)?[]:{}),N=Di(N||jt);var H=U(_);Yr(y,function($,X,Z){H(S,$,X,Z)},function($){N($,S)})}function Yl(y,S){var _=null,N;S=S||jt,xo(y,function(H,$){U(H)(function(X,Z){arguments.length>2?N=r(arguments,1):N=Z,_=X,$(!X)})},function(){S(_,N)})}function Ql(y){return function(){return(y.unmemoized||y).apply(null,arguments)}}function Jl(y,S,_){_=vr(_||jt);var N=U(S);if(!y())return _(null);var H=function($){if($)return _($);if(y())return N(H);var X=r(arguments,1);_.apply(null,[null].concat(X))};N(H)}function tg(y,S,_){Jl(function(){return!y.apply(this,arguments)},S,_)}var xd=function(y,S){if(S=Di(S||jt),!ke(y))return S(new Error("First argument to waterfall must be an array of functions"));if(!y.length)return S();var _=0;function N($){var X=U(y[_++]);$.push(vr(H)),X.apply(null,$)}function H($){if($||_===y.length)return S.apply(null,arguments);N(r(arguments,1))}N([])},Ox={apply:i,applyEach:Xf,applyEachSeries:Qf,asyncify:x,auto:bc,autoInject:Fm,cargo:Co,compose:yc,concat:Km,concatLimit:Ol,concatSeries:kc,constant:Rc,detect:Bs,detectLimit:ti,detectSeries:Pl,dir:Vm,doDuring:$m,doUntil:Hm,doWhilst:md,during:jm,each:wc,eachLimit:Fl,eachOf:Yr,eachOfLimit:_i,eachOfSeries:vs,eachSeries:xo,ensureAsync:Sc,every:bo,everyLimit:Kl,everySeries:Lc,filter:Dc,filterLimit:Vl,filterSeries:_c,forever:Gm,groupBy:vo,groupByLimit:Mc,groupBySeries:K,log:W,map:xc,mapLimit:Mi,mapSeries:Yf,mapValues:pt,mapValuesLimit:j,mapValuesSeries:St,memoize:Ie,nextTick:Uc,parallel:Sn,parallelLimit:$l,priorityQueue:Bo,queue:pd,race:Hl,reduce:Zr,reduceRight:To,reflect:Xt,reflectAll:Wm,reject:jl,rejectLimit:Ed,rejectSeries:qm,retry:yo,retryable:ei,seq:Tc,series:zl,setImmediate:E,some:Gl,someLimit:Oi,someSeries:Wl,sortBy:Ad,timeout:ql,times:Qm,timesLimit:Ro,timesSeries:Jm,transform:Zm,tryEach:Yl,unmemoize:Ql,until:tg,waterfall:xd,whilst:Jl,all:bo,allLimit:Kl,allSeries:Lc,any:Gl,anyLimit:Oi,anySeries:Wl,find:Bs,findLimit:ti,findSeries:Pl,forEach:wc,forEachSeries:xo,forEachLimit:Fl,forEachOf:Yr,forEachOfSeries:vs,forEachOfLimit:_i,inject:Zr,foldl:Zr,foldr:To,select:Dc,selectLimit:Vl,selectSeries:_c,wrapSync:x};e.default=Ox,e.apply=i,e.applyEach=Xf,e.applyEachSeries=Qf,e.asyncify=x,e.auto=bc,e.autoInject=Fm,e.cargo=Co,e.compose=yc,e.concat=Km,e.concatLimit=Ol,e.concatSeries=kc,e.constant=Rc,e.detect=Bs,e.detectLimit=ti,e.detectSeries=Pl,e.dir=Vm,e.doDuring=$m,e.doUntil=Hm,e.doWhilst=md,e.during=jm,e.each=wc,e.eachLimit=Fl,e.eachOf=Yr,e.eachOfLimit=_i,e.eachOfSeries=vs,e.eachSeries=xo,e.ensureAsync=Sc,e.every=bo,e.everyLimit=Kl,e.everySeries=Lc,e.filter=Dc,e.filterLimit=Vl,e.filterSeries=_c,e.forever=Gm,e.groupBy=vo,e.groupByLimit=Mc,e.groupBySeries=K,e.log=W,e.map=xc,e.mapLimit=Mi,e.mapSeries=Yf,e.mapValues=pt,e.mapValuesLimit=j,e.mapValuesSeries=St,e.memoize=Ie,e.nextTick=Uc,e.parallel=Sn,e.parallelLimit=$l,e.priorityQueue=Bo,e.queue=pd,e.race=Hl,e.reduce=Zr,e.reduceRight=To,e.reflect=Xt,e.reflectAll=Wm,e.reject=jl,e.rejectLimit=Ed,e.rejectSeries=qm,e.retry=yo,e.retryable=ei,e.seq=Tc,e.series=zl,e.setImmediate=E,e.some=Gl,e.someLimit=Oi,e.someSeries=Wl,e.sortBy=Ad,e.timeout=ql,e.times=Qm,e.timesLimit=Ro,e.timesSeries=Jm,e.transform=Zm,e.tryEach=Yl,e.unmemoize=Ql,e.until=tg,e.waterfall=xd,e.whilst=Jl,e.all=bo,e.allLimit=Kl,e.allSeries=Lc,e.any=Gl,e.anyLimit=Oi,e.anySeries=Wl,e.find=Bs,e.findLimit=ti,e.findSeries=Pl,e.forEach=wc,e.forEachSeries=xo,e.forEachLimit=Fl,e.forEachOf=Yr,e.forEachOfSeries=vs,e.forEachOfLimit=_i,e.inject=Zr,e.foldl=Zr,e.foldr=To,e.select=Dc,e.selectLimit=Vl,e.selectSeries=_c,e.wrapSync=x,Object.defineProperty(e,"__esModule",{value:!0})})})(Pp,Pp.exports);var YT={exports:{}},Fp=YT.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),r=2;e===1/0;r*=2)e=Math.log(Math.pow(2,n/r))/Math.log(t)*r;for(var i=e-Math.floor(e),o="",r=0;r<Math.floor(e);r++){var s=Math.floor(Math.random()*t).toString(t);o=s+o}if(i){var l=Math.pow(t,i),s=Math.floor(Math.random()*l).toString(t);o=s+o}var c=parseInt(o,t);return c!==1/0&&c>=Math.pow(2,n)?Fp(n,t):o};Fp.rack=function(n,t,e){var r=function(o){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=Fp(n,t)}while(Object.hasOwnProperty.call(i,l));return i[l]=o,l},i=r.hats={};return r.get=function(o){return r.hats[o]},r.set=function(o,s){return r.hats[o]=s,r},r.bits=n||128,r.base=t||16,r};var QT=Yo,eN=qT,nN=XT,zh=gr,Kp=Pp.exports,rN=YT.exports,JT=Jo.ACTIONS,ZT=Fe;function Fe(n,t){if(QT.EventEmitter.call(this),!t||typeof t!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=t,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}QT.mixin(Fe),Fe.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Fe.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Fe.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||rN();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Fe.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(r){if(r)return t._callbackOrEmit(r,n);var i=Object.keys(t._remotePresenceInstances);Kp.parallel([function(o){Kp.each(e,function(s,l){t.localPresences[s].destroy(l)},o)},function(o){if(!t._wantsDestroy)return o();Kp.each(i,function(s,l){t._remotePresenceInstances[s].destroy(l)},o)}],function(o){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(o,n)})})},Fe.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?JT.presenceSubscribe:JT.presenceUnsubscribe,r=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[r]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,r,this)},Fe.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Fe.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Fe.prototype._receiveUpdate=function(n,t){var e=zh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var r=this,i=zh.digOrCreate(this._remotePresenceInstances,t.id,function(){return r._createRemotePresence(t.id)});i.receiveUpdate(t)},Fe.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Fe.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var t in this.localPresences){var e=this.localPresences[t];e.value!==null&&e.send()}},Fe.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Fe.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Fe.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var r=this;this.subscribe(function(i){r._callEachOrEmit(n,i)})},Fe.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Fe.prototype._callbackOrEmit=function(n,t){if(t)return zh.nextTick(t,n);n&&this.emit("error",n)},Fe.prototype._createLocalPresence=function(n){return new eN(this,n)},Fe.prototype._createRemotePresence=function(n){return new nN(this,n)},Fe.prototype._callEachOrEmit=function(n,t){var e=zh.callEach(n,t);!e&&t&&this.emit("error",t)};var _u=qT,t2=Vh,iN=gr,e2=t2.CODES,oN=Vr;function Vr(n,t){_u.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._emitter=this.connection._docPresenceEmitter,this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}Vr.prototype=Object.create(_u.prototype),Vr.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:e2.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(e,t)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,_u.prototype.submit.call(this,n,t)},Vr.prototype.destroy=function(n){this._emitter.removeEventListener(this._doc,"op",this._opHandler),this._emitter.removeEventListener(this._doc,"create",this._createOrDelHandler),this._emitter.removeEventListener(this._doc,"del",this._createOrDelHandler),this._emitter.removeEventListener(this._doc,"load",this._loadHandler),this._emitter.removeEventListener(this._doc,"destroy",this._destroyHandler),_u.prototype.destroy.call(this,n)},Vr.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},Vr.prototype._registerWithDoc=function(){this._emitter.addEventListener(this._doc,"op",this._opHandler),this._emitter.addEventListener(this._doc,"create",this._createOrDelHandler),this._emitter.addEventListener(this._doc,"del",this._createOrDelHandler),this._emitter.addEventListener(this._doc,"load",this._loadHandler),this._emitter.addEventListener(this._doc,"destroy",this._destroyHandler)},Vr.prototype._transformAgainstOp=function(n,t){var e=this,r=this._doc._dataStateVersion;this._pendingMessages.forEach(function(i){var o=e._docDataVersionByPresenceVersion[i.pv];if(!(o>=r))try{i.p=e._transformPresence(i.p,n,t),e._docDataVersionByPresenceVersion[i.pv]=r}catch(l){var s=e._getCallback(i.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(i){this.emit("error",i)}},Vr.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Vr.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Vr.prototype._message=function(){var n=_u.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Vr.prototype._transformPresence=function(n,t,e){var r=this._doc.type;if(!iN.supportsPresence(r))throw new t2(e2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+r.name);return r.transformPresence(n,t,e)};var n2={};(function(n){var t=Su,e=Vh,r=gr,i=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[c];if(d==null||typeof d!="object")return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(i.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(i.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new e(i.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new e(i.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new e(i.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new e(i.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=c.create,h=t.map[d.type];if(!h)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(E){return E}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var C=o(l,c.op);if(C)return C;l.v++}else l.v++};function o(l,c){if(!l.type)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new e(i.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,c)}catch(h){return new e(i.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,c,d){if(c.v!=null&&c.v!==d.v)return new e(i.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(c.create||"op"in c)return new e(i.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in c||c.create||c.del)||"op"in d&&c.create)return new e(i.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in c){if(!l)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,d.op,"left")}catch(h){return h}}}c.v!=null&&c.v++},n.applyOps=function(l,c,d){d=d||{};for(var h=0;h<c.length;h++){var C=c[h];if(d._normalizeLegacyJson0Ops)try{s(l,C)}catch{return new e(i.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=C.v;var E=n.apply(l,C);if(E)return E}},n.transformPresence=function(l,c,d){var h=this.checkOp(c);if(h)return h;var C=l.t;if(typeof C=="string"&&(C=t.map[C]),!C)return{code:i.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!r.supportsPresence(C))return{code:i.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:C.transformPresence(l.p,c.op,d)}catch(E){return{code:i.ERR_PRESENCE_TRANSFORM_FAILED,message:E.message||E}}l.v++};function s(l,c){if(l.type===t.defaultType.uri){var d=c.op;if(!!d){var h=l.data;d.length>1&&(h=r.clone(h));for(var C=0;C<d.length;C++){var E=d[C];typeof E.lm=="string"&&(E.lm=+E.lm);for(var x=E.p,v=h,k=0;k<x.length;k++){var L=x[k];Object.prototype.toString.call(v)=="[object Array]"?x[k]=+L:v.constructor===Object&&(x[k]=L.toString()),v=v[L]}C<d.length-1&&(h=t.defaultType.apply(h,[E]))}}}}})(n2);var Mu=XT,sN=n2,lN=pr;function pr(n,t){Mu.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._emitter=this.connection._docPresenceEmitter,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()}pr.prototype=Object.create(Mu.prototype),pr.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},pr.prototype.destroy=function(n){this._emitter.removeEventListener(this._doc,"op",this._opHandler),this._emitter.removeEventListener(this._doc,"create",this._createDelHandler),this._emitter.removeEventListener(this._doc,"del",this._createDelHandler),this._emitter.removeEventListener(this._doc,"load",this._loadHandler),Mu.prototype.destroy.call(this,n)},pr.prototype._registerWithDoc=function(){this._emitter.addEventListener(this._doc,"op",this._opHandler),this._emitter.addEventListener(this._doc,"create",this._createDelHandler),this._emitter.addEventListener(this._doc,"del",this._createDelHandler),this._emitter.addEventListener(this._doc,"load",this._loadHandler)},pr.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))}})}},pr.prototype._handleOp=function(n,t,e){var r=e===this.src;this._transformAgainstOp(n,r),this._cacheOp(n,r),this._setPendingPresence()},Mu.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Mu.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},pr.prototype._transformAgainstOp=function(n,t){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,t)}catch(e){return this.presence.emit("error",e)}this.presence._updateRemotePresence(this)}},pr.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],t=n.op,e=n.isOwnOp;t===null?(this._pending.p=null,this._pending.v++):sN.transformPresence(this._pending,t,e)}var r=this._pending.v>=this._doc.version;return r&&this._stopCachingOps(),r},pr.prototype._startCachingOps=function(){this._opCache=[]},pr.prototype._stopCachingOps=function(){this._opCache=null},pr.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var r2=ZT,aN=oN,cN=lN;function Da(n,t,e){var r=Da.channel(t,e);r2.call(this,n,r),this.collection=t,this.id=e}var uN=Da;Da.prototype=Object.create(r2.prototype),Da.channel=function(n,t){return n+"."+t},Da.prototype._createLocalPresence=function(n){return new aN(this,n)},Da.prototype._createRemotePresence=function(n){return new cN(this,n)};var fN=dN;function dN(n,t,e,r,i){this.id=n,this.v=t,this.type=e,this.data=r,this.m=i}var hN=fN,i2=Yo,o2=Uu;function Uu(n,t,e,r,i){if(i2.EventEmitter.call(this),typeof i!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=r,this.collection=e,this.callback=i,this.sent=!1}i2.mixin(Uu),Uu.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Uu.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Uu.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,r=new hN(this.id,t.v,t.type,t.data,e);this.callback(null,r)};var s2=o2,mN=gr,gN=Jo.ACTIONS,pN=Vp;function Vp(n,t,e,r,i,o){if(s2.call(this,n,t,e,r,o),!mN.isValidVersion(i))throw new Error("Snapshot version must be a positive integer or null");this.version=i}Vp.prototype=Object.create(s2.prototype),Vp.prototype._message=function(){return{a:gN.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var l2=o2,CN=gr,EN=Jo.ACTIONS,AN=$p;function $p(n,t,e,r,i,o){if(l2.call(this,n,t,e,r,o),!CN.isValidTimestamp(i))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=i}$p.prototype=Object.create(l2.prototype),$p.prototype._message=function(){return{a:EN.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var Ci=gr,xN=Rg.default.EventEmitter,bN=["create","del","destroy","load","op"],vN=Ou;function Ou(){this._docs={},this._forwarders={},this._emitters={}}Ou.prototype.addEventListener=function(n,t,e){this._registerDoc(n);var r=Ci.dig(this._emitters,n.collection,n.id);r.on(t,e)},Ou.prototype.removeEventListener=function(n,t,e){var r=Ci.dig(this._emitters,n.collection,n.id);!r||(r.off(t,e),r._eventsCount===1&&this._unregisterDoc(n))},Ou.prototype._registerDoc=function(n){var t=!0;if(Ci.digOrCreate(this._docs,n.collection,n.id,function(){return t=!1,n}),!t){var e=Ci.digOrCreate(this._emitters,n.collection,n.id,function(){var i=new xN;return i.setMaxListeners(1e3),i}),r=this;bN.forEach(function(i){var o=Ci.digOrCreate(r._forwarders,n.collection,n.id,i,function(){return e.emit.bind(e,i)});n.on(i,o)}),this.addEventListener(n,"destroy",this._unregisterDoc.bind(this,n))}},Ou.prototype._unregisterDoc=function(n){var t=Ci.dig(this._forwarders,n.collection,n.id);for(var e in t)n.off(e,t[e]);var r=Ci.dig(this._emitters,n.collection,n.id);r.removeAllListeners(),Ci.digAndRemove(this._forwarders,n.collection,n.id),Ci.digAndRemove(this._emitters,n.collection,n.id),Ci.digAndRemove(this._docs,n.collection,n.id)};var BN=GO,TN=QO,yN=ZT,a2=uN,kN=pN,RN=AN,c2=Yo,_a=Vh,se=Jo.ACTIONS,u2=Su,$r=gr,Nu=FT,wN=vN,Pu=_a.CODES;function f2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var SN=Rt;function Rt(n){c2.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.nextSnapshotRequestId=1,this.queries={},this._presences={},this._docPresenceEmitter=new wN,this._snapshotRequests={},this.seq=1,this._presenceSeq=1,this.id=null,this.agent=null,this.debug=!1,this.state=f2(n),this.bindToSocket(n)}c2.mixin(Rt),Rt.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var t=f2(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(r){try{var i=typeof r.data=="string"?JSON.parse(r.data):r.data}catch{Nu.warn("Failed to parse message",r);return}e.debug&&Nu.info("RECV",JSON.stringify(i));var o={data:i};if(e.emit("receive",o),!!o.data)try{e.handleMessage(o.data)}catch(s){$r.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(r){e.emit("connection error",r)},n.onclose=function(r){r==="closed"||r==="Closed"?e._setState("closed",r):r==="stopped"||r==="Stopped by server"?e._setState("stopped",r):e._setState("disconnected",r)}},Rt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=d2(n.error,n),delete n.error),n.a){case se.initLegacy:return this._handleLegacyInit(n);case se.handshake:return this._handleHandshake(t,n);case se.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case se.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case se.queryUnsubscribe:return;case se.queryUpdate:var e=this.queries[n.id];if(!e)return;if(t)return e._handleError(t);n.diff&&e._handleDiff(n.diff),n.hasOwnProperty("extra")&&e._handleExtra(n.extra);return;case se.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case se.bulkSubscribe:case se.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case se.snapshotFetch:case se.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case se.fetch:var r=this.getExisting(n.c,n.d);r&&r._handleFetch(t,n.data);return;case se.subscribe:case se.unsubscribe:var r=this.getExisting(n.c,n.d);r&&r._handleSubscribe(t,n.data);return;case se.op:var r=this.getExisting(n.c,n.d);r&&r._handleOp(t,n);return;case se.presence:return this._handlePresence(t,n);case se.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case se.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case se.presenceRequest:return this._handlePresenceRequest(t,n);case se.pingPong:return this._handlePingPong(t);default:Nu.warn("Ignoring unrecognized message",n)}};function d2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}Rt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var r in t.data){var i=t.data[r],o=this.getExisting(t.c,r);o&&(n?o[e](n):i.error?o[e](d2(i.error)):o[e](null,i))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var r=t.b[s],o=this.getExisting(t.c,r);o&&o[e](n)}else if(t.b)for(var r in t.b){var o=this.getExisting(t.c,r);o&&o[e](n)}else Nu.error("Invalid bulk message",t)},Rt.prototype._reset=function(){this.agent=null},Rt.prototype._setState=function(n,t){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var e=new _a(Pu.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var r in this.queries){var i=this.queries[r];i._onConnectionStateChanged()}for(var o in this.collections){var s=this.collections[o];for(var r in s)s[r]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var r in this._snapshotRequests){var c=this._snapshotRequests[r];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},Rt.prototype.startBulk=function(){this.bulk||(this.bulk={})},Rt.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var t=this.bulk[n];this._sendBulk("f",n,t.f),this._sendBulk("s",n,t.s),this._sendBulk("u",n,t.u)}this.bulk=null},Rt.prototype._sendBulk=function(n,t,e){if(!!e){var r=[],i={},o=0,s;for(var l in e){var c=e[l];c==null?r.push(l):(i[l]=c,s=l,o++)}if(r.length===1){var l=r[0];this.send({a:n,c:t,d:l})}else r.length&&this.send({a:"b"+n,c:t,b:r});if(o===1){var d=i[s];this.send({a:n,c:t,d:s,v:d})}else o&&this.send({a:"b"+n,c:t,b:i})}},Rt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var r=this.bulk[t.collection]||(this.bulk[t.collection]={}),i=r[n]||(r[n]={}),o=i.hasOwnProperty(t.id);return i[t.id]=e,o}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},Rt.prototype.sendFetch=function(n){return this._sendActions(se.fetch,n,n.version)},Rt.prototype.sendSubscribe=function(n){return this._sendActions(se.subscribe,n,n.version)},Rt.prototype.sendUnsubscribe=function(n){return this._sendActions(se.unsubscribe,n)},Rt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:se.op,c:n.collection,d:n.id,v:n.version,src:t.src,seq:t.seq,x:{}};"op"in t&&(e.op=t.op),t.create&&(e.create=t.create),t.del&&(e.del=t.del),n.submitSource&&(e.x.source=t.source),this.send(e)},Rt.prototype.send=function(n){this.debug&&Nu.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Rt.prototype.ping=function(){if(!this.canSend)throw new _a(Pu.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:se.pingPong};this.send(n)},Rt.prototype.close=function(){this.socket.close()},Rt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},Rt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),r=e[t];return r||(r=e[t]=new BN(this,n,t),this.emit("doc",r)),r._wantsDestroy=!1,r},Rt.prototype._destroyDoc=function(n){!n._wantsDestroy||($r.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Rt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},Rt.prototype._createQuery=function(n,t,e,r,i){var o=this.nextQueryId++,s=new TN(n,this,o,t,e,r,i);return this.queries[o]=s,s.send(),s},Rt.prototype._destroyQuery=function(n){delete this.queries[n.id]},Rt.prototype.createFetchQuery=function(n,t,e,r){return this._createQuery(se.queryFetch,n,t,e,r)},Rt.prototype.createSubscribeQuery=function(n,t,e,r){return this._createQuery(se.querySubscribe,n,t,e,r)},Rt.prototype.hasPending=function(){return!!(this._firstDoc(Gh)||this._firstQuery(Gh)||this._firstSnapshotRequest())};function Gh(n){return n.hasPending()}Rt.prototype.hasWritePending=function(){return!!this._firstDoc(LN)};function LN(n){return n.hasWritePending()}Rt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Gh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Gh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var r=this._firstSnapshotRequest();if(r){r.once("ready",this._nothingPendingRetry(n));return}$r.nextTick(n)},Rt.prototype._nothingPendingRetry=function(n){var t=this;return function(){$r.nextTick(function(){t.whenNothingPending(n)})}},Rt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var r in e){var i=e[r];if(n(i))return i}}},Rt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},Rt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Rt.prototype.fetchSnapshot=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new kN(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},Rt.prototype.fetchSnapshotByTimestamp=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new RN(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},Rt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},Rt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Rt.prototype._initializeHandshake=function(){this.send({a:se.handshake,id:this.id})},Rt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},Rt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Rt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new _a(Pu.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(u2.map[n.type]!==u2.defaultType)return this.emit("error",new _a(Pu.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new _a(Pu.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Rt.prototype.getPresence=function(n){var t=this,e=$r.digOrCreate(this._presences,n,function(){return new yN(t,n)});return e._wantsDestroy=!1,e},Rt.prototype.getDocPresence=function(n,t){var e=a2.channel(n,t),r=this,i=$r.digOrCreate(this._presences,e,function(){return new a2(r,n,t)});return i._wantsDestroy=!1,i},Rt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var r={a:n,ch:e.channel,seq:t};return this.send(r),r.seq},Rt.prototype._addPresence=function(n){$r.digOrCreate(this._presences,n.channel,function(){return n})},Rt.prototype._handlePresenceSubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},Rt.prototype._handlePresenceUnsubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},Rt.prototype._handlePresence=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},Rt.prototype._handlePresenceRequest=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var h2=SN,IN=Su;const Fu={err:1001,msg:"user auth error",name:"AuthError"},Wh={err:1002,msg:"you don't have required permission",name:"PermissionError"},Hp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Ku={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},DN={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},_N={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},ol="x-live-editor-token",Ma="x-live-editor-base-url",mn=I("auth-connection");function MN(n){try{n()}catch(t){mn.error(t)}}class UN{constructor(t,e){m(this,"enabled",!0);m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new Sb.EventEmitter);m(this,"token",null);m(this,"resourceToken",null);m(this,"pingOptions",{interval:5e4,timeout:15e4});m(this,"reAuth",async()=>{if(this.connection&&this.reauthFunc){const t=await this.reauthFunc();await this.auth(t);const e=this.pingOptions;this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t,options:{ping:e}})}}});this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return li(this.getBaseURL())}async auth(t){p(mn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,r=await window.fetch(e,{method:"GET",headers:{[ol]:t.token,[Ma]:this.getBase64BaseURL()},credentials:"include"});return r.status,this.enabled?(this.token=t.token,await r.json()):{read:"",user:""}}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Ma]:li(this.getBaseURL())}})}async init(t){const e=await this.auth(t);if(!this.enabled)return;this.resourceToken=e.read,this.ws=new o9.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(h2.prototype),p(mn,this.connection,"no this.connection");const r=this.ws,i=this.pingOptions;this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t,options:{ping:i}}),this._ping==null&&(this._ping=window.setInterval(()=>{var d;const c=Date.now();c-((d=this.lastReceiveTime)!=null?d:0)>i.interval&&this.send({a:"ping",id:this.id,ts:c}),this.lastReceiveTime&&c-this.lastReceiveTime>i.timeout&&r&&r.readyState===r.OPEN&&(r.reconnect(),this.lastReceiveTime=Date.now())},1e3))};const o=this.connection.handleMessage.bind(this.connection);let s=!1;this.connection.handleMessage=l=>{var d;const c=l;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in c||c.a==="pong")s=!1,this.handleMessage(c);else{Object.prototype.hasOwnProperty.call(c,"a")&&c.a==="hs"&&this.retryCount>=5&&(s?(mn.info("retrying re-auth success"),s=!1,this.emitAuthRecover()):s=!0),Object.prototype.hasOwnProperty.call(c,"a")&&c.a!=="init"&&c.a!=="hs"&&(this.retryCount=0);try{o(c)}catch(h){if((h==null?void 0:h.type)==="writeConflict"){this.emitWriteConflictError(h,c);return}if((d=h==null?void 0:h.message)!=null&&d.startsWith("Cannot invert subtype")){this.emitWriteConflictError(h,c);return}throw h}}},h2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc){this.retryCount>=5&&(mn.warn("retry auth times exceed 5, broadcast auth error"),this.emitAuthError()),this.retryCount+=1,mn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();if(await this.auth(t),!this.enabled){this.retryCount=10,setTimeout(()=>this.handleAuthError(),0);return}const e=this.pingOptions;this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t,options:{ping:e}})}}}catch(t){mn.error(t),setTimeout(()=>this.handleAuthError(),0)}}}emitPermissionError(){const t=new Error(Wh.msg);t.code=Wh.err,this.events.emit("error",t)}emitAuthRecover(){this.events.emit("authRecover")}emitAuthError(){const t=new Error(Fu.msg);t.code=Fu.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Ku.msg);t.code=Ku.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const r=e.err;if(r===Fu.err)mn.warn("auth error"),this.handleAuthError();else if(r===Hp.err)mn.warn(Hp.msg),this.emitMaxUsersError();else if(r===Ku.err){mn.warn(Ku.msg);try{this.emitRequestReloadError()}catch(i){mn.error(`error occurred while process reload error: ${JSON.stringify(i)}`)}finally{this.end(!1)}}else r===Wh.err?this.emitPermissionError():(mn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError())}get(t,e){return p(mn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(p(mn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onAuthError(t){this.events.addListener("error",t)}onAuthRecover(t){this.events.addListener("authRecover",t)}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){p(mn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){p(mn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e,r;this.enabled=!1,this.reauthFunc=void 0,this.events.removeAllListeners(),MN(()=>{var i;return(i=this.connection)==null?void 0:i.close()}),(e=this.connection)!=null&&e._ping&&window.clearInterval(this.connection._ping),this.connection=void 0,(r=this.ws)==null||r.close(),this.ws=void 0,t&&this.logout()}}I("utils/file");function ON(){function n(){return new Promise(t=>{const e=new FileReader;e.onload=()=>{t(e.result)},e.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}ON();async function NN(n){const e=n.size,r=Math.floor((e+102400-1)/102400),i=new s9.Hash;for(let s=0;s<r;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const h=await n.slice(l,c,n.type).arrayBuffer();i.update(new Uint8Array(h))}const o=i.digest();return li(o)}const Ei=I("sharedb-doc/client"),PN=Lb.default.create();class FN{constructor(t,e,r){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",tt());m(this,"getDoc",async()=>{const t=r=>new Promise((i,o)=>{r.fetch(s=>{s?o(s):i()})});p(Ei,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),Ei.debug(e),e});this.auth=t;const i=`${e}/${this.auth.appId}/${this.auth.docId}`;IN.register(Id.type),this.connection=new UN(i,r),this.reauthFunc=r}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(Ei,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,r=>{(t==="error"||this.doc)&&e(r)})}onAuthError(t){this.connection.onAuthError(t)}onAuthRecover(t){this.connection.onAuthRecover(t)}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,r,i,o){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...o},data:{name:r,size:i}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const r=`${this.apiServer()}/resources`;try{const i=`${r}/hash`,o=await this.request(i,{method:"post",headers:{[ol]:this.connection.token},data:{resources:t}});return o.data&&Array.isArray(o.data)?o.data:[]}catch{return[]}}async uploadFile(t,e,r,i,o){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=x=>{Ei.info(`on progress: ${x.loaded}`);let v=x.loaded*100/s;v>100&&(v=100),i(v)},c=await NN(e),d=await this.getFileUrlByHash(t,c,e.name,e.size,r);if(d)return i(-1),d;let h=t;o!=null&&o.thumbnail&&(h+="/thumbnail");const C=new FormData;C.append("file-size",`${e.size}`),C.append("file-hash",c),C.append("file",e,e.name);const E=await this.request(h,{method:"post",data:C,withCredentials:!0,headers:{...r},onUploadProgress:l});return Ei.info(E),i(100),Array.isArray(E.data)?E.data[0]:E.data}async uploadResource(t,e=()=>{},r){const o=`${this.apiServer()}/resources`;p(Ei,this.connection.token,"no connection token");const s=await this.uploadFile(o,t,{[ol]:this.connection.token},e,r);return p(Ei,s,"no result"),s}async request(t,e){var o,s;let r=this.connection.token,i;for(let l=0;l<2;l++){const c=e||{};c.url=t,c.headers||(c.headers={}),p(Ei,r,"no token"),c.headers={...c.headers,[ol]:r,[Ma]:this.connection.getBase64BaseURL()};try{return await PN(t,c)}catch(d){if(i=d,((o=d==null?void 0:d.response)==null?void 0:o.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;r=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw p(Ei,i,"no error"),i}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=Ib.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(Ei,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const r=`${this.apiServer()}/resources/external/${li(t)}`;return(await this.request(r)).data}getResourceId(t){const e=/\/resources\/([^?]+)/,r=t.match(e);return r&&r.length>=2?r[1]:""}buildResourceUrl(t,e){var s,l;if(!t)return"";if(t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;const r=this.apiServer();if(t.startsWith("http:")||t.startsWith("https:")){const c=r.replace(/\/[^/]*$/,"");if(c&&t.includes(c)){const d=this.auth.docId,h=`${c}/`,C="/resources",E=t.indexOf(h),x=t.indexOf(C,E+h.length);if(E!==-1&&x!==-1){const v=t.substring(E+h.length,x);if(v!==d){let k=t.replace(v,d);const L=new URL(k),M="token";(s=L.searchParams)==null||s.delete(M),k=L.toString();const U=this.getResourceId(k);return e!=null&&e.syncNewResources&&((l=e==null?void 0:e.syncNewResources)==null||l.call(e,U,k)),k}return t}return t}return t}let i=`${r}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken&&o.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const c=o.join("&");i+=`?${c}`}return i}reAuth(){this.connection.reAuth()}}function KN(){return{blocks:[{id:tt(),type:"text",text:[]}],comments:{},meta:{}}}const jp=I("block-ids");class VN{constructor(){m(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((i,o)=>o-i);for(let i=0;i<e.length;i++){const o=e[i];if(o>=t){const s=this.ids.get(o);p(jp,s!==void 0,"old id is not exists"),this.ids.delete(o),this.ids.set(o+1,s)}}const r=tt();this.ids.set(t,r)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((r,i)=>r-i);for(let r=0;r<e.length;r++){const i=e[r];if(i>t){const o=this.ids.get(i);p(jp,o!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i-1,o)}}}getId(t){let e=this.ids.get(t);return e||(e=tt(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class $N{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new VN,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let r=0;r<e.length;r++){const i=e[r],o=i[1].getById(t);if(o)return{containerId:i[0],blockIndex:o[0]}}return p(jp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class m2{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,r)=>{t[r]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const zp=I("op-parse-handler");class HN{constructor(t,e){m(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const r={...t,containerId:(i=>i==="blocks"?"root":i)(t.containerId)};this.actions.push(r)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,r){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:r})}onDeleteBlockData(t,e,r){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:r})}onInsertBlockData(t,e,r,i){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:r,value:i})}onUpdateBlockText(t,e,r){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:r})}onDeleteContainer(t){this.pushActions({type:"deleteContainer",containerId:t})}onCreateContainer(t,e){this.pushActions({type:"createContainer",containerId:t,data:e})}onDeleteComment(t){this.pushActions({type:"deleteComment",commentId:t})}onCreateComment(t){this.pushActions({type:"createComment",commentId:t})}onUpdateComment(t){this.pushActions({type:"updateComment",commentId:t})}end(){const t=this.actions,e=new Set,r=new Map,i=new $N,o=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of o)if(s.type==="deleteBlock"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);i.onDeleteBlock(l.containerId,l.blockIndex);const d=r.get(c);d&&(zp.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),r.delete(c));const h=`${l.containerId}-${l.blockIndex}`;e.add(h),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,c=`${l.containerId}-${l.blockIndex}`;if(e.has(c)){zp.warn("delete block data after delete block, ignore it");continue}const d=i.getBlockId(l.containerId,l.blockIndex);let h=r.get(d);h||(h=new m2,r.set(d,h)),h.delete(l.key)}else p(zp,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);let d=r.get(c);d||(d=new m2,r.set(c,d)),d.insert(l.key,l.value)}else if(s.type==="updateBlockText"){const l=s;this.outerHandler.onUpdateBlockText(l.containerId,l.blockIndex,l.richTextData,this.local)}else if(s.type==="createComment"){const l=s;this.outerHandler.onCreateComment(l.commentId,this.local)}else if(s.type==="updateComment"){const l=s;this.outerHandler.onUpdateComment(l.commentId,this.local)}}),Array.from(r.entries()).forEach(([s,l])=>{const{containerId:c,blockIndex:d}=i.getBlockIndexById(s);this.outerHandler.onUpdateBlockData(c,d,l.toDocBlockDelta(),this.local)})}}const Ke=I("op-parser");class g2{}class Gp{constructor(t){m(this,"key");this.key=t}}function jN(n,t,e){const r=t.concat(),i=r[0];if(typeof i!="number"||(r.shift(),r.length===1))return!1;const o=r[0];if(typeof o!="object"||!o.i||Object.keys(o).length!==1)return!1;for(let l=1;l<r.length;l++){const c=r[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const h=c[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=o.i;p(Ke,s.id,"block id is required"),p(Ke,s.type,"block type is required");for(let l=1;l<r.length;l++){const c=r[l],d=c[0],h=c[1];s[d]=h.i}return e.onInsertBlock(n,i,s),!0}function Wp(n,t,e,r){if(e==="upsert"&&jN(n,t,r))return;p(Ke,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const i=t.concat(),o=i[0];i.shift();const s=[];for(;i.length>0;){const l=i[0];if(l==="text"){const c=i[1];if(p(Ke,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),p(Ke,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),i.splice(0,2),e==="upsert"){const h=c.e;r.onUpdateBlockText(n,o,h)}p(Ke,i.length===0,`invalid block ops.length !== 0, ${JSON.stringify(i)}`)}else if(Array.isArray(l)){p(Ke,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];p(Ke,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const d=l[1];if(c==="text"){if(p(Ke,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&r.onInsertBlockData(n,o,c,d.i),d.r&&e==="remove"&&r.onDeleteBlockData(n,o,c),d.et==="rich-text"&&e==="upsert"){const C=d.e;r.onUpdateBlockText(n,o,C)}}else e==="remove"&&d.r&&s.push(new Gp(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i);i.shift()}else if(typeof l=="object"){const c=l;e==="remove"&&c.r&&s.push(new g2),e==="upsert"&&c.i&&r.onInsertBlock(n,o,c.i),i.shift()}else{p(Ke,typeof l=="string","data is not string"),p(Ke,l!=="text","data !== 'text'"),p(Ke,i.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(i)}`);const c=l,d=i[1];e==="remove"&&d.r&&s.push(new Gp(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i),i.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof g2?r.onDeleteBlock(n,o):l instanceof Gp?r.onDeleteBlockData(n,o,l.key):p(Ke,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function zN(n,t,e){Ke.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function GN(n,t,e){const r=n[1],i=n[2];p(Ke,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),p(Ke,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?Ke.error(`unknown comment op, ${JSON.stringify(n)}`):i.i&&i.r?t==="upsert"&&e.onUpdateComment(r):i.i?t==="upsert"&&e.onCreateComment(r):i.r?t==="remove"&&e.onDeleteComment(r):Ke.error(`unknown comment op, ${JSON.stringify(n)}`)}function qp(n,t,e){const r=n[0];if(Array.isArray(r)){r.forEach(s=>{qp(s,t,e)});return}const i=r;if(p(Ke,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){zN(n);return}if(i==="comments"){GN(n,t,e);return}const o=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Wp(o,s,t,e)}):n.slice(1).forEach(s=>{Wp(o,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(o),s.i&&t==="upsert"&&e.onCreateContainer(o,s.i)}else p(Ke,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Wp(o,n.slice(1),t,e)}function Xp(n,t,e){const r=new HN(t,e);for(let i=0;i<2;i++){const o=i===0?"remove":"upsert",s=mt.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{qp(c,o,r)}):qp(s,o,r)}r.end()}const WN=I("sharedb-comments");function Yp(n){const t=n.blocks;p(WN,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([r,i])=>{Array.isArray(i)&&(e.blocks[r]=i)}),mt.default(e)}function p2(n){const{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}=n;return{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}}function Qp(n,t){const e=RO(t),{comments:r,meta:i,blocks:o,...s}=e,l={...n,blocks:o,...s},c=mt.default(l);return delete c.children,c}const le=I("sharedb-doc/doc-container"),C2="ot-json1";Id.type.registerSubtype(wO.type),Id.type.name=C2,Id.type.invert=null;class Vu extends aa{constructor(e,r,i=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new yO);m(this,"batching",0);m(this,"status","clean");m(this,"disableLogout");m(this,"destroyed",!1);m(this,"handleNothingPending",()=>{this.setStatus("clean")});m(this,"handleCreate",()=>{this.handleReload("doc created")});m(this,"handleDel",()=>{});m(this,"handleReload",e=>{this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)})});m(this,"handleReset",async e=>{const r=new Error(`reset doc: ${e}`);r.code="ResetDoc",this.callbacks.forEach(i=>{var o;return(o=i.onError)==null?void 0:o.call(i,r)}),this.destroy()});m(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});m(this,"insertObject",async(e,r,i)=>{const o=[e,r,{i}];return this.submitOp(o)});m(this,"deleteObject",async(e,r)=>{const i=[e,r,{r:!0}];return this.submitOp(i)});m(this,"replaceObject",async(e,r,i)=>{const o=[e,r,{r:!0,i}];return this.submitOp(o)});m(this,"updateObject",async(e,r,i)=>{const o=this.data()[e][r],s=[e,r];return Object.entries(i).forEach(([l,c])=>{if(!$c.default(o[l],c))if(o[l]===void 0){if(c!=null){const d={i:c};s.push([l,d])}}else if(c==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:c};s.push([l,d])}}),Object.entries(o).forEach(([l,c])=>{if((i[l]===void 0||i[l]===null)&&c!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});m(this,"broadcastMessage",async e=>{const r={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(r)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async e=>new Promise((r,i)=>{if(this.destroyed){le.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},o=>{o?(le.error(`invalid op, ${o.message}, ${JSON.stringify(e)}`),i(o),le.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):r()}),this.doc.data||(le.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));m(this,"createDoc",async e=>new Promise((r,i)=>{this.doc.create(e,C2,o=>{o?i(o):r()})}));m(this,"submitInsertChildContainers",async e=>{if(e.length===0)return Promise.resolve();const r=e.map(({containerId:i,blocks:o})=>[ro(i),{i:o}]);return this.submitOp([r])});m(this,"submitDeleteChildContainer",async e=>{const r=[ro(e),{r:!0}];return this.submitOp(r)});m(this,"submitInsertBlock",async(e,r,i)=>{const o=[ro(e),r,{i}];return this.submitOp(o)});m(this,"submitDeleteBlock",async(e,r)=>{const i=[ro(e),r,{r:!0}];return this.submitOp(i)});m(this,"submitUpdateBlockData",async(e,r,i)=>{if(i.delete.length===0&&Object.keys(i.insert).length===0)return Promise.resolve();const o=[ro(e),r],s=new Set(i.delete);Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c)){const h={r:!0,i:d};o.push([c,h])}});const l=new Set(Object.keys(i.insert));return i.delete.forEach(c=>{if(l.has(c))return;const d={r:!0};o.push([c,d])}),Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c))return;const h={i:d};o.push([c,h])}),this.submitOp(o)});m(this,"submitUpdateRichText",async(e,r,i)=>{const o=[ro(e),r,"text",{e:i,et:"rich-text"}];return this.submitOp(o)});m(this,"handleOp",(e,r,i)=>{if(this.destroyed){le.warn("handleOp: destroyed");return}try{Xp(e,this,!!r)}catch(o){throw le.error(o),o}});this.client=e,this.doc=r,this.doc.preventCompose=!0,this.disableLogout=i,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,p(le,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const r=new FN(e.auth,e.serverUrl,e.reauthFunc),i=await r.getDoc(),o=new Vu(r,i,e.disableLogout);if(i.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await o.createDoc(e.templateData||KN())}return await o.initPresence(),await o.subscribe(),o.initEvents(),o}catch(r){throw le.error(r),le.error(`failed to load doc: ${JSON.stringify(r)}`),r}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onAuthError(e=>{this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}),this.client.onAuthRecover(()=>{this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((e,r)=>{if(this.localPresence)e();else{const i=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);i.on("receive",(o,s)=>{this.onCustomMessage(s)}),i.subscribe(o=>{o?r(o):(this.localPresence=i.create(tt()),e())})}})}subscribe(){return new Promise((e,r)=>{this.doc.subscribe(i=>{i?r(i):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return no(this.data())}getContainerBlocks(e){const r=this.data();p(le,r,"no doc data");const i=r[ro(e)];return p(le,i,`no container data: ${e}`),mt.default(i)}findContainerBlocks(e){const r=this.data();p(le,r,"no doc data");const i=r[ro(e)];return i!=null?i:null}getBlockData(e,r){const i=this.data();p(le,i,"no doc data");const o=i[ro(e)];p(le,o,`no container data: ${e}`);const s=o[r];return p(le,s,`no block data: ${r}`),mt.default(s)}localInsertBlock(e,r,i){return this.submitInsertBlock(e,r,i),this.getBlockData(e,r)}localDeleteBlock(e,r){const i=this.getBlockData(e,r);return this.submitDeleteBlock(e,r),i}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(le,o.text,"no block text");const s=mt.default(o.text);this.submitUpdateRichText(e,r,i);const l=hn.apply(s,i);return p(le,l,"no block text"),l}localUpdateBlockData(e,r,i){const o=mt.default(this.getBlockData(e,r));return this.submitUpdateBlockData(e,r,i),o}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(r=>{this.submitDeleteChildContainer(r)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(r=>p2(r))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const r=this.data().comments[e];return Yp(r)}localCreateComment(e,r){const i=Qp(e,r),s=["comments",i.id,{i}];return this.submitOp(s)}localDeleteComment(e){const r=["comments",e,{r:!0}];return this.submitOp(r)}localUpdateComment(e,r){const i=Qp(e,r),o=["comments",e.id,{r:!0,i}];return this.submitOp(o)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,r,i){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onDeleteBlock)==null?void 0:s.call(o,Ia(e),r,i)})}onInsertBlock(e,r,i,o){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Ia(e),r,i,o)})}onUpdateBlockData(e,r,i,o){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Ia(e),r,i,o)})}onUpdateBlockText(e,r,i,o){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Ia(e),r,i,o)})}onDeleteContainer(e,r){p(le,this.callbacks.length>0,"no callbacks"),p(le,e!=="root","should not delete root container in doc"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,Ia(e),r)})}onCreateContainer(e,r,i){p(le,this.callbacks.length>0,"no callbacks"),p(le,e!=="root","should not create root container in doc"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,Ia(e),r,i)})}onDeleteComment(e,r){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteComment)==null?void 0:o.call(i,e,r)})}onCreateComment(e,r){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onCreateComment)==null?void 0:o.call(i,e,r)})}onUpdateComment(e,r){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onUpdateComment)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){const r=e;(r==null?void 0:r.type)==="custom"&&(r==null?void 0:r.clientId)!==this.client.clientId?this.callbacks.forEach(i=>{var o;return(o=i.onCustomMessage)==null?void 0:o.call(i,r.data)}):(r==null?void 0:r.type)==="onlineUsers"&&setTimeout(()=>{const i={type:"custom",data:e,clientId:"-"};this.onCustomMessage(i)})}onAuthRecover(){this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}async addResources(e){let r=[];return e.forEach(o=>{const s=o.split("|");r.push(...s)}),r=Array.from(new Set(r)),await this.client.getFileUrlsByHashes(r)}async uploadResource(e,r){var o;return{resourceId:await this.client.uploadResource(e,(o=r==null?void 0:r.onProgress)!=null?o:()=>{})}}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}request(e,r){return this.client.request(e,r)}getUser(){const e=this.client.clientId,{permission:r,userId:i,displayName:o,avatarUrl:s}=this.client.auth;return{permission:r,clientId:e,userId:i,displayName:o,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return no(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return no(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:no(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:no(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,r){Xp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}triggerReAuth(){this.client.reAuth()}}I("remote-cursor");class E2{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Me.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));m(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const r=this.editor.findBlockById(e);r&&this.editor.reloadBlock(r)})});this.editor=t,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const A2=I("remote-cursor-decorator");class Jp{decorateText(t,e,r){const i=t.doc.getRemoteUsers();if(!i)return{};const o=new Map,{containerId:s,blockIndex:l}=e[e.length-1];p(A2,typeof s=="string","invalid path containerId"),p(A2,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),d=dn(r);return i.getSimpleCursors(c.id).forEach((C,E)=>{E>d&&(E=d);const x=C.map(k=>({id:tt(),type:"remote-cursor",name:k.user.displayName,time:k.time,rainbowIndex:k.user.rainbowIndex})),v=o.get(E);v?v.push(...x):o.set(E,x)}),{insertions:o}}}const Zp=I("sharedb-doc/share-db-server"),qN=Lb.default.create();class XN{constructor(t,e){m(this,"auth");m(this,"clientId",tt());this.serverUrl=e,this.auth=t}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(Zp,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}apiServer(){const t=`${this.serverUrl}/${this.auth.appId}/${this.auth.docId}`;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}getBaseURL(){const t=new URL(this.apiServer());return`${t.protocol}//${t.host}${t.pathname}`}getBase64BaseURL(){return li(this.getBaseURL())}async request(t,e){var o;const r=this.auth.token,i=e||{};i.url=t,i.headers||(i.headers={}),p(Zp,r,"no token"),i.headers={...i.headers,[ol]:r,[Ma]:this.getBase64BaseURL()};try{return await qN(t,i)}catch(s){throw(o=s.response)!=null&&o.data&&(s.responseData=s.response.data),s}}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=Ib.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(Zp,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let i=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken,e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const s=o.join("&");i+=`?${s}`}return i}}const YN=I("sharedb-doc/share-db-server");function x2(n){const t=new URL(n);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}function QN(n){return li(x2(n))}class qh extends aa{constructor(e){super();m(this,"remoteUsers",new wu);m(this,"client");this.options=e,this.client=new XN(e.auth,e.serverUrl)}destroy(){}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}getRemoteUsers(){return this.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return no(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return no(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:no(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:no(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}parseHistoryData(e,r){Xp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}static async auth(e,r){p(YN,e.token,"no auth token");const i=`${x2(r)}/auth`,o=await window.fetch(i,{method:"GET",headers:{[ol]:e.token,[Ma]:QN(r)},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return await o.json()}static async load(e){const r=`${e.serverUrl}/${e.auth.appId}/${e.auth.docId}`;return await this.auth(e.auth,r),new qh(e)}}class b2 extends Be.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,r){if(Qt(Lr(this.editor,t)))return;const i=this.editor.getBlockByIndex(t,e),o=J(this.editor.getContainerById(t));o&&this.emit("change",this.editor,{containerId:t,blockIndex:e},o,i,r)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}onInsertBlock(t,e){Qt(Lr(this.editor,t))||this.emit("insert",this.editor,{containerId:t,blockIndex:e})}onDeleteBlock(t,e){this.handleChild(t,e,"remove")}destroy(){this.editor.doc.unregisterCallback(this)}}function v2(n,t){const e=n.addCustom("child-block-tracker",()=>new b2(n));e.addListener("change",t),e.addListener("insert",t)}function B2(n,t){const e=n.addCustom("child-block-tracker",()=>new b2(n));e.removeListener("change",t),e.removeListener("insert",t)}const uct="",JN={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",name:"\u6587\u672C\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},ZN={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},tP={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};D.mergeLang({"zh-CN":JN,"en-US":ZN,"ja-JP":tP});const fct="";I("button");function Cr(n,t,e,r,i){const o=B("button",["editor-button"],null);return o.setAttribute("data-button-id",n),i&&o.setAttribute(`data-editor-tooltip-${i}`,t),e?typeof e=="string"?e.startsWith("<")?o.innerHTML=e:o.innerText=e:o.appendChild(e):o.innerText=t,r&&(r.indexOf("checked")!==-1&&z(o,"checked"),r.indexOf("disabled")!==-1&&(o.disabled=!0),r.indexOf("primary")!==-1&&z(o,"primary")),o}const dct="",Xh=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
31
+ `)}return Xc([{type:"text/plain",data:new Blob([r],{type:"text/plain"})}]),!0}const $U=Object.freeze(Object.defineProperty({__proto__:null,editorHandleEnter:lT,editorHandleDelete:aT,editorHandleBackspace:cT,editorHandleInsertBr:uT,editorHandlePastePlainText:fT,isSelectedCodeTextBlock:dT,getSelectedCodeBlockMarkdown:hT,editorHandleCopyMarkdown:wp},Symbol.toStringTag,{value:"Module"})),Nh={ArrowDown:T5,ArrowUp:B5,ArrowLeft:b5,ArrowRight:v5,"Shift+ArrowDown":y5,"Shift+ArrowUp":w5,"Shift+ArrowLeft":k5,"Shift+ArrowRight":R5,"CtrlOrCmd+ArrowLeft":L5,"CtrlOrCmd+ArrowRight":I5,"CtrlOrCmd+Shift+ArrowLeft":D5,"CtrlOrCmd+Shift+ArrowRight":_5,"CtrlOrCmd+ArrowUp":M5,"CtrlOrCmd+ArrowDown":Ap,"CtrlOrCmd+Shift+ArrowUp":U5,"CtrlOrCmd+Shift+ArrowDown":xp,"CtrlOrCmd+A":bp,Home:V5,End:$5,"Shift+Home":F5,"Shift+End":K5,PageUp:W5,PageDown:q5,"Shift+PageUp":Y5,"Shift+PageDown":Q5,"CtrlOrCmd+Z":LU,"CtrlOrCmd+Shift+Z":IU,Enter:lT,Delete:aT,Backspace:cT,"Shift+Enter":uT,"CtrlOrCmd+Shift+V":fT,"CtrlOrCmd+Shift+C":wp};function mT(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function gT(n,t,e){if(t.type==="embed"){const o=t.embedData,s=o.src;if(s&&typeof s=="string"){const l=e.get(s);if(l)o.src=l;else{let c="";s.split("|").forEach(h=>{const C=e.get(h);C&&(c+=c?`|${C}`:`${C}`)}),c&&(o.src=c)}}return}const r=t.text;r&&r.forEach(o=>{if(o.attributes&&o.attributes.src&&typeof o.attributes.src=="string"){const s=e.get(o.attributes.src);s&&(o.attributes.src=s)}});const i=t.children;i&&i.forEach(o=>{n.blocks[o].forEach(l=>{gT(n,l,e)})})}function pT(n,t,e){if(e.size===0)return;t.blocks.root.forEach(i=>{const o=n.editorBlocks.getBlockClass(i.type);o.replaceResources?o.replaceResources(i,e):gT(t,i,e)})}async function HU(n,t){let e=t.filter(s=>s.indexOf(":")===-1);const r=[];e.forEach(s=>{const l=s.split("|");r.push(...l)}),e=Array.from(new Set(r)),e=r;const i=await n.doc.addResources(e),o=new Map;if(e.length!==i.length)return o;for(let s=0;s<e.length;s++)o.set(e[s],i[s]);return o}function jU(n,t){var l,c,d,h;const r=t.meta.serverId;if(!r||typeof r!="string")return!1;const i=(c=(l=n.doc).getServerMeta)==null?void 0:c.call(l);if(!i)return!1;const o=/.*(?=\/)/;return((d=(i.serverId||"").match(o))==null?void 0:d[0])===((h=r.match(o))==null?void 0:h[0])}async function Sp(n,t){const r=t.meta.resources;if(!r||Object.keys(r).length===0)return;let i=new Map;if(jU(n,t)){const s=Array.from(Object.keys(r));i=await HU(n,s),pT(n,t,i)}const o=new Map;Object.entries(r).forEach(([s,l])=>{i.get(s)===void 0&&s!==l&&o.set(s,l)}),o.size!==0&&pT(n,t,o)}async function zU(n,t,e){await Sp(n,t),n.undoManager.runInGroup(()=>{const{start:r,end:i}=n.selection.range,o=n.getBlockById(r.blockId);if(r.blockId===i.blockId&&ge(o)){const s=it(o),l=n.getBlockIndex(o),[c]=n.insertDocAt(s,l+1,t,e);c&&n.selection.selectBlock(c,dt(n,c))}else{n.clearSelectedContents();const{block:s,offset:l}=Ba(n);n.insertDoc(s,l,t,e)}})}const GU=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function WU(n){let t;for(const e of GU)if(t=n[e],t)break;return t||null}class qU{constructor(t){m(this,"editor");m(this,"handlers",[]);m(this,"hookExecutionAttempt",(t,e,r)=>{for(let i=0;i<this.handlers.length;i++){const o=this.handlers[i];if(o.handleBeforeCopy){const s=o.handleBeforeCopy(this.editor,e,r);if(s===!0)return!0;if(typeof s=="object"&&s!=null)return s}}});m(this,"onPasteText",async(t,e)=>{const r=new DataTransfer;r.setData("text/plain",t);const i=await this.editor.dataConverter.fromData(this.editor,r,e);if(i){const o=[];this.pasteDocs(i,null,o)}});this.editor=t}onInsertText(t,e){if(!nt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:r,blockIndex:i,offset:o}=Ba(this.editor);this.handleBeforeInsertText(r,i,o,e)||(this.defaultInsertText(this.editor,r,i,o,e),this.handleAfterInsertText(r,i,o,e),this.editor.selection.updateLastCaretRect())}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const r=this.handlers[e];r.handleChanged&&r.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const r=this.handlers[e];r.handleRemoteChanged&&r.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){if(!nt(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:r,offset:i}=Ba(this.editor);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,r,i)}}onUpdateCompositionText(t,e,r){if(!nt(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText(e,r),this.editor.selection.caret.update();const{containerId:i,blockIndex:o,offset:s}=Ba(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,i,o,s,r)}this.editor.selection.updateLastCaretRect()}onCopy(t){FU(this.editor,t,this.hookExecutionAttempt)}onCopyWithoutEvent(){KU(this.editor,this.hookExecutionAttempt)}onCut(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeCut&&i.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const r=this.editor.selection.focusedBlock;ge(r)&&this.editor.deleteBlock(r)}else Sh(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;const e=this.editor.dataConverter.fromData(this.editor,t.clipboardData),r=Array.from(t.clipboardData.files);e.then(async i=>{i&&this.pasteDocs(i,t,r)})}onFocus(){z(this.editor.rootElement,"active")}onBlur(){ot(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,r)=>{var s,l;const i=(s=e.order)!=null?s:1;return((l=r.order)!=null?l:1)-i})}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,r,i))return!0}return!1}handleAfterInsertText(t,e,r,i){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,r,i))return!0}return!1}handleBeforeKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforeKeyDown&&i.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterKeyDown&&i.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,r,i,o){rp(this.editor,o)}defaultHandleKeydown(t,e){return mT(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePasteDoc&&await i.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await zU(this.editor,t,e);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPasteDoc&&await i.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e,r){for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,e,t,r))return}const i=WU(t);if(!!i){await this.pasteDoc(i);for(let o=0;o<this.handlers.length;o++){const s=this.handlers[o];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}forEach(t){this.handlers.forEach(t)}}function XU(n,t,e){const r=Hi(t,e);return r.remove(),r}I("copy-dom-attributes");const CT=["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 YU(n,t){for(let l=0;l<CT.length;l++){const c=CT[l];t[c]=n[c]}const e=n.attributes,r=t.attributes,i=[],o=[];for(let l=0;l<e.length;l++){const c=e[l],d=r.getNamedItem(c.name);d?d.value!==c.value&&(d.value=c.value,o.push(c)):i.push(c)}const s=[];for(let l=0;l<r.length;l++){const c=r[l];e.getNamedItem(c.name)||s.push(c)}i.forEach(l=>{t.setAttribute(l.name,l.value)}),o.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function ET(n){const t=Array.from(n.childNodes).filter(e=>!Mv(e));return t.forEach(e=>{e.remove()}),t}function AT(n,t,e){var d;const r=n.getContainerById(t),i=Hi(r,e),o=Ko(i),s=n.doc.getBlockData(t,e),l=Jt(n,i);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,i,s))n.editorBlockRenders.updateBlock(n,o,i,s);else{const h=n.editorBlocks.createBlock(o,r,s),C=ET(h);ET(i),C.forEach(x=>{i.appendChild(x)});const E=Yd(h);if(E){const x=Yd(i);x&&x.remove(),i.appendChild(E)}YU(h,i)}Xv(n,i,s),n.blockHooks.forEach(h=>{var C;(C=h.update)==null||C.call(h,n,o,r,i,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const QU=I("transform-selection");function xT(n,t,e,r){const{range:i}=n.selection,{anchor:o,focus:s}=i;if(o.blockId!==t&&s.blockId!==t)return i;p(QU,o.isSimple()&&s.isSimple(),"invalid text pos type");let l=o;if(o.blockId===t){const d=hn.transformCursor(o.offset,e,r);l=ct(t,d,"normal")}let c=s;if(s.blockId===t){const d=hn.transformCursor(s.offset,e,r);c=ct(t,d,"normal")}return Xe(n,{anchor:l,focus:c})}const JU=I("handle-block-text-changed");function ZU(n,t,e,r,i){const o=n.getContainerById(t),s=Hi(o,e),l=n.doc.getBlockData(t,e);if(p(JU,l.text,"no block text"),Lv(n,s).setBlockText(n,s,l.text),!i){const c=xT(n,l.id,r,i);n.selection.setRange(c,{noScroll:!0})}}function tO(n,t){const e=mt.default(n);return t.delete.forEach(i=>{delete e[i]}),{...e,...t.insert}}function bT(n,t,e,r){const i=Jt(n,t);i.handleDeleteBlock&&i.handleDeleteBlock(n,t,e,r),n.emit("blockDeleted",n,t,e,r)}function eO(n,t,e,r){const i=n.getBlockByIndex(t,e);i.querySelectorAll('[data-type="editor-block"]').forEach(o=>{bT(n,o,r,{child:!0})}),bT(n,i,r,{child:!1})}const Nr=I("editor-doc");class nO extends aa{constructor(e,r,i){super();m(this,"localEvents",[]);this.editor=e,this.externalDoc=r,this.externalDoc.registerCallback(this),this.registerLocalEvents(i)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var r,i;return(i=(r=this.externalDoc).getVersionHelper)==null?void 0:i.call(r)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}findContainerBlocks(e){return this.externalDoc.findContainerBlocks(e)}getBlockData(e,r){return this.externalDoc.getBlockData(e,r)}verifyBlockWritable(e,r){const i=this.editor.getBlockByIndex(e,r);p(Nr,this.editor.isBlockWritable(i),`block is not writable, ${e}, ${r}`)}localUpdateBlockText(e,r,i,o){p(Nr,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const s=this.getBlockData(e,r),l=s.text;p(Nr,l,`no text, ${e}, ${r}`);const c=xT(this.editor,s.id,i,!0),d=hn.apply(l,i);this.localEvents.forEach(C=>C.onBeforeUpdateBlockText(e,s.id,l,d,c.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,r,i);return this.editor.selection.setRange(c,o),h}localUpdateBlockData(e,r,i,o){p(Nr,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,r);if(!this.editor.isBlockWritable(s)){const h=Array.from(i.delete).filter(E=>E!=="comments"),C=Object.keys(i.insert).filter(E=>E!=="comments");(h.length>0||C.length>0)&&p(Nr,!1,`block is not writable, comment supported only, ${JSON.stringify(i)}}`)}const l=mt.default(this.getBlockData(e,r)),c=mt.default(tO(l,i));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,c,o));const d=this.externalDoc.localUpdateBlockData(e,r,i,o);return this.editor.selection.setRange(Vo(this.editor,o)),d}localInsertBlock(e,r,i,o,s){p(Nr,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(e,r,i,o));const l=this.externalDoc.localInsertBlock(e,r,i,o);return s!=null&&s.noFocus||this.editor.selection.setRange(Vo(this.editor,o),s),l}localDeleteBlock(e,r,i){p(Nr,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,r);const o=mt.default(this.getBlockData(e,r));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,r,o,i));const s=this.externalDoc.localDeleteBlock(e,r,i);return this.editor.selection.setRange(Vo(this.editor,i)),s}localDeleteChildContainers(e){return p(Nr,!this.editor.readonly,"editor is readonly"),e.forEach(r=>{const i=mt.default(this.getContainerBlocks(r));this.localEvents.forEach(o=>o.onBeforeDeleteChildContainer(r,i))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainers(e){p(Nr,!this.editor.readonly,"editor is readonly");const r=mt.default(e);r.forEach(i=>{this.localEvents.forEach(o=>o.onBeforeInsertChildContainer(i.containerId,i.blocks))}),this.externalDoc.localInsertChildContainers(r)}onRequestReload(e){Nr.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(i=>{var o;return(o=i.onRequestReload)==null?void 0:o.call(i,e)});const r=!1;this.editor.emit("docChanged",this.editor,r)}onUpdateBlockText(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,r,i,o)}),ZU(this.editor,e,r,i,o),this.editor.emit("docChanged",this.editor,o)}onUpdateBlockData(e,r,i,o){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,o)}),AT(this.editor,e,r),this.editor.emit("docChanged",this.editor,o)}onInsertBlock(e,r,i,o){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,e,r,i,o)});const s=this.editor.getContainerById(e);NI(this.editor,s,r,i),this.editor.emit("docChanged",this.editor,o)}onDeleteBlock(e,r,i){eO(this.editor,e,r,i),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,i)});const o=this.editor.getContainerById(e);XU(this.editor,o,r),this.editor.emit("docChanged",this.editor,i)}onInsertChildContainer(e,r,i){this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,e,r,i)})}onDeleteChildContainer(e,r){this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,e)})}onStatusChanged(e){this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)})}onError(e){this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}uploadResource(e,r){return this.externalDoc.uploadResource(e,r)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,r){return this.externalDoc.buildResourceUrl(e,r)}request(e,r){return this.externalDoc.request(e,r)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}triggerReAuth(){var e,r;return(r=(e=this.externalDoc).triggerReAuth)==null?void 0:r.call(e)}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,r,i;return(i=(r=(e=this.externalDoc).getServerMeta)==null?void 0:r.call(e))!=null?i:{}}reset(e){Nr.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function vT(n,t){if(n.length===0){n.push(t);return}const e=n[n.length-1];if(!e.combinable(t)){n.push(t);return}e.combine(t)}const Ph=I("undo-action");class Sa{constructor(t,e,r){m(this,"beforeRange");m(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=r}undo(t){return!1}redo(t){return!1}combinable(t){return p(Ph,t,"no other action"),!1}combine(t){p(Ph,!1,"no other")}setAfterRange(t){this.afterRange&&Ph.warn("after range has already set"),this.afterRange=t}findContainerById(t,e){return!!t.doc.findContainerBlocks(e)}findBlockById(t,e){const r=t.doc.findContainerBlocks(this.containerId);return r?r.some(i=>i.id===e):!1}checkBlockData(t,e){if(Array.isArray(e.children)){const r=t.doc.toJSON();for(let i=0;i<e.children.length;i++){const o=e.children[i];if(!r.blocks[o])return Ph.warn(`container (${o}) not found, deleted by others?`),!1}}return!0}}const La=I("block-action");class BT extends Sa{constructor(e,r,i,o,s){super(e,r,s);m(this,"blockData");m(this,"blockIndex");this.blockData=mt.default(o),this.blockIndex=i}deleteBlock(e,r){if(!this.findContainerById(e,this.containerId))return La.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockData.id))return La.warn(`block (${this.blockData.id}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const o=e.getBlockById(this.blockData.id);if(!o)return!1;try{p(La,this.blockIndex===Bt(o),"invalid block index"),Rh(e,o,Vo(e,r))}catch(s){La.warn(s.message),e.selection.selectBlock(o,0)}return!0}insertBlock(e,r){if(!this.findContainerById(e,this.containerId))return La.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.checkBlockData(e,this.blockData))return!1;try{ya(e,this.containerId,this.blockIndex,mt.default(this.blockData),r)}catch(i){La.warn(i.message);const o=e.doc.getContainerBlocks(this.containerId),s=Math.min(o.length-1,this.blockIndex),l=e.getBlockByIndex(this.containerId,s);e.selection.selectBlock(l,0)}return!0}}I("insert-block-action");class rO extends BT{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class iO extends BT{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class oO extends Sa{constructor(e){super(e,at(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){vT(this.actions,e),this.afterRange=e.afterRange}undo(e){let r=!1;return this.actions.concat().reverse().forEach(i=>{i.undo(e)&&(r=!0)}),r}redo(e){let r=!1;return this.actions.forEach(i=>{i.redo(e)&&(r=!0)}),r}setAfterRange(e){this.afterRange=e;const r=this.actions[this.actions.length-1];!r||r instanceof Sa&&(r.afterRange||r.setAfterRange(e))}}const Xo=I("update-block-data-action");class Fh extends Sa{constructor(e,r,i,o,s,l){super(e,r,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=i,p(Xo,this.blockId===o.id,"invalid block id"),p(Xo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(o),this.afterBlockData=mt.default(s),p(Xo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return Xo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(Xo,i,"no container"),Ih(e,r,Fh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return Xo.warn(`block (${this.blockId}) not found, deleted by others?`),!1;p(Xo,e,"no editor");const r=e.getBlockById(this.blockId);if(!r||!this.checkBlockData(e,this.beforeBlockData))return!1;const i=e.getContainerById(this.containerId);return p(Xo,i,"no container"),Ih(e,r,Fh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const r=mt.default(e);return delete r.id,delete r.type,r}}const rl=I("update-block-text-action");class ku extends Sa{constructor(e,r,i,o,s,l){super(e,r,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=i,this.beforeRichTextData=mt.default(o),this.afterRichTextData=mt.default(s),this.type=ku.calType(o,s)}static calType(e,r){p(rl,e,"no old data"),p(rl,r,"no new data");const o=hn.diff(e,r),s=new Set;let l=!1;const c=h=>ov(h)?`cjk_${h}`:rv(h)?"number":$d(h)?"space":iv(h)?"letter":"unknown";let d=!1;return o.forEach(h=>{h.insert?h.insert===" "?s.add("insert_letter"):typeof h.insert=="string"&&h.insert.startsWith(" ")&&h.insert.length>1?(l=!0,d=!0,s.add(`insert_${c(h.insert.substr(1))}`)):s.add(`insert_${c(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!this.findContainerById(e,this.containerId))return rl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return rl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(Lh(e,i,this.beforeRichTextData),!0):!1}redo(e){if(!this.findContainerById(e,this.containerId))return rl.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return rl.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockId);return i?(Lh(e,i,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof ku)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const r=e.beforeRange,i=r.anchor;if(!i.isSimple())return!1;const o=this.afterRange;if(!o)return!1;const s=o.anchor;return!(!s.isSimple()||s.blockId!==r.anchor.blockId||s.offset!==i.offset)}combine(e){p(rl,e instanceof ku,"invalid action type");const r=e;this.afterRichTextData=r.afterRichTextData,this.afterRange=e.afterRange}}const TT=I("child-container-action");class yT extends Sa{constructor(t,e,r){super(t,e,t.selection.range.toDocRange()),this.blocks=r}deleteChildContainer(t){return this.findContainerById(t,this.containerId)?(t.doc.localDeleteChildContainers([this.containerId]),!0):(TT.warn(`container (${this.containerId}) not found, deleted by others?`),!1)}insertChildContainer(t){return this.findContainerById(t,this.containerId)?(TT.warn(`container (${this.containerId}) already exists`),!1):(t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:mt.default(this.blocks)}]),!0)}}class sO extends yT{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class lO extends yT{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Pr=I("undo");class aO{constructor(t){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(this,"handleSelectionChange",t=>{if(this.currentGroup){this.currentGroup.setAfterRange(t.selection.range.toDocRange());return}const e=this.actions[this.actions.length-1];!e||e.afterRange||e.setAfterRange(t.selection.range.toDocRange())});this.editor=t,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(t){this.currentGroup?this.currentGroup.addAction(t):(vT(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(p(Pr,!this.currentGroup,"current group already exists"),this.currentGroup=new oO(this.editor),this.groupCounter=1):(p(Pr,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){p(Pr,this.currentGroup,"current group not exists"),p(Pr,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Pr.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw Pr.error(`failed to run action: ${e.message}`),e}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const t=this.actions[this.undoCursor];if(t.undo(this.editor)){try{this.editor.selection.setRange(Vo(this.editor,t.beforeRange))}catch(e){Pr.error(`undo: failed to restore caret pos: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const t=this.actions[this.undoCursor];if(this.undoCursor+=1,t.redo(this.editor)){try{const e=t.afterRange;e?this.editor.selection.setRange(Vo(this.editor,e)):Pr.warn("no after range")}catch(e){Pr.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,r,i,o){this.undoRedoing||(this.prepareSaveUndoState(),hn.diff(r,i).length!==0&&this.addAction(new ku(this.editor,t,e,r,i,o)))}onBeforeUpdateBlockData(t,e,r,i,o){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Fh(this.editor,t,e,r,i,o);this.addAction(s)}onBeforeInsertBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),p(Pr,e>=0,"invalid block index"),p(Pr,r,"no block data"),this.addAction(new rO(this.editor,t,e,r,i)))}onBeforeDeleteBlock(t,e,r,i){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new iO(this.editor,t,e,r,i)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new sO(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new lO(this.editor,t,e)))}}class cO{async fromData(t,e){const r=e.getData("text/x-ones-editor-doc");if(r)return{"text/x-ones-editor-doc":JSON.parse(r)}}}class uO{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new cO)}prepareData(t){const e=new DataTransfer;for(let r=0;r<this.converterTypes.length;r++)e.setData(this.converterTypes[r],t.getData(this.converterTypes[r]));return e}async fromData(t,e,r){let i={};const o=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,o,r);l&&(i={...i,...l})}return i}addConverter(t){this.converters.push(t)}}function fO(n){n.editorBlocks.registerBlockClass(On),n.editorBlocks.registerBlockClass(h3),n.editorBoxes.registerBoxClass(_B),n.editorBoxes.registerBoxClass(MB),n.editorBoxes.registerBoxClass(NB),n.editorBoxes.registerBoxClass(PB),n.editorInsertions.registerInsertionClass(FB),n.editorBlockRenders.registerRender(new _v)}function dO(n,t){fO(n),t!=null&&t.blocks&&t.blocks.forEach(e=>n.editorBlocks.registerBlockClass(e)),t!=null&&t.boxes&&t.boxes.forEach(e=>n.editorBoxes.registerBoxClass(e)),t!=null&&t.embeds&&t.embeds.forEach(e=>n.editorEmbeds.registerEmbedClass(e)),t!=null&&t.insertions&&t.insertions.forEach(e=>n.editorInsertions.registerInsertionClass(e)),t!=null&&t.decorators&&t.decorators.forEach(e=>n.editorDecorators.registerDecorator(e)),t!=null&&t.dataConverters&&t.dataConverters.forEach(e=>n.dataConverter.addConverter(e)),t!=null&&t.commandProviders&&t.commandProviders.forEach(e=>n.editorCommandProviders.registerCommandProvider(e)),t!=null&&t.textRenders&&t.textRenders.forEach(e=>n.editorBlockRenders.registerRender(e))}const Kh=I("range-commands");function kT(n,t){n.forEach(e=>{e.source=t,e.children&&kT(e.children,t)})}function RT(n,t){n.forEach(e=>{e.group=t,e.children&&RT(e.children,t)})}function wT(n,t,e,r){const i=lt(t);p(Kh,i===e.start.blockId,"invalid start range"),p(Kh,i===e.end.blockId,"invalid end range");const o=n.editorCommandProviders.getCommandProviders();let s=[];if(o.forEach(l=>{const c=l.getAvailableCommands(n,t,e);kT(c,r),RT(c,l.id),s.push(...c)}),o.forEach(l=>{if(l.filterCommands){const c=l.filterCommands(n,t,e,s);c&&(s=c)}}),Mt(n,t)){if(!ga(e.start))return s;p(Kh,!e.start.isSimple(),"invalid start pos"),p(Kh,!e.end.isSimple(),"invalid end pos");const l=e.start.childContainerId,c=Lr(n,l),h=fe(c)[0];if(h){const C=dt(n,h),E=Xe(n,{anchor:ct(h,0,"home"),focus:ct(h,C,"end")}),x=wT(n,h,E,r);s.push(...x)}}return s}function ST(n,t){const e=n.getEditor(),r=n.getSelectedBlocks(),i=[],o=n.isReverse()?r[0]:r[r.length-1],s=Xe(e,{anchor:o.start,focus:o.end});return wT(e,o.block,s,t).forEach(c=>{i.push(c)}),i}function LT(n,t,e,r,i,o){var h;const s=n.editorCommandProviders.getCommandProviders();for(let C=0;C<s.length;C++){const E=s[C];if(E.beforeExecuteCommand&&E.beforeExecuteCommand(n,t,e,r,i))return!1}const l=n.editorCommandProviders.getCommandProvider(r.group),c={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,r,i,{}))return o[lt(t)]=c,!0;let d=!1;return Mt(n,t)&&pa(n,t,e.start,e.end).forEach(E=>{fe(E).forEach(v=>{const k=dt(n,v),L=Xe(n,{anchor:ct(v,0,"home"),focus:ct(v,k,"end")});LT(n,v,L,r,i,o)&&(d=!0)})}),s.forEach(C=>{C.afterExecuteCommand&&C.afterExecuteCommand(n,t,e,r,i,o)}),d}function IT(n,t,e){const r=n.getEditor(),i={},o=r.editorCommandProviders.getCommandProvider(t.group);return o.executeRangeCommand&&o.executeRangeCommand(r,n,t,e,i)||(n.getSelectedBlocks().forEach(l=>{const c=Xe(r,{anchor:l.start,focus:l.end});LT(r,l.block,c,t,e,i)}),r.focus()),i}const hO=I("command-providers");class DT{constructor(t){m(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(r=>r.id===t);return p(hO,e,`no command provider, id=${t}`),e}getCommands(t,e){return ST(t,e)}executeCommand(t,e,r){return this.editor.emit("beforeExecCommand",this.editor,e,{source:e.source}),this.editor.undoManager.runInGroup(()=>IT(t,e,r))}getEmptyBlockTextAttributes(t,e){let r={};if(this.providers.forEach(i=>{var s;const o=(s=i.getEmptyBlockTextAttributes)==null?void 0:s.call(i,t,e);o&&(r={...r,...o})}),Object.keys(r).length!==0)return r}}function mO(n,t){const e=it(t),r=at(e),i=Bt(t);AT(n,r,i)}const _T=I("update-block-text");function gO(n,t){const e=n.getBoxById(t.id),r=J(e);p(_T,r,"no parent block"),p(_T,nt(n,r),"not a text block");const i=n.getBlockText(r),o=yB(i,"id",t.id,t);s5(n,r,o)}function pO(n,t){for(const e of n.blockHooks)if(e.writable){const r=e.writable(n,t);if(typeof r=="boolean")return r}return!0}function CO(n){if(n.readonly)return!1;const t=fi(n);return!!n.isBlockWritable(t.map(e=>e.block))}class EO{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}getItem(t){return window.localStorage.getItem(this.getKey(t))}setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class AO{constructor(){m(this,"shortcuts",[])}handleKeyboardEvents(t,e){const r=this.shortcuts;for(const i of r){const o=Object.entries(i);for(const[s,l]of o)if(si(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const eo=I("editor");class xO extends Be.TypedEmitter{constructor(e,r,i){var o,s,l,c,d,h,C,E;super();m(this,"parent");m(this,"rootElement");m(this,"contentElement");m(this,"rootContainerObject");m(this,"rootContainer");m(this,"input");m(this,"selection");m(this,"selectionHandler");m(this,"doc");m(this,"id");m(this,"clientId");m(this,"compositingText","");m(this,"undoManager");m(this,"shortcuts",new AO);m(this,"dataConverter",new uO);m(this,"editorBlocks",new c3(this));m(this,"editorBoxes",new OB(this));m(this,"editorInsertions",new VB(this));m(this,"editorEmbeds",new f3(this));m(this,"editorDecorators",new $B(this));m(this,"editorCommandProviders",new DT(this));m(this,"editorBlockRenders",new RI(this));m(this,"blockHooks",[]);m(this,"domEvents",new xU(this));m(this,"customs",new Map);m(this,"options");m(this,"version","");m(this,"inputHandlers",new qU(this));m(this,"settingsProvider");m(this,"_readonly",!1);m(this,"getColor",e=>{const r=this.options.colors;return r.length===0?"#FF1A75":r[e%r.length]});eo.debug("create editor"),this.setMaxListeners(100),this.options={colors:(o=i==null?void 0:i.colors)!=null?o:["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"],componentsOptions:(l=(s=i==null?void 0:i.components)==null?void 0:s.options)!=null?l:{},scrollContainer:i==null?void 0:i.scrollContainer,enableComments:(c=i==null?void 0:i.enableComments)!=null?c:!0},this.settingsProvider=(d=i==null?void 0:i.settingsProvider)!=null?d:new EO(this),dO(this,i==null?void 0:i.components),this.blockHooks.push(...(C=(h=i==null?void 0:i.components)==null?void 0:h.blockHooks)!=null?C:[]),this.id=(E=i==null?void 0:i.id)!=null?E:tt(),this.clientId=tt(),this.undoManager=new aO(this),this.doc=new nO(this,r,this.undoManager),this.parent=e,this.rootElement=B("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=B("div",["editor-content"],this.rootElement),this.rootContainerObject=s3(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new PM(this,this.inputHandlers),this.selection=new kU(this),this.selectionHandler=new SU(this),i!=null&&i.shortcuts&&this.shortcuts.shortcuts.push(...i.shortcuts),ue.isMobile&&z(this.rootElement,"mobile"),ue.isSafari&&z(this.rootElement,"safari"),this._readonly&&z(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?z(this.rootElement,"readonly"):ot(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:Ge(this.rootContainer)}addCustom(e,r){const i=this.customs.get(e);if(i)return i;const o=r(this);return this.customs.set(e,o),o}getCustom(e){const r=this.customs.get(e);return p(eo,r,`${e} does not exists`),r}replaceCustom(e,r){const i=this.customs.get(e);return i&&i.destroy(),this.customs.set(e,r),r}findCustom(e){return this.customs.get(e)}findCustomByType(e){const r=this.customs.values();for(const i of r)if(i instanceof e)return i;return null}destroyCustom(e){const r=this.customs.get(e);r&&(this.customs.delete(e),r.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,r,i){return this.editorBlocks.createBlock(e,r,i)}createBox(e,r){return this.editorBoxes.createBox(e,r)}createInsertion(e,r){return this.editorInsertions.createInsertion(e,r)}destroy(){eo.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(e=>e.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(e,r){cp(this,e,r)}isWritable(){return CO(this)}isBlockWritable(e){return pO(this,e)}getChildContainerData(e){const r=this.doc.getContainerBlocks(e);return(!r||!Array.isArray(r))&&(p(eo,r,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),p(eo,Array.isArray(r),`container data is not an array: ${JSON.stringify(r)}`)),r}createChildContainer(e,r,i){return l3(this,e,r,i)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const r=this.rootContainer.querySelector(`#${e}`);return r&&p(eo,$s(r),"not an valid block element"),r!=null?r:null}findBoxById(e){const r=this.rootContainer.querySelector(`#${e}`);return r&&p(eo,Qd(r),"not an valid box element"),r!=null?r:null}getBlockById(e){const r=this.findBlockById(e);return p(eo,r,`no block, id=${e}`),r}getBoxById(e){const r=this.findBoxById(e);return p(eo,r,`no box, id=${e}`),r}getBlockByIndex(e,r){const i=this.getContainerById(e);return Hi(i,r)}findBlockByIndex(e,r){const i=this.getContainerById(e);return wv(i,r)}getBlockIndex(e){if(typeof e=="string"){const r=this.getBlockById(e);return Bt(r)}return Bt(e)}getContainerById(e){return Lr(this,e)}getParentContainer(e){return it(e)}reloadBlock(e){mO(this,e)}contains(e){const r=e instanceof Element?e:e.parentElement;return r?r.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,r,i,o,s){const l={blockId:i.id,offset:0},c={anchor:l,focus:l};return ya(this,e,r,i,o!=null?o:c,s)}insertEmbed(e,r,i,o,s){const l={id:tt(),type:"embed",embedType:i,embedData:o};return this.insertBlock(e,r,l,s)}deleteBlock(e,r){lp(this,e,r)}mergeTextBlock(e,r){return r5(this,e,r)}breakTextBlock(e,r,i){return ka(this,e,r,i).newBlock}getTextPosition(){return Ba(this)}getBlockString(e,r){const i=this.getBlockText(e);return de(i,r)}getBlockData(e){return zo(this,e)}getBoxData(e){return IB(this,e)}getBlockText(e){return Tn(this,e)}setBlockText(e,r){s5(this,e,r)}deleteTextFromBlock(e,r,i,o){return op(this,e,r,i,o)}insertTextToBlock(e,r,i,o){return QB(this,e,r,i,o)}insertBoxToBlock(e,r,i){return JB(this,e,r,i)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,r,i,o){c5(this,e,r,i,o)}insertDocAt(e,r,i,o){return dp(this,e,r,i,o)}deleteChildContainers(e){n5(this,e)}replaceBlockText(e,r){return Lh(this,e,r)}updateBlockData(e,r,i){const o={...this.getBlockData(e),...r},{id:s,type:l,...c}=o;return Ih(this,e,c,(i!=null?i:this.selection.range).toDocRange())}updateEmbedData(e,r,i){return l5(this,e,r,i)}updateBoxData(e){gO(this,e)}getSelectedText(){const e=wa(this);return Go(this,e)}clearSelectedContents(){Sh(this)}insertTextBlock(e,r,i,o){const s=mi(e!=null?e:"");return e5(this,s,r,i,o==null?void 0:o.newRange,o==null?void 0:o.insertBlockOptions)}updateCompositionText(e,r){if(e&&!r&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!r){ip(this);return}r?(this.compositingText="",Gc()?e||ip(this):rp(this,e)):(this.compositingText=e,ZB(this))}}function Ru(n,t,e){return new xO(n,t,e)}function bO(n){const t=(r,i)=>{const o=r.findIndex(l=>l.id===i.id);if(o===-1){r.push(i);return}const s=r[o];if(s.value!==i.value){r.splice(o,1);return}if(!!s.states){if(!i.states){s.states=[];return}s.states=wg.default(s.states,i.states)}},e=[];return n.forEach(r=>{r.forEach(i=>{t(e,i)})}),e}const vO=["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"];class wu extends Be.TypedEmitter{constructor(e){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=e&&e.length>0?e:vO}setCursor(e){this.addUser(e.user);const r=this.cursors.get(e.user.userId);if(r&&$c.default(r,e))return;this.cursors.set(e.user.userId,e);const i=new Set([e.range.anchor.blockId,e.range.focus.blockId]),o=new Set(i);r&&new Set([r.range.anchor.blockId,r.range.focus.blockId]).forEach(l=>{i.has(l)||o.add(l)}),this.emit("remote-carets-change",[...o])}addUsers(e){this.addingUser=!0,e.forEach(r=>this.addUser(r)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var r;return(r=this.users.get(e))!=null?r:null}removeUser(e){this.users.delete(e),this.emit("change",Array.from(this.users.values()));const r=this.cursors.get(e);if(r){const i=new Set(new Set([r==null?void 0:r.range.anchor.blockId,r==null?void 0:r.range.focus.blockId]));this.cursors.delete(e),this.emit("remote-carets-change",[...i])}}updateUsers(e){this.users.forEach(r=>{e.find(i=>i.userId===r.userId)||this.removeUser(r.userId)}),this.users.clear(),this.addingUser=!0;try{e.forEach(r=>{this.addUser(r)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const r=new Map;return Array.from(this.cursors.values()).filter(i=>i.range.anchor.blockId===e&&Ch(i.range)).forEach(i=>{const o=i.range.focus.offset;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}),r}getCursors(e){return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e||r.range.focus.blockId===e)}onUpdateBlockText(e,r,i){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(Ch(l.range)){const{anchor:c,focus:d}=l.range;c.blockId===e.id&&(c.offset=hn.transformCursor(c.offset,r,i)),d.blockId===e.id&&(d.offset=hn.transformCursor(d.offset,r,i))}})}getFixedUserColor(e,r){let i=0;Array.from(e).forEach(s=>{i+=s.charCodeAt(0)});const o=i%this.colors.length;return this.colors[o]}destroy(){this.removeAllListeners()}}const on=I("local-doc");class Lp extends aa{constructor(e,r){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[mi("")]}},this.serviceUrl=(r==null?void 0:r.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}findContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,r){const i=this.getContainerBlocks(e);p(on,i,`no container data: ${e}`);const o=i[r];return p(on,o,`no block data: ${r}`),o}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(on,o.text,"no text for data");const s=hn.apply(o.text,i);return o.text=s,p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,e,r,i,!0)}),s}localUpdateBlockData(e,r,i){const o=this.getBlockData(e,r);return i.delete.forEach(s=>delete o[s]),Object.entries(i.insert).forEach(([s,l])=>{o[s]=l}),p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,r,i,!0)}),o}localInsertBlock(e,r,i){const o=this.getContainerBlocks(e);return p(on,o,`no container data: ${e}`),p(on,r>=0&&r<=o.length,`invalid block index: ${r}, ${o.length}`),o.splice(r,0,i),p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,r,i,!0)}),i}localDeleteBlock(e,r){const i=this.getContainerBlocks(e);p(on,i,`no container data: ${e}`),p(on,r>=0&&r<=i.length,`invalid block index: ${r}, ${i.length}`);const o=i[r];return i.splice(r,1),p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,r,!0)}),o}localInsertChildContainers(e){e.forEach(({containerId:r,blocks:i})=>{this.doc.blocks[r]=i,p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,r,i,!0)})})}localDeleteChildContainers(e){on.debug(`delete child containers: ${e}`),e.forEach(r=>{p(on,this.doc.blocks[r],`no child container: ${r}`),delete this.doc.blocks[r]}),e.forEach(r=>{p(on,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,r,!0)})})}uploadResource(e,r){p(on,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,r){p(on,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new wu}setDoc(e){this.doc=mt.default(e),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,"change doc")})}destroy(){this.clearCallbacks()}}class BO{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function Ip(n,t,e){n.addCustom(t,()=>{var o;const r=(o=e())!=null?o:void 0;return new BO(r)})}const MT=I("find-block");function UT(n,t){const e=zs(t);if(!e){if(dr(t))return null;const r=Hs(t);return p(MT,r,"no parent block"),UT(n,r)}return Mt(n,e)?Ca(n,e,{visibleOnly:!0}):e}function OT(n,t){const e=Gs(t);if(!e){if(dr(t))return null;const r=Hs(t);return p(MT,r,"no parent block"),OT(n,r)}return Mt(n,e)?g1(n,e,{visibleOnly:!0}):e}const TO=I("remote-cursor");class yO{constructor(){m(this,"remoteUsers",new wu)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const r=e;this.handleUpdateUsers(r.users)}else e.type==="caret"?this.handleUpdateCaret(e):TO.debug(`unknown remote message received: ${t}`)}handleUpdateUsers(t){this.remoteUsers.updateUsers(t)}handleUpdateCaret(t){const e=this.remoteUsers.findUser(t.userId);!e||this.remoteUsers.setCursor({oneseditor:"cursor",user:e,range:t.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function kO(n){const{blocks:t,meta:e,comments:r,...i}=n;return{rootBlocks:t,meta:e,comments:r,childBlocks:i}}function RO(n){const{blocks:t,meta:e,comments:r}=n,{root:i,...o}=t;return{blocks:i,meta:e,comments:r,...o}}function no(n){const{childBlocks:t,meta:e,comments:r,rootBlocks:i}=kO(mt.default(n));return{blocks:{root:i,...t},meta:e,comments:r}}function ro(n){return n==="root"?"blocks":n}function Ia(n){return n==="blocks"?"root":n}const wO={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new fn.default(n)},apply(n,t){const e=new fn.default(n),r=new fn.default(t);return e.compose(r).ops},compose(n,t){const e=new fn.default(n),r=new fn.default(t);return e.compose(r).ops},diff(n,t){const e=new fn.default(n),r=new fn.default(t);return e.diff(r).ops},transform(n,t,e){const r=new fn.default(n);return new fn.default(t).transform(r,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const r=new fn.default(t),i=this.transformCursor(n.index,r,e),o=this.transformCursor(n.index+n.length,r,e);return{...n,index:i,length:o-i}}}};var Yo={},Dp=Rg.default.EventEmitter;Yo.EventEmitter=Dp,Yo.mixin=SO;function SO(n){for(var t in Dp.prototype)n.prototype[t]=Dp.prototype[t]}var NT=["info","warn","error"];function PT(){var n={};NT.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var LO=PT;PT.prototype.setMethods=function(n){n=n||{};var t=this;NT.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var IO=LO,DO=new IO,FT=DO;function il(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,il):this.stack=new Error().stack}il.prototype=Object.create(Error.prototype),il.prototype.constructor=il,il.prototype.name="ShareDBError",il.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_FIXUP_IS_ONLY_VALID_ON_APPLY:"ERR_FIXUP_IS_ONLY_VALID_ON_APPLY",ERR_CANNOT_FIXUP_DELETION:"ERR_CANNOT_FIXUP_DELETION",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_CHANNEL_MISSING:"ERR_QUERY_CHANNEL_MISSING",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_COMPOSE:"ERR_TYPE_DOES_NOT_SUPPORT_COMPOSE",ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE:"ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE",ERR_UNKNOWN_ERROR:"ERR_UNKNOWN_ERROR"};var Vh=il,Su={},KT=_O;function _O(n,t,e,r){var i=function(s,l,c,d){t(c,s,l,"left"),t(d,l,s,"right")},o=n.transformX=function(s,l){e(s),e(l);for(var c=[],d=0;d<l.length;d++){for(var h=l[d],C=[],E=0;E<s.length;){var x=[];if(i(s[E],h,C,x),E++,x.length===1)h=x[0];else if(x.length===0){for(var v=E;v<s.length;v++)r(C,s[v]);h=null;break}else{for(var k=o(s.slice(E),x),L=0;L<k[0].length;L++)r(C,k[0][L]);for(var M=0;M<k[1].length;M++)r(c,k[1][M]);h=null;break}}h!=null&&r(c,h),s=C}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?t([],s[0],l[0],c):c==="left"?o(s,l)[0]:o(l,s)[1]}}var VT={exports:{}},Qo=VT.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||""}},_p=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Mp=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")},$h=function(n){for(var t=0;t<n.length;t++)Mp(n[t])};Qo.apply=function(n,t){var e;$h(t);for(var r=0;r<t.length;r++){var i=t[r];if(i.i!=null)n=_p(n,i.p,i.i);else{if(e=n.slice(i.p,i.p+i.d.length),i.d!==e)throw new Error("Delete component '"+i.d+"' does not match deleted text '"+e+"'");n=n.slice(0,i.p)+n.slice(i.p+i.d.length)}}return n};var io=Qo._append=function(n,t){if(!(t.i===""||t.d===""))if(n.length===0)n.push(t);else{var e=n[n.length-1];e.i!=null&&t.i!=null&&e.p<=t.p&&t.p<=e.p+e.i.length?n[n.length-1]={i:_p(e.i,t.p-e.p,t.i),p:e.p}:e.d!=null&&t.d!=null&&t.p<=e.p&&e.p<=t.p+t.d.length?n[n.length-1]={d:_p(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};Qo.compose=function(n,t){$h(n),$h(t);for(var e=n.slice(),r=0;r<t.length;r++)io(e,t[r]);return e},Qo.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=0),io(t,r)}return t};var Up=function(n,t,e){return t.i!=null?t.p<n||t.p===n&&e?n+t.i.length:n:n<=t.p?n:n<=t.p+t.d.length?t.p:n-t.d.length};Qo.transformCursor=function(n,t,e){for(var r=e==="right",i=0;i<t.length;i++)n=Up(n,t[i],r);return n};var MO=Qo._tc=function(n,t,e,r){if(Mp(t),Mp(e),t.i!=null)io(n,{i:t.i,p:Up(t.p,e,r==="right")});else if(e.i!=null){var i=t.d;t.p<e.p&&(io(n,{d:i.slice(0,e.p-t.p),p:t.p}),i=i.slice(e.p-t.p)),i!==""&&io(n,{d:i,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)io(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)io(n,t);else{var o={d:"",p:t.p};t.p<e.p&&(o.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(o.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),c=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(c!==d)throw new Error("Delete ops delete different text in the same region of the document");o.d!==""&&(o.p=Up(o.p,e),io(n,o))}return n},UO=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Qo.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=UO(n[t]);return n},KT(Qo,MO,$h,io);var Hh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},OO=function(n){return!!n&&n.constructor===Object},Fr=function(n){return JSON.parse(JSON.stringify(n))},Lt={name:"json0",uri:"http://sharejs.org/types/JSONv0"},oo={};Lt.registerSubtype=function(n){oo[n.name]=n},Lt.create=function(n){return n===void 0?null:Fr(n)},Lt.invertComponent=function(n){var t={p:n.p};return n.t&&oo[n.t]&&(t.t=n.t,t.o=oo[n.t].invert(n.o)),n.si!==void 0&&(t.sd=n.si),n.sd!==void 0&&(t.si=n.sd),n.oi!==void 0&&(t.od=n.oi),n.od!==void 0&&(t.oi=n.od),n.li!==void 0&&(t.ld=n.li),n.ld!==void 0&&(t.li=n.ld),n.na!==void 0&&(t.na=-n.na),n.lm!==void 0&&(t.lm=n.p[n.p.length-1],t.p=n.p.slice(0,n.p.length-1).concat([n.lm])),t},Lt.invert=function(n){for(var t=n.slice().reverse(),e=[],r=0;r<t.length;r++)e.push(Lt.invertComponent(t[r]));return e},Lt.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Hh(n[t].p))throw new Error("Missing path")},Lt.checkList=function(n){if(!Hh(n))throw new Error("Referenced element not a list")},Lt.checkObj=function(n){if(!OO(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function Lu(n){n.t="text0";var t={p:n.p.pop()};n.si!=null&&(t.i=n.si),n.sd!=null&&(t.d=n.sd),n.o=[t]}function Iu(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}Lt.apply=function(n,t){Lt.checkValidOp(t),t=Fr(t);for(var e={data:n},r=0;r<t.length;r++){var i=t[r];(i.si!=null||i.sd!=null)&&Lu(i);for(var o=null,s=e,l="data",c=0;c<i.p.length;c++){var d=i.p[c];if(o=s,s=s[l],l=d,o==null)throw new Error("Path invalid")}if(i.t&&i.o!==void 0&&oo[i.t])s[l]=oo[i.t].apply(s[l],i.o);else if(i.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=i.na}else if(i.li!==void 0&&i.ld!==void 0)Lt.checkList(s),s[l]=i.li;else if(i.li!==void 0)Lt.checkList(s),s.splice(l,0,i.li);else if(i.ld!==void 0)Lt.checkList(s),s.splice(l,1);else if(i.lm!==void 0){if(Lt.checkList(s),i.lm!=l){var h=s[l];s.splice(l,1),s.splice(i.lm,0,h)}}else if(i.oi!==void 0)Lt.checkObj(s),s[l]=i.oi;else if(i.od!==void 0)Lt.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},Lt.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},Lt.incrementalApply=function(n,t,e){for(var r=0;r<t.length;r++){var i=[t[r]];n=Lt.apply(n,i),e(i,n)}return n};var NO=Lt.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var r=0;r<n.length;r++)if(n[r]!==t[r]&&(!e||r!==n.length-1))return!1;return!0};Lt.append=function(n,t){if(t=Fr(t),n.length===0){n.push(t);return}var e=n[n.length-1];if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Lu(t),Lu(e)),NO(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&oo[t.t]){if(e.o=oo[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var r=t.p,i=0;i<e.o.length-1;i++)t.o=[e.o.pop()],t.p=r.slice(),Iu(t),n.push(t);Iu(e)}}else e.na!=null&&t.na!=null?n[n.length-1]={p:e.p,na:e.na+t.na}:e.li!==void 0&&t.li===void 0&&t.ld===e.li?e.ld!==void 0?delete e.li:n.pop():e.od!==void 0&&e.oi===void 0&&t.oi!==void 0&&t.od===void 0?e.oi=t.oi:e.oi!==void 0&&t.od!==void 0?t.oi!==void 0?e.oi=t.oi:e.od!==void 0?delete e.oi:n.pop():t.lm!==void 0&&t.p[t.p.length-1]===t.lm||n.push(t);else(t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Iu(t),Iu(e)),n.push(t)},Lt.compose=function(n,t){Lt.checkValidOp(n),Lt.checkValidOp(t);for(var e=Fr(n),r=0;r<t.length;r++)Lt.append(e,t[r]);return e},Lt.normalize=function(n){var t=[];n=Hh(n)?n:[n];for(var e=0;e<n.length;e++){var r=n[e];r.p==null&&(r.p=[]),Lt.append(t,r)}return t},Lt.commonLengthForOps=function(n,t){var e=n.p.length,r=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&r++,e===0)return-1;if(r===0)return null;e--,r--;for(var i=0;i<e;i++){var o=n.p[i];if(i>=r||o!==t.p[i])return null}return e},Lt.canOpAffectPath=function(n,t){return Lt.commonLengthForOps({p:t},n)!=null},Lt.transformComponent=function(n,t,e,r){t=Fr(t);var i=Lt.commonLengthForOps(e,t),o=Lt.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,o!=null&&l>s&&t.p[o]==e.p[o]){if(t.ld!==void 0){var c=Fr(e);c.p=c.p.slice(s),t.ld=Lt.apply(Fr(t.ld),[c])}else if(t.od!==void 0){var c=Fr(e);c.p=c.p.slice(s),t.od=Lt.apply(Fr(t.od),[c])}}if(i!=null){var d=s==l,c=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(Lu(t),c=Fr(e),Lu(c)),c.t&&oo[c.t]){if(t.t&&t.t===c.t){var h=oo[t.t].transform(t.o,c.o,r);if(t.si!=null||t.sd!=null)for(var C=t.p,E=0;E<h.length;E++)t.o=[h[E]],t.p=C.slice(),Iu(t),Lt.append(n,t);else(!Hh(h)||h.length>0)&&(t.o=h,Lt.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[i]===t.p[i])if(d){if(t.ld!==void 0)if(t.li!==void 0&&r==="left")t.ld=Fr(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&d&&t.p[i]===e.p[i]?r==="right"&&t.p[i]++:e.p[i]<=t.p[i]&&t.p[i]++,t.lm!==void 0&&d&&e.p[i]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[i]===t.p[i])return n;var C=e.p[i],x=t.p[i],v=t.lm;(C<v||C===v&&x<v)&&t.lm--}if(e.p[i]<t.p[i])t.p[i]--;else if(e.p[i]===t.p[i]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var x=t.p[i],v=t.lm,k=e.p[i],L=e.lm;if(k!==L)if(x===k)if(r==="left")t.p[i]=L,x===v&&(t.lm=L);else return n;else x>k&&t.p[i]--,x>L?t.p[i]++:x===L&&k>L&&(t.p[i]++,x===v&&t.lm++),(v>k||v===k&&v>x)&&t.lm--,v>L?t.lm++:v===L&&(L>k&&v>x||L<k&&v<x?r==="right"&&t.lm++:v>x?t.lm++:v===k&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var x=e.p[i],v=e.lm;C=t.p[i],C>x&&t.p[i]--,C>v&&t.p[i]++}else{var x=e.p[i],v=e.lm;C=t.p[i],C===x?t.p[i]=v:(C>x&&t.p[i]--,(C>v||C===v&&x>v)&&t.p[i]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[i]===e.p[i])if(t.oi!==void 0&&d){if(r==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[i]===e.p[i])if(r==="left")Lt.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[i]==e.p[i]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return Lt.append(n,t),n},KT(Lt,Lt.transformComponent,Lt.checkValidOp,Lt.append);var PO=VT.exports;Lt.registerSubtype(PO);var FO=Lt,KO={type:FO};(function(n){n.defaultType=KO.type,n.map={},n.register=function(t){t.name&&(n.map[t.name]=t),t.uri&&(n.map[t.uri]=t)},n.register(n.defaultType)})(Su);var gr={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var r in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],r=1;r<arguments.length;r++){var i=arguments[r];e=e[i]||(r===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],r=arguments[arguments.length-1],i=1;i<arguments.length-1;i++){var o=arguments[i];e=e[o]||(e[o]=i===arguments.length-2?r():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],r=[e],i=1;i<arguments.length-1;i++){var o=arguments[i];if(!e.hasOwnProperty(o))break;e=e[o],r.push(e)}for(var i=r.length-1;i>=0;i--){var s=r[i],o=arguments[i+1],l=s[o];(i===r.length-1||!n.hasKeys(l))&&delete s[o]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,r){var i=!1;return e.forEach(function(o){o&&(o(r),i=!0)}),i},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];setTimeout(function(){e.apply(null,r)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(gr);var $T=Array.isArray,HT=Object.keys,VO=Object.prototype.hasOwnProperty,$O=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=$T(t),i=$T(e),o,s,l;if(r&&i){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!n(t[o],e[o]))return!1;return!0}if(r!=i)return!1;var c=t instanceof Date,d=e instanceof Date;if(c!=d)return!1;if(c&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,C=e instanceof RegExp;if(h!=C)return!1;if(h&&C)return t.toString()==e.toString();var E=HT(t);if(s=E.length,s!==HT(e).length)return!1;for(o=s;o--!==0;)if(!VO.call(e,E[o]))return!1;for(o=s;o--!==0;)if(l=E[o],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},Jo={};Jo.ACTIONS={initLegacy:"init",handshake:"hs",queryFetch:"qf",querySubscribe:"qs",queryUnsubscribe:"qu",queryUpdate:"q",bulkFetch:"bf",bulkSubscribe:"bs",bulkUnsubscribe:"bu",fetch:"f",fixup:"fixup",subscribe:"s",unsubscribe:"u",op:"op",snapshotFetch:"nf",snapshotFetchByTimestamp:"nt",pingPong:"pp",presence:"p",presenceSubscribe:"ps",presenceUnsubscribe:"pu",presenceRequest:"pr"};var jT=Yo,HO=FT,Zn=Vh,jh=Su,Kr=gr,jO=Kr.clone,zO=$O,Op=Jo.ACTIONS,Nn=Zn.CODES,GO=Ft;function Ft(n,t,e){jT.EventEmitter.call(this),this.connection=n,this.collection=t,this.id=e,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}jT.mixin(Ft),Ft.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this;t.whenNothingPending(function(){t.wantSubscribe?t.unsubscribe(function(e){if(e)return n?n(e):t.emit("error",e);t.connection._destroyDoc(t),n&&n()}):(t.connection._destroyDoc(t),n&&n())})},Ft.prototype._setType=function(n){if(typeof n=="string"&&(n=jh.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Zn(Nn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Ft.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Ft.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Zn(Nn.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return t&&this.once("no write pending",t);var e=new Zn(Nn.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var r=n.type===void 0?jh.defaultType:n.type;this._setType(r),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},Ft.prototype.whenNothingPending=function(n){var t=this;Kr.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Ft.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Ft.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Ft.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Ft.prototype._emitResponseError=function(n,t){if(n&&n.code===Nn.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,t&&t(),this._emitNothingPending();return}if(t){t(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},Ft.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var r=this.inflightFetch.shift();if(r&&e.push(r),e.length&&(r=function(i){Kr.callEach(e,i)}),n)return this._emitResponseError(n,r);this.ingestSnapshot(t,r),this._emitNothingPending()},Ft.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var r=this.pendingFetch;this.pendingFetch=[],e.callback&&r.push(e.callback);var i;if(r.length&&(i=function(o){Kr.callEach(r,o)}),n)return this._emitResponseError(n,i);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,i):i&&i(),this._emitNothingPending(),this._flushSubscribe()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Nn.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq){this._opAcknowledged(t);return}if(this.version==null||t.v>this.version){this.fetch();return}if(!(t.v<this.version)){if(this.inflightOp){var e=Du(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var r=0;r<this.pendingOps.length;r++){var e=Du(this.pendingOps[r],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}}},Ft.prototype._onConnectionStateChanged=function(){this.connection.canSend?(this.flush(),this._resubscribe()):(this.inflightOp&&(this.pendingOps.unshift(this.inflightOp),this.inflightOp=null),this.subscribed=!1,this.inflightSubscribe&&(this.inflightSubscribe.wantSubscribe?(this.pendingSubscribe.unshift(this.inflightSubscribe),this.inflightSubscribe=null):this._handleSubscribe()),this.inflightFetch.length&&(this.pendingFetch=this.pendingFetch.concat(this.inflightFetch),this.inflightFetch.length=0))},Ft.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(t){return t.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},Ft.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);WO(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Ft.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Ft.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Ft.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,r=e&&e.wantSubscribe===n;if(r){e.callback=qO([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Ft.prototype._flushSubscribe=function(){if(!(this.inflightSubscribe||!this.pendingSubscribe.length)){if(this.connection.canSend){this.inflightSubscribe=this.pendingSubscribe.shift(),this.wantSubscribe=this.inflightSubscribe.wantSubscribe,this.wantSubscribe?this.connection.sendSubscribe(this):(this.subscribed=!1,this.connection.sendUnsubscribe(this));return}if(!this.pendingSubscribe[0].wantSubscribe){this.inflightSubscribe=this.pendingSubscribe.shift();var n=this;Kr.nextTick(function(){n._handleSubscribe()})}}};function WO(n,t,e){if(t){var r=n.pop();n.push(function(i){r&&r(i),e&&e(i)})}else n.push(e)}function qO(n){return n=n.filter(Kr.truthy),n.length?function(t){Kr.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function XO(n){delete n.op,delete n.create,delete n.del}function Du(n,t){if(n.del)return XO(t);if(t.del)return new Zn(Nn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Zn(Nn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Zn(Nn.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var r=n.type.transform(n.op,t.op,"left"),i=n.type.transform(t.op,n.op,"right");n.op=r,t.op=i}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Zn(Nn.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,t),!t&&this.type===jh.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,r=0;r<n.op.length;r++){var i=n.op[r],o={op:[i]};this.emit("before op",o.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=Du(this.applyStack[s],o);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,o.op)),this.emit("op",o.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",t);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,t);return}},Ft.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var t=this.inflightOp;if(!t){var e=new Zn(Nn.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",e)}if(t.sentAt=Date.now(),t.retries=t.retries==null?0:t.retries+1,t.seq==null){if(this.connection.seq>=Kr.MAX_SAFE_INTEGER)return this.emit("error",new Zn(Nn.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));t.seq=this.connection.seq++}this.connection.sendOp(this,t),t.src==null&&(t.src=n)}},Ft.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var r=new Zn(Nn.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(r):this.emit("error",r)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(o){return this._hardRollback(o)}var i=this;Kr.nextTick(function(){i.flush()})},Ft.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var r=this._tryCompose(n);if(r){r.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},Ft.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var r=this.pendingOps.splice(e),e=0;e<r.length;e++){var t=r[e],i=this._tryCompose(t);i?i.callbacks=i.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},Ft.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!zO(n.source,t.source))){if(t.create&&"op"in n)return t.create.data=this.type.apply(t.create.data,n.op),t;if("op"in t&&"op"in n&&this.type.compose)return t.op=this.type.compose(t.op,n.op),t}}},Ft.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var r={op:n},i=t&&t.source;this._submit(r,i,e)},Ft.prototype.create=function(n,t,e,r){if(typeof t=="function"?(r=t,e=null,t=null):typeof e=="function"&&(r=e,e=null),t||(t=jh.defaultType.uri),this.type){var i=new Zn(Nn.ERR_DOC_ALREADY_CREATED,"Document already exists");return r?r(i):this.emit("error",i)}var o={create:{type:t,data:n}},s=e&&e.source;this._submit(o,s,r)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Zn(Nn.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var r={del:!0},i=n&&n.source;this._submit(r,i,t)},Ft.prototype.pause=function(){this.paused=!0},Ft.prototype.resume=function(){this.paused=!1,this.flush()},Ft.prototype.toSnapshot=function(){return{v:this.version,data:jO(this.data),type:this.type.uri}},Ft.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return HO.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();if(n[Op.fixup])for(var t=0;t<n[Op.fixup].length;t++){for(var e=n[Op.fixup][t],r=0;r<this.pendingOps.length;r++){var i=Du(this.pendingOps[t],e);if(i)return this._hardRollback(i)}try{this._otApply(e,!1)}catch(o){return this._hardRollback(o)}}this.version++,this._clearInflightOp()},Ft.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var r=Du(this.pendingOps[e],t);if(r)return this._hardRollback(r)}try{this._otApply(t,!1)}catch(i){return this._hardRollback(i)}this._clearInflightOp(n);return}this._hardRollback(n)},Ft.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var r=!!t.length,i=0;i<t.length;i++)r=Kr.callEach(t[i].callbacks,n)&&r;if(n&&!r)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Kr.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var zT=Yo,GT=Jo.ACTIONS,YO=gr,QO=Pn;function Pn(n,t,e,r,i,o,s){zT.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=r,this.query=i,this.results=null,o&&o.results&&(this.results=o.results,delete o.results),this.extra=void 0,this.options=o,this.callback=s,this.ready=!1,this.sent=!1}zT.mixin(Pn),Pn.prototype.hasPending=function(){return!this.ready},Pn.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var t=[],e=0;e<this.results.length;e++){var r=this.results[e];t.push([r.id,r.version])}n.r=t}this.connection.send(n),this.sent=!0}},Pn.prototype.destroy=function(n){this.connection.canSend&&this.action===GT.querySubscribe&&this.connection.send({a:GT.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&YO.nextTick(n)},Pn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Pn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Pn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Pn.prototype._handleResponse=function(n,t,e){var r=this.callback;if(this.callback=null,n)return this._finishResponse(n,r);if(!t)return this._finishResponse(null,r);var i=this,o=1,s=function(h){if(h)return i._finishResponse(h,r);--o||i._finishResponse(null,r)};if(Array.isArray(t))o+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){o++;var c=t[l],d=this.connection.get(c.c||this.collection,l);d.ingestSnapshot(c,s)}s()},Pn.prototype._ingestSnapshots=function(n,t){for(var e=[],r=0;r<n.length;r++){var i=n[r],o=this.connection.get(i.c||this.collection,i.d);o.ingestSnapshot(i,t),e.push(o)}return e},Pn.prototype._finishResponse=function(n,t){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),t?t(n):this.emit("error",n);t&&t(null,this.results,this.extra)},Pn.prototype._handleError=function(n){this.emit("error",n)},Pn.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var r=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(r)),this.emit("insert",r,e.index);break;case"remove":var o=e.howMany||1,i=this.results.splice(e.index,o);this.emit("remove",i,e.index);break;case"move":var o=e.howMany||1,s=this.results.splice(e.from,o);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},Pn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var WT=Yo,JO=Jo.ACTIONS,ZO=gr,qT=pi;function pi(n,t){if(WT.EventEmitter.call(this),!t||typeof t!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=t,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}WT.mixin(pi),pi.prototype.submit=function(n,t){this.value=n,this.send(t)},pi.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},pi.prototype.destroy=function(n){var t=this;this.submit(null,function(e){if(e)return t._callbackOrEmit(e,n);delete t.presence.localPresences[t.presenceId],n&&n()})},pi.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},pi.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},pi.prototype._message=function(){return{a:JO.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},pi.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},pi.prototype._callbackOrEmit=function(n,t){if(t)return ZO.nextTick(t,n);n&&this.emit("error",n)};var tN=gr,XT=Np;function Np(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}Np.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},Np.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&tN.nextTick(n)};var Pp={exports:{}};(function(n,t){(function(e,r){r(t)})(Mn,function(e){function r(y,S){S=S|0;for(var _=Math.max(y.length-S,0),N=Array(_),H=0;H<_;H++)N[H]=y[S+H];return N}var i=function(y){var S=r(arguments,1);return function(){var _=r(arguments);return y.apply(null,S.concat(_))}},o=function(y){return function(){var S=r(arguments),_=S.pop();y.call(this,S,_)}};function s(y){var S=typeof y;return y!=null&&(S=="object"||S=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function d(y){setTimeout(y,0)}function h(y){return function(S){var _=r(arguments,1);y(function(){S.apply(null,_)})}}var C;l?C=setImmediate:c?C=process.nextTick:C=d;var E=h(C);function x(y){return o(function(S,_){var N;try{N=y.apply(this,S)}catch(H){return _(H)}s(N)&&typeof N.then=="function"?N.then(function(H){v(_,null,H)},function(H){v(_,H.message?H:new Error(H))}):_(null,N)})}function v(y,S,_){try{y(S,_)}catch(N){E(k,N)}}function k(y){throw y}var L=typeof Symbol=="function";function M(y){return L&&y[Symbol.toStringTag]==="AsyncFunction"}function U(y){return M(y)?x(y):y}function F(y){return function(S){var _=r(arguments,1),N=o(function(H,$){var X=this;return y(S,function(Z,ut){U(Z).apply(X,H.concat(ut))},$)});return _.length?N.apply(this,_):N}}var G=typeof Mn=="object"&&Mn&&Mn.Object===Object&&Mn,q=typeof self=="object"&&self&&self.Object===Object&&self,rt=G||q||Function("return this")(),st=rt.Symbol,Et=Object.prototype,gt=Et.hasOwnProperty,At=Et.toString,Vt=st?st.toStringTag:void 0;function Gt(y){var S=gt.call(y,Vt),_=y[Vt];try{y[Vt]=void 0;var N=!0}catch{}var H=At.call(y);return N&&(S?y[Vt]=_:delete y[Vt]),H}var an=Object.prototype,be=an.toString;function Kn(y){return be.call(y)}var Li="[object Null]",Rn="[object Undefined]",En=st?st.toStringTag:void 0;function Ii(y){return y==null?y===void 0?Rn:Li:En&&En in Object(y)?Gt(y):Kn(y)}var fo="[object AsyncFunction]",xr="[object Function]",NA="[object GeneratorFunction]",PA="[object Proxy]";function FA(y){if(!s(y))return!1;var S=Ii(y);return S==xr||S==NA||S==fo||S==PA}var ps=9007199254740991;function Bl(y){return typeof y=="number"&&y>-1&&y%1==0&&y<=ps}function Tl(y){return y!=null&&Bl(y.length)&&!FA(y)}var ho={};function jt(){}function Di(y){return function(){if(y!==null){var S=y;y=null,S.apply(this,arguments)}}}var Cs=typeof Symbol=="function"&&Symbol.iterator,gc=function(y){return Cs&&y[Cs]&&y[Cs]()};function Am(y,S){for(var _=-1,N=Array(y);++_<y;)N[_]=S(_);return N}function An(y){return y!=null&&typeof y=="object"}var yl="[object Arguments]";function xm(y){return An(y)&&Ii(y)==yl}var br=Object.prototype,bm=br.hasOwnProperty,KA=br.propertyIsEnumerable,kl=xm(function(){return arguments}())?xm:function(y){return An(y)&&bm.call(y,"callee")&&!KA.call(y,"callee")},ke=Array.isArray;function Rl(){return!1}var wl=typeof e=="object"&&e&&!e.nodeType&&e,vm=wl&&!0&&n&&!n.nodeType&&n,Sl=vm&&vm.exports===wl,Bm=Sl?rt.Buffer:void 0,Ll=Bm?Bm.isBuffer:void 0,Es=Ll||Rl,Of=9007199254740991,Nf=/^(?:0|[1-9]\d*)$/;function Pf(y,S){var _=typeof y;return S=S==null?Of:S,!!S&&(_=="number"||_!="symbol"&&Nf.test(y))&&y>-1&&y%1==0&&y<S}var Ff="[object Arguments]",Kf="[object Array]",Vf="[object Boolean]",$f="[object Date]",Hf="[object Error]",jf="[object Function]",VA="[object Map]",$A="[object Number]",HA="[object Object]",Tm="[object RegExp]",ym="[object Set]",jA="[object String]",zA="[object WeakMap]",GA="[object ArrayBuffer]",WA="[object DataView]",km="[object Float32Array]",qA="[object Float64Array]",XA="[object Int8Array]",YA="[object Int16Array]",zf="[object Int32Array]",QA="[object Uint8Array]",Gf="[object Uint8ClampedArray]",JA="[object Uint16Array]",ZA="[object Uint32Array]",he={};he[km]=he[qA]=he[XA]=he[YA]=he[zf]=he[QA]=he[Gf]=he[JA]=he[ZA]=!0,he[Ff]=he[Kf]=he[GA]=he[Vf]=he[WA]=he[$f]=he[Hf]=he[jf]=he[VA]=he[$A]=he[HA]=he[Tm]=he[ym]=he[jA]=he[zA]=!1;function tx(y){return An(y)&&Bl(y.length)&&!!he[Ii(y)]}function ex(y){return function(S){return y(S)}}var Rm=typeof e=="object"&&e&&!e.nodeType&&e,Il=Rm&&!0&&n&&!n.nodeType&&n,nx=Il&&Il.exports===Rm,pc=nx&&G.process,wm=function(){try{var y=Il&&Il.require&&Il.require("util").types;return y||pc&&pc.binding&&pc.binding("util")}catch{}}(),Sm=wm&&wm.isTypedArray,rx=Sm?ex(Sm):tx,ix=Object.prototype,ox=ix.hasOwnProperty;function sx(y,S){var _=ke(y),N=!_&&kl(y),H=!_&&!N&&Es(y),$=!_&&!N&&!H&&rx(y),X=_||N||H||$,Z=X?Am(y.length,String):[],ut=Z.length;for(var xt in y)(S||ox.call(y,xt))&&!(X&&(xt=="length"||H&&(xt=="offset"||xt=="parent")||$&&(xt=="buffer"||xt=="byteLength"||xt=="byteOffset")||Pf(xt,ut)))&&Z.push(xt);return Z}var Cc=Object.prototype;function lx(y){var S=y&&y.constructor,_=typeof S=="function"&&S.prototype||Cc;return y===_}function Ec(y,S){return function(_){return y(S(_))}}var ax=Ec(Object.keys,Object),cx=Object.prototype,ux=cx.hasOwnProperty;function Lm(y){if(!lx(y))return ax(y);var S=[];for(var _ in Object(y))ux.call(y,_)&&_!="constructor"&&S.push(_);return S}function Ac(y){return Tl(y)?sx(y):Lm(y)}function Im(y){var S=-1,_=y.length;return function(){return++S<_?{value:y[S],key:S}:null}}function fx(y){var S=-1;return function(){var N=y.next();return N.done?null:(S++,{value:N.value,key:S})}}function dx(y){var S=Ac(y),_=-1,N=S.length;return function H(){var $=S[++_];return $==="__proto__"?H():_<N?{value:y[$],key:$}:null}}function hx(y){if(Tl(y))return Im(y);var S=gc(y);return S?fx(S):dx(y)}function vr(y){return function(){if(y===null)throw new Error("Callback was already called.");var S=y;y=null,S.apply(this,arguments)}}function Dl(y){return function(S,_,N){if(N=Di(N||jt),y<=0||!S)return N(null);var H=hx(S),$=!1,X=0,Z=!1;function ut(ft,vt){if(X-=1,ft)$=!0,N(ft);else{if(vt===ho||$&&X<=0)return $=!0,N(null);Z||xt()}}function xt(){for(Z=!0;X<y&&!$;){var ft=H();if(ft===null){$=!0,X<=0&&N(null);return}X+=1,_(ft.value,ft.key,vr(ut))}Z=!1}xt()}}function _i(y,S,_,N){Dl(S)(y,U(_),N)}function je(y,S){return function(_,N,H){return y(_,S,N,H)}}function Wf(y,S,_){_=Di(_||jt);var N=0,H=0,$=y.length;$===0&&_(null);function X(Z,ut){Z?_(Z):(++H===$||ut===ho)&&_(null)}for(;N<$;N++)S(y[N],N,vr(X))}var mx=je(_i,1/0),Yr=function(y,S,_){var N=Tl(y)?Wf:mx;N(y,U(S),_)};function Qr(y){return function(S,_,N){return y(Yr,S,U(_),N)}}function qf(y,S,_,N){N=N||jt,S=S||[];var H=[],$=0,X=U(_);y(S,function(Z,ut,xt){var ft=$++;X(Z,function(vt,te){H[ft]=te,xt(vt)})},function(Z){N(Z,H)})}var xc=Qr(qf),Xf=F(xc);function mo(y){return function(S,_,N,H){return y(Dl(_),S,U(N),H)}}var Mi=mo(qf),Yf=je(Mi,1),Qf=F(Yf);function As(y,S){for(var _=-1,N=y==null?0:y.length;++_<N&&S(y[_],_,y)!==!1;);return y}function Jf(y){return function(S,_,N){for(var H=-1,$=Object(S),X=N(S),Z=X.length;Z--;){var ut=X[y?Z:++H];if(_($[ut],ut,$)===!1)break}return S}}var xs=Jf();function bs(y,S){return y&&xs(y,S,Ac)}function Dm(y,S,_,N){for(var H=y.length,$=_+(N?1:-1);N?$--:++$<H;)if(S(y[$],$,y))return $;return-1}function gx(y){return y!==y}function _m(y,S,_){for(var N=_-1,H=y.length;++N<H;)if(y[N]===S)return N;return-1}function _l(y,S,_){return S===S?_m(y,S,_):Dm(y,gx,_)}var bc=function(y,S,_){typeof S=="function"&&(_=S,S=null),_=Di(_||jt);var N=Ac(y),H=N.length;if(!H)return _(null);S||(S=H);var $={},X=0,Z=!1,ut=Object.create(null),xt=[],ft=[],vt={};bs(y,function(Ce,ce){if(!ke(Ce)){te(ce,[Ce]),ft.push(ce);return}var ve=Ce.slice(0,Ce.length-1),Tr=ve.length;if(Tr===0){te(ce,Ce),ft.push(ce);return}vt[ce]=Tr,As(ve,function(R){if(!y[R])throw new Error("async.auto task `"+ce+"` has a non-existent dependency `"+R+"` in "+ve.join(", "));cn(R,function(){Tr--,Tr===0&&te(ce,Ce)})})}),Nx(),Oe();function te(Ce,ce){xt.push(function(){Br(Ce,ce)})}function Oe(){if(xt.length===0&&X===0)return _(null,$);for(;xt.length&&X<S;){var Ce=xt.shift();Ce()}}function cn(Ce,ce){var ve=ut[Ce];ve||(ve=ut[Ce]=[]),ve.push(ce)}function Hn(Ce){var ce=ut[Ce]||[];As(ce,function(ve){ve()}),Oe()}function Br(Ce,ce){if(!Z){var ve=vr(function(R,Ni){if(X--,arguments.length>2&&(Ni=r(arguments,1)),R){var ys={};bs($,function(jn,$t){ys[$t]=jn}),ys[Ce]=Ni,Z=!0,ut=Object.create(null),_(R,ys)}else $[Ce]=Ni,Hn(Ce)});X++;var Tr=U(ce[ce.length-1]);ce.length>1?Tr($,ve):Tr(ve)}}function Nx(){for(var Ce,ce=0;ft.length;)Ce=ft.pop(),ce++,As(Px(Ce),function(ve){--vt[ve]===0&&ft.push(ve)});if(ce!==H)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function Px(Ce){var ce=[];return bs(y,function(ve,Tr){ke(ve)&&_l(ve,Ce,0)>=0&&ce.push(Tr)}),ce}};function go(y,S){for(var _=-1,N=y==null?0:y.length,H=Array(N);++_<N;)H[_]=S(y[_],_,y);return H}var px="[object Symbol]";function Cx(y){return typeof y=="symbol"||An(y)&&Ii(y)==px}var Ex=1/0,Zf=st?st.prototype:void 0,Mm=Zf?Zf.toString:void 0;function td(y){if(typeof y=="string")return y;if(ke(y))return go(y,td)+"";if(Cx(y))return Mm?Mm.call(y):"";var S=y+"";return S=="0"&&1/y==-Ex?"-0":S}function Ax(y,S,_){var N=-1,H=y.length;S<0&&(S=-S>H?0:H+S),_=_>H?H:_,_<0&&(_+=H),H=S>_?0:_-S>>>0,S>>>=0;for(var $=Array(H);++N<H;)$[N]=y[N+S];return $}function xx(y,S,_){var N=y.length;return _=_===void 0?N:_,!S&&_>=N?y:Ax(y,S,_)}function ed(y,S){for(var _=y.length;_--&&_l(S,y[_],0)>-1;);return _}function bx(y,S){for(var _=-1,N=y.length;++_<N&&_l(S,y[_],0)>-1;);return _}function vx(y){return y.split("")}var Bx="\\ud800-\\udfff",Tx="\\u0300-\\u036f",yx="\\ufe20-\\ufe2f",me="\\u20d0-\\u20ff",ae=Tx+yx+me,kx="\\ufe0e\\ufe0f",Rx="\\u200d",wx=RegExp("["+Rx+Bx+ae+kx+"]");function Sx(y){return wx.test(y)}var Um="\\ud800-\\udfff",Lx="\\u0300-\\u036f",Om="\\ufe20-\\ufe2f",Ix="\\u20d0-\\u20ff",Ze=Lx+Om+Ix,nd="\\ufe0e\\ufe0f",po="["+Um+"]",vc="["+Ze+"]",Ml="\\ud83c[\\udffb-\\udfff]",Vn="(?:"+vc+"|"+Ml+")",rd="[^"+Um+"]",id="(?:\\ud83c[\\udde6-\\uddff]){2}",od="[\\ud800-\\udbff][\\udc00-\\udfff]",Nm="\\u200d",sd=Vn+"?",ld="["+nd+"]?",wn="(?:"+Nm+"(?:"+[rd,id,od].join("|")+")"+ld+sd+")*",Dx=ld+sd+wn,$n="(?:"+[rd+vc+"?",vc,id,od,po].join("|")+")",_x=RegExp(Ml+"(?="+Ml+")|"+$n+Dx,"g");function Pm(y){return y.match(_x)||[]}function Jr(y){return Sx(y)?Pm(y):vx(y)}function Bc(y){return y==null?"":td(y)}var ad=/^\s+|\s+$/g;function pe(y,S,_){if(y=Bc(y),y&&(_||S===void 0))return y.replace(ad,"");if(!y||!(S=td(S)))return y;var N=Jr(y),H=Jr(S),$=bx(N,H),X=ed(N,H)+1;return xx(N,$,X).join("")}var Ui=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,cd=/,/,Mx=/(=.+)?(\s*)$/,ud=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function Ux(y){return y=y.toString().replace(ud,""),y=y.match(Ui)[2].replace(" ",""),y=y?y.split(cd):[],y=y.map(function(S){return pe(S.replace(Mx,""))}),y}function Fm(y,S){var _={};bs(y,function(N,H){var $,X=M(N),Z=!X&&N.length===1||X&&N.length===0;if(ke(N))$=N.slice(0,-1),N=N[N.length-1],_[H]=$.concat($.length>0?ut:N);else if(Z)_[H]=N;else{if($=Ux(N),N.length===0&&!X&&$.length===0)throw new Error("autoInject task functions require explicit parameters.");X||$.pop(),_[H]=$.concat(ut)}function ut(xt,ft){var vt=go($,function(te){return xt[te]});vt.push(ft),U(N).apply(null,vt)}}),bc(_,S)}function rr(){this.head=this.tail=null,this.length=0}function fd(y,S){y.length=1,y.head=y.tail=S}rr.prototype.removeLink=function(y){return y.prev?y.prev.next=y.next:this.head=y.next,y.next?y.next.prev=y.prev:this.tail=y.prev,y.prev=y.next=null,this.length-=1,y},rr.prototype.empty=function(){for(;this.head;)this.shift();return this},rr.prototype.insertAfter=function(y,S){S.prev=y,S.next=y.next,y.next?y.next.prev=S:this.tail=S,y.next=S,this.length+=1},rr.prototype.insertBefore=function(y,S){S.prev=y.prev,S.next=y,y.prev?y.prev.next=S:this.head=S,y.prev=S,this.length+=1},rr.prototype.unshift=function(y){this.head?this.insertBefore(this.head,y):fd(this,y)},rr.prototype.push=function(y){this.tail?this.insertAfter(this.tail,y):fd(this,y)},rr.prototype.shift=function(){return this.head&&this.removeLink(this.head)},rr.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},rr.prototype.toArray=function(){for(var y=Array(this.length),S=this.head,_=0;_<this.length;_++)y[_]=S.data,S=S.next;return y},rr.prototype.remove=function(y){for(var S=this.head;S;){var _=S.next;y(S)&&this.removeLink(S),S=_}return this};function Ul(y,S,_){if(S==null)S=1;else if(S===0)throw new Error("Concurrency must not be zero");var N=U(y),H=0,$=[],X=!1;function Z(vt,te,Oe){if(Oe!=null&&typeof Oe!="function")throw new Error("task callback must be a function");if(ft.started=!0,ke(vt)||(vt=[vt]),vt.length===0&&ft.idle())return E(function(){ft.drain()});for(var cn=0,Hn=vt.length;cn<Hn;cn++){var Br={data:vt[cn],callback:Oe||jt};te?ft._tasks.unshift(Br):ft._tasks.push(Br)}X||(X=!0,E(function(){X=!1,ft.process()}))}function ut(vt){return function(te){H-=1;for(var Oe=0,cn=vt.length;Oe<cn;Oe++){var Hn=vt[Oe],Br=_l($,Hn,0);Br===0?$.shift():Br>0&&$.splice(Br,1),Hn.callback.apply(Hn,arguments),te!=null&&ft.error(te,Hn.data)}H<=ft.concurrency-ft.buffer&&ft.unsaturated(),ft.idle()&&ft.drain(),ft.process()}}var xt=!1,ft={_tasks:new rr,concurrency:S,payload:_,saturated:jt,unsaturated:jt,buffer:S/4,empty:jt,drain:jt,error:jt,started:!1,paused:!1,push:function(vt,te){Z(vt,!1,te)},kill:function(){ft.drain=jt,ft._tasks.empty()},unshift:function(vt,te){Z(vt,!0,te)},remove:function(vt){ft._tasks.remove(vt)},process:function(){if(!xt){for(xt=!0;!ft.paused&&H<ft.concurrency&&ft._tasks.length;){var vt=[],te=[],Oe=ft._tasks.length;ft.payload&&(Oe=Math.min(Oe,ft.payload));for(var cn=0;cn<Oe;cn++){var Hn=ft._tasks.shift();vt.push(Hn),$.push(Hn),te.push(Hn.data)}H+=1,ft._tasks.length===0&&ft.empty(),H===ft.concurrency&&ft.saturated();var Br=vr(ut(vt));N(te,Br)}xt=!1}},length:function(){return ft._tasks.length},running:function(){return H},workersList:function(){return $},idle:function(){return ft._tasks.length+H===0},pause:function(){ft.paused=!0},resume:function(){ft.paused!==!1&&(ft.paused=!1,E(ft.process))}};return ft}function Co(y,S){return Ul(y,1,S)}var vs=je(_i,1);function Zr(y,S,_,N){N=Di(N||jt);var H=U(_);vs(y,function($,X,Z){H(S,$,function(ut,xt){S=xt,Z(ut)})},function($){N($,S)})}function Tc(){var y=go(arguments,U);return function(){var S=r(arguments),_=this,N=S[S.length-1];typeof N=="function"?S.pop():N=jt,Zr(y,S,function(H,$,X){$.apply(_,H.concat(function(Z){var ut=r(arguments,1);X(Z,ut)}))},function(H,$){N.apply(_,[H].concat($))})}}var yc=function(){return Tc.apply(null,r(arguments).reverse())},dd=Array.prototype.concat,Ol=function(y,S,_,N){N=N||jt;var H=U(_);Mi(y,S,function($,X){H($,function(Z){return Z?X(Z):X(null,r(arguments,1))})},function($,X){for(var Z=[],ut=0;ut<X.length;ut++)X[ut]&&(Z=dd.apply(Z,X[ut]));return N($,Z)})},Km=je(Ol,1/0),kc=je(Ol,1),Rc=function(){var y=r(arguments),S=[null].concat(y);return function(){var _=arguments[arguments.length-1];return _.apply(this,S)}};function Nl(y){return y}function Eo(y,S){return function(_,N,H,$){$=$||jt;var X=!1,Z;_(N,function(ut,xt,ft){H(ut,function(vt,te){vt?ft(vt):y(te)&&!Z?(X=!0,Z=S(!0,ut),ft(null,ho)):ft()})},function(ut){ut?$(ut):$(null,X?Z:S(!1))})}}function xn(y,S){return S}var Bs=Qr(Eo(Nl,xn)),ti=mo(Eo(Nl,xn)),Pl=je(ti,1);function hd(y){return function(S){var _=r(arguments,1);_.push(function(N){var H=r(arguments,1);typeof console=="object"&&(N?console.error&&console.error(N):console[y]&&As(H,function($){console[y]($)}))}),U(S).apply(null,_)}}var Vm=hd("dir");function $m(y,S,_){_=vr(_||jt);var N=U(y),H=U(S);function $(Z){if(Z)return _(Z);var ut=r(arguments,1);ut.push(X),H.apply(this,ut)}function X(Z,ut){if(Z)return _(Z);if(!ut)return _(null);N($)}X(null,!0)}function md(y,S,_){_=vr(_||jt);var N=U(y),H=function($){if($)return _($);var X=r(arguments,1);if(S.apply(this,X))return N(H);_.apply(null,[null].concat(X))};N(H)}function Hm(y,S,_){md(y,function(){return!S.apply(this,arguments)},_)}function jm(y,S,_){_=vr(_||jt);var N=U(S),H=U(y);function $(Z){if(Z)return _(Z);H(X)}function X(Z,ut){if(Z)return _(Z);if(!ut)return _(null);N($)}H(X)}function Ao(y){return function(S,_,N){return y(S,N)}}function wc(y,S,_){Yr(y,Ao(U(S)),_)}function Fl(y,S,_,N){Dl(S)(y,Ao(U(_)),N)}var xo=je(Fl,1);function Sc(y){return M(y)?y:o(function(S,_){var N=!0;S.push(function(){var H=arguments;N?E(function(){_.apply(null,H)}):_.apply(null,H)}),y.apply(this,S),N=!1})}function ir(y){return!y}var bo=Qr(Eo(ir,ir)),Kl=mo(Eo(ir,ir)),Lc=je(Kl,1);function zm(y){return function(S){return S==null?void 0:S[y]}}function Ts(y,S,_,N){var H=new Array(S.length);y(S,function($,X,Z){_($,function(ut,xt){H[X]=!!xt,Z(ut)})},function($){if($)return N($);for(var X=[],Z=0;Z<S.length;Z++)H[Z]&&X.push(S[Z]);N(null,X)})}function or(y,S,_,N){var H=[];y(S,function($,X,Z){_($,function(ut,xt){ut?Z(ut):(xt&&H.push({index:X,value:$}),Z())})},function($){$?N($):N(null,go(H.sort(function(X,Z){return X.index-Z.index}),zm("value")))})}function Ic(y,S,_,N){var H=Tl(S)?Ts:or;H(y,S,U(_),N||jt)}var Dc=Qr(Ic),Vl=mo(Ic),_c=je(Vl,1);function Gm(y,S){var _=vr(S||jt),N=U(Sc(y));function H($){if($)return _($);N(H)}H()}var Mc=function(y,S,_,N){N=N||jt;var H=U(_);Mi(y,S,function($,X){H($,function(Z,ut){return Z?X(Z):X(null,{key:ut,val:$})})},function($,X){for(var Z={},ut=Object.prototype.hasOwnProperty,xt=0;xt<X.length;xt++)if(X[xt]){var ft=X[xt].key,vt=X[xt].val;ut.call(Z,ft)?Z[ft].push(vt):Z[ft]=[vt]}return N($,Z)})},vo=je(Mc,1/0),K=je(Mc,1),W=hd("log");function j(y,S,_,N){N=Di(N||jt);var H={},$=U(_);_i(y,S,function(X,Z,ut){$(X,Z,function(xt,ft){if(xt)return ut(xt);H[Z]=ft,ut()})},function(X){N(X,H)})}var pt=je(j,1/0),St=je(j,1);function qt(y,S){return S in y}function Ie(y,S){var _=Object.create(null),N=Object.create(null);S=S||Nl;var H=U(y),$=o(function(Z,ut){var xt=S.apply(null,Z);qt(_,xt)?E(function(){ut.apply(null,_[xt])}):qt(N,xt)?N[xt].push(ut):(N[xt]=[ut],H.apply(null,Z.concat(function(){var ft=r(arguments);_[xt]=ft;var vt=N[xt];delete N[xt];for(var te=0,Oe=vt.length;te<Oe;te++)vt[te].apply(null,ft)})))});return $.memo=_,$.unmemoized=y,$}var Zt;c?Zt=process.nextTick:l?Zt=setImmediate:Zt=d;var Uc=h(Zt);function gd(y,S,_){_=_||jt;var N=Tl(S)?[]:{};y(S,function(H,$,X){U(H)(function(Z,ut){arguments.length>2&&(ut=r(arguments,1)),N[$]=ut,X(Z)})},function(H){_(H,N)})}function Sn(y,S){gd(Yr,y,S)}function $l(y,S,_){gd(Dl(S),y,_)}var pd=function(y,S){var _=U(y);return Ul(function(N,H){_(N[0],H)},S,1)},Bo=function(y,S){var _=pd(y,S);return _.push=function(N,H,$){if($==null&&($=jt),typeof $!="function")throw new Error("task callback must be a function");if(_.started=!0,ke(N)||(N=[N]),N.length===0)return E(function(){_.drain()});H=H||0;for(var X=_._tasks.head;X&&H>=X.priority;)X=X.next;for(var Z=0,ut=N.length;Z<ut;Z++){var xt={data:N[Z],priority:H,callback:$};X?_._tasks.insertBefore(X,xt):_._tasks.push(xt)}E(_.process)},delete _.unshift,_};function Hl(y,S){if(S=Di(S||jt),!ke(y))return S(new TypeError("First argument to race must be an array of functions"));if(!y.length)return S();for(var _=0,N=y.length;_<N;_++)U(y[_])(S)}function To(y,S,_,N){var H=r(y).reverse();Zr(H,S,_,N)}function Xt(y){var S=U(y);return o(function(N,H){return N.push(function(X,Z){if(X)H(null,{error:X});else{var ut;arguments.length<=2?ut=Z:ut=r(arguments,1),H(null,{value:ut})}}),S.apply(this,N)})}function Wm(y){var S;return ke(y)?S=go(y,Xt):(S={},bs(y,function(_,N){S[N]=Xt.call(this,_)})),S}function Cd(y,S,_,N){Ic(y,S,function(H,$){_(H,function(X,Z){$(X,!Z)})},N)}var jl=Qr(Cd),Ed=mo(Cd),qm=je(Ed,1);function Xm(y){return function(){return y}}function yo(y,S,_){var N=5,H=0,$={times:N,intervalFunc:Xm(H)};function X(ft,vt){if(typeof vt=="object")ft.times=+vt.times||N,ft.intervalFunc=typeof vt.interval=="function"?vt.interval:Xm(+vt.interval||H),ft.errorFilter=vt.errorFilter;else if(typeof vt=="number"||typeof vt=="string")ft.times=+vt||N;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof y=="function"?(_=S||jt,S=y):(X($,y),_=_||jt),typeof S!="function")throw new Error("Invalid arguments for async.retry");var Z=U(S),ut=1;function xt(){Z(function(ft){ft&&ut++<$.times&&(typeof $.errorFilter!="function"||$.errorFilter(ft))?setTimeout(xt,$.intervalFunc(ut)):_.apply(null,arguments)})}xt()}var ei=function(y,S){S||(S=y,y=null);var _=U(S);return o(function(N,H){function $(X){_.apply(null,N.concat(X))}y?yo(y,$,H):yo($,H)})};function zl(y,S){gd(vs,y,S)}var Gl=Qr(Eo(Boolean,Nl)),Oi=mo(Eo(Boolean,Nl)),Wl=je(Oi,1);function Ad(y,S,_){var N=U(S);xc(y,function($,X){N($,function(Z,ut){if(Z)return X(Z);X(null,{value:$,criteria:ut})})},function($,X){if($)return _($);_(null,go(X.sort(H),zm("value")))});function H($,X){var Z=$.criteria,ut=X.criteria;return Z<ut?-1:Z>ut?1:0}}function ql(y,S,_){var N=U(y);return o(function(H,$){var X=!1,Z;function ut(){var xt=y.name||"anonymous",ft=new Error('Callback function "'+xt+'" timed out.');ft.code="ETIMEDOUT",_&&(ft.info=_),X=!0,$(ft)}H.push(function(){X||($.apply(null,arguments),clearTimeout(Z))}),Z=setTimeout(ut,S),N.apply(null,H)})}var Ym=Math.ceil,Xl=Math.max;function ko(y,S,_,N){for(var H=-1,$=Xl(Ym((S-y)/(_||1)),0),X=Array($);$--;)X[N?$:++H]=y,y+=_;return X}function Ro(y,S,_,N){var H=U(_);Mi(ko(0,y,1),S,H,N)}var Qm=je(Ro,1/0),Jm=je(Ro,1);function Zm(y,S,_,N){arguments.length<=3&&(N=_,_=S,S=ke(y)?[]:{}),N=Di(N||jt);var H=U(_);Yr(y,function($,X,Z){H(S,$,X,Z)},function($){N($,S)})}function Yl(y,S){var _=null,N;S=S||jt,xo(y,function(H,$){U(H)(function(X,Z){arguments.length>2?N=r(arguments,1):N=Z,_=X,$(!X)})},function(){S(_,N)})}function Ql(y){return function(){return(y.unmemoized||y).apply(null,arguments)}}function Jl(y,S,_){_=vr(_||jt);var N=U(S);if(!y())return _(null);var H=function($){if($)return _($);if(y())return N(H);var X=r(arguments,1);_.apply(null,[null].concat(X))};N(H)}function tg(y,S,_){Jl(function(){return!y.apply(this,arguments)},S,_)}var xd=function(y,S){if(S=Di(S||jt),!ke(y))return S(new Error("First argument to waterfall must be an array of functions"));if(!y.length)return S();var _=0;function N($){var X=U(y[_++]);$.push(vr(H)),X.apply(null,$)}function H($){if($||_===y.length)return S.apply(null,arguments);N(r(arguments,1))}N([])},Ox={apply:i,applyEach:Xf,applyEachSeries:Qf,asyncify:x,auto:bc,autoInject:Fm,cargo:Co,compose:yc,concat:Km,concatLimit:Ol,concatSeries:kc,constant:Rc,detect:Bs,detectLimit:ti,detectSeries:Pl,dir:Vm,doDuring:$m,doUntil:Hm,doWhilst:md,during:jm,each:wc,eachLimit:Fl,eachOf:Yr,eachOfLimit:_i,eachOfSeries:vs,eachSeries:xo,ensureAsync:Sc,every:bo,everyLimit:Kl,everySeries:Lc,filter:Dc,filterLimit:Vl,filterSeries:_c,forever:Gm,groupBy:vo,groupByLimit:Mc,groupBySeries:K,log:W,map:xc,mapLimit:Mi,mapSeries:Yf,mapValues:pt,mapValuesLimit:j,mapValuesSeries:St,memoize:Ie,nextTick:Uc,parallel:Sn,parallelLimit:$l,priorityQueue:Bo,queue:pd,race:Hl,reduce:Zr,reduceRight:To,reflect:Xt,reflectAll:Wm,reject:jl,rejectLimit:Ed,rejectSeries:qm,retry:yo,retryable:ei,seq:Tc,series:zl,setImmediate:E,some:Gl,someLimit:Oi,someSeries:Wl,sortBy:Ad,timeout:ql,times:Qm,timesLimit:Ro,timesSeries:Jm,transform:Zm,tryEach:Yl,unmemoize:Ql,until:tg,waterfall:xd,whilst:Jl,all:bo,allLimit:Kl,allSeries:Lc,any:Gl,anyLimit:Oi,anySeries:Wl,find:Bs,findLimit:ti,findSeries:Pl,forEach:wc,forEachSeries:xo,forEachLimit:Fl,forEachOf:Yr,forEachOfSeries:vs,forEachOfLimit:_i,inject:Zr,foldl:Zr,foldr:To,select:Dc,selectLimit:Vl,selectSeries:_c,wrapSync:x};e.default=Ox,e.apply=i,e.applyEach=Xf,e.applyEachSeries=Qf,e.asyncify=x,e.auto=bc,e.autoInject=Fm,e.cargo=Co,e.compose=yc,e.concat=Km,e.concatLimit=Ol,e.concatSeries=kc,e.constant=Rc,e.detect=Bs,e.detectLimit=ti,e.detectSeries=Pl,e.dir=Vm,e.doDuring=$m,e.doUntil=Hm,e.doWhilst=md,e.during=jm,e.each=wc,e.eachLimit=Fl,e.eachOf=Yr,e.eachOfLimit=_i,e.eachOfSeries=vs,e.eachSeries=xo,e.ensureAsync=Sc,e.every=bo,e.everyLimit=Kl,e.everySeries=Lc,e.filter=Dc,e.filterLimit=Vl,e.filterSeries=_c,e.forever=Gm,e.groupBy=vo,e.groupByLimit=Mc,e.groupBySeries=K,e.log=W,e.map=xc,e.mapLimit=Mi,e.mapSeries=Yf,e.mapValues=pt,e.mapValuesLimit=j,e.mapValuesSeries=St,e.memoize=Ie,e.nextTick=Uc,e.parallel=Sn,e.parallelLimit=$l,e.priorityQueue=Bo,e.queue=pd,e.race=Hl,e.reduce=Zr,e.reduceRight=To,e.reflect=Xt,e.reflectAll=Wm,e.reject=jl,e.rejectLimit=Ed,e.rejectSeries=qm,e.retry=yo,e.retryable=ei,e.seq=Tc,e.series=zl,e.setImmediate=E,e.some=Gl,e.someLimit=Oi,e.someSeries=Wl,e.sortBy=Ad,e.timeout=ql,e.times=Qm,e.timesLimit=Ro,e.timesSeries=Jm,e.transform=Zm,e.tryEach=Yl,e.unmemoize=Ql,e.until=tg,e.waterfall=xd,e.whilst=Jl,e.all=bo,e.allLimit=Kl,e.allSeries=Lc,e.any=Gl,e.anyLimit=Oi,e.anySeries=Wl,e.find=Bs,e.findLimit=ti,e.findSeries=Pl,e.forEach=wc,e.forEachSeries=xo,e.forEachLimit=Fl,e.forEachOf=Yr,e.forEachOfSeries=vs,e.forEachOfLimit=_i,e.inject=Zr,e.foldl=Zr,e.foldr=To,e.select=Dc,e.selectLimit=Vl,e.selectSeries=_c,e.wrapSync=x,Object.defineProperty(e,"__esModule",{value:!0})})})(Pp,Pp.exports);var YT={exports:{}},Fp=YT.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),r=2;e===1/0;r*=2)e=Math.log(Math.pow(2,n/r))/Math.log(t)*r;for(var i=e-Math.floor(e),o="",r=0;r<Math.floor(e);r++){var s=Math.floor(Math.random()*t).toString(t);o=s+o}if(i){var l=Math.pow(t,i),s=Math.floor(Math.random()*l).toString(t);o=s+o}var c=parseInt(o,t);return c!==1/0&&c>=Math.pow(2,n)?Fp(n,t):o};Fp.rack=function(n,t,e){var r=function(o){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=Fp(n,t)}while(Object.hasOwnProperty.call(i,l));return i[l]=o,l},i=r.hats={};return r.get=function(o){return r.hats[o]},r.set=function(o,s){return r.hats[o]=s,r},r.bits=n||128,r.base=t||16,r};var QT=Yo,eN=qT,nN=XT,zh=gr,Kp=Pp.exports,rN=YT.exports,JT=Jo.ACTIONS,ZT=Fe;function Fe(n,t){if(QT.EventEmitter.call(this),!t||typeof t!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=t,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}QT.mixin(Fe),Fe.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Fe.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Fe.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||rN();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Fe.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(r){if(r)return t._callbackOrEmit(r,n);var i=Object.keys(t._remotePresenceInstances);Kp.parallel([function(o){Kp.each(e,function(s,l){t.localPresences[s].destroy(l)},o)},function(o){if(!t._wantsDestroy)return o();Kp.each(i,function(s,l){t._remotePresenceInstances[s].destroy(l)},o)}],function(o){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(o,n)})})},Fe.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?JT.presenceSubscribe:JT.presenceUnsubscribe,r=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[r]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,r,this)},Fe.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Fe.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Fe.prototype._receiveUpdate=function(n,t){var e=zh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var r=this,i=zh.digOrCreate(this._remotePresenceInstances,t.id,function(){return r._createRemotePresence(t.id)});i.receiveUpdate(t)},Fe.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Fe.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var t in this.localPresences){var e=this.localPresences[t];e.value!==null&&e.send()}},Fe.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Fe.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Fe.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var r=this;this.subscribe(function(i){r._callEachOrEmit(n,i)})},Fe.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Fe.prototype._callbackOrEmit=function(n,t){if(t)return zh.nextTick(t,n);n&&this.emit("error",n)},Fe.prototype._createLocalPresence=function(n){return new eN(this,n)},Fe.prototype._createRemotePresence=function(n){return new nN(this,n)},Fe.prototype._callEachOrEmit=function(n,t){var e=zh.callEach(n,t);!e&&t&&this.emit("error",t)};var _u=qT,t2=Vh,iN=gr,e2=t2.CODES,oN=Vr;function Vr(n,t){_u.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._emitter=this.connection._docPresenceEmitter,this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}Vr.prototype=Object.create(_u.prototype),Vr.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:e2.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(e,t)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,_u.prototype.submit.call(this,n,t)},Vr.prototype.destroy=function(n){this._emitter.removeEventListener(this._doc,"op",this._opHandler),this._emitter.removeEventListener(this._doc,"create",this._createOrDelHandler),this._emitter.removeEventListener(this._doc,"del",this._createOrDelHandler),this._emitter.removeEventListener(this._doc,"load",this._loadHandler),this._emitter.removeEventListener(this._doc,"destroy",this._destroyHandler),_u.prototype.destroy.call(this,n)},Vr.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},Vr.prototype._registerWithDoc=function(){this._emitter.addEventListener(this._doc,"op",this._opHandler),this._emitter.addEventListener(this._doc,"create",this._createOrDelHandler),this._emitter.addEventListener(this._doc,"del",this._createOrDelHandler),this._emitter.addEventListener(this._doc,"load",this._loadHandler),this._emitter.addEventListener(this._doc,"destroy",this._destroyHandler)},Vr.prototype._transformAgainstOp=function(n,t){var e=this,r=this._doc._dataStateVersion;this._pendingMessages.forEach(function(i){var o=e._docDataVersionByPresenceVersion[i.pv];if(!(o>=r))try{i.p=e._transformPresence(i.p,n,t),e._docDataVersionByPresenceVersion[i.pv]=r}catch(l){var s=e._getCallback(i.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(i){this.emit("error",i)}},Vr.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Vr.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Vr.prototype._message=function(){var n=_u.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Vr.prototype._transformPresence=function(n,t,e){var r=this._doc.type;if(!iN.supportsPresence(r))throw new t2(e2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+r.name);return r.transformPresence(n,t,e)};var n2={};(function(n){var t=Su,e=Vh,r=gr,i=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[c];if(d==null||typeof d!="object")return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(i.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(i.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(i.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(i.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new e(i.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(i.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new e(i.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new e(i.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new e(i.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=c.create,h=t.map[d.type];if(!h)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(E){return E}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var C=o(l,c.op);if(C)return C;l.v++}else l.v++};function o(l,c){if(!l.type)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new e(i.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,c)}catch(h){return new e(i.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,c,d){if(c.v!=null&&c.v!==d.v)return new e(i.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(c.create||"op"in c)return new e(i.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in c||c.create||c.del)||"op"in d&&c.create)return new e(i.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in c){if(!l)return new e(i.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(i.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,d.op,"left")}catch(h){return h}}}c.v!=null&&c.v++},n.applyOps=function(l,c,d){d=d||{};for(var h=0;h<c.length;h++){var C=c[h];if(d._normalizeLegacyJson0Ops)try{s(l,C)}catch{return new e(i.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=C.v;var E=n.apply(l,C);if(E)return E}},n.transformPresence=function(l,c,d){var h=this.checkOp(c);if(h)return h;var C=l.t;if(typeof C=="string"&&(C=t.map[C]),!C)return{code:i.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!r.supportsPresence(C))return{code:i.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:C.transformPresence(l.p,c.op,d)}catch(E){return{code:i.ERR_PRESENCE_TRANSFORM_FAILED,message:E.message||E}}l.v++};function s(l,c){if(l.type===t.defaultType.uri){var d=c.op;if(!!d){var h=l.data;d.length>1&&(h=r.clone(h));for(var C=0;C<d.length;C++){var E=d[C];typeof E.lm=="string"&&(E.lm=+E.lm);for(var x=E.p,v=h,k=0;k<x.length;k++){var L=x[k];Object.prototype.toString.call(v)=="[object Array]"?x[k]=+L:v.constructor===Object&&(x[k]=L.toString()),v=v[L]}C<d.length-1&&(h=t.defaultType.apply(h,[E]))}}}}})(n2);var Mu=XT,sN=n2,lN=pr;function pr(n,t){Mu.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._emitter=this.connection._docPresenceEmitter,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()}pr.prototype=Object.create(Mu.prototype),pr.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},pr.prototype.destroy=function(n){this._emitter.removeEventListener(this._doc,"op",this._opHandler),this._emitter.removeEventListener(this._doc,"create",this._createDelHandler),this._emitter.removeEventListener(this._doc,"del",this._createDelHandler),this._emitter.removeEventListener(this._doc,"load",this._loadHandler),Mu.prototype.destroy.call(this,n)},pr.prototype._registerWithDoc=function(){this._emitter.addEventListener(this._doc,"op",this._opHandler),this._emitter.addEventListener(this._doc,"create",this._createDelHandler),this._emitter.addEventListener(this._doc,"del",this._createDelHandler),this._emitter.addEventListener(this._doc,"load",this._loadHandler)},pr.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))}})}},pr.prototype._handleOp=function(n,t,e){var r=e===this.src;this._transformAgainstOp(n,r),this._cacheOp(n,r),this._setPendingPresence()},Mu.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Mu.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},pr.prototype._transformAgainstOp=function(n,t){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,t)}catch(e){return this.presence.emit("error",e)}this.presence._updateRemotePresence(this)}},pr.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],t=n.op,e=n.isOwnOp;t===null?(this._pending.p=null,this._pending.v++):sN.transformPresence(this._pending,t,e)}var r=this._pending.v>=this._doc.version;return r&&this._stopCachingOps(),r},pr.prototype._startCachingOps=function(){this._opCache=[]},pr.prototype._stopCachingOps=function(){this._opCache=null},pr.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var r2=ZT,aN=oN,cN=lN;function Da(n,t,e){var r=Da.channel(t,e);r2.call(this,n,r),this.collection=t,this.id=e}var uN=Da;Da.prototype=Object.create(r2.prototype),Da.channel=function(n,t){return n+"."+t},Da.prototype._createLocalPresence=function(n){return new aN(this,n)},Da.prototype._createRemotePresence=function(n){return new cN(this,n)};var fN=dN;function dN(n,t,e,r,i){this.id=n,this.v=t,this.type=e,this.data=r,this.m=i}var hN=fN,i2=Yo,o2=Uu;function Uu(n,t,e,r,i){if(i2.EventEmitter.call(this),typeof i!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=r,this.collection=e,this.callback=i,this.sent=!1}i2.mixin(Uu),Uu.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Uu.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Uu.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,r=new hN(this.id,t.v,t.type,t.data,e);this.callback(null,r)};var s2=o2,mN=gr,gN=Jo.ACTIONS,pN=Vp;function Vp(n,t,e,r,i,o){if(s2.call(this,n,t,e,r,o),!mN.isValidVersion(i))throw new Error("Snapshot version must be a positive integer or null");this.version=i}Vp.prototype=Object.create(s2.prototype),Vp.prototype._message=function(){return{a:gN.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var l2=o2,CN=gr,EN=Jo.ACTIONS,AN=$p;function $p(n,t,e,r,i,o){if(l2.call(this,n,t,e,r,o),!CN.isValidTimestamp(i))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=i}$p.prototype=Object.create(l2.prototype),$p.prototype._message=function(){return{a:EN.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var Ci=gr,xN=Rg.default.EventEmitter,bN=["create","del","destroy","load","op"],vN=Ou;function Ou(){this._docs={},this._forwarders={},this._emitters={}}Ou.prototype.addEventListener=function(n,t,e){this._registerDoc(n);var r=Ci.dig(this._emitters,n.collection,n.id);r.on(t,e)},Ou.prototype.removeEventListener=function(n,t,e){var r=Ci.dig(this._emitters,n.collection,n.id);!r||(r.off(t,e),r._eventsCount===1&&this._unregisterDoc(n))},Ou.prototype._registerDoc=function(n){var t=!0;if(Ci.digOrCreate(this._docs,n.collection,n.id,function(){return t=!1,n}),!t){var e=Ci.digOrCreate(this._emitters,n.collection,n.id,function(){var i=new xN;return i.setMaxListeners(1e3),i}),r=this;bN.forEach(function(i){var o=Ci.digOrCreate(r._forwarders,n.collection,n.id,i,function(){return e.emit.bind(e,i)});n.on(i,o)}),this.addEventListener(n,"destroy",this._unregisterDoc.bind(this,n))}},Ou.prototype._unregisterDoc=function(n){var t=Ci.dig(this._forwarders,n.collection,n.id);for(var e in t)n.off(e,t[e]);var r=Ci.dig(this._emitters,n.collection,n.id);r.removeAllListeners(),Ci.digAndRemove(this._forwarders,n.collection,n.id),Ci.digAndRemove(this._emitters,n.collection,n.id),Ci.digAndRemove(this._docs,n.collection,n.id)};var BN=GO,TN=QO,yN=ZT,a2=uN,kN=pN,RN=AN,c2=Yo,_a=Vh,se=Jo.ACTIONS,u2=Su,$r=gr,Nu=FT,wN=vN,Pu=_a.CODES;function f2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var SN=Rt;function Rt(n){c2.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.nextSnapshotRequestId=1,this.queries={},this._presences={},this._docPresenceEmitter=new wN,this._snapshotRequests={},this.seq=1,this._presenceSeq=1,this.id=null,this.agent=null,this.debug=!1,this.state=f2(n),this.bindToSocket(n)}c2.mixin(Rt),Rt.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var t=f2(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(r){try{var i=typeof r.data=="string"?JSON.parse(r.data):r.data}catch{Nu.warn("Failed to parse message",r);return}e.debug&&Nu.info("RECV",JSON.stringify(i));var o={data:i};if(e.emit("receive",o),!!o.data)try{e.handleMessage(o.data)}catch(s){$r.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(r){e.emit("connection error",r)},n.onclose=function(r){r==="closed"||r==="Closed"?e._setState("closed",r):r==="stopped"||r==="Stopped by server"?e._setState("stopped",r):e._setState("disconnected",r)}},Rt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=d2(n.error,n),delete n.error),n.a){case se.initLegacy:return this._handleLegacyInit(n);case se.handshake:return this._handleHandshake(t,n);case se.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case se.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case se.queryUnsubscribe:return;case se.queryUpdate:var e=this.queries[n.id];if(!e)return;if(t)return e._handleError(t);n.diff&&e._handleDiff(n.diff),n.hasOwnProperty("extra")&&e._handleExtra(n.extra);return;case se.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case se.bulkSubscribe:case se.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case se.snapshotFetch:case se.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case se.fetch:var r=this.getExisting(n.c,n.d);r&&r._handleFetch(t,n.data);return;case se.subscribe:case se.unsubscribe:var r=this.getExisting(n.c,n.d);r&&r._handleSubscribe(t,n.data);return;case se.op:var r=this.getExisting(n.c,n.d);r&&r._handleOp(t,n);return;case se.presence:return this._handlePresence(t,n);case se.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case se.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case se.presenceRequest:return this._handlePresenceRequest(t,n);case se.pingPong:return this._handlePingPong(t);default:Nu.warn("Ignoring unrecognized message",n)}};function d2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}Rt.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var r in t.data){var i=t.data[r],o=this.getExisting(t.c,r);o&&(n?o[e](n):i.error?o[e](d2(i.error)):o[e](null,i))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var r=t.b[s],o=this.getExisting(t.c,r);o&&o[e](n)}else if(t.b)for(var r in t.b){var o=this.getExisting(t.c,r);o&&o[e](n)}else Nu.error("Invalid bulk message",t)},Rt.prototype._reset=function(){this.agent=null},Rt.prototype._setState=function(n,t){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var e=new _a(Pu.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var r in this.queries){var i=this.queries[r];i._onConnectionStateChanged()}for(var o in this.collections){var s=this.collections[o];for(var r in s)s[r]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var r in this._snapshotRequests){var c=this._snapshotRequests[r];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},Rt.prototype.startBulk=function(){this.bulk||(this.bulk={})},Rt.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var t=this.bulk[n];this._sendBulk("f",n,t.f),this._sendBulk("s",n,t.s),this._sendBulk("u",n,t.u)}this.bulk=null},Rt.prototype._sendBulk=function(n,t,e){if(!!e){var r=[],i={},o=0,s;for(var l in e){var c=e[l];c==null?r.push(l):(i[l]=c,s=l,o++)}if(r.length===1){var l=r[0];this.send({a:n,c:t,d:l})}else r.length&&this.send({a:"b"+n,c:t,b:r});if(o===1){var d=i[s];this.send({a:n,c:t,d:s,v:d})}else o&&this.send({a:"b"+n,c:t,b:i})}},Rt.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var r=this.bulk[t.collection]||(this.bulk[t.collection]={}),i=r[n]||(r[n]={}),o=i.hasOwnProperty(t.id);return i[t.id]=e,o}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},Rt.prototype.sendFetch=function(n){return this._sendActions(se.fetch,n,n.version)},Rt.prototype.sendSubscribe=function(n){return this._sendActions(se.subscribe,n,n.version)},Rt.prototype.sendUnsubscribe=function(n){return this._sendActions(se.unsubscribe,n)},Rt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:se.op,c:n.collection,d:n.id,v:n.version,src:t.src,seq:t.seq,x:{}};"op"in t&&(e.op=t.op),t.create&&(e.create=t.create),t.del&&(e.del=t.del),n.submitSource&&(e.x.source=t.source),this.send(e)},Rt.prototype.send=function(n){this.debug&&Nu.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Rt.prototype.ping=function(){if(!this.canSend)throw new _a(Pu.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:se.pingPong};this.send(n)},Rt.prototype.close=function(){this.socket.close()},Rt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},Rt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),r=e[t];return r||(r=e[t]=new BN(this,n,t),this.emit("doc",r)),r._wantsDestroy=!1,r},Rt.prototype._destroyDoc=function(n){!n._wantsDestroy||($r.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Rt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},Rt.prototype._createQuery=function(n,t,e,r,i){var o=this.nextQueryId++,s=new TN(n,this,o,t,e,r,i);return this.queries[o]=s,s.send(),s},Rt.prototype._destroyQuery=function(n){delete this.queries[n.id]},Rt.prototype.createFetchQuery=function(n,t,e,r){return this._createQuery(se.queryFetch,n,t,e,r)},Rt.prototype.createSubscribeQuery=function(n,t,e,r){return this._createQuery(se.querySubscribe,n,t,e,r)},Rt.prototype.hasPending=function(){return!!(this._firstDoc(Gh)||this._firstQuery(Gh)||this._firstSnapshotRequest())};function Gh(n){return n.hasPending()}Rt.prototype.hasWritePending=function(){return!!this._firstDoc(LN)};function LN(n){return n.hasWritePending()}Rt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Gh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Gh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var r=this._firstSnapshotRequest();if(r){r.once("ready",this._nothingPendingRetry(n));return}$r.nextTick(n)},Rt.prototype._nothingPendingRetry=function(n){var t=this;return function(){$r.nextTick(function(){t.whenNothingPending(n)})}},Rt.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var r in e){var i=e[r];if(n(i))return i}}},Rt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},Rt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Rt.prototype.fetchSnapshot=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new kN(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},Rt.prototype.fetchSnapshotByTimestamp=function(n,t,e,r){typeof e=="function"&&(r=e,e=null);var i=this.nextSnapshotRequestId++,o=new RN(this,i,n,t,e,r);this._snapshotRequests[o.requestId]=o,o.send()},Rt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},Rt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Rt.prototype._initializeHandshake=function(){this.send({a:se.handshake,id:this.id})},Rt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},Rt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Rt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new _a(Pu.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(u2.map[n.type]!==u2.defaultType)return this.emit("error",new _a(Pu.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new _a(Pu.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Rt.prototype.getPresence=function(n){var t=this,e=$r.digOrCreate(this._presences,n,function(){return new yN(t,n)});return e._wantsDestroy=!1,e},Rt.prototype.getDocPresence=function(n,t){var e=a2.channel(n,t),r=this,i=$r.digOrCreate(this._presences,e,function(){return new a2(r,n,t)});return i._wantsDestroy=!1,i},Rt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var r={a:n,ch:e.channel,seq:t};return this.send(r),r.seq},Rt.prototype._addPresence=function(n){$r.digOrCreate(this._presences,n.channel,function(){return n})},Rt.prototype._handlePresenceSubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},Rt.prototype._handlePresenceUnsubscribe=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},Rt.prototype._handlePresence=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},Rt.prototype._handlePresenceRequest=function(n,t){var e=$r.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var h2=SN,IN=Su;const Fu={err:1001,msg:"user auth error",name:"AuthError"},Wh={err:1002,msg:"you don't have required permission",name:"PermissionError"},Hp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Ku={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},DN={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},_N={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},ol="x-live-editor-token",Ma="x-live-editor-base-url",mn=I("auth-connection");function MN(n){try{n()}catch(t){mn.error(t)}}class UN{constructor(t,e){m(this,"enabled",!0);m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new Sb.EventEmitter);m(this,"token",null);m(this,"resourceToken",null);m(this,"pingOptions",{interval:5e4,timeout:15e4});m(this,"reAuth",async()=>{if(this.connection&&this.reauthFunc){const t=await this.reauthFunc();await this.auth(t);const e=this.pingOptions;this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t,options:{ping:e}})}}});this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return li(this.getBaseURL())}async auth(t){p(mn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,r=await window.fetch(e,{method:"GET",headers:{[ol]:t.token,[Ma]:this.getBase64BaseURL()},credentials:"include"});return r.status,this.enabled?(this.token=t.token,await r.json()):{read:"",user:""}}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[Ma]:li(this.getBaseURL())}})}async init(t){const e=await this.auth(t);if(!this.enabled)return;this.resourceToken=e.read,this.ws=new o9.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(h2.prototype),p(mn,this.connection,"no this.connection");const r=this.ws,i=this.pingOptions;this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t,options:{ping:i}}),this._ping==null&&(this._ping=window.setInterval(()=>{var d;const c=Date.now();c-((d=this.lastReceiveTime)!=null?d:0)>i.interval&&this.send({a:"ping",id:this.id,ts:c}),this.lastReceiveTime&&c-this.lastReceiveTime>i.timeout&&r&&r.readyState===r.OPEN&&(r.reconnect(),this.lastReceiveTime=Date.now())},1e3))};const o=this.connection.handleMessage.bind(this.connection);let s=!1;this.connection.handleMessage=l=>{var d;const c=l;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in c||c.a==="pong")s=!1,this.handleMessage(c);else{Object.prototype.hasOwnProperty.call(c,"a")&&c.a==="hs"&&this.retryCount>=5&&(s?(mn.info("retrying re-auth success"),s=!1,this.emitAuthRecover()):s=!0),Object.prototype.hasOwnProperty.call(c,"a")&&c.a!=="init"&&c.a!=="hs"&&(this.retryCount=0);try{o(c)}catch(h){if((h==null?void 0:h.type)==="writeConflict"){this.emitWriteConflictError(h,c);return}if((d=h==null?void 0:h.message)!=null&&d.startsWith("Cannot invert subtype")){this.emitWriteConflictError(h,c);return}throw h}}},h2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc){this.retryCount>=5&&(mn.warn("retry auth times exceed 5, broadcast auth error"),this.emitAuthError()),this.retryCount+=1,mn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();if(await this.auth(t),!this.enabled){this.retryCount=10,setTimeout(()=>this.handleAuthError(),0);return}const e=this.pingOptions;this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t,options:{ping:e}})}}}catch(t){mn.error(t),setTimeout(()=>this.handleAuthError(),0)}}}emitPermissionError(){const t=new Error(Wh.msg);t.code=Wh.err,this.events.emit("error",t)}emitAuthRecover(){this.events.emit("authRecover")}emitAuthError(){const t=new Error(Fu.msg);t.code=Fu.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Ku.msg);t.code=Ku.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const r=e.err;if(r===Fu.err)mn.warn("auth error"),this.handleAuthError();else if(r===Hp.err)mn.warn(Hp.msg),this.emitMaxUsersError();else if(r===Ku.err){mn.warn(Ku.msg);try{this.emitRequestReloadError()}catch(i){mn.error(`error occurred while process reload error: ${JSON.stringify(i)}`)}finally{this.end(!1)}}else r===Wh.err?this.emitPermissionError():(mn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError())}get(t,e){return p(mn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(p(mn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onAuthError(t){this.events.addListener("error",t)}onAuthRecover(t){this.events.addListener("authRecover",t)}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){p(mn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){p(mn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e,r;this.enabled=!1,this.reauthFunc=void 0,this.events.removeAllListeners(),MN(()=>{var i;return(i=this.connection)==null?void 0:i.close()}),(e=this.connection)!=null&&e._ping&&window.clearInterval(this.connection._ping),this.connection=void 0,(r=this.ws)==null||r.close(),this.ws=void 0,t&&this.logout()}}I("utils/file");function ON(){function n(){return new Promise(t=>{const e=new FileReader;e.onload=()=>{t(e.result)},e.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}ON();async function NN(n){const e=n.size,r=Math.floor((e+102400-1)/102400),i=new s9.Hash;for(let s=0;s<r;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const h=await n.slice(l,c,n.type).arrayBuffer();i.update(new Uint8Array(h))}const o=i.digest();return li(o)}const Ei=I("sharedb-doc/client"),PN=Lb.default.create();class FN{constructor(t,e,r){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",tt());m(this,"getDoc",async()=>{const t=r=>new Promise((i,o)=>{r.fetch(s=>{s?o(s):i()})});p(Ei,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),Ei.debug(e),e});this.auth=t;const i=`${e}/${this.auth.appId}/${this.auth.docId}`;IN.register(Id.type),this.connection=new UN(i,r),this.reauthFunc=r}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(Ei,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,r=>{(t==="error"||this.doc)&&e(r)})}onAuthError(t){this.connection.onAuthError(t)}onAuthRecover(t){this.connection.onAuthRecover(t)}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,r,i,o){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...o},data:{name:r,size:i}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const r=`${this.apiServer()}/resources`;try{const i=`${r}/hash`,o=await this.request(i,{method:"post",headers:{[ol]:this.connection.token},data:{resources:t}});return o.data&&Array.isArray(o.data)?o.data:[]}catch{return[]}}async uploadFile(t,e,r,i,o){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=x=>{Ei.info(`on progress: ${x.loaded}`);let v=x.loaded*100/s;v>100&&(v=100),i(v)},c=await NN(e),d=await this.getFileUrlByHash(t,c,e.name,e.size,r);if(d)return i(-1),d;let h=t;o!=null&&o.thumbnail&&(h+="/thumbnail");const C=new FormData;C.append("file-size",`${e.size}`),C.append("file-hash",c),C.append("file",e,e.name);const E=await this.request(h,{method:"post",data:C,withCredentials:!0,headers:{...r},onUploadProgress:l});return Ei.info(E),i(100),Array.isArray(E.data)?E.data[0]:E.data}async uploadResource(t,e=()=>{},r){const o=`${this.apiServer()}/resources`;p(Ei,this.connection.token,"no connection token");const s=await this.uploadFile(o,t,{[ol]:this.connection.token},e,r);return p(Ei,s,"no result"),s}async request(t,e){var o,s;let r=this.connection.token,i;for(let l=0;l<2;l++){const c=e||{};c.url=t,c.headers||(c.headers={}),p(Ei,r,"no token"),c.headers={...c.headers,[ol]:r,[Ma]:this.connection.getBase64BaseURL()};try{return await PN(t,c)}catch(d){if(i=d,((o=d==null?void 0:d.response)==null?void 0:o.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;r=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw p(Ei,i,"no error"),i}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=Ib.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(Ei,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const r=`${this.apiServer()}/resources/external/${li(t)}`;return(await this.request(r)).data}getResourceId(t){const e=/\/resources\/([^?]+)/,r=t.match(e);return r&&r.length>=2?r[1]:""}buildResourceUrl(t,e){var s,l;if(!t)return"";if(t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;const r=this.apiServer();if(t.startsWith("http:")||t.startsWith("https:")){const c=r.replace(/\/[^/]*$/,"");if(c&&t.includes(c)){const d=this.auth.docId,h=`${c}/`,C="/resources",E=t.indexOf(h),x=t.indexOf(C,E+h.length);if(E!==-1&&x!==-1){const v=t.substring(E+h.length,x);if(v!==d){let k=t.replace(v,d);const L=new URL(k),M="token";(s=L.searchParams)==null||s.delete(M),k=L.toString();const U=this.getResourceId(k);return e!=null&&e.syncNewResources&&((l=e==null?void 0:e.syncNewResources)==null||l.call(e,U,k)),k}return t}return t}return t}let i=`${r}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken&&o.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const c=o.join("&");i+=`?${c}`}return i}reAuth(){this.connection.reAuth()}}function KN(){return{blocks:[{id:tt(),type:"text",text:[]}],comments:{},meta:{}}}const jp=I("block-ids");class VN{constructor(){m(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((i,o)=>o-i);for(let i=0;i<e.length;i++){const o=e[i];if(o>=t){const s=this.ids.get(o);p(jp,s!==void 0,"old id is not exists"),this.ids.delete(o),this.ids.set(o+1,s)}}const r=tt();this.ids.set(t,r)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((r,i)=>r-i);for(let r=0;r<e.length;r++){const i=e[r];if(i>t){const o=this.ids.get(i);p(jp,o!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i-1,o)}}}getId(t){let e=this.ids.get(t);return e||(e=tt(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class $N{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new VN,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let r=0;r<e.length;r++){const i=e[r],o=i[1].getById(t);if(o)return{containerId:i[0],blockIndex:o[0]}}return p(jp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class m2{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,r)=>{t[r]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const zp=I("op-parse-handler");class HN{constructor(t,e){m(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const r={...t,containerId:(i=>i==="blocks"?"root":i)(t.containerId)};this.actions.push(r)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,r){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:r})}onDeleteBlockData(t,e,r){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:r})}onInsertBlockData(t,e,r,i){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:r,value:i})}onUpdateBlockText(t,e,r){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:r})}onDeleteContainer(t){this.pushActions({type:"deleteContainer",containerId:t})}onCreateContainer(t,e){this.pushActions({type:"createContainer",containerId:t,data:e})}onDeleteComment(t){this.pushActions({type:"deleteComment",commentId:t})}onCreateComment(t){this.pushActions({type:"createComment",commentId:t})}onUpdateComment(t){this.pushActions({type:"updateComment",commentId:t})}end(){const t=this.actions,e=new Set,r=new Map,i=new $N,o=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of o)if(s.type==="deleteBlock"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);i.onDeleteBlock(l.containerId,l.blockIndex);const d=r.get(c);d&&(zp.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),r.delete(c));const h=`${l.containerId}-${l.blockIndex}`;e.add(h),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,c=`${l.containerId}-${l.blockIndex}`;if(e.has(c)){zp.warn("delete block data after delete block, ignore it");continue}const d=i.getBlockId(l.containerId,l.blockIndex);let h=r.get(d);h||(h=new m2,r.set(d,h)),h.delete(l.key)}else p(zp,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,c=i.getBlockId(l.containerId,l.blockIndex);let d=r.get(c);d||(d=new m2,r.set(c,d)),d.insert(l.key,l.value)}else if(s.type==="updateBlockText"){const l=s;this.outerHandler.onUpdateBlockText(l.containerId,l.blockIndex,l.richTextData,this.local)}else if(s.type==="createComment"){const l=s;this.outerHandler.onCreateComment(l.commentId,this.local)}else if(s.type==="updateComment"){const l=s;this.outerHandler.onUpdateComment(l.commentId,this.local)}}),Array.from(r.entries()).forEach(([s,l])=>{const{containerId:c,blockIndex:d}=i.getBlockIndexById(s);this.outerHandler.onUpdateBlockData(c,d,l.toDocBlockDelta(),this.local)})}}const Ke=I("op-parser");class g2{}class Gp{constructor(t){m(this,"key");this.key=t}}function jN(n,t,e){const r=t.concat(),i=r[0];if(typeof i!="number"||(r.shift(),r.length===1))return!1;const o=r[0];if(typeof o!="object"||!o.i||Object.keys(o).length!==1)return!1;for(let l=1;l<r.length;l++){const c=r[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const h=c[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=o.i;p(Ke,s.id,"block id is required"),p(Ke,s.type,"block type is required");for(let l=1;l<r.length;l++){const c=r[l],d=c[0],h=c[1];s[d]=h.i}return e.onInsertBlock(n,i,s),!0}function Wp(n,t,e,r){if(e==="upsert"&&jN(n,t,r))return;p(Ke,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const i=t.concat(),o=i[0];i.shift();const s=[];for(;i.length>0;){const l=i[0];if(l==="text"){const c=i[1];if(p(Ke,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),p(Ke,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),i.splice(0,2),e==="upsert"){const h=c.e;r.onUpdateBlockText(n,o,h)}p(Ke,i.length===0,`invalid block ops.length !== 0, ${JSON.stringify(i)}`)}else if(Array.isArray(l)){p(Ke,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];p(Ke,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const d=l[1];if(c==="text"){if(p(Ke,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&r.onInsertBlockData(n,o,c,d.i),d.r&&e==="remove"&&r.onDeleteBlockData(n,o,c),d.et==="rich-text"&&e==="upsert"){const C=d.e;r.onUpdateBlockText(n,o,C)}}else e==="remove"&&d.r&&s.push(new Gp(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i);i.shift()}else if(typeof l=="object"){const c=l;e==="remove"&&c.r&&s.push(new g2),e==="upsert"&&c.i&&r.onInsertBlock(n,o,c.i),i.shift()}else{p(Ke,typeof l=="string","data is not string"),p(Ke,l!=="text","data !== 'text'"),p(Ke,i.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(i)}`);const c=l,d=i[1];e==="remove"&&d.r&&s.push(new Gp(c)),e==="upsert"&&d.i&&r.onInsertBlockData(n,o,c,d.i),i.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof g2?r.onDeleteBlock(n,o):l instanceof Gp?r.onDeleteBlockData(n,o,l.key):p(Ke,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function zN(n,t,e){Ke.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function GN(n,t,e){const r=n[1],i=n[2];p(Ke,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),p(Ke,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?Ke.error(`unknown comment op, ${JSON.stringify(n)}`):i.i&&i.r?t==="upsert"&&e.onUpdateComment(r):i.i?t==="upsert"&&e.onCreateComment(r):i.r?t==="remove"&&e.onDeleteComment(r):Ke.error(`unknown comment op, ${JSON.stringify(n)}`)}function qp(n,t,e){const r=n[0];if(Array.isArray(r)){r.forEach(s=>{qp(s,t,e)});return}const i=r;if(p(Ke,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){zN(n);return}if(i==="comments"){GN(n,t,e);return}const o=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Wp(o,s,t,e)}):n.slice(1).forEach(s=>{Wp(o,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(o),s.i&&t==="upsert"&&e.onCreateContainer(o,s.i)}else p(Ke,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Wp(o,n.slice(1),t,e)}function Xp(n,t,e){const r=new HN(t,e);for(let i=0;i<2;i++){const o=i===0?"remove":"upsert",s=mt.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{qp(c,o,r)}):qp(s,o,r)}r.end()}const WN=I("sharedb-comments");function Yp(n){const t=n.blocks;p(WN,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([r,i])=>{Array.isArray(i)&&(e.blocks[r]=i)}),mt.default(e)}function p2(n){const{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}=n;return{id:t,groupId:e,userId:r,displayName:i,avatarUrl:o,abstract:s,created:l,modified:c}}function Qp(n,t){const e=RO(t),{comments:r,meta:i,blocks:o,...s}=e,l={...n,blocks:o,...s},c=mt.default(l);return delete c.children,c}const le=I("sharedb-doc/doc-container"),C2="ot-json1";Id.type.registerSubtype(wO.type),Id.type.name=C2,Id.type.invert=null;class Vu extends aa{constructor(e,r,i=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new yO);m(this,"batching",0);m(this,"status","clean");m(this,"disableLogout");m(this,"destroyed",!1);m(this,"handleNothingPending",()=>{this.setStatus("clean")});m(this,"handleCreate",()=>{this.handleReload("doc created")});m(this,"handleDel",()=>{});m(this,"handleReload",e=>{this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)})});m(this,"handleReset",async e=>{const r=new Error(`reset doc: ${e}`);r.code="ResetDoc",this.callbacks.forEach(i=>{var o;return(o=i.onError)==null?void 0:o.call(i,r)}),this.destroy()});m(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});m(this,"insertObject",async(e,r,i)=>{const o=[e,r,{i}];return this.submitOp(o)});m(this,"deleteObject",async(e,r)=>{const i=[e,r,{r:!0}];return this.submitOp(i)});m(this,"replaceObject",async(e,r,i)=>{const o=[e,r,{r:!0,i}];return this.submitOp(o)});m(this,"updateObject",async(e,r,i)=>{const o=this.data()[e][r],s=[e,r];return Object.entries(i).forEach(([l,c])=>{if(!$c.default(o[l],c))if(o[l]===void 0){if(c!=null){const d={i:c};s.push([l,d])}}else if(c==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:c};s.push([l,d])}}),Object.entries(o).forEach(([l,c])=>{if((i[l]===void 0||i[l]===null)&&c!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});m(this,"broadcastMessage",async e=>{const r={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(r)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async e=>new Promise((r,i)=>{if(this.destroyed){le.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},o=>{o?(le.error(`invalid op, ${o.message}, ${JSON.stringify(e)}`),i(o),le.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):r()}),this.doc.data||(le.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));m(this,"createDoc",async e=>new Promise((r,i)=>{this.doc.create(e,C2,o=>{o?i(o):r()})}));m(this,"submitInsertChildContainers",async e=>{if(e.length===0)return Promise.resolve();const r=e.map(({containerId:i,blocks:o})=>[ro(i),{i:o}]);return this.submitOp([r])});m(this,"submitDeleteChildContainer",async e=>{const r=[ro(e),{r:!0}];return this.submitOp(r)});m(this,"submitInsertBlock",async(e,r,i)=>{const o=[ro(e),r,{i}];return this.submitOp(o)});m(this,"submitDeleteBlock",async(e,r)=>{const i=[ro(e),r,{r:!0}];return this.submitOp(i)});m(this,"submitUpdateBlockData",async(e,r,i)=>{if(i.delete.length===0&&Object.keys(i.insert).length===0)return Promise.resolve();const o=[ro(e),r],s=new Set(i.delete);Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c)){const h={r:!0,i:d};o.push([c,h])}});const l=new Set(Object.keys(i.insert));return i.delete.forEach(c=>{if(l.has(c))return;const d={r:!0};o.push([c,d])}),Object.entries(i.insert).forEach(([c,d])=>{if(s.has(c))return;const h={i:d};o.push([c,h])}),this.submitOp(o)});m(this,"submitUpdateRichText",async(e,r,i)=>{const o=[ro(e),r,"text",{e:i,et:"rich-text"}];return this.submitOp(o)});m(this,"handleOp",(e,r,i)=>{if(this.destroyed){le.warn("handleOp: destroyed");return}try{Xp(e,this,!!r)}catch(o){throw le.error(o),o}});this.client=e,this.doc=r,this.doc.preventCompose=!0,this.disableLogout=i,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,p(le,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const r=new FN(e.auth,e.serverUrl,e.reauthFunc),i=await r.getDoc(),o=new Vu(r,i,e.disableLogout);if(i.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await o.createDoc(e.templateData||KN())}return await o.initPresence(),await o.subscribe(),o.initEvents(),o}catch(r){throw le.error(r),le.error(`failed to load doc: ${JSON.stringify(r)}`),r}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(r=>{var i;return(i=r.onStatusChanged)==null?void 0:i.call(r,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onAuthError(e=>{this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,e)})}),this.client.onAuthRecover(()=>{this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((e,r)=>{if(this.localPresence)e();else{const i=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);i.on("receive",(o,s)=>{this.onCustomMessage(s)}),i.subscribe(o=>{o?r(o):(this.localPresence=i.create(tt()),e())})}})}subscribe(){return new Promise((e,r)=>{this.doc.subscribe(i=>{i?r(i):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return no(this.data())}getContainerBlocks(e){const r=this.data();p(le,r,"no doc data");const i=r[ro(e)];return p(le,i,`no container data: ${e}`),mt.default(i)}findContainerBlocks(e){const r=this.data();p(le,r,"no doc data");const i=r[ro(e)];return i!=null?i:null}getBlockData(e,r){const i=this.data();p(le,i,"no doc data");const o=i[ro(e)];p(le,o,`no container data: ${e}`);const s=o[r];return p(le,s,`no block data: ${r}`),mt.default(s)}localInsertBlock(e,r,i){return this.submitInsertBlock(e,r,i),this.getBlockData(e,r)}localDeleteBlock(e,r){const i=this.getBlockData(e,r);return this.submitDeleteBlock(e,r),i}localUpdateBlockText(e,r,i){const o=this.getBlockData(e,r);p(le,o.text,"no block text");const s=mt.default(o.text);this.submitUpdateRichText(e,r,i);const l=hn.apply(s,i);return p(le,l,"no block text"),l}localUpdateBlockData(e,r,i){const o=mt.default(this.getBlockData(e,r));return this.submitUpdateBlockData(e,r,i),o}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(r=>{this.submitDeleteChildContainer(r)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(r=>p2(r))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const r=this.data().comments[e];return Yp(r)}localCreateComment(e,r){const i=Qp(e,r),s=["comments",i.id,{i}];return this.submitOp(s)}localDeleteComment(e){const r=["comments",e,{r:!0}];return this.submitOp(r)}localUpdateComment(e,r){const i=Qp(e,r),o=["comments",e.id,{r:!0,i}];return this.submitOp(o)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,r,i){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(o=>{var s;return(s=o.onDeleteBlock)==null?void 0:s.call(o,Ia(e),r,i)})}onInsertBlock(e,r,i,o){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Ia(e),r,i,o)})}onUpdateBlockData(e,r,i,o){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Ia(e),r,i,o)})}onUpdateBlockText(e,r,i,o){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Ia(e),r,i,o)})}onDeleteContainer(e,r){p(le,this.callbacks.length>0,"no callbacks"),p(le,e!=="root","should not delete root container in doc"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteChildContainer)==null?void 0:o.call(i,Ia(e),r)})}onCreateContainer(e,r,i){p(le,this.callbacks.length>0,"no callbacks"),p(le,e!=="root","should not create root container in doc"),this.callbacks.forEach(o=>{var s;return(s=o.onInsertChildContainer)==null?void 0:s.call(o,Ia(e),r,i)})}onDeleteComment(e,r){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onDeleteComment)==null?void 0:o.call(i,e,r)})}onCreateComment(e,r){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onCreateComment)==null?void 0:o.call(i,e,r)})}onUpdateComment(e,r){p(le,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var o;return(o=i.onUpdateComment)==null?void 0:o.call(i,e,r)})}onCustomMessage(e){const r=e;(r==null?void 0:r.type)==="custom"&&(r==null?void 0:r.clientId)!==this.client.clientId?this.callbacks.forEach(i=>{var o;return(o=i.onCustomMessage)==null?void 0:o.call(i,r.data)}):(r==null?void 0:r.type)==="onlineUsers"&&setTimeout(()=>{const i={type:"custom",data:e,clientId:"-"};this.onCustomMessage(i)})}onAuthRecover(){this.callbacks.forEach(e=>{var r;return(r=e.onAuthRecover)==null?void 0:r.call(e)})}async addResources(e){let r=[];return e.forEach(o=>{const s=o.split("|");r.push(...s)}),r=Array.from(new Set(r)),await this.client.getFileUrlsByHashes(r)}async uploadResource(e,r){var o;return{resourceId:await this.client.uploadResource(e,(o=r==null?void 0:r.onProgress)!=null?o:()=>{})}}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}request(e,r){return this.client.request(e,r)}getUser(){const e=this.client.clientId,{permission:r,userId:i,displayName:o,avatarUrl:s}=this.client.auth;return{permission:r,clientId:e,userId:i,displayName:o,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return no(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return no(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:no(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:no(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,r){Xp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}triggerReAuth(){this.client.reAuth()}}I("remote-cursor");class E2{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Me.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));m(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const r=this.editor.findBlockById(e);r&&this.editor.reloadBlock(r)})});this.editor=t,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const A2=I("remote-cursor-decorator");class Jp{decorateText(t,e,r){const i=t.doc.getRemoteUsers();if(!i)return{};const o=new Map,{containerId:s,blockIndex:l}=e[e.length-1];p(A2,typeof s=="string","invalid path containerId"),p(A2,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),d=dn(r);return i.getSimpleCursors(c.id).forEach((C,E)=>{E>d&&(E=d);const x=C.map(k=>({id:tt(),type:"remote-cursor",name:k.user.displayName,time:k.time,rainbowIndex:k.user.rainbowIndex})),v=o.get(E);v?v.push(...x):o.set(E,x)}),{insertions:o}}}const Zp=I("sharedb-doc/share-db-server"),qN=Lb.default.create();class XN{constructor(t,e){m(this,"auth");m(this,"clientId",tt());this.serverUrl=e,this.auth=t}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return p(Zp,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}apiServer(){const t=`${this.serverUrl}/${this.auth.appId}/${this.auth.docId}`;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}getBaseURL(){const t=new URL(this.apiServer());return`${t.protocol}//${t.host}${t.pathname}`}getBase64BaseURL(){return li(this.getBaseURL())}async request(t,e){var o;const r=this.auth.token,i=e||{};i.url=t,i.headers||(i.headers={}),p(Zp,r,"no token"),i.headers={...i.headers,[ol]:r,[Ma]:this.getBase64BaseURL()};try{return await qN(t,i)}catch(s){throw(o=s.response)!=null&&o.data&&(s.responseData=s.response.data),s}}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,i=(await this.request(e)).data.versions;return i.forEach(o=>{o.extra&&(o.extra=JSON.parse(o.extra))}),i}async getVersion(t){const r=`${this.apiServer()}/versions/${t}`,i=await this.request(r);return JSON.parse(i.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,r=await this.request(e);return JSON.parse(r.data.data)}async getVersionOps(t,e){let i=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(i+=`&from=${e}`);const o=await this.request(i),s=o.data.ops,l=Ib.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let d;return c?(p(Zp,c.create,"no createDoc.create"),d=c.create.data):d=JSON.parse(o.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:o.data.ops}}async updateVersionExtra(t,e,r){const o=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(o,{method:"post",data:{extra:JSON.stringify(r)}})}async revertVersion(t){const r=`${this.apiServer()}/versions/revert/${t}`;await this.request(r,{method:"post",data:{}})}async createVersion(t,e){const i=`${this.apiServer()}/versions`;return(await this.request(i,{method:"post",data:{publish:e,tag:t}})).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let i=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const o=[];if(e!=null&&e.withToken,e!=null&&e.downloadFileName&&o.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),o.length>0){const s=o.join("&");i+=`?${s}`}return i}}const YN=I("sharedb-doc/share-db-server");function x2(n){const t=new URL(n);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}function QN(n){return li(x2(n))}class qh extends aa{constructor(e){super();m(this,"remoteUsers",new wu);m(this,"client");this.options=e,this.client=new XN(e.auth,e.serverUrl)}destroy(){}buildResourceUrl(e,r){return this.client.buildResourceUrl(e,r)}getRemoteUsers(){return this.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const r=await this.client.getVersion(e);return no(r)}async getLatestVersion(){const e=await this.client.getLatestVersion();return no(e)}async getHistoryData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r),s=o.map(l=>({user:l.meta.createdBy,data:l}));return{doc:no(i),historyData:s}}async getVersionData(e,r){const{doc:i,ops:o}=await this.client.getVersionOps(e,r);return{doc:no(i),versionData:o}}async updateVersionExtra(e,r,i){await this.client.updateVersionExtra(e,r,i)}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,r){return this.client.createVersion(e,r)}parseHistoryData(e,r){Xp(e.data.op,r,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}static async auth(e,r){p(YN,e.token,"no auth token");const i=`${x2(r)}/auth`,o=await window.fetch(i,{method:"GET",headers:{[ol]:e.token,[Ma]:QN(r)},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return await o.json()}static async load(e){const r=`${e.serverUrl}/${e.auth.appId}/${e.auth.docId}`;return await this.auth(e.auth,r),new qh(e)}}class b2 extends Be.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,r){if(Qt(Lr(this.editor,t)))return;const i=this.editor.getBlockByIndex(t,e),o=J(this.editor.getContainerById(t));o&&this.emit("change",this.editor,{containerId:t,blockIndex:e},o,i,r)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}onInsertBlock(t,e){Qt(Lr(this.editor,t))||this.emit("insert",this.editor,{containerId:t,blockIndex:e})}onDeleteBlock(t,e){this.handleChild(t,e,"remove")}destroy(){this.editor.doc.unregisterCallback(this)}}function v2(n,t){const e=n.addCustom("child-block-tracker",()=>new b2(n));e.addListener("change",t),e.addListener("insert",t)}function B2(n,t){const e=n.addCustom("child-block-tracker",()=>new b2(n));e.removeListener("change",t),e.removeListener("insert",t)}const uct="",JN={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",name:"\u6587\u672C\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},ZN={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},tP={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};D.mergeLang({"zh-CN":JN,"en-US":ZN,"ja-JP":tP});const fct="";I("button");function Cr(n,t,e,r,i){const o=B("button",["editor-button"],null);return o.setAttribute("data-button-id",n),i&&o.setAttribute(`data-editor-tooltip-${i}`,t),e?typeof e=="string"?e.startsWith("<")?o.innerHTML=e:o.innerText=e:o.appendChild(e):o.innerText=t,r&&(r.indexOf("checked")!==-1&&z(o,"checked"),r.indexOf("disabled")!==-1&&(o.disabled=!0),r.indexOf("primary")!==-1&&z(o,"primary")),o}const dct="",Xh=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
32
32
  <path d="M8.00874 7.89952L12.9497 2.94975M8.00874 7.89952L12.9497 12.8492M8.00874 7.89952L3.05025 12.8492M8.00874 7.89952L3.05025 2.94975" stroke="currentColor" stroke-linejoin="round"/>
33
33
  </svg>
34
34
  `,T2=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
@@ -948,4 +948,4 @@ ${o.mermaidText}
948
948
  ${o.flowchartText}
949
949
  \`\`\`\`\`\``}return""}const ctt={embedType:"flowchart",convertFrom:stt,handleUpdateBlock:ott,createEmbedContent:itt,getBlockProperties:ltt,convertTo:att},utt=I("plantuml-helper");function _S(n,t){var l;let r=((l=(n.getComponentOptions("plantuml")||{}).cdn)==null?void 0:l.plantuml)||VZ;r.endsWith("/")||(r+="/");const i=d9.default.encode(t);p(utt,i,i),r+=i;const s=new URLSearchParams(document.location.search).get("doc");return Vg(r,{id:`${s}-${tt()}`})}async function ftt(n,t){try{const e=await yA(n,t);return(await n.doc.uploadResource(e)).resourceId}catch{return Promise.resolve(t)}}class hc extends LA{constructor(t){super(t,"plantuml","plantumlText")}static get(t,e){return t.addCustom(`plantuml-${e.id}`,()=>new hc(t))}code2ObjectUrl(t){return Promise.resolve(_S(this.editor,t))}code2ResourceId(t){const e=_S(this.editor,t);return ftt(this.editor,e)}destroy(){}}function dtt(n,t,e){hc.get(n,e).createEmbedContent(t,e)}function htt(n,t,e){const r=hc.get(n,e),i=Ot(t);return r.updateEmbedContent(i,e),!0}function mtt(n,t,e){const{data:r}=e,i=n.getBlockString(t).trim();if(!r||r.embedType!=="plantuml"||i!=="```plantuml"||!nt(n,t))return null;const o={src:"",plantumlText:""};return{blockData:{id:tt(),type:"embed",embedType:"plantuml",embedData:o},onConverted:(c,d)=>{hc.get(c,c.getBlockData(d)).editGraph(Ot(d))}}}function gtt(n,t){return hc.get(n,n.getBlockData(t)).getBlockProperties(t)}function ptt(n,t,e,r){const{embedData:i}=t,o=i;if(r==="html")return o.src?`<img src="${n.doc.buildResourceUrl(o.src,{withToken:!0})}" />`:o.flowchartText?`<div>${o.flowchartText}</div>`:"<p>[plantuml]</p>";if(r==="markdown"){if(o.src)return`![plantuml](${n.doc.buildResourceUrl(o.src,{withToken:!0})})`;if(o.flowchartText)return`\`\`\`plantuml\`\`\`
950
950
  ${o.flowchartText}
951
- \`\`\`\`\`\``}return""}const Ctt={embedType:"plantuml",convertFrom:mtt,handleUpdateBlock:htt,createEmbedContent:dtt,getBlockProperties:gtt,convertTo:ptt},Eut="",Ett="hr",Att={dividingLine:{type:"\u5206\u5272\u7EBF",abstract:"\u5206\u5272\u7EBF"}},xtt={dividingLine:{type:"Dividing-Line",abstract:"Dividing-Line"}},btt={dividingLine:{type:"\u533A\u5207\u308A\u7DDA",abstract:"\u533A\u5207\u308A\u7DDA"}};D.mergeLang({"zh-CN":Att,"en-US":xtt,"ja-JP":btt});function vtt(n,t){const e=B("div",["editor-embed-container"],t);B("hr",["editor-embed-hr"],e)}function Btt(n,t,e,r){return r==="html"?"<hr />":r==="markdown"?"---":"------------"}function Ttt(){return{name:"hr",insertEmbedCommandItems:[{id:"insert-hr",name:D.t("dividingLine.type"),icon:J2,order:500,group:"common",subText:yn("insert-hr")}],handleInsertEmptyEmbed:async(n,t)=>{const{containerId:e,blockIndex:r}=t;return n.insertEmbed(e,r,Ett,{})}}}function ytt(n,t,e){const{data:r}=e;if(!r||r.embedType!=="dividing-line"||!nt(n,t))return null;const i={};return{blockData:{id:tt(),type:"embed",embedType:"hr",embedData:i}}}function ktt(){return{abstract:D.t("dividingLine.abstract")}}const Rtt={embedType:"hr",createEmbedContent:vtt,convertTo:Btt,getOptions:Ttt,convertFrom:ytt,getBlockProperties:ktt},Aut="",xut="",wtt={media:{upload:{failed:'<div class="line-1">{name}\u4E0A\u4F20\u5931\u8D25</div><div class="line-2">\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5 <span class="retry-upload">\u91CD\u8BD5</span></div>',maxSizeFailed:'<div class="line-1">{name}\u4E0A\u4F20\u5931\u8D25</div><div class="line-2">\u6587\u4EF6\u5927\u5C0F\u8D85\u8FC7\u9650\u5236\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u6587\u4EF6</div>'},load:{failed:'<div class="line-1">{name}\u52A0\u8F7D\u5931\u8D25</div><div class="line-2">\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5 <span class="retry-upload">\u91CD\u8BD5</span></div>'},audio:{menuItem:"\u97F3\u9891",abstract:"\u97F3\u9891"},video:{menuItem:"\u89C6\u9891",abstract:"\u89C6\u9891"}}},Stt={media:{upload:{failed:'<div class="line-1">{name} upload failed</div><div class="line-2">Network error, you can <span class="retry-upload">Retry</span></div>',maxSizeFailed:'<div class="line-1">{name} upload failed</div><div class="line-2">The file size exceeds limit. Please choose another file.</div>'},load:{failed:'<div class="line-1">{name} loading failed</div><div class="line-2">Network error, you can <span class="retry-upload">Retry</span></div>'},audio:{menuItem:"Audio",abstract:"Audio"},video:{menuItem:"Video",abstract:"Video"}}},Ltt={media:{upload:{failed:'<div class="line-1">{name}\u306E\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u306B\u5931\u6557\u3057\u307E\u3057\u305F</div><div class="line-2">\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 <span class="retry-upload">\u518D\u8A66\u884C</span></div>',maxSizeFailed:'<div class="line-1">{name}\u306E\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u306B\u5931\u6557\u3057\u307E\u3057\u305F</div><div class="line-2">\u30D5\u30A1\u30A4\u30EB\u306E\u30B5\u30A4\u30BA\u304C\u4E0A\u9650\u3092\u8D85\u3048\u3066\u3044\u308B\u305F\u3081\u3001\u4ED6\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044</div>'},load:{failed:'<div class="line-1">{name}\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 <span class="retry-upload">\u518D\u8A66\u884C</span></div>'},audio:{menuItem:"\u97F3\u58F0",abstract:"\u97F3\u58F0"},video:{menuItem:"\u52D5\u753B",abstract:"\u52D5\u753B"}}};D.mergeLang({"zh-CN":wtt,"en-US":Stt,"ja-JP":Ltt});var Xr=(n=>(n.AUDIO="audio",n.VIDEO="video",n))(Xr||{}),Mf=(n=>(n.Empty="empty",n.Progress="progress",n.Error="error",n))(Mf||{});const MS=10*1024*1024,Itt=["wav","mp3","aac","ogg","webm","flac"],Dtt=["ogg","mp4","webm"],_tt=()=>{};function US(n){var h,C,E,x,v,k;const t=(h=n.getComponentOptions("media"))!=null?h:{},{allowedMedias:e,maxSize:r,callbacks:i}=t,o=(C=e==null?void 0:e.audio)!=null?C:Itt,s=(E=e==null?void 0:e.video)!=null?E:Dtt,l=(x=r==null?void 0:r.audio)!=null?x:MS,c=(v=r==null?void 0:r.video)!=null?v:MS,d=(k=i==null?void 0:i.onError)!=null?k:_tt;return{allowedMedias:{audio:o,video:s},maxSize:{audio:l,video:c},callbacks:{onError:d}}}function Mtt(n,t){const e=o=>o.map(s=>`.${s}`).join(","),{allowedMedias:r}=US(n),i=r[t];return i?e(i):"*"}function Utt(n,t,e){const{maxSize:r,callbacks:i,allowedMedias:o}=US(t),{[e]:s}=r,{[e]:l}=o;if(s&&n.size>s){const d=new Error("media is too large");throw d.code=`MaxMediaSize-${e}`,i!=null&&i.onError&&(i==null||i.onError(t,d)),d}const c=Yc(n.name);if(l&&!l.includes(c.toLowerCase())){const d=new Error(`media file is not allowed: ${c}`);throw d.code="NotAllowedFile",i!=null&&i.onError&&(i==null||i.onError(t,d)),d}}function Ott(n){return n===Mf.Empty||n===Mf.Error}const Je=I("media");class Ntt extends Be.TypedEmitter{constructor(e){super();m(this,"mediaContainer",null);m(this,"media",null);m(this,"abstract",null);m(this,"handleMediaLoadError",(e,r)=>{if(!r.target||!(r.target instanceof Node)||!(r.target instanceof Element?r.target:r.target.parentElement))return;const o=J(r.target);if(!o||!o.contains(this.mediaContainer))return;const s=this.renderError();this.updateMediaContent(s),this.emit("mediaError",e,"load_error",lt(o))});m(this,"handleUploadFile",async e=>{p(Je,this.abstract,"no abstract"),p(Je,this.mediaContainer,"The media element not exist");const{editor:r}=this.options,i=J(this.mediaContainer);p(Je,i,"The block element not exist");const o=r.getBlockData(i);try{const{resourceId:s}=await r.doc.uploadResource(e,{onProgress:C=>{this.renderProgress(C,e)}}),{name:l,type:c,size:d}=e,h={...o,embedData:{...o.embedData,src:s,fileName:l,fileSize:d,fileType:c}};r.updateBlockData(i,h)}catch(s){Je.error(s),this.emit("mediaError",r,"upload_error",o.id),this.renderRetry(e,s)}ot(i,"media-block-uploading")});m(this,"destroy",()=>{this.mediaContainer=null});this.options=e}bindMediaEvent(){const{editor:e}=this.options;this.media&&e.domEvents.addEventListener(this.media,"error",this.handleMediaLoadError)}unbindMediaEvent(){const{editor:e}=this.options;this.media&&e.domEvents.removeEventListener(this.media,"error",this.handleMediaLoadError)}updateMediaContent(e){p(Je,this.mediaContainer,"The media element not exist"),this.mediaContainer.innerHTML="",this.mediaContainer.append(e)}renderError(){p(Je,this.abstract,"no abstract");const{editor:e,createMediaElement:r}=this.options,{mediaIcon:i,mediaName:o}=this.abstract;p(Je,this.mediaContainer,"The media element not exist");const s=J(this.mediaContainer);p(Je,s,"The block element not exist");const l=e.getBlockData(s),c=B("div",["media-error","embed-selected-content","embed-hover-content"],null),d=B("span",["media-error-icon"],c);d.innerHTML=i;const h=B("div",[],c);h.innerHTML=D.t("media.load.failed",{name:o}),c.appendChild(h);const C=h.querySelector(".retry-upload");return p(Je,C,"The element not exist"),e.domEvents.addEventListener(C,"click",(E,x)=>{const v=B("div",["media-element"],null),k=this.getResourceUrl(l),L=r(E,v,l,k);this.unbindMediaEvent(),this.media=L,this.bindMediaEvent(),this.updateMediaContent(v)}),this.setFullScreen(),c}renderRetry(e,r){var E,x;p(Je,this.abstract,"no abstract");const{editor:i}=this.options,{mediaIcon:o,mediaName:s}=this.abstract,l=B("div",["media-error","embed-selected-content","embed-hover-content"],null),c=B("span",["media-error-icon"],l);c.innerHTML=o;const d=B("div",[],l);let h=D.t("media.upload.failed",{name:s});(((E=r.response)==null?void 0:E.status)===420||((x=r.response)==null?void 0:x.status)===413)&&(h=D.t("media.upload.maxSizeFailed",{name:s})),d.innerHTML=h,l.appendChild(d);const C=d.querySelector(".retry-upload");C&&i.domEvents.addEventListener(C,"click",()=>{i.readonly||(p(Je,this.abstract,"no abstract"),this.handleUploadFile(e))}),this.updateMediaContent(l),this.setFullScreen()}renderProgress(e,r){p(Je,this.mediaContainer,"The media element not exist");const i=this.mediaContainer.querySelector(":scope .media-progress"),o=e===-1||e===100?100:e;if(i){const{updateProgressElement:s}=this.options;s(i,o)}else{const{createProgressElement:s}=this.options,l=J(this.mediaContainer);p(Je,l,"The element not exist"),z(l,"media-block-uploading");const c=B("div",["media-progress"],null);s(c,o,r),this.updateMediaContent(c)}this.setFullScreen()}renderMediaElement(e,r){p(Je,this.mediaContainer,"The media element not exist");const i=this.mediaContainer.querySelector(":scope > .media-element"),{createMediaElement:o,updateMediaElement:s,editor:l}=this.options,c=this.getResourceUrl(e,r);if(i){const d=s(l,i,e,c);this.unbindMediaEvent(),this.media=d,this.bindMediaEvent()}else{const d=B("div",["media-element"],null),h=o(l,d,e,c);this.unbindMediaEvent(),this.media=h,this.bindMediaEvent(),this.updateMediaContent(d)}}renderEmpty(e){p(Je,this.abstract,"no abstract"),p(Je,this.mediaContainer,"The media element not exist");const r=B("div",["media-empty","embed-selected-content","embed-hover-content"],this.mediaContainer);r.innerHTML=this.abstract.mediaIcon,this.updateMediaContent(r);const{editor:i}=this.options;i.findBlockById(e.id)&&this.emit("mediaError",i,"empty",e.id),this.setFullScreen()}getResourceUrl(e,r){const{src:i}=e.embedData,{editor:o}=this.options;return o.doc.buildResourceUrl(i,{syncNewResources:async(s,l)=>{var d,h;if(!r)return;await o.doc.addResources([s]);const c=(h=(d=o.doc).getServerMeta)==null?void 0:h.call(d).appId;if(l!==e.embedData.src&&c&&e.embedData.src.includes(c)){const C=J(r);if(C&&!o.readonly&&o.isBlockWritable(C)){const E=mt.default(e);E.embedData.src=s,o.updateBlockData(C,E)}}}})}setFullScreen(){p(Je,this.mediaContainer,"The media element not exist"),z(this.mediaContainer,"full-screen")}removeFullScreen(){p(Je,this.mediaContainer,"The media element not exist"),ot(this.mediaContainer,"full-screen")}updateBlockAlign(e,r){const i=J(r);p(Je,i,"The block element not exist");const{align:o}=e;e.embedType==="video"&&(i.hasAttribute("data-style-align")&&i.removeAttribute("data-style-align"),i.setAttribute("data-style-align",o))}render(e,r){const{src:i}=e.embedData;(!this.mediaContainer||!r.contains(this.mediaContainer))&&(this.mediaContainer=B("div",["media"],r)),this.updateBlockAlign(e,r),Ott(i)?i===Mf.Empty&&this.renderEmpty(e):this.renderMediaElement(e,r)}setAbstract(e){this.abstract=e}}I("media-embed");const Ptt="left";class OS{constructor(){m(this,"handleInsertEmptyEmbed",async(t,e)=>{var C;const{containerId:r,blockIndex:i}=e;let o;(C=e.data)!=null&&C.file&&(o=e.data.file);const s=Mtt(t,this.embedType);if(o=o!=null?o:await ha(s,{}),!o)return null;const{mediaType:l}=this.getAbstract();try{Utt(o,t,l)}catch{return null}const c={id:tt(),type:"embed",embedType:this.embedType,embedData:{src:Mf.Empty}};l==="video"&&(c.align=Ptt);const d=t.insertBlock(r,i,c);return await this.getMedia(t,c.id).handleUploadFile(o),d})}getMedia(t,e){const r=t.addCustom(`media-${e}`,()=>new Ntt({editor:t,createMediaElement:this.createMediaElement,updateMediaElement:this.updateMediaElement,createProgressElement:this.createProgressElement,updateProgressElement:this.updateProgressElement}));return r.setAbstract({...this.getAbstract()}),r}getOptions(){const{menuItem:t,mediaIcon:e,mediaName:r,order:i,group:o}=this.getAbstract();return{name:r,insertEmbedCommandItems:[{id:`insert-${this.embedType}`,name:t,icon:e,order:i,group:o,subText:yn(`insert-${this.embedType}`)}],handleInsertEmptyEmbed:this.handleInsertEmptyEmbed}}createEmbedContent(t,e,r){const{id:i}=r;this.getMedia(t,i).render(r,e)}handleUpdateBlock(t,e,r){const{id:i}=r,o=this.getMedia(t,i),s=Ot(e);return o.render(r,s),!0}handleDeleteBlock(t,e){const r=e.id,i=this.getMedia(t,r);i.removeAllListeners(),i.destroy()}convertTo(t,e,r,i){const o=e.embedData,s=t.doc.buildResourceUrl(o.src,{withToken:!0});return i==="html"?`<${o.type} src="${s}" />`:i==="markdown"?`![${o.src}](${s})`:s}}function NS(n,t){const e=B("div",["uploading-progress-mask"],n),r=B("div",["uploading-progress-bar"],e),i=B("div",["uploading-progress-bar-value"],r);i.style.width=`${t}%`}function PS(n,t){const e=n.querySelector(".uploading-progress-bar-value");e&&(e.style.width=`${t}%`)}const Ftt=I("media-audio");class Ktt extends OS{constructor(){super(...arguments);m(this,"embedType",Xr.AUDIO);m(this,"updateProgressElement",PS);m(this,"createMediaElement",(e,r,i,o)=>{const s=B("div",["audio-container","embed-hover-content","embed-selected-content"],r),l=B("audio",[],s);return l.innerHTML="Your browser does not support the <code>audio</code> element.",l.controls=!0,l.src=o,setTimeout(()=>{this.getMedia(e,i.id).setFullScreen()}),l})}getAbstract(){return{mediaIcon:X2,mediaName:D.t(`media.${Xr.AUDIO}.menuItem`),menuItem:D.t(`media.${Xr.AUDIO}.menuItem`),order:800,mediaType:Xr.AUDIO,group:"common"}}getBlockProperties(){return{abstract:`${D.t(`media.${Xr.AUDIO}.abstract`)}`}}updateMediaElement(e,r,i,o){const s=r.querySelector(":scope .audio-container > audio");return p(Ftt,s,"The media element not exist"),s.src!==o&&(s.src=o),s}createProgressElement(e,r){const i=B("audio",[],e);i.innerHTML="Your browser does not support the <code>audio</code> element.",i.controls=!0,i.src="about:blank",NS(e,r)}}const Vtt=new Ktt;I("video-resizer");function FS(n){return n&&ge(n)&&We(n)==="video"}const $tt=50;class IA{constructor(t){m(this,"currentResizableElement",null);m(this,"resizing",!1);m(this,"handleHoveringBlockChange",(t,e)=>{if(!this.resizing&&!window.isDragging&&(e&&FS(e)&&this.disableBlockResize(e),t&&FS(t)&&this.editor.isBlockWritable(t))){const r=this.getVideoElement(t);if(!r)return;this.enableBlockResize(t,r)}});m(this,"handleResizing",(t,e)=>{if(this.resizing=!0,!this.currentResizableElement)return;const r=t.getBlock();if(!r)return;const i=r.getBoundingClientRect().width,o=Math.min(Math.max(e.width,$tt),i);this.currentResizableElement.style.width=`${o}px`,this.currentResizableElement.style.pointerEvents="none"});m(this,"handleResized",t=>{this.resizing=!1;const e=t.getBlock();if(!this.currentResizableElement||!e)return;const r=this.editor.getBlockData(e),{width:i}=this.currentResizableElement.getBoundingClientRect();this.currentResizableElement.style.pointerEvents="auto",this.editor.updateBlockData(e,{...r,width:i})});this.editor=t,Te.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){this.currentResizableElement=null,Te.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}getVideoElement(t){return Ot(t).querySelector(":scope .video-container > video")}updateResizer(t){const e=this.editor.findCustom(`${lt(t)}-resizer`);e&&e.updateResizer()}disableBlockResize(t){const e=this.editor.findCustom(`${lt(t)}-resizer`);e&&e.disableResize()}enableBlockResize(t,e){const r=this.editor.addCustom(`${lt(t)}-resizer`,()=>new df(this.editor,{resize:["top-left","top-right","bottom-left","bottom-right"]}));r.enableResize(t,e),r.removeListener("resizing",this.handleResizing),r.removeListener("resized",this.handleResized),r.addListener("resizing",this.handleResizing),r.addListener("resized",this.handleResized),this.currentResizableElement=e}}const Htt=I("video");class jtt extends OS{constructor(){super(...arguments);m(this,"embedType",Xr.VIDEO);m(this,"updateProgressElement",PS);m(this,"createMediaElement",(e,r,i,o)=>{const s=B("div",["video-container","embed-selected-content","drag-preview-element"],r),l=B("video",[],s);return l.innerHTML="Your browser does not support the <code>video</code> element.",l.controls=!0,l.src=o,l.addEventListener("canplay",()=>{e.addCustom("video-resizer",()=>new IA(e)),this.getMedia(e,i.id).removeListener("mediaError",this.handleMediaError),this.getMedia(e,i.id).addListener("mediaError",this.handleMediaError),this.getMedia(e,i.id).removeFullScreen()}),i.width&&(l.style.width=`${i.width}px`),l});m(this,"createProgressElement",(e,r,i)=>{const o=B("video",["progress-video"],e);o.innerHTML="Your browser does not support the <code>audio</code> element.",o.controls=!0,NS(e,r),da(i).then(s=>{const l=e.querySelector(".progress-video");l&&i1(e)&&(l.src=s)})})}getAbstract(){return{mediaName:D.t(`media.${Xr.VIDEO}.menuItem`),mediaIcon:Y2,menuItem:D.t(`media.${Xr.VIDEO}.menuItem`),order:700,mediaType:Xr.VIDEO,group:"common"}}getBlockProperties(){return{abstract:`${D.t(`media.${Xr.VIDEO}.abstract`)}`}}handleMediaError(e,r,i){const o=e.addCustom("video-resizer",()=>new IA(e)),s=e.getBlockById(i);o.disableBlockResize(s)}updateMediaElement(e,r,i,o){const s=r.querySelector(":scope .video-container > video");p(Htt,s,"The media element not exist"),s.src!==o&&(s.src=o),i.width?s.style.width=`${i.width}px`:s.style.width="";const l=e.getBlockById(i.id);return setTimeout(()=>{e.addCustom("video-resizer",()=>new IA(e)).updateResizer(l)}),s}}const ztt=new jtt,KS=[pE,BE,TE,Pk],DA=[SS,GJ,ttt,ctt,Ctt,u$,Rtt,ztt,Vtt,bW,sS,nQ],VS=[Qk,cS,K4];function Gtt(n,t,e){var i,o,s,l;oi.level=(i=e.logLevel)!=null?i:Ds.DEBUG;const r=Ru(n,t,{components:{blocks:[...KS,...((o=e==null?void 0:e.components)==null?void 0:o.blocks)||[]],embeds:[...DA,...((s=e.components)==null?void 0:s.embeds)||[]],boxes:[...VS,...((l=e.components)==null?void 0:l.boxes)||[]],textRenders:[new ZC],options:{...e.componentsOptions}}});return r.readonly=!0,r.addCustom("heading-collapse",()=>new HE(r)),r.addCustom("editor-tooltip",()=>new M0(r)),r.addListener("clickLink",(c,d,h)=>{var E;if((E=e==null?void 0:e.events)!=null&&E.onClickLink){e.events.onClickLink(c,d,h);return}const C=h.getAttribute("link");C&&(c.readonly||d.ctrlKey||d.metaKey)&&window.open(C,"_blank")}),r}class $S{constructor(t){this.createOptions=t,t.lang&&D.setLang(t.lang)}createHistoryEditor(t,e){return Gtt(t,e,this.createOptions)}}I("create-editor");function HS(n,{root:t,childDoc:e,doc:r}){var h,C;e.uploadResource=r.uploadResource.bind(r),e.buildResourceUrl=r.buildResourceUrl.bind(r);const i=n.getComponentOptions("comment"),o={image:{defaultAlign:"left"},table:{locatingContainer:t,hideCellMenu:!0,hideToolbar:!0},...i==null?void 0:i.componentsOptions},s=[];n.editorBlocks.forEach(E=>{E.blockType==="text"||E.blockType==="embed"||s.push(E)});const l=[];n.editorEmbeds.forEach(E=>{l.push(E)});const c=[];n.editorBoxes.forEach(E=>{E.boxType==="text"||E.boxType==="br"||E.boxType==="image"||E.boxType==="anchor"||c.push(E)});const d=Ru(t,e,{shortcuts:[Nh],components:{blocks:s,commandProviders:[new m0],decorators:[new V0],embeds:l,boxes:c,options:o}});if(d.input.addHandler(new H0),d.input.addHandler(new XE(d)),d.input.addHandler(new eA(d)),d.input.addHandler(new dY(d)),d.input.addHandler(new W0),d.addCustom("image-paste-handler",()=>new qE(d)),(h=n.options.componentsOptions)!=null&&h.mention){const E=n.options.componentsOptions.mention;d.addCustom("mention",()=>new aS(d,{...E}))}if((C=n.options.componentsOptions)!=null&&C.comment){const E=n.options.componentsOptions.comment;E.onCommentEditorClick&&d.addListener("click",E.onCommentEditorClick)}return d}function Wtt(n,t){const e=Array.from(n.rootContainer.querySelectorAll(`[comment-${t.toLocaleLowerCase()}="${t}"]`)),r=new Set;e.forEach(i=>{const o=J(i);o&&r.add(o)}),r.forEach(i=>{hY(n,i,t)})}class qtt{constructor(t){m(this,"listeners",new Set);m(this,"doc");this.editor=t,this.doc=this.editor.doc.externalDoc,this.doc.registerCallback(this)}getComments(){return this.doc.getComments()}getComment(t){return this.doc.getComment(t)}getCommentDoc(t){return this.doc.getCommentDoc(t)}localCreateComment(t,e){this.doc.localCreateComment(t,e)}localDeleteComment(t){const e=this.getComment(t);this.doc.localDeleteComment(t);const r=e.groupId;this.getComments().filter(o=>o.groupId===r).length===0&&Wtt(this.editor,r)}localUpdateComment(t,e){this.doc.localUpdateComment(t,e)}onCreateComment(t,e){Array.from(this.listeners.values()).forEach(r=>r.onCreateComment(t,e))}onDeleteComment(t,e){Array.from(this.listeners.values()).forEach(r=>r.onDeleteComment(t,e))}onUpdateComment(t,e){Array.from(this.listeners.values()).forEach(r=>r.onUpdateComment(t,e))}addListener(t){this.listeners.add(t)}removeListener(t){this.listeners.delete(t)}createCommentEditor(t,e){return HS(this.editor,{root:t,childDoc:e,doc:this.doc})}allowEdit(t){return t.userId===this.doc.getUser().userId}}class Xtt{constructor(t,e){m(this,"listeners",new Set);this.editor=t,this.localDoc=e}get doc(){return this.localDoc.toJSON()}getComments(){return Object.values(this.doc.comments)}getComment(t){return this.doc.comments[t]}getCommentDoc(t){const e=this.doc.comments[t];return Yp(e)}addListener(t){this.listeners.add(t)}removeListener(t){this.listeners.delete(t)}localCreateComment(t,e){}localDeleteComment(t){}localUpdateComment(t,e){}createCommentEditor(t,e){return HS(this.editor,{root:t,childDoc:e,doc:this.localDoc})}allowEdit(t){return t.userId===this.localDoc.getUser().userId}}const Ytt={placeholder:{common:{title:"\u8BF7\u8F93\u5165\u6807\u9898",readonlyTitle:"\u8BF7\u8F93\u5165\u6807\u9898",content:"\u70B9\u51FB + \uFF0C\u6216\u8F93\u5165 / \u5FEB\u6377\u63D2\u5165\u7EC4\u4EF6",contentInTable:"\u8F93\u5165 / \u5FEB\u6377\u63D2\u5165\u7EC4\u4EF6"},local:{readonlyTitle:"\u672A\u547D\u540D"}},copyCutProperty:{copy:"\u590D\u5236",cut:"\u526A\u5207",unsafeEnvTips:"\u7531\u4E8E\u5F53\u524D http \u8BBF\u95EE\u73AF\u5883\u4E0B\u7684\u9650\u5236\uFF0C\u8BF7\u4F7F\u7528\u5FEB\u6377\u952E({shortCut}) {operation}",limitedEnvTips:"\u7531\u4E8E\u6D4F\u89C8\u5668\u9650\u5236\uFF0C\u8BF7\u4F7F\u7528 {shortCut} \u7C98\u8D34"}},Qtt={placeholder:{common:{title:"Enter a title",readonlyTitle:"Enter a title",content:'Click "+", or enter "/" to insert components quickly',contentInTable:'Enter "/" to insert components quickly'},local:{readonlyTitle:"Untitled"}},copyCutProperty:{copy:"Copy",cut:"Cut",unsafeEnvTips:"Due to the limitations of the current http access environment, please use the shortcut ({shortCut}) {operation}",limitedEnvTips:"Press {shortCut} to paste due to browser restrictions"}},Jtt={placeholder:{common:{title:"\u30BF\u30A4\u30C8\u30EB\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044",readonlyTitle:"\u30BF\u30A4\u30C8\u30EB\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044",content:"\u300C+\u300D\u3092\u30AF\u30EA\u30C3\u30AF\u3059\u308B\u304B\u3001\u300C/\u300D\u3092\u5165\u529B\u3059\u308B\u3068\u3001\u30B3\u30F3\u30DD\u30FC\u30CD\u30F3\u30C8\u304C\u7D20\u65E9\u304F\u633F\u5165\u3067\u304D\u307E\u3059",contentInTable:"\u300C/\u300D\u3092\u5165\u529B\u3059\u308B\u3068\u3001\u30B3\u30F3\u30DD\u30FC\u30CD\u30F3\u30C8\u304C\u7D20\u65E9\u304F\u633F\u5165\u3067\u304D\u307E\u3059"},local:{readonlyTitle:"\u7121\u984C"}},copyCutProperty:{copy:"\u8907\u88FD",cut:"\u5207\u308B",unsafeEnvTips:"HTTP\u74B0\u5883\u306E\u5236\u7D04\u306B\u3088\u308A\u3001{operation}\u3059\u308B\u306B\u306F\u3001\u30B7\u30E7\u30FC\u30C8\u30AB\u30C3\u30C8({shortCut}) \u3092\u3054\u4F7F\u7528\u304F\u3060\u3055\u3044",limitedEnvTips:"\u30D6\u30E9\u30A6\u30B6\u30FC\u306E\u5236\u9650\u306B\u3088\u308A\u3001\u300C{shortCut}\u300D\u3092\u4F7F\u7528\u3057\u3066\u8CBC\u308A\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044"}};D.mergeLang({"zh-CN":Ytt,"en-US":Qtt,"ja-JP":Jtt});const Ztt="UEsDBBQABgAIAAAAIQBk9WPugQEAACkGAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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Zm9udFRhYmxlLnhtbFBLBQYAAAAADwAPANQDAADePgAAAAA=",tet=()=>$g(Ztt),eet=I("image-to-docx");async function net(n){return new Promise((t,e)=>{const r=new Image;r.onload=()=>{t({width:r.naturalWidth,height:r.naturalHeight})},r.onerror=e,r.src=n})}async function jS(n,t){if(n.width&&n.height)return{width:n.width,height:n.height,buffer:t};try{const e=await da(new File([t],"",{})),r=await net(e);return r.width===void 0||r.height===void 0?{width:345,height:230,buffer:t}:n.width||n.height?{width:n.width||r.width*n.height/r.height,height:n.height||r.height*n.width/r.width,buffer:t}:{width:r.width,height:r.height,buffer:t}}catch(e){eet.error(e);return}}function ret(n,t){let e=n.filter(s=>s!=null);const r=t-(e.length-1)*20,i=.87,o=e.reduce((s,l)=>s+l.width,0);return o>r&&(e=e.map(s=>({width:s.width*r/o,height:s.height*r/o,buffer:s.buffer}))),e.map(s=>({width:s.width*i,height:s.height*i,buffer:s.buffer}))}function iet(n,t,e){if(!e||typeof e!="object")return;const r=e,i=n.filter(s=>s!=null),o=t-(i.length-1)*20;i.forEach((s,l)=>{if(i.length===1&&r.widthPercent){const d=r.widthPercent,h=s.width;s.width=o*(d/100),s.height*=s.width/h;return}const c=`${l}_flex`;if(r[c]){const d=r[c],h=s.width;s.width=o*d,s.height*=s.width/h}})}function zS(n=[0,1,2,3,4,5,6,7],t=1){return n.map(e=>{let r;switch(e%3){case 0:r=Ct.LevelFormat.DECIMAL;break;case 1:r=Ct.LevelFormat.LOWER_LETTER;break;default:r=Ct.LevelFormat.LOWER_ROMAN;break}return{level:e,format:r,text:`%${e+1}. `,alignment:Ct.AlignmentType.START,start:t,style:{paragraph:{indent:{left:Ct.convertInchesToTwip(.3*(e+1)),hanging:Ct.convertInchesToTwip(.2)}}}}})}function oet(){return[0,1,2,3,4,5,6,7].map(n=>{let t;switch(n%3){case 0:t="\u2022";break;case 1:t="\u25E6";break;default:t="\u25AA";break}return{level:n,format:Ct.LevelFormat.BULLET,text:t,alignment:Ct.AlignmentType.START,style:{paragraph:{indent:{left:Ct.convertInchesToTwip(.3*(n+1)),hanging:Ct.convertInchesToTwip(.2)}}}}})}function set(){return[0,1,2,3,4,5,6,7].map(n=>({level:n,format:Ct.LevelFormat.BULLET,text:"\u2611",alignment:Ct.AlignmentType.START,style:{paragraph:{indent:{left:Ct.convertInchesToTwip(.3*(n+1)),hanging:Ct.convertInchesToTwip(.2)}}}}))}function aet(){return[0,1,2,3,4,5,6,7].map(n=>({level:n,format:Ct.LevelFormat.BULLET,text:"\u2610",alignment:Ct.AlignmentType.START,style:{paragraph:{indent:{left:Ct.convertInchesToTwip(.3*(n+1)),hanging:Ct.convertInchesToTwip(.2)}}}}))}var Uf=(n=>(n.NUMBERING="number-numbering-reference",n.BULLET="number-bullet-reference",n.CHECKED="checked-bullet-reference",n.UNCHECKED="unchecked-bullet-reference",n))(Uf||{});const cet=[{levels:zS(),reference:"number-numbering-reference"},{levels:oet(),reference:"number-bullet-reference"},{levels:set(),reference:"checked-bullet-reference"},{levels:aet(),reference:"unchecked-bullet-reference"}];function uet(n){switch(n){case"style-color-0":return"d83931";case"style-color-1":return"de7802";case"style-color-2":return"dc9b04";case"style-color-3":return"2ea121";case"style-color-4":return"245bdb";case"style-color-5":return"6425d0";case"style-color-6":return"8f959e";default:return}}function fet(n){switch(n){case"style-bg-color-1":case"style-bg-color-2":case"style-bg-color-8":case"style-bg-color-9":return"yellow";case"style-bg-color-0":case"style-bg-color-5":return"magenta";case"style-bg-color-3":return"green";case"style-bg-color-4":case"style-bg-color-11":return"blue";case"style-bg-color-6":return"lightGray";case"style-bg-color-7":return"red";case"style-bg-color-10":return"darkGreen";case"style-bg-color-12":return"darkMagenta";case"style-bg-color-13":return"darkGray";default:return}}function det(n){switch(n){case"style-bg-color-0":return"fbbab6";case"style-bg-color-1":return"ffdcb0";case"style-bg-color-2":return"fff7a0";case"style-bg-color-3":return"ceefc5";case"style-bg-color-4":return"d1ddfb";case"style-bg-color-5":return"d9cbf8";case"style-bg-color-6":return"eaeaea";case"style-bg-color-7":return"fe837c";case"style-bg-color-8":return"ffbd6a";case"style-bg-color-9":return"ffe662";case"style-bg-color-10":return"a8f393";case"style-bg-color-11":return"98b5ff";case"style-bg-color-12":return"b394f8";case"style-bg-color-13":return"b1b1b1";default:return}}const het=/rgb\((\d+),\s*(\d+),\s*(\d+)\)/;function GS(n){if(typeof n=="string"&&n.length>0){if(n[0]==="#")return n.substring(1);const t=n.match(het);if(t){const e=s=>{let l=Number(s).toString(16);return l.length<2&&(l=`0${l}`),l},r=e(t[1]),i=e(t[2]),o=e(t[3]);return`${r}${i}${o}`}if(n==="red")return"FF0000";if(n==="green")return"00FF00";if(n==="blue")return"0000FF"}}function ln(n,t){if(n&&n.attributes&&n.attributes[t])return n.attributes[t];if(n&&n.attributes&&n.attributes.box&&n.attributes.inputType&&t==="style-underline")return!0}function WS(n,t,e){for(let r=0;r<=e;++r){const i=`${t}${r}`;if(ln(n,i))return i}}function Cm(n,t,e){n.attributes=n.attributes||{},n.attributes[t]=e}function _A(n){return n==="image"||n==="drawio"||n==="plantuml"||n==="mermaid"||n==="flowchart"}function qS(n){return n&&n.startsWith("//")?`https:${n}`:n&&!n.startsWith("http://")&&!n.startsWith("https://")?`https://${n}`:n}function met(n){const t=ln(n,"inlineStyle");if(t==null)return;const e=t.split(";");for(const r of e){const i=r.split(":");if(i.length!==2)continue;const o=i[0].trim().toLowerCase(),s=i[1].trim().toLowerCase();o==="font-size"&&Cm(n,"inline-style-font-size",s),o==="color"&&Cm(n,"inline-style-color",s),o==="background-color"&&Cm(n,"inline-style-background-color",s),o==="font-family"&&Cm(n,"inline-style-font-family",s)}}function get(n,t){if(t==null)return n==null?void 0:n.normal;if(n)return n[`heading${t}`]}function pet(n){const t=`${ln(n,"inline-style-font-size")}`;if(t&&t.indexOf("px")>0)return+t.replace(/px/g,"")}function Cet(n){if(n.attributes&&n.attributes.box&&n.attributes.text)return` ${n.attributes.text} `;if(n.attributes&&n.attributes.box&&n.attributes.inputType)return n.attributes.value?`${n.attributes.value}`:" "}function Eet(n){if(n.attributes&&n.attributes.box&&n.attributes.text)return` @${n.attributes.text} `}function Aet(n){return ln(n,"inline-style-font-family")}function xet(n){const t=ln(n,"inline-style-background-color");return GS(t)}function bet(n){const t=ln(n,"inline-style-color");return GS(t)}function vet(n){met(n);const t=ln(n,"type")==="mention";return{box:n.attributes&&n.attributes.box?n.attributes:void 0,inlineCode:!!ln(n,"style-code"),link:qS(ln(n,"link")),size:pet(n),text:t?Eet(n):Cet(n)||n.insert,bold:!!ln(n,"style-bold"),underline:!!ln(n,"style-underline"),italics:!!ln(n,"style-italic"),strike:!!ln(n,"style-strikethrough"),superScript:!!ln(n,"style-super"),subScript:!!ln(n,"style-sub"),math:ln(n,"type")==="math"?ln(n,"src"):void 0,mention:t,fontFamily:Aet(n),background:xet(n),color:t?"338fe5":uet(WS(n,"style-color-",6))||bet(n),highlight:WS(n,"style-bg-color-",13)}}function Bet(){return[new Ct.Paragraph({border:{top:{color:"auto",style:Ct.BorderStyle.DASHED,size:4,space:1}},spacing:{before:300}}),new Ct.Paragraph({spacing:{line:0}})]}function Tet(){return new Ct.Paragraph({children:[new Ct.TextRun({text:"[\u89C6\u9891\u6682\u4E0D\u652F\u6301\u5BFC\u51FA]",shading:{type:Ct.ShadingType.CLEAR,color:"FFFFFF",fill:"CCCCCC"}})]})}function yet(){return new Ct.Paragraph({children:[new Ct.TextRun({text:"[\u97F3\u9891\u6682\u4E0D\u652F\u6301\u5BFC\u51FA]",shading:{type:Ct.ShadingType.CLEAR,color:"FFFFFF",fill:"CCCCCC"}})]})}function ket(n,t){return new Ct.Paragraph({children:[new Ct.ExternalHyperlink({children:[new Ct.TextRun({style:"Hyperlink",text:t||n})],link:n})]})}function XS(n){if(n.heading!=null)return`Heading${n.heading}`}function YS(n){if(n.alignment!=null){if(n.alignment==="center")return Ct.AlignmentType.CENTER;if(n.alignment==="right")return Ct.AlignmentType.RIGHT;if(n.alignment==="left")return Ct.AlignmentType.LEFT}}function Ret(n){if(n.indent)return{left:Ct.convertInchesToTwip(.3*n.indent-.2)};if(n.padding)return{left:Ct.convertInchesToTwip(.3*n.padding)}}function wet(n){return{type:Ct.ShadingType.CLEAR,color:"FFFFFF",fill:n}}function Let(n){const t=n.split(",");if(t.length!==0)return t[0].trim()}function QS(n,t){let e;e=n.inlineCode?"InlineCode":void 0,e=n.link?"Hyperlink":e;const r=n.size||t,i=r!=null?Math.floor(r*1.5+.5):void 0;return new Ct.TextRun({text:n.text,bold:n.bold||void 0,underline:n.underline?{type:Ct.UnderlineType.SINGLE}:void 0,italics:n.italics||void 0,strike:n.strike||void 0,superScript:n.superScript||void 0,subScript:n.subScript||void 0,size:i,style:e,font:n.fontFamily?Let(n.fontFamily):void 0,shading:n.background?wet(n.background):void 0,color:n.color,highlight:fet(n.highlight)})}function Iet(n,t){if(n.link)return new Ct.ExternalHyperlink({children:[QS(n,t)],link:n.link})}async function JS(n,t,e,r,i){const[o]=await i(n,t,e);if(o==null)return;const s=await jS({width:r||0,height:0,src:e},o);return new Ct.ImageRun({data:o,transformation:{width:(s==null?void 0:s.width)||100,height:(s==null?void 0:s.height)||20}})}function Det(n){if(n.heading||n.heading)return n.heading}function _et(n){if(n.align&&(n.align==="center"||n.align==="right"||n.align==="left"))return n.align}function Met(n){if(n.textOnly===!0&&n.level!=null)return n.level}async function Uet(n,t){var r;const e=[];if(n.text&&Array.isArray(n.text)){for(let i=0;i<n.text.length;i++){const o=n.text[i];if(((r=o.attributes)==null?void 0:r.box)===!0&&t){const s=await t(o);if(s){n.text.splice(i+1,0,...s);continue}}e.push(vet(o))}return e}}function Oet(n){if(n.type==="list"&&n.textOnly!==!0)return{checkbox:n.checkbox,groupId:n.groupId,ordered:!!n.ordered,level:n.level||1,start:n.start||0}}function Net(n,t){if(n.type==="embed"&&n.embedType&&_A(n.embedType)&&n.embedData&&n.embedData.src)return n.embedData.src.split("|").map(r=>{const i=t(r),o=n.embedData[`${i}_width`],s=n.embedData[`${i}_height`];return{src:r,width:o,height:s}})}function Pet(n){if(n.padding)return n.padding}function Fet(n){return!!(n.type==="embed"&&n.embedType&&_A(n.embedType)&&n.embedData&&n.embedData.src)}async function Em(n,t,e){return{quoted:!!n.quoted,heading:Det(n),alignment:_et(n),indent:Met(n),padding:Pet(n),texts:await Uet(n,e),list:Oet(n),images:Net(n,t),border:Fet(n)}}async function Ket(n,t,e,r){const i=[];if(!n.children)return[];for(const o of n.children){const s=[];for(const l of t.blocks[o])s.push(await Em(l,e,r));i.push(s)}return i}const Vet=I("to-docx");function $et(n,t){return Array(n).fill(0).map(()=>Array(t).fill(0).map(()=>({cellId:void 0,color:void 0,from:void 0,rowSpan:1,colSpan:1,width:0,originalWidth:void 0,align:void 0})))}function Het(n,t,e,r){const i=!!n.hasColTitle,o=!!n.hasRowTitle,s=!!n.isStripeStyle,l="F5F8FB";for(let c=0;c<t;c++)for(let d=0;d<e;d++)(i&&d===0||o&&c===0||s&&c%2===1)&&(r[c][d].color=l)}function jet(n){p(Vet,n.children,"no table children");const t=n.rows,e=n.cols,r=n.colsWidth;if(r)for(let s=0;s<r.length;s++)r[s]===0&&(r[s]=100);const i=$et(t,e);let o=0;for(let s=0;s<t;++s)for(let l=0;l<e;++l){if(i[s][l].originalWidth=r?r[l]:void 0,i[s][l].from!==void 0)continue;const c=n.children[o];o+=1,i[s][l].cellId=c,i[s][l].color=det(n[`${c}_background`]),i[s][l].width=r?r[l]:100,i[s][l].align=n[`${c}_align`];const d=n[`${c}_rowSpan`]||1,h=n[`${c}_colSpan`]||1;if(i[s][l].rowSpan=d,i[s][l].colSpan=h,d>1||h>1){let C=0;for(let E=0;E<d;E++)for(let x=0;x<h;x++)E===0&&(C+=r?r[l+x]:80),!(E===0&&x===0)&&(i[s+E][l+x].from=[s,l]);i[s][l].width=C}}return Het(n,t,e,i),i}async function zet(n,t,e,r,i,o,s,l,c,d){async function h(x){if(l){const v=await l(i,o,x);if(v){await r.addDoc(n,v,d);return}}if(x.type==="text"||x.textOnly===!0){const v=await Em(x,s,c);await r.addTextBlock(v);return}if(x.type==="code"){const v=await Ket(x,e,s,c);await r.addCodeBlockObject(v);return}if(x.type==="list"&&x.textOnly!==!0){const v=await Em(x,s,c);await r.addListBlockObject(n,v);return}if(x.type==="embed"&&x.embedType){const v=x,k=v.embedData,L=v.embedType;if(_A(L)){const M=await Em(x,s,c);await r.addImagesBlockObject(x,M,d)}else x.embedType==="hr"?r.addSeparatorBlock():x.embedType==="video"?r.addVideoPlaceholder():x.embedType==="audio"?r.addAudioPlaceholder():x.embedType==="webpage"?r.addHyperlinkParagraph(qS(k.src),k.title):r.addOtherEmbedBlock(L,x.embedData);return}if(x.type==="table"){let v=[];if(x.colsWidth)v=x.colsWidth;else{const L=x.cols;v=new Array(L);for(let M=0;M<v.length;M++)v[M]=100;x.colsWidth=v}const k=jet(x);await r.addTableMatrix(v,k,e),r.addEmptyParagraph()}}function C(x){const v=[];for(const{type:k,data:L}of x.embedData.exportSpec){if(k==="text"){const M={id:tt(),text:[{insert:L}],type:"text"};v.push(M);continue}if(k==="image"){const M={id:tt(),type:"embed",embedType:"image",align:"left",embedData:{src:L}};v.push(M);continue}if(k==="link"){const M={id:tt(),type:"embed",embedType:"webpage",embedData:{src:L.url,title:L.title}};v.push(M);continue}}return v}function E(x){var v;return(v=x==null?void 0:x.embedData)!=null&&v.exportSpec?C(x):[x]}for(const x of t)for(const v of E(x))await h(v)}function Get(){return{listMaxInst:1,listInstMap:{},listRefMap:{},levelConfigs:[]}}const Wet=I("to-docx");class qet{constructor(t,e,r,i,o,s){m(this,"paragraphs");this.appId=t,this.docId=e,this.state=r,this.readImageFunc=i,this.convertBlocksFunc=o,this.defaultFontSize=s,this.paragraphs=[]}async addTextBlock(t){this.paragraphs.push(new Ct.Paragraph({heading:XS(t),alignment:YS(t),children:await this.paragraphsFromBlockTexts(t),indent:Ret(t)}))}async addEmptyImagePlaceHolder(){this.paragraphs.push(new Ct.Paragraph({text:`[${D.t("docx.imageExportFailed")}]`,shading:{type:Ct.ShadingType.CLEAR,color:"FFFFFF",fill:"CCCCCC"}}))}async paragraphsFromBlockTexts(t){if(t.texts==null)return;const e=get(this.defaultFontSize,t.heading),r=[];for(const i of t.texts){if(i.link){const o=Iet(i,e);o&&r.push(o);continue}if(i.box&&i.box.type&&i.box.type==="br"){r.push(new Ct.TextRun({text:"",break:1}));continue}if(i.box&&i.box.type&&i.box.type==="image"){const o=await JS(this.appId,this.docId,i.box.src,i.box.width,this.readImageFunc);o&&r.push(o);continue}if(i.math){const o=await JS(this.appId,this.docId,i.math,0,this.readImageFunc);o&&r.push(o);continue}r.push(QS(i,e))}return r}async addCodeBlockObject(t){for(const e of t)for(const r of e){const i={style:Ct.BorderStyle.SINGLE,color:"#DEDEDE"};this.paragraphs.push(new Ct.Paragraph({style:"Code",border:{left:{...i},right:{...i},top:{...i},bottom:{...i}},children:await this.paragraphsFromBlockTexts(r)}))}}async addListBlockObject(t,e){if(e.list==null)return;let r;const i=e.list.checkbox?`${t}-${e.list.groupId}-${e.list.checkbox}`:`${t}-${e.list.groupId}`;if(this.state.listInstMap[i])r=this.state.listInstMap[i];else if(r=this.state.listMaxInst,this.state.listMaxInst+=1,this.state.listInstMap[i]=r,e.list.start>0&&e.list.ordered){const s=`number-numbering-reference-${r}`,l=zS([e.list.level-1],e.list.start);this.state.levelConfigs.push({levels:l,reference:s,inst:r}),this.state.listRefMap[i]=s}else e.list.ordered?this.state.listRefMap[i]=Uf.NUMBERING:e.list.checkbox&&e.list.checkbox==="checked"?this.state.listRefMap[i]=Uf.CHECKED:e.list.checkbox&&e.list.checkbox==="unchecked"?this.state.listRefMap[i]=Uf.UNCHECKED:this.state.listRefMap[i]=Uf.BULLET;const o=XS(e);e.texts&&this.paragraphs.push(new Ct.Paragraph({heading:o,children:await this.paragraphsFromBlockTexts(e),numbering:{reference:this.state.listRefMap[i],level:e.list.level-1,instance:r}}))}imageDimWithBufferToImageRun(t){return new Ct.ImageRun({data:t.buffer,transformation:{width:t.width,height:t.height}})}async addImagesBlockObject(t,e,r){if(e.images==null){if(t.type==="embed"&&t.embedType==="image"){const{src:c}=t.embedData;c||this.addEmptyImagePlaceHolder()}return}const i=[],o=await Promise.all(e.images.map(async c=>{const[d,h]=await this.readImageFunc(this.appId,this.docId,c.src);if(d){const C=await jS(c,d);if(C)return C}i.push(h)}));iet(o,r,t.embedData);const s=ret(o,r),l={style:Ct.BorderStyle.SINGLE,color:"#DEDEDE"};s.length&&this.paragraphs.push(new Ct.Paragraph({border:e.border?{left:{...l},right:{...l},top:{...l},bottom:{...l}}:void 0,alignment:YS(e)||Ct.AlignmentType.CENTER,children:s.map(c=>this.imageDimWithBufferToImageRun(c)).flatMap((c,d,h)=>c==null?[]:h.length-1!==d?[c,new Ct.TextRun({text:" "})]:c)})),i.forEach(c=>{this.addHyperlinkParagraph(c)})}addSeparatorBlock(){Bet().forEach(t=>this.paragraphs.push(t))}addEmptyParagraph(){this.paragraphs.push(new Ct.Paragraph(""))}addVideoPlaceholder(){this.paragraphs.push(Tet())}addAudioPlaceholder(){this.paragraphs.push(yet())}addHyperlinkParagraph(t,e){t!=null&&this.paragraphs.push(ket(t,e))}async addTableMatrix(t,e,r){const i=t.map(o=>o!==0?o*15:1500);this.paragraphs.push(new Ct.Table({rows:await this.generateTableRows(e,r),columnWidths:i}))}async generateRowCells(t,e){const r=[];for(const i of t){const o=i.cellId;if(o===void 0)continue;const s=i.width*.9;r.push(new Ct.TableCell({children:await this.convertBlocksFunc(o,e.blocks[o],e,this.appId,this.docId,this.state,s),columnSpan:i.colSpan,rowSpan:i.rowSpan,width:{type:Ct.WidthType.DXA,size:i.width*15},shading:i.color?{fill:i.color,type:Ct.ShadingType.CLEAR,color:"auto"}:void 0}))}return r}async generateTableRows(t,e){const r=[];for(const i of t)r.push(new Ct.TableRow({children:await this.generateRowCells(i,e)}));return r}async addDoc(t,e,r){const i=await this.convertBlocksFunc(t,e.blocks.root,e,this.appId,this.docId,this.state,r);i&&(this.paragraphs=this.paragraphs.concat(i))}async addOtherEmbedBlock(){}}class Xet{constructor(t,e,r,i,o,s,l,c){m(this,"convertBlocks",async(t,e,r,i,o,s,l=720)=>{const c=new qet(i,o,s,this.readImage,this.convertBlocks,this.defaultFontSize);return await zet(t,e,r,c,i,o,this.md5HexFunc,this.getDocByBlock,this.getTextsByBox,l||720),c.paragraphs});this.templateData=t,this.docData=e,this.md5HexFunc=r,this.readImage=i,this.defaultFontSize=o,this.getDocByBlock=s,this.getTextsByBox=l,this.backgroundImageOptions=c}async convert(t,e){return this.snapshot2docx(this.docData,t,e)}async snapshot2docx(t,e,r){const i=new Ct.ImportDotx,o=this.templateData?await i.extract(this.templateData):void 0,s=t.blocks.root;p(Wet,s,"data must have blocks");const l=Get(),c=await this.convertBlocks("blocks",s,t,e,r,l),d=this.backgroundImageOptions?{default:new Ct.Header({children:[new Ct.Paragraph({children:[new Ct.ImageRun(this.backgroundImageOptions)]})]})}:{},h=new Ct.Document({numbering:{config:[...cet,...l.levelConfigs]},sections:[{headers:d,children:c,properties:{page:{size:{width:12240,height:15840},margin:{top:1440,bottom:1440,left:1440,right:1440}}}}]},{template:o});return Ct.Packer.toBlob(h)}}async function Yet(n,t,e,r){const i=n.doc.buildResourceUrl(r,{withToken:!0});let o=await pS(i);if(!o)return[void 0,i];if(o.type.indexOf("/svg")!==-1){const l=await hS(o);l&&(o=new File([l],o.name))}return[await o.arrayBuffer(),i]}async function Qet(n,t,e){const r=n.editorBlocks.getBlockClass(e.type);if(r.toStandardDoc)return r.toStandardDoc(n,e,t)}async function Jet(n,t){const e=t.attributes,r=n.editorBoxes.getBoxClass(e.type);if(r.toStandardText)return r.toStandardText(n,e)}async function Zet(n,t){let{template:e,download:r,backgroundImageOptions:i}=t!=null?t:{};e||(e=tet());const o=n.doc.toJSON(),s=(C,E,x)=>Yet(n,C,E,x),l=async(C,E,x)=>Qet(n,o,x),c=async C=>Jet(n,C),h=await new Xet(e,o,Dd.default,s,void 0,l,c,i).convert("_appId","_docId");if(r){const C=URL.createObjectURL(h),E=document.createElement("a");E.setAttribute("download",`${gS(n)}.docx`),E.setAttribute("href",`${C}`),E.click(),E.remove()}return h}const MA=I("create-editor");async function tnt(n,t){var s,l,c,d,h,C,E,x,v,k,L,M,U,F;p(MA,n,"app does not exists"),t.lang&&D.setLang(t.lang),oi.level=(s=t.logLevel)!=null?s:Ds.DEBUG;const e=t.onReauth?async()=>{var st;const G=t.user.userId,q=t.docId,rt=await((st=t.onReauth)==null?void 0:st.call(t,G,q,t.permission));return{userId:G,docId:q,permission:t.permission,appId:t.appId,token:rt,displayName:t.user.displayName,avatarUrl:t.user.avatarUrl}}:void 0,r={auth:{appId:t.appId,docId:t.docId,userId:t.user.userId,permission:t.permission,token:t.token,displayName:t.user.displayName,avatarUrl:t.user.avatarUrl},serverUrl:t.serverUrl,reauthFunc:e,disableLogout:t.disableLogout},i=await Vu.load(r),o=Ru(n,i,{id:t.id,scrollContainer:t==null?void 0:t.scrollContainer,enableComments:t==null?void 0:t.enableComments,components:{blocks:[...KS,...((l=t==null?void 0:t.components)==null?void 0:l.blocks)||[]],embeds:[...DA,...((c=t.components)==null?void 0:c.embeds)||[]],boxes:[...VS,...((d=t.components)==null?void 0:d.boxes)||[]],commandProviders:[new m0,...((h=t.components)==null?void 0:h.commandProviders)||[]],decorators:[new V0,new Jp],insertions:[Q1],blockHooks:[new NE,new sw,...((C=t.components)==null?void 0:C.blockHooks)||[]],textRenders:[new D4,new ZC],options:{...t.componentsOptions}},shortcuts:[TY,_j,fW,CE,r4,YK,fE,aQ,Nh,HK,...t.shortcuts||[]],colors:["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"]});if(o.editorCommandProviders.registerCommandProvider(new Ri(o)),o.input.addHandler(new EG),o.input.addHandler(new H0),o.input.addHandler(new g$),o.input.addHandler(new rW),o.input.addHandler(new yE(o,{hideTitle:t.hideTitle,headingLevel:1,titlePlaceholder:D.t("placeholder.common.title"),contentPlaceholder:D.t("placeholder.common.content"),readonlyTitlePlaceholder:D.t("placeholder.common.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),o.input.addHandler(new _0(o,(E=t.componentsOptions)==null?void 0:E.quickMenu)),o.input.addHandler(new XE(o)),o.input.addHandler(new eA(o)),o.input.addHandler(new W0),o.doc.registerCallback(new AG(o)),o.addCustom("remote-cursor",()=>new E2(o)),o.addCustom("block-menu",G=>new Cw(G)),ue.isMobile||o.addCustom("editor-tooltip",()=>new M0(o)),t!=null&&t.enableComments&&o.addCustom("editor-comments",G=>new I4(G,new qtt(G))),t.enableContextMenu!==!1&&o.addCustom("editor-context-menu",G=>new l4(G)),o.addCustom("create-options",()=>new Ob(o,t)),o.addCustom("drop-target",()=>new Tf(o)),o.addCustom("list-to-mindmap",()=>new R0(o)),o.addCustom("list-to-mention",()=>new eJ(o)),o.addCustom("mobile-helper",()=>new TJ(o)),o.addCustom("code-caret",()=>new Sj(o)),o.addCustom("image-paste-handler",()=>new qE(o)),(x=t.componentsOptions)!=null&&x.mention){const G=t.componentsOptions.mention;o.addCustom("mention",()=>new aS(o,G))}if(o.addCustom("heading-collapse",()=>new HE(o)),o.addCustom(gm,G=>new vA(G)),Qa.register(o),Tf.register(o),gs.register(o),cs.register(o),o.addListener("clickLink",(G,q,rt)=>{var Et;if((Et=t==null?void 0:t.events)!=null&&Et.onClickLink){t.events.onClickLink(G,q,rt);return}const st=rt.getAttribute("link");st&&(G.readonly||q.ctrlKey||q.metaKey)&&window.open(st,"_blank")}),(k=(v=t.componentsOptions)==null?void 0:v.remoteCarets)!=null&&k.onUserChanged){const G=(M=(L=t.componentsOptions)==null?void 0:L.remoteCarets)==null?void 0:M.onUserChanged;o.doc.getRemoteUsers().on("change",q=>{G(o,q)})}return(F=(U=t.componentsOptions)==null?void 0:U.templates)!=null&&F.templates.length&&(o.addListener("docChanged",()=>{mm(o)}),o.addListener("resize",()=>{mm(o,{reset:!0})}),setTimeout(()=>{mm(o)},100)),o.doc.registerCallback({onError:async G=>{if(G.code==="ResetDoc"){MA.error(`reset doc: ${G.message}`);const q=await Vu.load(r);o.doc.reset(q)}}}),o}function ent(n){return n.toJSON!==void 0}async function nnt(n,t,e){var o,s,l,c,d,h;p(MA,n,"app does not exists");const r=ent(t)?t:new Lp(t,{serverUrl:e.serverUrl||""});e.lang&&D.setLang(e.lang),oi.level=(o=e.logLevel)!=null?o:Ds.DEBUG;const i=Ru(n,r,{id:e.id,scrollContainer:e==null?void 0:e.scrollContainer,components:{blocks:[pE,BE,TE,Pk],commandProviders:[new m0],decorators:[new V0,new Jp],embeds:[...DA,...((s=e.components)==null?void 0:s.embeds)||[]],boxes:[Qk,cS,K4,...((l=e.components)==null?void 0:l.boxes)||[]],insertions:[Q1],blockHooks:[new NE,...((c=e.components)==null?void 0:c.blockHooks)||[]],textRenders:[new D4,new ZC,...((d=e.components)==null?void 0:d.textRenders)||[]],options:{...e.componentsOptions}},shortcuts:[CE,r4,fE,Nh]});return i.editorCommandProviders.registerCommandProvider(new Ri(i)),i.input.addHandler(new H0),i.input.addHandler(new yE(i,{hideTitle:e.hideTitle,headingLevel:1,titlePlaceholder:D.t("placeholder.common.title"),contentPlaceholder:D.t("placeholder.common.content"),readonlyTitlePlaceholder:D.t("placeholder.local.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),i.input.addHandler(new _0(i,(h=e.componentsOptions)==null?void 0:h.quickMenu)),i.input.addHandler(new XE(i)),i.input.addHandler(new eA(i)),i.input.addHandler(new W0),i.addCustom("block-menu",C=>new Cw(C)),ue.isMobile||i.addCustom("editor-tooltip",()=>new M0(i)),i.addCustom("image-paste-handler",()=>new qE(i)),e!=null&&e.enableComments&&i.addCustom("editor-comments",C=>new I4(C,new Xtt(C,r))),e.enableContextMenu!==!1&&i.addCustom("editor-context-menu",C=>new l4(C)),i.addCustom("heading-collapse",()=>new HE(i)),i.addListener("clickLink",(C,E,x)=>{var k;if((k=e==null?void 0:e.events)!=null&&k.onClickLink){e.events.onClickLink(C,E,x);return}const v=x.getAttribute("link");v&&(C.readonly||E.ctrlKey||E.metaKey)&&window.open(v,"_blank")}),i.addCustom(gm,C=>new vA(C)),Qa.register(i),i}async function rnt(n,t,e){var h;const r=n.doc.externalDoc.client.auth,i=await qh.load({auth:r,serverUrl:e});if(!((h=i.getVersionHelper)==null?void 0:h.call(i)))throw new Error("the editor does not support to show versions");const s=n.getCustom("create-options");if(!s)throw new Error("the editor does not support to show versions");const l=s.getData(),c=new $S(l),d=n.addCustom("version-dialog",()=>new nS(i,c));return d.show(t),d}b.tippy=a9,b.AnchorBox=PB,b.AuthError=Fu,b.AuthHeader=ol,b.AutoScroll=Wd,b.BaseURLHeader=Ma,b.BasicCommands=NV,b.BlockExclusiveHook=sw,b.BlockLockerHook=NE,b.BlockLockerPasteHandler=W0,b.BlockResizer=df,b.BrBox=MB,b.CodeBlock=BE,b.CodeLineBlock=TE,b.CodeTextDecorator=V0,b.DOC_RE_AUTH_KEYS=gm,b.DefaultShortcuts=Nh,b.DocIdError=DN,b.DocReAuthCallbacks=vA,b.DragDrop=ev,b.DrawioEmbed=SS,b.EditorBlocks=c3,b.EditorBoxes=OB,b.EditorCommandProviders=DT,b.EditorComplexBlockPosition=Ur,b.EditorComplexSelectionRange=ui,b.EditorDecorators=$B,b.EditorEmbeds=f3,b.EditorInsertions=VB,b.EditorSimpleBlockPosition=qe,b.EditorSimpleSelectionRange=en,b.EmbedBlock=h3,b.EmbedBlockResizer=Df,b.EnforceWithDocumentTitleHandler=yE,b.EventCallbacks=aa,b.FILL_CHAR=iM,b.FileExtError=_N,b.GroupOrder=Hk,b.HeadingBlockScrollListener=qQ,b.ImageBox=NB,b.InlineBoxCommandProvider=Jk,b.InputtingInsertion=FB,b.LocalDoc=Lp,b.LogLevel=Ds,b.Logger=oi,b.MIN_DISTANCE_THRESHOLD=Zb,b.ManualCloseDialog=ju,b.ManualMenu=Zo,b.ManualToolbar=Hu,b.MarkdownInputHandler=H0,b.MaxUserError=Hp,b.Mindmap=k0,b.OnesEditorAutoSuggest=xC,b.OnesEditorCustomDataWrapper=Ob,b.OnesEditorExclusiveBlock=cs,b.OnesEditorHoveringBlock=Te,b.OnesEditorIcons=EP,b.OnesEditorQuickMenu=_0,b.OnesEditorToc=_f,b.OnesEditorTocProvider=gs,b.OnesEditorToolbar=Qa,b.OnesEditorTooltip=M0,b.OnesEditorVersionsDialog=nS,b.PermissionError=Wh,b.Popup=$u,b.ReAuthToolbar=CS,b.RemoteCarets=E2,b.RemoteCaretsDecorator=Jp,b.RemoteCaretsInsertion=Q1,b.RemoteUsers=wu,b.RequestReloadError=Ku,b.RichText=hn,b.ShareDBDoc=Vu,b.ShareDBDocVersionsProvider=$S,b.ShareDBServer=qh,b.SimpleCache=jb,b.StandardEmbedBlockCommands=hA,b.TEXT_STYLE_BACKGROUND_COLOR_PREFIX=L1,b.TEXT_STYLE_COLOR_PREFIX=S1,b.TableBlock=pE,b.TableBlockCommandProvider=m0,b.TableShortcuts=CE,b.TextBlock=On,b.TextBox=_B,b.TextColorItem=Uy,b.TextStyleShortcuts=fE,b.TocEmbed=sS,b.ZERO_WIDTH_SPACE_CHAR=jc,b.abbreviation=qd,b.addAttribute=ah,b.addClass=z,b.addCommentToBlock=If,b.addDays=pI,b.addMetaToDoc=yu,b.addMonths=gI,b.animateScrollTo=Ns,b.applyPlaceholderToBlock=uf,b.assert=p,b.autoShowHideTemplates=mm,b.blockToDoc=Tp,b.blockToHtml=tp,b.blockToMarkdown=Th,b.blockToText=Bh,b.blocksToDoc=nT,b.clearAllSelection=Gv,b.clientType=ue,b.cloneBlock=Wo,b.cloneChildContainer=up,b.cloneDoc=fp,b.cloneText=TB,b.commentToShareDbComment=Qp,b.compareElement=Fd,b.comparePosition=h1,b.complexBlockAdjustSelectionPos=th,b.complexBlockFindNearestChildBlock=m7,b.complexBlockGeFirstSimpleChild=g1,b.complexBlockGetAllChildContainers=Bn,b.complexBlockGetBottomChildContainers=p3,b.complexBlockGetLastSimpleChild=Ca,b.complexBlockGetSelectedContainers=pa,b.complexBlockGetTopChildContainers=g3,b.containerToDoc=rT,b.continuousScroll=Cv,b.convertBlockFrom=Jd,b.convertImageFileToPng=hS,b.convertImageSrcToPng=EJ,b.converterIntercept=$0,b.copyBlockAttributes=t5,b.copyResourcesFromDoc=Sp,b.createBlockAnchor=Xi,b.createBlockCaretAnchor=A3,b.createBlockContentElement=js,b.createBlockElement=Nv,b.createBlockSimpleDocRange=Eh,b.createBlockSimpleRange=ye,b.createBoxContentElement=Kv,b.createBoxElement=Pv,b.createBoxOp=BB,b.createChildContainer=l3,b.createComplexBlockPosition=Ee,b.createComplexDocPos=SB,b.createComplexDocRange=lM,b.createContainer=kB,b.createContainerElement=Jg,b.createDeleteOps=AB,b.createEditor=Ru,b.createEditorSelectionRange=Xe,b.createElement=B,b.createEmptyContainer=to,b.createEmptyDoc=Zi,b.createEmptyTextBlockData=ph,b.createExpandedRange=Nd,b.createIconButton=Ms,b.createImage=Ig,b.createInsertOps=mh,b.createInsertionContentElement=Hv,b.createInsertionElement=Vv,b.createLocalEditor=nnt,b.createOnesEditor=tnt,b.createRange=zb,b.createRichText=el,b.createRootContainer=s3,b.createSimpleBlockPosition=ct,b.createSimpleDocPos=wB,b.createTextBlockData=mi,b.createTextButton=ml,b.createTextOp=mr,b.createTextWithReplaceSoftReturn=$1,b.daysAfter=Wg,b.deleteText=j1,b.diffDays=CI,b.disablePageScroll=jg,b.docToHtml=XB,b.docToHtmlFragment=Cu,b.docToMarkdown=YB,b.docToText=Go,b.downloadImageToFile=pS,b.downloadObjectToFile=yA,b.downloadSvgToString=xS,b.editLink=ef,b.editorAddComment=gY,b.editorAddTextAttribute=f5,b.editorAutoInsertBlock=e5,b.editorBreakTextBlock=ka,b.editorClearCompositionText=ip,b.editorClearSelectedContents=Sh,b.editorCopyBlock=Rp,b.editorCopyDoc=Oh,b.editorDeleteBlock=lp,b.editorDeleteBlockText=op,b.editorDeleteBlockWithoutChildren=Rh,b.editorDeleteChildContainer=iU,b.editorDeleteChildContainers=n5,b.editorFocusToBlock=cp,b.editorFocusToEnd=BU,b.editorGetBlockData=zo,b.editorGetBlockText=Tn,b.editorGetBlockTextEx=xh,b.editorGetBoxData=IB,b.editorHandleKeyboardEvent=mT,b.editorInsertBlock=ya,b.editorInsertBoxToBlock=JB,b.editorInsertDoc=c5,b.editorInsertDocAt=dp,b.editorInsertText=rp,b.editorInsertTextToBlock=QB,b.editorInsertTextToBlockEx=np,b.editorMergeTextBlock=r5,b.editorMoveDown=T5,b.editorMoveEnd=Ap,b.editorMoveHome=M5,b.editorMoveLeft=b5,b.editorMoveLineEnd=$5,b.editorMoveLineHome=V5,b.editorMovePageDown=q5,b.editorMovePageUp=W5,b.editorMoveRight=v5,b.editorMoveUp=B5,b.editorMoveWordEnd=I5,b.editorMoveWordLeft=L5,b.editorRangeClearColor=h5,b.editorRangeGetColor=m5,b.editorRangeSetColor=d5,b.editorRemoveTextAttribute=aU,b.editorReplaceBlockText=Lh,b.editorReplaceContainer=u5,b.editorRunOnce=Ip,b.editorSelectAll=bp,b.editorSelectContainer=_h,b.editorSelectDown=y5,b.editorSelectEnd=xp,b.editorSelectHome=U5,b.editorSelectLeft=k5,b.editorSelectLineEnd=K5,b.editorSelectLineHome=F5,b.editorSelectPageDown=Q5,b.editorSelectPageUp=Y5,b.editorSelectRight=R5,b.editorSelectUp=w5,b.editorSelectWordEnd=_5,b.editorSelectWordLeft=D5,b.editorSetTextColor=Ra,b.editorShowFindDialog=lX,b.editorToDocx=Zet,b.editorUpdateBlockData=Ih,b.editorUpdateCompositionText=ZB,b.editorUpdateEmbedData=l5,b.enablePageScroll=zg,b.escapeHtmlText=Vd,b.escapeRegExp=Qg,b.escapeSpace=Z9,b.exclusiveBlock=ME,b.executeBlockCommand=e3,b.executeEmbedBlockCommand=t3,b.executeRangeCommand=IT,b.fileToDataUrl=da,b.findAfterOffsetNotType=q1,b.findAllText=vp,b.findBlockByIndex=wv,b.findEventTargetBlock=Xb,b.findInsertionById=$v,b.findNextOffset=kM,b.findNextVisibleSimpleBlock=OT,b.findPrevOffset=yM,b.findPrevOffsetNotType=W1,b.findPrevSimpleBlockBeforeChildContainer=m3,b.findPrevVisibleSimpleBlock=UT,b.findTarget=ua,b.findWordEnd=Y1,b.findWordLeft=X1,b.format=Qc,b.formatBytes=Ev,b.formatDate=Xg,b.fragmentToHtml=dv,b.fromBase64=Wc,b.fromBase64ToBlob=$g,b.fromBase64ToUint8Array=uI,b.fromDocRange=Vo,b.fromNowString=Yg,b.genId=tt,b.getAllChildBlocks=E1,b.getAllQuickMenuItems=uE,b.getAllSelectedBlocks=fi,b.getAttributesAt=ba,b.getBlockBackground=Ov,b.getBlockByIndex=Hi,b.getBlockCaretRect=Fo,b.getBlockClass=Jt,b.getBlockClassByType=Vs,b.getBlockClientRects=Gi,b.getBlockCommandsWithHook=l1,b.getBlockContent=Ot,b.getBlockId=lt,b.getBlockIndex=Bt,b.getBlockInfo=Cf,b.getBlockKind=Dr,b.getBlockMinWidth=qv,b.getBlockNearestRangeFromPoint=p1,b.getBlockOptions=LI,b.getBlockPath=Ko,b.getBlockProperties=Qv,b.getBlockRangeFromPoint=eh,b.getBlockStyles=SI,b.getBlockTextLength=dt,b.getBlockTools=ie,b.getBlockType=Dt,b.getBoxContent=n1,b.getBoxId=Fv,b.getBoxTypeFromElement=eu,b.getChildBlockCount=Ir,b.getChildBlocks=fe,b.getChildOffset=Js,b.getColorFromAttributes=D1,b.getColorFromContent=Xd,b.getComplexBlockClass=fr,b.getContainerBlockPath=r3,b.getContainerBlocks=zv,b.getContainerBlocksElement=Zc,b.getContainerById=Lr,b.getContainerId=at,b.getContainerMinWidth=f1,b.getContainerToolsElement=kI,b.getContainerWidth=a3,b.getDistanceSquare=Po,b.getElementOffset=Hc,b.getElementScale=ur,b.getEmbedType=We,b.getExistsBlockTools=Yd,b.getExistsContainerById=Jc,b.getFileExt=Yc,b.getFirstChildBlock=we,b.getFirstClientRect=Pd,b.getHeadingMenuOptions=sE,b.getHorizontalPadding=_g,b.getInsertionContent=r1,b.getLastChildBlock=tn,b.getLastClientRect=Us,b.getListAllNextBrothers=Ga,b.getLogger=I,b.getNextBlock=Yt,b.getNextValidOffset=Zs,b.getNextVisibleBlock=Gs,b.getOffsetFromPoint=Dg,b.getOffsetInfoAfter=mu,b.getOffsetInfoBefore=bh,b.getOpAt=Z3,b.getOpLength=lh,b.getParentBlock=J,b.getParentBlockExcludeSelf=Hs,b.getParentBox=e1,b.getParentContainer=it,b.getPrevBlock=Ae,b.getPrevValidOffset=jo,b.getPrevVisibleBlock=zs,b.getRangeCommands=ST,b.getReferenceClientRect=mk,b.getRootBlock=s1,b.getScrollContainer=Ge,b.getSpecialBlockCommands=Jv,b.getStandardEmbedBlockProperties=mA,b.getTextAfterOffset=BM,b.getTextAttributes=ep,b.getTextBeforeOffset=TM,b.getTextBlockChild=iu,b.getTextBlockClass=Lv,b.getTextBlockContentChildTextLength=hr,b.getTextBlockContentChildType=n3,b.getTextBlockContentChildren=ai,b.getTextLength=dn,b.getTextOpLength=w1,b.getTextWidth=jd,b.getToolbar=x0,b.handleBlockElementUpdated=Xv,b.hasAltOnly=oI,b.hasClass=wt,b.hasCtrlOrCmd=lv,b.hasCtrlOrCmdOnly=iI,b.hashCode=yv,b.hideBlock=Uv,b.htmlToFragment=Hd,b.i18n=D,b.includeBigTable=qP,b.injectDocToHtmlFragment=Tu,b.injectStyle=Jb,b.inputActions=$U,b.insertEmptyBlock=_I,b.insertEmptyEmbedBlock=a1,b.insertText=Ji,b.intersectionCommands=bO,b.isBackspace=cv,b.isBlock=$s,b.isBlockLocked=G0,b.isBlockLockedByOthers=OE,b.isBlockLockedBySelf=Ef,b.isBlockTools=Mv,b.isBox=Qd,b.isBoxOp=Ho,b.isCJK=ov,b.isChildContainer=Mr,b.isChildNode=re,b.isCodeBlock=Gr,b.isCollapsedRange=sM,b.isComplexBlockPosition=ga,b.isComplexKindBlock=Mt,b.isContainer=zi,b.isContainerSelectedAllChildBlocks=J5,b.isControlEvent=Fs,b.isDelete=lI,b.isDraggingFiles=zd,b.isElementVisible=Og,b.isEmbedBlock=ge,b.isEmptyContainer=ou,b.isEmptyDoc=z1,b.isEmptyTextBlock=oe,b.isEmptyTextBlockWithoutCompositionText=cf,b.isEnterOnly=av,b.isEscape=Kg,b.isExclusiveBlock=pf,b.isFirefox=Gc,b.isFirstChildBlockInComplexBlock=h7,b.isHighSurrogate=X9,b.isInBlock=i1,b.isInBlockTools=Ws,b.isLetter=iv,b.isLowSurrogate=Y9,b.isMatchShortcut=si,b.isMoveForward=nI,b.isNavigationEvent=eI,b.isNavigationKey=sv,b.isNodeRemoved=Wb,b.isNumber=rv,b.isPrintableKey=Fg,b.isRootBlock=dr,b.isRootContainer=Qt,b.isSafari=fa,b.isSameDay=qg,b.isSelectBoxOnly=Fk,b.isShiftEnter=sI,b.isShiftTab=cI,b.isShortcutEvent=rI,b.isSimpleBlock=wI,b.isSimpleBlockPosition=ci,b.isSimplePos=RB,b.isSimpleRange=Ch,b.isSpace=$d,b.isTab=aI,b.isTextBlockContentBoxChild=Yn,b.isTextBlockContentChild=nu,b.isTextBlockContentInsertionChild=qi,b.isTextBlockContentTextChild=ru,b.isTextKindBlock=nt,b.isTextKindBlockType=tu,b.isTitleBlock=ji,b.isToday=Av,b.isValidOffset=Un,b.isVisibleBlock=ma,b.isYesterday=xv,b.loadJs=qb,b.loadJsPromise=Os,b.lockers=Sr,b.mergeCommands=A0,b.mergeDocs=nl,b.mergeOps=H1,b.mergeText=nM,b.multiSplitText=eB,b.overflowText=bv,b.parseShortcut=uv,b.patchNode=qc,b.pointInRect=Ps,b.rangeAddAttribute=uu,b.rangeGetTextColor=aB,b.rangeRemoveAttribute=xa,b.rangeSetTextColor=oB,b.rangeTransformText=rB,b.registerDragDrop=Ng,b.removeAttribute=I1,b.removeClass=ot,b.removeLastBr=J_,b.removePlaceholderFromBlock=DR,b.removeStyle=Qb,b.replaceAll=EI,b.replaceAllCaseInsensitive=AI,b.replaceAllText=tT,b.replaceText=gh,b.requestDownload=Gd,b.resetListStart=qa,b.scrollIntoView=pu,b.scrollable=pv,b.selectFile=ha,b.selectedBlockToDoc=Mh,b.selectionToDoc=wa,b.setAttributes=Kd,b.setClipboardData=Xc,b.setClipboardDataByEvent=hI,b.setColorToAttributes=sB,b.setDataset=Mg,b.setDefaultCursor=zc,b.setStyles=Ug,b.shareDBCommentToDocObject=Yp,b.shareDBDocCommentToComment=p2,b.shortcutToDisplayText=ze,b.showBlock=t1,b.showDocVersions=rnt,b.splitText=_n,b.splitToThree=Ye,b.stringToDataUrl=Hg,b.stringToObjectUrl=Gg,b.subText=nB,b.textNodeOffsetFromPoint=Gb,b.titleFromEditor=gS,b.toBase64URL=li,b.toMindmap=y0,b.toPlainText=de,b.toPlainTextKeepLength=G1,b.trimChar=Pg,b.unexclusiveBlock=UE,b.unicodeLength=Q9,b.unicodeSubstr=J9,b.updateBlockSelection=Wv,b.updateOpAttributes=yB,b.updateTextBlockContent=vM,b.updateUrl=Vg;for(const n in Be)n!=="default"&&!b.hasOwnProperty(n)&&Object.defineProperty(b,n,{enumerable:!0,get:()=>Be[n]});Object.defineProperties(b,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
951
+ \`\`\`\`\`\``}return""}const Ctt={embedType:"plantuml",convertFrom:mtt,handleUpdateBlock:htt,createEmbedContent:dtt,getBlockProperties:gtt,convertTo:ptt},Eut="",Ett="hr",Att={dividingLine:{type:"\u5206\u5272\u7EBF",abstract:"\u5206\u5272\u7EBF"}},xtt={dividingLine:{type:"Dividing-Line",abstract:"Dividing-Line"}},btt={dividingLine:{type:"\u533A\u5207\u308A\u7DDA",abstract:"\u533A\u5207\u308A\u7DDA"}};D.mergeLang({"zh-CN":Att,"en-US":xtt,"ja-JP":btt});function vtt(n,t){const e=B("div",["editor-embed-container"],t);B("hr",["editor-embed-hr"],e)}function Btt(n,t,e,r){return r==="html"?"<hr />":r==="markdown"?"---":"------------"}function Ttt(){return{name:"hr",insertEmbedCommandItems:[{id:"insert-hr",name:D.t("dividingLine.type"),icon:J2,order:500,group:"common",subText:yn("insert-hr")}],handleInsertEmptyEmbed:async(n,t)=>{const{containerId:e,blockIndex:r}=t;return n.insertEmbed(e,r,Ett,{})}}}function ytt(n,t,e){const{data:r}=e;if(!r||r.embedType!=="dividing-line"||!nt(n,t))return null;const i={};return{blockData:{id:tt(),type:"embed",embedType:"hr",embedData:i}}}function ktt(){return{abstract:D.t("dividingLine.abstract")}}const Rtt={embedType:"hr",createEmbedContent:vtt,convertTo:Btt,getOptions:Ttt,convertFrom:ytt,getBlockProperties:ktt},Aut="",xut="",wtt={media:{upload:{failed:'<div class="line-1">{name}\u4E0A\u4F20\u5931\u8D25</div><div class="line-2">\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5 <span class="retry-upload">\u91CD\u8BD5</span></div>',maxSizeFailed:'<div class="line-1">{name}\u4E0A\u4F20\u5931\u8D25</div><div class="line-2">\u6587\u4EF6\u5927\u5C0F\u8D85\u8FC7\u9650\u5236\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u6587\u4EF6</div>'},load:{failed:'<div class="line-1">{name}\u52A0\u8F7D\u5931\u8D25</div><div class="line-2">\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5 <span class="retry-upload">\u91CD\u8BD5</span></div>'},audio:{menuItem:"\u97F3\u9891",abstract:"\u97F3\u9891"},video:{menuItem:"\u89C6\u9891",abstract:"\u89C6\u9891"}}},Stt={media:{upload:{failed:'<div class="line-1">{name} upload failed</div><div class="line-2">Network error, you can <span class="retry-upload">Retry</span></div>',maxSizeFailed:'<div class="line-1">{name} upload failed</div><div class="line-2">The file size exceeds limit. Please choose another file.</div>'},load:{failed:'<div class="line-1">{name} loading failed</div><div class="line-2">Network error, you can <span class="retry-upload">Retry</span></div>'},audio:{menuItem:"Audio",abstract:"Audio"},video:{menuItem:"Video",abstract:"Video"}}},Ltt={media:{upload:{failed:'<div class="line-1">{name}\u306E\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u306B\u5931\u6557\u3057\u307E\u3057\u305F</div><div class="line-2">\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 <span class="retry-upload">\u518D\u8A66\u884C</span></div>',maxSizeFailed:'<div class="line-1">{name}\u306E\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u306B\u5931\u6557\u3057\u307E\u3057\u305F</div><div class="line-2">\u30D5\u30A1\u30A4\u30EB\u306E\u30B5\u30A4\u30BA\u304C\u4E0A\u9650\u3092\u8D85\u3048\u3066\u3044\u308B\u305F\u3081\u3001\u4ED6\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044</div>'},load:{failed:'<div class="line-1">{name}\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 <span class="retry-upload">\u518D\u8A66\u884C</span></div>'},audio:{menuItem:"\u97F3\u58F0",abstract:"\u97F3\u58F0"},video:{menuItem:"\u52D5\u753B",abstract:"\u52D5\u753B"}}};D.mergeLang({"zh-CN":wtt,"en-US":Stt,"ja-JP":Ltt});var Xr=(n=>(n.AUDIO="audio",n.VIDEO="video",n))(Xr||{}),Mf=(n=>(n.Empty="empty",n.Progress="progress",n.Error="error",n))(Mf||{});const MS=10*1024*1024,Itt=["wav","mp3","aac","ogg","webm","flac"],Dtt=["ogg","mp4","webm"],_tt=()=>{};function US(n){var h,C,E,x,v,k;const t=(h=n.getComponentOptions("media"))!=null?h:{},{allowedMedias:e,maxSize:r,callbacks:i}=t,o=(C=e==null?void 0:e.audio)!=null?C:Itt,s=(E=e==null?void 0:e.video)!=null?E:Dtt,l=(x=r==null?void 0:r.audio)!=null?x:MS,c=(v=r==null?void 0:r.video)!=null?v:MS,d=(k=i==null?void 0:i.onError)!=null?k:_tt;return{allowedMedias:{audio:o,video:s},maxSize:{audio:l,video:c},callbacks:{onError:d}}}function Mtt(n,t){const e=o=>o.map(s=>`.${s}`).join(","),{allowedMedias:r}=US(n),i=r[t];return i?e(i):"*"}function Utt(n,t,e){const{maxSize:r,callbacks:i,allowedMedias:o}=US(t),{[e]:s}=r,{[e]:l}=o;if(s&&n.size>s){const d=new Error("media is too large");throw d.code=`MaxMediaSize-${e}`,i!=null&&i.onError&&(i==null||i.onError(t,d)),d}const c=Yc(n.name);if(l&&!l.includes(c.toLowerCase())){const d=new Error(`media file is not allowed: ${c}`);throw d.code="NotAllowedFile",i!=null&&i.onError&&(i==null||i.onError(t,d)),d}}function Ott(n){return n===Mf.Empty||n===Mf.Error}const Je=I("media");class Ntt extends Be.TypedEmitter{constructor(e){super();m(this,"mediaContainer",null);m(this,"media",null);m(this,"abstract",null);m(this,"handleMediaLoadError",(e,r)=>{if(!r.target||!(r.target instanceof Node)||!(r.target instanceof Element?r.target:r.target.parentElement))return;const o=J(r.target);if(!o||!o.contains(this.mediaContainer))return;const s=this.renderError();this.updateMediaContent(s),this.emit("mediaError",e,"load_error",lt(o))});m(this,"handleUploadFile",async e=>{p(Je,this.abstract,"no abstract"),p(Je,this.mediaContainer,"The media element not exist");const{editor:r}=this.options,i=J(this.mediaContainer);p(Je,i,"The block element not exist");const o=r.getBlockData(i);try{const{resourceId:s}=await r.doc.uploadResource(e,{onProgress:C=>{this.renderProgress(C,e)}}),{name:l,type:c,size:d}=e,h={...o,embedData:{...o.embedData,src:s,fileName:l,fileSize:d,fileType:c}};r.updateBlockData(i,h)}catch(s){Je.error(s),this.emit("mediaError",r,"upload_error",o.id),this.renderRetry(e,s)}ot(i,"media-block-uploading")});m(this,"destroy",()=>{this.mediaContainer=null});this.options=e}bindMediaEvent(){const{editor:e}=this.options;this.media&&e.domEvents.addEventListener(this.media,"error",this.handleMediaLoadError)}unbindMediaEvent(){const{editor:e}=this.options;this.media&&e.domEvents.removeEventListener(this.media,"error",this.handleMediaLoadError)}updateMediaContent(e){p(Je,this.mediaContainer,"The media element not exist"),this.mediaContainer.innerHTML="",this.mediaContainer.append(e)}renderError(){p(Je,this.abstract,"no abstract");const{editor:e,createMediaElement:r}=this.options,{mediaIcon:i,mediaName:o}=this.abstract;p(Je,this.mediaContainer,"The media element not exist");const s=J(this.mediaContainer);p(Je,s,"The block element not exist");const l=e.getBlockData(s),c=B("div",["media-error","embed-selected-content","embed-hover-content"],null),d=B("span",["media-error-icon"],c);d.innerHTML=i;const h=B("div",[],c);h.innerHTML=D.t("media.load.failed",{name:o}),c.appendChild(h);const C=h.querySelector(".retry-upload");return p(Je,C,"The element not exist"),e.domEvents.addEventListener(C,"click",(E,x)=>{const v=B("div",["media-element"],null),k=this.getResourceUrl(l),L=r(E,v,l,k);this.unbindMediaEvent(),this.media=L,this.bindMediaEvent(),this.updateMediaContent(v)}),this.setFullScreen(),c}renderRetry(e,r){var E,x;p(Je,this.abstract,"no abstract");const{editor:i}=this.options,{mediaIcon:o,mediaName:s}=this.abstract,l=B("div",["media-error","embed-selected-content","embed-hover-content"],null),c=B("span",["media-error-icon"],l);c.innerHTML=o;const d=B("div",[],l);let h=D.t("media.upload.failed",{name:s});(((E=r.response)==null?void 0:E.status)===420||((x=r.response)==null?void 0:x.status)===413)&&(h=D.t("media.upload.maxSizeFailed",{name:s})),d.innerHTML=h,l.appendChild(d);const C=d.querySelector(".retry-upload");C&&i.domEvents.addEventListener(C,"click",()=>{i.readonly||(p(Je,this.abstract,"no abstract"),this.handleUploadFile(e))}),this.updateMediaContent(l),this.setFullScreen()}renderProgress(e,r){p(Je,this.mediaContainer,"The media element not exist");const i=this.mediaContainer.querySelector(":scope .media-progress"),o=e===-1||e===100?100:e;if(i){const{updateProgressElement:s}=this.options;s(i,o)}else{const{createProgressElement:s}=this.options,l=J(this.mediaContainer);p(Je,l,"The element not exist"),z(l,"media-block-uploading");const c=B("div",["media-progress"],null);s(c,o,r),this.updateMediaContent(c)}this.setFullScreen()}renderMediaElement(e,r){p(Je,this.mediaContainer,"The media element not exist");const i=this.mediaContainer.querySelector(":scope > .media-element"),{createMediaElement:o,updateMediaElement:s,editor:l}=this.options,c=this.getResourceUrl(e,r);if(i){const d=s(l,i,e,c);this.unbindMediaEvent(),this.media=d,this.bindMediaEvent()}else{const d=B("div",["media-element"],null),h=o(l,d,e,c);this.unbindMediaEvent(),this.media=h,this.bindMediaEvent(),this.updateMediaContent(d)}}renderEmpty(e){p(Je,this.abstract,"no abstract"),p(Je,this.mediaContainer,"The media element not exist");const r=B("div",["media-empty","embed-selected-content","embed-hover-content"],this.mediaContainer);r.innerHTML=this.abstract.mediaIcon,this.updateMediaContent(r);const{editor:i}=this.options;i.findBlockById(e.id)&&this.emit("mediaError",i,"empty",e.id),this.setFullScreen()}getResourceUrl(e,r){const{src:i}=e.embedData,{editor:o}=this.options;return o.doc.buildResourceUrl(i,{syncNewResources:async(s,l)=>{var d,h;if(!r)return;await o.doc.addResources([s]);const c=(h=(d=o.doc).getServerMeta)==null?void 0:h.call(d).appId;if(l!==e.embedData.src&&c&&e.embedData.src.includes(c)){const C=J(r);if(C&&!o.readonly&&o.isBlockWritable(C)){const E=mt.default(e);E.embedData.src=s,o.updateBlockData(C,E)}}}})}setFullScreen(){p(Je,this.mediaContainer,"The media element not exist"),z(this.mediaContainer,"full-screen")}removeFullScreen(){p(Je,this.mediaContainer,"The media element not exist"),ot(this.mediaContainer,"full-screen")}updateBlockAlign(e,r){const i=J(r);p(Je,i,"The block element not exist");const{align:o}=e;e.embedType==="video"&&(i.hasAttribute("data-style-align")&&i.removeAttribute("data-style-align"),i.setAttribute("data-style-align",o))}render(e,r){const{src:i}=e.embedData;(!this.mediaContainer||!r.contains(this.mediaContainer))&&(this.mediaContainer=B("div",["media"],r)),this.updateBlockAlign(e,r),Ott(i)?i===Mf.Empty&&this.renderEmpty(e):this.renderMediaElement(e,r)}setAbstract(e){this.abstract=e}}I("media-embed");const Ptt="left";class OS{constructor(){m(this,"handleInsertEmptyEmbed",async(t,e)=>{var C;const{containerId:r,blockIndex:i}=e;let o;(C=e.data)!=null&&C.file&&(o=e.data.file);const s=Mtt(t,this.embedType);if(o=o!=null?o:await ha(s,{}),!o)return null;const{mediaType:l}=this.getAbstract();try{Utt(o,t,l)}catch{return null}const c={id:tt(),type:"embed",embedType:this.embedType,embedData:{src:Mf.Empty}};l==="video"&&(c.align=Ptt);const d=t.insertBlock(r,i,c);return await this.getMedia(t,c.id).handleUploadFile(o),d})}getMedia(t,e){const r=t.addCustom(`media-${e}`,()=>new Ntt({editor:t,createMediaElement:this.createMediaElement,updateMediaElement:this.updateMediaElement,createProgressElement:this.createProgressElement,updateProgressElement:this.updateProgressElement}));return r.setAbstract({...this.getAbstract()}),r}getOptions(){const{menuItem:t,mediaIcon:e,mediaName:r,order:i,group:o}=this.getAbstract();return{name:r,insertEmbedCommandItems:[{id:`insert-${this.embedType}`,name:t,icon:e,order:i,group:o,subText:yn(`insert-${this.embedType}`)}],handleInsertEmptyEmbed:this.handleInsertEmptyEmbed}}createEmbedContent(t,e,r){const{id:i}=r;this.getMedia(t,i).render(r,e)}handleUpdateBlock(t,e,r){const{id:i}=r,o=this.getMedia(t,i),s=Ot(e);return o.render(r,s),!0}handleDeleteBlock(t,e){const r=e.id,i=this.getMedia(t,r);i.removeAllListeners(),i.destroy()}convertTo(t,e,r,i){const o=e.embedData,s=t.doc.buildResourceUrl(o.src,{withToken:!0});return i==="html"?`<${o.type} src="${s}" />`:i==="markdown"?`![${o.src}](${s})`:s}}function NS(n,t){const e=B("div",["uploading-progress-mask"],n),r=B("div",["uploading-progress-bar"],e),i=B("div",["uploading-progress-bar-value"],r);i.style.width=`${t}%`}function PS(n,t){const e=n.querySelector(".uploading-progress-bar-value");e&&(e.style.width=`${t}%`)}const Ftt=I("media-audio");class Ktt extends OS{constructor(){super(...arguments);m(this,"embedType",Xr.AUDIO);m(this,"updateProgressElement",PS);m(this,"createMediaElement",(e,r,i,o)=>{const s=B("div",["audio-container","embed-hover-content","embed-selected-content"],r),l=B("audio",[],s);return l.innerHTML="Your browser does not support the <code>audio</code> element.",l.controls=!0,l.src=o,setTimeout(()=>{this.getMedia(e,i.id).setFullScreen()}),l})}getAbstract(){return{mediaIcon:X2,mediaName:D.t(`media.${Xr.AUDIO}.menuItem`),menuItem:D.t(`media.${Xr.AUDIO}.menuItem`),order:800,mediaType:Xr.AUDIO,group:"common"}}getBlockProperties(){return{abstract:`${D.t(`media.${Xr.AUDIO}.abstract`)}`}}updateMediaElement(e,r,i,o){const s=r.querySelector(":scope .audio-container > audio");return p(Ftt,s,"The media element not exist"),s.src!==o&&(s.src=o),s}createProgressElement(e,r){const i=B("audio",[],e);i.innerHTML="Your browser does not support the <code>audio</code> element.",i.controls=!0,i.src="about:blank",NS(e,r)}}const Vtt=new Ktt;I("video-resizer");function FS(n){return n&&ge(n)&&We(n)==="video"}const $tt=50;class IA{constructor(t){m(this,"currentResizableElement",null);m(this,"resizing",!1);m(this,"handleHoveringBlockChange",(t,e)=>{if(!this.resizing&&!window.isDragging&&(e&&FS(e)&&this.disableBlockResize(e),t&&FS(t)&&this.editor.isBlockWritable(t))){const r=this.getVideoElement(t);if(!r)return;this.enableBlockResize(t,r)}});m(this,"handleResizing",(t,e)=>{if(this.resizing=!0,!this.currentResizableElement)return;const r=t.getBlock();if(!r)return;const i=r.getBoundingClientRect().width,o=Math.min(Math.max(e.width,$tt),i);this.currentResizableElement.style.width=`${o}px`,this.currentResizableElement.style.pointerEvents="none"});m(this,"handleResized",t=>{this.resizing=!1;const e=t.getBlock();if(!this.currentResizableElement||!e)return;const r=this.editor.getBlockData(e),{width:i}=this.currentResizableElement.getBoundingClientRect();this.currentResizableElement.style.pointerEvents="auto",this.editor.updateBlockData(e,{...r,width:i})});this.editor=t,Te.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){this.currentResizableElement=null,Te.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}getVideoElement(t){return Ot(t).querySelector(":scope .video-container > video")}updateResizer(t){const e=this.editor.findCustom(`${lt(t)}-resizer`);e&&e.updateResizer()}disableBlockResize(t){const e=this.editor.findCustom(`${lt(t)}-resizer`);e&&e.disableResize()}enableBlockResize(t,e){const r=this.editor.addCustom(`${lt(t)}-resizer`,()=>new df(this.editor,{resize:["top-left","top-right","bottom-left","bottom-right"]}));r.enableResize(t,e),r.removeListener("resizing",this.handleResizing),r.removeListener("resized",this.handleResized),r.addListener("resizing",this.handleResizing),r.addListener("resized",this.handleResized),this.currentResizableElement=e}}const Htt=I("video");class jtt extends OS{constructor(){super(...arguments);m(this,"embedType",Xr.VIDEO);m(this,"updateProgressElement",PS);m(this,"createMediaElement",(e,r,i,o)=>{const s=B("div",["video-container","embed-selected-content","drag-preview-element"],r),l=B("video",[],s);return l.innerHTML="Your browser does not support the <code>video</code> element.",l.controls=!0,l.src=o,l.addEventListener("canplay",()=>{e.addCustom("video-resizer",()=>new IA(e)),this.getMedia(e,i.id).removeListener("mediaError",this.handleMediaError),this.getMedia(e,i.id).addListener("mediaError",this.handleMediaError),this.getMedia(e,i.id).removeFullScreen()}),i.width&&(l.style.width=`${i.width}px`),l});m(this,"createProgressElement",(e,r,i)=>{const o=B("video",["progress-video"],e);o.innerHTML="Your browser does not support the <code>audio</code> element.",o.controls=!0,NS(e,r),da(i).then(s=>{const l=e.querySelector(".progress-video");l&&i1(e)&&(l.src=s)})})}getAbstract(){return{mediaName:D.t(`media.${Xr.VIDEO}.menuItem`),mediaIcon:Y2,menuItem:D.t(`media.${Xr.VIDEO}.menuItem`),order:700,mediaType:Xr.VIDEO,group:"common"}}getBlockProperties(){return{abstract:`${D.t(`media.${Xr.VIDEO}.abstract`)}`}}handleMediaError(e,r,i){const o=e.addCustom("video-resizer",()=>new IA(e)),s=e.getBlockById(i);o.disableBlockResize(s)}updateMediaElement(e,r,i,o){const s=r.querySelector(":scope .video-container > video");p(Htt,s,"The media element not exist"),s.src!==o&&(s.src=o),i.width?s.style.width=`${i.width}px`:s.style.width="";const l=e.getBlockById(i.id);return setTimeout(()=>{e.addCustom("video-resizer",()=>new IA(e)).updateResizer(l)}),s}}const ztt=new jtt,KS=[pE,BE,TE,Pk],DA=[SS,GJ,ttt,ctt,Ctt,u$,Rtt,ztt,Vtt,bW,sS,nQ],VS=[Qk,cS,K4];function Gtt(n,t,e){var i,o,s,l;oi.level=(i=e.logLevel)!=null?i:Ds.DEBUG;const r=Ru(n,t,{components:{blocks:[...KS,...((o=e==null?void 0:e.components)==null?void 0:o.blocks)||[]],embeds:[...DA,...((s=e.components)==null?void 0:s.embeds)||[]],boxes:[...VS,...((l=e.components)==null?void 0:l.boxes)||[]],textRenders:[new ZC],options:{...e.componentsOptions}}});return r.readonly=!0,r.addCustom("heading-collapse",()=>new HE(r)),r.addCustom("editor-tooltip",()=>new M0(r)),r.addListener("clickLink",(c,d,h)=>{var E;if((E=e==null?void 0:e.events)!=null&&E.onClickLink){e.events.onClickLink(c,d,h);return}const C=h.getAttribute("link");C&&(c.readonly||d.ctrlKey||d.metaKey)&&window.open(C,"_blank")}),r}class $S{constructor(t){this.createOptions=t,t.lang&&D.setLang(t.lang)}createHistoryEditor(t,e){return Gtt(t,e,this.createOptions)}}I("create-editor");function HS(n,{root:t,childDoc:e,doc:r}){var h,C;e.uploadResource=r.uploadResource.bind(r),e.buildResourceUrl=r.buildResourceUrl.bind(r);const i=n.getComponentOptions("comment"),o={image:{defaultAlign:"left"},table:{locatingContainer:t,hideCellMenu:!0,hideToolbar:!0},...i==null?void 0:i.componentsOptions},s=[];n.editorBlocks.forEach(E=>{E.blockType==="text"||E.blockType==="embed"||s.push(E)});const l=[];n.editorEmbeds.forEach(E=>{l.push(E)});const c=[];n.editorBoxes.forEach(E=>{E.boxType==="text"||E.boxType==="br"||E.boxType==="image"||E.boxType==="anchor"||c.push(E)});const d=Ru(t,e,{shortcuts:[Nh],components:{blocks:s,commandProviders:[new m0],decorators:[new V0],embeds:l,boxes:c,options:o}});if(d.input.addHandler(new H0),d.input.addHandler(new XE(d)),d.input.addHandler(new eA(d)),d.input.addHandler(new dY(d)),d.input.addHandler(new W0),d.addCustom("image-paste-handler",()=>new qE(d)),(h=n.options.componentsOptions)!=null&&h.mention){const E=n.options.componentsOptions.mention;d.addCustom("mention",()=>new aS(d,{...E}))}if((C=n.options.componentsOptions)!=null&&C.comment){const E=n.options.componentsOptions.comment;E.onCommentEditorClick&&d.addListener("click",E.onCommentEditorClick)}return d}function Wtt(n,t){const e=Array.from(n.rootContainer.querySelectorAll(`[comment-${t.toLocaleLowerCase()}="${t}"]`)),r=new Set;e.forEach(i=>{const o=J(i);o&&r.add(o)}),r.forEach(i=>{hY(n,i,t)})}class qtt{constructor(t){m(this,"listeners",new Set);m(this,"doc");this.editor=t,this.doc=this.editor.doc.externalDoc,this.doc.registerCallback(this)}getComments(){return this.doc.getComments()}getComment(t){return this.doc.getComment(t)}getCommentDoc(t){return this.doc.getCommentDoc(t)}localCreateComment(t,e){this.doc.localCreateComment(t,e)}localDeleteComment(t){const e=this.getComment(t);this.doc.localDeleteComment(t);const r=e.groupId;this.getComments().filter(o=>o.groupId===r).length===0&&Wtt(this.editor,r)}localUpdateComment(t,e){this.doc.localUpdateComment(t,e)}onCreateComment(t,e){Array.from(this.listeners.values()).forEach(r=>r.onCreateComment(t,e))}onDeleteComment(t,e){Array.from(this.listeners.values()).forEach(r=>r.onDeleteComment(t,e))}onUpdateComment(t,e){Array.from(this.listeners.values()).forEach(r=>r.onUpdateComment(t,e))}addListener(t){this.listeners.add(t)}removeListener(t){this.listeners.delete(t)}createCommentEditor(t,e){return HS(this.editor,{root:t,childDoc:e,doc:this.doc})}allowEdit(t){return t.userId===this.doc.getUser().userId}}class Xtt{constructor(t,e){m(this,"listeners",new Set);this.editor=t,this.localDoc=e}get doc(){return this.localDoc.toJSON()}getComments(){return Object.values(this.doc.comments)}getComment(t){return this.doc.comments[t]}getCommentDoc(t){const e=this.doc.comments[t];return Yp(e)}addListener(t){this.listeners.add(t)}removeListener(t){this.listeners.delete(t)}localCreateComment(t,e){}localDeleteComment(t){}localUpdateComment(t,e){}createCommentEditor(t,e){return HS(this.editor,{root:t,childDoc:e,doc:this.localDoc})}allowEdit(t){return t.userId===this.localDoc.getUser().userId}}const Ytt={placeholder:{common:{title:"\u8BF7\u8F93\u5165\u6807\u9898",readonlyTitle:"\u8BF7\u8F93\u5165\u6807\u9898",content:"\u70B9\u51FB + \uFF0C\u6216\u8F93\u5165 / \u5FEB\u6377\u63D2\u5165\u7EC4\u4EF6",contentInTable:"\u8F93\u5165 / \u5FEB\u6377\u63D2\u5165\u7EC4\u4EF6"},local:{readonlyTitle:"\u672A\u547D\u540D"}},copyCutProperty:{copy:"\u590D\u5236",cut:"\u526A\u5207",unsafeEnvTips:"\u7531\u4E8E\u5F53\u524D http \u8BBF\u95EE\u73AF\u5883\u4E0B\u7684\u9650\u5236\uFF0C\u8BF7\u4F7F\u7528\u5FEB\u6377\u952E({shortCut}) {operation}",limitedEnvTips:"\u7531\u4E8E\u6D4F\u89C8\u5668\u9650\u5236\uFF0C\u8BF7\u4F7F\u7528 {shortCut} \u7C98\u8D34"}},Qtt={placeholder:{common:{title:"Enter a title",readonlyTitle:"Enter a title",content:'Click "+", or enter "/" to insert components quickly',contentInTable:'Enter "/" to insert components quickly'},local:{readonlyTitle:"Untitled"}},copyCutProperty:{copy:"Copy",cut:"Cut",unsafeEnvTips:"Due to the limitations of the current http access environment, please use the shortcut ({shortCut}) {operation}",limitedEnvTips:"Press {shortCut} to paste due to browser restrictions"}},Jtt={placeholder:{common:{title:"\u30BF\u30A4\u30C8\u30EB\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044",readonlyTitle:"\u30BF\u30A4\u30C8\u30EB\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044",content:"\u300C+\u300D\u3092\u30AF\u30EA\u30C3\u30AF\u3059\u308B\u304B\u3001\u300C/\u300D\u3092\u5165\u529B\u3059\u308B\u3068\u3001\u30B3\u30F3\u30DD\u30FC\u30CD\u30F3\u30C8\u304C\u7D20\u65E9\u304F\u633F\u5165\u3067\u304D\u307E\u3059",contentInTable:"\u300C/\u300D\u3092\u5165\u529B\u3059\u308B\u3068\u3001\u30B3\u30F3\u30DD\u30FC\u30CD\u30F3\u30C8\u304C\u7D20\u65E9\u304F\u633F\u5165\u3067\u304D\u307E\u3059"},local:{readonlyTitle:"\u7121\u984C"}},copyCutProperty:{copy:"\u8907\u88FD",cut:"\u5207\u308B",unsafeEnvTips:"HTTP\u74B0\u5883\u306E\u5236\u7D04\u306B\u3088\u308A\u3001{operation}\u3059\u308B\u306B\u306F\u3001\u30B7\u30E7\u30FC\u30C8\u30AB\u30C3\u30C8({shortCut}) \u3092\u3054\u4F7F\u7528\u304F\u3060\u3055\u3044",limitedEnvTips:"\u30D6\u30E9\u30A6\u30B6\u30FC\u306E\u5236\u9650\u306B\u3088\u308A\u3001\u300C{shortCut}\u300D\u3092\u4F7F\u7528\u3057\u3066\u8CBC\u308A\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044"}};D.mergeLang({"zh-CN":Ytt,"en-US":Qtt,"ja-JP":Jtt});const Ztt="UEsDBBQABgAIAAAAIQBk9WPugQEAACkGAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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){return new Promise((t,e)=>{const r=new Image;r.onload=()=>{t({width:r.naturalWidth,height:r.naturalHeight})},r.onerror=e,r.src=n})}async function jS(n,t){if(n.width&&n.height)return{width:n.width,height:n.height,buffer:t};try{const e=await da(new File([t],"",{})),r=await net(e);return r.width===void 0||r.height===void 0?{width:345,height:230,buffer:t}:n.width||n.height?{width:n.width||r.width*n.height/r.height,height:n.height||r.height*n.width/r.width,buffer:t}:{width:r.width,height:r.height,buffer:t}}catch(e){eet.error(e);return}}function ret(n,t){let e=n.filter(s=>s!=null);const r=t-(e.length-1)*20,i=.87,o=e.reduce((s,l)=>s+l.width,0);return o>r&&(e=e.map(s=>({width:s.width*r/o,height:s.height*r/o,buffer:s.buffer}))),e.map(s=>({width:s.width*i,height:s.height*i,buffer:s.buffer}))}function iet(n,t,e){if(!e||typeof e!="object")return;const r=e,i=n.filter(s=>s!=null),o=t-(i.length-1)*20;i.forEach((s,l)=>{if(i.length===1&&r.widthPercent){const d=r.widthPercent,h=s.width;s.width=o*(d/100),s.height*=s.width/h;return}const c=`${l}_flex`;if(r[c]){const d=r[c],h=s.width;s.width=o*d,s.height*=s.width/h}})}function zS(n=[0,1,2,3,4,5,6,7],t=1){return n.map(e=>{let r;switch(e%3){case 0:r=Ct.LevelFormat.DECIMAL;break;case 1:r=Ct.LevelFormat.LOWER_LETTER;break;default:r=Ct.LevelFormat.LOWER_ROMAN;break}return{level:e,format:r,text:`%${e+1}. `,alignment:Ct.AlignmentType.START,start:t,style:{paragraph:{indent:{left:Ct.convertInchesToTwip(.3*(e+1)),hanging:Ct.convertInchesToTwip(.2)}}}}})}function oet(){return[0,1,2,3,4,5,6,7].map(n=>{let t;switch(n%3){case 0:t="\u2022";break;case 1:t="\u25E6";break;default:t="\u25AA";break}return{level:n,format:Ct.LevelFormat.BULLET,text:t,alignment:Ct.AlignmentType.START,style:{paragraph:{indent:{left:Ct.convertInchesToTwip(.3*(n+1)),hanging:Ct.convertInchesToTwip(.2)}}}}})}function set(){return[0,1,2,3,4,5,6,7].map(n=>({level:n,format:Ct.LevelFormat.BULLET,text:"\u2611",alignment:Ct.AlignmentType.START,style:{paragraph:{indent:{left:Ct.convertInchesToTwip(.3*(n+1)),hanging:Ct.convertInchesToTwip(.2)}}}}))}function aet(){return[0,1,2,3,4,5,6,7].map(n=>({level:n,format:Ct.LevelFormat.BULLET,text:"\u2610",alignment:Ct.AlignmentType.START,style:{paragraph:{indent:{left:Ct.convertInchesToTwip(.3*(n+1)),hanging:Ct.convertInchesToTwip(.2)}}}}))}var Uf=(n=>(n.NUMBERING="number-numbering-reference",n.BULLET="number-bullet-reference",n.CHECKED="checked-bullet-reference",n.UNCHECKED="unchecked-bullet-reference",n))(Uf||{});const cet=[{levels:zS(),reference:"number-numbering-reference"},{levels:oet(),reference:"number-bullet-reference"},{levels:set(),reference:"checked-bullet-reference"},{levels:aet(),reference:"unchecked-bullet-reference"}];function uet(n){switch(n){case"style-color-0":return"d83931";case"style-color-1":return"de7802";case"style-color-2":return"dc9b04";case"style-color-3":return"2ea121";case"style-color-4":return"245bdb";case"style-color-5":return"6425d0";case"style-color-6":return"8f959e";default:return}}function fet(n){switch(n){case"style-bg-color-1":case"style-bg-color-2":case"style-bg-color-8":case"style-bg-color-9":return"yellow";case"style-bg-color-0":case"style-bg-color-5":return"magenta";case"style-bg-color-3":return"green";case"style-bg-color-4":case"style-bg-color-11":return"blue";case"style-bg-color-6":return"lightGray";case"style-bg-color-7":return"red";case"style-bg-color-10":return"darkGreen";case"style-bg-color-12":return"darkMagenta";case"style-bg-color-13":return"darkGray";default:return}}function det(n){switch(n){case"style-bg-color-0":return"fbbab6";case"style-bg-color-1":return"ffdcb0";case"style-bg-color-2":return"fff7a0";case"style-bg-color-3":return"ceefc5";case"style-bg-color-4":return"d1ddfb";case"style-bg-color-5":return"d9cbf8";case"style-bg-color-6":return"eaeaea";case"style-bg-color-7":return"fe837c";case"style-bg-color-8":return"ffbd6a";case"style-bg-color-9":return"ffe662";case"style-bg-color-10":return"a8f393";case"style-bg-color-11":return"98b5ff";case"style-bg-color-12":return"b394f8";case"style-bg-color-13":return"b1b1b1";default:return}}const het=/rgb\((\d+),\s*(\d+),\s*(\d+)\)/;function GS(n){if(typeof n=="string"&&n.length>0){if(n[0]==="#")return n.substring(1);const t=n.match(het);if(t){const e=s=>{let l=Number(s).toString(16);return l.length<2&&(l=`0${l}`),l},r=e(t[1]),i=e(t[2]),o=e(t[3]);return`${r}${i}${o}`}if(n==="red")return"FF0000";if(n==="green")return"00FF00";if(n==="blue")return"0000FF"}}function ln(n,t){if(n&&n.attributes&&n.attributes[t])return n.attributes[t];if(n&&n.attributes&&n.attributes.box&&n.attributes.inputType&&t==="style-underline")return!0}function WS(n,t,e){for(let r=0;r<=e;++r){const i=`${t}${r}`;if(ln(n,i))return i}}function Cm(n,t,e){n.attributes=n.attributes||{},n.attributes[t]=e}function _A(n){return n==="image"||n==="drawio"||n==="plantuml"||n==="mermaid"||n==="flowchart"}function qS(n){return n&&n.startsWith("//")?`https:${n}`:n&&!n.startsWith("http://")&&!n.startsWith("https://")?`https://${n}`:n}function met(n){const t=ln(n,"inlineStyle");if(t==null)return;const e=t.split(";");for(const r of e){const i=r.split(":");if(i.length!==2)continue;const o=i[0].trim().toLowerCase(),s=i[1].trim().toLowerCase();o==="font-size"&&Cm(n,"inline-style-font-size",s),o==="color"&&Cm(n,"inline-style-color",s),o==="background-color"&&Cm(n,"inline-style-background-color",s),o==="font-family"&&Cm(n,"inline-style-font-family",s)}}function get(n,t){if(t==null)return n==null?void 0:n.normal;if(n)return n[`heading${t}`]}function pet(n){const t=`${ln(n,"inline-style-font-size")}`;if(t&&t.indexOf("px")>0)return+t.replace(/px/g,"")}function Cet(n){if(n.attributes&&n.attributes.box&&n.attributes.text)return` ${n.attributes.text} `;if(n.attributes&&n.attributes.box&&n.attributes.inputType)return n.attributes.value?`${n.attributes.value}`:" "}function Eet(n){if(n.attributes&&n.attributes.box&&n.attributes.text)return` @${n.attributes.text} `}function Aet(n){return ln(n,"inline-style-font-family")}function xet(n){const t=ln(n,"inline-style-background-color");return GS(t)}function bet(n){const t=ln(n,"inline-style-color");return GS(t)}function vet(n){met(n);const t=ln(n,"type")==="mention";return{box:n.attributes&&n.attributes.box?n.attributes:void 0,inlineCode:!!ln(n,"style-code"),link:qS(ln(n,"link")),size:pet(n),text:t?Eet(n):Cet(n)||n.insert,bold:!!ln(n,"style-bold"),underline:!!ln(n,"style-underline"),italics:!!ln(n,"style-italic"),strike:!!ln(n,"style-strikethrough"),superScript:!!ln(n,"style-super"),subScript:!!ln(n,"style-sub"),math:ln(n,"type")==="math"?ln(n,"src"):void 0,mention:t,fontFamily:Aet(n),background:xet(n),color:t?"338fe5":uet(WS(n,"style-color-",6))||bet(n),highlight:WS(n,"style-bg-color-",13)}}function Bet(){return[new Ct.Paragraph({border:{top:{color:"auto",style:Ct.BorderStyle.DASHED,size:4,space:1}},spacing:{before:300}}),new Ct.Paragraph({spacing:{line:0}})]}function Tet(){return new Ct.Paragraph({children:[new Ct.TextRun({text:"[\u89C6\u9891\u6682\u4E0D\u652F\u6301\u5BFC\u51FA]",shading:{type:Ct.ShadingType.CLEAR,color:"FFFFFF",fill:"CCCCCC"}})]})}function yet(){return new Ct.Paragraph({children:[new Ct.TextRun({text:"[\u97F3\u9891\u6682\u4E0D\u652F\u6301\u5BFC\u51FA]",shading:{type:Ct.ShadingType.CLEAR,color:"FFFFFF",fill:"CCCCCC"}})]})}function ket(n,t){return new Ct.Paragraph({children:[new Ct.ExternalHyperlink({children:[new Ct.TextRun({style:"Hyperlink",text:t||n})],link:n})]})}function XS(n){if(n.heading!=null)return`Heading${n.heading}`}function YS(n){if(n.alignment!=null){if(n.alignment==="center")return Ct.AlignmentType.CENTER;if(n.alignment==="right")return Ct.AlignmentType.RIGHT;if(n.alignment==="left")return Ct.AlignmentType.LEFT}}function Ret(n){if(n.indent)return{left:Ct.convertInchesToTwip(.3*n.indent-.2)};if(n.padding)return{left:Ct.convertInchesToTwip(.3*n.padding)}}function wet(n){return{type:Ct.ShadingType.CLEAR,color:"FFFFFF",fill:n}}function Let(n){const t=n.split(",");if(t.length!==0)return t[0].trim()}function QS(n,t){let e;e=n.inlineCode?"InlineCode":void 0,e=n.link?"Hyperlink":e;const r=n.size||t,i=r!=null?Math.floor(r*1.5+.5):void 0;return new Ct.TextRun({text:n.text,bold:n.bold||void 0,underline:n.underline?{type:Ct.UnderlineType.SINGLE}:void 0,italics:n.italics||void 0,strike:n.strike||void 0,superScript:n.superScript||void 0,subScript:n.subScript||void 0,size:i,style:e,font:n.fontFamily?Let(n.fontFamily):void 0,shading:n.background?wet(n.background):void 0,color:n.color,highlight:fet(n.highlight)})}function Iet(n,t){if(n.link)return new Ct.ExternalHyperlink({children:[QS(n,t)],link:n.link})}async function JS(n,t,e,r,i){const[o]=await i(n,t,e);if(o==null)return;const s=await jS({width:r||0,height:0,src:e},o);return new Ct.ImageRun({data:o,transformation:{width:(s==null?void 0:s.width)||100,height:(s==null?void 0:s.height)||20}})}function Det(n){if(n.heading||n.heading)return n.heading}function _et(n){if(n.align&&(n.align==="center"||n.align==="right"||n.align==="left"))return n.align}function Met(n){if(n.textOnly===!0&&n.level!=null)return n.level}async function Uet(n,t){var r;const e=[];if(n.text&&Array.isArray(n.text)){for(let i=0;i<n.text.length;i++){const o=n.text[i];if(((r=o.attributes)==null?void 0:r.box)===!0&&t){const s=await t(o);if(s){n.text.splice(i+1,0,...s);continue}}e.push(vet(o))}return e}}function Oet(n){if(n.type==="list"&&n.textOnly!==!0)return{checkbox:n.checkbox,groupId:n.groupId,ordered:!!n.ordered,level:n.level||1,start:n.start||0}}function Net(n,t){if(n.type==="embed"&&n.embedType&&_A(n.embedType)&&n.embedData&&n.embedData.src)return n.embedData.src.split("|").map(r=>{const i=t(r),o=n.embedData[`${i}_width`],s=n.embedData[`${i}_height`];return{src:r,width:o,height:s}})}function Pet(n){if(n.padding)return n.padding}function Fet(n){return!!(n.type==="embed"&&n.embedType&&_A(n.embedType)&&n.embedData&&n.embedData.src)}async function Em(n,t,e){return{quoted:!!n.quoted,heading:Det(n),alignment:_et(n),indent:Met(n),padding:Pet(n),texts:await Uet(n,e),list:Oet(n),images:Net(n,t),border:Fet(n)}}async function Ket(n,t,e,r){const i=[];if(!n.children)return[];for(const o of n.children){const s=[];for(const l of t.blocks[o])s.push(await Em(l,e,r));i.push(s)}return i}const Vet=I("to-docx");function $et(n,t){return Array(n).fill(0).map(()=>Array(t).fill(0).map(()=>({cellId:void 0,color:void 0,from:void 0,rowSpan:1,colSpan:1,width:0,originalWidth:void 0,align:void 0})))}function Het(n,t,e,r){const i=!!n.hasColTitle,o=!!n.hasRowTitle,s=!!n.isStripeStyle,l="F5F8FB";for(let c=0;c<t;c++)for(let d=0;d<e;d++)(i&&d===0||o&&c===0||s&&c%2===1)&&(r[c][d].color=l)}function jet(n){p(Vet,n.children,"no table children");const t=n.rows,e=n.cols,r=n.colsWidth;if(r)for(let s=0;s<r.length;s++)r[s]===0&&(r[s]=100);const i=$et(t,e);let o=0;for(let s=0;s<t;++s)for(let l=0;l<e;++l){if(i[s][l].originalWidth=r?r[l]:void 0,i[s][l].from!==void 0)continue;const c=n.children[o];o+=1,i[s][l].cellId=c,i[s][l].color=det(n[`${c}_background`]),i[s][l].width=r?r[l]:100,i[s][l].align=n[`${c}_align`];const d=n[`${c}_rowSpan`]||1,h=n[`${c}_colSpan`]||1;if(i[s][l].rowSpan=d,i[s][l].colSpan=h,d>1||h>1){let C=0;for(let E=0;E<d;E++)for(let x=0;x<h;x++)E===0&&(C+=r?r[l+x]:80),!(E===0&&x===0)&&(i[s+E][l+x].from=[s,l]);i[s][l].width=C}}return Het(n,t,e,i),i}async function zet(n,t,e,r,i,o,s,l,c,d){async function h(x){if(l){const v=await l(i,o,x);if(v){await r.addDoc(n,v,d);return}}if(x.type==="text"||x.textOnly===!0){const v=await Em(x,s,c);await r.addTextBlock(v);return}if(x.type==="code"){const v=await Ket(x,e,s,c);await r.addCodeBlockObject(v);return}if(x.type==="list"&&x.textOnly!==!0){const v=await Em(x,s,c);await r.addListBlockObject(n,v);return}if(x.type==="embed"&&x.embedType){const v=x,k=v.embedData,L=v.embedType;if(_A(L)){const M=await Em(x,s,c);await r.addImagesBlockObject(x,M,d)}else x.embedType==="hr"?r.addSeparatorBlock():x.embedType==="video"?r.addVideoPlaceholder():x.embedType==="audio"?r.addAudioPlaceholder():x.embedType==="webpage"?r.addHyperlinkParagraph(qS(k.src),k.title):r.addOtherEmbedBlock(L,x.embedData);return}if(x.type==="table"){let v=[];if(x.colsWidth)v=x.colsWidth;else{const L=x.cols;v=new Array(L);for(let M=0;M<v.length;M++)v[M]=100;x.colsWidth=v}const k=jet(x);await r.addTableMatrix(v,k,e),r.addEmptyParagraph()}}function C(x){const v=[];for(const{type:k,data:L}of x.embedData.exportSpec){if(k==="text"){const M={id:tt(),text:[{insert:L}],type:"text"};v.push(M);continue}if(k==="image"){const M={id:tt(),type:"embed",embedType:"image",align:"left",embedData:{src:L}};v.push(M);continue}if(k==="link"){const M={id:tt(),type:"embed",embedType:"webpage",embedData:{src:L.url,title:L.title}};v.push(M);continue}}return v}function E(x){var v;return(v=x==null?void 0:x.embedData)!=null&&v.exportSpec?C(x):[x]}for(const x of t)for(const v of E(x))await h(v)}function Get(){return{listMaxInst:1,listInstMap:{},listRefMap:{},levelConfigs:[]}}const Wet=I("to-docx");class qet{constructor(t,e,r,i,o,s){m(this,"paragraphs");this.appId=t,this.docId=e,this.state=r,this.readImageFunc=i,this.convertBlocksFunc=o,this.defaultFontSize=s,this.paragraphs=[]}async addTextBlock(t){this.paragraphs.push(new Ct.Paragraph({heading:XS(t),alignment:YS(t),children:await this.paragraphsFromBlockTexts(t),indent:Ret(t)}))}async addEmptyImagePlaceHolder(){this.paragraphs.push(new Ct.Paragraph({text:`[${D.t("docx.imageExportFailed")}]`,shading:{type:Ct.ShadingType.CLEAR,color:"FFFFFF",fill:"CCCCCC"}}))}async paragraphsFromBlockTexts(t){if(t.texts==null)return;const e=get(this.defaultFontSize,t.heading),r=[];for(const i of t.texts){if(i.link){const o=Iet(i,e);o&&r.push(o);continue}if(i.box&&i.box.type&&i.box.type==="br"){r.push(new Ct.TextRun({text:"",break:1}));continue}if(i.box&&i.box.type&&i.box.type==="image"){const o=await JS(this.appId,this.docId,i.box.src,i.box.width,this.readImageFunc);o&&r.push(o);continue}if(i.math){const o=await JS(this.appId,this.docId,i.math,0,this.readImageFunc);o&&r.push(o);continue}r.push(QS(i,e))}return r}async addCodeBlockObject(t){for(const e of t)for(const r of e){const i={style:Ct.BorderStyle.SINGLE,color:"#DEDEDE"};this.paragraphs.push(new Ct.Paragraph({style:"Code",border:{left:{...i},right:{...i},top:{...i},bottom:{...i}},children:await this.paragraphsFromBlockTexts(r)}))}}async addListBlockObject(t,e){if(e.list==null)return;let r;const i=e.list.checkbox?`${t}-${e.list.groupId}-${e.list.checkbox}`:`${t}-${e.list.groupId}`;if(this.state.listInstMap[i])r=this.state.listInstMap[i];else if(r=this.state.listMaxInst,this.state.listMaxInst+=1,this.state.listInstMap[i]=r,e.list.start>0&&e.list.ordered){const s=`number-numbering-reference-${r}`,l=zS([e.list.level-1],e.list.start);this.state.levelConfigs.push({levels:l,reference:s,inst:r}),this.state.listRefMap[i]=s}else e.list.ordered?this.state.listRefMap[i]=Uf.NUMBERING:e.list.checkbox&&e.list.checkbox==="checked"?this.state.listRefMap[i]=Uf.CHECKED:e.list.checkbox&&e.list.checkbox==="unchecked"?this.state.listRefMap[i]=Uf.UNCHECKED:this.state.listRefMap[i]=Uf.BULLET;const o=XS(e);e.texts&&this.paragraphs.push(new Ct.Paragraph({heading:o,children:await this.paragraphsFromBlockTexts(e),numbering:{reference:this.state.listRefMap[i],level:e.list.level-1,instance:r}}))}imageDimWithBufferToImageRun(t){return new Ct.ImageRun({data:t.buffer,transformation:{width:t.width,height:t.height}})}async addImagesBlockObject(t,e,r){if(e.images==null){if(t.type==="embed"&&t.embedType==="image"){const{src:c}=t.embedData;c||this.addEmptyImagePlaceHolder()}return}const i=[],o=await Promise.all(e.images.map(async c=>{const[d,h]=await this.readImageFunc(this.appId,this.docId,c.src);if(d){const C=await jS(c,d);if(C)return C}i.push(h)}));iet(o,r,t.embedData);const s=ret(o,r),l={style:Ct.BorderStyle.SINGLE,color:"#DEDEDE"};s.length&&this.paragraphs.push(new Ct.Paragraph({border:e.border?{left:{...l},right:{...l},top:{...l},bottom:{...l}}:void 0,alignment:YS(e)||Ct.AlignmentType.CENTER,children:s.map(c=>this.imageDimWithBufferToImageRun(c)).flatMap((c,d,h)=>c==null?[]:h.length-1!==d?[c,new Ct.TextRun({text:" "})]:c)})),i.forEach(c=>{this.addHyperlinkParagraph(c)})}addSeparatorBlock(){Bet().forEach(t=>this.paragraphs.push(t))}addEmptyParagraph(){this.paragraphs.push(new Ct.Paragraph(""))}addVideoPlaceholder(){this.paragraphs.push(Tet())}addAudioPlaceholder(){this.paragraphs.push(yet())}addHyperlinkParagraph(t,e){t!=null&&this.paragraphs.push(ket(t,e))}async addTableMatrix(t,e,r){const i=t.map(o=>o!==0?o*15:1500);this.paragraphs.push(new Ct.Table({rows:await this.generateTableRows(e,r),columnWidths:i}))}async generateRowCells(t,e){const r=[];for(const i of t){const o=i.cellId;if(o===void 0)continue;const s=i.width*.9;r.push(new Ct.TableCell({children:await this.convertBlocksFunc(o,e.blocks[o],e,this.appId,this.docId,this.state,s),columnSpan:i.colSpan,rowSpan:i.rowSpan,width:{type:Ct.WidthType.DXA,size:i.width*15},shading:i.color?{fill:i.color,type:Ct.ShadingType.CLEAR,color:"auto"}:void 0}))}return r}async generateTableRows(t,e){const r=[];for(const i of t)r.push(new Ct.TableRow({children:await this.generateRowCells(i,e)}));return r}async addDoc(t,e,r){const i=await this.convertBlocksFunc(t,e.blocks.root,e,this.appId,this.docId,this.state,r);i&&(this.paragraphs=this.paragraphs.concat(i))}async addOtherEmbedBlock(){}}class Xet{constructor(t,e,r,i,o,s,l,c){m(this,"convertBlocks",async(t,e,r,i,o,s,l=720)=>{const c=new qet(i,o,s,this.readImage,this.convertBlocks,this.defaultFontSize);return await zet(t,e,r,c,i,o,this.md5HexFunc,this.getDocByBlock,this.getTextsByBox,l||720),c.paragraphs});this.templateData=t,this.docData=e,this.md5HexFunc=r,this.readImage=i,this.defaultFontSize=o,this.getDocByBlock=s,this.getTextsByBox=l,this.backgroundImageOptions=c}async convert(t,e){return this.snapshot2docx(this.docData,t,e)}async snapshot2docx(t,e,r){const i=new Ct.ImportDotx,o=this.templateData?await i.extract(this.templateData):void 0,s=t.blocks.root;p(Wet,s,"data must have blocks");const l=Get(),c=await this.convertBlocks("blocks",s,t,e,r,l),d=this.backgroundImageOptions?{default:new Ct.Header({children:[new Ct.Paragraph({children:[new Ct.ImageRun(this.backgroundImageOptions)]})]})}:{},h=new Ct.Document({numbering:{config:[...cet,...l.levelConfigs]},sections:[{headers:d,children:c,properties:{page:{size:{width:12240,height:15840},margin:{top:1440,bottom:1440,left:1440,right:1440}}}}]},{template:o});return Ct.Packer.toBlob(h)}}async function Yet(n,t,e,r){const i=n.doc.buildResourceUrl(r,{withToken:!0});let o=await pS(i);if(!o)return[void 0,i];if(o.type.indexOf("/svg")!==-1){const l=await hS(o);l&&(o=new File([l],o.name))}return[await o.arrayBuffer(),i]}async function Qet(n,t,e){const r=n.editorBlocks.getBlockClass(e.type);if(r.toStandardDoc)return r.toStandardDoc(n,e,t)}async function Jet(n,t){const e=t.attributes,r=n.editorBoxes.getBoxClass(e.type);if(r.toStandardText)return r.toStandardText(n,e)}async function Zet(n,t){let{template:e,download:r,backgroundImageOptions:i}=t!=null?t:{};e||(e=tet());const o=n.doc.toJSON(),s=(C,E,x)=>Yet(n,C,E,x),l=async(C,E,x)=>Qet(n,o,x),c=async C=>Jet(n,C),h=await new Xet(e,o,Dd.default,s,void 0,l,c,i).convert("_appId","_docId");if(r){const C=URL.createObjectURL(h),E=document.createElement("a");E.setAttribute("download",`${gS(n)}.docx`),E.setAttribute("href",`${C}`),E.click(),E.remove()}return h}const MA=I("create-editor");async function tnt(n,t){var s,l,c,d,h,C,E,x,v,k,L,M,U,F;p(MA,n,"app does not exists"),t.lang&&D.setLang(t.lang),oi.level=(s=t.logLevel)!=null?s:Ds.DEBUG;const e=t.onReauth?async()=>{var st;const G=t.user.userId,q=t.docId,rt=await((st=t.onReauth)==null?void 0:st.call(t,G,q,t.permission));return{userId:G,docId:q,permission:t.permission,appId:t.appId,token:rt,displayName:t.user.displayName,avatarUrl:t.user.avatarUrl}}:void 0,r={auth:{appId:t.appId,docId:t.docId,userId:t.user.userId,permission:t.permission,token:t.token,displayName:t.user.displayName,avatarUrl:t.user.avatarUrl},serverUrl:t.serverUrl,reauthFunc:e,disableLogout:t.disableLogout},i=await Vu.load(r),o=Ru(n,i,{id:t.id,scrollContainer:t==null?void 0:t.scrollContainer,enableComments:t==null?void 0:t.enableComments,components:{blocks:[...KS,...((l=t==null?void 0:t.components)==null?void 0:l.blocks)||[]],embeds:[...DA,...((c=t.components)==null?void 0:c.embeds)||[]],boxes:[...VS,...((d=t.components)==null?void 0:d.boxes)||[]],commandProviders:[new m0,...((h=t.components)==null?void 0:h.commandProviders)||[]],decorators:[new V0,new Jp],insertions:[Q1],blockHooks:[new NE,new sw,...((C=t.components)==null?void 0:C.blockHooks)||[]],textRenders:[new D4,new ZC],options:{...t.componentsOptions}},shortcuts:[TY,_j,fW,CE,r4,YK,fE,aQ,Nh,HK,...t.shortcuts||[]],colors:["#0064FF","#EB3723","#F59300","#00A865","#F25A0A","#70A310","#009CAD","#0990D9","#8851ED","#D62069"]});if(o.editorCommandProviders.registerCommandProvider(new Ri(o)),o.input.addHandler(new EG),o.input.addHandler(new H0),o.input.addHandler(new g$),o.input.addHandler(new rW),o.input.addHandler(new yE(o,{hideTitle:t.hideTitle,headingLevel:1,titlePlaceholder:D.t("placeholder.common.title"),contentPlaceholder:D.t("placeholder.common.content"),readonlyTitlePlaceholder:D.t("placeholder.common.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),o.input.addHandler(new _0(o,(E=t.componentsOptions)==null?void 0:E.quickMenu)),o.input.addHandler(new XE(o)),o.input.addHandler(new eA(o)),o.input.addHandler(new W0),o.doc.registerCallback(new AG(o)),o.addCustom("remote-cursor",()=>new E2(o)),o.addCustom("block-menu",G=>new Cw(G)),ue.isMobile||o.addCustom("editor-tooltip",()=>new M0(o)),t!=null&&t.enableComments&&o.addCustom("editor-comments",G=>new I4(G,new qtt(G))),t.enableContextMenu!==!1&&o.addCustom("editor-context-menu",G=>new l4(G)),o.addCustom("create-options",()=>new Ob(o,t)),o.addCustom("drop-target",()=>new Tf(o)),o.addCustom("list-to-mindmap",()=>new R0(o)),o.addCustom("list-to-mention",()=>new eJ(o)),o.addCustom("mobile-helper",()=>new TJ(o)),o.addCustom("code-caret",()=>new Sj(o)),o.addCustom("image-paste-handler",()=>new qE(o)),(x=t.componentsOptions)!=null&&x.mention){const G=t.componentsOptions.mention;o.addCustom("mention",()=>new aS(o,G))}if(o.addCustom("heading-collapse",()=>new HE(o)),o.addCustom(gm,G=>new vA(G)),Qa.register(o),Tf.register(o),gs.register(o),cs.register(o),o.addListener("clickLink",(G,q,rt)=>{var Et;if((Et=t==null?void 0:t.events)!=null&&Et.onClickLink){t.events.onClickLink(G,q,rt);return}const st=rt.getAttribute("link");st&&(G.readonly||q.ctrlKey||q.metaKey)&&window.open(st,"_blank")}),(k=(v=t.componentsOptions)==null?void 0:v.remoteCarets)!=null&&k.onUserChanged){const G=(M=(L=t.componentsOptions)==null?void 0:L.remoteCarets)==null?void 0:M.onUserChanged;o.doc.getRemoteUsers().on("change",q=>{G(o,q)})}return(F=(U=t.componentsOptions)==null?void 0:U.templates)!=null&&F.templates.length&&(o.addListener("docChanged",()=>{mm(o)}),o.addListener("resize",()=>{mm(o,{reset:!0})}),setTimeout(()=>{mm(o)},100)),o.doc.registerCallback({onError:async G=>{if(G.code==="ResetDoc"){MA.error(`reset doc: ${G.message}`);const q=await Vu.load(r);o.doc.reset(q)}}}),o.version="1.1.8-beta.19",o}function ent(n){return n.toJSON!==void 0}async function nnt(n,t,e){var o,s,l,c,d,h;p(MA,n,"app does not exists");const r=ent(t)?t:new Lp(t,{serverUrl:e.serverUrl||""});e.lang&&D.setLang(e.lang),oi.level=(o=e.logLevel)!=null?o:Ds.DEBUG;const i=Ru(n,r,{id:e.id,scrollContainer:e==null?void 0:e.scrollContainer,components:{blocks:[pE,BE,TE,Pk],commandProviders:[new m0],decorators:[new V0,new Jp],embeds:[...DA,...((s=e.components)==null?void 0:s.embeds)||[]],boxes:[Qk,cS,K4,...((l=e.components)==null?void 0:l.boxes)||[]],insertions:[Q1],blockHooks:[new NE,...((c=e.components)==null?void 0:c.blockHooks)||[]],textRenders:[new D4,new ZC,...((d=e.components)==null?void 0:d.textRenders)||[]],options:{...e.componentsOptions}},shortcuts:[CE,r4,fE,Nh]});return i.editorCommandProviders.registerCommandProvider(new Ri(i)),i.input.addHandler(new H0),i.input.addHandler(new yE(i,{hideTitle:e.hideTitle,headingLevel:1,titlePlaceholder:D.t("placeholder.common.title"),contentPlaceholder:D.t("placeholder.common.content"),readonlyTitlePlaceholder:D.t("placeholder.local.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),i.input.addHandler(new _0(i,(h=e.componentsOptions)==null?void 0:h.quickMenu)),i.input.addHandler(new XE(i)),i.input.addHandler(new eA(i)),i.input.addHandler(new W0),i.addCustom("block-menu",C=>new Cw(C)),ue.isMobile||i.addCustom("editor-tooltip",()=>new M0(i)),i.addCustom("image-paste-handler",()=>new qE(i)),e!=null&&e.enableComments&&i.addCustom("editor-comments",C=>new I4(C,new Xtt(C,r))),e.enableContextMenu!==!1&&i.addCustom("editor-context-menu",C=>new l4(C)),i.addCustom("heading-collapse",()=>new HE(i)),i.addListener("clickLink",(C,E,x)=>{var k;if((k=e==null?void 0:e.events)!=null&&k.onClickLink){e.events.onClickLink(C,E,x);return}const v=x.getAttribute("link");v&&(C.readonly||E.ctrlKey||E.metaKey)&&window.open(v,"_blank")}),i.addCustom(gm,C=>new vA(C)),Qa.register(i),i.version="1.1.8-beta.19",i}async function rnt(n,t,e){var h;const r=n.doc.externalDoc.client.auth,i=await qh.load({auth:r,serverUrl:e});if(!((h=i.getVersionHelper)==null?void 0:h.call(i)))throw new Error("the editor does not support to show versions");const s=n.getCustom("create-options");if(!s)throw new Error("the editor does not support to show versions");const l=s.getData(),c=new $S(l),d=n.addCustom("version-dialog",()=>new nS(i,c));return d.show(t),d}b.tippy=a9,b.AnchorBox=PB,b.AuthError=Fu,b.AuthHeader=ol,b.AutoScroll=Wd,b.BaseURLHeader=Ma,b.BasicCommands=NV,b.BlockExclusiveHook=sw,b.BlockLockerHook=NE,b.BlockLockerPasteHandler=W0,b.BlockResizer=df,b.BrBox=MB,b.CodeBlock=BE,b.CodeLineBlock=TE,b.CodeTextDecorator=V0,b.DOC_RE_AUTH_KEYS=gm,b.DefaultShortcuts=Nh,b.DocIdError=DN,b.DocReAuthCallbacks=vA,b.DragDrop=ev,b.DrawioEmbed=SS,b.EditorBlocks=c3,b.EditorBoxes=OB,b.EditorCommandProviders=DT,b.EditorComplexBlockPosition=Ur,b.EditorComplexSelectionRange=ui,b.EditorDecorators=$B,b.EditorEmbeds=f3,b.EditorInsertions=VB,b.EditorSimpleBlockPosition=qe,b.EditorSimpleSelectionRange=en,b.EmbedBlock=h3,b.EmbedBlockResizer=Df,b.EnforceWithDocumentTitleHandler=yE,b.EventCallbacks=aa,b.FILL_CHAR=iM,b.FileExtError=_N,b.GroupOrder=Hk,b.HeadingBlockScrollListener=qQ,b.ImageBox=NB,b.InlineBoxCommandProvider=Jk,b.InputtingInsertion=FB,b.LocalDoc=Lp,b.LogLevel=Ds,b.Logger=oi,b.MIN_DISTANCE_THRESHOLD=Zb,b.ManualCloseDialog=ju,b.ManualMenu=Zo,b.ManualToolbar=Hu,b.MarkdownInputHandler=H0,b.MaxUserError=Hp,b.Mindmap=k0,b.OnesEditorAutoSuggest=xC,b.OnesEditorCustomDataWrapper=Ob,b.OnesEditorExclusiveBlock=cs,b.OnesEditorHoveringBlock=Te,b.OnesEditorIcons=EP,b.OnesEditorQuickMenu=_0,b.OnesEditorToc=_f,b.OnesEditorTocProvider=gs,b.OnesEditorToolbar=Qa,b.OnesEditorTooltip=M0,b.OnesEditorVersionsDialog=nS,b.PermissionError=Wh,b.Popup=$u,b.ReAuthToolbar=CS,b.RemoteCarets=E2,b.RemoteCaretsDecorator=Jp,b.RemoteCaretsInsertion=Q1,b.RemoteUsers=wu,b.RequestReloadError=Ku,b.RichText=hn,b.ShareDBDoc=Vu,b.ShareDBDocVersionsProvider=$S,b.ShareDBServer=qh,b.SimpleCache=jb,b.StandardEmbedBlockCommands=hA,b.TEXT_STYLE_BACKGROUND_COLOR_PREFIX=L1,b.TEXT_STYLE_COLOR_PREFIX=S1,b.TableBlock=pE,b.TableBlockCommandProvider=m0,b.TableShortcuts=CE,b.TextBlock=On,b.TextBox=_B,b.TextColorItem=Uy,b.TextStyleShortcuts=fE,b.TocEmbed=sS,b.ZERO_WIDTH_SPACE_CHAR=jc,b.abbreviation=qd,b.addAttribute=ah,b.addClass=z,b.addCommentToBlock=If,b.addDays=pI,b.addMetaToDoc=yu,b.addMonths=gI,b.animateScrollTo=Ns,b.applyPlaceholderToBlock=uf,b.assert=p,b.autoShowHideTemplates=mm,b.blockToDoc=Tp,b.blockToHtml=tp,b.blockToMarkdown=Th,b.blockToText=Bh,b.blocksToDoc=nT,b.clearAllSelection=Gv,b.clientType=ue,b.cloneBlock=Wo,b.cloneChildContainer=up,b.cloneDoc=fp,b.cloneText=TB,b.commentToShareDbComment=Qp,b.compareElement=Fd,b.comparePosition=h1,b.complexBlockAdjustSelectionPos=th,b.complexBlockFindNearestChildBlock=m7,b.complexBlockGeFirstSimpleChild=g1,b.complexBlockGetAllChildContainers=Bn,b.complexBlockGetBottomChildContainers=p3,b.complexBlockGetLastSimpleChild=Ca,b.complexBlockGetSelectedContainers=pa,b.complexBlockGetTopChildContainers=g3,b.containerToDoc=rT,b.continuousScroll=Cv,b.convertBlockFrom=Jd,b.convertImageFileToPng=hS,b.convertImageSrcToPng=EJ,b.converterIntercept=$0,b.copyBlockAttributes=t5,b.copyResourcesFromDoc=Sp,b.createBlockAnchor=Xi,b.createBlockCaretAnchor=A3,b.createBlockContentElement=js,b.createBlockElement=Nv,b.createBlockSimpleDocRange=Eh,b.createBlockSimpleRange=ye,b.createBoxContentElement=Kv,b.createBoxElement=Pv,b.createBoxOp=BB,b.createChildContainer=l3,b.createComplexBlockPosition=Ee,b.createComplexDocPos=SB,b.createComplexDocRange=lM,b.createContainer=kB,b.createContainerElement=Jg,b.createDeleteOps=AB,b.createEditor=Ru,b.createEditorSelectionRange=Xe,b.createElement=B,b.createEmptyContainer=to,b.createEmptyDoc=Zi,b.createEmptyTextBlockData=ph,b.createExpandedRange=Nd,b.createIconButton=Ms,b.createImage=Ig,b.createInsertOps=mh,b.createInsertionContentElement=Hv,b.createInsertionElement=Vv,b.createLocalEditor=nnt,b.createOnesEditor=tnt,b.createRange=zb,b.createRichText=el,b.createRootContainer=s3,b.createSimpleBlockPosition=ct,b.createSimpleDocPos=wB,b.createTextBlockData=mi,b.createTextButton=ml,b.createTextOp=mr,b.createTextWithReplaceSoftReturn=$1,b.daysAfter=Wg,b.deleteText=j1,b.diffDays=CI,b.disablePageScroll=jg,b.docToHtml=XB,b.docToHtmlFragment=Cu,b.docToMarkdown=YB,b.docToText=Go,b.downloadImageToFile=pS,b.downloadObjectToFile=yA,b.downloadSvgToString=xS,b.editLink=ef,b.editorAddComment=gY,b.editorAddTextAttribute=f5,b.editorAutoInsertBlock=e5,b.editorBreakTextBlock=ka,b.editorClearCompositionText=ip,b.editorClearSelectedContents=Sh,b.editorCopyBlock=Rp,b.editorCopyDoc=Oh,b.editorDeleteBlock=lp,b.editorDeleteBlockText=op,b.editorDeleteBlockWithoutChildren=Rh,b.editorDeleteChildContainer=iU,b.editorDeleteChildContainers=n5,b.editorFocusToBlock=cp,b.editorFocusToEnd=BU,b.editorGetBlockData=zo,b.editorGetBlockText=Tn,b.editorGetBlockTextEx=xh,b.editorGetBoxData=IB,b.editorHandleKeyboardEvent=mT,b.editorInsertBlock=ya,b.editorInsertBoxToBlock=JB,b.editorInsertDoc=c5,b.editorInsertDocAt=dp,b.editorInsertText=rp,b.editorInsertTextToBlock=QB,b.editorInsertTextToBlockEx=np,b.editorMergeTextBlock=r5,b.editorMoveDown=T5,b.editorMoveEnd=Ap,b.editorMoveHome=M5,b.editorMoveLeft=b5,b.editorMoveLineEnd=$5,b.editorMoveLineHome=V5,b.editorMovePageDown=q5,b.editorMovePageUp=W5,b.editorMoveRight=v5,b.editorMoveUp=B5,b.editorMoveWordEnd=I5,b.editorMoveWordLeft=L5,b.editorRangeClearColor=h5,b.editorRangeGetColor=m5,b.editorRangeSetColor=d5,b.editorRemoveTextAttribute=aU,b.editorReplaceBlockText=Lh,b.editorReplaceContainer=u5,b.editorRunOnce=Ip,b.editorSelectAll=bp,b.editorSelectContainer=_h,b.editorSelectDown=y5,b.editorSelectEnd=xp,b.editorSelectHome=U5,b.editorSelectLeft=k5,b.editorSelectLineEnd=K5,b.editorSelectLineHome=F5,b.editorSelectPageDown=Q5,b.editorSelectPageUp=Y5,b.editorSelectRight=R5,b.editorSelectUp=w5,b.editorSelectWordEnd=_5,b.editorSelectWordLeft=D5,b.editorSetTextColor=Ra,b.editorShowFindDialog=lX,b.editorToDocx=Zet,b.editorUpdateBlockData=Ih,b.editorUpdateCompositionText=ZB,b.editorUpdateEmbedData=l5,b.enablePageScroll=zg,b.escapeHtmlText=Vd,b.escapeRegExp=Qg,b.escapeSpace=Z9,b.exclusiveBlock=ME,b.executeBlockCommand=e3,b.executeEmbedBlockCommand=t3,b.executeRangeCommand=IT,b.fileToDataUrl=da,b.findAfterOffsetNotType=q1,b.findAllText=vp,b.findBlockByIndex=wv,b.findEventTargetBlock=Xb,b.findInsertionById=$v,b.findNextOffset=kM,b.findNextVisibleSimpleBlock=OT,b.findPrevOffset=yM,b.findPrevOffsetNotType=W1,b.findPrevSimpleBlockBeforeChildContainer=m3,b.findPrevVisibleSimpleBlock=UT,b.findTarget=ua,b.findWordEnd=Y1,b.findWordLeft=X1,b.format=Qc,b.formatBytes=Ev,b.formatDate=Xg,b.fragmentToHtml=dv,b.fromBase64=Wc,b.fromBase64ToBlob=$g,b.fromBase64ToUint8Array=uI,b.fromDocRange=Vo,b.fromNowString=Yg,b.genId=tt,b.getAllChildBlocks=E1,b.getAllQuickMenuItems=uE,b.getAllSelectedBlocks=fi,b.getAttributesAt=ba,b.getBlockBackground=Ov,b.getBlockByIndex=Hi,b.getBlockCaretRect=Fo,b.getBlockClass=Jt,b.getBlockClassByType=Vs,b.getBlockClientRects=Gi,b.getBlockCommandsWithHook=l1,b.getBlockContent=Ot,b.getBlockId=lt,b.getBlockIndex=Bt,b.getBlockInfo=Cf,b.getBlockKind=Dr,b.getBlockMinWidth=qv,b.getBlockNearestRangeFromPoint=p1,b.getBlockOptions=LI,b.getBlockPath=Ko,b.getBlockProperties=Qv,b.getBlockRangeFromPoint=eh,b.getBlockStyles=SI,b.getBlockTextLength=dt,b.getBlockTools=ie,b.getBlockType=Dt,b.getBoxContent=n1,b.getBoxId=Fv,b.getBoxTypeFromElement=eu,b.getChildBlockCount=Ir,b.getChildBlocks=fe,b.getChildOffset=Js,b.getColorFromAttributes=D1,b.getColorFromContent=Xd,b.getComplexBlockClass=fr,b.getContainerBlockPath=r3,b.getContainerBlocks=zv,b.getContainerBlocksElement=Zc,b.getContainerById=Lr,b.getContainerId=at,b.getContainerMinWidth=f1,b.getContainerToolsElement=kI,b.getContainerWidth=a3,b.getDistanceSquare=Po,b.getElementOffset=Hc,b.getElementScale=ur,b.getEmbedType=We,b.getExistsBlockTools=Yd,b.getExistsContainerById=Jc,b.getFileExt=Yc,b.getFirstChildBlock=we,b.getFirstClientRect=Pd,b.getHeadingMenuOptions=sE,b.getHorizontalPadding=_g,b.getInsertionContent=r1,b.getLastChildBlock=tn,b.getLastClientRect=Us,b.getListAllNextBrothers=Ga,b.getLogger=I,b.getNextBlock=Yt,b.getNextValidOffset=Zs,b.getNextVisibleBlock=Gs,b.getOffsetFromPoint=Dg,b.getOffsetInfoAfter=mu,b.getOffsetInfoBefore=bh,b.getOpAt=Z3,b.getOpLength=lh,b.getParentBlock=J,b.getParentBlockExcludeSelf=Hs,b.getParentBox=e1,b.getParentContainer=it,b.getPrevBlock=Ae,b.getPrevValidOffset=jo,b.getPrevVisibleBlock=zs,b.getRangeCommands=ST,b.getReferenceClientRect=mk,b.getRootBlock=s1,b.getScrollContainer=Ge,b.getSpecialBlockCommands=Jv,b.getStandardEmbedBlockProperties=mA,b.getTextAfterOffset=BM,b.getTextAttributes=ep,b.getTextBeforeOffset=TM,b.getTextBlockChild=iu,b.getTextBlockClass=Lv,b.getTextBlockContentChildTextLength=hr,b.getTextBlockContentChildType=n3,b.getTextBlockContentChildren=ai,b.getTextLength=dn,b.getTextOpLength=w1,b.getTextWidth=jd,b.getToolbar=x0,b.handleBlockElementUpdated=Xv,b.hasAltOnly=oI,b.hasClass=wt,b.hasCtrlOrCmd=lv,b.hasCtrlOrCmdOnly=iI,b.hashCode=yv,b.hideBlock=Uv,b.htmlToFragment=Hd,b.i18n=D,b.includeBigTable=qP,b.injectDocToHtmlFragment=Tu,b.injectStyle=Jb,b.inputActions=$U,b.insertEmptyBlock=_I,b.insertEmptyEmbedBlock=a1,b.insertText=Ji,b.intersectionCommands=bO,b.isBackspace=cv,b.isBlock=$s,b.isBlockLocked=G0,b.isBlockLockedByOthers=OE,b.isBlockLockedBySelf=Ef,b.isBlockTools=Mv,b.isBox=Qd,b.isBoxOp=Ho,b.isCJK=ov,b.isChildContainer=Mr,b.isChildNode=re,b.isCodeBlock=Gr,b.isCollapsedRange=sM,b.isComplexBlockPosition=ga,b.isComplexKindBlock=Mt,b.isContainer=zi,b.isContainerSelectedAllChildBlocks=J5,b.isControlEvent=Fs,b.isDelete=lI,b.isDraggingFiles=zd,b.isElementVisible=Og,b.isEmbedBlock=ge,b.isEmptyContainer=ou,b.isEmptyDoc=z1,b.isEmptyTextBlock=oe,b.isEmptyTextBlockWithoutCompositionText=cf,b.isEnterOnly=av,b.isEscape=Kg,b.isExclusiveBlock=pf,b.isFirefox=Gc,b.isFirstChildBlockInComplexBlock=h7,b.isHighSurrogate=X9,b.isInBlock=i1,b.isInBlockTools=Ws,b.isLetter=iv,b.isLowSurrogate=Y9,b.isMatchShortcut=si,b.isMoveForward=nI,b.isNavigationEvent=eI,b.isNavigationKey=sv,b.isNodeRemoved=Wb,b.isNumber=rv,b.isPrintableKey=Fg,b.isRootBlock=dr,b.isRootContainer=Qt,b.isSafari=fa,b.isSameDay=qg,b.isSelectBoxOnly=Fk,b.isShiftEnter=sI,b.isShiftTab=cI,b.isShortcutEvent=rI,b.isSimpleBlock=wI,b.isSimpleBlockPosition=ci,b.isSimplePos=RB,b.isSimpleRange=Ch,b.isSpace=$d,b.isTab=aI,b.isTextBlockContentBoxChild=Yn,b.isTextBlockContentChild=nu,b.isTextBlockContentInsertionChild=qi,b.isTextBlockContentTextChild=ru,b.isTextKindBlock=nt,b.isTextKindBlockType=tu,b.isTitleBlock=ji,b.isToday=Av,b.isValidOffset=Un,b.isVisibleBlock=ma,b.isYesterday=xv,b.loadJs=qb,b.loadJsPromise=Os,b.lockers=Sr,b.mergeCommands=A0,b.mergeDocs=nl,b.mergeOps=H1,b.mergeText=nM,b.multiSplitText=eB,b.overflowText=bv,b.parseShortcut=uv,b.patchNode=qc,b.pointInRect=Ps,b.rangeAddAttribute=uu,b.rangeGetTextColor=aB,b.rangeRemoveAttribute=xa,b.rangeSetTextColor=oB,b.rangeTransformText=rB,b.registerDragDrop=Ng,b.removeAttribute=I1,b.removeClass=ot,b.removeLastBr=J_,b.removePlaceholderFromBlock=DR,b.removeStyle=Qb,b.replaceAll=EI,b.replaceAllCaseInsensitive=AI,b.replaceAllText=tT,b.replaceText=gh,b.requestDownload=Gd,b.resetListStart=qa,b.scrollIntoView=pu,b.scrollable=pv,b.selectFile=ha,b.selectedBlockToDoc=Mh,b.selectionToDoc=wa,b.setAttributes=Kd,b.setClipboardData=Xc,b.setClipboardDataByEvent=hI,b.setColorToAttributes=sB,b.setDataset=Mg,b.setDefaultCursor=zc,b.setStyles=Ug,b.shareDBCommentToDocObject=Yp,b.shareDBDocCommentToComment=p2,b.shortcutToDisplayText=ze,b.showBlock=t1,b.showDocVersions=rnt,b.splitText=_n,b.splitToThree=Ye,b.stringToDataUrl=Hg,b.stringToObjectUrl=Gg,b.subText=nB,b.textNodeOffsetFromPoint=Gb,b.titleFromEditor=gS,b.toBase64URL=li,b.toMindmap=y0,b.toPlainText=de,b.toPlainTextKeepLength=G1,b.trimChar=Pg,b.unexclusiveBlock=UE,b.unicodeLength=Q9,b.unicodeSubstr=J9,b.updateBlockSelection=Wv,b.updateOpAttributes=yB,b.updateTextBlockContent=vM,b.updateUrl=Vg;for(const n in Be)n!=="default"&&!b.hasOwnProperty(n)&&Object.defineProperty(b,n,{enumerable:!0,get:()=>Be[n]});Object.defineProperties(b,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});