react-reason-editor 1.0.114 → 1.0.116
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/Ai-DOAuz6ZE.js +1 -0
- package/dist/Ai-DVWZg0-D.cjs +1 -0
- package/dist/Ai.cjs +1 -1
- package/dist/Ai.js +1 -1
- package/dist/BubbleMenus-D8BicxJF.cjs +1 -0
- package/dist/{BubbleMenus-CFzQBrVG.js → BubbleMenus-DopOZm_P.js} +43 -43
- package/dist/{Drawio-s-Xgqy7a.js → Drawio-LEtUoVAY.js} +7 -7
- package/dist/Drawio.js +1 -1
- package/dist/{Emoji-CTKm00BR.js → Emoji-CIxVw-Kv.js} +2 -2
- package/dist/Emoji.js +1 -1
- package/dist/{ReasonDocs-CsmZMk6W.cjs → ReasonDocs-BCjyspDd.cjs} +1 -1
- package/dist/{ReasonDocs-BXtUm4zk.js → ReasonDocs-eAuJLZVg.js} +17 -17
- package/dist/{RichTextProvider-KRSFedCE.cjs → RichTextProvider-C0V3hhy_.cjs} +1 -1
- package/dist/RichTextProvider-z_4PSTNH.js +5 -0
- package/dist/{bubble-B39N7x_B.js → bubble-DF0FOqik.js} +17 -17
- package/dist/bubble.cjs +1 -1
- package/dist/bubble.js +1 -1
- package/dist/docs-agent/plate/ai-controller.d.ts +82 -0
- package/dist/docs-agent/plate/kits/ai-kit.d.ts +37 -0
- package/dist/docs-agent/plate/ui/ai-menu.d.ts +19 -0
- package/dist/docs-agent/plate/ui/ai-toolbar-button.d.ts +12 -0
- package/dist/docs-agent.cjs +1 -1
- package/dist/docs-agent.d.ts +4 -0
- package/dist/docs-agent.js +18 -18
- package/dist/editor-kit.cjs +1 -1
- package/dist/editor-kit.js +1 -1
- package/dist/editorConfig-CpUHUq44.js +18 -0
- package/dist/editorConfig-DaUET9eN.cjs +1 -0
- package/dist/extensions/Ai/index.d.ts +1 -0
- package/dist/extensions/Ai/lib/rewriteEndpoint.d.ts +17 -0
- package/dist/{html-to-docx.esm-BLUcO7pp-BKB2FJoB.cjs → html-to-docx.esm-BLUcO7pp-sCMiaq9J.cjs} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/reason-docs.cjs +1 -1
- package/dist/reason-docs.js +1 -1
- package/dist/reason-toolbar-skin-BQRPoci6.cjs +1 -0
- package/dist/reason-toolbar-skin-Beh6Q5Ra.js +560 -0
- package/package.json +2 -2
- package/dist/Ai-B_8fziaT.js +0 -1
- package/dist/Ai-BxQjqvdT.cjs +0 -1
- package/dist/BubbleMenus-3RiQc4lw.cjs +0 -1
- package/dist/RichTextProvider-BcsYTR6Z.js +0 -5
- package/dist/editorConfig-9-ZxkRbw.js +0 -18
- package/dist/editorConfig-DF8EAH_P.cjs +0 -1
- package/dist/reason-toolbar-skin-DY4w9SRA.cjs +0 -1
- package/dist/reason-toolbar-skin-DarRq6V-.js +0 -539
package/dist/docs-agent.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./rolldown-runtime-Drgf5FY8.js";import{o as r}from"./dist-DmY5xFkC.js";import{i,n as s,r as o,t as a}from"./tooltip-G11f5UOp.js";import{i as c,n as l,t as h}from"./editorConfig-9-ZxkRbw.js";import{A as d,B as u,C as f,D as g,E as p,F as m,G as y,H as b,I as w,J as v,K as _,L as k,M as C,N as S,O as E,P as A,Q as T,R as x,S as R,T as D,U as O,V as P,W as L,X as M,Y as N,Z as I,_ as U,a as j,at as F,b as B,c as W,d as H,et as q,f as V,g as z,h as $,i as Y,it as J,j as Q,k as K,l as G,m as X,n as Z,nt as ee,o as te,p as ne,q as re,r as ie,rt as se,s as oe,t as ae,tt as ce,u as le,v as he,w as de,x as ue,y as fe,z as ge}from"./reason-toolbar-skin-DarRq6V-.js";import{a as pe,f as me,h as ye,m as be,o as we,p as ve,r as _e,s as ke,t as Ce,u as Se}from"./dropdown-menu-tmQwCqOR.js";import{getTranscribeStorage as Ee,isTranscriptionSupported as Ae,subscribeTranscribe as Te}from"./Transcribe.js";import{$ as xe,A as Re,At as De,B as Oe,Bt as Pe,C as Le,Ct as Me,D as Ne,Dt as Ie,E as Ue,Et as je,F as Fe,Ft as Be,G as We,Gt as He,H as qe,Ht as Ve,I as ze,It as $e,J as Ye,K as Je,Kt as Qe,L as Ke,Lt as Ge,M as Xe,Mt as Ze,N as et,Nt as tt,O as nt,Ot as rt,P as it,Pt as st,Q as ot,R as at,Rt as ct,S as lt,St as ht,T as dt,Tt as ut,U as ft,Ut as gt,V as pt,Vt as mt,W as yt,Wt as bt,X as wt,Y as vt,Z as _t,_ as kt,_t as Ct,at as St,b as Et,bt as At,c as Tt,ct as xt,d as Rt,dt as Dt,et as Ot,f as Pt,ft as Lt,g as Mt,gt as Nt,h as It,ht as Ut,i as jt,it as Ft,j as Bt,jt as Wt,k as Ht,kt as qt,l as Vt,lt as zt,m as $t,mt as Yt,nt as Jt,o as Qt,ot as Kt,p as Gt,pt as Xt,q as Zt,qt as en,rt as tn,st as nn,t as rn,tt as sn,u as on,ut as an,v as cn,vt as ln,w as hn,wt as dn,x as un,xt as fn,y as gn,yt as pn,z as mn,zt as yn}from"./dist-kbEzWzhg.js";import*as bn from"react";import{useCallback as wn,useEffect as vn,useLayoutEffect as _n,useMemo as kn,useReducer as Cn,useRef as Sn,useState as En}from"react";import{Extension as An}from"@tiptap/core";import{Plugin as Tn,PluginKey as xn}from"@tiptap/pm/state";import{Fragment as Rn,jsx as Dn,jsxs as On}from"react/jsx-runtime";import{AlignCenter as Pn,AlignJustify as Ln,AlignLeft as Mn,AlignRight as Nn,Baseline as In,Bold as Un,Braces as jn,Code as Fn,Code2 as Bn,Columns2 as Wn,Eraser as Hn,FileText as qn,Heading1 as Vn,Heading2 as zn,Heading3 as $n,Heading4 as Yn,Heading5 as Jn,Heading6 as Qn,Highlighter as Kn,Image as Gn,IndentDecrease as Xn,IndentIncrease as Zn,Info as er,Italic as tr,Link2 as nr,List as rr,ListChecks as ir,ListOrdered as sr,Mic as or,Minus as ar,Pencil as cr,Pilcrow as lr,Plus as hr,Quote as dr,Redo2 as ur,Rows3 as fr,Sigma as gr,Smile as pr,Strikethrough as mr,Subscript as yr,Superscript as br,Table2 as wr,Trash2 as vr,Type as _r,Underline as kr,Undo2 as Cr,Video as Sr}from"lucide-react";import{useSyncExternalStore as Er}from"use-sync-external-store/shim";import"use-sync-external-store/shim/with-selector";var Ar=class extends $e{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=/* @__PURE__ */new Map,this.meta=/* @__PURE__ */new Map,this._checkInterval=setInterval(()=>{const e=wt();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&Tr(this,t,"timeout")},Ze(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:wt()});const s=[],o=[],a=[],c=[];null===e?c.push(t):null==i?null!=e&&s.push(t):(o.push(t),Ke(i,e)||a.push(t)),(s.length>0||a.length>0||c.length>0)&&this.emit("change",[{added:s,updated:a,removed:c},"local"]),this.emit("update",[{added:s,updated:o,removed:c},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},Tr=(e,t,n)=>{const r=[];for(let i=0;i<t.length;i++){const n=t[i];if(e.states.has(n)){if(e.states.delete(n),n===e.clientID){const t=e.meta.get(n);e.meta.set(n,{clock:t.clock+1,lastUpdated:wt()})}r.push(n)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},xr=(e,t,n=e.states)=>{const r=t.length,i=At();rt(i,r);for(let s=0;s<r;s++){const r=t[s],o=n.get(r)||null,a=e.meta.get(r).clock;rt(i,r),rt(i,a),Ie(i,JSON.stringify(o))}return ht(i)};function Rr(e){return{engine:e,execute(){},isActive:()=>!1,isEnabled:()=>!1,getValue(){},subscribe:()=>()=>{}}}var Dr=[{kind:"button",id:"undo",label:"Undo",icon:Cr,shortcut:"⌘Z"},{kind:"button",id:"redo",label:"Redo",icon:ur,shortcut:"⇧⌘Z"},{kind:"separator",id:"history-divider"},{kind:"button",id:"bold",label:"Bold",icon:Un,shortcut:"⌘B"},{kind:"button",id:"italic",label:"Italic",icon:tr,shortcut:"⌘I"},{kind:"button",id:"underline",label:"Underline",icon:kr,shortcut:"⌘U"},{kind:"button",id:"highlight",label:"Highlight",icon:Kn,shortcut:"⌘⇧H"},{kind:"separator",id:"marks-divider"},{kind:"menu",id:"block-format",label:"Block Format",icon:fr,children:[{kind:"button",id:"paragraph",label:"Paragraph",icon:lr},{kind:"button",id:"heading-1",label:"Heading 1",icon:Vn,shortcut:"Ctrl+Alt+1"},{kind:"button",id:"heading-2",label:"Heading 2",icon:zn,shortcut:"Ctrl+Alt+2"},{kind:"button",id:"heading-3",label:"Heading 3",icon:$n,shortcut:"Ctrl+Alt+3"},{kind:"button",id:"heading-4",label:"Heading 4",icon:Yn,shortcut:"Ctrl+Alt+4"},{kind:"button",id:"heading-5",label:"Heading 5",icon:Jn,shortcut:"Ctrl+Alt+5"},{kind:"button",id:"heading-6",label:"Heading 6",icon:Qn,shortcut:"Ctrl+Alt+6"},{kind:"separator",id:"block-format-lists-divider"},{kind:"button",id:"bullet-list",label:"Bullet List",icon:rr,shortcut:"Ctrl+Shift+8"},{kind:"button",id:"ordered-list",label:"Ordered List",icon:sr,shortcut:"Ctrl+Shift+7"},{kind:"button",id:"task-list",label:"Check List",icon:ir,shortcut:"Ctrl+Shift+9"},{kind:"separator",id:"block-format-quote-divider"},{kind:"button",id:"blockquote",label:"Blockquote",icon:dr,shortcut:"Ctrl+Shift+B"},{kind:"button",id:"code-block",label:"Code Block",icon:Bn,shortcut:"Ctrl+Alt+C"},{kind:"separator",id:"block-format-clear-divider"},{kind:"button",id:"clear-formatting",label:"Clear Format",icon:Hn}]},{kind:"menu",id:"text-styles",label:"Text Styles",icon:_r,children:[{kind:"group-label",id:"text-styles-label",label:"Text Styles"},{kind:"button",id:"strike",label:"Strikethrough",icon:mr,shortcut:"Ctrl+Shift+S"},{kind:"button",id:"code",label:"Inline Code",icon:Fn,shortcut:"Ctrl+E"},{kind:"button",id:"text-color",label:"Text Color",icon:In,shortcut:"Alt+Shift+C"},{kind:"button",id:"superscript",label:"Superscript",icon:br,shortcut:"Ctrl+."},{kind:"button",id:"subscript",label:"Subscript",icon:yr,shortcut:"Ctrl+,"},{kind:"separator",id:"text-styles-indent-divider"},{kind:"button",id:"indent",label:"Indent",icon:Zn},{kind:"button",id:"outdent",label:"Outdent",icon:Xn},{kind:"menu",id:"alignment",label:"Alignment",icon:Mn,children:[{kind:"button",id:"align-left",label:"Align Left",icon:Mn},{kind:"button",id:"align-center",label:"Align Center",icon:Pn},{kind:"button",id:"align-right",label:"Align Right",icon:Nn},{kind:"button",id:"align-justify",label:"Justify",icon:Ln}]}]},{kind:"menu",id:"insert",label:"Insert",icon:hr,children:[{kind:"group-label",id:"insert-label",label:"Insert"},{kind:"button",id:"link",label:"Link",icon:nr},{kind:"button",id:"emoji",label:"Emoji",icon:pr},{kind:"button",id:"table",label:"Table",icon:wr},{kind:"button",id:"image",label:"Image",icon:Gn},{kind:"button",id:"columns",label:"Columns",icon:Wn,shortcut:"Ctrl+Alt+G"},{kind:"button",id:"callout",label:"Callout",icon:er},{kind:"button",id:"horizontal-rule",label:"Divider",icon:ar,shortcut:"Ctrl+Alt+S"},{kind:"button",id:"video",label:"Video",icon:Sr},{kind:"button",id:"math",label:"Math",icon:gr}]},{kind:"separator",id:"voice-divider"},{kind:"button",id:"transcribe",label:"Dictate",icon:or,shortcut:"Ctrl+Shift+D"},{kind:"menu",id:"table-tools",label:"Table",icon:wr,visibleWhenActive:"table",children:[{kind:"group-label",id:"table-rows-label",label:"Rows"},{kind:"button",id:"table.add-row-before",label:"Insert Row Above",icon:fr},{kind:"button",id:"table.add-row-after",label:"Insert Row Below",icon:fr},{kind:"button",id:"table.delete-row",label:"Delete Row",icon:vr},{kind:"separator",id:"table-columns-divider"},{kind:"group-label",id:"table-columns-label",label:"Columns"},{kind:"button",id:"table.add-column-before",label:"Insert Column Left",icon:Wn},{kind:"button",id:"table.add-column-after",label:"Insert Column Right",icon:Wn},{kind:"button",id:"table.delete-column",label:"Delete Column",icon:vr},{kind:"separator",id:"table-cells-divider"},{kind:"group-label",id:"table-cells-label",label:"Cells"},{kind:"button",id:"table.merge-cells",label:"Merge Cells",icon:jn},{kind:"button",id:"table.split-cell",label:"Split Cell",icon:jn},{kind:"button",id:"table.toggle-header-row",label:"Toggle Header Row",icon:fr},{kind:"separator",id:"table-delete-divider"},{kind:"button",id:"table.delete",label:"Delete Table",icon:vr}]}];function Or(e=Dr){const t=[];for(const n of e)"button"===n.kind&&t.push(n.id),"menu"===n.kind&&t.push(...Or(n.children));return t}var Pr="flex items-center justify-center rounded p-1.5 text-gray-600 transition-colors dark:text-gray-300 disabled:cursor-not-allowed disabled:opacity-40 hover:enabled:bg-gray-100 dark:hover:enabled:bg-slate-800",Lr="bg-gray-200 text-gray-900 dark:bg-slate-700 dark:text-white",Mr="flex w-full cursor-pointer items-center gap-2 text-xs data-disabled:cursor-not-allowed data-disabled:opacity-40";function Nr({shortcut:e}){return e?/* @__PURE__ */Dn("span",{className:"ml-auto pl-4 text-[10px] tracking-widest text-gray-400 dark:text-gray-500",children:e}):null}function Ir({items:e,adapter:t}){/* @__PURE__ */
|
|
2
|
-
return
|
|
3
|
-
return
|
|
4
|
-
return
|
|
5
|
-
/* @__PURE__ */
|
|
6
|
-
/* @__PURE__ */
|
|
7
|
-
/* @__PURE__ */
|
|
8
|
-
return
|
|
9
|
-
return
|
|
10
|
-
return
|
|
11
|
-
/* @__PURE__ */
|
|
12
|
-
return
|
|
13
|
-
/* @__PURE__ */Dn(qn,{className:"size-3.5 shrink-0 opacity-60"}),d?/* @__PURE__ */Dn("input",{autoFocus:!0,className:"min-w-0 flex-1 rounded border border-gray-300 bg-white px-1 py-0.5 text-sm dark:border-slate-600 dark:bg-slate-800",onBlur:u,onChange:e=>h(e.target.value),onKeyDown:e=>{"Enter"===e.key&&u(),"Escape"===e.key&&c(null)},value:l}):/* @__PURE__ */Dn("a",{className:"min-w-0 flex-1 truncate",href:t(i.id),children:i.title}),!d&&/* @__PURE__ */On("div",{className:"hidden shrink-0 items-center gap-0.5 group-hover:flex",children:[/* @__PURE__ */Dn("button",{"aria-label":`Rename ${i.title}`,className:"rounded p-0.5 text-gray-400 hover:bg-gray-200 dark:hover:bg-slate-700",onClick:()=>(e=>{c(e.id),h(e.title)})(i),type:"button",children:/* @__PURE__ */Dn(cr,{className:"size-3"})}),/* @__PURE__ */Dn("button",{"aria-label":`Delete ${i.title}`,className:"rounded p-0.5 text-gray-400 hover:bg-gray-200 dark:hover:bg-slate-700",onClick:()=>(t=>{if("undefined"!=typeof window&&!window.confirm(`Delete "${t.title}"?`))return;if(Yr(t.id),t.id!==e)return;const r=s.find(e=>e.id!==t.id);n(r?r.id:zr().id)})(i),type:"button",children:/* @__PURE__ */Dn(vr,{className:"size-3"})})]})]},i.id)}),0===s.length&&/* @__PURE__ */Dn("p",{className:"px-1.5 py-2 text-xs text-gray-400",children:"No documents yet."})]})}var Kr=/* @__PURE__ */function(e){return e[e.Token=0]="Token",e[e.PermissionDenied=1]="PermissionDenied",e[e.Authenticated=2]="Authenticated",e}({}),Gr=(e,t)=>{rt(e,Kr.Token),Ie(e,t)},Xr=(e,t,n,r)=>{switch(Dt(e)){case Kr.Token:t();break;case Kr.PermissionDenied:n(an(e));break;case Kr.Authenticated:r(an(e))}},Zr=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));function ei(e,t){return e+"\0"+t}function ti(e){const t=e.indexOf("\0");return-1===t?{documentName:e,sessionId:null}:{documentName:e.substring(0,t),sessionId:e.substring(t+1)}}var ni=/* @__PURE__ */function(e){return e[e.Connecting=0]="Connecting",e[e.Open=1]="Open",e[e.Closing=2]="Closing",e[e.Closed=3]="Closed",e}({});async function ri(e){return new Promise(t=>setTimeout(t,e))}function ii(e,t){let n=t.delay;if(0===n)return 0;if(t.factor&&(n*=Math.pow(t.factor,e.attemptNum-1),0!==t.maxDelay&&(n=Math.min(n,t.maxDelay))),t.jitter){const e=Math.ceil(t.minDelay);n=Math.floor(Math.random()*(Math.floor(n)-e+1))+e}return Math.round(n)}async function si(e,t){const n=function(e){return e||(e={}),{delay:void 0===e.delay?200:e.delay,initialDelay:void 0===e.initialDelay?0:e.initialDelay,minDelay:void 0===e.minDelay?0:e.minDelay,maxDelay:void 0===e.maxDelay?0:e.maxDelay,factor:void 0===e.factor?0:e.factor,maxAttempts:void 0===e.maxAttempts?3:e.maxAttempts,timeout:void 0===e.timeout?0:e.timeout,jitter:!0===e.jitter,initialJitter:!0===e.initialJitter,handleError:void 0===e.handleError?null:e.handleError,handleTimeout:void 0===e.handleTimeout?null:e.handleTimeout,beforeAttempt:void 0===e.beforeAttempt?null:e.beforeAttempt,calculateDelay:void 0===e.calculateDelay?null:e.calculateDelay}}(t);for(const o of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const e=n[o];if(!Number.isInteger(e)||e<0)throw new Error(`Value for ${o} must be an integer greater than or equal to 0`)}if(n.factor.constructor!==Number||n.factor<0)throw new Error("Value for factor must be a number greater than or equal to 0");if(n.delay<n.minDelay)throw new Error(`delay cannot be less than minDelay (delay: ${n.delay}, minDelay: ${n.minDelay}`);const r={attemptNum:0,attemptsRemaining:n.maxAttempts?n.maxAttempts:-1,aborted:!1,abort(){r.aborted=!0}},i=n.calculateDelay||ii;const s=n.calculateDelay?n.calculateDelay(r,n):n.initialDelay;if(s&&await ri(s),r.attemptNum<1&&n.initialJitter){const e=i(r,n);e&&await ri(e)}return async function t(){if(n.beforeAttempt&&n.beforeAttempt(r,n),r.aborted){const e=/* @__PURE__ */new Error("Attempt aborted");throw e.code="ATTEMPT_ABORTED",e}const s=async e=>{if(n.handleError&&await n.handleError(e,r,n),r.aborted||0===r.attemptsRemaining)throw e;r.attemptNum++;const s=i(r,n);return s&&await ri(s),t()};return r.attemptsRemaining>0&&r.attemptsRemaining--,n.timeout?new Promise((t,i)=>{const o=setTimeout(()=>{if(n.handleTimeout)try{t(n.handleTimeout(r,n))}catch(e){i(e)}else{const e=/* @__PURE__ */new Error(`Retry timeout (attemptNum: ${r.attemptNum}, timeout: ${n.timeout})`);e.code="ATTEMPT_TIMEOUT",i(e)}},n.timeout);e(r,n).then(e=>{clearTimeout(o),t(e)}).catch(e=>{clearTimeout(o),s(e).then(t).catch(i)})}):e(r,n).catch(s)}()}var oi=(e,t,n)=>((e,t,n)=>{rt(e,1),qt(e,kt(t,n))})(t,n,Lt(e)),ai=(e,t,n,r)=>{try{Rt(t,Lt(e),n)}catch(i){null!=r&&r(i)}},ci=ai,li=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){const n=this.callbacks[e];return n&&n.forEach(e=>e.apply(this,t)),this}off(e,t){const n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(e=>e!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}},hi=class{constructor(e){this.data=e,this.encoder=At(),this.decoder=Ft(new Uint8Array(this.data))}peekVarString(){return Kt(this.decoder)}readVarUint(){return Dt(this.decoder)}readVarString(){return an(this.decoder)}readVarUint8Array(){return Lt(this.decoder)}writeVarUint(e){return rt(this.encoder,e)}writeVarString(e){return Ie(this.encoder,e)}writeVarUint8Array(e){return qt(this.encoder,e)}length(){return fn(this.encoder)}},di=/* @__PURE__ */function(e){return e[e.Sync=0]="Sync",e[e.Awareness=1]="Awareness",e[e.Auth=2]="Auth",e[e.QueryAwareness=3]="QueryAwareness",e[e.Stateless=5]="Stateless",e[e.CLOSE=7]="CLOSE",e[e.SyncStatus=8]="SyncStatus",e[e.Ping=9]="Ping",e[e.Pong=10]="Pong",e}({}),ui=/* @__PURE__ */function(e){return e.Connecting="connecting",e.Connected="connected",e.Disconnected="disconnected",e}({}),fi=class{constructor(){this.encoder=At()}get(e){return e.encoder}toUint8Array(){return ht(this.encoder)}},gi=class extends fi{constructor(...e){super(...e),this.type=di.CLOSE,this.description="Ask the server to close the connection"}get(e){return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),this.encoder}},pi=class e extends li{static{this.DEDUPLICATABLE_TYPES=/* @__PURE__ */new Set([di.Awareness,di.QueryAwareness])}constructor(e){super(),this.messageQueue=[],this.configuration={url:"",autoConnect:!0,preserveTrailingSlash:!1,document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,handleTimeout:null,providerMap:/* @__PURE__ */new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=ui.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(e),this.configuration.WebSocketPolyfill=e.WebSocketPolyfill?e.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(e){this.status=ui.Connected,this.emit("status",{status:ui.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){const t=e.effectiveName,n=this.configuration.providerMap.get(t);if(n&&n!==e&&n.isAuthenticated)throw new Error(`Cannot attach two providers with the same effective name "${t}". Use sessionAwareness: true to multiplex providers with the same document name.`);this.configuration.providerMap.set(t,e),this.status===ui.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===ui.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){const t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(gi,{documentName:t}),this.configuration.providerMap.delete(t))}setConfiguration(e={}){this.configuration={...this.configuration,...e},this.configuration.autoConnect||(this.shouldConnect=!1)}async connect(){if(this.status===ui.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const{retryPromise:e,cancelFunc:t}=(()=>{let e=!1;return{retryPromise:si(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,handleTimeout:this.configuration.handleTimeout,beforeAttempt:t=>{this.shouldConnect&&!e||t.abort()}}).catch(e=>{if(e&&"ATTEMPT_ABORTED"!==e.code)throw e}),cancelFunc:()=>{e=!0}}})();return this.cancelWebsocketRetry=t,e}attachWebSocketListeners(e,t){const{identifier:n}=e;this.webSocketHandlers[n]={message:e=>this.emit("message",e),close:e=>this.emit("close",{event:e}),open:e=>this.emit("open",e),error:e=>{t(e)}};const r=this.webSocketHandlers[e.identifier];Object.keys(r).forEach(t=>{e.addEventListener(t,r[t])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:e}=this.webSocket,t=this.webSocketHandlers[e];Object.keys(t).forEach(n=>{this.webSocket?.removeEventListener(n,t[n]),delete this.webSocketHandlers[e]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((e,t)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=ui.Connecting,this.emit("status",{status:ui.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=wt();const t=new Uint8Array(e.data);if(1===t.length&&t[0]===di.Ping)return void this.sendPong();const n=new hi(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){const e=At();rt(e,di.Pong),this.send(ht(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=ui.Connected,this.emit("status",{status:ui.Connected}),this.emit("connect"),this.messageQueue.forEach(e=>this.send(e)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){this.connectionAttempt?.reject(),this.connectionAttempt=null}checkConnection(){this.status===ui.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=wt()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):(this.webSocket?.close(),this.messageQueue=[])))}get serverUrl(){if(this.configuration.preserveTrailingSlash)return this.configuration.url;let e=this.configuration.url;for(;"/"===e[e.length-1];)e=e.slice(0,e.length-1);return e}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,null!==this.webSocket)try{this.webSocket.close(),this.messageQueue=[]}catch(e){}}parseQueuedMessage(e){try{const t=Ft(e);return{documentName:an(t),messageType:Dt(t)}}catch{return null}}addToQueue(t){if(t instanceof Uint8Array){const n=this.parseQueuedMessage(t);n&&e.DEDUPLICATABLE_TYPES.has(n.messageType)&&(this.messageQueue=this.messageQueue.filter(e=>{if(!(e instanceof Uint8Array))return!0;const t=this.parseQueuedMessage(e);return!t||!(t.documentName===n.documentName&&t.messageType===n.messageType)}))}this.messageQueue.push(t)}send(e){this.webSocket?.readyState===ni.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=ui.Disconnected,this.emit("status",{status:ui.Disconnected}),this.emit("disconnect",{event:e}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}},mi=class{constructor(e){this.message=e}apply(e,t){const{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case di.Sync:this.applySyncMessage(e,t);break;case di.Awareness:this.applyAwarenessMessage(e);break;case di.Auth:this.applyAuthMessage(e);break;case di.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case di.Stateless:e.receiveStateless(an(n.decoder));break;case di.SyncStatus:this.applySyncStatusMessage(e,1===zt(n.decoder));break;case di.CLOSE:{const t={code:1e3,reason:an(n.decoder)};e.onClose(),e.configuration.onClose({event:t}),e.forwardClose({event:t});break}}n.length()>i+1&&e.send(fi,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(di.Sync);const r=((e,t,n,r,i)=>{const s=Dt(e);switch(s){case 0:oi(e,t,n);break;case 1:ai(e,n,r,i);break;case 2:ci(e,n,r,i);break;default:throw new Error("Unknown message type")}return s})(n.decoder,n.encoder,e.document,e);t&&1===r&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;((e,t,n)=>{const r=Ft(t),i=wt(),s=[],o=[],a=[],c=[],l=Dt(r);for(let h=0;h<l;h++){const t=Dt(r);let n=Dt(r);const l=JSON.parse(an(r)),h=e.meta.get(t),d=e.states.get(t),u=void 0===h?0:h.clock;(u<n||u===n&&null===l&&e.states.has(t))&&(null===l?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===h&&null!==l?s.push(t):void 0!==h&&null===l?c.push(t):null!==l&&(Ke(l,d)||a.push(t),o.push(t)))}(s.length>0||a.length>0||c.length>0)&&e.emit("change",[{added:s,updated:a,removed:c},n]),(s.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:s,updated:o,removed:c},n])})(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;Xr(t.decoder,e.sendToken.bind(e),e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;t.writeVarUint(di.Awareness),t.writeVarUint8Array(xr(e.awareness,Array.from(e.awareness.getStates().keys())))}},yi=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return ht(this.encoder)}send(e){e?.send(this.create())}},bi=class extends fi{constructor(...e){super(...e),this.type=di.Auth,this.description="Authentication"}get(e){if(void 0===e.token)throw new Error("The authentication message requires `token` as an argument.");return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),Gr(this.encoder,e.token),Ie(this.encoder,"4.6.0"),this.encoder}},wi=class extends fi{constructor(...e){super(...e),this.type=di.Awareness,this.description="Awareness states update"}get(e){if(void 0===e.awareness)throw new Error("The awareness message requires awareness as an argument");if(void 0===e.clients)throw new Error("The awareness message requires clients as an argument");let t;return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),t=void 0===e.states?xr(e.awareness,e.clients):xr(e.awareness,e.clients,e.states),qt(this.encoder,t),this.encoder}},vi=class extends fi{constructor(...e){super(...e),this.type=di.Stateless,this.description="A stateless message"}get(e){return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),Ie(this.encoder,e.payload??""),this.encoder}},_i=class extends fi{constructor(...e){super(...e),this.type=di.Sync,this.description="First sync step"}get(e){if(void 0===e.document)throw new Error("The sync step one message requires document as an argument");return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),((e,t)=>{rt(e,0);const n=cn(t);qt(e,n)})(this.encoder,e.document),this.encoder}},ki=class extends fi{constructor(...e){super(...e),this.type=di.Sync,this.description="A document update"}get(e){var t,n;return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),t=this.encoder,n=e.update,rt(t,2),qt(t,n),this.encoder}},Ci=class extends Error{constructor(...e){super(...e),this.code=1001}},Si=class extends li{get effectiveName(){return this.configuration.sessionAwareness?ei(this.configuration.name,this.sessionId):this.configuration.name}constructor(e){super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,sessionAwareness:!1,forceSyncInterval:!1,flushDelay:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.pendingUpdates=[],this.pendingAwarenessClients=/* @__PURE__ */new Set,this.flushTimeout=null,this.sessionId=Math.random().toString(36).slice(2),this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=()=>this.emit("connect"),this.forwardStatus=e=>this.emit("status",e),this.forwardClose=e=>this.emit("close",e),this.forwardDisconnect=e=>this.emit("disconnect",e),this.forwardDestroy=()=>this.emit("destroy"),this.setConfiguration(e),this.configuration.document=e.document?e.document:new Vt,this.configuration.awareness=void 0!==e.awareness?e.awareness:new Ar(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),this.awareness?.on("update",()=>{this.emit("awarenessUpdate",{states:Zr(this.awareness.getStates())})}),this.awareness?.on("change",()=>{this.emit("awarenessChange",{states:Zr(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),this.awareness?.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&"number"==typeof this.configuration.forceSyncInterval&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(e={}){e.websocketProvider||(this.manageSocket=!0,this.configuration.websocketProvider=new pi(e)),this.configuration={...this.configuration,...e}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),0===this.unsyncedChanges&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(_i,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&Tr(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(vi,{documentName:this.effectiveName,payload:e})}async sendToken(){let e;try{e=await this.getToken()}catch(t){return void this.permissionDeniedHandler(`Failed to get token during sendToken(): ${t}`)}this.send(bi,{token:e??"",documentName:this.effectiveName})}get batchingEnabled(){return!!this.configuration.flushDelay&&"number"==typeof this.configuration.flushDelay}documentUpdateHandler(e,t){if(t!==this){if(!this.batchingEnabled)return this.incrementUnsyncedChanges(),void this.send(ki,{update:e,documentName:this.effectiveName});0===this.pendingUpdates.length&&this.incrementUnsyncedChanges(),this.pendingUpdates.push(e),this.scheduleFlush()}}awarenessUpdateHandler({added:e,updated:t,removed:n},r){if(r===this)return;const i=e.concat(t).concat(n);if(this.batchingEnabled){for(const e of i)this.pendingAwarenessClients.add(e);this.scheduleFlush()}else this.send(wi,{awareness:this.awareness,clients:i,documentName:this.effectiveName})}scheduleFlush(){null===this.flushTimeout&&(this.flushTimeout=setTimeout(()=>{this.flushTimeout=null,this.flushPendingUpdates()},this.configuration.flushDelay))}flushPendingUpdates(){if(null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates.length>0){const e=1===this.pendingUpdates.length?this.pendingUpdates[0]:gn(this.pendingUpdates);this.pendingUpdates=[],this.send(ki,{update:e,documentName:this.effectiveName})}if(this.pendingAwarenessClients.size>0){const e=Array.from(this.pendingAwarenessClients);this.pendingAwarenessClients.clear(),this.send(wi,{awareness:this.awareness,clients:e,documentName:this.effectiveName})}}get synced(){return this.isSynced}set synced(e){this.isSynced!==e&&(this.isSynced=e,e&&this.emit("synced",{state:e}))}receiveStateless(e){this.emit("stateless",{payload:e})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect()}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect()}async onOpen(e){this.isAuthenticated=!1,this.emit("open",{event:e}),await this.sendToken(),this.startSync()}async getToken(){return"function"==typeof this.configuration.token?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(_i,{document:this.document,documentName:this.effectiveName}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(wi,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;const n=new yi(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new hi(e.data),{documentName:n}=ti(t.readVarString());t.writeVarString(this.effectiveName),this.emit("message",{event:e,message:new hi(e.data)}),new mi(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates=[],this.pendingAwarenessClients.clear(),this.awareness&&Tr(this.awareness,Array.from(this.awareness.getStates().keys()).filter(e=>e!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(Tr(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.flushPendingUpdates(),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),"undefined"!=typeof window&&"removeEventListener"in window&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("status",this.forwardStatus),this.configuration.websocketProvider.off("status",this.configuration.onStatus),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("status",this.configuration.onStatus),this.configuration.websocketProvider.on("status",this.forwardStatus),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(e){this.emit("authenticationFailed",{reason:e}),this.isAuthenticated=!1}authenticatedHandler(e){this.isAuthenticated=!0,this.authorizedScope=e,this.emit("authenticated",{scope:e})}setAwarenessField(e,t){if(!this.awareness)throw new Ci(`Cannot set awareness field "${e}" to ${JSON.stringify(t)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(e,t)}},Ei="reason-editor";function Ai(e,t){if(!t)throw new Error("collaborationRoom: documentId is required");return`${Ei}:${e}:${t}`}function Ti(e){const[t,n,...r]=e.split(":"),i=r.join(":");return"reason-editor"!==t||"tiptap"!==n&&"plate"!==n?null:i?{engine:n,documentId:i}:null}function xi(){return"undefined"!=typeof process&&(process.env.NEXT_PUBLIC_HOCUSPOCUS_URL??process.env.VITE_HOCUSPOCUS_URL)||"ws://127.0.0.1:1234"}function Ri({engine:e,documentId:t,token:n,url:r=xi(),onSynced:i}){const s=Ai(e,t),o=new Vt,a=new Si({document:o,name:s,token:n,url:r,onSynced:()=>i?.(!0)});return{room:s,ydoc:o,provider:a,destroy(){a.destroy(),o.destroy()}}}function Di({documentId:e,token:t,url:n=xi()}){const r=Ai("plate",e);return[{type:"hocuspocus",options:{name:r,token:t,url:n}},{type:"indexeddb",options:{docName:r}}]}var Oi=["#e11d48","#0891b2","#7c3aed","#ea580c","#16a34a","#2563eb","#db2777","#ca8a04"];function Pi(e){let t=0;for(let n=0;n<e.length;n++)t=31*t+e.charCodeAt(n)|0;return Oi[Math.abs(t)%Oi.length]}var Li={bold:"bold",italic:"italic",underline:"underline",strike:"strike",code:"code",superscript:"superscript",subscript:"subscript",highlight:"highlight","text-color":"textStyle"},Mi={paragraph:{name:"paragraph"},"heading-1":{name:"heading",attrs:{level:1}},"heading-2":{name:"heading",attrs:{level:2}},"heading-3":{name:"heading",attrs:{level:3}},"heading-4":{name:"heading",attrs:{level:4}},"heading-5":{name:"heading",attrs:{level:5}},"heading-6":{name:"heading",attrs:{level:6}},blockquote:{name:"blockquote"},"code-block":{name:"codeBlock"},"bullet-list":{name:"bulletList"},"ordered-list":{name:"orderedList"},"task-list":{name:"taskList"},table:{name:"table"},callout:{name:"callout"},columns:{name:"columns"}},Ni={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},Ii={"table.add-row-before":"addRowBefore","table.add-row-after":"addRowAfter","table.delete-row":"deleteRow","table.add-column-before":"addColumnBefore","table.add-column-after":"addColumnAfter","table.delete-column":"deleteColumn","table.merge-cells":"mergeCells","table.split-cell":"splitCell","table.toggle-header-row":"toggleHeaderRow","table.delete":"deleteTable"};function Ui(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function ji(e){return{engine:"tiptap",execute(t,n){!function(e,t,n){const r=()=>e.chain().focus(),i=e.commands,s=Ii[t];if(s)return void r()[s]?.().run();const o=Ni[t];if(o)r().setTextAlign?.(o).run();else switch(t){case"undo":return void i.undo?.();case"redo":return void i.redo?.();case"bold":return void r().toggleBold().run();case"italic":return void r().toggleItalic().run();case"underline":return void r().toggleUnderline?.().run();case"strike":return void r().toggleStrike().run();case"code":return void r().toggleCode().run();case"superscript":return void r().toggleSuperscript?.().run();case"subscript":return void r().toggleSubscript?.().run();case"text-color":{const t=n?.value??"#ef4444";return void(e.isActive("textStyle",{color:t})?r().unsetColor?.().run():r().setColor?.(t).run())}case"highlight":{const t=n?.value??"#fde047";return void(e.isActive("highlight")?r().unsetHighlight?.().run():r().setHighlight?.({color:t}).run())}case"clear-formatting":return void r().clearNodes().unsetAllMarks().run();case"paragraph":return void r().setParagraph().run();case"heading-1":case"heading-2":case"heading-3":case"heading-4":case"heading-5":case"heading-6":{const e=Number(t.slice(8));return void r().toggleHeading({level:e}).run()}case"blockquote":return void r().toggleBlockquote().run();case"code-block":return void r().toggleCodeBlock().run();case"bullet-list":return void r().toggleBulletList().run();case"ordered-list":return void r().toggleOrderedList().run();case"task-list":return void r().toggleTaskList?.().run();case"indent":return void r().indent?.().run();case"outdent":return void r().outdent?.().run();case"link":{const e=Ui(n,"Link URL");if(!e)return;return void r().extendMarkRange("link").setLink({href:e}).run()}case"image":{const e=Ui(n,"Image URL");if(!e)return;const t=r();return void("function"==typeof t.setImageInline?t.setImageInline({src:e}).run():t.setImage?.({src:e}).run())}case"video":{const e=Ui(n,"Video URL");if(!e)return;return void r().setVideo?.({src:e}).run()}case"table":return void r().insertTable?.({rows:3,cols:3,withHeaderRow:!0}).run();case"horizontal-rule":return void r().setHorizontalRule().run();case"emoji":return void r().insertContent(":").run();case"math":return void r().setKatex?.({text:n?.value??""}).run();case"callout":return void r().setCallout?.({type:"note",title:"",body:""}).run();case"columns":return void r().insertColumns?.({cols:2}).run();case"transcribe":return void i.toggleTranscribe?.();default:;}}(e,t,n)},isActive:t=>function(e,t){const n=Ni[t];if(n)return e.isActive({textAlign:n});const r=Mi[t];if(r)return e.isActive(r.name,r.attrs);const i=Li[t];return i?"text-color"===t?!!e.getAttributes("textStyle").color:e.isActive(i):"link"===t?e.isActive("link"):"transcribe"===t&&!!Ee(e)?.listening}(e,t),isEnabled:t=>function(e,t){const n=function(e){switch(e){case"highlight":return"highlight";case"text-color":return"color";case"superscript":return"superscript";case"subscript":return"subscript";case"task-list":return"taskList";case"link":return"link";case"image":return"image";case"video":return"video";case"table":return"table";case"emoji":return"emoji";case"math":return"katex";case"callout":return"callout";case"columns":return"columns";case"transcribe":return"transcribe";case"indent":case"outdent":return"indent";case"align-left":case"align-center":case"align-right":case"align-justify":return"textAlign";default:return}}(t);if(n&&!function(e,t){return e.extensionManager.extensions.some(e=>e.name===t)}(e,n))return!1;if("undo"===t)return e.can().undo();if("redo"===t)return e.can().redo();if("transcribe"===t)return Ae();const r=Ii[t];return r?!!e.isActive("table")&&Boolean(e.can()[r]?.()):e.isEditable}(e,t),getValue:t=>function(e,t){return"text-color"===t?e.getAttributes("textStyle").color:"highlight"===t?e.getAttributes("highlight").color:"link"===t?e.getAttributes("link").href:void 0}(e,t),subscribe(t){e.on("transaction",t),e.on("selectionUpdate",t);const n=Te(e,t);return()=>{e.off("transaction",t),e.off("selectionUpdate",t),n()}}}}function Fi(e){return"string"==typeof e&&/^#[0-9a-fA-F]{6}$/.test(e)}var Bi=e=>Array.from(e.entries()).map(([e,t])=>t&&t.user?{clientId:e,...t.user}:{clientId:e}),Wi=()=>null,Hi=e=>({...e,color:Fi(e.color)?e.color:"transparent"}),qi=An.create({name:"collaborationCaret",priority:999,addOptions:()=>({provider:null,user:{name:null,color:null},render:e=>{const t=document.createElement("span"),{color:n}=Hi(e);t.classList.add("collaboration-carets__caret"),t.style.borderColor=n;const r=document.createElement("div");return r.classList.add("collaboration-carets__label"),r.style.backgroundColor=n,r.insertBefore(document.createTextNode(e.name),null),t.insertBefore(r,null),t},selectionRender:e=>Fi(e.color)?jt(e):{},onUpdate:Wi}),onCreate(){if(this.options.onUpdate,!this.options.provider)throw new Error('The "provider" option is required for the CollaborationCaret extension')},addStorage:()=>({users:[]}),addCommands(){return{updateUser:e=>()=>(this.options.provider.awareness.setLocalStateField("user",e),!0),user:e=>({editor:t})=>t.commands.updateUser(e)}},addProseMirrorPlugins(){const{provider:e}=this.options,t=this.storage,n=this.options.user;return[new Tn({key:new xn("collaborationCaretAwarenessListener"),view:()=>{const r=()=>{t.users=Bi(e.awareness.states)};return e.awareness.setLocalStateField("user",n),t.users=Bi(e.awareness.states),e.awareness.on("update",r),{destroy:()=>{e.awareness.off("update",r),t.users=[]}}}}),Qt(e.awareness,{cursorBuilder:e=>this.options.render(Hi(e)),selectionBuilder:e=>this.options.selectionRender(Hi(e))})]}});function Vi({documentId:e,initialContent:t="",user:n,authToken:r,className:i}){const[s,o]=bn.useState(null),[a,d]=bn.useState(null),u=Ai("tiptap",e),f=n.color??Pi(n.id);bn.useEffect(()=>{if(!r)return;const t=Ri({engine:"tiptap",documentId:e,token:r});return d(t),()=>{d(null),t.destroy()}},[r,e]);const g=bn.useMemo(()=>{const e=h(l());return a?function(e,t,n){return[...e.filter(e=>"undoRedo"!==e?.name),rn.configure({document:t.ydoc}),qi.configure({provider:t.provider,user:n})]}(e,a,{name:n.name,color:f}):e},[a,n.name,f]),p=bn.useMemo(()=>s?ji(s):Rr("tiptap"),[s]);/* @__PURE__ */
|
|
14
|
-
return Dn("div",{className:`flex h-full min-h-0 w-full flex-col ${i??""}`,"data-room":u,children:/* @__PURE__ */Dn(c,{className:"flex min-h-0 flex-1 flex-col",extensions:g,immediatelyRender:!1,initialContent:a?void 0:t,onEditor:o,rebuildKey:a?`collab:${u}`:"local",textDirection:"auto",children:({EditorSurface:e})=>/* @__PURE__ */On(Rn,{children:[/* @__PURE__ */Dn(jr,{adapter:p}),/* @__PURE__ */Dn("div",{className:"relative min-h-0 flex-1 overflow-auto",children:/* @__PURE__ */Dn(e,{className:"h-full"})})]})})})}var zi={bold:I.bold,italic:I.italic,underline:I.underline,strike:I.strikethrough,code:I.code,superscript:I.sup,subscript:I.sub,highlight:I.highlight,"text-color":I.color},$i={superscript:I.sub,subscript:I.sup},Yi={paragraph:I.p,"heading-1":I.h1,"heading-2":I.h2,"heading-3":I.h3,"heading-4":I.h4,"heading-5":I.h5,"heading-6":I.h6,blockquote:I.blockquote},Ji={"bullet-list":d.Disc,"ordered-list":d.Decimal,"task-list":I.listTodo},Qi={"bullet-list":[d.Disc,d.Circle,d.Square],"ordered-list":[d.Decimal,d.LowerAlpha,d.UpperAlpha,d.LowerRoman,d.UpperRoman],"task-list":[I.listTodo]},Ki={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},Gi=/* @__PURE__ */new Set(["table.add-row-before","table.add-row-after","table.delete-row","table.add-column-before","table.add-column-after","table.delete-column","table.merge-cells","table.split-cell","table.toggle-header-row","table.delete"]);function Xi(e){return!!e.selection&&Boolean(f(e))}function Zi(e){if(!Xi(e))return{canMerge:!1,canSplit:!1};const t=ue(e);if(!t?.length)return{canMerge:!1,canSplit:!1};const n=t.map(([e])=>e);if(n.length>1){const{maxCol:t,maxRow:r,minCol:i,minRow:s}=R(e,n),o=n.reduce((e,t)=>e+fe(t)*B(t),0)===(t-i+1)*(r-s+1);return{canMerge:e.api.isExpanded()&&o,canSplit:!1}}const[r]=n;return{canMerge:!1,canSplit:fe(r)>1||B(r)>1}}function es(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function ts(e,t){const n=function(e){if(Gi.has(e)||"table"===e)return I.table;switch(e){case"highlight":return I.highlight;case"text-color":return I.color;case"link":return I.link;case"image":return I.img;case"video":return I.video;case"math":return I.equation;case"callout":return I.callout;case"columns":return I.columnGroup;case"transcribe":return"transcribe";case"emoji":return I.emoji;case"code-block":return I.codeBlock;case"bullet-list":case"ordered-list":case"task-list":return I.list;case"indent":case"outdent":return I.indent;case"align-left":case"align-center":case"align-right":case"align-justify":return I.textAlign;default:return}}(t);return!(n&&!function(e,t){return Boolean(e.plugins?.[t])}(e,n))&&("undo"===t?e.history.undos.length>0:"redo"===t?e.history.redos.length>0:"transcribe"===t?te()&&!e.api.isReadOnly?.():"table.merge-cells"===t?Zi(e).canMerge:"table.split-cell"===t?Zi(e).canSplit:Gi.has(t)?Xi(e):!e.api.isReadOnly?.())}function ns(e){return{engine:"plate",execute(t,n){!function(e,t,n){e.tf.focus();const r=zi[t];if(r&&"text-color"!==t&&"highlight"!==t)return void e.tf.toggleMark(r,{remove:$i[t]});const i=Yi[t];if(i)return void e.tf.toggleBlock(i,i===I.blockquote?{wrap:!0}:void 0);const s=Ji[t];if(s)return void S(e,{listStyleType:s});const o=Ki[t];if(o)e.getTransforms(P).textAlign.setNodes(o);else switch(t){case"undo":return void e.tf.undo();case"redo":return void e.tf.redo();case"text-color":{const t=n?.value??"#ef4444";return void(e.api.marks()?.[I.color]===t?e.tf.removeMarks(I.color):e.tf.addMarks({[I.color]:t}))}case"highlight":return void(e.api.marks()?.[I.highlight]?e.tf.removeMarks(I.highlight):e.tf.addMarks({[I.highlight]:n?.value??"#fde047"}));case"clear-formatting":return e.tf.removeMarks(Object.values(zi)),void e.tf.toggleBlock(I.p);case"code-block":return void ge(e);case"link":return void(n?.value?m(e,{url:n.value}):A(e,{focused:!0}));case"image":{const t=es(n,"Image URL");if(!t)return;return void b(e,t)}case"video":{const t=es(n,"Video URL");if(!t)return;return void O(e,{select:!0,type:I.video,url:t})}case"table":return void de(e,{colCount:3,rowCount:3},{select:!0});case"horizontal-rule":return void e.tf.insertNodes({children:[{text:""}],type:I.hr});case"emoji":return void e.tf.insertText(":");case"math":return void K(e,{select:!0});case"callout":return void u(e,{select:!0});case"columns":return void x(e,{columns:2,select:!0});case"transcribe":return void j(e).toggle();case"indent":return void w(e);case"outdent":return void k(e);case"table.add-row-before":return void p(e,{before:!0});case"table.add-row-after":return void p(e);case"table.delete-row":return void U(e);case"table.add-column-before":return void D(e,{before:!0});case"table.add-column-after":return void D(e);case"table.delete-column":return void z(e);case"table.merge-cells":return void g(e);case"table.split-cell":return void E(e);case"table.toggle-header-row":{const t=f(e);if(!t)return;const[n,r]=t;return void e.tf.setNodes({headerRow:!n.headerRow},{at:r})}case"table.delete":return void he(e);default:;}}(e,t,n)},isActive(t){if("transcribe"===t)return j(e).getState().listening;if(!e.selection)return!1;try{return function(e,t){if("task-list"===t)return C(e);const n=Qi[t];if(n)return Q(e,n);const r=zi[t];if(r)return Boolean(e.api.marks()?.[r]);const i=Yi[t];if(i)return e.api.some({match:{type:i}});if("code-block"===t)return e.api.some({match:{type:I.codeBlock}});if("table"===t)return Xi(e);if("callout"===t)return e.api.some({match:{type:I.callout}});if("columns"===t)return e.api.some({match:{type:I.column}});if("link"===t)return e.api.some({match:{type:I.link}});if("transcribe"===t)return j(e).getState().listening;const s=Ki[t];return!!s&&e.api.some({match:e=>e[I.textAlign]===s})}(e,t)}catch{return!1}},isEnabled(t){try{return ts(e,t)}catch{return!1}},getValue(t){if(e.selection)try{return function(e,t){const n=e.api.marks();return"text-color"===t?n?.[I.color]:"highlight"===t?n?.[I.highlight]:void 0}(e,t)}catch{return}},subscribe(t){const n=e.apply;let r=!1;e.apply=i=>{n.call(e,i),r||(r=!0,queueMicrotask(()=>{r=!1,t()}))};const i=j(e).subscribe(t);return()=>{e.apply=n,i()}}}}var rs,is=class{constructor(e,t){this.clock=e,this.len=t}},ss=class{constructor(){this.clients=/* @__PURE__ */new Map}},os=(e,t,n)=>t.clients.forEach((t,r)=>{const i=e.doc.store.clients.get(r);if(null!=i){const r=i[i.length-1],s=r.id.clock+r.length;for(let o=0,a=t[o];o<t.length&&a.clock<s;a=t[++o])fo(e,i,a.clock,a.len,n)}}),as=(e,t)=>{const n=e.clients.get(t.client);return void 0!==n&&null!==((e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const i=Ze((n+r)/2),s=e[i],o=s.clock;if(o<=t){if(t<o+s.len)return i;n=i+1}else r=i-1}return null})(n,t.clock)},cs=e=>{e.clients.forEach(e=>{let t,n;for(e.sort((e,t)=>e.clock-t.clock),t=1,n=1;t<e.length;t++){const r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new is(r.clock,st(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},ls=e=>{const t=new ss;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){const s=r.slice();for(let t=n+1;t<e.length;t++)ct(s,e[t].clients.get(i)||[]);t.clients.set(i,s)}});return cs(t),t},hs=(e,t,n,r)=>{en(e.clients,t,()=>[]).push(new is(n,r))},ds=()=>new ss,us=(e,t)=>{rt(e.restEncoder,t.clients.size),yn(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),rt(e.restEncoder,t);const r=n.length;rt(e.restEncoder,r);for(let i=0;i<r;i++){const t=n[i];e.writeDsClock(t.clock),e.writeDsLen(t.len)}})},fs=e=>{const t=new ss,n=Dt(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=Dt(e.restDecoder),r=Dt(e.restDecoder);if(r>0){const i=en(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new is(e.readDsClock(),e.readDsLen()))}}return t},gs=(e,t,n)=>{const r=new ss,i=Dt(e.restDecoder);for(let s=0;s<i;s++){e.resetDsCurVal();const i=Dt(e.restDecoder),s=Dt(e.restDecoder),o=n.clients.get(i)||[],a=so(n,i);for(let n=0;n<s;n++){const n=e.readDsClock(),s=n+e.readDsLen();if(n<a){a<s&&hs(r,i,a,s-a);let e=ao(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,nc(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<s);)c.deleted||(s<c.id.clock+c.length&&o.splice(e,0,nc(t,c,s-c.id.clock)),c.delete(t))}else hs(r,i,n,s-n)}}if(r.clients.size>0){const e=new Ss;return rt(e.restEncoder,0),us(e,r),e.toUint8Array()}return null},ps=ot,ms=class e extends Ge{constructor({guid:e=xe(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:s=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=ps(),this.guid=e,this.collectionid=t,this.share=/* @__PURE__ */new Map,this.store=new ro,this._transaction=null,this._transactionCleanups=[],this.subdocs=/* @__PURE__ */new Set,this._item=null,this.shouldLoad=o,this.autoLoad=s,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Zt(e=>{this.on("load",()=>{this.isLoaded=!0,e(this)})});const a=()=>Zt(e=>{const t=n=>{void 0!==n&&!0!==n||(this.off("sync",t),e())};this.on("sync",t)});this.on("sync",e=>{!1===e&&this.isSynced&&(this.whenSynced=a()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=a()}load(){const e=this._item;null===e||this.shouldLoad||wo(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(yn(this.subdocs).map(e=>e.guid))}transact(e,t=null){return wo(this,e,t)}get(e,t=Vo){const n=en(this.share,e,()=>{const e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==Vo&&r!==t){if(r===Vo){const r=new t;r._map=n._map,n._map.forEach(e=>{for(;null!==e;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;null!==e;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw new Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=""){return this.get(e,ca)}getText(e=""){return this.get(e,Aa)}getMap(e=""){return this.get(e,ha)}getXmlElement(e=""){return this.get(e,Ra)}getXmlFragment(e=""){return this.get(e,xa)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,yn(this.subdocs).forEach(e=>e.destroy());const t=this._item;if(null!==t){this._item=null;const n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,wo(t.parent.doc,e=>{const r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}},ys=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Dt(this.restDecoder)}readDsLen(){return Dt(this.restDecoder)}},bs=class extends ys{readLeftID(){return Ws(Dt(this.restDecoder),Dt(this.restDecoder))}readRightID(){return Ws(Dt(this.restDecoder),Dt(this.restDecoder))}readClient(){return Dt(this.restDecoder)}readInfo(){return xt(this.restDecoder)}readString(){return an(this.restDecoder)}readParentInfo(){return 1===Dt(this.restDecoder)}readTypeRef(){return Dt(this.restDecoder)}readLen(){return Dt(this.restDecoder)}readAny(){return nn(this.restDecoder)}readBuf(){return Bt(Lt(this.restDecoder))}readJSON(){return JSON.parse(an(this.restDecoder))}readKey(){return an(this.restDecoder)}},ws=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Dt(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Dt(this.restDecoder)+1;return this.dsCurrVal+=e,e}},vs=class extends ws{constructor(e){super(e),this.keys=[],Dt(e),this.keyClockDecoder=new Ot(Lt(e)),this.clientDecoder=new tn(Lt(e)),this.leftClockDecoder=new Ot(Lt(e)),this.rightClockDecoder=new Ot(Lt(e)),this.infoDecoder=new sn(Lt(e),xt),this.stringDecoder=new Jt(Lt(e)),this.parentInfoDecoder=new sn(Lt(e),xt),this.typeRefDecoder=new tn(Lt(e)),this.lenDecoder=new tn(Lt(e))}readLeftID(){return new Fs(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Fs(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return 1===this.parentInfoDecoder.read()}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return nn(this.restDecoder)}readBuf(){return Lt(this.restDecoder)}readJSON(){return nn(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const e=this.stringDecoder.read();return this.keys.push(e),e}}},_s=class{constructor(){this.restEncoder=At()}toUint8Array(){return ht(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){rt(this.restEncoder,e)}writeDsLen(e){rt(this.restEncoder,e)}},ks=class extends _s{writeLeftID(e){rt(this.restEncoder,e.client),rt(this.restEncoder,e.clock)}writeRightID(e){rt(this.restEncoder,e.client),rt(this.restEncoder,e.clock)}writeClient(e){rt(this.restEncoder,e)}writeInfo(e){dn(this.restEncoder,e)}writeString(e){Ie(this.restEncoder,e)}writeParentInfo(e){rt(this.restEncoder,e?1:0)}writeTypeRef(e){rt(this.restEncoder,e)}writeLen(e){rt(this.restEncoder,e)}writeAny(e){Me(this.restEncoder,e)}writeBuf(e){qt(this.restEncoder,e)}writeJSON(e){Ie(this.restEncoder,JSON.stringify(e))}writeKey(e){Ie(this.restEncoder,e)}},Cs=class{constructor(){this.restEncoder=At(),this.dsCurrVal=0}toUint8Array(){return ht(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,rt(this.restEncoder,t)}writeDsLen(e){0===e&&Ut(),rt(this.restEncoder,e-1),this.dsCurrVal+=e}},Ss=class extends Cs{constructor(){super(),this.keyMap=/* @__PURE__ */new Map,this.keyClock=0,this.keyClockEncoder=new Nt,this.clientEncoder=new pn,this.leftClockEncoder=new Nt,this.rightClockEncoder=new Nt,this.infoEncoder=new Ct(dn),this.stringEncoder=new ln,this.parentInfoEncoder=new Ct(dn),this.typeRefEncoder=new pn,this.lenEncoder=new pn}toUint8Array(){const e=At();return rt(e,0),qt(e,this.keyClockEncoder.toUint8Array()),qt(e,this.clientEncoder.toUint8Array()),qt(e,this.leftClockEncoder.toUint8Array()),qt(e,this.rightClockEncoder.toUint8Array()),qt(e,ht(this.infoEncoder)),qt(e,this.stringEncoder.toUint8Array()),qt(e,ht(this.parentInfoEncoder)),qt(e,this.typeRefEncoder.toUint8Array()),qt(e,this.lenEncoder.toUint8Array()),ut(e,ht(this.restEncoder)),ht(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Me(this.restEncoder,e)}writeBuf(e){qt(this.restEncoder,e)}writeJSON(e){Me(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);void 0===t?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}},Es=(e,t,n)=>{const r=/* @__PURE__ */new Map;n.forEach((e,n)=>{so(t,n)>e&&r.set(n,e)}),io(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),rt(e.restEncoder,r.size),yn(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{((e,t,n,r)=>{r=st(r,t[0].id.clock);const i=ao(t,r);rt(e.restEncoder,t.length-i),e.writeClient(n),rt(e.restEncoder,r);const s=t[i];s.write(e,r-s.id.clock);for(let o=i+1;o<t.length;o++)t[o].write(e,0)})(e,t.clients.get(n),n,r)})},As=(e,t,n,r=new vs(e))=>wo(t,e=>{e.local=!1;let t=!1;const n=e.doc,i=n.store,s=((e,t)=>{const n=Qe(),r=Dt(e.restDecoder);for(let i=0;i<r;i++){const r=Dt(e.restDecoder),i=new Array(r),s=e.readClient();let o=Dt(e.restDecoder);n.set(s,{i:0,refs:i});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();i[n]=new Ma(Ws(s,o),t),o+=t;break}case 10:{const t=Dt(e.restDecoder);i[n]=new cc(Ws(s,o),t),o+=t;break}default:{const a=!(192&r),c=new sc(Ws(s,o),null,128&~r?null:e.readLeftID(),null,64&~r?null:e.readRightID(),a?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,!a||32&~r?null:e.readString(),oc(e,r));i[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let i=yn(n.keys()).sort((e,t)=>e-t);if(0===i.length)return null;const s=()=>{if(0===i.length)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;){if(i.pop(),!(i.length>0))return null;e=n.get(i[i.length-1])}return e};let o=s();if(null===o)return null;const a=new ro,c=/* @__PURE__ */new Map,l=(e,t)=>{const n=c.get(e);(null==n||n>t)&&c.set(e,t)};let h=o.refs[o.i++];const d=/* @__PURE__ */new Map,u=()=>{for(const e of r){const t=e.id.client,r=n.get(t);r?(r.i--,a.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):a.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(h.constructor!==cc){const i=en(d,h.id.client,()=>so(t,h.id.client))-h.id.clock;if(i<0)r.push(h),l(h.id.client,h.id.clock-1),u();else{const s=h.getMissing(e,t);if(null!==s){r.push(h);const e=n.get(s)||{refs:[],i:0};if(e.refs.length!==e.i){h=e.refs[e.i++];continue}l(s,so(t,s)),u()}else(0===i||i<h.length)&&(h.integrate(e,i),d.set(h.id.client,h.id.clock+h.length))}}if(r.length>0)h=r.pop();else if(null!==o&&o.i<o.refs.length)h=o.refs[o.i++];else{if(o=s(),null===o)break;h=o.refs[o.i++]}}if(a.clients.size>0){const e=new Ss;return Es(e,a,/* @__PURE__ */new Map),rt(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null})(e,i,s),a=i.pendingStructs;if(a){for(const[e,n]of a.missing)if(n<so(i,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=a.missing.get(e);(null==n||n>t)&&a.missing.set(e,t)}a.update=xo([a.update,o.update])}}else i.pendingStructs=o;const c=gs(r,e,i);if(i.pendingDs){const t=new vs(Ft(i.pendingDs));Dt(t.restDecoder);const n=gs(t,e,i);i.pendingDs=c&&n?xo([c,n]):c||n}else i.pendingDs=c;if(t){const t=i.pendingStructs.update;i.pendingStructs=null,Ts(e.doc,t)}},n,!1),Ts=(e,t,n,r=vs)=>{const i=Ft(t);As(i,e,n,new r(i))},xs=(e,t,n)=>Ts(e,t,n,bs),Rs=(e,t,n=/* @__PURE__ */new Map)=>{Es(e,t.store,n),us(e,(e=>{const t=ds();return e.clients.forEach((e,n)=>{const r=[];for(let t=0;t<e.length;t++){const n=e[t];if(n.deleted){const i=n.id.clock;let s=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[1+ ++t])s+=n.length;r.push(new is(i,s))}}r.length>0&&t.clients.set(n,r)}),t})(t.store))},Ds=(e,t)=>((e,t=new Uint8Array([0]),n=new Ss)=>{const r=Os(t);Rs(n,e,r);const i=[n.toUint8Array()];if(e.store.pendingDs&&i.push(e.store.pendingDs),e.store.pendingStructs&&i.push(Ro(e.store.pendingStructs.update,t)),i.length>1){if(n.constructor===ks)return Ao(i.map((e,t)=>0===t?e:Lo(e)));if(n.constructor===Ss)return xo(i)}return i[0]})(e,t,new ks),Os=e=>(e=>{const t=/* @__PURE__ */new Map,n=Dt(e.restDecoder);for(let r=0;r<n;r++){const n=Dt(e.restDecoder),r=Dt(e.restDecoder);t.set(n,r)}return t})(new ys(Ft(e))),Ps=(e,t)=>(rt(e.restEncoder,t.size),yn(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{rt(e.restEncoder,t),rt(e.restEncoder,n)}),e),Ls=(e,t=new Cs)=>(e instanceof Map?Ps(t,e):((e,t)=>{Ps(e,io(t.store))})(t,e),t.toUint8Array()),Ms=class{constructor(){this.l=[]}},Ns=()=>new Ms,Is=(e,t)=>e.l.push(t),Us=(e,t)=>{const n=e.l;n.length;e.l=n.filter(e=>t!==e),e.l.length},js=(e,t,n)=>ze(e.l,[t,n]),Fs=class{constructor(e,t){this.client=e,this.clock=t}},Bs=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,Ws=(e,t)=>new Fs(e,t),Hs=(e,t)=>{rt(e,t.client),rt(e,t.clock)},qs=e=>Ws(Dt(e),Dt(e)),Vs=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Ut()},zs=(e,t)=>{for(;null!==t;){if(t.parent===e)return!0;t=t.parent._item}return!1},$s=class{constructor(e,t,n,r=0){this.type=e,this.tname=t,this.item=n,this.assoc=r}},Ys=class{constructor(e,t,n=0){this.type=e,this.index=t,this.assoc=n}},Js=(e,t,n)=>{let r=null,i=null;return null===e._item?i=Vs(e):r=Ws(e._item.id.client,e._item.id.clock),new $s(r,i,t,n)},Qs=(e,t,n=0)=>{let r=e._start;if(n<0){if(0===t)return Js(e,null,n);t--}for(;null!==r;){if(!r.deleted&&r.countable){if(r.length>t)return Js(e,Ws(r.id.client,r.id.clock+t),n);t-=r.length}if(null===r.right&&n<0)return Js(e,r.lastId,n);r=r.right}return Js(e,null,n)},Ks=e=>{const t=At();return((e,t)=>{const{type:n,tname:r,item:i,assoc:s}=t;if(null!==i)rt(e,0),Hs(e,i);else if(null!==r)dn(e,1),Ie(e,r);else{if(null===n)throw Ut();dn(e,2),Hs(e,n)}je(e,s)})(t,e),ht(t)},Gs=e=>(e=>{let t=null,n=null,r=null;switch(Dt(e)){case 0:r=qs(e);break;case 1:n=an(e);break;case 2:t=qs(e)}const i=St(e)?zt(e):0;return new $s(t,n,r,i)})(Ft(e)),Xs=(e,t,n=!0)=>{const r=t.store,i=e.item,s=e.type,o=e.tname,a=e.assoc;let c=null,l=0;if(null!==i){if(so(r,i.client)<=i.clock)return null;const e=n?ec(r,i):((e,t)=>{const n=co(e,t);return{item:n,diff:t.clock-n.id.clock}})(r,i),t=e.item;if(!(t instanceof sc))return null;if(c=t.parent,null===c._item||!c._item.deleted){l=t.deleted||!t.countable?0:e.diff+(a>=0?0:1);let n=t.left;for(;null!==n;)!n.deleted&&n.countable&&(l+=n.length),n=n.left}}else{if(null!==o)c=t.get(o);else{if(null===s)throw Ut();{if(so(r,s.client)<=s.clock)return null;const{item:e}=n?ec(r,s):{item:co(r,s)};if(!(e instanceof sc&&e.content instanceof Za))return null;c=e.content.type}}l=a>=0?c._length:0}return((e,t,n=0)=>new Ys(e,t,n))(c,l,e.assoc)},Zs=(e,t)=>e===t||null!==e&&null!==t&&e.tname===t.tname&&Bs(e.item,t.item)&&Bs(e.type,t.type)&&e.assoc===t.assoc,eo=class{constructor(e,t){this.ds=e,this.sv=t}},to=(rs=ds(),new eo(rs,/* @__PURE__ */new Map),(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!as(t.ds,e.id)),no=(e,t)=>{const n=en(e.meta,no,gt),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<so(r,n)&&ho(e,Ws(n,t))}),os(e,t.ds,e=>{}),n.add(t))},ro=class{constructor(){this.clients=/* @__PURE__ */new Map,this.pendingStructs=null,this.pendingDs=null}},io=e=>{const t=/* @__PURE__ */new Map;return e.clients.forEach((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},so=(e,t)=>{const n=e.clients.get(t);if(void 0===n)return 0;const r=n[n.length-1];return r.id.clock+r.length},oo=(e,t)=>{let n=e.clients.get(t.id.client);if(void 0===n)n=[],e.clients.set(t.id.client,n);else{const e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw Ut()}n.push(t)},ao=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=Ze(t/(s+i.length-1)*r);for(;n<=r;){if(i=e[o],s=i.id.clock,s<=t){if(t<s+i.length)return o;n=o+1}else r=o-1;o=Ze((n+r)/2)}throw Ut()},co=(e,t)=>{const n=e.clients.get(t.client);return n[ao(n,t.clock)]},lo=(e,t,n)=>{const r=ao(t,n),i=t[r];return i.id.clock<n&&i instanceof sc?(t.splice(r+1,0,nc(e,i,n-i.id.clock)),r+1):r},ho=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[lo(e,n,t.clock)]},uo=(e,t,n)=>{const r=t.clients.get(n.client),i=ao(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==Ma&&r.splice(i+1,0,nc(e,s,n.clock-s.id.clock+1)),s},fo=(e,t,n,r,i)=>{if(0===r)return;const s=n+r;let o,a=lo(e,t,n);do{o=t[a++],s<o.id.clock+o.length&&lo(e,t,s),i(o)}while(a<t.length&&t[a].id.clock<s)},go=class{constructor(e,t,n){this.doc=e,this.deleteSet=new ss,this.beforeState=io(e.store),this.afterState=/* @__PURE__ */new Map,this.changed=/* @__PURE__ */new Map,this.changedParentTypes=/* @__PURE__ */new Map,this._mergeStructs=[],this.origin=t,this.meta=/* @__PURE__ */new Map,this.local=n,this.subdocsAdded=/* @__PURE__ */new Set,this.subdocsRemoved=/* @__PURE__ */new Set,this.subdocsLoaded=/* @__PURE__ */new Set,this._needFormattingCleanup=!1}},po=(e,t)=>!(0===t.deleteSet.clients.size&&!bt(t.afterState,(e,n)=>t.beforeState.get(n)!==e))&&(cs(t.deleteSet),((e,t)=>{Es(e,t.doc.store,t.beforeState)})(e,t),us(e,t.deleteSet),!0),mo=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&en(e.changed,t,gt).add(n)},yo=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0&&(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n));n=r,r=e[--i-1])n instanceof sc&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const s=t-i;return s&&e.splice(t+1-s,s),s},bo=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,i=r.store,s=n.deleteSet,o=n._mergeStructs;try{cs(s),n.afterState=io(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach((t,r)=>e.push(()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(null===r._item||!r._item.deleted)&&((t=t.filter(e=>null===e.target._item||!e.target._item.deleted)).forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{js(r._dEH,t,n)}))}),e.push(()=>r.emit("afterTransaction",[n,r])),e.push(()=>{n._needFormattingCleanup&&Ca(n)})}),ze(e,[])}finally{r.gc&&((e,t,n)=>{for(const[r,i]of e.clients.entries()){const e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){const s=i[r],o=s.clock+s.len;for(let r=ao(e,s.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){const i=e[r];if(s.clock+s.len<=i.id.clock)break;i instanceof sc&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}})(s,i,r.gcFilter),((e,t)=>{e.clients.forEach((e,n)=>{const r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){const n=e[t];for(let e=Be(r.length-1,1+ao(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+yo(r,e)}})})(s,i),n.afterState.forEach((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=i.clients.get(t),n=st(ao(e,r),1);for(let t=e.length-1;t>=n;)t-=1+yo(e,t)}});for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=i.clients.get(t),s=ao(r,n);s+1<r.length&&yo(r,s+1)>1||s>0&&yo(r,s)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(Le(Ne,dt,"[yjs] ",Ht,nt,"Changed the client-id because another client seems to be using it."),r.clientID=ps()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new ks;po(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new Ss;po(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:l}=n;(a.size>0||l.size>0||c.size>0)&&(a.forEach(e=>{e.clientID=r.clientID,null==e.collectionid&&(e.collectionid=r.collectionid),r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit("subdocs",[{loaded:c,added:a,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):bo(e,t+1)}}},wo=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;null===e._transaction&&(s=!0,e._transaction=new go(e,n,r),i.push(e._transaction),1===i.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(s){const t=e._transaction===i[0];e._transaction=null,t&&bo(i,0)}}return o},vo=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=/* @__PURE__ */new Map}},_o=(e,t,n)=>{os(e,n.deletions,n=>{n instanceof sc&&t.scope.some(t=>t===e.doc||zs(t,n))&&tc(n,!1)})},ko=(e,t,n)=>{let r=null;const i=e.doc,s=e.scope;wo(i,n=>{for(;t.length>0&&null===e.currStackItem;){const r=i.store,o=t.pop(),a=/* @__PURE__ */new Set,c=[];let l=!1;os(n,o.insertions,e=>{if(e instanceof sc){if(null!==e.redone){let{item:t,diff:i}=ec(r,e.id);i>0&&(t=ho(n,Ws(t.id.client,t.id.clock+i))),e=t}!e.deleted&&s.some(t=>t===n.doc||zs(t,e))&&c.push(e)}}),os(n,o.deletions,e=>{e instanceof sc&&s.some(t=>t===n.doc||zs(t,e))&&!as(o.insertions,e.id)&&a.add(e)}),a.forEach(t=>{l=null!==ic(n,t,a,o.insertions,e.ignoreRemoteMapChanges,e)||l});for(let t=c.length-1;t>=0;t--){const r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);const o=e.currStackItem;if(null!=o){const t=r.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o},Co=class extends Ge{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=/* @__PURE__ */new Set([null]),ignoreRemoteMapChanges:s=!1,doc:o=(Pe(e)?e[0].doc:e instanceof ms?e:e.doc)}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=s,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!(this.captureTransaction(e)&&this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)&&(this.trackedOrigins.has(e.origin)||e.origin&&this.trackedOrigins.has(e.origin.constructor))))return;const t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);const i=new ss;e.afterState.forEach((t,n)=>{const r=e.beforeState.get(n)||0,s=t-r;s>0&&hs(i,n,r,s)});const s=wt();let o=!1;if(this.lastChange>0&&s-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){const t=r[r.length-1];t.deletions=ls([t.deletions,e.deleteSet]),t.insertions=ls([t.insertions,i])}else r.push(new vo(e.deleteSet,i)),o=!0;t||n||(this.lastChange=s),os(e,e.deleteSet,t=>{t instanceof sc&&this.scope.some(n=>n===e.doc||zs(n,t))&&tc(t,!0)});const a=[{stackItem:r[r.length-1],origin:e.origin,type:t?"redo":"undo",changedParentTypes:e.changedParentTypes},this];o?this.emit("stack-item-added",a):this.emit("stack-item-updated",a)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const t=new Set(this.scope);(e=Pe(e)?e:[e]).forEach(e=>{t.has(e)||(t.add(e),(e instanceof Vo?e.doc!==this.doc:e!==this.doc)&&hn("[yjs#509] Not same Y.Doc"),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>_o(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>_o(n,this,e)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){let e;this.undoing=!0;try{e=ko(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){let e;this.redoing=!0;try{e=ko(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}};var So=class{constructor(e,t){this.gen=function*(e){const t=Dt(e.restDecoder);for(let n=0;n<t;n++){const t=Dt(e.restDecoder),n=e.readClient();let r=Dt(e.restDecoder);for(let i=0;i<t;i++){const t=e.readInfo();if(10===t){const t=Dt(e.restDecoder);yield new cc(Ws(n,r),t),r+=t}else if(31&t){const i=!(192&t),s=new sc(Ws(n,r),null,128&~t?null:e.readLeftID(),null,64&~t?null:e.readRightID(),i?e.readParentInfo()?e.readString():e.readLeftID():null,!i||32&~t?null:e.readString(),oc(e,t));yield s,r+=s.length}else{const t=e.readLen();yield new Ma(Ws(n,r),t),r+=t}}}}(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do{this.curr=this.gen.next().value||null}while(this.filterSkips&&null!==this.curr&&this.curr.constructor===cc);return this.curr}},Eo=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}},Ao=e=>xo(e,bs,ks),To=(e,t)=>{if(e.constructor===Ma){const{client:n,clock:r}=e.id;return new Ma(Ws(n,r+t),e.length-t)}if(e.constructor===cc){const{client:n,clock:r}=e.id;return new cc(Ws(n,r+t),e.length-t)}{const n=e,{client:r,clock:i}=n.id;return new sc(Ws(r,i+t),null,Ws(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},xo=(e,t=vs,n=Ss)=>{if(1===e.length)return e[0];const r=e.map(e=>new t(Ft(e)));let i=r.map(e=>new So(e,!0)),s=null;const o=new n,a=new Eo(o);for(;i=i.filter(e=>null!==e.curr),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){const n=e.curr.id.clock-t.curr.id.clock;return 0===n?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===cc?1:-1:n}return t.curr.id.client-e.curr.id.client}),0!==i.length;){const e=i[0],t=e.curr.id.client;if(null!==s){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=s.struct.id.clock+s.struct.length&&n.id.client>=s.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>s.struct.id.clock+s.struct.length)continue;if(t!==s.struct.id.client)Oo(a,s.struct,s.offset),s={struct:n,offset:0},e.next();else if(s.struct.id.clock+s.struct.length<n.id.clock)if(s.struct.constructor===cc)s.struct.length=n.id.clock+n.length-s.struct.id.clock;else{Oo(a,s.struct,s.offset);const e=n.id.clock-s.struct.id.clock-s.struct.length;s={struct:new cc(Ws(t,s.struct.id.clock+s.struct.length),e),offset:0}}else{const t=s.struct.id.clock+s.struct.length-n.id.clock;t>0&&(s.struct.constructor===cc?s.struct.length-=t:n=To(n,t)),s.struct.mergeWith(n)||(Oo(a,s.struct,s.offset),s={struct:n,offset:0},e.next())}}else s={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===s.struct.id.clock+s.struct.length&&n.constructor!==cc;n=e.next())Oo(a,s.struct,s.offset),s={struct:n,offset:0}}null!==s&&(Oo(a,s.struct,s.offset),s=null),Po(a);const c=r.map(e=>fs(e)),l=ls(c);return us(o,l),o.toUint8Array()},Ro=(e,t,n=vs,r=Ss)=>{const i=Os(t),s=new r,o=new Eo(s),a=new n(Ft(e)),c=new So(a,!1);for(;c.curr;){const e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor!==cc)if(e.id.clock+e.length>n)for(Oo(o,e,st(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)Oo(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next();else c.next()}Po(o);const l=fs(a);return us(s,l),s.toUint8Array()},Do=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:ht(e.encoder.restEncoder)}),e.encoder.restEncoder=At(),e.written=0)},Oo=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Do(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),rt(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Po=e=>{Do(e);const t=e.encoder.restEncoder;rt(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];rt(t,r.written),ut(t,r.restEncoder)}},Lo=e=>((e,t,n,r)=>{const i=new n(Ft(e)),s=new So(i,!1),o=new r,a=new Eo(o);for(let l=s.curr;null!==l;l=s.next())Oo(a,t(l),0);Po(a);const c=fs(i);return us(o,c),o.toUint8Array()})(e,at,vs,ks),Mo="You must not compute changes after the event-handler fired.",No=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Io(this.currentTarget,this.target))}deletes(e){return as(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw Xt(Mo);const e=/* @__PURE__ */new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(null!==n){const r=t._map.get(n);let i,s;if(this.adds(r)){let e=r.left;for(;null!==e&&this.adds(e);)e=e.left;if(this.deletes(r)){if(null===e||!this.deletes(e))return;i="delete",s=mt(e.content.getContent())}else null!==e&&this.deletes(e)?(i="update",s=mt(e.content.getContent())):(i="add",s=void 0)}else{if(!this.deletes(r))return;i="delete",s=mt(r.content.getContent())}e.set(n,{action:i,oldValue:s})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(null===e){if(0===this.transaction.doc._transactionCleanups.length)throw Xt(Mo);const t=this.target,n=gt(),r=gt(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null;const s=()=>{e&&i.push(e)};for(let i=t._start;null!==i;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&(null!==e&&void 0!==e.delete||(s(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?(null!==e&&void 0!==e.insert||(s(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):(null!==e&&void 0!==e.retain||(s(),e={retain:0}),e.retain+=i.length);null!==e&&void 0===e.retain&&s()}this._changes=e}return e}},Io=(e,t)=>{const n=[];for(;null!==t._item&&t!==e;){if(null!==t._item.parentSub)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&null!==r;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},Uo=()=>{hn("Invalid access: Add Yjs type to a document before reading data.")},jo=0,Fo=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=jo++}},Bo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=jo++},Wo=(e,t)=>{if(null===e._start||0===t||null===e._searchMarker)return null;const n=0===e._searchMarker.length?null:e._searchMarker.reduce((e,n)=>Wt(t-e.index)<Wt(t-n.index)?e:n);let r=e._start,i=0;for(null!==n&&(r=n.p,i=n.index,(e=>{e.timestamp=jo++})(n));null!==r.right&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;null!==r.left&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;null!==r.left&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return null!==n&&Wt(n.index-i)<r.parent.length/80?(Bo(n,r,i),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return Bo(r,t,n),r}{const r=new Fo(t,n);return e.push(r),r}})(e._searchMarker,r,i)},Ho=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=st(t,i.index+n))}},qo=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;en(i,e,()=>[]).push(n),null!==e._item;)e=e._item.parent;js(r._eH,n,t)},Vo=class{constructor(){this._item=null,this._map=/* @__PURE__ */new Map,this._start=null,this.doc=null,this._length=0,this._eH=Ns(),this._dEH=Ns(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Yt()}clone(){throw Yt()}_write(e){}get _first(){let e=this._start;for(;null!==e&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Is(this._eH,e)}observeDeep(e){Is(this._dEH,e)}unobserve(e){Us(this._eH,e)}unobserveDeep(e){Us(this._dEH,e)}toJSON(){}},zo=(e,t,n)=>{e.doc??Uo(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const i=[];let s=e._start;for(;null!==s&&r>0;){if(s.countable&&!s.deleted){const e=s.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}s=s.right}return i},$o=e=>{e.doc??Uo();const t=[];let n=e._start;for(;null!==n;){if(n.countable&&!n.deleted){const e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},Yo=(e,t)=>{let n=0,r=e._start;for(e.doc??Uo();null!==r;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},Jo=(e,t)=>{const n=[];return Yo(e,(r,i)=>{n.push(t(r,i,e))}),n},Qo=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(null===n){for(;null!==t&&t.deleted;)t=t.right;if(null===t)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},Ko=(e,t)=>{e.doc??Uo();const n=Wo(e,t);let r=e._start;for(null!==n&&(r=n.p,t-=n.index);null!==r;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},Go=(e,t,n,r)=>{let i=n;const s=e.doc,o=s.clientID,a=s.store,c=null===n?t._start:n.right;let l=[];const h=()=>{l.length>0&&(i=new sc(Ws(o,so(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new qa(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(null===n)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(h(),n.constructor){case Uint8Array:case ArrayBuffer:i=new sc(Ws(o,so(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Na(new Uint8Array(n))),i.integrate(e,0);break;case ms:i=new sc(Ws(o,so(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ja(n)),i.integrate(e,0);break;default:if(!(n instanceof Vo))throw new Error("Unexpected content type in insert operation");i=new sc(Ws(o,so(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Za(n)),i.integrate(e,0)}}}),h()},Xo=()=>Xt("Length exceeded!"),Zo=(e,t,n,r)=>{if(n>t._length)throw Xo();if(0===n)return t._searchMarker&&Ho(t._searchMarker,n,r.length),Go(e,t,null,r);const i=n,s=Wo(t,n);let o=t._start;for(null!==s&&(o=s.p,0===(n-=s.index)&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));null!==o;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&ho(e,Ws(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Ho(t._searchMarker,i,r.length),Go(e,t,o,r)},ea=(e,t,n,r)=>{if(0===r)return;const i=n,s=r,o=Wo(t,n);let a=t._start;for(null!==o&&(a=o.p,n-=o.index);null!==a&&n>0;a=a.right)!a.deleted&&a.countable&&(n<a.length&&ho(e,Ws(a.id.client,a.id.clock+n)),n-=a.length);for(;r>0&&null!==a;)a.deleted||(r<a.length&&ho(e,Ws(a.id.client,a.id.clock+r)),a.delete(e),r-=a.length),a=a.right;if(r>0)throw Xo();t._searchMarker&&Ho(t._searchMarker,i,-s+r)},ta=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},na=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let a;if(null==r)a=new qa([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new qa([r]);break;case Uint8Array:a=new Na(r);break;case ms:a=new ja(r);break;default:if(!(r instanceof Vo))throw new Error("Unexpected content type");a=new Za(r)}new sc(Ws(o,so(s.store,o)),i,i&&i.lastId,null,null,t,n,a).integrate(e,0)},ra=(e,t)=>{e.doc??Uo();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},ia=e=>{const t={};return e.doc??Uo(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},sa=(e,t)=>{e.doc??Uo();const n=e._map.get(t);return void 0!==n&&!n.deleted},oa=e=>(e.doc??Uo(),Et(e._map.entries(),e=>!e[1].deleted)),aa=class extends No{},ca=class e extends Vo{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return t.insert(0,this.toArray().map(e=>e instanceof Vo?e.clone():e)),t}get length(){return this.doc??Uo(),this._length}_callObserver(e,t){super._callObserver(e,t),qo(this,e,new aa(this,e))}insert(e,t){null!==this.doc?wo(this.doc,n=>{Zo(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?wo(this.doc,t=>{((e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;Go(e,t,r,n)})(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?wo(this.doc,n=>{ea(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return Ko(this,e)}toArray(){return $o(this)}slice(e=0,t=this.length){return zo(this,e,t)}toJSON(){return this.map(e=>e instanceof Vo?e.toJSON():e)}map(e){return Jo(this,e)}forEach(e){Yo(this,e)}[Symbol.iterator](){return Qo(this)}_write(e){e.writeTypeRef($a)}},la=class extends No{constructor(e,t,n){super(e,t),this.keysChanged=n}},ha=class e extends Vo{constructor(e){super(),this._prelimContent=null,this._prelimContent=void 0===e?/* @__PURE__ */new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof Vo?e.clone():e)}),t}_callObserver(e,t){qo(this,e,new la(this,e,t))}toJSON(){this.doc??Uo();const e={};return this._map.forEach((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof Vo?r.toJSON():r}}),e}get size(){return[...oa(this)].length}keys(){return un(oa(this),e=>e[0])}values(){return un(oa(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return un(oa(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Uo(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){null!==this.doc?wo(this.doc,t=>{ta(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?wo(this.doc,n=>{na(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return ra(this,e)}has(e){return sa(this,e)}clear(){null!==this.doc?wo(this.doc,e=>{this.forEach(function(t,n,r){ta(e,r,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Ya)}},da=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&pt(e,t),ua=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&Ut(),this.right.content.constructor===Ba)this.right.deleted||ma(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}},fa=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===Ba)t.right.deleted||ma(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&ho(e,Ws(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);t.left=t.right,t.right=t.right.right}return t},ga=(e,t,n,r)=>{const i=/* @__PURE__ */new Map,s=r?Wo(t,n):null;if(s){const t=new ua(s.p.left,s.p,s.index,i);return fa(e,t,n-s.index)}{const r=new ua(null,t._start,0,i);return fa(e,r,n)}},pa=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===Ba&&da(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=e.doc,s=i.clientID;r.forEach((r,o)=>{const a=n.left,c=n.right,l=new sc(Ws(s,so(i.store,s)),a,a&&a.lastId,c,c&&c.id,t,null,new Ba(o,r));l.integrate(e,0),n.right=l,n.forward()})},ma=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},ya=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===Ba&&da(t[e.right.content.key]??null,e.right.content.value));)e.forward()},ba=(e,t,n,r)=>{const i=e.doc,s=i.clientID,o=/* @__PURE__ */new Map;for(const a in r){const c=r[a],l=n.currentAttributes.get(a)??null;if(!da(l,c)){o.set(a,l);const{left:r,right:h}=n;n.right=new sc(Ws(s,so(i.store,s)),r,r&&r.lastId,h,h&&h.id,t,null,new Ba(a,c)),n.right.integrate(e,0),n.forward()}}return o},wa=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{void 0===i[t]&&(i[t]=null)});const s=e.doc,o=s.clientID;ya(n,i);const a=ba(e,t,n,i),c=r.constructor===String?new Va(r):r instanceof Vo?new Za(r):new Fa(r);let{left:l,right:h,index:d}=n;t._searchMarker&&Ho(t._searchMarker,n.index,c.getLength()),h=new sc(Ws(o,so(s.store,o)),l,l&&l.lastId,h,h&&h.id,t,null,c),h.integrate(e,0),n.right=h,n.index=d,n.forward(),pa(e,t,n,a)},va=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;ya(n,i);const a=ba(e,t,n,i);e:for(;null!==n.right&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Ba));){if(!n.right.deleted)switch(n.right.content.constructor){case Ba:{const{key:t,value:s}=n.right.content,o=i[t];if(void 0!==o){if(da(o,s))a.delete(t);else{if(0===r)break e;a.set(t,s)}n.right.delete(e)}else n.currentAttributes.set(t,s);break}default:r<n.right.length&&ho(e,Ws(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i="";for(;r>0;r--)i+="\n";n.right=new sc(Ws(o,so(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Va(i)),n.right.integrate(e,0),n.forward()}pa(e,t,n,a)},_a=(e,t,n,r,i)=>{let s=t;const o=Qe();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===Ba){const e=s.content;o.set(e.key,e)}s=s.right}let a=0,c=!1;for(;t!==s;){if(n===t&&(c=!0),!t.deleted){const n=t.content;switch(n.constructor){case Ba:{const{key:s,value:l}=n,h=r.get(s)??null;o.get(s)===n&&h!==l||(t.delete(e),a++,c||(i.get(s)??null)!==l||h===l||(null===h?i.delete(s):i.set(s,h))),c||t.deleted||ma(i,n);break}}}t=t.right}return a},ka=e=>{let t=0;return wo(e.doc,n=>{let r=e._start,i=e._start,s=Qe();const o=He(s);for(;i;){if(!1===i.deleted)if(i.content.constructor===Ba)ma(o,i.content);else t+=_a(n,r,i,s,o),s=He(o),r=i;i=i.right}}),t},Ca=e=>{const t=/* @__PURE__ */new Set,n=e.doc;for(const[r,i]of e.afterState.entries()){const s=e.beforeState.get(r)||0;i!==s&&fo(e,n.store.clients.get(r),s,i,e=>{e.deleted||e.content.constructor!==Ba||e.constructor===Ma||t.add(e.parent)})}wo(n,n=>{os(e,e.deleteSet,e=>{if(e instanceof Ma||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===Ba?t.add(r):((e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=/* @__PURE__ */new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Ba){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)});for(const e of t)ka(e)})},Sa=(e,t,n)=>{const r=n,i=He(t.currentAttributes),s=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Za:case Fa:case Va:n<t.right.length&&ho(e,Ws(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}s&&_a(e,s,t.right,i,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&Ho(o._searchMarker,t.index,-r+n),t},Ea=class extends No{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=/* @__PURE__ */new Set,n.forEach(e=>{null===e?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(null===this._changes){const e={keys:this.keys,delta:this.delta,added:/* @__PURE__ */new Set,deleted:/* @__PURE__ */new Set};this._changes=e}return this._changes}get delta(){if(null===this._delta){const e=this.target.doc,t=[];wo(e,e=>{const n=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map;let i=this.target._start,s=null;const o={};let a="",c=0,l=0;const h=()=>{if(null!==s){let e=null;switch(s){case"delete":l>0&&(e={delete:l}),l=0;break;case"insert":("object"==typeof a||a.length>0)&&(e={insert:a},n.size>0&&(e.attributes={},n.forEach((t,n)=>{null!==t&&(e.attributes[n]=t)}))),a="";break;case"retain":c>0&&(e={retain:c},ft(o)||(e.attributes=mn({},o))),c=0}e&&t.push(e),s=null}};for(;null!==i;){switch(i.content.constructor){case Za:case Fa:this.adds(i)?this.deletes(i)||(h(),s="insert",a=i.content.getContent()[0],h()):this.deletes(i)?("delete"!==s&&(h(),s="delete"),l+=1):i.deleted||("retain"!==s&&(h(),s="retain"),c+=1);break;case Va:this.adds(i)?this.deletes(i)||("insert"!==s&&(h(),s="insert"),a+=i.content.str):this.deletes(i)?("delete"!==s&&(h(),s="delete"),l+=i.length):i.deleted||("retain"!==s&&(h(),s="retain"),c+=i.length);break;case Ba:{const{key:t,value:a}=i.content;if(this.adds(i)){if(!this.deletes(i)){const c=n.get(t)??null;da(c,a)?null!==a&&i.delete(e):("retain"===s&&h(),da(a,r.get(t)??null)?delete o[t]:o[t]=a)}}else if(this.deletes(i)){r.set(t,a);const e=n.get(t)??null;da(e,a)||("retain"===s&&h(),o[t]=e)}else if(!i.deleted){r.set(t,a);const n=o[t];void 0!==n&&(da(n,a)?null!==n&&i.delete(e):("retain"===s&&h(),null===a?delete o[t]:o[t]=a))}i.deleted||("insert"===s&&h(),ma(n,i.content));break}}i=i.right}for(h();t.length>0;){const e=t[t.length-1];if(void 0===e.retain||void 0!==e.attributes)break;t.pop()}}),this._delta=t}return this._delta}},Aa=class e extends Vo{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Uo(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(n){}this._pending=null}_copy(){return new e}clone(){const t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);const n=new Ea(this,e,t);qo(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Uo();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===Va&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?wo(this.doc,n=>{const r=new ua(null,this._start,0,/* @__PURE__ */new Map);for(let i=0;i<e.length;i++){const s=e[i];if(void 0!==s.insert){const o=t||"string"!=typeof s.insert||i!==e.length-1||null!==r.right||"\n"!==s.insert.slice(-1)?s.insert:s.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&wa(n,this,r,o,s.attributes||{})}else void 0!==s.retain?va(n,this,r,s.retain,s.attributes||{}):void 0!==s.delete&&Sa(n,r,s.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){this.doc??Uo();const r=[],i=/* @__PURE__ */new Map,s=this.doc;let o="",a=this._start;function c(){if(o.length>0){const e={};let t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const l=()=>{for(;null!==a;){if(to(a,e)||void 0!==t&&to(a,t))switch(a.content.constructor){case Va:{const r=i.get("ychange");void 0===e||to(a,e)?void 0===t||to(a,t)?void 0!==r&&(c(),i.delete("ychange")):void 0!==r&&r.user===a.id.client&&"added"===r.type||(c(),i.set("ychange",n?n("added",a.id):{type:"added"})):void 0!==r&&r.user===a.id.client&&"removed"===r.type||(c(),i.set("ychange",n?n("removed",a.id):{type:"removed"})),o+=a.content.str;break}case Za:case Fa:{c();const e={insert:a.content.getContent()[0]};if(i.size>0){const t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Ba:to(a,e)&&(c(),ma(i,a.content))}a=a.right}c()};return e||t?wo(s,n=>{e&&no(n,e),t&&no(n,t),l()},"cleanup"):l(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?wo(r,r=>{const i=ga(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),wa(r,this,i,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const r=this.doc;null!==r?wo(r,r=>{const i=ga(r,this,e,!n);wa(r,this,i,t,n||{})}):this._pending.push(()=>this.insertEmbed(e,t,n||{}))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?wo(n,n=>{Sa(n,ga(n,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,n){if(0===t)return;const r=this.doc;null!==r?wo(r,r=>{const i=ga(r,this,e,!1);null!==i.right&&va(r,this,i,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){null!==this.doc?wo(this.doc,t=>{ta(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){null!==this.doc?wo(this.doc,n=>{na(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return ra(this,e)}getAttributes(){return ia(this)}_write(e){e.writeTypeRef(Ja)}},Ta=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Uo()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(null!==e&&(!this._firstCall||e.deleted||!this._filter(t)))do{if(t=e.content.type,e.deleted||t.constructor!==Ra&&t.constructor!==xa||null===t._start)for(;null!==e;){const t=e.next;if(null!==t){e=t;break}e=e.parent===this._root?null:e.parent._item}else e=t._start}while(null!==e&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,null===e?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},xa=class e extends Vo{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return t.insert(0,this.toArray().map(e=>e instanceof Vo?e.clone():e)),t}get length(){return this.doc??Uo(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new Ta(this,e)}querySelector(e){e=e.toUpperCase();const t=new Ta(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),yn(new Ta(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){qo(this,e,new Da(this,t,e))}toString(){return Jo(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const r=e.createDocumentFragment();return void 0!==n&&n._createAssociation(r,this),Yo(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){null!==this.doc?wo(this.doc,n=>{Zo(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)wo(this.doc,n=>{const r=e&&e instanceof Vo?e._item:e;Go(n,this,r,t)});else{const n=this._prelimContent,r=null===e?0:n.findIndex(t=>t===e)+1;if(0===r&&null!==e)throw Xt("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?wo(this.doc,n=>{ea(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return $o(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Ko(this,e)}slice(e=0,t=this.length){return zo(this,e,t)}forEach(e){Yo(this,e)}_write(e){e.writeTypeRef(Ka)}},Ra=class e extends xa{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=/* @__PURE__ */new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){const t=new e(this.nodeName),n=this.getAttributes();return qe(n,(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof Vo?e.clone():e)),t}toString(){const e=this.getAttributes(),t=[],n=[];for(const s in e)n.push(s);n.sort();const r=n.length;for(let s=0;s<r;s++){const r=n[s];t.push(r+'="'+e[r]+'"')}const i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${i}>`}removeAttribute(e){null!==this.doc?wo(this.doc,t=>{ta(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?wo(this.doc,n=>{na(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return ra(this,e)}hasAttribute(e){return sa(this,e)}getAttributes(e){return e?((e,t)=>{const n={};return e._map.forEach((e,r)=>{let i=e;for(;null!==i&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;null!==i&&to(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n})(this,e):ia(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const s in i){const e=i[s];"string"==typeof e&&r.setAttribute(s,e)}return Yo(this,i=>{r.appendChild(i.toDOM(e,t,n))}),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Qa),e.writeKey(this.nodeName)}},Da=class extends No{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=/* @__PURE__ */new Set,t.forEach(e=>{null===e?this.childListChanged=!0:this.attributesChanged.add(e)})}},Oa=class e extends ha{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){const t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){const r=t[this.hookName];let i;return i=void 0!==r?r.createDom(this):document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(Ga),e.writeKey(this.hookName)}},Pa=class e extends Aa{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){const t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){const r=e.createTextNode(this.toString());return void 0!==n&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{const t=[];for(const r in e.attributes){const n=[];for(const t in e.attributes[r])n.push({key:t,value:e.attributes[r][t]});n.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:r,attrs:n})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n="";for(let r=0;r<t.length;r++){const e=t[r];n+=`<${e.nodeName}`;for(let t=0;t<e.attrs.length;t++){const r=e.attrs[t];n+=` ${r.key}="${r.value}"`}n+=">"}n+=e.insert;for(let r=t.length-1;r>=0;r--)n+=`</${t[r].nodeName}>`;return n}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Xa)}},La=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Yt()}mergeWith(e){return!1}write(e,t,n){throw Yt()}integrate(e,t){throw Yt()}},Ma=class extends La{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),oo(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},Na=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw Yt()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},Ia=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){const n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){hs(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}},Ua=(e,t)=>new ms({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1}),ja=class e{constructor(e){e._item,this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),null!==e.meta&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(Ua(this.doc.guid,this.opts))}splice(e){throw Yt()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}},Fa=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw Yt()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},Ba=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw Yt()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}},Wa=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){const n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeString(void 0===t?"undefined":JSON.stringify(t))}}getRef(){return 2}},Ha="development"===Fe("node_env"),qa=class e{constructor(e){this.arr=e,Ha&&Oe(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){const n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeAny(t)}}getRef(){return 8}},Va=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new e(this.str)}splice(t){const n=new e(this.str.slice(t));this.str=this.str.slice(0,t);const r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(0===t?this.str:this.str.slice(t))}getRef(){return 4}},za=[e=>new ca,e=>new ha,e=>new Aa,e=>new Ra(e.readKey()),e=>new xa,e=>new Oa(e.readKey()),e=>new Pa],$a=0,Ya=1,Ja=2,Qa=3,Ka=4,Ga=5,Xa=6,Za=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw Yt()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;null!==t;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;null!==t;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;null!==t;)t.gc(e,!0),t=t.left}),this.type._map=/* @__PURE__ */new Map}write(e,t){this.type._write(e)}getRef(){return 7}},ec=(e,t)=>{let n,r=t,i=0;do{i>0&&(r=Ws(r.client,r.clock+i)),n=co(e,r),i=r.clock-n.id.clock,r=n.redone}while(null!==r&&n instanceof sc);return{item:n,diff:i}},tc=(e,t)=>{for(;null!==e&&e.keep!==t;)e.keep=t,e=e.parent._item},nc=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new sc(Ws(r,i+n),t,Ws(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&s.markDeleted(),t.keep&&(s.keep=!0),null!==t.redone&&(s.redone=Ws(t.redone.client,t.redone.clock+n)),t.right=s,null!==s.right&&(s.right.left=s),e._mergeStructs.push(s),null!==s.parentSub&&null===s.right&&s.parent._map.set(s.parentSub,s),t.length=n,s},rc=(e,t)=>Ve(e,e=>as(e.deletions,t)),ic=(e,t,n,r,i,s)=>{const o=e.doc,a=o.store,c=o.clientID,l=t.redone;if(null!==l)return ho(e,l);let h,d=t.parent._item,u=null;if(null!==d&&!0===d.deleted){if(null===d.redone&&(!n.has(d)||null===ic(e,d,n,r,i,s)))return null;for(;null!==d.redone;)d=ho(e,d.redone)}const f=null===d?t.parent:d.content.type;if(null===t.parentSub){for(u=t.left,h=t;null!==u;){let t=u;for(;null!==t&&t.parent._item!==d;)t=null===t.redone?null:ho(e,t.redone);if(null!==t&&t.parent._item===d){u=t;break}u=u.left}for(;null!==h;){let t=h;for(;null!==t&&t.parent._item!==d;)t=null===t.redone?null:ho(e,t.redone);if(null!==t&&t.parent._item===d){h=t;break}h=h.right}}else{if(h=null,t.right&&!i){for(u=t;null!==u&&null!==u.right&&(u.right.redone||as(r,u.right.id)||rc(s.undoStack,u.right.id)||rc(s.redoStack,u.right.id));)for(u=u.right;u.redone;)u=ho(e,u.redone);if(u&&null!==u.right)return null}else u=f._map.get(t.parentSub)||null;null!==u&&u.parent._item!==d&&(u=f._map.get(t.parentSub)||null)}const g=so(a,c),p=Ws(c,g),m=new sc(p,u,u&&u.lastId,h,h&&h.id,f,t.parentSub,t.content.copy());return t.redone=p,tc(m,!0),m.integrate(e,0),m},sc=class e extends La{constructor(e,t,n,r,i,s,o,a){super(e,a.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=s,this.parentSub=o,this.redone=null,this.content=a,this.info=this.content.isCountable()?2:0}set marker(e){(8&this.info)>0!==e&&(this.info^=8)}get marker(){return(8&this.info)>0}get keep(){return(1&this.info)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(2&this.info)>0}get deleted(){return(4&this.info)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=so(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=so(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Fs&&this.id.client!==this.parent.client&&this.parent.clock>=so(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=uo(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=ho(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ma||this.right&&this.right.constructor===Ma)this.parent=null;else if(this.parent){if(this.parent.constructor===Fs){const e=co(n,this.parent);e.constructor===Ma?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=uo(e,e.doc.store,Ws(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||null!==this.right.left)||this.left&&this.left.right!==this.right){let t,n=this.left;if(null!==n)t=n.right;else if(null!==this.parentSub)for(t=this.parent._map.get(this.parentSub)||null;null!==t&&null!==t.left;)t=t.left;else t=this.parent._start;const r=/* @__PURE__ */new Set,i=/* @__PURE__ */new Set;for(;null!==t&&t!==this.right;){if(i.add(t),r.add(t),Bs(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(Bs(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!i.has(co(e.doc.store,t.origin)))break;r.has(co(e.doc.store,t.origin))||(n=t,r.clear())}t=t.right}this.left=n}if(null!==this.left){const e=this.left.right;this.right=e,this.left.right=this}else{let e;if(null!==this.parentSub)for(e=this.parent._map.get(this.parentSub)||null;null!==e&&null!==e.left;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}null!==this.right?this.right.left=this:null!==this.parentSub&&(this.parent._map.set(this.parentSub,this),null!==this.left&&this.left.delete(e)),null===this.parentSub&&this.countable&&!this.deleted&&(this.parent._length+=this.length),oo(e.doc.store,this),this.content.integrate(e,this),mo(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new Ma(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;null!==e&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;null!==e&&e.deleted;)e=e.left;return e}get lastId(){return 1===this.length?this.id:Ws(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Bs(e.origin,this.lastId)&&this.right===e&&Bs(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&null===this.redone&&null===e.redone&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,null!==this.right&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&null===this.parentSub&&(t._length-=this.length),this.markDeleted(),hs(e.deleteSet,this.id.client,this.id.clock,this.length),mo(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Ut();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[ao(r,t.id.clock)]=n})(e,this,new Ma(this.id,this.length)):this.content=new Ia(this.length)}write(e,t){const n=t>0?Ws(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,s=31&this.content.getRef()|(null===n?0:128)|(null===r?0:64)|(null===i?0:32);if(e.writeInfo(s),null!==n&&e.writeLeftID(n),null!==r&&e.writeRightID(r),null===n&&null===r){const t=this.parent;if(void 0!==t._item){const n=t._item;if(null===n){const n=Vs(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===Fs?(e.writeParentInfo(!1),e.writeLeftID(t)):Ut();null!==i&&e.writeString(i)}this.content.write(e,t)}},oc=(e,t)=>ac[31&t](e),ac=[()=>{Ut()},e=>new Ia(e.readLen()),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const t=e.readString();"undefined"===t?n.push(void 0):n.push(JSON.parse(t))}return new Wa(n)},e=>new Na(e.readBuf()),e=>new Va(e.readString()),e=>new Fa(e.readJSON()),e=>new Ba(e.readKey(),e.readJSON()),e=>new Za(za[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new qa(n)},e=>new ja(Ua(e.readString(),e.readAny())),()=>{Ut()}],cc=class extends La{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){Ut()}write(e,t){e.writeInfo(10),rt(e.restEncoder,this.length-t)}getMissing(e,t){return null}},lc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},hc="__ $YJS$ __";lc[hc],lc[hc]=!0;var dc=Object.defineProperty,uc=Object.defineProperties,fc=Object.getOwnPropertyDescriptors,gc=Object.getOwnPropertySymbols,pc=Object.prototype.hasOwnProperty,mc=Object.prototype.propertyIsEnumerable,yc=(e,t,n)=>t in e?dc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,bc=(e,t)=>{for(var n in t||(t={}))pc.call(t,n)&&yc(e,n,t[n]);if(gc)for(var n of gc(t))mc.call(t,n)&&yc(e,n,t[n]);return e},wc=(e,t)=>uc(e,fc(t)),vc=(e,t)=>{var n={};for(var r in e)pc.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&gc)for(var r of gc(e))t.indexOf(r)<0&&mc.call(e,r)&&(n[r]=e[r]);return n};function _c(e){return"[object Object]"===Object.prototype.toString.call(e)}function kc(e){if(!_c(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==_c(n)&&!1!==n.hasOwnProperty("isPrototypeOf")}function Cc(e,t){for(const n in e){const r=e[n],i=t[n];if(kc(r)&&kc(i)){if(!Cc(r,i))return!1}else if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1}else if(r!==i)return!1}for(const n in t)if(void 0===e[n]&&void 0!==t[n])return!1;return!0}function Sc(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function Ec(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>null!==e))}function Ac(e){return function(e){var t,n;const r=[];for(const i of e){if("string"==typeof i.insert&&0===i.insert.length)continue;const e=r[r.length-1];e&&"string"==typeof e.insert&&"string"==typeof i.insert&&(e.attributes===i.attributes||!e.attributes==!i.attributes&&Cc(null!=(t=e.attributes)?t:{},null!=(n=i.attributes)?n:{}))?e.insert+=i.insert:r.push(i)}return r}(e.toDelta())}function Tc({insert:e}){return"string"==typeof e?e.length:1}function xc(e){return e.reduce((e,t)=>e+Tc(t),0)}function Rc(e,t,n){if(n<1)return[];let r=0;const i=[],s=t+n;for(let o=0;o<e.length&&!(r>=s);o++){const n=e[o],a=Tc(n);if(r+a<=t){r+=a;continue}if("string"!=typeof n.insert){r+=a,i.push(n);continue}const c=Math.max(0,t-r),l=Math.min(a,a-(r+a-s));i.push(wc(bc({},n),{insert:n.insert.slice(c,l)})),r+=a}return i}function Dc(e){return function(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}(e,J.isText(e)?"text":"children")}function Oc(e){const t=Ac(e),n=t.length>0?t.map(Pc):[{text:""}];return wc(bc({},e.getAttributes()),{children:n})}function Pc(e){return"string"==typeof e.insert?wc(bc({},e.attributes),{text:e.insert}):Oc(e.insert)}function Lc(e){return e.map(e=>J.isText(e)?{insert:e.text,attributes:Dc(e)}:{insert:Mc(e)})}function Mc(e){var t=e,{children:n}=t,r=vc(t,["children"]);const i=new Pa;return Object.entries(r).forEach(([e,t])=>{i.setAttribute(e,t)}),i.applyDelta(Lc(n),{sanitize:!1}),i}function Nc(e){return e?J.isText(e)?e.text.length:1:0}function Ic(e,t,n){var r;if(0===n.length)throw new Error("Path has to a have a length >= 1");if(J.isText(t))throw new Error("Cannot descent into slate text");const[i,...s]=n,o=function(e,t){return e.children.slice(0,t).reduce((e,t)=>e+Nc(t),0)}(t,i),a=t.children[i],c=Ac(e),l=Nc(a),h=Rc(c,o,l);if(h.length>1)throw new Error("Path doesn't match yText, yTarget spans multiple nodes");const d=null==(r=h[0])?void 0:r.insert;if(s.length>0){if(!(d instanceof Pa))throw new Error("Path doesn't match yText, cannot descent into non-yText");return Ic(d,a,s)}return{yParent:e,textRange:{start:o,end:o+l},yTarget:d instanceof Pa?d:void 0,slateParent:t,slateTarget:a,targetDelta:h}}function Uc(e,t,n={}){const{assoc:r=0,insert:i=!1}=n;let s=0,o=0;for(let c=0;c<e.children.length;c++){const n=e.children[c],i=J.isText(n)?n.text.length:1;i>0&&(o=c);const a=s+i;if(i>0&&(r>=0?a>t:a>=t))return[c,t-s];s+=i}if(t>s+(i?1:0))throw new Error("yOffset out of bounds");if(i)return[e.children.length,0];const a=e.children[o];return[o,J.isText(a)?a.text.length:1]}function jc(e,t,n){const r=[n];for(;r[0]!==e;){const{parent:e}=r[0];if(!e)throw new Error("yText isn't a descendant of root element");if(!(e instanceof Pa))throw new Error("Unexpected y parent type");r.unshift(e)}if(r.length<2)return[];let i=t;return r.reduce((e,t,n)=>{const s=r[n+1];if(!s)return e;let o=0;const a=Ac(t);for(const r of a){if(r.insert===s)break;o+="string"==typeof r.insert?r.insert.length:1}if(J.isText(i))throw new Error("Cannot descent into slate text");const[c]=Uc(i,o);return i=i.children[c],e.concat(c)},[])}function Fc(e,t,n){const{target:r,changes:i}=n,s=n.delta;if(!(r instanceof Pa))throw new Error("Unexpected target node type");const o=[],a=jc(e,t,r),c=ce.get(t,a);if(J.isText(c))throw new Error("Cannot apply yTextEvent to text node");const l=Array.from(i.keys.entries());if(a.length>0&&l.length>0){const e=Object.fromEntries(l.map(([e,t])=>[e,"delete"===t.action?null:r.getAttribute(e)])),t=Object.fromEntries(l.map(([e])=>[e,c[e]]));o.push({type:"set_node",newProperties:e,properties:t,path:a})}return s.length>0&&o.push(...function(e,t,n){const r=[];let i=n.reduce((e,t)=>"retain"in t?e+t.retain:"delete"in t?e+t.delete:e,0);return n.reverse().forEach(n=>{var s;if("attributes"in n&&"retain"in n){const[s,o]=Uc(e,i-n.retain),[a,c]=Uc(e,i,{assoc:-1});for(let i=a;i>=s;i--){const l=e.children[i],h=[...t,i];if(!J.isText(l))continue;const d=n.attributes,u=Sc(e,...Object.keys(n.attributes));if(i===s||i===a){const e=i===s?o:0,t=i===a?c:l.text.length;if(t!==l.text.length&&r.push({type:"split_node",path:h,position:t,properties:Dc(l)}),0!==e){r.push({type:"split_node",path:h,position:e,properties:Ec(bc(bc({},Dc(l)),d))});continue}}r.push({type:"set_node",newProperties:d,path:h,properties:u})}}if("retain"in n&&(i-=n.retain),"delete"in n){const[s,o]=Uc(e,i-n.delete),[a,c]=Uc(e,i,{assoc:-1});for(let n=0===c?a-1:a;n>=s;n--){const l=e.children[n],h=[...t,n];if(J.isText(l)&&(n===s||n===a)){const e=n===s?o:0,t=n===a?c:l.text.length;r.push({type:"remove_text",offset:e,text:l.text.slice(e,t),path:h}),i-=t-e;continue}r.push({type:"remove_node",node:l,path:h}),i-=Nc(l)}return}if("insert"in n){const[o,a]=Uc(e,i,{insert:!0}),c=e.children[o],l=[...t,o];if(J.isText(c)){const e=r[r.length-1],t=null!=e&&"insert_node"===e.type?e.node:Dc(c);let i=[];if(null==e||"insert_node"!==e.type&&"insert_text"!==e.type&&"split_node"!==e.type&&"set_node"!==e.type||(i=e.path),"string"==typeof n.insert&&Cc(null!=(s=n.attributes)?s:{},t)&&ee.equals(l,i))return r.push({type:"insert_text",offset:a,text:n.insert,path:l});const o=Pc(n);return 0===a?r.push({type:"insert_node",path:l,node:o}):(a<c.text.length&&r.push({type:"split_node",path:l,position:a,properties:Dc(c)}),r.push({type:"insert_node",path:ee.next(l),node:o}))}return r.push({type:"insert_node",path:l,node:Pc(n)})}}),r}(c,a,s)),o}function Bc(e,t,n){q.withoutNormalizing(t,()=>{n.forEach(n=>{(function(e,t,n){if(n instanceof Ea)return Fc(e,t,n);throw new Error("Unexpected Y event type")})(e,t,n).forEach(e=>{t.apply(e)})})})}function Wc(e){return e.map(e=>"string"==typeof e.insert?e:wc(bc({},e),{insert:Hc(e.insert)}))}function Hc(e){const t=new Pa,n=e.getAttributes();return Object.entries(n).forEach(([e,n])=>{t.setAttribute(e,n)}),t.applyDelta(Wc(Ac(e)),{sanitize:!1}),t}function qc(e){if(!e.doc)throw new Error("shared type isn't attached to a document")}var Vc="__slateYjsStoredPosition_";function zc(e,t,n){const{yTarget:r,yParent:i,textRange:s}=Ic(e,t,n.path);if(r)throw new Error("Slate point points to a non-text element inside sharedRoot");const o=s.start+n.offset;return Qs(i,o,o===s.end?-1:0)}function $c(e,t,n){if(!e.doc)throw new Error("sharedRoot isn't attach to a yDoc");const r=Xs(n,e.doc);return r&&function(e,t,{type:n,index:r,assoc:i}){if(!(n instanceof Pa))throw new Error("Absolute position points to a non-XMLText");const s=jc(e,t,n),o=ce.get(t,s);if(J.isText(o))throw new Error("Absolute position doesn't match slateRoot, cannot descent into text");const[a,c]=Uc(o,r,{assoc:i}),l=o.children[a];return J.isText(l)?{path:[...s,a],offset:c}:null}(e,t,r)}function Yc(e,t,n){e.setAttribute(Vc+t,Ks(n))}function Jc(e,t,n){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.type===t&&(!n||(e.assoc>=0?e.index>=n.start&&e.index<n.end:e.index>n.start&&e.index>=n.end))))}function Qc(e,t,n=""){const r={[n]:Jc(e,t)};return Ac(t).forEach(({insert:t},i)=>{t instanceof Pa&&Object.assign(r,Qc(e,t,n?`${n}.${i}`:i.toString()))}),r}function Kc(e,t,n,r=0){const i=function(e){return qc(e),Object.fromEntries(Object.entries(e.getAttributes()).filter(([e])=>e.startsWith(Vc)).map(([t,n])=>[t.slice(25),Xs(Gs(n),e.doc)]).filter(([,e])=>e))}(e),s={"":Jc(i,t,{start:r,end:r+xc(n)})};return n.forEach(({insert:e},t)=>{e instanceof Pa&&Object.assign(s,Qc(i,e,t.toString()))}),s}function Gc(e,t,n,r,i=0,s=0,o=""){const a=n[o];a&&Object.entries(a).forEach(([n,r])=>{Yc(e,n,Qs(t,r.index-s+i,r.assoc))}),r.forEach(({insert:t},r)=>{t instanceof Pa&&Gc(e,t,n,Ac(t),0,0,o?`${o}.${r}`:r.toString())})}function Xc(e,t,n){return{anchor:zc(e,t,n.anchor),focus:zc(e,t,n.focus)}}var Zc={insert_node:function(e,t,n){const{yParent:r,textRange:i}=Ic(e,t,n.path);if(J.isText(n.node))return r.insert(i.start,n.node.text,Dc(n.node));r.insertEmbed(i.start,Mc(n.node))},remove_node:function(e,t,n){const{yParent:r,textRange:i}=Ic(e,t,n.path);r.delete(i.start,i.end-i.start)},set_node:function(e,t,n){const{yTarget:r,textRange:i,yParent:s}=Ic(e,t,n.path);if(r)return Object.entries(n.newProperties).forEach(([e,t])=>{if(null===t)return r.removeAttribute(e);r.setAttribute(e,t)}),Object.entries(n.properties).forEach(([e])=>{n.newProperties.hasOwnProperty(e)||r.removeAttribute(e)});const o=bc(bc({},Object.fromEntries(Object.keys(n.properties).map(e=>[e,null]))),n.newProperties);s.format(i.start,i.end-i.start,o)},merge_node:function(e,t,n){const r=Ic(e,t,n.path),i=Ic(r.yParent,r.slateParent,ee.previous(n.path.slice(-1)));if(!r.yTarget!=!i.yTarget)throw new Error("Cannot merge y text with y element");if(!i.yTarget||!r.yTarget){const{yParent:e,textRange:i,slateTarget:s}=r;if(!s)throw new Error("Expected Slate target node for merge op.");const o=ce.get(t,ee.previous(n.path));if(!J.isText(o))throw new Error("Path points to Y.Text but not a Slate text node.");const a=Dc(s),c=Dc(o),l=Object.keys(a).reduce((e,t)=>t in c?e:wc(bc({},e),{[t]:null}),{});return e.format(i.start,i.end-i.start,bc(bc({},l),c))}const s=i.yTarget.length,o=Ac(r.yTarget),a=Wc(o),c=Kc(e,r.yTarget,o,s),l=[{retain:s},...a];i.yTarget.applyDelta(l,{sanitize:!1}),r.yParent.delete(r.textRange.start,r.textRange.end-r.textRange.start),Gc(e,i.yTarget,c,a,s)},move_node:function(e,t,n){const r=ee.parent(n.newPath),i=n.newPath[n.newPath.length-1],s=ce.get(t,r);if(J.isText(s))throw new Error("Cannot move slate node into text element");const o=[...r,Math.min(i,s.children.length)],a=Ic(e,t,n.path),c=Ic(e,t,o),l=Wc(a.targetDelta),h=Kc(e,a.yParent,a.targetDelta);a.yParent.delete(a.textRange.start,a.textRange.end-a.textRange.start);const d=xc(Ac(c.yParent)),u=Math.min(c.textRange.start,d),f=[{retain:u},...l];c.yParent.applyDelta(f,{sanitize:!1}),Gc(e,c.yParent,h,l,u,a.textRange.start)},split_node:function(e,t,n){const r=Ic(e,t,n.path);if(!r.slateTarget)throw new Error("Y target without corresponding slate node");if(!r.yTarget){if(!J.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const e={};return r.targetDelta.forEach(t=>{t.attributes&&Object.keys(t.attributes).forEach(t=>{e[t]=null})}),r.yParent.format(r.textRange.start,r.textRange.end-r.textRange.start,bc(bc({},e),n.properties))}if(J.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const i=Ic(r.yTarget,r.slateTarget,[n.position]),s=r.slateTarget.children.slice(0,n.position).reduce((e,t)=>e+Nc(t),0),o=r.slateTarget.children.reduce((e,t)=>e+Nc(t),0),a=Rc(Ac(r.yTarget),s,o-s),c=Wc(a),l=Kc(e,r.yTarget,a,s),h=new Pa;h.applyDelta(c,{sanitize:!1}),Object.entries(n.properties).forEach(([e,t])=>{h.setAttribute(e,t)}),r.yTarget.delete(i.textRange.start,r.yTarget.length-i.textRange.start),r.yParent.insertEmbed(r.textRange.end,h),Gc(e,h,l,c,0,s)}};var el=wc(bc(bc({},{insert_text:function(e,t,n){const{yParent:r,textRange:i}=Ic(e,t,n.path),s=ce.get(t,n.path);if(!J.isText(s))throw new Error("Cannot insert text into non-text node");r.insert(i.start+n.offset,n.text,Dc(s))},remove_text:function(e,t,n){const{yParent:r,textRange:i}=Ic(e,t,n.path);r.delete(i.start+n.offset,n.text.length)}}),Zc),{set_selection:()=>{}});var tl=Symbol("slate-yjs-operation"),nl=Symbol("slate-yjs-position-storage"),rl=/* @__PURE__ */new WeakMap,il=/* @__PURE__ */new WeakMap,sl=/* @__PURE__ */new WeakSet,ol={isYjsEditor:e=>q.isEditor(e)&&e.sharedRoot instanceof Pa&&"localOrigin"in e&&"positionStorageOrigin"in e&&"function"==typeof e.applyRemoteEvents&&"function"==typeof e.storeLocalChange&&"function"==typeof e.flushLocalChanges&&"function"==typeof e.isLocalOrigin&&"function"==typeof e.connect&&"function"==typeof e.disconnect,localChanges(e){var t;return null!=(t=il.get(e))?t:[]},applyRemoteEvents(e,t,n){e.applyRemoteEvents(t,n)},storeLocalChange(e,t){e.storeLocalChange(t)},flushLocalChanges(e){e.flushLocalChanges()},connected:e=>sl.has(e),connect(e){e.connect()},disconnect(e){e.disconnect()},isLocal:e=>e.isLocalOrigin(ol.origin(e)),origin(e){const t=rl.get(e);return void 0!==t?t:e.localOrigin},withOrigin(e,t,n){const r=ol.origin(e);rl.set(e,t),n(),rl.set(e,r)},storePosition(e,t,n){const{sharedRoot:r,positionStorageOrigin:i}=e;qc(r);const s=zc(r,e,n);r.doc.transact(()=>{Yc(r,t,s)},i)},removeStoredPosition(e,t){const{sharedRoot:n,positionStorageOrigin:r}=e;qc(n),n.doc.transact(()=>{!function(e,t){e.removeAttribute(Vc+t)}(n,t)},r)},position(e,t){const n=function(e,t){const n=e.getAttribute(Vc+t);return n?Gs(n):null}(e.sharedRoot,t);if(n)return $c(e.sharedRoot,e,n)},storedPositionsRelative(e){return t=e.sharedRoot,Object.fromEntries(Object.entries(t.getAttributes()).filter(([e])=>e.startsWith(Vc)).map(([e,t])=>{return[e.slice(25),(n=t,new $s(null==n.type?null:Ws(n.type.client,n.type.clock),n.tname??null,null==n.item?null:Ws(n.item.client,n.item.clock),null==n.assoc?0:n.assoc))];var n}));var t}};function al(e,t,{localOrigin:n,positionStorageOrigin:r,autoConnect:i=!1}={}){const s=e;s.sharedRoot=t,s.localOrigin=null!=n?n:tl,s.positionStorageOrigin=null!=r?r:nl,s.applyRemoteEvents=(e,t)=>{ol.flushLocalChanges(s),q.withoutNormalizing(s,()=>{ol.withOrigin(s,t,()=>{Bc(s.sharedRoot,s,e)})})},s.isLocalOrigin=e=>e===s.localOrigin;const o=(e,t)=>{s.isLocalOrigin(t.origin)||ol.applyRemoteEvents(s,e,t.origin)};let a=null;i&&(a=setTimeout(()=>{a=null,ol.connect(s)})),s.connect=()=>{if(ol.connected(s))throw new Error("already connected");s.sharedRoot.observeDeep(o);const t=Oc(s.sharedRoot);s.children=t.children,sl.add(s),q.normalize(e,{force:!0}),e.operations.length||e.onChange()},s.disconnect=()=>{a&&clearTimeout(a),ol.flushLocalChanges(s),s.sharedRoot.unobserveDeep(o),sl.delete(s)},s.storeLocalChange=t=>{il.set(s,[...ol.localChanges(s),{op:t,doc:e.children,origin:ol.origin(s)}])},s.flushLocalChanges=()=>{qc(s.sharedRoot);const e=ol.localChanges(s);il.delete(s);const t=[];e.forEach(e=>{const n=t[t.length-1];if(n&&n[0].origin===e.origin)return n.push(e);t.push([e])}),t.forEach(e=>{qc(s.sharedRoot),s.sharedRoot.doc.transact(()=>{e.forEach(e=>{qc(s.sharedRoot),function(e,t,n){const r=el[n.type];if(!r)throw new Error(`Unknown operation: ${n.type}`);r(e,t,n)}(s.sharedRoot,{children:e.doc},e.op)})},e[0].origin)})};const{apply:c,onChange:l}=s;return s.apply=e=>{ol.connected(s)&&ol.isLocal(s)&&ol.storeLocalChange(s,e),c(e)},s.onChange=()=>{ol.connected(s)&&ol.flushLocalChanges(s),l()},s}var cl=/* @__PURE__ */new WeakMap,ll=Symbol("slate-yjs-history-without-saving");function hl(e,t={}){var n=t,{withoutSavingOrigin:r=ll,trackedOrigins:i=/* @__PURE__ */new Set([e.localOrigin])}=n,s=vc(n,["withoutSavingOrigin","trackedOrigins"]);const o=e;o.undoManager=new Co(o.sharedRoot,bc({trackedOrigins:i},s)),o.withoutSavingOrigin=r;const{onChange:a,isLocalOrigin:c}=o;o.onChange=()=>{a(),cl.set(o,o.selection&&Xc(o.sharedRoot,o,o.selection))},o.isLocalOrigin=e=>e===o.withoutSavingOrigin||c(e);const l=({stackItem:e})=>{e.meta.set("selection",o.selection&&Xc(o.sharedRoot,o,o.selection)),e.meta.set("selectionBefore",cl.get(o))},h=({stackItem:e})=>{e.meta.set("selection",o.selection&&Xc(o.sharedRoot,o,o.selection))},d=({stackItem:e,type:t})=>{const n="undo"===t?o.undoManager.redoStack:o.undoManager.undoStack,r=n[n.length-1];r&&(r.meta.set("selection",e.meta.get("selectionBefore")),r.meta.set("selectionBefore",e.meta.get("selection")));const i=e.meta.get("selectionBefore");if(!i)return;const s=function(e,t,n){const r=$c(e,t,n.anchor);if(!r)return null;const i=$c(e,t,n.focus);return i?{anchor:r,focus:i}:null}(o.sharedRoot,o,i);s&&F.select(o,s)},{connect:u,disconnect:f}=o;return o.connect=()=>{u(),o.undoManager.on("stack-item-added",l),o.undoManager.on("stack-item-popped",d),o.undoManager.on("stack-item-updated",h)},o.disconnect=()=>{o.undoManager.off("stack-item-added",l),o.undoManager.off("stack-item-popped",d),o.undoManager.off("stack-item-updated",h),f()},o.undo=()=>{ol.connected(o)&&(ol.flushLocalChanges(o),o.undoManager.undo())},o.redo=()=>{ol.connected(o)&&(ol.flushLocalChanges(o),o.undoManager.redo())},o}var dl=/* @__PURE__ */new WeakMap,ul={isCursorEditor:e=>ol.isYjsEditor(e)&&e.awareness&&"string"==typeof e.cursorDataField&&"string"==typeof e.selectionStateField&&"function"==typeof e.sendCursorPosition&&"function"==typeof e.sendCursorData,sendCursorPosition(e,t=e.selection){e.sendCursorPosition(t)},sendCursorData(e,t){e.sendCursorData(t)},on(e,t,n){var r;if("change"!==t)return;const i=null!=(r=dl.get(e))?r:/* @__PURE__ */new Set;i.add(n),dl.set(e,i)},off(e,t,n){if("change"!==t)return;const r=dl.get(e);r&&r.delete(n)},cursorState(e,t){var n;if(t===e.awareness.clientID||!ol.connected(e))return null;const r=e.awareness.getStates().get(t);return r?{relativeSelection:null!=(n=r[e.selectionStateField])?n:null,data:r[e.cursorDataField],clientId:t}:null},cursorStates:e=>ol.connected(e)?Object.fromEntries(Array.from(e.awareness.getStates().entries(),([t,n])=>t!==e.awareness.clientID&&n?[t,{relativeSelection:n[e.selectionStateField],data:n[e.cursorDataField]}]:null).filter(Array.isArray)):{}};var fl=class extends $e{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=/* @__PURE__ */new Map,this.meta=/* @__PURE__ */new Map,this._checkInterval=setInterval(()=>{const e=wt();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&gl(this,t,"timeout")},Ze(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:wt()});const s=[],o=[],a=[],c=[];null===e?c.push(t):null==i?null!=e&&s.push(t):(o.push(t),Ke(i,e)||a.push(t)),(s.length>0||a.length>0||c.length>0)&&this.emit("change",[{added:s,updated:a,removed:c},"local"]),this.emit("update",[{added:s,updated:o,removed:c},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},gl=(e,t,n)=>{const r=[];for(let i=0;i<t.length;i++){const n=t[i];if(e.states.has(n)){if(e.states.delete(n),n===e.clientID){const t=e.meta.get(n);e.meta.set(n,{clock:t.clock+1,lastUpdated:wt()})}r.push(n)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},pl=(e,t,n=e.states)=>{const r=t.length,i=At();rt(i,r);for(let s=0;s<r;s++){const r=t[s],o=n.get(r)||null,a=e.meta.get(r).clock;rt(i,r),rt(i,a),Ie(i,JSON.stringify(o))}return ht(i)},ml=(e,t,n)=>{const r=Ft(t),i=wt(),s=[],o=[],a=[],c=[],l=Dt(r);for(let h=0;h<l;h++){const t=Dt(r);let n=Dt(r);const l=JSON.parse(an(r)),h=e.meta.get(t),d=e.states.get(t),u=void 0===h?0:h.clock;(u<n||u===n&&null===l&&e.states.has(t))&&(null===l?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===h&&null!==l?s.push(t):void 0!==h&&null===l?c.push(t):null!==l&&(Ke(l,d)||a.push(t),o.push(t)))}(s.length>0||a.length>0||c.length>0)&&e.emit("change",[{added:s,updated:a,removed:c},n]),(s.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:s,updated:o,removed:c},n])},yl=(e,t)=>{rt(e,0);const n=(e=>Ls(e,new _s))(t);qt(e,n)},bl=(e,t,n)=>{rt(e,1),qt(e,Ds(t,n))},wl=(e,t,n,r)=>{try{xs(t,Lt(e),n)}catch(i){null!=r&&r(i)}},vl=(e,t)=>{rt(e,2),qt(e,t)},_l=wl,kl=(e,t,n,r,i)=>{const s=Dt(e);switch(s){case 0:((e,t,n)=>{bl(t,n,Lt(e))})(e,t,n);break;case 1:wl(e,n,r,i);break;case 2:_l(e,n,r,i);break;default:throw new Error("Unknown message type")}return s},Cl=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){const n=this.callbacks[e];return n&&n.forEach(e=>e.apply(this,t)),this}off(e,t){const n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(e=>e!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}},Sl=class{constructor(e){this.data=e,this.encoder=At(),this.decoder=Ft(new Uint8Array(this.data))}peekVarString(){return Kt(this.decoder)}readVarUint(){return Dt(this.decoder)}readVarString(){return an(this.decoder)}readVarUint8Array(){return Lt(this.decoder)}writeVarUint(e){return rt(this.encoder,e)}writeVarString(e){return Ie(this.encoder,e)}writeVarUint8Array(e){return qt(this.encoder,e)}length(){return fn(this.encoder)}},El=/* @__PURE__ */function(e){return e[e.Sync=0]="Sync",e[e.Awareness=1]="Awareness",e[e.Auth=2]="Auth",e[e.QueryAwareness=3]="QueryAwareness",e[e.Stateless=5]="Stateless",e[e.CLOSE=7]="CLOSE",e[e.SyncStatus=8]="SyncStatus",e[e.Ping=9]="Ping",e[e.Pong=10]="Pong",e}({}),Al=/* @__PURE__ */function(e){return e.Connecting="connecting",e.Connected="connected",e.Disconnected="disconnected",e}({}),Tl=class{constructor(){this.encoder=At()}get(e){return e.encoder}toUint8Array(){return ht(this.encoder)}},xl=class extends Tl{constructor(...e){super(...e),this.type=El.CLOSE,this.description="Ask the server to close the connection"}get(e){return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),this.encoder}},Rl=class e extends Cl{static{this.DEDUPLICATABLE_TYPES=/* @__PURE__ */new Set([El.Awareness,El.QueryAwareness])}constructor(e){super(),this.messageQueue=[],this.configuration={url:"",autoConnect:!0,preserveTrailingSlash:!1,document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,handleTimeout:null,providerMap:/* @__PURE__ */new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=Al.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(e),this.configuration.WebSocketPolyfill=e.WebSocketPolyfill?e.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(e){this.status=Al.Connected,this.emit("status",{status:Al.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){const t=e.effectiveName,n=this.configuration.providerMap.get(t);if(n&&n!==e&&n.isAuthenticated)throw new Error(`Cannot attach two providers with the same effective name "${t}". Use sessionAwareness: true to multiplex providers with the same document name.`);this.configuration.providerMap.set(t,e),this.status===Al.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===Al.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){const t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(xl,{documentName:t}),this.configuration.providerMap.delete(t))}setConfiguration(e={}){this.configuration={...this.configuration,...e},this.configuration.autoConnect||(this.shouldConnect=!1)}async connect(){if(this.status===Al.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const{retryPromise:e,cancelFunc:t}=(()=>{let e=!1;return{retryPromise:si(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,handleTimeout:this.configuration.handleTimeout,beforeAttempt:t=>{this.shouldConnect&&!e||t.abort()}}).catch(e=>{if(e&&"ATTEMPT_ABORTED"!==e.code)throw e}),cancelFunc:()=>{e=!0}}})();return this.cancelWebsocketRetry=t,e}attachWebSocketListeners(e,t){const{identifier:n}=e;this.webSocketHandlers[n]={message:e=>this.emit("message",e),close:e=>this.emit("close",{event:e}),open:e=>this.emit("open",e),error:e=>{t(e)}};const r=this.webSocketHandlers[e.identifier];Object.keys(r).forEach(t=>{e.addEventListener(t,r[t])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:e}=this.webSocket,t=this.webSocketHandlers[e];Object.keys(t).forEach(n=>{this.webSocket?.removeEventListener(n,t[n]),delete this.webSocketHandlers[e]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((e,t)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=Al.Connecting,this.emit("status",{status:Al.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=wt();const t=new Uint8Array(e.data);if(1===t.length&&t[0]===El.Ping)return void this.sendPong();const n=new Sl(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){const e=At();rt(e,El.Pong),this.send(ht(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=Al.Connected,this.emit("status",{status:Al.Connected}),this.emit("connect"),this.messageQueue.forEach(e=>this.send(e)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){this.connectionAttempt?.reject(),this.connectionAttempt=null}checkConnection(){this.status===Al.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=wt()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):(this.webSocket?.close(),this.messageQueue=[])))}get serverUrl(){if(this.configuration.preserveTrailingSlash)return this.configuration.url;let e=this.configuration.url;for(;"/"===e[e.length-1];)e=e.slice(0,e.length-1);return e}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,null!==this.webSocket)try{this.webSocket.close(),this.messageQueue=[]}catch(e){}}parseQueuedMessage(e){try{const t=Ft(e);return{documentName:an(t),messageType:Dt(t)}}catch{return null}}addToQueue(t){if(t instanceof Uint8Array){const n=this.parseQueuedMessage(t);n&&e.DEDUPLICATABLE_TYPES.has(n.messageType)&&(this.messageQueue=this.messageQueue.filter(e=>{if(!(e instanceof Uint8Array))return!0;const t=this.parseQueuedMessage(e);return!t||!(t.documentName===n.documentName&&t.messageType===n.messageType)}))}this.messageQueue.push(t)}send(e){this.webSocket?.readyState===ni.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=Al.Disconnected,this.emit("status",{status:Al.Disconnected}),this.emit("disconnect",{event:e}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}},Dl=class{constructor(e){this.message=e}apply(e,t){const{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case El.Sync:this.applySyncMessage(e,t);break;case El.Awareness:this.applyAwarenessMessage(e);break;case El.Auth:this.applyAuthMessage(e);break;case El.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case El.Stateless:e.receiveStateless(an(n.decoder));break;case El.SyncStatus:this.applySyncStatusMessage(e,1===zt(n.decoder));break;case El.CLOSE:{const t={code:1e3,reason:an(n.decoder)};e.onClose(),e.configuration.onClose({event:t}),e.forwardClose({event:t});break}}n.length()>i+1&&e.send(Tl,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(El.Sync);const r=kl(n.decoder,n.encoder,e.document,e);t&&1===r&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;ml(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;Xr(t.decoder,e.sendToken.bind(e),e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;t.writeVarUint(El.Awareness),t.writeVarUint8Array(pl(e.awareness,Array.from(e.awareness.getStates().keys())))}},Ol=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return ht(this.encoder)}send(e){e?.send(this.create())}},Pl=class extends Tl{constructor(...e){super(...e),this.type=El.Auth,this.description="Authentication"}get(e){if(void 0===e.token)throw new Error("The authentication message requires `token` as an argument.");return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),Gr(this.encoder,e.token),Ie(this.encoder,"4.6.0"),this.encoder}},Ll=class extends Tl{constructor(...e){super(...e),this.type=El.Awareness,this.description="Awareness states update"}get(e){if(void 0===e.awareness)throw new Error("The awareness message requires awareness as an argument");if(void 0===e.clients)throw new Error("The awareness message requires clients as an argument");let t;return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),t=void 0===e.states?pl(e.awareness,e.clients):pl(e.awareness,e.clients,e.states),qt(this.encoder,t),this.encoder}},Ml=class extends Tl{constructor(...e){super(...e),this.type=El.Stateless,this.description="A stateless message"}get(e){return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),Ie(this.encoder,e.payload??""),this.encoder}},Nl=class extends Tl{constructor(...e){super(...e),this.type=El.Sync,this.description="First sync step"}get(e){if(void 0===e.document)throw new Error("The sync step one message requires document as an argument");return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),yl(this.encoder,e.document),this.encoder}},Il=class extends Tl{constructor(...e){super(...e),this.type=El.Sync,this.description="A document update"}get(e){return Ie(this.encoder,e.documentName),rt(this.encoder,this.type),vl(this.encoder,e.update),this.encoder}},Ul=class extends Error{constructor(...e){super(...e),this.code=1001}},jl=class extends Cl{get effectiveName(){return this.configuration.sessionAwareness?ei(this.configuration.name,this.sessionId):this.configuration.name}constructor(e){super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,sessionAwareness:!1,forceSyncInterval:!1,flushDelay:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.pendingUpdates=[],this.pendingAwarenessClients=/* @__PURE__ */new Set,this.flushTimeout=null,this.sessionId=Math.random().toString(36).slice(2),this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=()=>this.emit("connect"),this.forwardStatus=e=>this.emit("status",e),this.forwardClose=e=>this.emit("close",e),this.forwardDisconnect=e=>this.emit("disconnect",e),this.forwardDestroy=()=>this.emit("destroy"),this.setConfiguration(e),this.configuration.document=e.document?e.document:new ms,this.configuration.awareness=void 0!==e.awareness?e.awareness:new fl(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),this.awareness?.on("update",()=>{this.emit("awarenessUpdate",{states:Zr(this.awareness.getStates())})}),this.awareness?.on("change",()=>{this.emit("awarenessChange",{states:Zr(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),this.awareness?.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&"number"==typeof this.configuration.forceSyncInterval&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(e={}){e.websocketProvider||(this.manageSocket=!0,this.configuration.websocketProvider=new Rl(e)),this.configuration={...this.configuration,...e}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),0===this.unsyncedChanges&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(Nl,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&gl(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(Ml,{documentName:this.effectiveName,payload:e})}async sendToken(){let e;try{e=await this.getToken()}catch(t){return void this.permissionDeniedHandler(`Failed to get token during sendToken(): ${t}`)}this.send(Pl,{token:e??"",documentName:this.effectiveName})}get batchingEnabled(){return!!this.configuration.flushDelay&&"number"==typeof this.configuration.flushDelay}documentUpdateHandler(e,t){if(t!==this){if(!this.batchingEnabled)return this.incrementUnsyncedChanges(),void this.send(Il,{update:e,documentName:this.effectiveName});0===this.pendingUpdates.length&&this.incrementUnsyncedChanges(),this.pendingUpdates.push(e),this.scheduleFlush()}}awarenessUpdateHandler({added:e,updated:t,removed:n},r){if(r===this)return;const i=e.concat(t).concat(n);if(this.batchingEnabled){for(const e of i)this.pendingAwarenessClients.add(e);this.scheduleFlush()}else this.send(Ll,{awareness:this.awareness,clients:i,documentName:this.effectiveName})}scheduleFlush(){null===this.flushTimeout&&(this.flushTimeout=setTimeout(()=>{this.flushTimeout=null,this.flushPendingUpdates()},this.configuration.flushDelay))}flushPendingUpdates(){if(null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates.length>0){const e=1===this.pendingUpdates.length?this.pendingUpdates[0]:Ao(this.pendingUpdates);this.pendingUpdates=[],this.send(Il,{update:e,documentName:this.effectiveName})}if(this.pendingAwarenessClients.size>0){const e=Array.from(this.pendingAwarenessClients);this.pendingAwarenessClients.clear(),this.send(Ll,{awareness:this.awareness,clients:e,documentName:this.effectiveName})}}get synced(){return this.isSynced}set synced(e){this.isSynced!==e&&(this.isSynced=e,e&&this.emit("synced",{state:e}))}receiveStateless(e){this.emit("stateless",{payload:e})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect()}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect()}async onOpen(e){this.isAuthenticated=!1,this.emit("open",{event:e}),await this.sendToken(),this.startSync()}async getToken(){return"function"==typeof this.configuration.token?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(Nl,{document:this.document,documentName:this.effectiveName}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(Ll,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;const n=new Ol(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new Sl(e.data),{documentName:n}=ti(t.readVarString());t.writeVarString(this.effectiveName),this.emit("message",{event:e,message:new Sl(e.data)}),new Dl(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates=[],this.pendingAwarenessClients.clear(),this.awareness&&gl(this.awareness,Array.from(this.awareness.getStates().keys()).filter(e=>e!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(gl(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.flushPendingUpdates(),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),"undefined"!=typeof window&&"removeEventListener"in window&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("status",this.forwardStatus),this.configuration.websocketProvider.off("status",this.configuration.onStatus),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("status",this.configuration.onStatus),this.configuration.websocketProvider.on("status",this.forwardStatus),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(e){this.emit("authenticationFailed",{reason:e}),this.isAuthenticated=!1}authenticatedHandler(e){this.isAuthenticated=!0,this.authorizedScope=e,this.emit("authenticated",{scope:e})}setAwarenessField(e,t){if(!this.awareness)throw new Ul(`Cannot set awareness field "${e}" to ${JSON.stringify(t)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(e,t)}},Fl=e=>Zt((t,n)=>{e.onerror=e=>n(new Error(e.target.error)),e.onsuccess=e=>t(e.target.result)}),Bl=(e,t,n="readwrite")=>{const r=e.transaction(t,n);return t.map(e=>$l(r,e))},Wl=(e,t)=>Fl(e.count(t)),Hl=(e,t)=>Fl(e.delete(t)),ql=(e,t)=>Fl(e.add(t)),Vl=(e,t=null)=>((e,t,n)=>{let r=null;return zl(e,t,e=>(r=e,!1),n).then(()=>r)})(e,t,"prev"),zl=(e,t,n,r="next")=>((e,t)=>Zt((n,r)=>{e.onerror=r,e.onsuccess=async e=>{const r=e.target.result;if(null===r||!1===await t(r))return n();r.continue()}}))(e.openKeyCursor(t,r),e=>n(e.key)),$l=(e,t)=>e.objectStore(t),Yl="custom",Jl="updates",Ql=(e,t=()=>{},n=()=>{})=>{const[r]=Bl(e.db,[Jl]);return(i=r,a=e._dbref,c=!1,s=IDBKeyRange.lowerBound(a,c),Fl(i.getAll(s,o))).then(i=>{e._destroyed||(t(r),wo(e.doc,()=>{i.forEach(t=>xs(e.doc,t))},e,!1),n(r))}).then(()=>Vl(r).then(t=>{e._dbref=t+1})).then(()=>Wl(r).then(t=>{e._dbsize=t})).then(()=>r);var i,s,o,a,c},Kl=(e,t=!0)=>Ql(e).then(n=>{(t||e._dbsize>=500)&&ql(n,Ds(e.doc)).then(()=>{return Hl(n,(t=e._dbref,r=!0,IDBKeyRange.upperBound(t,r)));var t,r}).then(()=>Wl(n).then(t=>{e._dbsize=t}))}),Gl=class extends $e{constructor(e,t){super(),this.doc=t,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=((e,t)=>Zt((n,r)=>{const i=indexedDB.open(e);i.onupgradeneeded=e=>t(e.target.result),i.onerror=e=>r(Xt(e.target.error)),i.onsuccess=e=>{const t=e.target.result;t.onversionchange=()=>{t.close()},n(t)}}))(e,e=>((e,t)=>t.forEach(t=>e.createObjectStore.apply(e,t)))(e,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Zt(e=>this.on("synced",()=>e(this))),this._db.then(e=>{this.db=e;Ql(this,e=>ql(e,Ds(t)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(e,t)=>{if(this.db&&t!==this){const[t]=Bl(this.db,[Jl]);ql(t,e),++this._dbsize>=500&&(null!==this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{Kl(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},t.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),t.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(e=>{e.close()})}clearData(){return this.destroy().then(()=>{var e;e=this.name,Fl(indexedDB.deleteDatabase(e))})}get(e){return this._db.then(t=>{const[n]=Bl(t,[Yl],"readonly");return((e,t)=>Fl(e.get(t)))(n,e)})}set(e,t){return this._db.then(n=>{const[r]=Bl(n,[Yl]);return((e,t,n)=>Fl(e.put(t,n)))(r,t,e)})}del(e){return this._db.then(t=>{const[n]=Bl(t,[Yl]);return Hl(n,e)})}},Xl=3e4,Zl=e=>{if(e.shouldConnect&&null===e.ws){const t=new WebSocket(e.url),n=e.binaryType;let r=null;n&&(t.binaryType=n),e.ws=t,e.connecting=!0,e.connected=!1,t.onmessage=t=>{e.lastMessageReceived=wt();const n=t.data,i="string"==typeof n?JSON.parse(n):n;i&&"pong"===i.type&&(clearTimeout(r),r=setTimeout(s,15e3)),e.emit("message",[i,e])};const i=t=>{null!==e.ws&&(e.ws=null,e.connecting=!1,e.connected?(e.connected=!1,e.emit("disconnect",[{type:"disconnect",error:t},e])):e.unsuccessfulReconnects++,setTimeout(Zl,Be(1200*tt(e.unsuccessfulReconnects+1),2500),e)),clearTimeout(r)},s=()=>{e.ws===t&&e.send({type:"ping"})};t.onclose=()=>i(null),t.onerror=e=>i(e),t.onopen=()=>{e.lastMessageReceived=wt(),e.connecting=!1,e.connected=!0,e.unsuccessfulReconnects=0,e.emit("connect",[{type:"connect"},e]),r=setTimeout(s,15e3)}}},eh=class extends $e{constructor(e,{binaryType:t}={}){super(),this.url=e,this.ws=null,this.binaryType=t||null,this.connected=!1,this.connecting=!1,this.unsuccessfulReconnects=0,this.lastMessageReceived=0,this.shouldConnect=!0,this._checkInterval=setInterval(()=>{this.connected&&Xl<wt()-this.lastMessageReceived&&this.ws.close()},15e3),Zl(this)}send(e){this.ws&&this.ws.send(JSON.stringify(e))}destroy(){clearInterval(this._checkInterval),this.disconnect(),super.destroy()}disconnect(){this.shouldConnect=!1,null!==this.ws&&this.ws.close()}connect(){this.shouldConnect=!0,this.connected||null!==this.ws||Zl(this)}},th=/* @__PURE__ */new Map,nh="undefined"==typeof BroadcastChannel?class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.key===e&&null!==this.onmessage&&this.onmessage({data:et(t.newValue||"")}),We(this._onChange)}postMessage(e){Je.setItem(this.room,it(Xe(e)))}close(){yt(this._onChange)}}:BroadcastChannel,rh=e=>en(th,e,()=>{const t=gt(),n=new nh(e);return n.onmessage=e=>t.forEach(t=>t(e.data,"broadcastchannel")),{bc:n,subs:t}}),ih=/* @__PURE__ */t(/* @__PURE__ */n((t,n)=>{!function(e){if("object"==typeof t&&void 0!==n)n.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window).SimplePeer=e()}}(function(){var t=Math.floor,n=Math.abs,r=Math.pow;return function t(n,r,i){function s(a,c){if(!r[a]){if(!n[a]){var l="function"==typeof e&&e;if(!c&&l)return l(a,!0);if(o)return o(a,!0);var h=/* @__PURE__ */new Error("Cannot find module '"+a+"'");throw h.code="MODULE_NOT_FOUND",h}var d=r[a]={exports:{}};n[a][0].call(d.exports,function(e){return s(n[a][1][e]||e)},d,d.exports,t,n,r,i)}return r[a].exports}for(var o="function"==typeof e&&e,a=0;a<i.length;a++)s(i[a]);return s}({1:[function(e,t,n){function r(e){var t=e.length;if(0<t%4)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function i(e){return o[63&e>>18]+o[63&e>>12]+o[63&e>>6]+o[63&e]}function s(e,t,n){for(var r,s=[],o=t;o<n;o+=3)r=(16711680&e[o]<<16)+(65280&e[o+1]<<8)+(255&e[o+2]),s.push(i(r));return s.join("")}n.byteLength=function(e){var t=r(e),n=t[0],i=t[1];return 3*(n+i)/4-i},n.toByteArray=function(e){var t,n,i=r(e),s=i[0],o=i[1],l=new c(function(e,t,n){return 3*(t+n)/4-n}(0,s,o)),h=0,d=0<o?s-4:s;for(n=0;n<d;n+=4)t=a[e.charCodeAt(n)]<<18|a[e.charCodeAt(n+1)]<<12|a[e.charCodeAt(n+2)]<<6|a[e.charCodeAt(n+3)],l[h++]=255&t>>16,l[h++]=255&t>>8,l[h++]=255&t;return 2===o&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,l[h++]=255&t),1===o&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[e.charCodeAt(n+2)]>>2,l[h++]=255&t>>8,l[h++]=255&t),l},n.fromByteArray=function(e){for(var t,n=e.length,r=n%3,i=[],a=16383,c=0,l=n-r;c<l;c+=a)i.push(s(e,c,c+a>l?l:c+a));return 1===r?(t=e[n-1],i.push(o[t>>2]+o[63&t<<4]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(o[t>>10]+o[63&t>>4]+o[63&t<<2]+"=")),i.join("")};for(var o=[],a=[],c="undefined"==typeof Uint8Array?Array:Uint8Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=0;h<64;++h)o[h]=l[h],a[l.charCodeAt(h)]=h;a[45]=62,a[95]=63},{}],2:[function(){},{}],3:[function(e,t,n){(function(){(function(){var t=String.fromCharCode,i=Math.min;function s(e){if(2147483647<e)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=o.prototype,t}function o(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if(("string"!=typeof t||""===t)&&(t="utf8"),!o.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|u(e,t),r=s(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}(e,t);if(ArrayBuffer.isView(e))return h(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(F(e,ArrayBuffer)||e&&F(e.buffer,ArrayBuffer))return function(e,t,n){if(0>t||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n);return r.__proto__=o.prototype,r}(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return o.from(r,t,n);var i=function(e){if(o.isBuffer(e)){var t=0|d(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0===e.length?"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0:"number"!=typeof e.length||B(e.length)?s(0):h(e)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(0>e)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return c(e),s(0>e?0:0|d(e))}function h(e){for(var t=0>e.length?0:0|d(e.length),n=s(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function d(e){if(e>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647..toString(16)+" bytes");return 0|e}function u(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||F(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=2<arguments.length&&!0===arguments[2];if(!r&&0===n)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return I(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return U(e).length;default:if(i)return r?-1:I(e).length;t=(""+t).toLowerCase(),i=!0}}function f(e,t,n){var r=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),0>=n)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return S(this,t,n);case"ascii":return A(this,t,n);case"latin1":case"binary":return T(this,t,n);case"base64":return C(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function p(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):2147483647<n?n=2147483647:-2147483648>n&&(n=-2147483648),B(n=+n)&&(n=i?0:e.length-1),0>n&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(0>n){if(!i)return-1;n=0}if("string"==typeof t&&(t=o.from(t,r)),o.isBuffer(t))return 0===t.length?-1:m(e,t,n,r,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):m(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function m(e,t,n,r,i){function s(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var o,a=1,c=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=(r+"").toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(2>e.length||2>t.length)return-1;a=2,c/=2,l/=2,n/=2}if(i){var h=-1;for(o=n;o<c;o++)if(s(e,o)!==s(t,-1===h?0:o-h))-1!==h&&(o-=o-h),h=-1;else if(-1===h&&(h=o),o-h+1===l)return h*a}else for(n+l>c&&(n=c-l),o=n;0<=o;o--){for(var d=!0,u=0;u<l;u++)if(s(e,o+u)!==s(t,u)){d=!1;break}if(d)return o}return-1}function y(e,t,n,r){n=+n||0;var i=e.length-n;r?(r=+r)>i&&(r=i):r=i;var s=t.length;r>s/2&&(r=s/2);for(var o,a=0;a<r;++a){if(B(o=parseInt(t.substr(2*a,2),16)))return a;e[n+a]=o}return a}function b(e,t,n,r){return j(I(t,e.length-n),e,n,r)}function w(e,t,n,r){return j(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return w(e,t,n,r)}function _(e,t,n,r){return j(U(t),e,n,r)}function k(e,t,n,r){return j(function(e,t){for(var n,r,i,s=[],o=0;o<e.length&&!(0>(t-=2));++o)n=e.charCodeAt(o),r=n>>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function C(e,t,n){return 0===t&&n===e.length?W.fromByteArray(e):W.fromByteArray(e.slice(t,n))}function S(e,t,n){n=i(e.length,n);for(var r=[],s=t;s<n;){var o,a,c,l,h=e[s],d=null,u=239<h?4:223<h?3:191<h?2:1;if(s+u<=n)1===u?128>h&&(d=h):2===u?128==(192&(o=e[s+1]))&&(127<(l=(31&h)<<6|63&o)&&(d=l)):3===u?(o=e[s+1],a=e[s+2],128==(192&o)&&128==(192&a)&&(2047<(l=(15&h)<<12|(63&o)<<6|63&a)&&(55296>l||57343<l)&&(d=l))):4===u&&(o=e[s+1],a=e[s+2],c=e[s+3],128==(192&o)&&128==(192&a)&&128==(192&c)&&(65535<(l=(15&h)<<18|(63&o)<<12|(63&a)<<6|63&c)&&1114112>l&&(d=l)));null===d?(d=65533,u=1):65535<d&&(d-=65536,r.push(55296|1023&d>>>10),d=56320|1023&d),r.push(d),s+=u}return E(r)}function E(e){var n=e.length;if(n<=4096)return t.apply(String,e);for(var r="",i=0;i<n;)r+=t.apply(String,e.slice(i,i+=4096));return r}function A(e,n,r){var s="";r=i(e.length,r);for(var o=n;o<r;++o)s+=t(127&e[o]);return s}function T(e,n,r){var s="";r=i(e.length,r);for(var o=n;o<r;++o)s+=t(e[o]);return s}function x(e,t,n){var r=e.length;(!t||0>t)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var i="",s=t;s<n;++s)i+=N(e[s]);return i}function R(e,n,r){for(var i=e.slice(n,r),s="",o=0;o<i.length;o+=2)s+=t(i[o]+256*i[o+1]);return s}function D(e,t,n){if(0!=e%1||0>e)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,r,i,s){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function P(e,t,n,r){if(n+r>e.length)throw new RangeError("Index out of range");if(0>n)throw new RangeError("Index out of range")}function L(e,t,n,r,i){return t=+t,n>>>=0,i||P(e,0,n,4),H.write(e,t,n,r,23,4),n+4}function M(e,t,n,r,i){return t=+t,n>>>=0,i||P(e,0,n,8),H.write(e,t,n,r,52,8),n+8}function N(e){return 16>e?"0"+e.toString(16):e.toString(16)}function I(e,t){t=t||1/0;for(var n,r=e.length,i=null,s=[],o=0;o<r;++o){if(55295<(n=e.charCodeAt(o))&&57344>n){if(!i){if(56319<n){-1<(t-=3)&&s.push(239,191,189);continue}if(o+1===r){-1<(t-=3)&&s.push(239,191,189);continue}i=n;continue}if(56320>n){-1<(t-=3)&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&-1<(t-=3)&&s.push(239,191,189);if(i=null,128>n){if(0>(t-=1))break;s.push(n)}else if(2048>n){if(0>(t-=2))break;s.push(192|n>>6,128|63&n)}else if(65536>n){if(0>(t-=3))break;s.push(224|n>>12,128|63&n>>6,128|63&n)}else{if(!(1114112>n))throw new Error("Invalid code point");if(0>(t-=4))break;s.push(240|n>>18,128|63&n>>12,128|63&n>>6,128|63&n)}}return s}function U(e){return W.toByteArray(function(e){if(2>(e=(e=e.split("=")[0]).trim().replace(q,"")).length)return"";for(;0!=e.length%4;)e+="=";return e}(e))}function j(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function F(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function B(e){return e!=e}var W=e("base64-js"),H=e("ieee754");n.Buffer=o,n.SlowBuffer=function(e){return+e!=e&&(e=0),o.alloc(+e)},n.INSPECT_MAX_BYTES=50,n.kMaxLength=2147483647,o.TYPED_ARRAY_SUPPORT=function(){try{var e=/* @__PURE__ */new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||console.error,Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){return o.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){return o.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),o.poolSize=8192,o.from=function(e,t,n){return a(e,t,n)},o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,o.alloc=function(e,t,n){return function(e,t,n){return c(e),0>=e||void 0===t?s(e):"string"==typeof n?s(e).fill(t,n):s(e).fill(t)}(e,t,n)},o.allocUnsafe=function(e){return l(e)},o.allocUnsafeSlow=function(e){return l(e)},o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(F(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),F(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,s=0,a=i(n,r);s<a;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},o.isEncoding=function(e){switch((e+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=o.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var s=e[n];if(F(s,Uint8Array)&&(s=o.from(s)),!o.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,i),i+=s.length}return r},o.byteLength=u,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var e=this.length;if(0!=e%2)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},o.prototype.swap32=function(){var e=this.length;if(0!=e%4)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},o.prototype.swap64=function(){var e=this.length;if(0!=e%8)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},o.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?S(this,0,e):f.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",t=n.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},o.prototype.compare=function(e,t,n,r,s){if(F(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),0>t||n>e.length||0>r||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(s>>>=0)-(r>>>=0),c=(n>>>=0)-(t>>>=0),l=i(a,c),h=this.slice(r,s),d=e.slice(t,n),u=0;u<l;++u)if(h[u]!==d[u]){a=h[u],c=d[u];break}return a<c?-1:c<a?1:0},o.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},o.prototype.indexOf=function(e,t,n){return p(this,e,t,n,!0)},o.prototype.lastIndexOf=function(e,t,n){return p(this,e,t,n,!1)},o.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),0<e.length&&(0>n||0>t)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return y(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":return w(this,e,t,n);case"latin1":case"binary":return v(this,e,t,n);case"base64":return _(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},o.prototype.slice=function(e,t){var n=this.length;0>(e=~~e)?0>(e+=n)&&(e=0):e>n&&(e=n),0>(t=void 0===t?n:~~t)?0>(t+=n)&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return r.__proto__=o.prototype,r},o.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var r=this[e],i=1,s=0;++s<t&&(i*=256);)r+=this[e+s]*i;return r},o.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var r=this[e+--t],i=1;0<t&&(i*=256);)r+=this[e+--t]*i;return r},o.prototype.readUInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var i=this[e],s=1,o=0;++o<t&&(s*=256);)i+=this[e+o]*s;return i>=(s*=128)&&(i-=r(2,8*t)),i},o.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var i=t,s=1,o=this[e+--i];0<i&&(s*=256);)o+=this[e+--i]*s;return o>=(s*=128)&&(o-=r(2,8*t)),o},o.prototype.readInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||D(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt16BE=function(e,t){e>>>=0,t||D(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||D(e,4,this.length),H.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||D(e,4,this.length),H.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||D(e,8,this.length),H.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||D(e,8,this.length),H.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,n,i){(e=+e,t>>>=0,n>>>=0,i)||O(this,e,t,n,r(2,8*n)-1,0);var s=1,o=0;for(this[t]=255&e;++o<n&&(s*=256);)this[t+o]=255&e/s;return t+n},o.prototype.writeUIntBE=function(e,t,n,i){(e=+e,t>>>=0,n>>>=0,i)||O(this,e,t,n,r(2,8*n)-1,0);var s=n-1,o=1;for(this[t+s]=255&e;0<=--s&&(o*=256);)this[t+s]=255&e/o;return t+n},o.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){var s=r(2,8*n-1);O(this,e,t,n,s-1,-s)}var o=0,a=1,c=0;for(this[t]=255&e;++o<n&&(a*=256);)0>e&&0===c&&0!==this[t+o-1]&&(c=1),this[t+o]=255&(e/a|0)-c;return t+n},o.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){var s=r(2,8*n-1);O(this,e,t,n,s-1,-s)}var o=n-1,a=1,c=0;for(this[t+o]=255&e;0<=--o&&(a*=256);)0>e&&0===c&&0!==this[t+o+1]&&(c=1),this[t+o]=255&(e/a|0)-c;return t+n},o.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},o.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},o.prototype.writeDoubleLE=function(e,t,n){return M(this,e,t,!0,n)},o.prototype.writeDoubleBE=function(e,t,n){return M(this,e,t,!1,n)},o.prototype.copy=function(e,t,n,r){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),0<r&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(0>t)throw new RangeError("targetStart out of bounds");if(0>n||n>=this.length)throw new RangeError("Index out of range");if(0>r)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var i=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var s=i-1;0<=s;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return i},o.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!o.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var i=e.charCodeAt(0);("utf8"===r&&128>i||"latin1"===r)&&(e=i)}}else"number"==typeof e&&(e&=255);if(0>t||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var a=o.isBuffer(e)?e:o.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=a[s%c]}return this};var q=/[^+/0-9A-Za-z-_]/g}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:9}],4:[function(e,t,n){(function(r){(function(){n.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"===e||(r++,"%c"===e&&(i=r))}),e.splice(i,0,n)},n.save=function(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}},n.load=function(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e},n.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},n.storage=function(){try{return localStorage}catch(e){}}(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0)}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],n.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(n);const{formatters:i}=t.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":5,_process:12}],5:[function(e,t){t.exports=function(t){function r(e){function t(...e){if(!t.enabled)return;const i=t,s=+/* @__PURE__ */new Date;i.diff=s-(n||s),i.prev=n,i.curr=s,n=s,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,n)=>{if("%%"===t)return"%";o++;const s=r.formatters[n];if("function"==typeof s){const n=e[o];t=s.call(i,n),e.splice(o,1),o--}return t}),r.formatArgs.call(i,e),(i.log||r.log).apply(i,e)}let n,s=null;return t.namespace=e,t.useColors=r.useColors(),t.color=r.selectColor(e),t.extend=i,t.destroy=r.destroy,Object.defineProperty(t,"enabled",{enumerable:!0,configurable:!1,get:()=>null===s?r.enabled(e):s,set:e=>{s=e}}),"function"==typeof r.init&&r.init(t),t}function i(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return r.debug=r,r.default=r,r.coerce=function(e){return e instanceof Error?e.stack||e.message:e},r.disable=function(){const e=[...r.names.map(s),...r.skips.map(s).map(e=>"-"+e)].join(",");return r.enable(""),e},r.enable=function(e){let t;r.save(e),r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(t=0;t<i;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))},r.enabled=function(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=r.skips.length;t<n;t++)if(r.skips[t].test(e))return!1;for(t=0,n=r.names.length;t<n;t++)if(r.names[t].test(e))return!0;return!1},r.humanize=e("ms"),r.destroy=function(){},Object.keys(t).forEach(e=>{r[e]=t[e]}),r.names=[],r.skips=[],r.formatters={},r.selectColor=function(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return r.colors[n(t)%r.colors.length]},r.enable(r.load()),r}},{ms:11}],6:[function(e,t){function n(e,t){for(const n in t)Object.defineProperty(e,n,{value:t[n],enumerable:!0,configurable:!0});return e}t.exports=function(e,t,r){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");r||(r={}),"object"==typeof t&&(r=t,t=""),t&&(r.code=t);try{return n(e,r)}catch(t){r.message=e.message,r.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),n(new i,r)}}},{}],7:[function(e,t){function n(){n.init.call(this)}function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function i(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function s(e,t,n,s){var o,a,c;if(r(n),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]),void 0===c)c=a[t]=n,++e._eventsCount;else if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),0<(o=i(e))&&c.length>o&&!c.warned){c.warned=!0;var l=/* @__PURE__ */new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,console&&console.warn}return e}function o(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function a(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=o.bind(r);return i.listener=n,r.wrapFn=i,i}function c(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):h(i,i.length)}function l(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function h(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function d(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){r.once&&e.removeEventListener(t,i),n(s)})}}var u,f="object"==typeof Reflect?Reflect:null,g=f&&"function"==typeof f.apply?f.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};u=f&&"function"==typeof f.ownKeys?f.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var p=Number.isNaN||function(e){return e!=e};t.exports=n,t.exports.once=function(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,s),r(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}d(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&d(e,"error",t,n)}(e,i,{once:!0})})},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var m=10;Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return m},set:function(e){if("number"!=typeof e||0>e||p(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");m=e}}),n.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||p(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return i(this)},n.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,i=this._events;if(void 0!==i)r=r&&void 0===i.error;else if(!r)return!1;if(r){var s;if(0<t.length&&(s=t[0]),s instanceof Error)throw s;var o=/* @__PURE__ */new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)g(a,this,t);else{var c=a.length,l=h(a,c);for(n=0;n<c;++n)g(l[n],this,t)}return!0},n.prototype.addListener=function(e,t){return s(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return s(this,e,t,!0)},n.prototype.once=function(e,t){return r(t),this.on(e,a(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return r(t),this.prependListener(e,a(this,e,t)),this},n.prototype.removeListener=function(e,t){var n,i,s,o,a;if(r(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;0<=o;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,s=o;break}if(0>s)return this;0===s?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,s),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,n,r=this._events;if(void 0===r)return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;0<=n;n--)this.removeListener(e,t[n]);return this},n.prototype.listeners=function(e){return c(this,e,!0)},n.prototype.rawListeners=function(e){return c(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):l.call(e,t)},n.prototype.listenerCount=l,n.prototype.eventNames=function(){return 0<this._eventsCount?u(this._events):[]}},{}],8:[function(e,t){t.exports=function(){if("undefined"==typeof globalThis)return null;var e={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}},{}],9:[function(e,i,s){s.read=function(e,t,n,i,s){var o,a,c=8*s-i-1,l=(1<<c)-1,h=l>>1,d=-7,u=n?s-1:0,f=n?-1:1,g=e[t+u];for(u+=f,o=g&(1<<-d)-1,g>>=-d,d+=c;0<d;o=256*o+e[t+u],u+=f,d-=8);for(a=o&(1<<-d)-1,o>>=-d,d+=i;0<d;a=256*a+e[t+u],u+=f,d-=8);if(0===o)o=1-h;else{if(o===l)return a?NaN:1/0*(g?-1:1);a+=r(2,i),o-=h}return(g?-1:1)*a*r(2,o-i)},s.write=function(e,i,s,o,a,c){var l,h,d,u=Math.LN2,f=Math.log,g=8*c-a-1,p=(1<<g)-1,m=p>>1,y=23===a?r(2,-24)-r(2,-77):0,b=o?0:c-1,w=o?1:-1,v=0>i||0===i&&0>1/i?1:0;for(i=n(i),isNaN(i)||i===1/0?(h=isNaN(i)?1:0,l=p):(l=t(f(i)/u),1>i*(d=r(2,-l))&&(l--,d*=2),2<=(i+=1<=l+m?y/d:y*r(2,1-m))*d&&(l++,d/=2),l+m>=p?(h=0,l=p):1<=l+m?(h=(i*d-1)*r(2,a),l+=m):(h=i*r(2,m-1)*r(2,a),l=0));8<=a;e[s+b]=255&h,b+=w,h/=256,a-=8);for(l=l<<a|h,g+=a;0<g;e[s+b]=255&l,b+=w,l/=256,g-=8);e[s+b-w]|=128*v}},{}],10:[function(e,t){t.exports="function"==typeof Object.create?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],11:[function(e,t){var r=Math.round;function i(e){var t=n(e);return 864e5<=t?r(e/864e5)+"d":36e5<=t?r(e/36e5)+"h":6e4<=t?r(e/6e4)+"m":1e3<=t?r(e/1e3)+"s":e+"ms"}function s(e){var t=n(e);return 864e5<=t?o(e,t,864e5,"day"):36e5<=t?o(e,t,36e5,"hour"):6e4<=t?o(e,t,6e4,"minute"):1e3<=t?o(e,t,1e3,"second"):e+" ms"}function o(e,t,n,i){return r(e/n)+" "+i+(t>=1.5*n?"s":"")}t.exports=function(e,t){t=t||{};var n=typeof e;if("string"==n&&0<e.length)return function(e){if(!(100<(e+="").length)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();return"years"===r||"year"===r||"yrs"===r||"yr"===r||"y"===r?315576e5*n:"weeks"===r||"week"===r||"w"===r?6048e5*n:"days"===r||"day"===r||"d"===r?864e5*n:"hours"===r||"hour"===r||"hrs"===r||"hr"===r||"h"===r?36e5*n:"minutes"===r||"minute"===r||"mins"===r||"min"===r||"m"===r?6e4*n:"seconds"===r||"second"===r||"secs"===r||"sec"===r||"s"===r?1e3*n:"milliseconds"===r||"millisecond"===r||"msecs"===r||"msec"===r||"ms"===r?n:void 0}}}(e);if("number"===n&&isFinite(e))return t.long?s(e):i(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],12:[function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function i(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(n){try{return l.call(null,e,0)}catch(n){return l.call(this,e,0)}}}function s(){g&&u&&(g=!1,u.length?f=u.concat(f):p=-1,f.length&&o())}function o(){if(!g){var e=i(s);g=!0;for(var t=f.length;t;){for(u=f,f=[];++p<t;)u&&u[p].run();p=-1,t=f.length}u=null,g=!1,function(e){if(h===clearTimeout)return clearTimeout(e);if((h===r||!h)&&clearTimeout)return h=clearTimeout,clearTimeout(e);try{return h(e)}catch(n){try{return h.call(null,e)}catch(n){return h.call(this,e)}}}(e)}}function a(e,t){this.fun=e,this.array=t}function c(){}var l,h,d=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{h="function"==typeof clearTimeout?clearTimeout:r}catch(t){h=r}}();var u,f=[],g=!1,p=-1;d.nextTick=function(e){var t=Array(arguments.length-1);if(1<arguments.length)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];f.push(new a(e,t)),1!==f.length||g||i(o)},a.prototype.run=function(){this.fun.apply(null,this.array)},d.title="browser",d.browser=!0,d.env={},d.argv=[],d.version="",d.versions={},d.on=c,d.addListener=c,d.once=c,d.off=c,d.removeListener=c,d.removeAllListeners=c,d.emit=c,d.prependListener=c,d.prependOnceListener=c,d.listeners=function(){return[]},d.binding=function(){throw new Error("process.binding is not supported")},d.cwd=function(){return"/"},d.chdir=function(){throw new Error("process.chdir is not supported")},d.umask=function(){return 0}},{}],13:[function(e,t){(function(e){(function(){let n;t.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"==typeof window?e:window):e=>(n||(n=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0))}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],14:[function(e,t){(function(n,r){(function(){var i=e("safe-buffer").Buffer,s=r.crypto||r.msCrypto;t.exports=s&&s.getRandomValues?function(e,t){if(e>4294967295)throw new RangeError("requested too many random bytes");var r=i.allocUnsafe(e);if(0<e)if(65536<e)for(var o=0;o<e;o+=65536)s.getRandomValues(r.slice(o,o+65536));else s.getRandomValues(r);return"function"==typeof t?n.nextTick(function(){t(null,r)}):r}:function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{_process:12,"safe-buffer":30}],15:[function(e,t){function n(e,t,n){function r(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var s=function(e){function t(t,n,i){return e.call(this,r(t,n,i))||this}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}(t,e),t}(n);s.prototype.name=n.name,s.prototype.code=e,i[e]=s}function r(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map(function(e){return e+""}),2<n?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(e+"")}var i={};n("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError),n("ERR_INVALID_ARG_TYPE",function(e,t,n){var i,s;if("string"==typeof t&&function(e,t,n){return e.substr(!n||0>n?0:+n,t.length)===t}(t,"not ")?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}(e," argument"))s="The ".concat(e," ").concat(i," ").concat(r(t,"type"));else{var o=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(o," ").concat(i," ").concat(r(t,"type"))}return s+=". Received type ".concat(typeof n)},TypeError),n("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),n("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"}),n("ERR_STREAM_PREMATURE_CLOSE","Premature close"),n("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"}),n("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),n("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),n("ERR_STREAM_WRITE_AFTER_END","write after end"),n("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),n("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError),n("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=i},{}],16:[function(e,t){(function(n){(function(){function r(e){return this instanceof r?(a.call(this,e),c.call(this,e),this.allowHalfOpen=!0,void(e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",i))))):new r(e)}function i(){this._writableState.ended||n.nextTick(s,this)}function s(e){e.end()}var o=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var a=e("./_stream_readable"),c=e("./_stream_writable");e("inherits")(r,a);for(var l,h=o(c.prototype),d=0;d<h.length;d++)l=h[d],r.prototype[l]||(r.prototype[l]=c.prototype[l]);Object.defineProperty(r.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(r.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(r.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(r.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0===this._readableState||void 0===this._writableState||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":18,"./_stream_writable":20,_process:12,inherits:10}],17:[function(e,t){function n(e){return this instanceof n?void r.call(this,e):new n(e)}t.exports=n;var r=e("./_stream_transform");e("inherits")(n,r),n.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":19,inherits:10}],18:[function(e,t){(function(n,r){(function(){function i(t,n,r){k=k||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof k),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=M(this,t,"readableHighWaterMark",r),this.buffer=new P,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(!R&&(R=e("string_decoder/").StringDecoder),this.decoder=new R(t.encoding),this.encoding=t.encoding)}function s(t){if(k=k||e("./_stream_duplex"),!(this instanceof s))return new s(t);var n=this instanceof k;this._readableState=new i(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),E.call(this)}function o(e,t,n,r,i){C("readableAddChunk",t);var s,o=e._readableState;if(null===t)o.reading=!1,function(e,t){if(C("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?h(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,d(e)))}}(e,o);else if(i||(s=c(o,t)),s)B(e,s);else if(o.objectMode||t&&0<t.length)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===A.prototype||(t=function(e){return A.from(e)}(t)),r)o.endEmitted?B(e,new F):a(e,o,t,!0);else if(o.ended)B(e,new U);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||0!==t.length?a(e,o,t,!1):u(e,o)):a(e,o,t,!1)}else r||(o.reading=!1,u(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.length)}function a(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&h(e)),u(e,t)}function c(e,t){var n;return function(e){return A.isBuffer(e)||e instanceof T}(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new I("chunk",["string","Buffer","Uint8Array"],t)),n}function l(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e==e?(e>t.highWaterMark&&(t.highWaterMark=function(e){return 1073741824<=e?e=1073741824:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function h(e){var t=e._readableState;C("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(C("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(d,e))}function d(e){var t=e._readableState;C("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,y(e)}function u(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(f,e,t))}function f(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(C("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function g(e){var t=e._readableState;t.readableListening=0<e.listenerCount("readable"),t.resumeScheduled&&!t.paused?t.flowing=!0:0<e.listenerCount("data")&&e.resume()}function p(e){C("readable nexttick read 0"),e.read(0)}function m(e,t){C("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),y(e),t.flowing&&!t.reading&&e.read(0)}function y(e){var t=e._readableState;for(C("flow",t.flowing);t.flowing&&null!==e.read(););}function b(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function w(e){var t=e._readableState;C("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(v,t,e))}function v(e,t){if(C("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function _(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}var k,C;t.exports=s,s.ReadableState=i,e("events").EventEmitter;var S=function(e,t){return e.listeners(t).length},E=e("./internal/streams/stream"),A=e("buffer").Buffer,T=r.Uint8Array||function(){},x=e("util");C=x&&x.debuglog?x.debuglog("stream"):function(){};var R,D,O,P=e("./internal/streams/buffer_list"),L=e("./internal/streams/destroy"),M=e("./internal/streams/state").getHighWaterMark,N=e("../errors").codes,I=N.ERR_INVALID_ARG_TYPE,U=N.ERR_STREAM_PUSH_AFTER_EOF,j=N.ERR_METHOD_NOT_IMPLEMENTED,F=N.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(s,E);var B=L.errorOrDestroy,W=["error","close","destroy","pause","resume"];Object.defineProperty(s.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),s.prototype.destroy=L.destroy,s.prototype._undestroy=L.undestroy,s.prototype._destroy=function(e,t){t(e)},s.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=A.from(e,t),t=""),n=!0),o(this,e,t,!1,n)},s.prototype.unshift=function(e){return o(this,e,null,!0,!1)},s.prototype.isPaused=function(){return!1===this._readableState.flowing},s.prototype.setEncoding=function(t){R||(R=e("string_decoder/").StringDecoder);var n=new R(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,i="";null!==r;)i+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==i&&this._readableState.buffer.push(i),this._readableState.length=i.length,this},s.prototype.read=function(e){C("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0===t.highWaterMark?0<t.length:t.length>=t.highWaterMark)||t.ended))return C("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?w(this):h(this),null;if(0===(e=l(e,t))&&t.ended)return 0===t.length&&w(this),null;var r=t.needReadable;C("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&C("length less than watermark",r=!0),t.ended||t.reading?C("reading or ended",r=!1):r&&(C("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,!t.reading&&(e=l(n,t)));var i=0<e?b(e,t):null;return null===i?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(!t.ended&&(t.needReadable=!0),n!==e&&t.ended&&w(this)),null!==i&&this.emit("data",i),i},s.prototype._read=function(){B(this,new j("_read()"))},s.prototype.pipe=function(e,t){function r(e,t){C("onunpipe"),e===d&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,s())}function i(){C("onend"),e.end()}function s(){C("cleanup"),e.removeListener("close",c),e.removeListener("finish",l),e.removeListener("drain",g),e.removeListener("error",a),e.removeListener("unpipe",r),d.removeListener("end",i),d.removeListener("end",h),d.removeListener("data",o),p=!0,u.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&g()}function o(t){C("ondata");var n=e.write(t);C("dest.write",n),!1===n&&((1===u.pipesCount&&u.pipes===e||1<u.pipesCount&&-1!==_(u.pipes,e))&&!p&&(C("false write response, pause",u.awaitDrain),u.awaitDrain++),d.pause())}function a(t){C("onerror",t),h(),e.removeListener("error",a),0===S(e,"error")&&B(e,t)}function c(){e.removeListener("finish",l),h()}function l(){C("onfinish"),e.removeListener("close",c),h()}function h(){C("unpipe"),d.unpipe(e)}var d=this,u=this._readableState;switch(u.pipesCount){case 0:u.pipes=e;break;case 1:u.pipes=[u.pipes,e];break;default:u.pipes.push(e)}u.pipesCount+=1,C("pipe count=%d opts=%j",u.pipesCount,t);var f=t&&!1===t.end||e===n.stdout||e===n.stderr?h:i;u.endEmitted?n.nextTick(f):d.once("end",f),e.on("unpipe",r);var g=function(e){return function(){var t=e._readableState;C("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&S(e,"data")&&(t.flowing=!0,y(e))}}(d);e.on("drain",g);var p=!1;return d.on("data",o),function(e,t,n){"function"==typeof e.prependListener?e.prependListener(t,n):e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",a),e.once("close",c),e.once("finish",l),e.emit("pipe",d),u.flowing||(C("pipe resume"),d.resume()),e},s.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=_(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},s.prototype.on=function(e,t){var r=E.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=0<this.listenerCount("readable"),!1!==i.flowing&&this.resume()):"readable"==e&&!i.endEmitted&&!i.readableListening&&(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,C("on readable",i.length,i.reading),i.length?h(this):!i.reading&&n.nextTick(p,this)),r},s.prototype.addListener=s.prototype.on,s.prototype.removeListener=function(e,t){var r=E.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(g,this),r},s.prototype.removeAllListeners=function(e){var t=E.prototype.removeAllListeners.apply(this,arguments);return("readable"===e||void 0===e)&&n.nextTick(g,this),t},s.prototype.resume=function(){var e=this._readableState;return e.flowing||(C("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(m,e,t))}(this,e)),e.paused=!1,this},s.prototype.pause=function(){return C("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(C("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},s.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on("end",function(){if(C("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on("data",function(i){C("wrapped data"),n.decoder&&(i=n.decoder.write(i)),n.objectMode&&null==i||!(n.objectMode||i&&i.length)||t.push(i)||(r=!0,e.pause())}),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var s=0;s<W.length;s++)e.on(W[s],this.emit.bind(this,W[s]));return this._read=function(t){C("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(s.prototype[Symbol.asyncIterator]=function(){return void 0===D&&(D=e("./internal/streams/async_iterator")),D(this)}),Object.defineProperty(s.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(s.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(s.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),s._fromList=b,Object.defineProperty(s.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(s.from=function(t,n){return void 0===O&&(O=e("./internal/streams/from")),O(s,t,n)})}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/async_iterator":21,"./internal/streams/buffer_list":22,"./internal/streams/destroy":23,"./internal/streams/from":25,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,events:7,inherits:10,"string_decoder/":31,util:2}],19:[function(e,t){function n(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new c);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function r(e){return this instanceof r?(d.call(this,e),this._transformState={afterTransform:n.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),void this.on("prefinish",i)):new r(e)}function i(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?s(this,null,null):this._flush(function(t,n){s(e,t,n)})}function s(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new h;if(e._transformState.transforming)throw new l;return e.push(null)}t.exports=r;var o=e("../errors").codes,a=o.ERR_METHOD_NOT_IMPLEMENTED,c=o.ERR_MULTIPLE_CALLBACK,l=o.ERR_TRANSFORM_ALREADY_TRANSFORMING,h=o.ERR_TRANSFORM_WITH_LENGTH_0,d=e("./_stream_duplex");e("inherits")(r,d),r.prototype.push=function(e,t){return this._transformState.needTransform=!1,d.prototype.push.call(this,e,t)},r.prototype._transform=function(e,t,n){n(new a("_transform()"))},r.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},r.prototype._read=function(){var e=this._transformState;null===e.writechunk||e.transforming?e.needTransform=!0:(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform))},r.prototype._destroy=function(e,t){d.prototype._destroy.call(this,e,function(e){t(e)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(e,t){(function(n,r){(function(){function i(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}(t,e)}}function s(){}function o(t,n,r){v=v||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof v),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=T(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var s=!1===t.decodeStrings;this.decodeStrings=!s,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){u(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new i(this)}function a(t){var n=this instanceof(v=v||e("./_stream_duplex"));return n||_.call(a,this)?(this._writableState=new o(t,this,n),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),void C.call(this)):new a(t)}function c(e,t){var r=new N;U(e,r),n.nextTick(t,r)}function l(e,t,r,i){var s;return null===r?s=new M:"string"!=typeof r&&!t.objectMode&&(s=new R("chunk",["string","Buffer"],r)),!s||(U(e,s),n.nextTick(i,s),!1)}function h(e,t,n,r,i,s){if(!n){var o=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=S.from(t,n)),t}(t,r,i);r!==o&&(n=!0,i="buffer",r=o)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else d(e,t,!1,a,r,i,s);return c}function d(e,t,n,r,i,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new L("write")):n?e._writev(i,t.onwrite):e._write(i,s,t.onwrite),t.sync=!1}function u(e,t){var r=e._writableState,i=r.sync,s=r.writecb;if("function"!=typeof s)throw new O;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,i,s){--t.pendingcb,r?(n.nextTick(s,i),n.nextTick(b,e,t),e._writableState.errorEmitted=!0,U(e,i)):(s(i),e._writableState.errorEmitted=!0,U(e,i),b(e,t))}(e,r,i,t,s);else{var o=p(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||g(e,r),i?n.nextTick(f,e,r,o,s):f(e,r,o,s)}}function f(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),b(e,t)}function g(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=Array(r),o=t.corkedRequestsFree;o.entry=n;for(var a=0,c=!0;n;)s[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;s.allBuffers=c,d(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new i(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,h=n.encoding,u=n.callback;if(d(e,t,!1,t.objectMode?1:l.length,l,h,u),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function p(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function m(e,t){e._final(function(n){t.pendingcb--,n&&U(e,n),t.prefinished=!0,e.emit("prefinish"),b(e,t)})}function y(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(m,e,t)))}function b(e,t){var n=p(t);if(n&&(y(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function w(e,t,r){t.ending=!0,b(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}var v;t.exports=a,a.WritableState=o;var _,k={deprecate:e("util-deprecate")},C=e("./internal/streams/stream"),S=e("buffer").Buffer,E=r.Uint8Array||function(){},A=e("./internal/streams/destroy"),T=e("./internal/streams/state").getHighWaterMark,x=e("../errors").codes,R=x.ERR_INVALID_ARG_TYPE,D=x.ERR_METHOD_NOT_IMPLEMENTED,O=x.ERR_MULTIPLE_CALLBACK,P=x.ERR_STREAM_CANNOT_PIPE,L=x.ERR_STREAM_DESTROYED,M=x.ERR_STREAM_NULL_VALUES,N=x.ERR_STREAM_WRITE_AFTER_END,I=x.ERR_UNKNOWN_ENCODING,U=A.errorOrDestroy;e("inherits")(a,C),o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:k.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(_=Function.prototype[Symbol.hasInstance],Object.defineProperty(a,Symbol.hasInstance,{value:function(e){return!!_.call(this,e)||!(this!==a)&&e&&e._writableState instanceof o}})):_=function(e){return e instanceof this},a.prototype.pipe=function(){U(this,new P)},a.prototype.write=function(e,t,n){var r=this._writableState,i=!1,o=!r.objectMode&&function(e){return S.isBuffer(e)||e instanceof E}(e);return o&&!S.isBuffer(e)&&(e=function(e){return S.from(e)}(e)),"function"==typeof t&&(n=t,t=null),o?t="buffer":!t&&(t=r.defaultEncoding),"function"!=typeof n&&(n=s),r.ending?c(this,n):(o||l(this,r,e,n))&&(r.pendingcb++,i=h(this,r,o,e,t,n)),i},a.prototype.cork=function(){this._writableState.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&g(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())))throw new I(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(a.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(a.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),a.prototype._write=function(e,t,n){n(new D("_write()"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||w(this,r,n),this},Object.defineProperty(a.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(a.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),a.prototype.destroy=A.destroy,a.prototype._undestroy=A.undestroy,a.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/destroy":23,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,inherits:10,"util-deprecate":32}],21:[function(e,t){(function(n){(function(){function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){return{value:e,done:t}}function s(e){var t=e[l];if(null!==t){var n=e[p].read();null!==n&&(e[f]=null,e[l]=null,e[h]=null,t(i(n,!1)))}}function o(e){n.nextTick(s,e)}var a,c=e("./end-of-stream"),l=Symbol("lastResolve"),h=Symbol("lastReject"),d=Symbol("error"),u=Symbol("ended"),f=Symbol("lastPromise"),g=Symbol("handlePromise"),p=Symbol("stream"),m=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((a={get stream(){return this[p]},next:function(){var e=this,t=this[d];if(null!==t)return Promise.reject(t);if(this[u])return Promise.resolve(i(void 0,!0));if(this[p].destroyed)return new Promise(function(t,r){n.nextTick(function(){e[d]?r(e[d]):t(i(void 0,!0))})});var r,s=this[f];if(s)r=new Promise(function(e,t){return function(n,r){e.then(function(){t[u]?n(i(void 0,!0)):t[g](n,r)},r)}}(s,this));else{var o=this[p].read();if(null!==o)return Promise.resolve(i(o,!1));r=new Promise(this[g])}return this[f]=r,r}},r(a,Symbol.asyncIterator,function(){return this}),r(a,"return",function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){e?n(e):t(i(void 0,!0))})})}),a),m);t.exports=function(e){var t,n=Object.create(y,(r(t={},p,{value:e,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,h,{value:null,writable:!0}),r(t,d,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,g,{value:function(e,t){var r=n[p].read();r?(n[f]=null,n[l]=null,n[h]=null,e(i(r,!1))):(n[l]=e,n[h]=t)},writable:!0}),t));return n[f]=null,c(e,function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[h];return null!==t&&(n[f]=null,n[l]=null,n[h]=null,t(e)),void(n[d]=e)}var r=n[l];null!==r&&(n[f]=null,n[l]=null,n[h]=null,r(i(void 0,!0))),n[u]=!0}),e.on("readable",o.bind(null,n)),n}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":24,_process:12}],22:[function(e,t){function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){for(var n,r=0;r<t.length;r++)(n=t[r]).enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}function s(e,t,n){o.prototype.copy.call(e,t,n)}var o=e("buffer").Buffer,a=e("util").inspect,c=a&&a.custom||"inspect";t.exports=function(){function e(){(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this.head=null,this.tail=null,this.length=0}return function(e,t,n){t&&i(e.prototype,t),n&&i(e,n)}(e,[{key:"push",value:function(e){var t={data:e,next:null};0<this.length?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return o.alloc(0);for(var t=o.allocUnsafe(e>>>0),n=this.head,r=0;n;)s(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,s=e>i.length?i.length:e;if(r+=s===i.length?i:i.slice(0,e),0===(e-=s)){s===i.length?(++n,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=o.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,s),0===(e-=s)){s===i.length?(++r,this.head=n.next?n.next:this.tail=null):(this.head=n,n.data=i.slice(s));break}++r}return this.length-=r,t}},{key:c,value:function(e,t){return a(this,function(e){for(var t,i=1;i<arguments.length;i++)t=null==arguments[i]?{}:arguments[i],i%2?n(Object(t),!0).forEach(function(n){r(e,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):n(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))});return e}({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:3,util:2}],23:[function(e,t){(function(e){(function(){function n(e,t){i(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function i(e,t){e.emit("error",t)}t.exports={destroy:function(t,s){var o=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(s?s(t):t&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,e.nextTick(i,this,t)):e.nextTick(i,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!s&&t?o._writableState?o._writableState.errorEmitted?e.nextTick(r,o):(o._writableState.errorEmitted=!0,e.nextTick(n,o,t)):e.nextTick(n,o,t):s?(e.nextTick(r,o),s(t)):e.nextTick(r,o)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}}}).call(this)}).call(this,e("_process"))},{_process:12}],24:[function(e,t){function n(){}var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;t.exports=function e(t,i,s){if("function"==typeof i)return e(t,null,i);i||(i={}),s=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}(s||n);var o=i.readable||!1!==i.readable&&t.readable,a=i.writable||!1!==i.writable&&t.writable,c=function(){t.writable||h()},l=t._writableState&&t._writableState.finished,h=function(){a=!1,l=!0,o||s.call(t)},d=t._readableState&&t._readableState.endEmitted,u=function(){o=!1,d=!0,a||s.call(t)},f=function(e){s.call(t,e)},g=function(){var e;return o&&!d?(t._readableState&&t._readableState.ended||(e=new r),s.call(t,e)):a&&!l?(t._writableState&&t._writableState.ended||(e=new r),s.call(t,e)):void 0},p=function(){t.req.on("finish",h)};return function(e){return e.setHeader&&"function"==typeof e.abort}(t)?(t.on("complete",h),t.on("abort",g),t.req?p():t.on("request",p)):a&&!t._writableState&&(t.on("end",c),t.on("close",c)),t.on("end",u),t.on("finish",h),!1!==i.error&&t.on("error",f),t.on("close",g),function(){t.removeListener("complete",h),t.removeListener("abort",g),t.removeListener("request",p),t.req&&t.req.removeListener("finish",h),t.removeListener("end",c),t.removeListener("close",c),t.removeListener("finish",h),t.removeListener("end",u),t.removeListener("error",f),t.removeListener("close",g)}}},{"../../../errors":15}],25:[function(e,t){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(e,t){function n(e){if(e)throw e}function r(t,n,r,i){i=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(i);var s=!1;t.on("close",function(){s=!0}),void 0===a&&(a=e("./end-of-stream")),a(t,{readable:n,writable:r},function(e){return e?i(e):(s=!0,void i())});var o=!1;return function(e){if(!s)return o?void 0:(o=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void i(e||new h("pipe")))}}function i(e){e()}function s(e,t){return e.pipe(t)}function o(e){return e.length&&"function"==typeof e[e.length-1]?e.pop():n}var a,c=e("../../../errors").codes,l=c.ERR_MISSING_ARGS,h=c.ERR_STREAM_DESTROYED;t.exports=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var a=o(t);if(Array.isArray(t[0])&&(t=t[0]),2>t.length)throw new l("streams");var c,h=t.map(function(e,n){var s=n<t.length-1;return r(e,s,0<n,function(e){c||(c=e),e&&h.forEach(i),s||(h.forEach(i),a(c))})});return t.reduce(s)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(e,n){var r=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;n.exports={getHighWaterMark:function(e,n,i,s){var o=function(e,t,n){return null==e.highWaterMark?t?e[n]:null:e.highWaterMark}(n,s,i);if(null!=o){if(!isFinite(o)||t(o)!==o||0>o)throw new r(s?i:"highWaterMark",o);return t(o)}return e.objectMode?16:16384}}},{"../../../errors":15}],28:[function(e,t){t.exports=e("events").EventEmitter},{events:7}],29:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"./lib/internal/streams/end-of-stream.js":24,"./lib/internal/streams/pipeline.js":26}],30:[function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return o(e,t,n)}var s=e("buffer"),o=s.Buffer;o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?t.exports=s:(r(s,n),n.Buffer=i),i.prototype=Object.create(o.prototype),r(o,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0===t?r.fill(0):"string"==typeof n?r.fill(t,n):r.fill(t),r},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s.SlowBuffer(e)}},{buffer:3}],31:[function(e,t,n){function r(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(u.isEncoding===f||!f(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=o,this.end=a,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=c,this.end=l,t=3;break;default:return this.write=h,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=u.allocUnsafe(t)}function i(e){return 127>=e?0:6==e>>5?2:14==e>>4?3:30==e>>3?4:2==e>>6?-1:-2}function s(e){var t=this.lastTotal-this.lastNeed,n=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(1<e.lastNeed&&1<t.length){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(2<e.lastNeed&&2<t.length&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0===n?this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length)):n}function o(e,t){if(0==(e.length-t)%2){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(55296<=r&&56319>=r)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function a(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function c(e,t){var n=(e.length-t)%3;return 0==n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function l(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}var u=e("safe-buffer").Buffer,f=u.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};n.StringDecoder=r,r.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},r.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},r.prototype.text=function(e,t){var n=function(e,t,n){var r=t.length-1;if(r<n)return 0;var s=i(t[r]);return 0<=s?(0<s&&(e.lastNeed=s-1),s):--r<n||-2===s?0:0<=(s=i(t[r]))?(0<s&&(e.lastNeed=s-2),s):--r<n||-2===s?0:0<=(s=i(t[r]))?(0<s&&(2===s?s=0:e.lastNeed=s-3),s):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},r.prototype.fillLast=function(e){return this.lastNeed<=e.length?(e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),void(this.lastNeed-=e.length))}},{"safe-buffer":30}],32:[function(e,t){(function(e){(function(){function n(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===(n+"").toLowerCase()}t.exports=function(e,t){if(n("noDeprecation"))return e;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation"),r=!0}return e.apply(this,arguments)}}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],"/":[function(e,t){function n(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}const r=e("debug")("simple-peer"),i=e("get-browser-rtc"),s=e("randombytes"),o=e("readable-stream"),a=e("queue-microtask"),c=e("err-code"),{Buffer:l}=e("buffer"),h=65536;class d extends o.Duplex{constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this._id=s(4).toString("hex").slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||s(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||d.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},d.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:i(),!this._wrtc)throw"undefined"==typeof window?c(/* @__PURE__ */new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(/* @__PURE__ */new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=/* @__PURE__ */new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void this.destroy(c(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(e=>{this.destroy(c(e,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach(e=>{this.addStream(e)}),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(e=>{this._addIceCandidate(e)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(e=>{this.destroy(c(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(c(/* @__PURE__ */new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch(e=>{!t.address||t.address.endsWith(".local")||this.destroy(c(e,"ERR_ADD_ICE_CANDIDATE"))})}send(e){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}addTransceiver(e,t){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(c(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),e.getTracks().forEach(t=>{this.addTrack(t,e)})}}addTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(e)||/* @__PURE__ */new Map;let r=n.get(t);if(r)throw r.removed?c(/* @__PURE__ */new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(/* @__PURE__ */new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation()}replaceTrack(e,t,n){if(this.destroying)return;if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const r=this._senderMap.get(e),i=r?r.get(n):null;if(!i)throw c(/* @__PURE__ */new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,r),null==i.replaceTrack?this.destroy(c(/* @__PURE__ */new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):i.replaceTrack(t)}removeTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const n=this._senderMap.get(e),r=n?n.get(t):null;if(!r)throw c(/* @__PURE__ */new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{r.removed=!0,this._pc.removeTrack(r)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(r):this.destroy(c(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),e.getTracks().forEach(t=>{this.removeTrack(t,e)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,a(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(e){this._destroy(e,()=>{})}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",e&&(e.message||e)),a(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close"),t()}))}_setupData(e){if(!e.channel)return this.destroy(c(/* @__PURE__ */new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=h),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const t=e.error instanceof Error?e.error:/* @__PURE__ */new Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.destroy(c(t,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1},5e3)}_read(){}_write(e,t,n){if(this.destroyed)return n(c(/* @__PURE__ */new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>h?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(!this.destroyed){const e=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?e():this.once("connect",e)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})}};this._pc.setLocalDescription(e).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))}).catch(e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(e=>{this.destroy(c(e,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(e).then(()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))}).catch(e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(e=>{this.destroy(c(e,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(c(/* @__PURE__ */new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),("connected"===e||"completed"===e)&&(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(c(/* @__PURE__ */new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(c(/* @__PURE__ */new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach(t=>{Object.assign(e,t)}),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(n=>{const r=[];n.forEach(e=>{r.push(t(e))}),e(null,r)},t=>e(t)):0<this._pc.getStats.length?this._pc.getStats(n=>{if(this.destroyed)return;const r=[];n.result().forEach(e=>{const n={};e.names().forEach(t=>{n[t]=e.stat(t)}),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,r.push(t(n))}),e(null,r)},t=>e(t)):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats((t,n)=>{if(this.destroyed)return;t&&(n=[]);const r={},i={},s={};let o=!1;n.forEach(e=>{("remotecandidate"===e.type||"remote-candidate"===e.type)&&(r[e.id]=e),("localcandidate"===e.type||"local-candidate"===e.type)&&(i[e.id]=e),("candidatepair"===e.type||"candidate-pair"===e.type)&&(s[e.id]=e)});const a=e=>{o=!0;let t=i[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=+t.port):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=+t.portNumber):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=+t[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=r[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=+n.port):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=+n.portNumber):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=+n[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)}),o||Object.keys(s).length&&!Object.keys(i).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const t=this._cb;this._cb=null,t(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)})};e()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>h)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=l.from(t)),this.push(t)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach(t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some(e=>e.id===t.id)||(this._remoteStreams.push(t),a(()=>{this._debug("on stream"),this.emit("stream",t)}))})}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],r.apply(null,e)}}d.WEBRTC_SUPPORT=!!i(),d.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},d.channelConfig={},t.exports=d},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})})(),1),sh=(e,t)=>{if(!t)return vt(e);const n=crypto.getRandomValues(/* @__PURE__ */new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,e).then(e=>{const t=At();return Ie(t,"AES-GCM"),qt(t,n),qt(t,new Uint8Array(e)),ht(t)})},oh=(e,t)=>{if(!t)return vt(e);const n=Ft(e);"AES-GCM"!==an(n)&&Ye(Xt("Unknown encryption algorithm"));const r=Lt(n),i=Lt(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,i).then(e=>new Uint8Array(e))},ah=lt("y-webrtc"),ch=/* @__PURE__ */new Map,lh=/* @__PURE__ */new Map,hh=e=>{let t=!0;e.webrtcConns.forEach(e=>{e.synced||(t=!1)}),(!t&&e.synced||t&&!e.synced)&&(e.synced=t,e.provider.emit("synced",[{synced:t}]),ah("synced ",dt,e.name,Ht," with all peers"))},dh=(e,t,n)=>{const r=Ft(t),i=At(),s=Dt(r);if(void 0===e)return null;const o=e.awareness,a=e.doc;let c=!1;switch(s){case 0:{rt(i,0);const t=kl(r,i,a,e);1!==t||e.synced||n(),0===t&&(c=!0);break}case 3:rt(i,1),qt(i,pl(o,Array.from(o.getStates().keys()))),c=!0;break;case 1:ml(o,Lt(r),e);break;case 4:{const t=1===xt(r),n=an(r);if(n!==e.peerId&&(e.bcConns.has(n)&&!t||!e.bcConns.has(n)&&t)){const r=[],i=[];t?(e.bcConns.add(n),i.push(n)):(e.bcConns.delete(n),r.push(n)),e.provider.emit("peers",[{added:i,removed:r,webrtcPeers:Array.from(e.webrtcConns.keys()),bcPeers:Array.from(e.bcConns)}]),yh(e)}break}default:return i}return c?i:null},uh=(e,t)=>{ah("send message to ",dt,e.remotePeerId,Ht,Ue," (",e.room.name,")",Re);try{e.peer.send(ht(t))}catch(n){}},fh=class{constructor(e,t,n,r){ah("establishing connection to ",dt,n),this.room=r,this.remotePeerId=n,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new ih.default({initiator:t,...r.provider.peerOpts}),this.peer.on("signal",t=>{void 0===this.glareToken&&(this.glareToken=Date.now()+Math.random()),wh(e,r,{to:n,from:r.peerId,type:"signal",token:this.glareToken,signal:t})}),this.peer.on("connect",()=>{ah("connected to ",dt,n),this.connected=!0;const e=r.provider.doc,t=r.awareness,i=At();rt(i,0),yl(i,e),uh(this,i);const s=t.getStates();if(s.size>0){const e=At();rt(e,1),qt(e,pl(t,Array.from(s.keys()))),uh(this,e)}}),this.peer.on("close",()=>{this.connected=!1,this.closed=!0,r.webrtcConns.has(this.remotePeerId)&&(r.webrtcConns.delete(this.remotePeerId),r.provider.emit("peers",[{removed:[this.remotePeerId],added:[],webrtcPeers:Array.from(r.webrtcConns.keys()),bcPeers:Array.from(r.bcConns)}])),hh(r),this.peer.destroy(),ah("closed connection to ",dt,n),mh(r)}),this.peer.on("error",e=>{ah("Error in connection to ",dt,n,": ",e),mh(r)}),this.peer.on("data",e=>{const t=((e,t)=>{const n=e.room;return ah("received message from ",dt,e.remotePeerId,Ue," (",n.name,")",Ht,Re),dh(n,t,()=>{e.synced=!0,ah("synced ",dt,n.name,Ht," with ",dt,e.remotePeerId),hh(n)})})(this,e);null!==t&&uh(this,t)})}destroy(){this.peer.destroy()}},gh=(e,t)=>sh(t,e.key).then(t=>e.mux(()=>((e,t,n=null)=>{const r=rh(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))})(e.name,t))),ph=(e,t)=>{e.bcconnected&&gh(e,t),((e,t)=>{ah("broadcast message in ",dt,e.name,Ht),e.webrtcConns.forEach(e=>{try{e.peer.send(t)}catch(n){}})})(e,t)},mh=e=>{ch.forEach(t=>{t.connected&&(t.send({type:"subscribe",topics:[e.name]}),e.webrtcConns.size<e.provider.maxConns&&wh(t,e,{type:"announce",from:e.peerId}))})},yh=e=>{if(e.provider.filterBcConns){const t=At();rt(t,4),dn(t,1),Ie(t,e.peerId),gh(e,ht(t))}},bh=class{constructor(e,t,n,r){this.peerId=xe(),this.doc=e,this.awareness=t.awareness,this.provider=t,this.synced=!1,this.name=n,this.key=r,this.webrtcConns=/* @__PURE__ */new Map,this.bcConns=/* @__PURE__ */new Set,this.mux=Tt(),this.bcconnected=!1,this._bcSubscriber=e=>oh(new Uint8Array(e),r).then(e=>this.mux(()=>{const t=dh(this,e,()=>{});t&&gh(this,ht(t))})),this._docUpdateHandler=(e,t)=>{const n=At();rt(n,0),vl(n,e),ph(this,ht(n))},this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{const i=e.concat(t).concat(n),s=At();rt(s,1),qt(s,pl(this.awareness,i)),ph(this,ht(s))},this._beforeUnloadHandler=()=>{gl(this.awareness,[e.clientID],"window unload"),lh.forEach(e=>{e.disconnect()})},"undefined"!=typeof window?window.addEventListener("beforeunload",this._beforeUnloadHandler):"undefined"!=typeof process&&process.on("exit",this._beforeUnloadHandler)}connect(){this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),mh(this);const e=this.name;var t,n;t=e,n=this._bcSubscriber,rh(t).subs.add(n),this.bcconnected=!0,yh(this);const r=At();rt(r,0),yl(r,this.doc),gh(this,ht(r));const i=At();rt(i,0),bl(i,this.doc),gh(this,ht(i));const s=At();rt(s,3),gh(this,ht(s));const o=At();rt(o,1),qt(o,pl(this.awareness,[this.doc.clientID])),gh(this,ht(o))}disconnect(){ch.forEach(e=>{e.connected&&e.send({type:"unsubscribe",topics:[this.name]})}),gl(this.awareness,[this.doc.clientID],"disconnect");const e=At();rt(e,4),dn(e,0),Ie(e,this.peerId),gh(this,ht(e)),((e,t)=>{const n=rh(e),r=n.subs.delete(t);r&&0===n.subs.size&&(n.bc.close(),th.delete(e))})(this.name,this._bcSubscriber),this.bcconnected=!1,this.doc.off("update",this._docUpdateHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.webrtcConns.forEach(e=>e.destroy())}destroy(){this.disconnect(),"undefined"!=typeof window?window.removeEventListener("beforeunload",this._beforeUnloadHandler):"undefined"!=typeof process&&process.off("exit",this._beforeUnloadHandler)}},wh=(e,t,n)=>{t.key?((e,t)=>{const n=At();return Me(n,e),sh(ht(n),t)})(n,t.key).then(n=>{e.send({type:"publish",topic:t.name,data:it(n)})}):e.send({type:"publish",topic:t.name,data:n})},vh=class extends eh{constructor(e){super(e),this.providers=/* @__PURE__ */new Set,this.on("connect",()=>{ah(`connected (${e})`);const t=Array.from(lh.keys());this.send({type:"subscribe",topics:t}),lh.forEach(e=>wh(this,e,{type:"announce",from:e.peerId}))}),this.on("message",e=>{if("publish"===e.type){const r=e.topic,i=lh.get(r);if(null==i||"string"!=typeof r)return;const s=e=>{const t=i.webrtcConns,n=i.peerId;if(null==e||e.from===n||void 0!==e.to&&e.to!==n||i.bcConns.has(e.from))return;const r=t.has(e.from)?()=>{}:()=>i.provider.emit("peers",[{removed:[],added:[e.from],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}]);switch(e.type){case"announce":t.size<i.provider.maxConns&&(en(t,e.from,()=>new fh(this,!0,e.from,i)),r());break;case"signal":if("offer"===e.signal.type){const n=t.get(e.from);if(n){const t=e.token,r=n.glareToken;if(r&&r>t)return void ah("offer rejected: ",e.from);n.glareToken=void 0}}if("answer"===e.signal.type){ah("offer answered by: ",e.from);t.get(e.from).glareToken=void 0}e.to===n&&(en(t,e.from,()=>new fh(this,!1,e.from,i)).peer.signal(e.signal),r())}};i.key?"string"==typeof e.data&&(t=et(e.data),n=i.key,oh(t,n).then(e=>nn(Ft(new Uint8Array(e))))).then(s):s(e.data)}var t,n}),this.on("disconnect",()=>ah(`disconnect (${e})`))}},_h=e=>{e.emit("status",[{connected:e.connected}])},kh=class extends Ge{constructor(e,t,{signaling:n=["wss://y-webrtc-eu.fly.dev"],password:r=null,awareness:i=new fl(t),maxConns:s=20+Ze(15*_t()),filterBcConns:o=!0,peerOpts:a={}}={}){super(),this.roomName=e,this.doc=t,this.filterBcConns=o,this.awareness=i,this.shouldConnect=!1,this.signalingUrls=n,this.signalingConns=[],this.maxConns=s,this.peerOpts=a,this.key=r?((e,t)=>{const n=De(e).buffer,r=De(t).buffer;return crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveKey"]).then(e=>crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:1e5,hash:"SHA-256"},e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]))})(r,e):vt(null),this.room=null,this.key.then(n=>{this.room=((e,t,n,r)=>{if(lh.has(n))throw Xt(`A Yjs Doc connected to room "${n}" already exists!`);const i=new bh(e,t,n,r);return lh.set(n,i),i})(t,this,e,n),this.shouldConnect?this.room.connect():this.room.disconnect(),_h(this)}),this.connect(),this.destroy=this.destroy.bind(this),t.on("destroy",this.destroy)}get connected(){return null!==this.room&&this.shouldConnect}connect(){this.shouldConnect=!0,this.signalingUrls.forEach(e=>{const t=en(ch,e,()=>new vh(e));this.signalingConns.push(t),t.providers.add(this)}),this.room&&(this.room.connect(),_h(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),0===e.providers.size&&(e.destroy(),ch.delete(e.url))}),this.room&&(this.room.disconnect(),_h(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),lh.delete(this.roomName)}),super.destroy()}};async function Ch(e,t){const n=await async function(e,t){const n=`${e}-${JSON.stringify(t)}`,r=(new TextEncoder).encode(n),i=globalThis.crypto?.subtle??globalThis.window?.crypto?.subtle;if(!i)throw new Error("Web Crypto API subtle.digest is unavailable");return function(e){const t=new DataView(e).getInt32(0,!1);return Math.abs(t)%2147483647+1}(await i.digest("SHA-256",r))}(e,t),r=new ms({guid:e});r.clientID=n;const i=Lc(t);r.get("content",Pa).applyDelta(i);const s=Ds(r);return r.destroy(),s}var Sh={hocuspocus:class{_isConnected=!1;_isSynced=!1;onConnect;onDisconnect;onError;onSyncChange;destroy=()=>{this._isConnected&&this.provider.disconnect()};disconnect=()=>{this._isConnected&&(this.provider.disconnect(),this._isConnected=!1,this._isSynced&&(this._isSynced=!1,this?.onSyncChange?.(!1)))};provider;type="hocuspocus";constructor({awareness:e,doc:t,options:n,wsOptions:r,onConnect:i,onDisconnect:s,onError:o,onSyncChange:a}){this.onConnect=i,this.onDisconnect=s,this.onSyncChange=a,this.onError=o;const c={...n,...t&&{document:t},...e&&{awareness:e},...r&&(()=>{try{return{websocketProvider:new Rl(r)}}catch(e){return this.onError?.(e instanceof Error?e:new Error(String(e))),{}}})(),onAwarenessChange:n.onAwarenessChange||(()=>{}),onConnect:()=>{this._isConnected=!0,this.onConnect?.(),n.onConnect?.()},onDisconnect:e=>{this._isConnected=!1,this._isSynced&&(this._isSynced=!1,this.onSyncChange?.(!1)),this.onDisconnect?.(),n.onDisconnect?.(e)},onSynced:e=>{const t=this._isSynced;this._isSynced=!0,t||this.onSyncChange?.(!0),n.onSynced?.(e)}};try{this.provider=new jl(c)}catch(l){this.provider=new jl({...c,connect:!1}),this.onError?.(l instanceof Error?l:new Error(String(l)))}}connect(){try{this.provider.connect()}catch(e){this._isConnected=!1}}get awareness(){return this.provider.awareness}get document(){return this.provider.document}get isConnected(){return this._isConnected}get isSynced(){return this._isSynced}},indexeddb:class{_isConnected=!1;_isDestroyed=!1;_isSynced=!1;onConnect;onDisconnect;onError;onSyncChange;providerOptions;_provider=null;awareness;document;isLocalPersistence=!0;type="indexeddb";constructor({awareness:e,doc:t,options:n,onConnect:r,onDisconnect:i,onError:s,onSyncChange:o}){this.document=t??new ms,this.awareness=e??new fl(this.document),this.providerOptions=n,this.onConnect=r,this.onDisconnect=i,this.onError=s,this.onSyncChange=o}connect=()=>{if(!this._isDestroyed){if(!this._provider)try{const e=new Gl(this.providerOptions.docName,this.document);this._provider=e,e._db.then(()=>{this._provider!==e||this._isDestroyed||this.setConnected(!0)}).catch(t=>{this._provider!==e||this._isDestroyed||(this._provider=null,this.destroyProvider(e,!1),this.handleError(t),this.setSynced(!1),this.setConnected(!1))}),e.whenSynced.then(()=>{this._provider===e&&this._isConnected&&!this._isDestroyed&&this.setSynced(!0)}).catch(e=>{this.handleError(e)})}catch(e){return this.handleError(e),this.setConnected(!1),void this.setSynced(!1)}this._provider.synced&&(this.setConnected(!0),this.setSynced(!0))}};destroy=()=>{this._isDestroyed||(this._isDestroyed=!0,this.disconnect())};disconnect=()=>{const e=this._provider;(e||this._isConnected||this._isSynced)&&(this._provider=null,this.setSynced(!1),this.setConnected(!1),e&&this.destroyProvider(e))};get isConnected(){return this._isConnected}get isConnectionPending(){return!!this._provider&&!this._isConnected&&!this._isDestroyed}get isSyncPending(){return!!this._provider&&!this._isSynced&&!this._isDestroyed}get isSynced(){return this._isSynced}get provider(){return this._provider}destroyProvider(e,t=!0){try{e.destroy().catch(e=>{t&&this.handleError(e)})}catch(n){t&&this.handleError(n)}}handleError(e){this.onError?.(e instanceof Error?e:new Error(String(e)))}setConnected(e){this._isConnected!==e&&(this._isConnected=e,e?this.onConnect?.():this.onDisconnect?.())}setSynced(e){this._isSynced!==e&&(this._isSynced=e,this.onSyncChange?.(e))}},webrtc:class{_isConnected=!1;_isSynced=!1;doc;onSyncChange;provider=null;connect=()=>{if(this.provider)try{this.provider.connect()}catch(e){}};destroy=()=>{if(this.provider)try{this.provider.destroy()}catch(e){}};disconnect=()=>{if(this.provider)try{this.provider.disconnect();const e=this._isSynced;this._isConnected=!1,this._isSynced=!1,e&&this.onSyncChange?.(!1)}catch(e){}};type="webrtc";constructor({awareness:e,doc:t,options:n,onConnect:r,onDisconnect:i,onError:s,onSyncChange:o}){this.onSyncChange=o,this.doc=t||new ms;try{this.provider=new kh(n.roomName,this.doc,{awareness:e,filterBcConns:n.filterBcConns,maxConns:n.maxConns,password:n.password,peerOpts:n.peerOpts,signaling:n.signaling}),this.provider.on("status",e=>{const t=this._isConnected;this._isConnected=e.connected,e.connected?(t||r?.(),this._isSynced||(this._isSynced=!0,o?.(!0))):t&&(i?.(),this._isSynced&&(this._isSynced=!1,o?.(!1)))})}catch(a){s?.(a instanceof Error?a:new Error(String(a)))}}get awareness(){return this.provider.awareness}get document(){return this.doc}get isConnected(){return this._isConnected}get isSynced(){return this._isSynced}}},Eh=({type:e,...t})=>{const n=(e=>Sh[e])(e);if(!n)throw new Error(`Provider type "${e}" not found in registry`);return new n(t)},Ah=(e,t,n)=>function(e,t,{cursorStateField:n="selection",cursorDataField:r="data",autoSend:i=!0,data:s}={}){const o=e;o.awareness=t,o.cursorDataField=r,o.selectionStateField=n,o.sendCursorData=e=>{o.awareness.setLocalStateField(o.cursorDataField,e)},o.sendCursorPosition=e=>{const t=o.awareness.getLocalState(),r=null==t?void 0:t[n];if(!e)return void(r&&o.awareness.setLocalStateField(o.selectionStateField,null));const{anchor:i,focus:s}=Xc(o.sharedRoot,o,e);r&&Zs(i,r)&&Zs(s,r)||o.awareness.setLocalStateField(o.selectionStateField,{anchor:i,focus:s})};const a=e=>{const t=dl.get(o);if(!t)return;const n=o.awareness.clientID,r={added:e.added.filter(e=>e!==n),removed:e.removed.filter(e=>e!==n),updated:e.updated.filter(e=>e!==n)};(r.added.length>0||r.removed.length>0||r.updated.length>0)&&t.forEach(e=>e(r))},{connect:c,disconnect:l}=o;return o.connect=()=>{if(c(),o.awareness.on("change",a),a({removed:[],added:Array.from(o.awareness.getStates().keys()),updated:[]}),i){s&&ul.sendCursorData(o,s);const{onChange:e}=o;o.onChange=()=>{e(),ol.connected(o)&&ul.sendCursorPosition(o)}}},o.disconnect=()=>{o.awareness.off("change",a),a({removed:Array.from(o.awareness.getStates().keys()),added:[],updated:[]}),l()},o}(e,t,n),Th=e=>"object"==typeof e&&null!==e&&"type"in e&&"options"in e,xh=T({key:I.yjs,extendEditor:({editor:e,getOptions:t})=>{let n=e;const{awareness:r,cursors:i,localOrigin:s,positionStorageOrigin:o,sharedType:a,ydoc:c}=t();if(n=((e,t,n)=>al(e,t,n))(n,a??c.get("content",Pa),{autoConnect:!1,localOrigin:s,positionStorageOrigin:o}),i)if(r){let e=!0;!1===i.autoSend&&(e=!1),n=Ah(n,r,{...i,autoSend:e})}else n.api.debug.error("Yjs plugin: Internal shared awareness (awareness) is missing but cursors are enabled.");return((e,t)=>hl(e,t))(n)},options:{_isConnected:!1,_isSynced:!1,userId:null,_providers:[],awareness:null,cursors:{},localOrigin:null,positionStorageOrigin:null,providers:[],sharedType:null,ydoc:null,onConnect:()=>{},onDisconnect:()=>{},onError:()=>{},onSyncChange:()=>{}}}).extend(({getOptions:e})=>{const{localOrigin:t,positionStorageOrigin:n,...r}=e();let{awareness:i,ydoc:s}=r;return s||(s=new ms),i||(i=new fl(s)),{options:{awareness:i,localOrigin:t??void 0,positionStorageOrigin:n??void 0,ydoc:s}}}).extendApi(e=>({connect:t=>{const{getOptions:n}=e,{_providers:r}=n(),i=t?Array.isArray(t)?t:[t]:null;r.forEach(e=>{if(!i||i.includes(e.type))try{e.connect()}catch(t){n().onError?.({error:t instanceof Error?t:new Error(String(t)),type:e.type})}})},destroy:()=>{const{editor:t,getOptions:n}=e,{_providers:r}=n();for(const e of[...r].reverse())try{(e.isConnected||e.isConnectionPending)&&e.destroy()}catch(i){}try{ol.disconnect(t)}catch{}},disconnect:t=>{const{editor:n,getOptions:r}=e,{_providers:i}=r(),s=t?Array.isArray(t)?t:[t]:null;for(const e of[...i].reverse())try{!e.isConnected&&!e.isConnectionPending||null!==s&&!s.includes(e.type)||e.disconnect()}catch(o){}},init:async({id:t,autoConnect:n=!0,autoSelect:r,selection:i,value:s,onReady:o}={})=>{const{editor:a,getOptions:c,setOption:l}=e,{awareness:h,providers:d=[],sharedType:u,ydoc:f}=c(),g=()=>{return(e=u??f.get("content",Pa)).length>0||null!=e._start;var e};if(0===d.length)throw new Error("No providers specified. Please provide provider configurations or instances in the `providers` array.");const p=[];let m=null;const y=new Promise(e=>{m=e});for(const e of d)if(Th(e)){const{options:t,type:n}=e;let r=null;if(!t)continue;try{const e=Eh({awareness:h,doc:f,options:t,type:n,onConnect:()=>{c().onConnect?.({type:n}),l("_isConnected",!0)},onDisconnect:()=>{c().onDisconnect?.({type:n});const{_providers:e}=c();e.some(e=>e.isConnected)||l("_isConnected",!1)},onError:e=>{c().onError?.({error:e,type:n})},onSyncChange:e=>{c().onSyncChange?.({isSynced:e,type:n}),l("_isSynced",e);const t=p.some(e=>!e.isLocalPersistence),i=!r?.isLocalPersistence||!t||g();e&&m&&i&&(m(),m=null)}});r=e,p.push(e)}catch{}}else p.push(e);if(l("_providers",p),n&&p.length>0){p.forEach(e=>{try{e.connect()}catch(t){c().onError?.({error:t instanceof Error?t:new Error(String(t)),type:e.type})}});const e=5e3;await Promise.race([y,new Promise(t=>{setTimeout(()=>{m=null,t()},e)})])}if(!g()&&!p.some(e=>e.isLocalPersistence&&(e.isConnectionPending||e.isSyncPending))&&null!==s){let e=s;if("string"==typeof s?e=a.api.html.deserialize({element:s}):"function"==typeof s?e=await s(a):s&&(e=s),e&&0!==e?.length||(e=a.api.create.value()),u){const t=Lc(e);f.transact(()=>{u.applyDelta(t)})}else{const n=await Ch(t??a.id,e);f.transact(()=>{xs(f,n)})}}ol.connect(a),a.tf.init({autoSelect:r,selection:i,shouldNormalizeEditor:!1,value:null}),a.api.onChange(),o?.({editor:a,isAsync:!0,value:a.children})}})),Rh=y(xh),Dh=Object.defineProperty,Oh=Object.defineProperties,Ph=Object.getOwnPropertyDescriptors,Lh=Object.getOwnPropertySymbols,Mh=Object.prototype.hasOwnProperty,Nh=Object.prototype.propertyIsEnumerable,Ih=(e,t,n)=>t in e?Dh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Uh=(e,t)=>{for(var n in t||(t={}))Mh.call(t,n)&&Ih(e,n,t[n]);if(Lh)for(var n of Lh(t))Nh.call(t,n)&&Ih(e,n,t[n]);return e},jh=(e,t)=>Oh(e,Ph(t));function Fh(e){return"[object Object]"===Object.prototype.toString.call(e)}function Bh(e){if(!Fh(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==Fh(n)&&!1!==n.hasOwnProperty("isPrototypeOf")}function Wh(e,t){for(const n in e){const r=e[n],i=t[n];if(Bh(r)&&Bh(i)){if(!Wh(r,i))return!1}else if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1}else if(r!==i)return!1}for(const n in t)if(void 0===e[n]&&void 0!==t[n])return!1;return!0}function Hh(e){return function(e){var t,n;const r=[];for(const i of e){if("string"==typeof i.insert&&0===i.insert.length)continue;const e=r[r.length-1];e&&"string"==typeof e.insert&&"string"==typeof i.insert&&(e.attributes===i.attributes||!e.attributes==!i.attributes&&Wh(null!=(t=e.attributes)?t:{},null!=(n=i.attributes)?n:{}))?e.insert+=i.insert:r.push(i)}return r}(e.toDelta())}function qh({insert:e}){return"string"==typeof e?e.length:1}function Vh(e){return e.reduce((e,t)=>e+qh(t),0)}function zh(e,t,n){if(n<1)return[];let r=0;const i=[],s=t+n;for(let o=0;o<e.length&&!(r>=s);o++){const n=e[o],a=qh(n);if(r+a<=t){r+=a;continue}if("string"!=typeof n.insert){r+=a,i.push(n);continue}const c=Math.max(0,t-r),l=Math.min(a,a-(r+a-s));i.push(jh(Uh({},n),{insert:n.insert.slice(c,l)})),r+=a}return i}function $h(e){return function(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}(e,J.isText(e)?"text":"children")}function Yh(e){var t=e,{children:n}=t,r=((e,t)=>{var n={};for(var r in e)Mh.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&Lh)for(var r of Lh(e))t.indexOf(r)<0&&Nh.call(e,r)&&(n[r]=e[r]);return n})(t,["children"]);const i=new on;return Object.entries(r).forEach(([e,t])=>{i.setAttribute(e,t)}),i.applyDelta(n.map(e=>J.isText(e)?{insert:e.text,attributes:$h(e)}:{insert:Yh(e)}),{sanitize:!1}),i}function Jh(e){return e?J.isText(e)?e.text.length:1:0}function Qh(e,t,n){var r;if(0===n.length)throw new Error("Path has to a have a length >= 1");if(J.isText(t))throw new Error("Cannot descent into slate text");const[i,...s]=n,o=function(e,t){return e.children.slice(0,t).reduce((e,t)=>e+Jh(t),0)}(t,i),a=t.children[i],c=Hh(e),l=Jh(a),h=zh(c,o,l);if(h.length>1)throw new Error("Path doesn't match yText, yTarget spans multiple nodes");const d=null==(r=h[0])?void 0:r.insert;if(s.length>0){if(!(d instanceof on))throw new Error("Path doesn't match yText, cannot descent into non-yText");return Qh(d,a,s)}return{yParent:e,textRange:{start:o,end:o+l},yTarget:d instanceof on?d:void 0,slateParent:t,slateTarget:a,targetDelta:h}}function Kh(e,t,n={}){const{assoc:r=0,insert:i=!1}=n;let s=0,o=0;for(let c=0;c<e.children.length;c++){const n=e.children[c],i=J.isText(n)?n.text.length:1;i>0&&(o=c);const a=s+i;if(i>0&&(r>=0?a>t:a>=t))return[c,t-s];s+=i}if(t>s+(i?1:0))throw new Error("yOffset out of bounds");if(i)return[e.children.length,0];const a=e.children[o];return[o,J.isText(a)?a.text.length:1]}function Gh(e){return e.map(e=>"string"==typeof e.insert?e:jh(Uh({},e),{insert:Xh(e.insert)}))}function Xh(e){const t=new on,n=e.getAttributes();return Object.entries(n).forEach(([e,n])=>{t.setAttribute(e,n)}),t.applyDelta(Gh(Hh(e)),{sanitize:!1}),t}function Zh(e){if(!e.doc)throw new Error("shared type isn't attached to a document")}var ed="__slateYjsStoredPosition_";function td(e,t,{type:n,index:r,assoc:i}){if(!(n instanceof on))throw new Error("Absolute position points to a non-XMLText");const s=function(e,t,n){const r=[n];for(;r[0]!==e;){const{parent:e}=r[0];if(!e)throw new Error("yText isn't a descendant of root element");if(!(e instanceof on))throw new Error("Unexpected y parent type");r.unshift(e)}if(r.length<2)return[];let i=t;return r.reduce((e,t,n)=>{const s=r[n+1];if(!s)return e;let o=0;const a=Hh(t);for(const r of a){if(r.insert===s)break;o+="string"==typeof r.insert?r.insert.length:1}if(J.isText(i))throw new Error("Cannot descent into slate text");const[c]=Kh(i,o);return i=i.children[c],e.concat(c)},[])}(e,t,n),o=ce.get(t,s);if(J.isText(o))throw new Error("Absolute position doesn't match slateRoot, cannot descent into text");const[a,c]=Kh(o,r,{assoc:i}),l=o.children[a];return J.isText(l)?{path:[...s,a],offset:c}:null}function nd(e,t,n){if(!e.doc)throw new Error("sharedRoot isn't attach to a yDoc");const r=Pt(n,e.doc);return r&&td(e,t,r)}function rd(e,t,n){e.setAttribute(ed+t,Mt(n))}function id(e,t,n){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.type===t&&(!n||(e.assoc>=0?e.index>=n.start&&e.index<n.end:e.index>n.start&&e.index>=n.end))))}function sd(e,t,n=""){const r={[n]:id(e,t)};return Hh(t).forEach(({insert:t},i)=>{t instanceof on&&Object.assign(r,sd(e,t,n?`${n}.${i}`:i.toString()))}),r}function od(e,t,n,r=0){const i=function(e){return Zh(e),Object.fromEntries(Object.entries(e.getAttributes()).filter(([e])=>e.startsWith(ed)).map(([t,n])=>[t.slice(25),Pt(It(n),e.doc)]).filter(([,e])=>e))}(e),s={"":id(i,t,{start:r,end:r+Vh(n)})};return n.forEach(({insert:e},t)=>{e instanceof on&&Object.assign(s,sd(i,e,t.toString()))}),s}function ad(e,t,n,r,i=0,s=0,o=""){const a=n[o];a&&Object.entries(a).forEach(([n,r])=>{rd(e,n,$t(t,r.index-s+i,r.assoc))}),r.forEach(({insert:t},r)=>{t instanceof on&&ad(e,t,n,Hh(t),0,0,o?`${o}.${r}`:r.toString())})}var cd={insert_node:function(e,t,n){const{yParent:r,textRange:i}=Qh(e,t,n.path);if(J.isText(n.node))return r.insert(i.start,n.node.text,$h(n.node));r.insertEmbed(i.start,Yh(n.node))},remove_node:function(e,t,n){const{yParent:r,textRange:i}=Qh(e,t,n.path);r.delete(i.start,i.end-i.start)},set_node:function(e,t,n){const{yTarget:r,textRange:i,yParent:s}=Qh(e,t,n.path);if(r)return Object.entries(n.newProperties).forEach(([e,t])=>{if(null===t)return r.removeAttribute(e);r.setAttribute(e,t)}),Object.entries(n.properties).forEach(([e])=>{n.newProperties.hasOwnProperty(e)||r.removeAttribute(e)});const o=Uh(Uh({},Object.fromEntries(Object.keys(n.properties).map(e=>[e,null]))),n.newProperties);s.format(i.start,i.end-i.start,o)},merge_node:function(e,t,n){const r=Qh(e,t,n.path),i=Qh(r.yParent,r.slateParent,ee.previous(n.path.slice(-1)));if(!r.yTarget!=!i.yTarget)throw new Error("Cannot merge y text with y element");if(!i.yTarget||!r.yTarget){const{yParent:e,textRange:i,slateTarget:s}=r;if(!s)throw new Error("Expected Slate target node for merge op.");const o=ce.get(t,ee.previous(n.path));if(!J.isText(o))throw new Error("Path points to Y.Text but not a Slate text node.");const a=$h(s),c=$h(o),l=Object.keys(a).reduce((e,t)=>t in c?e:jh(Uh({},e),{[t]:null}),{});return e.format(i.start,i.end-i.start,Uh(Uh({},l),c))}const s=i.yTarget.length,o=Hh(r.yTarget),a=Gh(o),c=od(e,r.yTarget,o,s),l=[{retain:s},...a];i.yTarget.applyDelta(l,{sanitize:!1}),r.yParent.delete(r.textRange.start,r.textRange.end-r.textRange.start),ad(e,i.yTarget,c,a,s)},move_node:function(e,t,n){const r=ee.parent(n.newPath),i=n.newPath[n.newPath.length-1],s=ce.get(t,r);if(J.isText(s))throw new Error("Cannot move slate node into text element");const o=[...r,Math.min(i,s.children.length)],a=Qh(e,t,n.path),c=Qh(e,t,o),l=Gh(a.targetDelta),h=od(e,a.yParent,a.targetDelta);a.yParent.delete(a.textRange.start,a.textRange.end-a.textRange.start);const d=Vh(Hh(c.yParent)),u=Math.min(c.textRange.start,d),f=[{retain:u},...l];c.yParent.applyDelta(f,{sanitize:!1}),ad(e,c.yParent,h,l,u,a.textRange.start)},split_node:function(e,t,n){const r=Qh(e,t,n.path);if(!r.slateTarget)throw new Error("Y target without corresponding slate node");if(!r.yTarget){if(!J.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const e={};return r.targetDelta.forEach(t=>{t.attributes&&Object.keys(t.attributes).forEach(t=>{e[t]=null})}),r.yParent.format(r.textRange.start,r.textRange.end-r.textRange.start,Uh(Uh({},e),n.properties))}if(J.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const i=Qh(r.yTarget,r.slateTarget,[n.position]),s=r.slateTarget.children.slice(0,n.position).reduce((e,t)=>e+Jh(t),0),o=r.slateTarget.children.reduce((e,t)=>e+Jh(t),0),a=zh(Hh(r.yTarget),s,o-s),c=Gh(a),l=od(e,r.yTarget,a,s),h=new on;h.applyDelta(c,{sanitize:!1}),Object.entries(n.properties).forEach(([e,t])=>{h.setAttribute(e,t)}),r.yTarget.delete(i.textRange.start,r.yTarget.length-i.textRange.start),r.yParent.insertEmbed(r.textRange.end,h),ad(e,h,l,c,0,s)}};jh(Uh(Uh({},{insert_text:function(e,t,n){const{yParent:r,textRange:i}=Qh(e,t,n.path),s=ce.get(t,n.path);if(!J.isText(s))throw new Error("Cannot insert text into non-text node");r.insert(i.start+n.offset,n.text,$h(s))},remove_text:function(e,t,n){const{yParent:r,textRange:i}=Qh(e,t,n.path);r.delete(i.start+n.offset,n.text.length)}}),cd),{set_selection:()=>{}});var ld=/* @__PURE__ */new WeakMap,hd=/* @__PURE__ */new WeakMap,dd=/* @__PURE__ */new WeakSet,ud={isYjsEditor:e=>q.isEditor(e)&&e.sharedRoot instanceof on&&"localOrigin"in e&&"positionStorageOrigin"in e&&"function"==typeof e.applyRemoteEvents&&"function"==typeof e.storeLocalChange&&"function"==typeof e.flushLocalChanges&&"function"==typeof e.isLocalOrigin&&"function"==typeof e.connect&&"function"==typeof e.disconnect,localChanges(e){var t;return null!=(t=hd.get(e))?t:[]},applyRemoteEvents(e,t,n){e.applyRemoteEvents(t,n)},storeLocalChange(e,t){e.storeLocalChange(t)},flushLocalChanges(e){e.flushLocalChanges()},connected:e=>dd.has(e),connect(e){e.connect()},disconnect(e){e.disconnect()},isLocal:e=>e.isLocalOrigin(ud.origin(e)),origin(e){const t=ld.get(e);return void 0!==t?t:e.localOrigin},withOrigin(e,t,n){const r=ud.origin(e);ld.set(e,t),n(),ld.set(e,r)},storePosition(e,t,n){const{sharedRoot:r,positionStorageOrigin:i}=e;Zh(r);const s=function(e,t,n){const{yTarget:r,yParent:i,textRange:s}=Qh(e,t,n.path);if(r)throw new Error("Slate point points to a non-text element inside sharedRoot");const o=s.start+n.offset;return $t(i,o,o===s.end?-1:0)}(r,e,n);r.doc.transact(()=>{rd(r,t,s)},i)},removeStoredPosition(e,t){const{sharedRoot:n,positionStorageOrigin:r}=e;Zh(n),n.doc.transact(()=>{!function(e,t){e.removeAttribute(ed+t)}(n,t)},r)},position(e,t){const n=function(e,t){const n=e.getAttribute(ed+t);return n?It(n):null}(e.sharedRoot,t);if(n)return nd(e.sharedRoot,e,n)},storedPositionsRelative(e){return t=e.sharedRoot,Object.fromEntries(Object.entries(t.getAttributes()).filter(([e])=>e.startsWith(ed)).map(([e,t])=>[e.slice(25),Gt(t)]));var t}},fd=/* @__PURE__ */new WeakMap,gd={isCursorEditor:e=>ud.isYjsEditor(e)&&e.awareness&&"string"==typeof e.cursorDataField&&"string"==typeof e.selectionStateField&&"function"==typeof e.sendCursorPosition&&"function"==typeof e.sendCursorData,sendCursorPosition(e,t=e.selection){e.sendCursorPosition(t)},sendCursorData(e,t){e.sendCursorData(t)},on(e,t,n){var r;if("change"!==t)return;const i=null!=(r=fd.get(e))?r:/* @__PURE__ */new Set;i.add(n),fd.set(e,i)},off(e,t,n){if("change"!==t)return;const r=fd.get(e);r&&r.delete(n)},cursorState(e,t){var n;if(t===e.awareness.clientID||!ud.connected(e))return null;const r=e.awareness.getStates().get(t);return r?{relativeSelection:null!=(n=r[e.selectionStateField])?n:null,data:r[e.cursorDataField],clientId:t}:null},cursorStates:e=>ud.connected(e)?Object.fromEntries(Array.from(e.awareness.getStates().entries(),([t,n])=>t!==e.awareness.clientID&&n?[t,{relativeSelection:n[e.selectionStateField],data:n[e.cursorDataField]}]:null).filter(Array.isArray)):{}},pd=Object.defineProperty,md=Object.defineProperties,yd=Object.getOwnPropertyDescriptors,bd=Object.getOwnPropertySymbols,wd=Object.prototype.hasOwnProperty,vd=Object.prototype.propertyIsEnumerable,_d=(e,t,n)=>t in e?pd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kd=(e,t)=>{for(var n in t||(t={}))wd.call(t,n)&&_d(e,n,t[n]);if(bd)for(var n of bd(t))vd.call(t,n)&&_d(e,n,t[n]);return e},Cd=/* @__PURE__ */new WeakMap;function Sd(e,t){if(!t.relativeSelection)return null;let n=Cd.get(e.children);n||(n=/* @__PURE__ */new WeakMap,Cd.set(e.children,n));let r=n.get(t);if(void 0===r)try{r=function(e,t,n){const r=nd(e,t,n.anchor);if(!r)return null;const i=nd(e,t,n.focus);return i?{anchor:r,focus:i}:null}(e.sharedRoot,e,t.relativeSelection),n.set(t,r)}catch(i){return null}return r}function Ed(){const e=M();if(!gd.isCursorEditor(e))throw new Error("Cannot use useSyncExternalStore outside the context of a RemoteCursorEditor");return e}var Ad=/* @__PURE__ */new WeakMap;function Td(e){const t=Ad.get(e);if(t)return t;const n=function(e){let t={};const n=/* @__PURE__ */new Set,r=n.add.bind(n),i=/* @__PURE__ */new Set;let s=null;return[t=>(i.add(t),s||(s=e=>{e.added.forEach(r),e.removed.forEach(r),e.updated.forEach(r),i.forEach(e=>e())},gd.on(e,"change",s)),()=>{i.delete(t),s&&0===i.size&&(gd.off(e,"change",s),s=null)}),()=>(0===n.size||(n.forEach(n=>{const r=gd.cursorState(e,n);null!==r?t[n]=r:delete t[n.toString()]}),n.clear(),t=kd({},t)),t)]}(e);return Ad.set(e,n),n}function xd(){const[e,t]=Td(Ed());return Er(e,t)}function Rd(e,t,{yOffset:n,xOffset:r,shouldGenerateOverlay:i}){const[s,o]=se.edges(t),a=function(e,t){try{return N.toDOMRange(e,t)}catch(n){return null}}(e,t);if(!a)return{caretPosition:null,selectionRects:[]};const c=[],l=q.nodes(e,{at:t,match:(e,t)=>J.isText(e)&&(!i||i(e,t))});let h=null;const d=se.isBackward(t);for(const[u,f]of l){const i=N.toDOMNode(e,u),l=ee.equals(f,s.path),g=ee.equals(f,o.path);let p=null;if(l||g){const e=document.createRange();e.selectNode(i),l&&e.setStart(a.startContainer,a.startOffset),g&&e.setEnd(a.endContainer,a.endOffset),p=e.getClientRects()}else p=i.getClientRects();const m=d?l:g;for(let e=0;e<p.length;e++){const i=p.item(e);if(!i)continue;const s=m&&(d?0===e:e===p.length-1),o=i.top-n,a=i.left-r;s&&(h={height:i.height,top:o,left:a+(d||se.isCollapsed(t)?0:i.width)}),c.push({width:i.width,height:i.height,top:o,left:a})}}return{selectionRects:c,caretPosition:h}}var Dd=Object.freeze([]);function Od(e={}){var t,n=e,{containerRef:r,shouldGenerateOverlay:i}=n,s=((e,t)=>{var n={};for(var r in e)wd.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&bd)for(var r of bd(e))t.indexOf(r)<0&&vd.call(e,r)&&(n[r]=e[r]);return n})(n,["containerRef","shouldGenerateOverlay"]);const o=Ed(),a=xd(),c=function(){const[,e]=Cn(e=>e+1,0),t=Sn(null),n=()=>{t.current&&(cancelAnimationFrame(t.current),t.current=0)};return vn(n),vn(()=>n,[]),wn((n=!1)=>{n?e():t.current||(t.current=requestAnimationFrame(e))},[])}(),l=Sn(/* @__PURE__ */new WeakMap),[h,d]=En({}),u=!("refreshOnResize"in s)||(null==(t=s.refreshOnResize)||t);return function(e,t){const n=Sn(t);n.current=t;const[r]=En(()=>new ResizeObserver(()=>{n.current()}));vn(()=>{if(!(null==e?void 0:e.current))return;const{current:t}=e;return r.observe(t),()=>r.unobserve(t)},[r,e])}(u?r:void 0,()=>{l.current=/* @__PURE__ */new WeakMap,c("debounced"!==u)}),_n(()=>{var e,t,n;if(r&&!r.current)return;const s=null==(e=null==r?void 0:r.current)?void 0:e.getBoundingClientRect(),c=null!=(t=null==s?void 0:s.x)?t:0,u=null!=(n=null==s?void 0:s.y)?n:0;let f=Object.keys(h).length!==Object.keys(a).length;const g=Object.fromEntries(Object.entries(a).map(([e,t])=>{const n=t.relativeSelection&&Sd(o,t);if(!n)return[e,Dd];const r=l.current.get(n);if(r)return[e,r];const s=Rd(o,n,{xOffset:c,yOffset:u,shouldGenerateOverlay:i});return f=!0,l.current.set(n,s),[e,s]}));f&&d(g)}),[kn(()=>Object.entries(a).map(([e,t])=>{var n,r;const i=t.relativeSelection&&Sd(o,t),s=h[e];return a=kd({},t),c={range:i,caretPosition:null!=(n=null==s?void 0:s.caretPosition)?n:null,selectionRects:null!=(r=null==s?void 0:s.selectionRects)?r:Dd},md(a,yd(c));var a,c}),[a,o,h]),wn(()=>{l.current=/* @__PURE__ */new WeakMap,c(!0)},[c])]}function Pd(){return v(Rh,"_isSynced")?/* @__PURE__ */Dn(Ld,{}):null}function Ld(){const e=_(),[t]=Od({containerRef:e});/* @__PURE__ */
|
|
15
|
-
return
|
|
16
|
-
return
|
|
17
|
-
return
|
|
18
|
-
return
|
|
1
|
+
import{i as e,o as t,t as n}from"./rolldown-runtime-Drgf5FY8.js";import{o as r}from"./dist-DmY5xFkC.js";import{i,n as s,r as o,t as a}from"./tooltip-G11f5UOp.js";import{n as c,o as l,t as h}from"./editorConfig-CpUHUq44.js";import{$ as d,A as u,B as f,C as g,D as p,E as m,F as y,G as b,H as w,I as v,J as _,K as k,L as C,M as S,N as E,O as A,P as T,Q as x,R,S as D,T as O,U as P,V as L,W as M,X as N,Y as I,Z as U,_ as j,a as F,at as B,b as W,c as H,ct as q,d as V,dt as z,et as $,f as Y,ft as J,g as Q,h as K,i as G,it as X,j as Z,k as ee,l as te,lt as ne,m as re,n as ie,nt as se,o as oe,p as ae,q as ce,r as le,rt as he,s as de,st as ue,t as fe,tt as ge,u as pe,ut as me,v as ye,w as be,x as we,y as ve,z as _e}from"./reason-toolbar-skin-Beh6Q5Ra.js";import{a as ke,f as Ce,h as Se,m as Ee,o as Ae,p as Te,r as xe,s as Re,t as De,u as Oe}from"./dropdown-menu-tmQwCqOR.js";import{getTranscribeStorage as Pe,isTranscriptionSupported as Le,subscribeTranscribe as Me}from"./Transcribe.js";import{$ as Ne,A as Ie,At as Ue,B as je,Bt as Fe,C as Be,Ct as We,D as He,Dt as qe,E as Ve,Et as ze,F as $e,Ft as Ye,G as Je,Gt as Qe,H as Ke,Ht as Ge,I as Xe,It as Ze,J as et,K as tt,Kt as nt,L as rt,Lt as it,M as st,Mt as ot,N as at,Nt as ct,O as lt,Ot as ht,P as dt,Pt as ut,Q as ft,R as gt,Rt as pt,S as mt,St as yt,T as bt,Tt as wt,U as vt,Ut as _t,V as kt,Vt as Ct,W as St,Wt as Et,X as At,Y as Tt,Z as xt,_ as Rt,_t as Dt,at as Ot,b as Pt,bt as Lt,c as Mt,ct as Nt,d as It,dt as Ut,et as jt,f as Ft,ft as Bt,g as Wt,gt as Ht,h as qt,ht as Vt,i as zt,it as $t,j as Yt,jt as Jt,k as Qt,kt as Kt,l as Gt,lt as Xt,m as Zt,mt as en,nt as tn,o as nn,ot as rn,p as sn,pt as on,q as an,qt as cn,rt as ln,st as hn,t as dn,tt as un,u as fn,ut as gn,v as pn,vt as mn,w as yn,wt as bn,x as wn,xt as vn,y as _n,yt as kn,z as Cn,zt as Sn}from"./dist-kbEzWzhg.js";import*as En from"react";import{useCallback as An,useEffect as Tn,useLayoutEffect as xn,useMemo as Rn,useReducer as Dn,useRef as On,useState as Pn}from"react";import{Extension as Ln}from"@tiptap/core";import{Plugin as Mn,PluginKey as Nn}from"@tiptap/pm/state";import{Fragment as In,jsx as Un,jsxs as jn}from"react/jsx-runtime";import{AlignCenter as Fn,AlignJustify as Bn,AlignLeft as Wn,AlignRight as Hn,Baseline as qn,Bold as Vn,Braces as zn,Code as $n,Code2 as Yn,Columns2 as Jn,Eraser as Qn,FileText as Kn,Heading1 as Gn,Heading2 as Xn,Heading3 as Zn,Heading4 as er,Heading5 as tr,Heading6 as nr,Highlighter as rr,Image as ir,IndentDecrease as sr,IndentIncrease as or,Info as ar,Italic as cr,Link2 as lr,List as hr,ListChecks as dr,ListOrdered as ur,Mic as fr,Minus as gr,Pencil as pr,Pilcrow as mr,Plus as yr,Quote as br,Redo2 as wr,Rows3 as vr,Sigma as _r,Smile as kr,Strikethrough as Cr,Subscript as Sr,Superscript as Er,Table2 as Ar,Trash2 as Tr,Type as xr,Underline as Rr,Undo2 as Dr,Video as Or}from"lucide-react";import{useSyncExternalStore as Pr}from"use-sync-external-store/shim";import"use-sync-external-store/shim/with-selector";var Lr=class extends Ze{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=/* @__PURE__ */new Map,this.meta=/* @__PURE__ */new Map,this._checkInterval=setInterval(()=>{const e=At();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&Mr(this,t,"timeout")},ot(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:At()});const s=[],o=[],a=[],c=[];null===e?c.push(t):null==i?null!=e&&s.push(t):(o.push(t),rt(i,e)||a.push(t)),(s.length>0||a.length>0||c.length>0)&&this.emit("change",[{added:s,updated:a,removed:c},"local"]),this.emit("update",[{added:s,updated:o,removed:c},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},Mr=(e,t,n)=>{const r=[];for(let i=0;i<t.length;i++){const n=t[i];if(e.states.has(n)){if(e.states.delete(n),n===e.clientID){const t=e.meta.get(n);e.meta.set(n,{clock:t.clock+1,lastUpdated:At()})}r.push(n)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},Nr=(e,t,n=e.states)=>{const r=t.length,i=Lt();ht(i,r);for(let s=0;s<r;s++){const r=t[s],o=n.get(r)||null,a=e.meta.get(r).clock;ht(i,r),ht(i,a),qe(i,JSON.stringify(o))}return yt(i)};function Ir(e){return{engine:e,execute(){},isActive:()=>!1,isEnabled:()=>!1,getValue(){},subscribe:()=>()=>{}}}var Ur=[{kind:"button",id:"undo",label:"Undo",icon:Dr,shortcut:"⌘Z"},{kind:"button",id:"redo",label:"Redo",icon:wr,shortcut:"⇧⌘Z"},{kind:"separator",id:"history-divider"},{kind:"button",id:"bold",label:"Bold",icon:Vn,shortcut:"⌘B"},{kind:"button",id:"italic",label:"Italic",icon:cr,shortcut:"⌘I"},{kind:"button",id:"underline",label:"Underline",icon:Rr,shortcut:"⌘U"},{kind:"button",id:"highlight",label:"Highlight",icon:rr,shortcut:"⌘⇧H"},{kind:"separator",id:"marks-divider"},{kind:"menu",id:"block-format",label:"Block Format",icon:vr,children:[{kind:"button",id:"paragraph",label:"Paragraph",icon:mr},{kind:"button",id:"heading-1",label:"Heading 1",icon:Gn,shortcut:"Ctrl+Alt+1"},{kind:"button",id:"heading-2",label:"Heading 2",icon:Xn,shortcut:"Ctrl+Alt+2"},{kind:"button",id:"heading-3",label:"Heading 3",icon:Zn,shortcut:"Ctrl+Alt+3"},{kind:"button",id:"heading-4",label:"Heading 4",icon:er,shortcut:"Ctrl+Alt+4"},{kind:"button",id:"heading-5",label:"Heading 5",icon:tr,shortcut:"Ctrl+Alt+5"},{kind:"button",id:"heading-6",label:"Heading 6",icon:nr,shortcut:"Ctrl+Alt+6"},{kind:"separator",id:"block-format-lists-divider"},{kind:"button",id:"bullet-list",label:"Bullet List",icon:hr,shortcut:"Ctrl+Shift+8"},{kind:"button",id:"ordered-list",label:"Ordered List",icon:ur,shortcut:"Ctrl+Shift+7"},{kind:"button",id:"task-list",label:"Check List",icon:dr,shortcut:"Ctrl+Shift+9"},{kind:"separator",id:"block-format-quote-divider"},{kind:"button",id:"blockquote",label:"Blockquote",icon:br,shortcut:"Ctrl+Shift+B"},{kind:"button",id:"code-block",label:"Code Block",icon:Yn,shortcut:"Ctrl+Alt+C"},{kind:"separator",id:"block-format-clear-divider"},{kind:"button",id:"clear-formatting",label:"Clear Format",icon:Qn}]},{kind:"menu",id:"text-styles",label:"Text Styles",icon:xr,children:[{kind:"group-label",id:"text-styles-label",label:"Text Styles"},{kind:"button",id:"strike",label:"Strikethrough",icon:Cr,shortcut:"Ctrl+Shift+S"},{kind:"button",id:"code",label:"Inline Code",icon:$n,shortcut:"Ctrl+E"},{kind:"button",id:"text-color",label:"Text Color",icon:qn,shortcut:"Alt+Shift+C"},{kind:"button",id:"superscript",label:"Superscript",icon:Er,shortcut:"Ctrl+."},{kind:"button",id:"subscript",label:"Subscript",icon:Sr,shortcut:"Ctrl+,"},{kind:"separator",id:"text-styles-indent-divider"},{kind:"button",id:"indent",label:"Indent",icon:or},{kind:"button",id:"outdent",label:"Outdent",icon:sr},{kind:"menu",id:"alignment",label:"Alignment",icon:Wn,children:[{kind:"button",id:"align-left",label:"Align Left",icon:Wn},{kind:"button",id:"align-center",label:"Align Center",icon:Fn},{kind:"button",id:"align-right",label:"Align Right",icon:Hn},{kind:"button",id:"align-justify",label:"Justify",icon:Bn}]}]},{kind:"menu",id:"insert",label:"Insert",icon:yr,children:[{kind:"group-label",id:"insert-label",label:"Insert"},{kind:"button",id:"link",label:"Link",icon:lr},{kind:"button",id:"emoji",label:"Emoji",icon:kr},{kind:"button",id:"table",label:"Table",icon:Ar},{kind:"button",id:"image",label:"Image",icon:ir},{kind:"button",id:"columns",label:"Columns",icon:Jn,shortcut:"Ctrl+Alt+G"},{kind:"button",id:"callout",label:"Callout",icon:ar},{kind:"button",id:"horizontal-rule",label:"Divider",icon:gr,shortcut:"Ctrl+Alt+S"},{kind:"button",id:"video",label:"Video",icon:Or},{kind:"button",id:"math",label:"Math",icon:_r}]},{kind:"separator",id:"voice-divider"},{kind:"button",id:"transcribe",label:"Dictate",icon:fr,shortcut:"Ctrl+Shift+D"},{kind:"menu",id:"table-tools",label:"Table",icon:Ar,visibleWhenActive:"table",children:[{kind:"group-label",id:"table-rows-label",label:"Rows"},{kind:"button",id:"table.add-row-before",label:"Insert Row Above",icon:vr},{kind:"button",id:"table.add-row-after",label:"Insert Row Below",icon:vr},{kind:"button",id:"table.delete-row",label:"Delete Row",icon:Tr},{kind:"separator",id:"table-columns-divider"},{kind:"group-label",id:"table-columns-label",label:"Columns"},{kind:"button",id:"table.add-column-before",label:"Insert Column Left",icon:Jn},{kind:"button",id:"table.add-column-after",label:"Insert Column Right",icon:Jn},{kind:"button",id:"table.delete-column",label:"Delete Column",icon:Tr},{kind:"separator",id:"table-cells-divider"},{kind:"group-label",id:"table-cells-label",label:"Cells"},{kind:"button",id:"table.merge-cells",label:"Merge Cells",icon:zn},{kind:"button",id:"table.split-cell",label:"Split Cell",icon:zn},{kind:"button",id:"table.toggle-header-row",label:"Toggle Header Row",icon:vr},{kind:"separator",id:"table-delete-divider"},{kind:"button",id:"table.delete",label:"Delete Table",icon:Tr}]}];function jr(e=Ur){const t=[];for(const n of e)"button"===n.kind&&t.push(n.id),"menu"===n.kind&&t.push(...jr(n.children));return t}var Fr="flex items-center justify-center rounded p-1.5 text-gray-600 transition-colors dark:text-gray-300 disabled:cursor-not-allowed disabled:opacity-40 hover:enabled:bg-gray-100 dark:hover:enabled:bg-slate-800",Br="bg-gray-200 text-gray-900 dark:bg-slate-700 dark:text-white",Wr="flex w-full cursor-pointer items-center gap-2 text-xs data-disabled:cursor-not-allowed data-disabled:opacity-40";function Hr({shortcut:e}){return e?/* @__PURE__ */Un("span",{className:"ml-auto pl-4 text-[10px] tracking-widest text-gray-400 dark:text-gray-500",children:e}):null}function qr({items:e,adapter:t}){/* @__PURE__ */
|
|
2
|
+
return Un(In,{children:e.map(e=>{if("separator"===e.kind)/* @__PURE__ */return Un(Oe,{},e.id);if("group-label"===e.kind)/* @__PURE__ */return Un(Ae,{className:"px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:e.label},e.id);if("menu"===e.kind){const n=e.icon;/* @__PURE__ */
|
|
3
|
+
return jn(Ce,{children:[/* @__PURE__ */jn(Ee,{className:Wr,children:[/* @__PURE__ */Un(n,{className:"size-3.5 shrink-0 text-gray-500 dark:text-gray-400"}),e.label]}),/* @__PURE__ */Un(Re,{children:/* @__PURE__ */Un(Te,{className:"min-w-[200px]",children:/* @__PURE__ */Un(qr,{items:e.children,adapter:t})})})]},e.id)}const n=e.icon,i=t.isActive(e.id);/* @__PURE__ */
|
|
4
|
+
return jn(ke,{"aria-pressed":i,className:r(Wr,i&&Br),"data-command":e.id,"data-state":i?"active":"inactive",disabled:!t.isEnabled(e.id),onSelect:()=>{t.execute(e.id)},children:[
|
|
5
|
+
/* @__PURE__ */Un(n,{className:"size-3.5 shrink-0 text-gray-500 dark:text-gray-400"}),
|
|
6
|
+
/* @__PURE__ */Un("span",{className:"truncate",children:e.label}),
|
|
7
|
+
/* @__PURE__ */Un(Hr,{shortcut:e.shortcut})]},e.id)})})}function Vr({item:e,adapter:t}){if("separator"===e.kind)/* @__PURE__ */return Un("div",{className:"mx-1 h-5 w-px bg-gray-200 dark:bg-slate-700"});if("group-label"===e.kind)/* @__PURE__ */return Un("span",{className:"px-1 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:e.label});if("menu"===e.kind){if(e.visibleWhenActive&&!t.isActive(e.visibleWhenActive))return null;const n=e.icon;/* @__PURE__ */
|
|
8
|
+
return jn(De,{children:[/* @__PURE__ */jn(a,{children:[/* @__PURE__ */Un(i,{asChild:!0,children:/* @__PURE__ */Un(Se,{"aria-label":e.label,className:r(Fr,"data-[state=open]:bg-gray-200 dark:data-[state=open]:bg-slate-700"),"data-menu":e.id,children:/* @__PURE__ */Un(n,{className:"size-4"})})}),/* @__PURE__ */Un(s,{side:"bottom",children:e.label})]}),/* @__PURE__ */Un(xe,{align:"start",className:"min-w-[240px]",children:/* @__PURE__ */Un(qr,{items:e.children,adapter:t})})]})}const n=e.icon,o=t.isActive(e.id),c=t.isEnabled(e.id);/* @__PURE__ */
|
|
9
|
+
return jn(a,{children:[/* @__PURE__ */Un(i,{asChild:!0,children:/* @__PURE__ */Un("button",{"aria-label":e.label,"aria-pressed":o,className:r(Fr,o&&Br),"data-command":e.id,"data-state":o?"active":"inactive",disabled:!c,onClick:()=>{t.execute(e.id)},type:"button",children:/* @__PURE__ */Un(n,{className:"size-4"})})}),/* @__PURE__ */jn(s,{side:"bottom",children:[e.label,e.shortcut?/* @__PURE__ */Un("span",{className:"ml-2 text-[10px] tracking-widest opacity-70",children:e.shortcut}):null]})]})}function zr({adapter:e,items:t=Ur,className:n,children:i}){return function(e){const[t,n]=En.useState(0);En.useEffect(()=>{if(e.subscribe)return e.subscribe(()=>n(e=>e+1))},[e])}(e),/* @__PURE__ */Un(o,{delayDuration:300,children:/* @__PURE__ */jn("div",{className:r("flex flex-wrap items-center gap-0.5 border-b border-gray-200 px-2 py-1 dark:border-slate-700",n),"data-engine":e.engine,role:"toolbar",children:[t.map(t=>/* @__PURE__ */Un(Vr,{adapter:e,item:t},(t.kind,t.id))),i?/* @__PURE__ */Un("div",{className:"ml-auto flex items-center gap-1",children:i}):null]})})}var $r="REASON-documents",Yr="reason-documents-changed";function Jr(){if("undefined"==typeof window)return[];try{const e=window.localStorage.getItem($r);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Qr(e){"undefined"!=typeof window&&(window.localStorage.setItem($r,JSON.stringify(e)),window.dispatchEvent(new Event(Yr)))}function Kr(e){return{id:e.id,title:e.title?.trim()||"Untitled Document"}}function Gr(){return Jr().filter(e=>!e.isFolder&&!e.isDeleted&&!e.parentId).map(Kr)}function Xr(e="Untitled Document"){const t={id:`doc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,title:e,content:"",parentId:null};return Qr([...Jr(),t]),Kr(t)}function Zr(e,t){const n=t.trim()||"Untitled Document";Qr(Jr().map(t=>t.id===e?{...t,title:n}:t))}function ei(e){Qr(Jr().map(t=>t.id===e?{...t,isDeleted:!0}:t))}function ti(e){if("undefined"==typeof window)return()=>{};const t=t=>{"REASON-documents"===t.key&&e()};return window.addEventListener(Yr,e),window.addEventListener("storage",t),()=>{window.removeEventListener(Yr,e),window.removeEventListener("storage",t)}}function ni({activeDocumentId:e,linkForDocument:t,onNavigate:n,className:i}){const[s,o]=En.useState([]),[a,c]=En.useState(null),[l,h]=En.useState(""),d=En.useCallback(()=>{o(Gr())},[]);En.useEffect(()=>(d(),ti(d)),[d]);const u=()=>{a&&Zr(a,l),c(null)};/* @__PURE__ */
|
|
10
|
+
return jn("nav",{"aria-label":"Documents",className:r("flex w-56 shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-gray-200 bg-gray-50 p-2 dark:border-slate-700 dark:bg-slate-900",i),"data-testid":"reason-sidebar",children:[
|
|
11
|
+
/* @__PURE__ */jn("div",{className:"flex items-center justify-between px-1 pb-2",children:[/* @__PURE__ */Un("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-gray-400",children:"Documents"}),/* @__PURE__ */Un("button",{"aria-label":"New document",className:"rounded p-1 text-gray-500 hover:bg-gray-200 dark:text-gray-400 dark:hover:bg-slate-800",onClick:()=>{n(Xr().id)},type:"button",children:/* @__PURE__ */Un(yr,{className:"size-3.5"})})]}),s.map(i=>{const o=i.id===e,d=a===i.id;/* @__PURE__ */
|
|
12
|
+
return jn("div",{className:r("group flex items-center gap-1.5 rounded px-1.5 py-1 text-sm",o?"bg-gray-200 text-gray-900 dark:bg-slate-700 dark:text-white":"text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-slate-800"),"data-document-id":i.id,children:[
|
|
13
|
+
/* @__PURE__ */Un(Kn,{className:"size-3.5 shrink-0 opacity-60"}),d?/* @__PURE__ */Un("input",{autoFocus:!0,className:"min-w-0 flex-1 rounded border border-gray-300 bg-white px-1 py-0.5 text-sm dark:border-slate-600 dark:bg-slate-800",onBlur:u,onChange:e=>h(e.target.value),onKeyDown:e=>{"Enter"===e.key&&u(),"Escape"===e.key&&c(null)},value:l}):/* @__PURE__ */Un("a",{className:"min-w-0 flex-1 truncate",href:t(i.id),children:i.title}),!d&&/* @__PURE__ */jn("div",{className:"hidden shrink-0 items-center gap-0.5 group-hover:flex",children:[/* @__PURE__ */Un("button",{"aria-label":`Rename ${i.title}`,className:"rounded p-0.5 text-gray-400 hover:bg-gray-200 dark:hover:bg-slate-700",onClick:()=>(e=>{c(e.id),h(e.title)})(i),type:"button",children:/* @__PURE__ */Un(pr,{className:"size-3"})}),/* @__PURE__ */Un("button",{"aria-label":`Delete ${i.title}`,className:"rounded p-0.5 text-gray-400 hover:bg-gray-200 dark:hover:bg-slate-700",onClick:()=>(t=>{if("undefined"!=typeof window&&!window.confirm(`Delete "${t.title}"?`))return;if(ei(t.id),t.id!==e)return;const r=s.find(e=>e.id!==t.id);n(r?r.id:Xr().id)})(i),type:"button",children:/* @__PURE__ */Un(Tr,{className:"size-3"})})]})]},i.id)}),0===s.length&&/* @__PURE__ */Un("p",{className:"px-1.5 py-2 text-xs text-gray-400",children:"No documents yet."})]})}var ri=/* @__PURE__ */function(e){return e[e.Token=0]="Token",e[e.PermissionDenied=1]="PermissionDenied",e[e.Authenticated=2]="Authenticated",e}({}),ii=(e,t)=>{ht(e,ri.Token),qe(e,t)},si=(e,t,n,r)=>{switch(Ut(e)){case ri.Token:t();break;case ri.PermissionDenied:n(gn(e));break;case ri.Authenticated:r(gn(e))}},oi=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));function ai(e,t){return e+"\0"+t}function ci(e){const t=e.indexOf("\0");return-1===t?{documentName:e,sessionId:null}:{documentName:e.substring(0,t),sessionId:e.substring(t+1)}}var li=/* @__PURE__ */function(e){return e[e.Connecting=0]="Connecting",e[e.Open=1]="Open",e[e.Closing=2]="Closing",e[e.Closed=3]="Closed",e}({});async function hi(e){return new Promise(t=>setTimeout(t,e))}function di(e,t){let n=t.delay;if(0===n)return 0;if(t.factor&&(n*=Math.pow(t.factor,e.attemptNum-1),0!==t.maxDelay&&(n=Math.min(n,t.maxDelay))),t.jitter){const e=Math.ceil(t.minDelay);n=Math.floor(Math.random()*(Math.floor(n)-e+1))+e}return Math.round(n)}async function ui(e,t){const n=function(e){return e||(e={}),{delay:void 0===e.delay?200:e.delay,initialDelay:void 0===e.initialDelay?0:e.initialDelay,minDelay:void 0===e.minDelay?0:e.minDelay,maxDelay:void 0===e.maxDelay?0:e.maxDelay,factor:void 0===e.factor?0:e.factor,maxAttempts:void 0===e.maxAttempts?3:e.maxAttempts,timeout:void 0===e.timeout?0:e.timeout,jitter:!0===e.jitter,initialJitter:!0===e.initialJitter,handleError:void 0===e.handleError?null:e.handleError,handleTimeout:void 0===e.handleTimeout?null:e.handleTimeout,beforeAttempt:void 0===e.beforeAttempt?null:e.beforeAttempt,calculateDelay:void 0===e.calculateDelay?null:e.calculateDelay}}(t);for(const o of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const e=n[o];if(!Number.isInteger(e)||e<0)throw new Error(`Value for ${o} must be an integer greater than or equal to 0`)}if(n.factor.constructor!==Number||n.factor<0)throw new Error("Value for factor must be a number greater than or equal to 0");if(n.delay<n.minDelay)throw new Error(`delay cannot be less than minDelay (delay: ${n.delay}, minDelay: ${n.minDelay}`);const r={attemptNum:0,attemptsRemaining:n.maxAttempts?n.maxAttempts:-1,aborted:!1,abort(){r.aborted=!0}},i=n.calculateDelay||di;const s=n.calculateDelay?n.calculateDelay(r,n):n.initialDelay;if(s&&await hi(s),r.attemptNum<1&&n.initialJitter){const e=i(r,n);e&&await hi(e)}return async function t(){if(n.beforeAttempt&&n.beforeAttempt(r,n),r.aborted){const e=/* @__PURE__ */new Error("Attempt aborted");throw e.code="ATTEMPT_ABORTED",e}const s=async e=>{if(n.handleError&&await n.handleError(e,r,n),r.aborted||0===r.attemptsRemaining)throw e;r.attemptNum++;const s=i(r,n);return s&&await hi(s),t()};return r.attemptsRemaining>0&&r.attemptsRemaining--,n.timeout?new Promise((t,i)=>{const o=setTimeout(()=>{if(n.handleTimeout)try{t(n.handleTimeout(r,n))}catch(e){i(e)}else{const e=/* @__PURE__ */new Error(`Retry timeout (attemptNum: ${r.attemptNum}, timeout: ${n.timeout})`);e.code="ATTEMPT_TIMEOUT",i(e)}},n.timeout);e(r,n).then(e=>{clearTimeout(o),t(e)}).catch(e=>{clearTimeout(o),s(e).then(t).catch(i)})}):e(r,n).catch(s)}()}var fi=(e,t,n)=>((e,t,n)=>{ht(e,1),Kt(e,Rt(t,n))})(t,n,Bt(e)),gi=(e,t,n,r)=>{try{It(t,Bt(e),n)}catch(i){null!=r&&r(i)}},pi=gi,mi=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){const n=this.callbacks[e];return n&&n.forEach(e=>e.apply(this,t)),this}off(e,t){const n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(e=>e!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}},yi=class{constructor(e){this.data=e,this.encoder=Lt(),this.decoder=$t(new Uint8Array(this.data))}peekVarString(){return rn(this.decoder)}readVarUint(){return Ut(this.decoder)}readVarString(){return gn(this.decoder)}readVarUint8Array(){return Bt(this.decoder)}writeVarUint(e){return ht(this.encoder,e)}writeVarString(e){return qe(this.encoder,e)}writeVarUint8Array(e){return Kt(this.encoder,e)}length(){return vn(this.encoder)}},bi=/* @__PURE__ */function(e){return e[e.Sync=0]="Sync",e[e.Awareness=1]="Awareness",e[e.Auth=2]="Auth",e[e.QueryAwareness=3]="QueryAwareness",e[e.Stateless=5]="Stateless",e[e.CLOSE=7]="CLOSE",e[e.SyncStatus=8]="SyncStatus",e[e.Ping=9]="Ping",e[e.Pong=10]="Pong",e}({}),wi=/* @__PURE__ */function(e){return e.Connecting="connecting",e.Connected="connected",e.Disconnected="disconnected",e}({}),vi=class{constructor(){this.encoder=Lt()}get(e){return e.encoder}toUint8Array(){return yt(this.encoder)}},_i=class extends vi{constructor(...e){super(...e),this.type=bi.CLOSE,this.description="Ask the server to close the connection"}get(e){return qe(this.encoder,e.documentName),ht(this.encoder,this.type),this.encoder}},ki=class e extends mi{static{this.DEDUPLICATABLE_TYPES=/* @__PURE__ */new Set([bi.Awareness,bi.QueryAwareness])}constructor(e){super(),this.messageQueue=[],this.configuration={url:"",autoConnect:!0,preserveTrailingSlash:!1,document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,handleTimeout:null,providerMap:/* @__PURE__ */new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=wi.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(e),this.configuration.WebSocketPolyfill=e.WebSocketPolyfill?e.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(e){this.status=wi.Connected,this.emit("status",{status:wi.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){const t=e.effectiveName,n=this.configuration.providerMap.get(t);if(n&&n!==e&&n.isAuthenticated)throw new Error(`Cannot attach two providers with the same effective name "${t}". Use sessionAwareness: true to multiplex providers with the same document name.`);this.configuration.providerMap.set(t,e),this.status===wi.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===wi.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){const t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(_i,{documentName:t}),this.configuration.providerMap.delete(t))}setConfiguration(e={}){this.configuration={...this.configuration,...e},this.configuration.autoConnect||(this.shouldConnect=!1)}async connect(){if(this.status===wi.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const{retryPromise:e,cancelFunc:t}=(()=>{let e=!1;return{retryPromise:ui(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,handleTimeout:this.configuration.handleTimeout,beforeAttempt:t=>{this.shouldConnect&&!e||t.abort()}}).catch(e=>{if(e&&"ATTEMPT_ABORTED"!==e.code)throw e}),cancelFunc:()=>{e=!0}}})();return this.cancelWebsocketRetry=t,e}attachWebSocketListeners(e,t){const{identifier:n}=e;this.webSocketHandlers[n]={message:e=>this.emit("message",e),close:e=>this.emit("close",{event:e}),open:e=>this.emit("open",e),error:e=>{t(e)}};const r=this.webSocketHandlers[e.identifier];Object.keys(r).forEach(t=>{e.addEventListener(t,r[t])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:e}=this.webSocket,t=this.webSocketHandlers[e];Object.keys(t).forEach(n=>{this.webSocket?.removeEventListener(n,t[n]),delete this.webSocketHandlers[e]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((e,t)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=wi.Connecting,this.emit("status",{status:wi.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=At();const t=new Uint8Array(e.data);if(1===t.length&&t[0]===bi.Ping)return void this.sendPong();const n=new yi(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){const e=Lt();ht(e,bi.Pong),this.send(yt(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=wi.Connected,this.emit("status",{status:wi.Connected}),this.emit("connect"),this.messageQueue.forEach(e=>this.send(e)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){this.connectionAttempt?.reject(),this.connectionAttempt=null}checkConnection(){this.status===wi.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=At()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):(this.webSocket?.close(),this.messageQueue=[])))}get serverUrl(){if(this.configuration.preserveTrailingSlash)return this.configuration.url;let e=this.configuration.url;for(;"/"===e[e.length-1];)e=e.slice(0,e.length-1);return e}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,null!==this.webSocket)try{this.webSocket.close(),this.messageQueue=[]}catch(e){}}parseQueuedMessage(e){try{const t=$t(e);return{documentName:gn(t),messageType:Ut(t)}}catch{return null}}addToQueue(t){if(t instanceof Uint8Array){const n=this.parseQueuedMessage(t);n&&e.DEDUPLICATABLE_TYPES.has(n.messageType)&&(this.messageQueue=this.messageQueue.filter(e=>{if(!(e instanceof Uint8Array))return!0;const t=this.parseQueuedMessage(e);return!t||!(t.documentName===n.documentName&&t.messageType===n.messageType)}))}this.messageQueue.push(t)}send(e){this.webSocket?.readyState===li.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=wi.Disconnected,this.emit("status",{status:wi.Disconnected}),this.emit("disconnect",{event:e}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}},Ci=class{constructor(e){this.message=e}apply(e,t){const{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case bi.Sync:this.applySyncMessage(e,t);break;case bi.Awareness:this.applyAwarenessMessage(e);break;case bi.Auth:this.applyAuthMessage(e);break;case bi.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case bi.Stateless:e.receiveStateless(gn(n.decoder));break;case bi.SyncStatus:this.applySyncStatusMessage(e,1===Xt(n.decoder));break;case bi.CLOSE:{const t={code:1e3,reason:gn(n.decoder)};e.onClose(),e.configuration.onClose({event:t}),e.forwardClose({event:t});break}}n.length()>i+1&&e.send(vi,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(bi.Sync);const r=((e,t,n,r,i)=>{const s=Ut(e);switch(s){case 0:fi(e,t,n);break;case 1:gi(e,n,r,i);break;case 2:pi(e,n,r,i);break;default:throw new Error("Unknown message type")}return s})(n.decoder,n.encoder,e.document,e);t&&1===r&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;((e,t,n)=>{const r=$t(t),i=At(),s=[],o=[],a=[],c=[],l=Ut(r);for(let h=0;h<l;h++){const t=Ut(r);let n=Ut(r);const l=JSON.parse(gn(r)),h=e.meta.get(t),d=e.states.get(t),u=void 0===h?0:h.clock;(u<n||u===n&&null===l&&e.states.has(t))&&(null===l?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===h&&null!==l?s.push(t):void 0!==h&&null===l?c.push(t):null!==l&&(rt(l,d)||a.push(t),o.push(t)))}(s.length>0||a.length>0||c.length>0)&&e.emit("change",[{added:s,updated:a,removed:c},n]),(s.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:s,updated:o,removed:c},n])})(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;si(t.decoder,e.sendToken.bind(e),e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;t.writeVarUint(bi.Awareness),t.writeVarUint8Array(Nr(e.awareness,Array.from(e.awareness.getStates().keys())))}},Si=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return yt(this.encoder)}send(e){e?.send(this.create())}},Ei=class extends vi{constructor(...e){super(...e),this.type=bi.Auth,this.description="Authentication"}get(e){if(void 0===e.token)throw new Error("The authentication message requires `token` as an argument.");return qe(this.encoder,e.documentName),ht(this.encoder,this.type),ii(this.encoder,e.token),qe(this.encoder,"4.6.0"),this.encoder}},Ai=class extends vi{constructor(...e){super(...e),this.type=bi.Awareness,this.description="Awareness states update"}get(e){if(void 0===e.awareness)throw new Error("The awareness message requires awareness as an argument");if(void 0===e.clients)throw new Error("The awareness message requires clients as an argument");let t;return qe(this.encoder,e.documentName),ht(this.encoder,this.type),t=void 0===e.states?Nr(e.awareness,e.clients):Nr(e.awareness,e.clients,e.states),Kt(this.encoder,t),this.encoder}},Ti=class extends vi{constructor(...e){super(...e),this.type=bi.Stateless,this.description="A stateless message"}get(e){return qe(this.encoder,e.documentName),ht(this.encoder,this.type),qe(this.encoder,e.payload??""),this.encoder}},xi=class extends vi{constructor(...e){super(...e),this.type=bi.Sync,this.description="First sync step"}get(e){if(void 0===e.document)throw new Error("The sync step one message requires document as an argument");return qe(this.encoder,e.documentName),ht(this.encoder,this.type),((e,t)=>{ht(e,0);const n=pn(t);Kt(e,n)})(this.encoder,e.document),this.encoder}},Ri=class extends vi{constructor(...e){super(...e),this.type=bi.Sync,this.description="A document update"}get(e){var t,n;return qe(this.encoder,e.documentName),ht(this.encoder,this.type),t=this.encoder,n=e.update,ht(t,2),Kt(t,n),this.encoder}},Di=class extends Error{constructor(...e){super(...e),this.code=1001}},Oi=class extends mi{get effectiveName(){return this.configuration.sessionAwareness?ai(this.configuration.name,this.sessionId):this.configuration.name}constructor(e){super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,sessionAwareness:!1,forceSyncInterval:!1,flushDelay:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.pendingUpdates=[],this.pendingAwarenessClients=/* @__PURE__ */new Set,this.flushTimeout=null,this.sessionId=Math.random().toString(36).slice(2),this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=()=>this.emit("connect"),this.forwardStatus=e=>this.emit("status",e),this.forwardClose=e=>this.emit("close",e),this.forwardDisconnect=e=>this.emit("disconnect",e),this.forwardDestroy=()=>this.emit("destroy"),this.setConfiguration(e),this.configuration.document=e.document?e.document:new Gt,this.configuration.awareness=void 0!==e.awareness?e.awareness:new Lr(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),this.awareness?.on("update",()=>{this.emit("awarenessUpdate",{states:oi(this.awareness.getStates())})}),this.awareness?.on("change",()=>{this.emit("awarenessChange",{states:oi(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),this.awareness?.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&"number"==typeof this.configuration.forceSyncInterval&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(e={}){e.websocketProvider||(this.manageSocket=!0,this.configuration.websocketProvider=new ki(e)),this.configuration={...this.configuration,...e}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),0===this.unsyncedChanges&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(xi,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&Mr(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(Ti,{documentName:this.effectiveName,payload:e})}async sendToken(){let e;try{e=await this.getToken()}catch(t){return void this.permissionDeniedHandler(`Failed to get token during sendToken(): ${t}`)}this.send(Ei,{token:e??"",documentName:this.effectiveName})}get batchingEnabled(){return!!this.configuration.flushDelay&&"number"==typeof this.configuration.flushDelay}documentUpdateHandler(e,t){if(t!==this){if(!this.batchingEnabled)return this.incrementUnsyncedChanges(),void this.send(Ri,{update:e,documentName:this.effectiveName});0===this.pendingUpdates.length&&this.incrementUnsyncedChanges(),this.pendingUpdates.push(e),this.scheduleFlush()}}awarenessUpdateHandler({added:e,updated:t,removed:n},r){if(r===this)return;const i=e.concat(t).concat(n);if(this.batchingEnabled){for(const e of i)this.pendingAwarenessClients.add(e);this.scheduleFlush()}else this.send(Ai,{awareness:this.awareness,clients:i,documentName:this.effectiveName})}scheduleFlush(){null===this.flushTimeout&&(this.flushTimeout=setTimeout(()=>{this.flushTimeout=null,this.flushPendingUpdates()},this.configuration.flushDelay))}flushPendingUpdates(){if(null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates.length>0){const e=1===this.pendingUpdates.length?this.pendingUpdates[0]:_n(this.pendingUpdates);this.pendingUpdates=[],this.send(Ri,{update:e,documentName:this.effectiveName})}if(this.pendingAwarenessClients.size>0){const e=Array.from(this.pendingAwarenessClients);this.pendingAwarenessClients.clear(),this.send(Ai,{awareness:this.awareness,clients:e,documentName:this.effectiveName})}}get synced(){return this.isSynced}set synced(e){this.isSynced!==e&&(this.isSynced=e,e&&this.emit("synced",{state:e}))}receiveStateless(e){this.emit("stateless",{payload:e})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect()}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect()}async onOpen(e){this.isAuthenticated=!1,this.emit("open",{event:e}),await this.sendToken(),this.startSync()}async getToken(){return"function"==typeof this.configuration.token?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(xi,{document:this.document,documentName:this.effectiveName}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(Ai,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;const n=new Si(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new yi(e.data),{documentName:n}=ci(t.readVarString());t.writeVarString(this.effectiveName),this.emit("message",{event:e,message:new yi(e.data)}),new Ci(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates=[],this.pendingAwarenessClients.clear(),this.awareness&&Mr(this.awareness,Array.from(this.awareness.getStates().keys()).filter(e=>e!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(Mr(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.flushPendingUpdates(),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),"undefined"!=typeof window&&"removeEventListener"in window&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("status",this.forwardStatus),this.configuration.websocketProvider.off("status",this.configuration.onStatus),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("status",this.configuration.onStatus),this.configuration.websocketProvider.on("status",this.forwardStatus),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(e){this.emit("authenticationFailed",{reason:e}),this.isAuthenticated=!1}authenticatedHandler(e){this.isAuthenticated=!0,this.authorizedScope=e,this.emit("authenticated",{scope:e})}setAwarenessField(e,t){if(!this.awareness)throw new Di(`Cannot set awareness field "${e}" to ${JSON.stringify(t)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(e,t)}},Pi="reason-editor";function Li(e,t){if(!t)throw new Error("collaborationRoom: documentId is required");return`${Pi}:${e}:${t}`}function Mi(e){const[t,n,...r]=e.split(":"),i=r.join(":");return"reason-editor"!==t||"tiptap"!==n&&"plate"!==n?null:i?{engine:n,documentId:i}:null}function Ni(){return"undefined"!=typeof process&&(process.env.NEXT_PUBLIC_HOCUSPOCUS_URL??process.env.VITE_HOCUSPOCUS_URL)||"ws://127.0.0.1:1234"}function Ii({engine:e,documentId:t,token:n,url:r=Ni(),onSynced:i}){const s=Li(e,t),o=new Gt,a=new Oi({document:o,name:s,token:n,url:r,onSynced:()=>i?.(!0)});return{room:s,ydoc:o,provider:a,destroy(){a.destroy(),o.destroy()}}}function Ui({documentId:e,token:t,url:n=Ni()}){const r=Li("plate",e);return[{type:"hocuspocus",options:{name:r,token:t,url:n}},{type:"indexeddb",options:{docName:r}}]}var ji=["#e11d48","#0891b2","#7c3aed","#ea580c","#16a34a","#2563eb","#db2777","#ca8a04"];function Fi(e){let t=0;for(let n=0;n<e.length;n++)t=31*t+e.charCodeAt(n)|0;return ji[Math.abs(t)%ji.length]}var Bi={bold:"bold",italic:"italic",underline:"underline",strike:"strike",code:"code",superscript:"superscript",subscript:"subscript",highlight:"highlight","text-color":"textStyle"},Wi={paragraph:{name:"paragraph"},"heading-1":{name:"heading",attrs:{level:1}},"heading-2":{name:"heading",attrs:{level:2}},"heading-3":{name:"heading",attrs:{level:3}},"heading-4":{name:"heading",attrs:{level:4}},"heading-5":{name:"heading",attrs:{level:5}},"heading-6":{name:"heading",attrs:{level:6}},blockquote:{name:"blockquote"},"code-block":{name:"codeBlock"},"bullet-list":{name:"bulletList"},"ordered-list":{name:"orderedList"},"task-list":{name:"taskList"},table:{name:"table"},callout:{name:"callout"},columns:{name:"columns"}},Hi={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},qi={"table.add-row-before":"addRowBefore","table.add-row-after":"addRowAfter","table.delete-row":"deleteRow","table.add-column-before":"addColumnBefore","table.add-column-after":"addColumnAfter","table.delete-column":"deleteColumn","table.merge-cells":"mergeCells","table.split-cell":"splitCell","table.toggle-header-row":"toggleHeaderRow","table.delete":"deleteTable"};function Vi(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function zi(e){return{engine:"tiptap",execute(t,n){!function(e,t,n){const r=()=>e.chain().focus(),i=e.commands,s=qi[t];if(s)return void r()[s]?.().run();const o=Hi[t];if(o)r().setTextAlign?.(o).run();else switch(t){case"undo":return void i.undo?.();case"redo":return void i.redo?.();case"bold":return void r().toggleBold().run();case"italic":return void r().toggleItalic().run();case"underline":return void r().toggleUnderline?.().run();case"strike":return void r().toggleStrike().run();case"code":return void r().toggleCode().run();case"superscript":return void r().toggleSuperscript?.().run();case"subscript":return void r().toggleSubscript?.().run();case"text-color":{const t=n?.value??"#ef4444";return void(e.isActive("textStyle",{color:t})?r().unsetColor?.().run():r().setColor?.(t).run())}case"highlight":{const t=n?.value??"#fde047";return void(e.isActive("highlight")?r().unsetHighlight?.().run():r().setHighlight?.({color:t}).run())}case"clear-formatting":return void r().clearNodes().unsetAllMarks().run();case"paragraph":return void r().setParagraph().run();case"heading-1":case"heading-2":case"heading-3":case"heading-4":case"heading-5":case"heading-6":{const e=Number(t.slice(8));return void r().toggleHeading({level:e}).run()}case"blockquote":return void r().toggleBlockquote().run();case"code-block":return void r().toggleCodeBlock().run();case"bullet-list":return void r().toggleBulletList().run();case"ordered-list":return void r().toggleOrderedList().run();case"task-list":return void r().toggleTaskList?.().run();case"indent":return void r().indent?.().run();case"outdent":return void r().outdent?.().run();case"link":{const e=Vi(n,"Link URL");if(!e)return;return void r().extendMarkRange("link").setLink({href:e}).run()}case"image":{const e=Vi(n,"Image URL");if(!e)return;const t=r();return void("function"==typeof t.setImageInline?t.setImageInline({src:e}).run():t.setImage?.({src:e}).run())}case"video":{const e=Vi(n,"Video URL");if(!e)return;return void r().setVideo?.({src:e}).run()}case"table":return void r().insertTable?.({rows:3,cols:3,withHeaderRow:!0}).run();case"horizontal-rule":return void r().setHorizontalRule().run();case"emoji":return void r().insertContent(":").run();case"math":return void r().setKatex?.({text:n?.value??""}).run();case"callout":return void r().setCallout?.({type:"note",title:"",body:""}).run();case"columns":return void r().insertColumns?.({cols:2}).run();case"transcribe":return void i.toggleTranscribe?.();default:;}}(e,t,n)},isActive:t=>function(e,t){const n=Hi[t];if(n)return e.isActive({textAlign:n});const r=Wi[t];if(r)return e.isActive(r.name,r.attrs);const i=Bi[t];return i?"text-color"===t?!!e.getAttributes("textStyle").color:e.isActive(i):"link"===t?e.isActive("link"):"transcribe"===t&&!!Pe(e)?.listening}(e,t),isEnabled:t=>function(e,t){const n=function(e){switch(e){case"highlight":return"highlight";case"text-color":return"color";case"superscript":return"superscript";case"subscript":return"subscript";case"task-list":return"taskList";case"link":return"link";case"image":return"image";case"video":return"video";case"table":return"table";case"emoji":return"emoji";case"math":return"katex";case"callout":return"callout";case"columns":return"columns";case"transcribe":return"transcribe";case"indent":case"outdent":return"indent";case"align-left":case"align-center":case"align-right":case"align-justify":return"textAlign";default:return}}(t);if(n&&!function(e,t){return e.extensionManager.extensions.some(e=>e.name===t)}(e,n))return!1;if("undo"===t)return e.can().undo();if("redo"===t)return e.can().redo();if("transcribe"===t)return Le();const r=qi[t];return r?!!e.isActive("table")&&Boolean(e.can()[r]?.()):e.isEditable}(e,t),getValue:t=>function(e,t){return"text-color"===t?e.getAttributes("textStyle").color:"highlight"===t?e.getAttributes("highlight").color:"link"===t?e.getAttributes("link").href:void 0}(e,t),subscribe(t){e.on("transaction",t),e.on("selectionUpdate",t);const n=Me(e,t);return()=>{e.off("transaction",t),e.off("selectionUpdate",t),n()}}}}function $i(e){return"string"==typeof e&&/^#[0-9a-fA-F]{6}$/.test(e)}var Yi=e=>Array.from(e.entries()).map(([e,t])=>t&&t.user?{clientId:e,...t.user}:{clientId:e}),Ji=()=>null,Qi=e=>({...e,color:$i(e.color)?e.color:"transparent"}),Ki=Ln.create({name:"collaborationCaret",priority:999,addOptions:()=>({provider:null,user:{name:null,color:null},render:e=>{const t=document.createElement("span"),{color:n}=Qi(e);t.classList.add("collaboration-carets__caret"),t.style.borderColor=n;const r=document.createElement("div");return r.classList.add("collaboration-carets__label"),r.style.backgroundColor=n,r.insertBefore(document.createTextNode(e.name),null),t.insertBefore(r,null),t},selectionRender:e=>$i(e.color)?zt(e):{},onUpdate:Ji}),onCreate(){if(this.options.onUpdate,!this.options.provider)throw new Error('The "provider" option is required for the CollaborationCaret extension')},addStorage:()=>({users:[]}),addCommands(){return{updateUser:e=>()=>(this.options.provider.awareness.setLocalStateField("user",e),!0),user:e=>({editor:t})=>t.commands.updateUser(e)}},addProseMirrorPlugins(){const{provider:e}=this.options,t=this.storage,n=this.options.user;return[new Mn({key:new Nn("collaborationCaretAwarenessListener"),view:()=>{const r=()=>{t.users=Yi(e.awareness.states)};return e.awareness.setLocalStateField("user",n),t.users=Yi(e.awareness.states),e.awareness.on("update",r),{destroy:()=>{e.awareness.off("update",r),t.users=[]}}}}),nn(e.awareness,{cursorBuilder:e=>this.options.render(Qi(e)),selectionBuilder:e=>this.options.selectionRender(Qi(e))})]}});function Gi({documentId:e,initialContent:t="",user:n,authToken:r,className:i}){const[s,o]=En.useState(null),[a,d]=En.useState(null),u=Li("tiptap",e),f=n.color??Fi(n.id);En.useEffect(()=>{if(!r)return;const t=Ii({engine:"tiptap",documentId:e,token:r});return d(t),()=>{d(null),t.destroy()}},[r,e]);const g=En.useMemo(()=>{const e=h(c());return a?function(e,t,n){return[...e.filter(e=>"undoRedo"!==e?.name),dn.configure({document:t.ydoc}),Ki.configure({provider:t.provider,user:n})]}(e,a,{name:n.name,color:f}):e},[a,n.name,f]),p=En.useMemo(()=>s?zi(s):Ir("tiptap"),[s]);/* @__PURE__ */
|
|
14
|
+
return Un("div",{className:`flex h-full min-h-0 w-full flex-col ${i??""}`,"data-room":u,children:/* @__PURE__ */Un(l,{className:"flex min-h-0 flex-1 flex-col",extensions:g,immediatelyRender:!1,initialContent:a?void 0:t,onEditor:o,rebuildKey:a?`collab:${u}`:"local",textDirection:"auto",children:({EditorSurface:e})=>/* @__PURE__ */jn(In,{children:[/* @__PURE__ */Un(zr,{adapter:p}),/* @__PURE__ */Un("div",{className:"relative min-h-0 flex-1 overflow-auto",children:/* @__PURE__ */Un(e,{className:"h-full"})})]})})})}var Xi={bold:X.bold,italic:X.italic,underline:X.underline,strike:X.strikethrough,code:X.code,superscript:X.sup,subscript:X.sub,highlight:X.highlight,"text-color":X.color},Zi={superscript:X.sub,subscript:X.sup},es={paragraph:X.p,"heading-1":X.h1,"heading-2":X.h2,"heading-3":X.h3,"heading-4":X.h4,"heading-5":X.h5,"heading-6":X.h6,blockquote:X.blockquote},ts={"bullet-list":Z.Disc,"ordered-list":Z.Decimal,"task-list":X.listTodo},ns={"bullet-list":[Z.Disc,Z.Circle,Z.Square],"ordered-list":[Z.Decimal,Z.LowerAlpha,Z.UpperAlpha,Z.LowerRoman,Z.UpperRoman],"task-list":[X.listTodo]},rs={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},is=/* @__PURE__ */new Set(["table.add-row-before","table.add-row-after","table.delete-row","table.add-column-before","table.add-column-after","table.delete-column","table.merge-cells","table.split-cell","table.toggle-header-row","table.delete"]);function ss(e){return!!e.selection&&Boolean(be(e))}function os(e){if(!ss(e))return{canMerge:!1,canSplit:!1};const t=D(e);if(!t?.length)return{canMerge:!1,canSplit:!1};const n=t.map(([e])=>e);if(n.length>1){const{maxCol:t,maxRow:r,minCol:i,minRow:s}=g(e,n),o=n.reduce((e,t)=>e+W(t)*we(t),0)===(t-i+1)*(r-s+1);return{canMerge:e.api.isExpanded()&&o,canSplit:!1}}const[r]=n;return{canMerge:!1,canSplit:W(r)>1||we(r)>1}}function as(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function cs(e,t){const n=function(e){if(is.has(e)||"table"===e)return X.table;switch(e){case"highlight":return X.highlight;case"text-color":return X.color;case"link":return X.link;case"image":return X.img;case"video":return X.video;case"math":return X.equation;case"callout":return X.callout;case"columns":return X.columnGroup;case"transcribe":return"transcribe";case"emoji":return X.emoji;case"code-block":return X.codeBlock;case"bullet-list":case"ordered-list":case"task-list":return X.list;case"indent":case"outdent":return X.indent;case"align-left":case"align-center":case"align-right":case"align-justify":return X.textAlign;default:return}}(t);return!(n&&!function(e,t){return Boolean(e.plugins?.[t])}(e,n))&&("undo"===t?e.history.undos.length>0:"redo"===t?e.history.redos.length>0:"transcribe"===t?de()&&!e.api.isReadOnly?.():"table.merge-cells"===t?os(e).canMerge:"table.split-cell"===t?os(e).canSplit:is.has(t)?ss(e):!e.api.isReadOnly?.())}function ls(e){return{engine:"plate",execute(t,n){!function(e,t,n){e.tf.focus();const r=Xi[t];if(r&&"text-color"!==t&&"highlight"!==t)return void e.tf.toggleMark(r,{remove:Zi[t]});const i=es[t];if(i)return void e.tf.toggleBlock(i,i===X.blockquote?{wrap:!0}:void 0);const s=ts[t];if(s)return void T(e,{listStyleType:s});const o=rs[t];if(o)e.getTransforms(w).textAlign.setNodes(o);else switch(t){case"undo":return void e.tf.undo();case"redo":return void e.tf.redo();case"text-color":{const t=n?.value??"#ef4444";return void(e.api.marks()?.[X.color]===t?e.tf.removeMarks(X.color):e.tf.addMarks({[X.color]:t}))}case"highlight":return void(e.api.marks()?.[X.highlight]?e.tf.removeMarks(X.highlight):e.tf.addMarks({[X.highlight]:n?.value??"#fde047"}));case"clear-formatting":return e.tf.removeMarks(Object.values(Xi)),void e.tf.toggleBlock(X.p);case"code-block":return void f(e);case"link":return void(n?.value?v(e,{url:n.value}):y(e,{focused:!0}));case"image":{const t=as(n,"Image URL");if(!t)return;return void I(e,t)}case"video":{const t=as(n,"Video URL");if(!t)return;return void N(e,{select:!0,type:X.video,url:t})}case"table":return void O(e,{colCount:3,rowCount:3},{select:!0});case"horizontal-rule":return void e.tf.insertNodes({children:[{text:""}],type:X.hr});case"emoji":return void e.tf.insertText(":");case"math":return void u(e,{select:!0});case"callout":return void L(e,{select:!0});case"columns":return void _e(e,{columns:2,select:!0});case"transcribe":return void oe(e).toggle();case"indent":return void C(e);case"outdent":return void R(e);case"table.add-row-before":return void p(e,{before:!0});case"table.add-row-after":return void p(e);case"table.delete-row":return void ye(e);case"table.add-column-before":return void m(e,{before:!0});case"table.add-column-after":return void m(e);case"table.delete-column":return void j(e);case"table.merge-cells":return void A(e);case"table.split-cell":return void ee(e);case"table.toggle-header-row":{const t=be(e);if(!t)return;const[n,r]=t;return void e.tf.setNodes({headerRow:!n.headerRow},{at:r})}case"table.delete":return void ve(e);default:;}}(e,t,n)},isActive(t){if("transcribe"===t)return oe(e).getState().listening;if(!e.selection)return!1;try{return function(e,t){if("task-list"===t)return E(e);const n=ns[t];if(n)return S(e,n);const r=Xi[t];if(r)return Boolean(e.api.marks()?.[r]);const i=es[t];if(i)return e.api.some({match:{type:i}});if("code-block"===t)return e.api.some({match:{type:X.codeBlock}});if("table"===t)return ss(e);if("callout"===t)return e.api.some({match:{type:X.callout}});if("columns"===t)return e.api.some({match:{type:X.column}});if("link"===t)return e.api.some({match:{type:X.link}});if("transcribe"===t)return oe(e).getState().listening;const s=rs[t];return!!s&&e.api.some({match:e=>e[X.textAlign]===s})}(e,t)}catch{return!1}},isEnabled(t){try{return cs(e,t)}catch{return!1}},getValue(t){if(e.selection)try{return function(e,t){const n=e.api.marks();return"text-color"===t?n?.[X.color]:"highlight"===t?n?.[X.highlight]:void 0}(e,t)}catch{return}},subscribe(t){const n=e.apply;let r=!1;e.apply=i=>{n.call(e,i),r||(r=!0,queueMicrotask(()=>{r=!1,t()}))};const i=oe(e).subscribe(t);return()=>{e.apply=n,i()}}}}var hs,ds=class{constructor(e,t){this.clock=e,this.len=t}},us=class{constructor(){this.clients=/* @__PURE__ */new Map}},fs=(e,t,n)=>t.clients.forEach((t,r)=>{const i=e.doc.store.clients.get(r);if(null!=i){const r=i[i.length-1],s=r.id.clock+r.length;for(let o=0,a=t[o];o<t.length&&a.clock<s;a=t[++o])vo(e,i,a.clock,a.len,n)}}),gs=(e,t)=>{const n=e.clients.get(t.client);return void 0!==n&&null!==((e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const i=ot((n+r)/2),s=e[i],o=s.clock;if(o<=t){if(t<o+s.len)return i;n=i+1}else r=i-1}return null})(n,t.clock)},ps=e=>{e.clients.forEach(e=>{let t,n;for(e.sort((e,t)=>e.clock-t.clock),t=1,n=1;t<e.length;t++){const r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new ds(r.clock,ut(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},ms=e=>{const t=new us;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){const s=r.slice();for(let t=n+1;t<e.length;t++)pt(s,e[t].clients.get(i)||[]);t.clients.set(i,s)}});return ps(t),t},ys=(e,t,n,r)=>{cn(e.clients,t,()=>[]).push(new ds(n,r))},bs=()=>new us,ws=(e,t)=>{ht(e.restEncoder,t.clients.size),Sn(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),ht(e.restEncoder,t);const r=n.length;ht(e.restEncoder,r);for(let i=0;i<r;i++){const t=n[i];e.writeDsClock(t.clock),e.writeDsLen(t.len)}})},vs=e=>{const t=new us,n=Ut(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=Ut(e.restDecoder),r=Ut(e.restDecoder);if(r>0){const i=cn(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new ds(e.readDsClock(),e.readDsLen()))}}return t},_s=(e,t,n)=>{const r=new us,i=Ut(e.restDecoder);for(let s=0;s<i;s++){e.resetDsCurVal();const i=Ut(e.restDecoder),s=Ut(e.restDecoder),o=n.clients.get(i)||[],a=fo(n,i);for(let n=0;n<s;n++){const n=e.readDsClock(),s=n+e.readDsLen();if(n<a){a<s&&ys(r,i,a,s-a);let e=po(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,lc(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<s);)c.deleted||(s<c.id.clock+c.length&&o.splice(e,0,lc(t,c,s-c.id.clock)),c.delete(t))}else ys(r,i,n,s-n)}}if(r.clients.size>0){const e=new Os;return ht(e.restEncoder,0),ws(e,r),e.toUint8Array()}return null},ks=ft,Cs=class e extends it{constructor({guid:e=Ne(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:s=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=ks(),this.guid=e,this.collectionid=t,this.share=/* @__PURE__ */new Map,this.store=new ho,this._transaction=null,this._transactionCleanups=[],this.subdocs=/* @__PURE__ */new Set,this._item=null,this.shouldLoad=o,this.autoLoad=s,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=an(e=>{this.on("load",()=>{this.isLoaded=!0,e(this)})});const a=()=>an(e=>{const t=n=>{void 0!==n&&!0!==n||(this.off("sync",t),e())};this.on("sync",t)});this.on("sync",e=>{!1===e&&this.isSynced&&(this.whenSynced=a()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=a()}load(){const e=this._item;null===e||this.shouldLoad||Ao(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Sn(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Ao(this,e,t)}get(e,t=Go){const n=cn(this.share,e,()=>{const e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==Go&&r!==t){if(r===Go){const r=new t;r._map=n._map,n._map.forEach(e=>{for(;null!==e;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;null!==e;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw new Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=""){return this.get(e,pa)}getText(e=""){return this.get(e,La)}getMap(e=""){return this.get(e,ya)}getXmlElement(e=""){return this.get(e,Ia)}getXmlFragment(e=""){return this.get(e,Na)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Sn(this.subdocs).forEach(e=>e.destroy());const t=this._item;if(null!==t){this._item=null;const n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,Ao(t.parent.doc,e=>{const r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}},Ss=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Ut(this.restDecoder)}readDsLen(){return Ut(this.restDecoder)}},Es=class extends Ss{readLeftID(){return Js(Ut(this.restDecoder),Ut(this.restDecoder))}readRightID(){return Js(Ut(this.restDecoder),Ut(this.restDecoder))}readClient(){return Ut(this.restDecoder)}readInfo(){return Nt(this.restDecoder)}readString(){return gn(this.restDecoder)}readParentInfo(){return 1===Ut(this.restDecoder)}readTypeRef(){return Ut(this.restDecoder)}readLen(){return Ut(this.restDecoder)}readAny(){return hn(this.restDecoder)}readBuf(){return Yt(Bt(this.restDecoder))}readJSON(){return JSON.parse(gn(this.restDecoder))}readKey(){return gn(this.restDecoder)}},As=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Ut(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Ut(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Ts=class extends As{constructor(e){super(e),this.keys=[],Ut(e),this.keyClockDecoder=new jt(Bt(e)),this.clientDecoder=new ln(Bt(e)),this.leftClockDecoder=new jt(Bt(e)),this.rightClockDecoder=new jt(Bt(e)),this.infoDecoder=new un(Bt(e),Nt),this.stringDecoder=new tn(Bt(e)),this.parentInfoDecoder=new un(Bt(e),Nt),this.typeRefDecoder=new ln(Bt(e)),this.lenDecoder=new ln(Bt(e))}readLeftID(){return new $s(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new $s(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return 1===this.parentInfoDecoder.read()}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return hn(this.restDecoder)}readBuf(){return Bt(this.restDecoder)}readJSON(){return hn(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const e=this.stringDecoder.read();return this.keys.push(e),e}}},xs=class{constructor(){this.restEncoder=Lt()}toUint8Array(){return yt(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){ht(this.restEncoder,e)}writeDsLen(e){ht(this.restEncoder,e)}},Rs=class extends xs{writeLeftID(e){ht(this.restEncoder,e.client),ht(this.restEncoder,e.clock)}writeRightID(e){ht(this.restEncoder,e.client),ht(this.restEncoder,e.clock)}writeClient(e){ht(this.restEncoder,e)}writeInfo(e){bn(this.restEncoder,e)}writeString(e){qe(this.restEncoder,e)}writeParentInfo(e){ht(this.restEncoder,e?1:0)}writeTypeRef(e){ht(this.restEncoder,e)}writeLen(e){ht(this.restEncoder,e)}writeAny(e){We(this.restEncoder,e)}writeBuf(e){Kt(this.restEncoder,e)}writeJSON(e){qe(this.restEncoder,JSON.stringify(e))}writeKey(e){qe(this.restEncoder,e)}},Ds=class{constructor(){this.restEncoder=Lt(),this.dsCurrVal=0}toUint8Array(){return yt(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,ht(this.restEncoder,t)}writeDsLen(e){0===e&&Vt(),ht(this.restEncoder,e-1),this.dsCurrVal+=e}},Os=class extends Ds{constructor(){super(),this.keyMap=/* @__PURE__ */new Map,this.keyClock=0,this.keyClockEncoder=new Ht,this.clientEncoder=new kn,this.leftClockEncoder=new Ht,this.rightClockEncoder=new Ht,this.infoEncoder=new Dt(bn),this.stringEncoder=new mn,this.parentInfoEncoder=new Dt(bn),this.typeRefEncoder=new kn,this.lenEncoder=new kn}toUint8Array(){const e=Lt();return ht(e,0),Kt(e,this.keyClockEncoder.toUint8Array()),Kt(e,this.clientEncoder.toUint8Array()),Kt(e,this.leftClockEncoder.toUint8Array()),Kt(e,this.rightClockEncoder.toUint8Array()),Kt(e,yt(this.infoEncoder)),Kt(e,this.stringEncoder.toUint8Array()),Kt(e,yt(this.parentInfoEncoder)),Kt(e,this.typeRefEncoder.toUint8Array()),Kt(e,this.lenEncoder.toUint8Array()),wt(e,yt(this.restEncoder)),yt(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){We(this.restEncoder,e)}writeBuf(e){Kt(this.restEncoder,e)}writeJSON(e){We(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);void 0===t?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}},Ps=(e,t,n)=>{const r=/* @__PURE__ */new Map;n.forEach((e,n)=>{fo(t,n)>e&&r.set(n,e)}),uo(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),ht(e.restEncoder,r.size),Sn(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{((e,t,n,r)=>{r=ut(r,t[0].id.clock);const i=po(t,r);ht(e.restEncoder,t.length-i),e.writeClient(n),ht(e.restEncoder,r);const s=t[i];s.write(e,r-s.id.clock);for(let o=i+1;o<t.length;o++)t[o].write(e,0)})(e,t.clients.get(n),n,r)})},Ls=(e,t,n,r=new Ts(e))=>Ao(t,e=>{e.local=!1;let t=!1;const n=e.doc,i=n.store,s=((e,t)=>{const n=nt(),r=Ut(e.restDecoder);for(let i=0;i<r;i++){const r=Ut(e.restDecoder),i=new Array(r),s=e.readClient();let o=Ut(e.restDecoder);n.set(s,{i:0,refs:i});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();i[n]=new Wa(Js(s,o),t),o+=t;break}case 10:{const t=Ut(e.restDecoder);i[n]=new pc(Js(s,o),t),o+=t;break}default:{const a=!(192&r),c=new uc(Js(s,o),null,128&~r?null:e.readLeftID(),null,64&~r?null:e.readRightID(),a?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,!a||32&~r?null:e.readString(),fc(e,r));i[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let i=Sn(n.keys()).sort((e,t)=>e-t);if(0===i.length)return null;const s=()=>{if(0===i.length)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;){if(i.pop(),!(i.length>0))return null;e=n.get(i[i.length-1])}return e};let o=s();if(null===o)return null;const a=new ho,c=/* @__PURE__ */new Map,l=(e,t)=>{const n=c.get(e);(null==n||n>t)&&c.set(e,t)};let h=o.refs[o.i++];const d=/* @__PURE__ */new Map,u=()=>{for(const e of r){const t=e.id.client,r=n.get(t);r?(r.i--,a.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):a.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(h.constructor!==pc){const i=cn(d,h.id.client,()=>fo(t,h.id.client))-h.id.clock;if(i<0)r.push(h),l(h.id.client,h.id.clock-1),u();else{const s=h.getMissing(e,t);if(null!==s){r.push(h);const e=n.get(s)||{refs:[],i:0};if(e.refs.length!==e.i){h=e.refs[e.i++];continue}l(s,fo(t,s)),u()}else(0===i||i<h.length)&&(h.integrate(e,i),d.set(h.id.client,h.id.clock+h.length))}}if(r.length>0)h=r.pop();else if(null!==o&&o.i<o.refs.length)h=o.refs[o.i++];else{if(o=s(),null===o)break;h=o.refs[o.i++]}}if(a.clients.size>0){const e=new Os;return Ps(e,a,/* @__PURE__ */new Map),ht(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null})(e,i,s),a=i.pendingStructs;if(a){for(const[e,n]of a.missing)if(n<fo(i,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=a.missing.get(e);(null==n||n>t)&&a.missing.set(e,t)}a.update=No([a.update,o.update])}}else i.pendingStructs=o;const c=_s(r,e,i);if(i.pendingDs){const t=new Ts($t(i.pendingDs));Ut(t.restDecoder);const n=_s(t,e,i);i.pendingDs=c&&n?No([c,n]):c||n}else i.pendingDs=c;if(t){const t=i.pendingStructs.update;i.pendingStructs=null,Ms(e.doc,t)}},n,!1),Ms=(e,t,n,r=Ts)=>{const i=$t(t);Ls(i,e,n,new r(i))},Ns=(e,t,n)=>Ms(e,t,n,Es),Is=(e,t,n=/* @__PURE__ */new Map)=>{Ps(e,t.store,n),ws(e,(e=>{const t=bs();return e.clients.forEach((e,n)=>{const r=[];for(let t=0;t<e.length;t++){const n=e[t];if(n.deleted){const i=n.id.clock;let s=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[1+ ++t])s+=n.length;r.push(new ds(i,s))}}r.length>0&&t.clients.set(n,r)}),t})(t.store))},Us=(e,t)=>((e,t=new Uint8Array([0]),n=new Os)=>{const r=js(t);Is(n,e,r);const i=[n.toUint8Array()];if(e.store.pendingDs&&i.push(e.store.pendingDs),e.store.pendingStructs&&i.push(Io(e.store.pendingStructs.update,t)),i.length>1){if(n.constructor===Rs)return Lo(i.map((e,t)=>0===t?e:Bo(e)));if(n.constructor===Os)return No(i)}return i[0]})(e,t,new Rs),js=e=>(e=>{const t=/* @__PURE__ */new Map,n=Ut(e.restDecoder);for(let r=0;r<n;r++){const n=Ut(e.restDecoder),r=Ut(e.restDecoder);t.set(n,r)}return t})(new Ss($t(e))),Fs=(e,t)=>(ht(e.restEncoder,t.size),Sn(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{ht(e.restEncoder,t),ht(e.restEncoder,n)}),e),Bs=(e,t=new Ds)=>(e instanceof Map?Fs(t,e):((e,t)=>{Fs(e,uo(t.store))})(t,e),t.toUint8Array()),Ws=class{constructor(){this.l=[]}},Hs=()=>new Ws,qs=(e,t)=>e.l.push(t),Vs=(e,t)=>{const n=e.l;n.length;e.l=n.filter(e=>t!==e),e.l.length},zs=(e,t,n)=>Xe(e.l,[t,n]),$s=class{constructor(e,t){this.client=e,this.clock=t}},Ys=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,Js=(e,t)=>new $s(e,t),Qs=(e,t)=>{ht(e,t.client),ht(e,t.clock)},Ks=e=>Js(Ut(e),Ut(e)),Gs=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Vt()},Xs=(e,t)=>{for(;null!==t;){if(t.parent===e)return!0;t=t.parent._item}return!1},Zs=class{constructor(e,t,n,r=0){this.type=e,this.tname=t,this.item=n,this.assoc=r}},eo=class{constructor(e,t,n=0){this.type=e,this.index=t,this.assoc=n}},to=(e,t,n)=>{let r=null,i=null;return null===e._item?i=Gs(e):r=Js(e._item.id.client,e._item.id.clock),new Zs(r,i,t,n)},no=(e,t,n=0)=>{let r=e._start;if(n<0){if(0===t)return to(e,null,n);t--}for(;null!==r;){if(!r.deleted&&r.countable){if(r.length>t)return to(e,Js(r.id.client,r.id.clock+t),n);t-=r.length}if(null===r.right&&n<0)return to(e,r.lastId,n);r=r.right}return to(e,null,n)},ro=e=>{const t=Lt();return((e,t)=>{const{type:n,tname:r,item:i,assoc:s}=t;if(null!==i)ht(e,0),Qs(e,i);else if(null!==r)bn(e,1),qe(e,r);else{if(null===n)throw Vt();bn(e,2),Qs(e,n)}ze(e,s)})(t,e),yt(t)},io=e=>(e=>{let t=null,n=null,r=null;switch(Ut(e)){case 0:r=Ks(e);break;case 1:n=gn(e);break;case 2:t=Ks(e)}const i=Ot(e)?Xt(e):0;return new Zs(t,n,r,i)})($t(e)),so=(e,t,n=!0)=>{const r=t.store,i=e.item,s=e.type,o=e.tname,a=e.assoc;let c=null,l=0;if(null!==i){if(fo(r,i.client)<=i.clock)return null;const e=n?ac(r,i):((e,t)=>{const n=mo(e,t);return{item:n,diff:t.clock-n.id.clock}})(r,i),t=e.item;if(!(t instanceof uc))return null;if(c=t.parent,null===c._item||!c._item.deleted){l=t.deleted||!t.countable?0:e.diff+(a>=0?0:1);let n=t.left;for(;null!==n;)!n.deleted&&n.countable&&(l+=n.length),n=n.left}}else{if(null!==o)c=t.get(o);else{if(null===s)throw Vt();{if(fo(r,s.client)<=s.clock)return null;const{item:e}=n?ac(r,s):{item:mo(r,s)};if(!(e instanceof uc&&e.content instanceof oc))return null;c=e.content.type}}l=a>=0?c._length:0}return((e,t,n=0)=>new eo(e,t,n))(c,l,e.assoc)},oo=(e,t)=>e===t||null!==e&&null!==t&&e.tname===t.tname&&Ys(e.item,t.item)&&Ys(e.type,t.type)&&e.assoc===t.assoc,ao=class{constructor(e,t){this.ds=e,this.sv=t}},co=(hs=bs(),new ao(hs,/* @__PURE__ */new Map),(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!gs(t.ds,e.id)),lo=(e,t)=>{const n=cn(e.meta,lo,_t),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<fo(r,n)&&bo(e,Js(n,t))}),fs(e,t.ds,e=>{}),n.add(t))},ho=class{constructor(){this.clients=/* @__PURE__ */new Map,this.pendingStructs=null,this.pendingDs=null}},uo=e=>{const t=/* @__PURE__ */new Map;return e.clients.forEach((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},fo=(e,t)=>{const n=e.clients.get(t);if(void 0===n)return 0;const r=n[n.length-1];return r.id.clock+r.length},go=(e,t)=>{let n=e.clients.get(t.id.client);if(void 0===n)n=[],e.clients.set(t.id.client,n);else{const e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw Vt()}n.push(t)},po=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=ot(t/(s+i.length-1)*r);for(;n<=r;){if(i=e[o],s=i.id.clock,s<=t){if(t<s+i.length)return o;n=o+1}else r=o-1;o=ot((n+r)/2)}throw Vt()},mo=(e,t)=>{const n=e.clients.get(t.client);return n[po(n,t.clock)]},yo=(e,t,n)=>{const r=po(t,n),i=t[r];return i.id.clock<n&&i instanceof uc?(t.splice(r+1,0,lc(e,i,n-i.id.clock)),r+1):r},bo=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[yo(e,n,t.clock)]},wo=(e,t,n)=>{const r=t.clients.get(n.client),i=po(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==Wa&&r.splice(i+1,0,lc(e,s,n.clock-s.id.clock+1)),s},vo=(e,t,n,r,i)=>{if(0===r)return;const s=n+r;let o,a=yo(e,t,n);do{o=t[a++],s<o.id.clock+o.length&&yo(e,t,s),i(o)}while(a<t.length&&t[a].id.clock<s)},_o=class{constructor(e,t,n){this.doc=e,this.deleteSet=new us,this.beforeState=uo(e.store),this.afterState=/* @__PURE__ */new Map,this.changed=/* @__PURE__ */new Map,this.changedParentTypes=/* @__PURE__ */new Map,this._mergeStructs=[],this.origin=t,this.meta=/* @__PURE__ */new Map,this.local=n,this.subdocsAdded=/* @__PURE__ */new Set,this.subdocsRemoved=/* @__PURE__ */new Set,this.subdocsLoaded=/* @__PURE__ */new Set,this._needFormattingCleanup=!1}},ko=(e,t)=>!(0===t.deleteSet.clients.size&&!Et(t.afterState,(e,n)=>t.beforeState.get(n)!==e))&&(ps(t.deleteSet),((e,t)=>{Ps(e,t.doc.store,t.beforeState)})(e,t),ws(e,t.deleteSet),!0),Co=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&cn(e.changed,t,_t).add(n)},So=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0&&(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n));n=r,r=e[--i-1])n instanceof uc&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const s=t-i;return s&&e.splice(t+1-s,s),s},Eo=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,i=r.store,s=n.deleteSet,o=n._mergeStructs;try{ps(s),n.afterState=uo(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach((t,r)=>e.push(()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(null===r._item||!r._item.deleted)&&((t=t.filter(e=>null===e.target._item||!e.target._item.deleted)).forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{zs(r._dEH,t,n)}))}),e.push(()=>r.emit("afterTransaction",[n,r])),e.push(()=>{n._needFormattingCleanup&&Da(n)})}),Xe(e,[])}finally{r.gc&&((e,t,n)=>{for(const[r,i]of e.clients.entries()){const e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){const s=i[r],o=s.clock+s.len;for(let r=po(e,s.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){const i=e[r];if(s.clock+s.len<=i.id.clock)break;i instanceof uc&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}})(s,i,r.gcFilter),((e,t)=>{e.clients.forEach((e,n)=>{const r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){const n=e[t];for(let e=Ye(r.length-1,1+po(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+So(r,e)}})})(s,i),n.afterState.forEach((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=i.clients.get(t),n=ut(po(e,r),1);for(let t=e.length-1;t>=n;)t-=1+So(e,t)}});for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=i.clients.get(t),s=po(r,n);s+1<r.length&&So(r,s+1)>1||s>0&&So(r,s)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(Be(He,bt,"[yjs] ",Qt,lt,"Changed the client-id because another client seems to be using it."),r.clientID=ks()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new Rs;ko(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new Os;ko(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:l}=n;(a.size>0||l.size>0||c.size>0)&&(a.forEach(e=>{e.clientID=r.clientID,null==e.collectionid&&(e.collectionid=r.collectionid),r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit("subdocs",[{loaded:c,added:a,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):Eo(e,t+1)}}},Ao=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;null===e._transaction&&(s=!0,e._transaction=new _o(e,n,r),i.push(e._transaction),1===i.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(s){const t=e._transaction===i[0];e._transaction=null,t&&Eo(i,0)}}return o},To=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=/* @__PURE__ */new Map}},xo=(e,t,n)=>{fs(e,n.deletions,n=>{n instanceof uc&&t.scope.some(t=>t===e.doc||Xs(t,n))&&cc(n,!1)})},Ro=(e,t,n)=>{let r=null;const i=e.doc,s=e.scope;Ao(i,n=>{for(;t.length>0&&null===e.currStackItem;){const r=i.store,o=t.pop(),a=/* @__PURE__ */new Set,c=[];let l=!1;fs(n,o.insertions,e=>{if(e instanceof uc){if(null!==e.redone){let{item:t,diff:i}=ac(r,e.id);i>0&&(t=bo(n,Js(t.id.client,t.id.clock+i))),e=t}!e.deleted&&s.some(t=>t===n.doc||Xs(t,e))&&c.push(e)}}),fs(n,o.deletions,e=>{e instanceof uc&&s.some(t=>t===n.doc||Xs(t,e))&&!gs(o.insertions,e.id)&&a.add(e)}),a.forEach(t=>{l=null!==dc(n,t,a,o.insertions,e.ignoreRemoteMapChanges,e)||l});for(let t=c.length-1;t>=0;t--){const r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);const o=e.currStackItem;if(null!=o){const t=r.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o},Do=class extends it{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=/* @__PURE__ */new Set([null]),ignoreRemoteMapChanges:s=!1,doc:o=(Fe(e)?e[0].doc:e instanceof Cs?e:e.doc)}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=s,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!(this.captureTransaction(e)&&this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)&&(this.trackedOrigins.has(e.origin)||e.origin&&this.trackedOrigins.has(e.origin.constructor))))return;const t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);const i=new us;e.afterState.forEach((t,n)=>{const r=e.beforeState.get(n)||0,s=t-r;s>0&&ys(i,n,r,s)});const s=At();let o=!1;if(this.lastChange>0&&s-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){const t=r[r.length-1];t.deletions=ms([t.deletions,e.deleteSet]),t.insertions=ms([t.insertions,i])}else r.push(new To(e.deleteSet,i)),o=!0;t||n||(this.lastChange=s),fs(e,e.deleteSet,t=>{t instanceof uc&&this.scope.some(n=>n===e.doc||Xs(n,t))&&cc(t,!0)});const a=[{stackItem:r[r.length-1],origin:e.origin,type:t?"redo":"undo",changedParentTypes:e.changedParentTypes},this];o?this.emit("stack-item-added",a):this.emit("stack-item-updated",a)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const t=new Set(this.scope);(e=Fe(e)?e:[e]).forEach(e=>{t.has(e)||(t.add(e),(e instanceof Go?e.doc!==this.doc:e!==this.doc)&&yn("[yjs#509] Not same Y.Doc"),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>xo(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>xo(n,this,e)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){let e;this.undoing=!0;try{e=Ro(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){let e;this.redoing=!0;try{e=Ro(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}};var Oo=class{constructor(e,t){this.gen=function*(e){const t=Ut(e.restDecoder);for(let n=0;n<t;n++){const t=Ut(e.restDecoder),n=e.readClient();let r=Ut(e.restDecoder);for(let i=0;i<t;i++){const t=e.readInfo();if(10===t){const t=Ut(e.restDecoder);yield new pc(Js(n,r),t),r+=t}else if(31&t){const i=!(192&t),s=new uc(Js(n,r),null,128&~t?null:e.readLeftID(),null,64&~t?null:e.readRightID(),i?e.readParentInfo()?e.readString():e.readLeftID():null,!i||32&~t?null:e.readString(),fc(e,t));yield s,r+=s.length}else{const t=e.readLen();yield new Wa(Js(n,r),t),r+=t}}}}(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do{this.curr=this.gen.next().value||null}while(this.filterSkips&&null!==this.curr&&this.curr.constructor===pc);return this.curr}},Po=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}},Lo=e=>No(e,Es,Rs),Mo=(e,t)=>{if(e.constructor===Wa){const{client:n,clock:r}=e.id;return new Wa(Js(n,r+t),e.length-t)}if(e.constructor===pc){const{client:n,clock:r}=e.id;return new pc(Js(n,r+t),e.length-t)}{const n=e,{client:r,clock:i}=n.id;return new uc(Js(r,i+t),null,Js(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},No=(e,t=Ts,n=Os)=>{if(1===e.length)return e[0];const r=e.map(e=>new t($t(e)));let i=r.map(e=>new Oo(e,!0)),s=null;const o=new n,a=new Po(o);for(;i=i.filter(e=>null!==e.curr),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){const n=e.curr.id.clock-t.curr.id.clock;return 0===n?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===pc?1:-1:n}return t.curr.id.client-e.curr.id.client}),0!==i.length;){const e=i[0],t=e.curr.id.client;if(null!==s){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=s.struct.id.clock+s.struct.length&&n.id.client>=s.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>s.struct.id.clock+s.struct.length)continue;if(t!==s.struct.id.client)jo(a,s.struct,s.offset),s={struct:n,offset:0},e.next();else if(s.struct.id.clock+s.struct.length<n.id.clock)if(s.struct.constructor===pc)s.struct.length=n.id.clock+n.length-s.struct.id.clock;else{jo(a,s.struct,s.offset);const e=n.id.clock-s.struct.id.clock-s.struct.length;s={struct:new pc(Js(t,s.struct.id.clock+s.struct.length),e),offset:0}}else{const t=s.struct.id.clock+s.struct.length-n.id.clock;t>0&&(s.struct.constructor===pc?s.struct.length-=t:n=Mo(n,t)),s.struct.mergeWith(n)||(jo(a,s.struct,s.offset),s={struct:n,offset:0},e.next())}}else s={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===s.struct.id.clock+s.struct.length&&n.constructor!==pc;n=e.next())jo(a,s.struct,s.offset),s={struct:n,offset:0}}null!==s&&(jo(a,s.struct,s.offset),s=null),Fo(a);const c=r.map(e=>vs(e)),l=ms(c);return ws(o,l),o.toUint8Array()},Io=(e,t,n=Ts,r=Os)=>{const i=js(t),s=new r,o=new Po(s),a=new n($t(e)),c=new Oo(a,!1);for(;c.curr;){const e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor!==pc)if(e.id.clock+e.length>n)for(jo(o,e,ut(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)jo(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next();else c.next()}Fo(o);const l=vs(a);return ws(s,l),s.toUint8Array()},Uo=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:yt(e.encoder.restEncoder)}),e.encoder.restEncoder=Lt(),e.written=0)},jo=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Uo(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),ht(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Fo=e=>{Uo(e);const t=e.encoder.restEncoder;ht(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];ht(t,r.written),wt(t,r.restEncoder)}},Bo=e=>((e,t,n,r)=>{const i=new n($t(e)),s=new Oo(i,!1),o=new r,a=new Po(o);for(let l=s.curr;null!==l;l=s.next())jo(a,t(l),0);Fo(a);const c=vs(i);return ws(o,c),o.toUint8Array()})(e,gt,Ts,Rs),Wo="You must not compute changes after the event-handler fired.",Ho=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=qo(this.currentTarget,this.target))}deletes(e){return gs(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw on(Wo);const e=/* @__PURE__ */new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(null!==n){const r=t._map.get(n);let i,s;if(this.adds(r)){let e=r.left;for(;null!==e&&this.adds(e);)e=e.left;if(this.deletes(r)){if(null===e||!this.deletes(e))return;i="delete",s=Ct(e.content.getContent())}else null!==e&&this.deletes(e)?(i="update",s=Ct(e.content.getContent())):(i="add",s=void 0)}else{if(!this.deletes(r))return;i="delete",s=Ct(r.content.getContent())}e.set(n,{action:i,oldValue:s})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(null===e){if(0===this.transaction.doc._transactionCleanups.length)throw on(Wo);const t=this.target,n=_t(),r=_t(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null;const s=()=>{e&&i.push(e)};for(let i=t._start;null!==i;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&(null!==e&&void 0!==e.delete||(s(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?(null!==e&&void 0!==e.insert||(s(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):(null!==e&&void 0!==e.retain||(s(),e={retain:0}),e.retain+=i.length);null!==e&&void 0===e.retain&&s()}this._changes=e}return e}},qo=(e,t)=>{const n=[];for(;null!==t._item&&t!==e;){if(null!==t._item.parentSub)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&null!==r;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},Vo=()=>{yn("Invalid access: Add Yjs type to a document before reading data.")},zo=0,$o=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=zo++}},Yo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=zo++},Jo=(e,t)=>{if(null===e._start||0===t||null===e._searchMarker)return null;const n=0===e._searchMarker.length?null:e._searchMarker.reduce((e,n)=>Jt(t-e.index)<Jt(t-n.index)?e:n);let r=e._start,i=0;for(null!==n&&(r=n.p,i=n.index,(e=>{e.timestamp=zo++})(n));null!==r.right&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;null!==r.left&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;null!==r.left&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return null!==n&&Jt(n.index-i)<r.parent.length/80?(Yo(n,r,i),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return Yo(r,t,n),r}{const r=new $o(t,n);return e.push(r),r}})(e._searchMarker,r,i)},Qo=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=ut(t,i.index+n))}},Ko=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;cn(i,e,()=>[]).push(n),null!==e._item;)e=e._item.parent;zs(r._eH,n,t)},Go=class{constructor(){this._item=null,this._map=/* @__PURE__ */new Map,this._start=null,this.doc=null,this._length=0,this._eH=Hs(),this._dEH=Hs(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw en()}clone(){throw en()}_write(e){}get _first(){let e=this._start;for(;null!==e&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){qs(this._eH,e)}observeDeep(e){qs(this._dEH,e)}unobserve(e){Vs(this._eH,e)}unobserveDeep(e){Vs(this._dEH,e)}toJSON(){}},Xo=(e,t,n)=>{e.doc??Vo(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const i=[];let s=e._start;for(;null!==s&&r>0;){if(s.countable&&!s.deleted){const e=s.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}s=s.right}return i},Zo=e=>{e.doc??Vo();const t=[];let n=e._start;for(;null!==n;){if(n.countable&&!n.deleted){const e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},ea=(e,t)=>{let n=0,r=e._start;for(e.doc??Vo();null!==r;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},ta=(e,t)=>{const n=[];return ea(e,(r,i)=>{n.push(t(r,i,e))}),n},na=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(null===n){for(;null!==t&&t.deleted;)t=t.right;if(null===t)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},ra=(e,t)=>{e.doc??Vo();const n=Jo(e,t);let r=e._start;for(null!==n&&(r=n.p,t-=n.index);null!==r;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},ia=(e,t,n,r)=>{let i=n;const s=e.doc,o=s.clientID,a=s.store,c=null===n?t._start:n.right;let l=[];const h=()=>{l.length>0&&(i=new uc(Js(o,fo(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Ka(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(null===n)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(h(),n.constructor){case Uint8Array:case ArrayBuffer:i=new uc(Js(o,fo(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Ha(new Uint8Array(n))),i.integrate(e,0);break;case Cs:i=new uc(Js(o,fo(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new za(n)),i.integrate(e,0);break;default:if(!(n instanceof Go))throw new Error("Unexpected content type in insert operation");i=new uc(Js(o,fo(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new oc(n)),i.integrate(e,0)}}}),h()},sa=()=>on("Length exceeded!"),oa=(e,t,n,r)=>{if(n>t._length)throw sa();if(0===n)return t._searchMarker&&Qo(t._searchMarker,n,r.length),ia(e,t,null,r);const i=n,s=Jo(t,n);let o=t._start;for(null!==s&&(o=s.p,0===(n-=s.index)&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));null!==o;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&bo(e,Js(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Qo(t._searchMarker,i,r.length),ia(e,t,o,r)},aa=(e,t,n,r)=>{if(0===r)return;const i=n,s=r,o=Jo(t,n);let a=t._start;for(null!==o&&(a=o.p,n-=o.index);null!==a&&n>0;a=a.right)!a.deleted&&a.countable&&(n<a.length&&bo(e,Js(a.id.client,a.id.clock+n)),n-=a.length);for(;r>0&&null!==a;)a.deleted||(r<a.length&&bo(e,Js(a.id.client,a.id.clock+r)),a.delete(e),r-=a.length),a=a.right;if(r>0)throw sa();t._searchMarker&&Qo(t._searchMarker,i,-s+r)},ca=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},la=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let a;if(null==r)a=new Ka([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new Ka([r]);break;case Uint8Array:a=new Ha(r);break;case Cs:a=new za(r);break;default:if(!(r instanceof Go))throw new Error("Unexpected content type");a=new oc(r)}new uc(Js(o,fo(s.store,o)),i,i&&i.lastId,null,null,t,n,a).integrate(e,0)},ha=(e,t)=>{e.doc??Vo();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},da=e=>{const t={};return e.doc??Vo(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},ua=(e,t)=>{e.doc??Vo();const n=e._map.get(t);return void 0!==n&&!n.deleted},fa=e=>(e.doc??Vo(),Pt(e._map.entries(),e=>!e[1].deleted)),ga=class extends Ho{},pa=class e extends Go{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return t.insert(0,this.toArray().map(e=>e instanceof Go?e.clone():e)),t}get length(){return this.doc??Vo(),this._length}_callObserver(e,t){super._callObserver(e,t),Ko(this,e,new ga(this,e))}insert(e,t){null!==this.doc?Ao(this.doc,n=>{oa(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?Ao(this.doc,t=>{((e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;ia(e,t,r,n)})(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?Ao(this.doc,n=>{aa(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return ra(this,e)}toArray(){return Zo(this)}slice(e=0,t=this.length){return Xo(this,e,t)}toJSON(){return this.map(e=>e instanceof Go?e.toJSON():e)}map(e){return ta(this,e)}forEach(e){ea(this,e)}[Symbol.iterator](){return na(this)}_write(e){e.writeTypeRef(Za)}},ma=class extends Ho{constructor(e,t,n){super(e,t),this.keysChanged=n}},ya=class e extends Go{constructor(e){super(),this._prelimContent=null,this._prelimContent=void 0===e?/* @__PURE__ */new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof Go?e.clone():e)}),t}_callObserver(e,t){Ko(this,e,new ma(this,e,t))}toJSON(){this.doc??Vo();const e={};return this._map.forEach((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof Go?r.toJSON():r}}),e}get size(){return[...fa(this)].length}keys(){return wn(fa(this),e=>e[0])}values(){return wn(fa(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return wn(fa(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Vo(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){null!==this.doc?Ao(this.doc,t=>{ca(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?Ao(this.doc,n=>{la(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return ha(this,e)}has(e){return ua(this,e)}clear(){null!==this.doc?Ao(this.doc,e=>{this.forEach(function(t,n,r){ca(e,r,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(ec)}},ba=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&kt(e,t),wa=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&Vt(),this.right.content.constructor===Ya)this.right.deleted||Ca(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}},va=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===Ya)t.right.deleted||Ca(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&bo(e,Js(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);t.left=t.right,t.right=t.right.right}return t},_a=(e,t,n,r)=>{const i=/* @__PURE__ */new Map,s=r?Jo(t,n):null;if(s){const t=new wa(s.p.left,s.p,s.index,i);return va(e,t,n-s.index)}{const r=new wa(null,t._start,0,i);return va(e,r,n)}},ka=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===Ya&&ba(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=e.doc,s=i.clientID;r.forEach((r,o)=>{const a=n.left,c=n.right,l=new uc(Js(s,fo(i.store,s)),a,a&&a.lastId,c,c&&c.id,t,null,new Ya(o,r));l.integrate(e,0),n.right=l,n.forward()})},Ca=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},Sa=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===Ya&&ba(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Ea=(e,t,n,r)=>{const i=e.doc,s=i.clientID,o=/* @__PURE__ */new Map;for(const a in r){const c=r[a],l=n.currentAttributes.get(a)??null;if(!ba(l,c)){o.set(a,l);const{left:r,right:h}=n;n.right=new uc(Js(s,fo(i.store,s)),r,r&&r.lastId,h,h&&h.id,t,null,new Ya(a,c)),n.right.integrate(e,0),n.forward()}}return o},Aa=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{void 0===i[t]&&(i[t]=null)});const s=e.doc,o=s.clientID;Sa(n,i);const a=Ea(e,t,n,i),c=r.constructor===String?new Ga(r):r instanceof Go?new oc(r):new $a(r);let{left:l,right:h,index:d}=n;t._searchMarker&&Qo(t._searchMarker,n.index,c.getLength()),h=new uc(Js(o,fo(s.store,o)),l,l&&l.lastId,h,h&&h.id,t,null,c),h.integrate(e,0),n.right=h,n.index=d,n.forward(),ka(e,t,n,a)},Ta=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;Sa(n,i);const a=Ea(e,t,n,i);e:for(;null!==n.right&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Ya));){if(!n.right.deleted)switch(n.right.content.constructor){case Ya:{const{key:t,value:s}=n.right.content,o=i[t];if(void 0!==o){if(ba(o,s))a.delete(t);else{if(0===r)break e;a.set(t,s)}n.right.delete(e)}else n.currentAttributes.set(t,s);break}default:r<n.right.length&&bo(e,Js(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i="";for(;r>0;r--)i+="\n";n.right=new uc(Js(o,fo(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Ga(i)),n.right.integrate(e,0),n.forward()}ka(e,t,n,a)},xa=(e,t,n,r,i)=>{let s=t;const o=nt();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===Ya){const e=s.content;o.set(e.key,e)}s=s.right}let a=0,c=!1;for(;t!==s;){if(n===t&&(c=!0),!t.deleted){const n=t.content;switch(n.constructor){case Ya:{const{key:s,value:l}=n,h=r.get(s)??null;o.get(s)===n&&h!==l||(t.delete(e),a++,c||(i.get(s)??null)!==l||h===l||(null===h?i.delete(s):i.set(s,h))),c||t.deleted||Ca(i,n);break}}}t=t.right}return a},Ra=e=>{let t=0;return Ao(e.doc,n=>{let r=e._start,i=e._start,s=nt();const o=Qe(s);for(;i;){if(!1===i.deleted)if(i.content.constructor===Ya)Ca(o,i.content);else t+=xa(n,r,i,s,o),s=Qe(o),r=i;i=i.right}}),t},Da=e=>{const t=/* @__PURE__ */new Set,n=e.doc;for(const[r,i]of e.afterState.entries()){const s=e.beforeState.get(r)||0;i!==s&&vo(e,n.store.clients.get(r),s,i,e=>{e.deleted||e.content.constructor!==Ya||e.constructor===Wa||t.add(e.parent)})}Ao(n,n=>{fs(e,e.deleteSet,e=>{if(e instanceof Wa||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===Ya?t.add(r):((e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=/* @__PURE__ */new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Ya){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)});for(const e of t)Ra(e)})},Oa=(e,t,n)=>{const r=n,i=Qe(t.currentAttributes),s=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case oc:case $a:case Ga:n<t.right.length&&bo(e,Js(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}s&&xa(e,s,t.right,i,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&Qo(o._searchMarker,t.index,-r+n),t},Pa=class extends Ho{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=/* @__PURE__ */new Set,n.forEach(e=>{null===e?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(null===this._changes){const e={keys:this.keys,delta:this.delta,added:/* @__PURE__ */new Set,deleted:/* @__PURE__ */new Set};this._changes=e}return this._changes}get delta(){if(null===this._delta){const e=this.target.doc,t=[];Ao(e,e=>{const n=/* @__PURE__ */new Map,r=/* @__PURE__ */new Map;let i=this.target._start,s=null;const o={};let a="",c=0,l=0;const h=()=>{if(null!==s){let e=null;switch(s){case"delete":l>0&&(e={delete:l}),l=0;break;case"insert":("object"==typeof a||a.length>0)&&(e={insert:a},n.size>0&&(e.attributes={},n.forEach((t,n)=>{null!==t&&(e.attributes[n]=t)}))),a="";break;case"retain":c>0&&(e={retain:c},vt(o)||(e.attributes=Cn({},o))),c=0}e&&t.push(e),s=null}};for(;null!==i;){switch(i.content.constructor){case oc:case $a:this.adds(i)?this.deletes(i)||(h(),s="insert",a=i.content.getContent()[0],h()):this.deletes(i)?("delete"!==s&&(h(),s="delete"),l+=1):i.deleted||("retain"!==s&&(h(),s="retain"),c+=1);break;case Ga:this.adds(i)?this.deletes(i)||("insert"!==s&&(h(),s="insert"),a+=i.content.str):this.deletes(i)?("delete"!==s&&(h(),s="delete"),l+=i.length):i.deleted||("retain"!==s&&(h(),s="retain"),c+=i.length);break;case Ya:{const{key:t,value:a}=i.content;if(this.adds(i)){if(!this.deletes(i)){const c=n.get(t)??null;ba(c,a)?null!==a&&i.delete(e):("retain"===s&&h(),ba(a,r.get(t)??null)?delete o[t]:o[t]=a)}}else if(this.deletes(i)){r.set(t,a);const e=n.get(t)??null;ba(e,a)||("retain"===s&&h(),o[t]=e)}else if(!i.deleted){r.set(t,a);const n=o[t];void 0!==n&&(ba(n,a)?null!==n&&i.delete(e):("retain"===s&&h(),null===a?delete o[t]:o[t]=a))}i.deleted||("insert"===s&&h(),Ca(n,i.content));break}}i=i.right}for(h();t.length>0;){const e=t[t.length-1];if(void 0===e.retain||void 0!==e.attributes)break;t.pop()}}),this._delta=t}return this._delta}},La=class e extends Go{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Vo(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(n){}this._pending=null}_copy(){return new e}clone(){const t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);const n=new Pa(this,e,t);Ko(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Vo();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===Ga&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?Ao(this.doc,n=>{const r=new wa(null,this._start,0,/* @__PURE__ */new Map);for(let i=0;i<e.length;i++){const s=e[i];if(void 0!==s.insert){const o=t||"string"!=typeof s.insert||i!==e.length-1||null!==r.right||"\n"!==s.insert.slice(-1)?s.insert:s.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&Aa(n,this,r,o,s.attributes||{})}else void 0!==s.retain?Ta(n,this,r,s.retain,s.attributes||{}):void 0!==s.delete&&Oa(n,r,s.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){this.doc??Vo();const r=[],i=/* @__PURE__ */new Map,s=this.doc;let o="",a=this._start;function c(){if(o.length>0){const e={};let t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const l=()=>{for(;null!==a;){if(co(a,e)||void 0!==t&&co(a,t))switch(a.content.constructor){case Ga:{const r=i.get("ychange");void 0===e||co(a,e)?void 0===t||co(a,t)?void 0!==r&&(c(),i.delete("ychange")):void 0!==r&&r.user===a.id.client&&"added"===r.type||(c(),i.set("ychange",n?n("added",a.id):{type:"added"})):void 0!==r&&r.user===a.id.client&&"removed"===r.type||(c(),i.set("ychange",n?n("removed",a.id):{type:"removed"})),o+=a.content.str;break}case oc:case $a:{c();const e={insert:a.content.getContent()[0]};if(i.size>0){const t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Ya:co(a,e)&&(c(),Ca(i,a.content))}a=a.right}c()};return e||t?Ao(s,n=>{e&&lo(n,e),t&&lo(n,t),l()},"cleanup"):l(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?Ao(r,r=>{const i=_a(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Aa(r,this,i,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const r=this.doc;null!==r?Ao(r,r=>{const i=_a(r,this,e,!n);Aa(r,this,i,t,n||{})}):this._pending.push(()=>this.insertEmbed(e,t,n||{}))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?Ao(n,n=>{Oa(n,_a(n,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,n){if(0===t)return;const r=this.doc;null!==r?Ao(r,r=>{const i=_a(r,this,e,!1);null!==i.right&&Ta(r,this,i,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){null!==this.doc?Ao(this.doc,t=>{ca(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){null!==this.doc?Ao(this.doc,n=>{la(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return ha(this,e)}getAttributes(){return da(this)}_write(e){e.writeTypeRef(tc)}},Ma=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Vo()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(null!==e&&(!this._firstCall||e.deleted||!this._filter(t)))do{if(t=e.content.type,e.deleted||t.constructor!==Ia&&t.constructor!==Na||null===t._start)for(;null!==e;){const t=e.next;if(null!==t){e=t;break}e=e.parent===this._root?null:e.parent._item}else e=t._start}while(null!==e&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,null===e?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},Na=class e extends Go{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return t.insert(0,this.toArray().map(e=>e instanceof Go?e.clone():e)),t}get length(){return this.doc??Vo(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new Ma(this,e)}querySelector(e){e=e.toUpperCase();const t=new Ma(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Sn(new Ma(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Ko(this,e,new Ua(this,t,e))}toString(){return ta(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const r=e.createDocumentFragment();return void 0!==n&&n._createAssociation(r,this),ea(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){null!==this.doc?Ao(this.doc,n=>{oa(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)Ao(this.doc,n=>{const r=e&&e instanceof Go?e._item:e;ia(n,this,r,t)});else{const n=this._prelimContent,r=null===e?0:n.findIndex(t=>t===e)+1;if(0===r&&null!==e)throw on("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?Ao(this.doc,n=>{aa(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return Zo(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return ra(this,e)}slice(e=0,t=this.length){return Xo(this,e,t)}forEach(e){ea(this,e)}_write(e){e.writeTypeRef(rc)}},Ia=class e extends Na{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=/* @__PURE__ */new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){const t=new e(this.nodeName),n=this.getAttributes();return Ke(n,(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof Go?e.clone():e)),t}toString(){const e=this.getAttributes(),t=[],n=[];for(const s in e)n.push(s);n.sort();const r=n.length;for(let s=0;s<r;s++){const r=n[s];t.push(r+'="'+e[r]+'"')}const i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${i}>`}removeAttribute(e){null!==this.doc?Ao(this.doc,t=>{ca(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?Ao(this.doc,n=>{la(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return ha(this,e)}hasAttribute(e){return ua(this,e)}getAttributes(e){return e?((e,t)=>{const n={};return e._map.forEach((e,r)=>{let i=e;for(;null!==i&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;null!==i&&co(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n})(this,e):da(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const s in i){const e=i[s];"string"==typeof e&&r.setAttribute(s,e)}return ea(this,i=>{r.appendChild(i.toDOM(e,t,n))}),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(nc),e.writeKey(this.nodeName)}},Ua=class extends Ho{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=/* @__PURE__ */new Set,t.forEach(e=>{null===e?this.childListChanged=!0:this.attributesChanged.add(e)})}},ja=class e extends ya{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){const t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){const r=t[this.hookName];let i;return i=void 0!==r?r.createDom(this):document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(ic),e.writeKey(this.hookName)}},Fa=class e extends La{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){const t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){const r=e.createTextNode(this.toString());return void 0!==n&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{const t=[];for(const r in e.attributes){const n=[];for(const t in e.attributes[r])n.push({key:t,value:e.attributes[r][t]});n.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:r,attrs:n})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n="";for(let r=0;r<t.length;r++){const e=t[r];n+=`<${e.nodeName}`;for(let t=0;t<e.attrs.length;t++){const r=e.attrs[t];n+=` ${r.key}="${r.value}"`}n+=">"}n+=e.insert;for(let r=t.length-1;r>=0;r--)n+=`</${t[r].nodeName}>`;return n}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(sc)}},Ba=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw en()}mergeWith(e){return!1}write(e,t,n){throw en()}integrate(e,t){throw en()}},Wa=class extends Ba{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),go(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},Ha=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw en()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},qa=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){const n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){ys(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}},Va=(e,t)=>new Cs({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1}),za=class e{constructor(e){e._item,this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),null!==e.meta&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(Va(this.doc.guid,this.opts))}splice(e){throw en()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}},$a=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw en()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},Ya=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw en()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}},Ja=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){const n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeString(void 0===t?"undefined":JSON.stringify(t))}}getRef(){return 2}},Qa="development"===$e("node_env"),Ka=class e{constructor(e){this.arr=e,Qa&&je(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){const n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeAny(t)}}getRef(){return 8}},Ga=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new e(this.str)}splice(t){const n=new e(this.str.slice(t));this.str=this.str.slice(0,t);const r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(0===t?this.str:this.str.slice(t))}getRef(){return 4}},Xa=[e=>new pa,e=>new ya,e=>new La,e=>new Ia(e.readKey()),e=>new Na,e=>new ja(e.readKey()),e=>new Fa],Za=0,ec=1,tc=2,nc=3,rc=4,ic=5,sc=6,oc=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw en()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;null!==t;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;null!==t;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;null!==t;)t.gc(e,!0),t=t.left}),this.type._map=/* @__PURE__ */new Map}write(e,t){this.type._write(e)}getRef(){return 7}},ac=(e,t)=>{let n,r=t,i=0;do{i>0&&(r=Js(r.client,r.clock+i)),n=mo(e,r),i=r.clock-n.id.clock,r=n.redone}while(null!==r&&n instanceof uc);return{item:n,diff:i}},cc=(e,t)=>{for(;null!==e&&e.keep!==t;)e.keep=t,e=e.parent._item},lc=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new uc(Js(r,i+n),t,Js(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&s.markDeleted(),t.keep&&(s.keep=!0),null!==t.redone&&(s.redone=Js(t.redone.client,t.redone.clock+n)),t.right=s,null!==s.right&&(s.right.left=s),e._mergeStructs.push(s),null!==s.parentSub&&null===s.right&&s.parent._map.set(s.parentSub,s),t.length=n,s},hc=(e,t)=>Ge(e,e=>gs(e.deletions,t)),dc=(e,t,n,r,i,s)=>{const o=e.doc,a=o.store,c=o.clientID,l=t.redone;if(null!==l)return bo(e,l);let h,d=t.parent._item,u=null;if(null!==d&&!0===d.deleted){if(null===d.redone&&(!n.has(d)||null===dc(e,d,n,r,i,s)))return null;for(;null!==d.redone;)d=bo(e,d.redone)}const f=null===d?t.parent:d.content.type;if(null===t.parentSub){for(u=t.left,h=t;null!==u;){let t=u;for(;null!==t&&t.parent._item!==d;)t=null===t.redone?null:bo(e,t.redone);if(null!==t&&t.parent._item===d){u=t;break}u=u.left}for(;null!==h;){let t=h;for(;null!==t&&t.parent._item!==d;)t=null===t.redone?null:bo(e,t.redone);if(null!==t&&t.parent._item===d){h=t;break}h=h.right}}else{if(h=null,t.right&&!i){for(u=t;null!==u&&null!==u.right&&(u.right.redone||gs(r,u.right.id)||hc(s.undoStack,u.right.id)||hc(s.redoStack,u.right.id));)for(u=u.right;u.redone;)u=bo(e,u.redone);if(u&&null!==u.right)return null}else u=f._map.get(t.parentSub)||null;null!==u&&u.parent._item!==d&&(u=f._map.get(t.parentSub)||null)}const g=fo(a,c),p=Js(c,g),m=new uc(p,u,u&&u.lastId,h,h&&h.id,f,t.parentSub,t.content.copy());return t.redone=p,cc(m,!0),m.integrate(e,0),m},uc=class e extends Ba{constructor(e,t,n,r,i,s,o,a){super(e,a.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=s,this.parentSub=o,this.redone=null,this.content=a,this.info=this.content.isCountable()?2:0}set marker(e){(8&this.info)>0!==e&&(this.info^=8)}get marker(){return(8&this.info)>0}get keep(){return(1&this.info)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(2&this.info)>0}get deleted(){return(4&this.info)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=fo(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=fo(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===$s&&this.id.client!==this.parent.client&&this.parent.clock>=fo(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=wo(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=bo(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Wa||this.right&&this.right.constructor===Wa)this.parent=null;else if(this.parent){if(this.parent.constructor===$s){const e=mo(n,this.parent);e.constructor===Wa?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=wo(e,e.doc.store,Js(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||null!==this.right.left)||this.left&&this.left.right!==this.right){let t,n=this.left;if(null!==n)t=n.right;else if(null!==this.parentSub)for(t=this.parent._map.get(this.parentSub)||null;null!==t&&null!==t.left;)t=t.left;else t=this.parent._start;const r=/* @__PURE__ */new Set,i=/* @__PURE__ */new Set;for(;null!==t&&t!==this.right;){if(i.add(t),r.add(t),Ys(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(Ys(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!i.has(mo(e.doc.store,t.origin)))break;r.has(mo(e.doc.store,t.origin))||(n=t,r.clear())}t=t.right}this.left=n}if(null!==this.left){const e=this.left.right;this.right=e,this.left.right=this}else{let e;if(null!==this.parentSub)for(e=this.parent._map.get(this.parentSub)||null;null!==e&&null!==e.left;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}null!==this.right?this.right.left=this:null!==this.parentSub&&(this.parent._map.set(this.parentSub,this),null!==this.left&&this.left.delete(e)),null===this.parentSub&&this.countable&&!this.deleted&&(this.parent._length+=this.length),go(e.doc.store,this),this.content.integrate(e,this),Co(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new Wa(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;null!==e&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;null!==e&&e.deleted;)e=e.left;return e}get lastId(){return 1===this.length?this.id:Js(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Ys(e.origin,this.lastId)&&this.right===e&&Ys(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&null===this.redone&&null===e.redone&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,null!==this.right&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&null===this.parentSub&&(t._length-=this.length),this.markDeleted(),ys(e.deleteSet,this.id.client,this.id.clock,this.length),Co(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Vt();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[po(r,t.id.clock)]=n})(e,this,new Wa(this.id,this.length)):this.content=new qa(this.length)}write(e,t){const n=t>0?Js(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,s=31&this.content.getRef()|(null===n?0:128)|(null===r?0:64)|(null===i?0:32);if(e.writeInfo(s),null!==n&&e.writeLeftID(n),null!==r&&e.writeRightID(r),null===n&&null===r){const t=this.parent;if(void 0!==t._item){const n=t._item;if(null===n){const n=Gs(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===$s?(e.writeParentInfo(!1),e.writeLeftID(t)):Vt();null!==i&&e.writeString(i)}this.content.write(e,t)}},fc=(e,t)=>gc[31&t](e),gc=[()=>{Vt()},e=>new qa(e.readLen()),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const t=e.readString();"undefined"===t?n.push(void 0):n.push(JSON.parse(t))}return new Ja(n)},e=>new Ha(e.readBuf()),e=>new Ga(e.readString()),e=>new $a(e.readJSON()),e=>new Ya(e.readKey(),e.readJSON()),e=>new oc(Xa[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Ka(n)},e=>new za(Va(e.readString(),e.readAny())),()=>{Vt()}],pc=class extends Ba{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){Vt()}write(e,t){e.writeInfo(10),ht(e.restEncoder,this.length-t)}getMissing(e,t){return null}},mc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},yc="__ $YJS$ __";mc[yc],mc[yc]=!0;var bc=Object.defineProperty,wc=Object.defineProperties,vc=Object.getOwnPropertyDescriptors,_c=Object.getOwnPropertySymbols,kc=Object.prototype.hasOwnProperty,Cc=Object.prototype.propertyIsEnumerable,Sc=(e,t,n)=>t in e?bc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ec=(e,t)=>{for(var n in t||(t={}))kc.call(t,n)&&Sc(e,n,t[n]);if(_c)for(var n of _c(t))Cc.call(t,n)&&Sc(e,n,t[n]);return e},Ac=(e,t)=>wc(e,vc(t)),Tc=(e,t)=>{var n={};for(var r in e)kc.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&_c)for(var r of _c(e))t.indexOf(r)<0&&Cc.call(e,r)&&(n[r]=e[r]);return n};function xc(e){return"[object Object]"===Object.prototype.toString.call(e)}function Rc(e){if(!xc(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==xc(n)&&!1!==n.hasOwnProperty("isPrototypeOf")}function Dc(e,t){for(const n in e){const r=e[n],i=t[n];if(Rc(r)&&Rc(i)){if(!Dc(r,i))return!1}else if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1}else if(r!==i)return!1}for(const n in t)if(void 0===e[n]&&void 0!==t[n])return!1;return!0}function Oc(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function Pc(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>null!==e))}function Lc(e){return function(e){var t,n;const r=[];for(const i of e){if("string"==typeof i.insert&&0===i.insert.length)continue;const e=r[r.length-1];e&&"string"==typeof e.insert&&"string"==typeof i.insert&&(e.attributes===i.attributes||!e.attributes==!i.attributes&&Dc(null!=(t=e.attributes)?t:{},null!=(n=i.attributes)?n:{}))?e.insert+=i.insert:r.push(i)}return r}(e.toDelta())}function Mc({insert:e}){return"string"==typeof e?e.length:1}function Nc(e){return e.reduce((e,t)=>e+Mc(t),0)}function Ic(e,t,n){if(n<1)return[];let r=0;const i=[],s=t+n;for(let o=0;o<e.length&&!(r>=s);o++){const n=e[o],a=Mc(n);if(r+a<=t){r+=a;continue}if("string"!=typeof n.insert){r+=a,i.push(n);continue}const c=Math.max(0,t-r),l=Math.min(a,a-(r+a-s));i.push(Ac(Ec({},n),{insert:n.insert.slice(c,l)})),r+=a}return i}function Uc(e){return function(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}(e,z.isText(e)?"text":"children")}function jc(e){const t=Lc(e),n=t.length>0?t.map(Fc):[{text:""}];return Ac(Ec({},e.getAttributes()),{children:n})}function Fc(e){return"string"==typeof e.insert?Ac(Ec({},e.attributes),{text:e.insert}):jc(e.insert)}function Bc(e){return e.map(e=>z.isText(e)?{insert:e.text,attributes:Uc(e)}:{insert:Wc(e)})}function Wc(e){var t=e,{children:n}=t,r=Tc(t,["children"]);const i=new Fa;return Object.entries(r).forEach(([e,t])=>{i.setAttribute(e,t)}),i.applyDelta(Bc(n),{sanitize:!1}),i}function Hc(e){return e?z.isText(e)?e.text.length:1:0}function qc(e,t,n){var r;if(0===n.length)throw new Error("Path has to a have a length >= 1");if(z.isText(t))throw new Error("Cannot descent into slate text");const[i,...s]=n,o=function(e,t){return e.children.slice(0,t).reduce((e,t)=>e+Hc(t),0)}(t,i),a=t.children[i],c=Lc(e),l=Hc(a),h=Ic(c,o,l);if(h.length>1)throw new Error("Path doesn't match yText, yTarget spans multiple nodes");const d=null==(r=h[0])?void 0:r.insert;if(s.length>0){if(!(d instanceof Fa))throw new Error("Path doesn't match yText, cannot descent into non-yText");return qc(d,a,s)}return{yParent:e,textRange:{start:o,end:o+l},yTarget:d instanceof Fa?d:void 0,slateParent:t,slateTarget:a,targetDelta:h}}function Vc(e,t,n={}){const{assoc:r=0,insert:i=!1}=n;let s=0,o=0;for(let c=0;c<e.children.length;c++){const n=e.children[c],i=z.isText(n)?n.text.length:1;i>0&&(o=c);const a=s+i;if(i>0&&(r>=0?a>t:a>=t))return[c,t-s];s+=i}if(t>s+(i?1:0))throw new Error("yOffset out of bounds");if(i)return[e.children.length,0];const a=e.children[o];return[o,z.isText(a)?a.text.length:1]}function zc(e,t,n){const r=[n];for(;r[0]!==e;){const{parent:e}=r[0];if(!e)throw new Error("yText isn't a descendant of root element");if(!(e instanceof Fa))throw new Error("Unexpected y parent type");r.unshift(e)}if(r.length<2)return[];let i=t;return r.reduce((e,t,n)=>{const s=r[n+1];if(!s)return e;let o=0;const a=Lc(t);for(const r of a){if(r.insert===s)break;o+="string"==typeof r.insert?r.insert.length:1}if(z.isText(i))throw new Error("Cannot descent into slate text");const[c]=Vc(i,o);return i=i.children[c],e.concat(c)},[])}function $c(e,t,n){const{target:r,changes:i}=n,s=n.delta;if(!(r instanceof Fa))throw new Error("Unexpected target node type");const o=[],a=zc(e,t,r),c=q.get(t,a);if(z.isText(c))throw new Error("Cannot apply yTextEvent to text node");const l=Array.from(i.keys.entries());if(a.length>0&&l.length>0){const e=Object.fromEntries(l.map(([e,t])=>[e,"delete"===t.action?null:r.getAttribute(e)])),t=Object.fromEntries(l.map(([e])=>[e,c[e]]));o.push({type:"set_node",newProperties:e,properties:t,path:a})}return s.length>0&&o.push(...function(e,t,n){const r=[];let i=n.reduce((e,t)=>"retain"in t?e+t.retain:"delete"in t?e+t.delete:e,0);return n.reverse().forEach(n=>{var s;if("attributes"in n&&"retain"in n){const[s,o]=Vc(e,i-n.retain),[a,c]=Vc(e,i,{assoc:-1});for(let i=a;i>=s;i--){const l=e.children[i],h=[...t,i];if(!z.isText(l))continue;const d=n.attributes,u=Oc(e,...Object.keys(n.attributes));if(i===s||i===a){const e=i===s?o:0,t=i===a?c:l.text.length;if(t!==l.text.length&&r.push({type:"split_node",path:h,position:t,properties:Uc(l)}),0!==e){r.push({type:"split_node",path:h,position:e,properties:Pc(Ec(Ec({},Uc(l)),d))});continue}}r.push({type:"set_node",newProperties:d,path:h,properties:u})}}if("retain"in n&&(i-=n.retain),"delete"in n){const[s,o]=Vc(e,i-n.delete),[a,c]=Vc(e,i,{assoc:-1});for(let n=0===c?a-1:a;n>=s;n--){const l=e.children[n],h=[...t,n];if(z.isText(l)&&(n===s||n===a)){const e=n===s?o:0,t=n===a?c:l.text.length;r.push({type:"remove_text",offset:e,text:l.text.slice(e,t),path:h}),i-=t-e;continue}r.push({type:"remove_node",node:l,path:h}),i-=Hc(l)}return}if("insert"in n){const[o,a]=Vc(e,i,{insert:!0}),c=e.children[o],l=[...t,o];if(z.isText(c)){const e=r[r.length-1],t=null!=e&&"insert_node"===e.type?e.node:Uc(c);let i=[];if(null==e||"insert_node"!==e.type&&"insert_text"!==e.type&&"split_node"!==e.type&&"set_node"!==e.type||(i=e.path),"string"==typeof n.insert&&Dc(null!=(s=n.attributes)?s:{},t)&&ne.equals(l,i))return r.push({type:"insert_text",offset:a,text:n.insert,path:l});const o=Fc(n);return 0===a?r.push({type:"insert_node",path:l,node:o}):(a<c.text.length&&r.push({type:"split_node",path:l,position:a,properties:Uc(c)}),r.push({type:"insert_node",path:ne.next(l),node:o}))}return r.push({type:"insert_node",path:l,node:Fc(n)})}}),r}(c,a,s)),o}function Yc(e,t,n){ue.withoutNormalizing(t,()=>{n.forEach(n=>{(function(e,t,n){if(n instanceof Pa)return $c(e,t,n);throw new Error("Unexpected Y event type")})(e,t,n).forEach(e=>{t.apply(e)})})})}function Jc(e){return e.map(e=>"string"==typeof e.insert?e:Ac(Ec({},e),{insert:Qc(e.insert)}))}function Qc(e){const t=new Fa,n=e.getAttributes();return Object.entries(n).forEach(([e,n])=>{t.setAttribute(e,n)}),t.applyDelta(Jc(Lc(e)),{sanitize:!1}),t}function Kc(e){if(!e.doc)throw new Error("shared type isn't attached to a document")}var Gc="__slateYjsStoredPosition_";function Xc(e,t,n){const{yTarget:r,yParent:i,textRange:s}=qc(e,t,n.path);if(r)throw new Error("Slate point points to a non-text element inside sharedRoot");const o=s.start+n.offset;return no(i,o,o===s.end?-1:0)}function Zc(e,t,n){if(!e.doc)throw new Error("sharedRoot isn't attach to a yDoc");const r=so(n,e.doc);return r&&function(e,t,{type:n,index:r,assoc:i}){if(!(n instanceof Fa))throw new Error("Absolute position points to a non-XMLText");const s=zc(e,t,n),o=q.get(t,s);if(z.isText(o))throw new Error("Absolute position doesn't match slateRoot, cannot descent into text");const[a,c]=Vc(o,r,{assoc:i}),l=o.children[a];return z.isText(l)?{path:[...s,a],offset:c}:null}(e,t,r)}function el(e,t,n){e.setAttribute(Gc+t,ro(n))}function tl(e,t,n){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.type===t&&(!n||(e.assoc>=0?e.index>=n.start&&e.index<n.end:e.index>n.start&&e.index>=n.end))))}function nl(e,t,n=""){const r={[n]:tl(e,t)};return Lc(t).forEach(({insert:t},i)=>{t instanceof Fa&&Object.assign(r,nl(e,t,n?`${n}.${i}`:i.toString()))}),r}function rl(e,t,n,r=0){const i=function(e){return Kc(e),Object.fromEntries(Object.entries(e.getAttributes()).filter(([e])=>e.startsWith(Gc)).map(([t,n])=>[t.slice(25),so(io(n),e.doc)]).filter(([,e])=>e))}(e),s={"":tl(i,t,{start:r,end:r+Nc(n)})};return n.forEach(({insert:e},t)=>{e instanceof Fa&&Object.assign(s,nl(i,e,t.toString()))}),s}function il(e,t,n,r,i=0,s=0,o=""){const a=n[o];a&&Object.entries(a).forEach(([n,r])=>{el(e,n,no(t,r.index-s+i,r.assoc))}),r.forEach(({insert:t},r)=>{t instanceof Fa&&il(e,t,n,Lc(t),0,0,o?`${o}.${r}`:r.toString())})}function sl(e,t,n){return{anchor:Xc(e,t,n.anchor),focus:Xc(e,t,n.focus)}}var ol={insert_node:function(e,t,n){const{yParent:r,textRange:i}=qc(e,t,n.path);if(z.isText(n.node))return r.insert(i.start,n.node.text,Uc(n.node));r.insertEmbed(i.start,Wc(n.node))},remove_node:function(e,t,n){const{yParent:r,textRange:i}=qc(e,t,n.path);r.delete(i.start,i.end-i.start)},set_node:function(e,t,n){const{yTarget:r,textRange:i,yParent:s}=qc(e,t,n.path);if(r)return Object.entries(n.newProperties).forEach(([e,t])=>{if(null===t)return r.removeAttribute(e);r.setAttribute(e,t)}),Object.entries(n.properties).forEach(([e])=>{n.newProperties.hasOwnProperty(e)||r.removeAttribute(e)});const o=Ec(Ec({},Object.fromEntries(Object.keys(n.properties).map(e=>[e,null]))),n.newProperties);s.format(i.start,i.end-i.start,o)},merge_node:function(e,t,n){const r=qc(e,t,n.path),i=qc(r.yParent,r.slateParent,ne.previous(n.path.slice(-1)));if(!r.yTarget!=!i.yTarget)throw new Error("Cannot merge y text with y element");if(!i.yTarget||!r.yTarget){const{yParent:e,textRange:i,slateTarget:s}=r;if(!s)throw new Error("Expected Slate target node for merge op.");const o=q.get(t,ne.previous(n.path));if(!z.isText(o))throw new Error("Path points to Y.Text but not a Slate text node.");const a=Uc(s),c=Uc(o),l=Object.keys(a).reduce((e,t)=>t in c?e:Ac(Ec({},e),{[t]:null}),{});return e.format(i.start,i.end-i.start,Ec(Ec({},l),c))}const s=i.yTarget.length,o=Lc(r.yTarget),a=Jc(o),c=rl(e,r.yTarget,o,s),l=[{retain:s},...a];i.yTarget.applyDelta(l,{sanitize:!1}),r.yParent.delete(r.textRange.start,r.textRange.end-r.textRange.start),il(e,i.yTarget,c,a,s)},move_node:function(e,t,n){const r=ne.parent(n.newPath),i=n.newPath[n.newPath.length-1],s=q.get(t,r);if(z.isText(s))throw new Error("Cannot move slate node into text element");const o=[...r,Math.min(i,s.children.length)],a=qc(e,t,n.path),c=qc(e,t,o),l=Jc(a.targetDelta),h=rl(e,a.yParent,a.targetDelta);a.yParent.delete(a.textRange.start,a.textRange.end-a.textRange.start);const d=Nc(Lc(c.yParent)),u=Math.min(c.textRange.start,d),f=[{retain:u},...l];c.yParent.applyDelta(f,{sanitize:!1}),il(e,c.yParent,h,l,u,a.textRange.start)},split_node:function(e,t,n){const r=qc(e,t,n.path);if(!r.slateTarget)throw new Error("Y target without corresponding slate node");if(!r.yTarget){if(!z.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const e={};return r.targetDelta.forEach(t=>{t.attributes&&Object.keys(t.attributes).forEach(t=>{e[t]=null})}),r.yParent.format(r.textRange.start,r.textRange.end-r.textRange.start,Ec(Ec({},e),n.properties))}if(z.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const i=qc(r.yTarget,r.slateTarget,[n.position]),s=r.slateTarget.children.slice(0,n.position).reduce((e,t)=>e+Hc(t),0),o=r.slateTarget.children.reduce((e,t)=>e+Hc(t),0),a=Ic(Lc(r.yTarget),s,o-s),c=Jc(a),l=rl(e,r.yTarget,a,s),h=new Fa;h.applyDelta(c,{sanitize:!1}),Object.entries(n.properties).forEach(([e,t])=>{h.setAttribute(e,t)}),r.yTarget.delete(i.textRange.start,r.yTarget.length-i.textRange.start),r.yParent.insertEmbed(r.textRange.end,h),il(e,h,l,c,0,s)}};var al=Ac(Ec(Ec({},{insert_text:function(e,t,n){const{yParent:r,textRange:i}=qc(e,t,n.path),s=q.get(t,n.path);if(!z.isText(s))throw new Error("Cannot insert text into non-text node");r.insert(i.start+n.offset,n.text,Uc(s))},remove_text:function(e,t,n){const{yParent:r,textRange:i}=qc(e,t,n.path);r.delete(i.start+n.offset,n.text.length)}}),ol),{set_selection:()=>{}});var cl=Symbol("slate-yjs-operation"),ll=Symbol("slate-yjs-position-storage"),hl=/* @__PURE__ */new WeakMap,dl=/* @__PURE__ */new WeakMap,ul=/* @__PURE__ */new WeakSet,fl={isYjsEditor:e=>ue.isEditor(e)&&e.sharedRoot instanceof Fa&&"localOrigin"in e&&"positionStorageOrigin"in e&&"function"==typeof e.applyRemoteEvents&&"function"==typeof e.storeLocalChange&&"function"==typeof e.flushLocalChanges&&"function"==typeof e.isLocalOrigin&&"function"==typeof e.connect&&"function"==typeof e.disconnect,localChanges(e){var t;return null!=(t=dl.get(e))?t:[]},applyRemoteEvents(e,t,n){e.applyRemoteEvents(t,n)},storeLocalChange(e,t){e.storeLocalChange(t)},flushLocalChanges(e){e.flushLocalChanges()},connected:e=>ul.has(e),connect(e){e.connect()},disconnect(e){e.disconnect()},isLocal:e=>e.isLocalOrigin(fl.origin(e)),origin(e){const t=hl.get(e);return void 0!==t?t:e.localOrigin},withOrigin(e,t,n){const r=fl.origin(e);hl.set(e,t),n(),hl.set(e,r)},storePosition(e,t,n){const{sharedRoot:r,positionStorageOrigin:i}=e;Kc(r);const s=Xc(r,e,n);r.doc.transact(()=>{el(r,t,s)},i)},removeStoredPosition(e,t){const{sharedRoot:n,positionStorageOrigin:r}=e;Kc(n),n.doc.transact(()=>{!function(e,t){e.removeAttribute(Gc+t)}(n,t)},r)},position(e,t){const n=function(e,t){const n=e.getAttribute(Gc+t);return n?io(n):null}(e.sharedRoot,t);if(n)return Zc(e.sharedRoot,e,n)},storedPositionsRelative(e){return t=e.sharedRoot,Object.fromEntries(Object.entries(t.getAttributes()).filter(([e])=>e.startsWith(Gc)).map(([e,t])=>{return[e.slice(25),(n=t,new Zs(null==n.type?null:Js(n.type.client,n.type.clock),n.tname??null,null==n.item?null:Js(n.item.client,n.item.clock),null==n.assoc?0:n.assoc))];var n}));var t}};function gl(e,t,{localOrigin:n,positionStorageOrigin:r,autoConnect:i=!1}={}){const s=e;s.sharedRoot=t,s.localOrigin=null!=n?n:cl,s.positionStorageOrigin=null!=r?r:ll,s.applyRemoteEvents=(e,t)=>{fl.flushLocalChanges(s),ue.withoutNormalizing(s,()=>{fl.withOrigin(s,t,()=>{Yc(s.sharedRoot,s,e)})})},s.isLocalOrigin=e=>e===s.localOrigin;const o=(e,t)=>{s.isLocalOrigin(t.origin)||fl.applyRemoteEvents(s,e,t.origin)};let a=null;i&&(a=setTimeout(()=>{a=null,fl.connect(s)})),s.connect=()=>{if(fl.connected(s))throw new Error("already connected");s.sharedRoot.observeDeep(o);const t=jc(s.sharedRoot);s.children=t.children,ul.add(s),ue.normalize(e,{force:!0}),e.operations.length||e.onChange()},s.disconnect=()=>{a&&clearTimeout(a),fl.flushLocalChanges(s),s.sharedRoot.unobserveDeep(o),ul.delete(s)},s.storeLocalChange=t=>{dl.set(s,[...fl.localChanges(s),{op:t,doc:e.children,origin:fl.origin(s)}])},s.flushLocalChanges=()=>{Kc(s.sharedRoot);const e=fl.localChanges(s);dl.delete(s);const t=[];e.forEach(e=>{const n=t[t.length-1];if(n&&n[0].origin===e.origin)return n.push(e);t.push([e])}),t.forEach(e=>{Kc(s.sharedRoot),s.sharedRoot.doc.transact(()=>{e.forEach(e=>{Kc(s.sharedRoot),function(e,t,n){const r=al[n.type];if(!r)throw new Error(`Unknown operation: ${n.type}`);r(e,t,n)}(s.sharedRoot,{children:e.doc},e.op)})},e[0].origin)})};const{apply:c,onChange:l}=s;return s.apply=e=>{fl.connected(s)&&fl.isLocal(s)&&fl.storeLocalChange(s,e),c(e)},s.onChange=()=>{fl.connected(s)&&fl.flushLocalChanges(s),l()},s}var pl=/* @__PURE__ */new WeakMap,ml=Symbol("slate-yjs-history-without-saving");function yl(e,t={}){var n=t,{withoutSavingOrigin:r=ml,trackedOrigins:i=/* @__PURE__ */new Set([e.localOrigin])}=n,s=Tc(n,["withoutSavingOrigin","trackedOrigins"]);const o=e;o.undoManager=new Do(o.sharedRoot,Ec({trackedOrigins:i},s)),o.withoutSavingOrigin=r;const{onChange:a,isLocalOrigin:c}=o;o.onChange=()=>{a(),pl.set(o,o.selection&&sl(o.sharedRoot,o,o.selection))},o.isLocalOrigin=e=>e===o.withoutSavingOrigin||c(e);const l=({stackItem:e})=>{e.meta.set("selection",o.selection&&sl(o.sharedRoot,o,o.selection)),e.meta.set("selectionBefore",pl.get(o))},h=({stackItem:e})=>{e.meta.set("selection",o.selection&&sl(o.sharedRoot,o,o.selection))},d=({stackItem:e,type:t})=>{const n="undo"===t?o.undoManager.redoStack:o.undoManager.undoStack,r=n[n.length-1];r&&(r.meta.set("selection",e.meta.get("selectionBefore")),r.meta.set("selectionBefore",e.meta.get("selection")));const i=e.meta.get("selectionBefore");if(!i)return;const s=function(e,t,n){const r=Zc(e,t,n.anchor);if(!r)return null;const i=Zc(e,t,n.focus);return i?{anchor:r,focus:i}:null}(o.sharedRoot,o,i);s&&J.select(o,s)},{connect:u,disconnect:f}=o;return o.connect=()=>{u(),o.undoManager.on("stack-item-added",l),o.undoManager.on("stack-item-popped",d),o.undoManager.on("stack-item-updated",h)},o.disconnect=()=>{o.undoManager.off("stack-item-added",l),o.undoManager.off("stack-item-popped",d),o.undoManager.off("stack-item-updated",h),f()},o.undo=()=>{fl.connected(o)&&(fl.flushLocalChanges(o),o.undoManager.undo())},o.redo=()=>{fl.connected(o)&&(fl.flushLocalChanges(o),o.undoManager.redo())},o}var bl=/* @__PURE__ */new WeakMap,wl={isCursorEditor:e=>fl.isYjsEditor(e)&&e.awareness&&"string"==typeof e.cursorDataField&&"string"==typeof e.selectionStateField&&"function"==typeof e.sendCursorPosition&&"function"==typeof e.sendCursorData,sendCursorPosition(e,t=e.selection){e.sendCursorPosition(t)},sendCursorData(e,t){e.sendCursorData(t)},on(e,t,n){var r;if("change"!==t)return;const i=null!=(r=bl.get(e))?r:/* @__PURE__ */new Set;i.add(n),bl.set(e,i)},off(e,t,n){if("change"!==t)return;const r=bl.get(e);r&&r.delete(n)},cursorState(e,t){var n;if(t===e.awareness.clientID||!fl.connected(e))return null;const r=e.awareness.getStates().get(t);return r?{relativeSelection:null!=(n=r[e.selectionStateField])?n:null,data:r[e.cursorDataField],clientId:t}:null},cursorStates:e=>fl.connected(e)?Object.fromEntries(Array.from(e.awareness.getStates().entries(),([t,n])=>t!==e.awareness.clientID&&n?[t,{relativeSelection:n[e.selectionStateField],data:n[e.cursorDataField]}]:null).filter(Array.isArray)):{}};var vl=class extends Ze{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=/* @__PURE__ */new Map,this.meta=/* @__PURE__ */new Map,this._checkInterval=setInterval(()=>{const e=At();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&_l(this,t,"timeout")},ot(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:At()});const s=[],o=[],a=[],c=[];null===e?c.push(t):null==i?null!=e&&s.push(t):(o.push(t),rt(i,e)||a.push(t)),(s.length>0||a.length>0||c.length>0)&&this.emit("change",[{added:s,updated:a,removed:c},"local"]),this.emit("update",[{added:s,updated:o,removed:c},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},_l=(e,t,n)=>{const r=[];for(let i=0;i<t.length;i++){const n=t[i];if(e.states.has(n)){if(e.states.delete(n),n===e.clientID){const t=e.meta.get(n);e.meta.set(n,{clock:t.clock+1,lastUpdated:At()})}r.push(n)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},kl=(e,t,n=e.states)=>{const r=t.length,i=Lt();ht(i,r);for(let s=0;s<r;s++){const r=t[s],o=n.get(r)||null,a=e.meta.get(r).clock;ht(i,r),ht(i,a),qe(i,JSON.stringify(o))}return yt(i)},Cl=(e,t,n)=>{const r=$t(t),i=At(),s=[],o=[],a=[],c=[],l=Ut(r);for(let h=0;h<l;h++){const t=Ut(r);let n=Ut(r);const l=JSON.parse(gn(r)),h=e.meta.get(t),d=e.states.get(t),u=void 0===h?0:h.clock;(u<n||u===n&&null===l&&e.states.has(t))&&(null===l?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===h&&null!==l?s.push(t):void 0!==h&&null===l?c.push(t):null!==l&&(rt(l,d)||a.push(t),o.push(t)))}(s.length>0||a.length>0||c.length>0)&&e.emit("change",[{added:s,updated:a,removed:c},n]),(s.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:s,updated:o,removed:c},n])},Sl=(e,t)=>{ht(e,0);const n=(e=>Bs(e,new xs))(t);Kt(e,n)},El=(e,t,n)=>{ht(e,1),Kt(e,Us(t,n))},Al=(e,t,n,r)=>{try{Ns(t,Bt(e),n)}catch(i){null!=r&&r(i)}},Tl=(e,t)=>{ht(e,2),Kt(e,t)},xl=Al,Rl=(e,t,n,r,i)=>{const s=Ut(e);switch(s){case 0:((e,t,n)=>{El(t,n,Bt(e))})(e,t,n);break;case 1:Al(e,n,r,i);break;case 2:xl(e,n,r,i);break;default:throw new Error("Unknown message type")}return s},Dl=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){const n=this.callbacks[e];return n&&n.forEach(e=>e.apply(this,t)),this}off(e,t){const n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(e=>e!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}},Ol=class{constructor(e){this.data=e,this.encoder=Lt(),this.decoder=$t(new Uint8Array(this.data))}peekVarString(){return rn(this.decoder)}readVarUint(){return Ut(this.decoder)}readVarString(){return gn(this.decoder)}readVarUint8Array(){return Bt(this.decoder)}writeVarUint(e){return ht(this.encoder,e)}writeVarString(e){return qe(this.encoder,e)}writeVarUint8Array(e){return Kt(this.encoder,e)}length(){return vn(this.encoder)}},Pl=/* @__PURE__ */function(e){return e[e.Sync=0]="Sync",e[e.Awareness=1]="Awareness",e[e.Auth=2]="Auth",e[e.QueryAwareness=3]="QueryAwareness",e[e.Stateless=5]="Stateless",e[e.CLOSE=7]="CLOSE",e[e.SyncStatus=8]="SyncStatus",e[e.Ping=9]="Ping",e[e.Pong=10]="Pong",e}({}),Ll=/* @__PURE__ */function(e){return e.Connecting="connecting",e.Connected="connected",e.Disconnected="disconnected",e}({}),Ml=class{constructor(){this.encoder=Lt()}get(e){return e.encoder}toUint8Array(){return yt(this.encoder)}},Nl=class extends Ml{constructor(...e){super(...e),this.type=Pl.CLOSE,this.description="Ask the server to close the connection"}get(e){return qe(this.encoder,e.documentName),ht(this.encoder,this.type),this.encoder}},Il=class e extends Dl{static{this.DEDUPLICATABLE_TYPES=/* @__PURE__ */new Set([Pl.Awareness,Pl.QueryAwareness])}constructor(e){super(),this.messageQueue=[],this.configuration={url:"",autoConnect:!0,preserveTrailingSlash:!1,document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,handleTimeout:null,providerMap:/* @__PURE__ */new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=Ll.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(e),this.configuration.WebSocketPolyfill=e.WebSocketPolyfill?e.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(e){this.status=Ll.Connected,this.emit("status",{status:Ll.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){const t=e.effectiveName,n=this.configuration.providerMap.get(t);if(n&&n!==e&&n.isAuthenticated)throw new Error(`Cannot attach two providers with the same effective name "${t}". Use sessionAwareness: true to multiplex providers with the same document name.`);this.configuration.providerMap.set(t,e),this.status===Ll.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===Ll.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){const t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(Nl,{documentName:t}),this.configuration.providerMap.delete(t))}setConfiguration(e={}){this.configuration={...this.configuration,...e},this.configuration.autoConnect||(this.shouldConnect=!1)}async connect(){if(this.status===Ll.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const{retryPromise:e,cancelFunc:t}=(()=>{let e=!1;return{retryPromise:ui(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,handleTimeout:this.configuration.handleTimeout,beforeAttempt:t=>{this.shouldConnect&&!e||t.abort()}}).catch(e=>{if(e&&"ATTEMPT_ABORTED"!==e.code)throw e}),cancelFunc:()=>{e=!0}}})();return this.cancelWebsocketRetry=t,e}attachWebSocketListeners(e,t){const{identifier:n}=e;this.webSocketHandlers[n]={message:e=>this.emit("message",e),close:e=>this.emit("close",{event:e}),open:e=>this.emit("open",e),error:e=>{t(e)}};const r=this.webSocketHandlers[e.identifier];Object.keys(r).forEach(t=>{e.addEventListener(t,r[t])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:e}=this.webSocket,t=this.webSocketHandlers[e];Object.keys(t).forEach(n=>{this.webSocket?.removeEventListener(n,t[n]),delete this.webSocketHandlers[e]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((e,t)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=Ll.Connecting,this.emit("status",{status:Ll.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=At();const t=new Uint8Array(e.data);if(1===t.length&&t[0]===Pl.Ping)return void this.sendPong();const n=new Ol(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){const e=Lt();ht(e,Pl.Pong),this.send(yt(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=Ll.Connected,this.emit("status",{status:Ll.Connected}),this.emit("connect"),this.messageQueue.forEach(e=>this.send(e)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){this.connectionAttempt?.reject(),this.connectionAttempt=null}checkConnection(){this.status===Ll.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=At()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):(this.webSocket?.close(),this.messageQueue=[])))}get serverUrl(){if(this.configuration.preserveTrailingSlash)return this.configuration.url;let e=this.configuration.url;for(;"/"===e[e.length-1];)e=e.slice(0,e.length-1);return e}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,null!==this.webSocket)try{this.webSocket.close(),this.messageQueue=[]}catch(e){}}parseQueuedMessage(e){try{const t=$t(e);return{documentName:gn(t),messageType:Ut(t)}}catch{return null}}addToQueue(t){if(t instanceof Uint8Array){const n=this.parseQueuedMessage(t);n&&e.DEDUPLICATABLE_TYPES.has(n.messageType)&&(this.messageQueue=this.messageQueue.filter(e=>{if(!(e instanceof Uint8Array))return!0;const t=this.parseQueuedMessage(e);return!t||!(t.documentName===n.documentName&&t.messageType===n.messageType)}))}this.messageQueue.push(t)}send(e){this.webSocket?.readyState===li.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=Ll.Disconnected,this.emit("status",{status:Ll.Disconnected}),this.emit("disconnect",{event:e}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}},Ul=class{constructor(e){this.message=e}apply(e,t){const{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case Pl.Sync:this.applySyncMessage(e,t);break;case Pl.Awareness:this.applyAwarenessMessage(e);break;case Pl.Auth:this.applyAuthMessage(e);break;case Pl.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case Pl.Stateless:e.receiveStateless(gn(n.decoder));break;case Pl.SyncStatus:this.applySyncStatusMessage(e,1===Xt(n.decoder));break;case Pl.CLOSE:{const t={code:1e3,reason:gn(n.decoder)};e.onClose(),e.configuration.onClose({event:t}),e.forwardClose({event:t});break}}n.length()>i+1&&e.send(Ml,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(Pl.Sync);const r=Rl(n.decoder,n.encoder,e.document,e);t&&1===r&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;Cl(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;si(t.decoder,e.sendToken.bind(e),e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;t.writeVarUint(Pl.Awareness),t.writeVarUint8Array(kl(e.awareness,Array.from(e.awareness.getStates().keys())))}},jl=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return yt(this.encoder)}send(e){e?.send(this.create())}},Fl=class extends Ml{constructor(...e){super(...e),this.type=Pl.Auth,this.description="Authentication"}get(e){if(void 0===e.token)throw new Error("The authentication message requires `token` as an argument.");return qe(this.encoder,e.documentName),ht(this.encoder,this.type),ii(this.encoder,e.token),qe(this.encoder,"4.6.0"),this.encoder}},Bl=class extends Ml{constructor(...e){super(...e),this.type=Pl.Awareness,this.description="Awareness states update"}get(e){if(void 0===e.awareness)throw new Error("The awareness message requires awareness as an argument");if(void 0===e.clients)throw new Error("The awareness message requires clients as an argument");let t;return qe(this.encoder,e.documentName),ht(this.encoder,this.type),t=void 0===e.states?kl(e.awareness,e.clients):kl(e.awareness,e.clients,e.states),Kt(this.encoder,t),this.encoder}},Wl=class extends Ml{constructor(...e){super(...e),this.type=Pl.Stateless,this.description="A stateless message"}get(e){return qe(this.encoder,e.documentName),ht(this.encoder,this.type),qe(this.encoder,e.payload??""),this.encoder}},Hl=class extends Ml{constructor(...e){super(...e),this.type=Pl.Sync,this.description="First sync step"}get(e){if(void 0===e.document)throw new Error("The sync step one message requires document as an argument");return qe(this.encoder,e.documentName),ht(this.encoder,this.type),Sl(this.encoder,e.document),this.encoder}},ql=class extends Ml{constructor(...e){super(...e),this.type=Pl.Sync,this.description="A document update"}get(e){return qe(this.encoder,e.documentName),ht(this.encoder,this.type),Tl(this.encoder,e.update),this.encoder}},Vl=class extends Error{constructor(...e){super(...e),this.code=1001}},zl=class extends Dl{get effectiveName(){return this.configuration.sessionAwareness?ai(this.configuration.name,this.sessionId):this.configuration.name}constructor(e){super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,sessionAwareness:!1,forceSyncInterval:!1,flushDelay:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.pendingUpdates=[],this.pendingAwarenessClients=/* @__PURE__ */new Set,this.flushTimeout=null,this.sessionId=Math.random().toString(36).slice(2),this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=()=>this.emit("connect"),this.forwardStatus=e=>this.emit("status",e),this.forwardClose=e=>this.emit("close",e),this.forwardDisconnect=e=>this.emit("disconnect",e),this.forwardDestroy=()=>this.emit("destroy"),this.setConfiguration(e),this.configuration.document=e.document?e.document:new Cs,this.configuration.awareness=void 0!==e.awareness?e.awareness:new vl(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),this.awareness?.on("update",()=>{this.emit("awarenessUpdate",{states:oi(this.awareness.getStates())})}),this.awareness?.on("change",()=>{this.emit("awarenessChange",{states:oi(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),this.awareness?.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&"number"==typeof this.configuration.forceSyncInterval&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(e={}){e.websocketProvider||(this.manageSocket=!0,this.configuration.websocketProvider=new Il(e)),this.configuration={...this.configuration,...e}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),0===this.unsyncedChanges&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(Hl,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&_l(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(Wl,{documentName:this.effectiveName,payload:e})}async sendToken(){let e;try{e=await this.getToken()}catch(t){return void this.permissionDeniedHandler(`Failed to get token during sendToken(): ${t}`)}this.send(Fl,{token:e??"",documentName:this.effectiveName})}get batchingEnabled(){return!!this.configuration.flushDelay&&"number"==typeof this.configuration.flushDelay}documentUpdateHandler(e,t){if(t!==this){if(!this.batchingEnabled)return this.incrementUnsyncedChanges(),void this.send(ql,{update:e,documentName:this.effectiveName});0===this.pendingUpdates.length&&this.incrementUnsyncedChanges(),this.pendingUpdates.push(e),this.scheduleFlush()}}awarenessUpdateHandler({added:e,updated:t,removed:n},r){if(r===this)return;const i=e.concat(t).concat(n);if(this.batchingEnabled){for(const e of i)this.pendingAwarenessClients.add(e);this.scheduleFlush()}else this.send(Bl,{awareness:this.awareness,clients:i,documentName:this.effectiveName})}scheduleFlush(){null===this.flushTimeout&&(this.flushTimeout=setTimeout(()=>{this.flushTimeout=null,this.flushPendingUpdates()},this.configuration.flushDelay))}flushPendingUpdates(){if(null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates.length>0){const e=1===this.pendingUpdates.length?this.pendingUpdates[0]:Lo(this.pendingUpdates);this.pendingUpdates=[],this.send(ql,{update:e,documentName:this.effectiveName})}if(this.pendingAwarenessClients.size>0){const e=Array.from(this.pendingAwarenessClients);this.pendingAwarenessClients.clear(),this.send(Bl,{awareness:this.awareness,clients:e,documentName:this.effectiveName})}}get synced(){return this.isSynced}set synced(e){this.isSynced!==e&&(this.isSynced=e,e&&this.emit("synced",{state:e}))}receiveStateless(e){this.emit("stateless",{payload:e})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect()}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect()}async onOpen(e){this.isAuthenticated=!1,this.emit("open",{event:e}),await this.sendToken(),this.startSync()}async getToken(){return"function"==typeof this.configuration.token?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(Hl,{document:this.document,documentName:this.effectiveName}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(Bl,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;const n=new jl(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new Ol(e.data),{documentName:n}=ci(t.readVarString());t.writeVarString(this.effectiveName),this.emit("message",{event:e,message:new Ol(e.data)}),new Ul(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates=[],this.pendingAwarenessClients.clear(),this.awareness&&_l(this.awareness,Array.from(this.awareness.getStates().keys()).filter(e=>e!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(_l(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.flushPendingUpdates(),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),"undefined"!=typeof window&&"removeEventListener"in window&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("status",this.forwardStatus),this.configuration.websocketProvider.off("status",this.configuration.onStatus),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("status",this.configuration.onStatus),this.configuration.websocketProvider.on("status",this.forwardStatus),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(e){this.emit("authenticationFailed",{reason:e}),this.isAuthenticated=!1}authenticatedHandler(e){this.isAuthenticated=!0,this.authorizedScope=e,this.emit("authenticated",{scope:e})}setAwarenessField(e,t){if(!this.awareness)throw new Vl(`Cannot set awareness field "${e}" to ${JSON.stringify(t)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(e,t)}},$l=e=>an((t,n)=>{e.onerror=e=>n(new Error(e.target.error)),e.onsuccess=e=>t(e.target.result)}),Yl=(e,t,n="readwrite")=>{const r=e.transaction(t,n);return t.map(e=>Zl(r,e))},Jl=(e,t)=>$l(e.count(t)),Ql=(e,t)=>$l(e.delete(t)),Kl=(e,t)=>$l(e.add(t)),Gl=(e,t=null)=>((e,t,n)=>{let r=null;return Xl(e,t,e=>(r=e,!1),n).then(()=>r)})(e,t,"prev"),Xl=(e,t,n,r="next")=>((e,t)=>an((n,r)=>{e.onerror=r,e.onsuccess=async e=>{const r=e.target.result;if(null===r||!1===await t(r))return n();r.continue()}}))(e.openKeyCursor(t,r),e=>n(e.key)),Zl=(e,t)=>e.objectStore(t),eh="custom",th="updates",nh=(e,t=()=>{},n=()=>{})=>{const[r]=Yl(e.db,[th]);return(i=r,a=e._dbref,c=!1,s=IDBKeyRange.lowerBound(a,c),$l(i.getAll(s,o))).then(i=>{e._destroyed||(t(r),Ao(e.doc,()=>{i.forEach(t=>Ns(e.doc,t))},e,!1),n(r))}).then(()=>Gl(r).then(t=>{e._dbref=t+1})).then(()=>Jl(r).then(t=>{e._dbsize=t})).then(()=>r);var i,s,o,a,c},rh=(e,t=!0)=>nh(e).then(n=>{(t||e._dbsize>=500)&&Kl(n,Us(e.doc)).then(()=>{return Ql(n,(t=e._dbref,r=!0,IDBKeyRange.upperBound(t,r)));var t,r}).then(()=>Jl(n).then(t=>{e._dbsize=t}))}),ih=class extends Ze{constructor(e,t){super(),this.doc=t,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=((e,t)=>an((n,r)=>{const i=indexedDB.open(e);i.onupgradeneeded=e=>t(e.target.result),i.onerror=e=>r(on(e.target.error)),i.onsuccess=e=>{const t=e.target.result;t.onversionchange=()=>{t.close()},n(t)}}))(e,e=>((e,t)=>t.forEach(t=>e.createObjectStore.apply(e,t)))(e,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=an(e=>this.on("synced",()=>e(this))),this._db.then(e=>{this.db=e;nh(this,e=>Kl(e,Us(t)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(e,t)=>{if(this.db&&t!==this){const[t]=Yl(this.db,[th]);Kl(t,e),++this._dbsize>=500&&(null!==this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{rh(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},t.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),t.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(e=>{e.close()})}clearData(){return this.destroy().then(()=>{var e;e=this.name,$l(indexedDB.deleteDatabase(e))})}get(e){return this._db.then(t=>{const[n]=Yl(t,[eh],"readonly");return((e,t)=>$l(e.get(t)))(n,e)})}set(e,t){return this._db.then(n=>{const[r]=Yl(n,[eh]);return((e,t,n)=>$l(e.put(t,n)))(r,t,e)})}del(e){return this._db.then(t=>{const[n]=Yl(t,[eh]);return Ql(n,e)})}},sh=3e4,oh=e=>{if(e.shouldConnect&&null===e.ws){const t=new WebSocket(e.url),n=e.binaryType;let r=null;n&&(t.binaryType=n),e.ws=t,e.connecting=!0,e.connected=!1,t.onmessage=t=>{e.lastMessageReceived=At();const n=t.data,i="string"==typeof n?JSON.parse(n):n;i&&"pong"===i.type&&(clearTimeout(r),r=setTimeout(s,15e3)),e.emit("message",[i,e])};const i=t=>{null!==e.ws&&(e.ws=null,e.connecting=!1,e.connected?(e.connected=!1,e.emit("disconnect",[{type:"disconnect",error:t},e])):e.unsuccessfulReconnects++,setTimeout(oh,Ye(1200*ct(e.unsuccessfulReconnects+1),2500),e)),clearTimeout(r)},s=()=>{e.ws===t&&e.send({type:"ping"})};t.onclose=()=>i(null),t.onerror=e=>i(e),t.onopen=()=>{e.lastMessageReceived=At(),e.connecting=!1,e.connected=!0,e.unsuccessfulReconnects=0,e.emit("connect",[{type:"connect"},e]),r=setTimeout(s,15e3)}}},ah=class extends Ze{constructor(e,{binaryType:t}={}){super(),this.url=e,this.ws=null,this.binaryType=t||null,this.connected=!1,this.connecting=!1,this.unsuccessfulReconnects=0,this.lastMessageReceived=0,this.shouldConnect=!0,this._checkInterval=setInterval(()=>{this.connected&&sh<At()-this.lastMessageReceived&&this.ws.close()},15e3),oh(this)}send(e){this.ws&&this.ws.send(JSON.stringify(e))}destroy(){clearInterval(this._checkInterval),this.disconnect(),super.destroy()}disconnect(){this.shouldConnect=!1,null!==this.ws&&this.ws.close()}connect(){this.shouldConnect=!0,this.connected||null!==this.ws||oh(this)}},ch=/* @__PURE__ */new Map,lh="undefined"==typeof BroadcastChannel?class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.key===e&&null!==this.onmessage&&this.onmessage({data:at(t.newValue||"")}),Je(this._onChange)}postMessage(e){tt.setItem(this.room,dt(st(e)))}close(){St(this._onChange)}}:BroadcastChannel,hh=e=>cn(ch,e,()=>{const t=_t(),n=new lh(e);return n.onmessage=e=>t.forEach(t=>t(e.data,"broadcastchannel")),{bc:n,subs:t}}),dh=/* @__PURE__ */t(/* @__PURE__ */n((t,n)=>{!function(e){if("object"==typeof t&&void 0!==n)n.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window).SimplePeer=e()}}(function(){var t=Math.floor,n=Math.abs,r=Math.pow;return function t(n,r,i){function s(a,c){if(!r[a]){if(!n[a]){var l="function"==typeof e&&e;if(!c&&l)return l(a,!0);if(o)return o(a,!0);var h=/* @__PURE__ */new Error("Cannot find module '"+a+"'");throw h.code="MODULE_NOT_FOUND",h}var d=r[a]={exports:{}};n[a][0].call(d.exports,function(e){return s(n[a][1][e]||e)},d,d.exports,t,n,r,i)}return r[a].exports}for(var o="function"==typeof e&&e,a=0;a<i.length;a++)s(i[a]);return s}({1:[function(e,t,n){function r(e){var t=e.length;if(0<t%4)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function i(e){return o[63&e>>18]+o[63&e>>12]+o[63&e>>6]+o[63&e]}function s(e,t,n){for(var r,s=[],o=t;o<n;o+=3)r=(16711680&e[o]<<16)+(65280&e[o+1]<<8)+(255&e[o+2]),s.push(i(r));return s.join("")}n.byteLength=function(e){var t=r(e),n=t[0],i=t[1];return 3*(n+i)/4-i},n.toByteArray=function(e){var t,n,i=r(e),s=i[0],o=i[1],l=new c(function(e,t,n){return 3*(t+n)/4-n}(0,s,o)),h=0,d=0<o?s-4:s;for(n=0;n<d;n+=4)t=a[e.charCodeAt(n)]<<18|a[e.charCodeAt(n+1)]<<12|a[e.charCodeAt(n+2)]<<6|a[e.charCodeAt(n+3)],l[h++]=255&t>>16,l[h++]=255&t>>8,l[h++]=255&t;return 2===o&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,l[h++]=255&t),1===o&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[e.charCodeAt(n+2)]>>2,l[h++]=255&t>>8,l[h++]=255&t),l},n.fromByteArray=function(e){for(var t,n=e.length,r=n%3,i=[],a=16383,c=0,l=n-r;c<l;c+=a)i.push(s(e,c,c+a>l?l:c+a));return 1===r?(t=e[n-1],i.push(o[t>>2]+o[63&t<<4]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(o[t>>10]+o[63&t>>4]+o[63&t<<2]+"=")),i.join("")};for(var o=[],a=[],c="undefined"==typeof Uint8Array?Array:Uint8Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=0;h<64;++h)o[h]=l[h],a[l.charCodeAt(h)]=h;a[45]=62,a[95]=63},{}],2:[function(){},{}],3:[function(e,t,n){(function(){(function(){var t=String.fromCharCode,i=Math.min;function s(e){if(2147483647<e)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=o.prototype,t}function o(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if(("string"!=typeof t||""===t)&&(t="utf8"),!o.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|u(e,t),r=s(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}(e,t);if(ArrayBuffer.isView(e))return h(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(F(e,ArrayBuffer)||e&&F(e.buffer,ArrayBuffer))return function(e,t,n){if(0>t||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n);return r.__proto__=o.prototype,r}(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return o.from(r,t,n);var i=function(e){if(o.isBuffer(e)){var t=0|d(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0===e.length?"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0:"number"!=typeof e.length||B(e.length)?s(0):h(e)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(0>e)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return c(e),s(0>e?0:0|d(e))}function h(e){for(var t=0>e.length?0:0|d(e.length),n=s(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function d(e){if(e>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647..toString(16)+" bytes");return 0|e}function u(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||F(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=2<arguments.length&&!0===arguments[2];if(!r&&0===n)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return I(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return U(e).length;default:if(i)return r?-1:I(e).length;t=(""+t).toLowerCase(),i=!0}}function f(e,t,n){var r=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),0>=n)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return S(this,t,n);case"ascii":return A(this,t,n);case"latin1":case"binary":return T(this,t,n);case"base64":return C(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function p(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):2147483647<n?n=2147483647:-2147483648>n&&(n=-2147483648),B(n=+n)&&(n=i?0:e.length-1),0>n&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(0>n){if(!i)return-1;n=0}if("string"==typeof t&&(t=o.from(t,r)),o.isBuffer(t))return 0===t.length?-1:m(e,t,n,r,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):m(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function m(e,t,n,r,i){function s(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var o,a=1,c=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=(r+"").toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(2>e.length||2>t.length)return-1;a=2,c/=2,l/=2,n/=2}if(i){var h=-1;for(o=n;o<c;o++)if(s(e,o)!==s(t,-1===h?0:o-h))-1!==h&&(o-=o-h),h=-1;else if(-1===h&&(h=o),o-h+1===l)return h*a}else for(n+l>c&&(n=c-l),o=n;0<=o;o--){for(var d=!0,u=0;u<l;u++)if(s(e,o+u)!==s(t,u)){d=!1;break}if(d)return o}return-1}function y(e,t,n,r){n=+n||0;var i=e.length-n;r?(r=+r)>i&&(r=i):r=i;var s=t.length;r>s/2&&(r=s/2);for(var o,a=0;a<r;++a){if(B(o=parseInt(t.substr(2*a,2),16)))return a;e[n+a]=o}return a}function b(e,t,n,r){return j(I(t,e.length-n),e,n,r)}function w(e,t,n,r){return j(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return w(e,t,n,r)}function _(e,t,n,r){return j(U(t),e,n,r)}function k(e,t,n,r){return j(function(e,t){for(var n,r,i,s=[],o=0;o<e.length&&!(0>(t-=2));++o)n=e.charCodeAt(o),r=n>>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function C(e,t,n){return 0===t&&n===e.length?W.fromByteArray(e):W.fromByteArray(e.slice(t,n))}function S(e,t,n){n=i(e.length,n);for(var r=[],s=t;s<n;){var o,a,c,l,h=e[s],d=null,u=239<h?4:223<h?3:191<h?2:1;if(s+u<=n)1===u?128>h&&(d=h):2===u?128==(192&(o=e[s+1]))&&(127<(l=(31&h)<<6|63&o)&&(d=l)):3===u?(o=e[s+1],a=e[s+2],128==(192&o)&&128==(192&a)&&(2047<(l=(15&h)<<12|(63&o)<<6|63&a)&&(55296>l||57343<l)&&(d=l))):4===u&&(o=e[s+1],a=e[s+2],c=e[s+3],128==(192&o)&&128==(192&a)&&128==(192&c)&&(65535<(l=(15&h)<<18|(63&o)<<12|(63&a)<<6|63&c)&&1114112>l&&(d=l)));null===d?(d=65533,u=1):65535<d&&(d-=65536,r.push(55296|1023&d>>>10),d=56320|1023&d),r.push(d),s+=u}return E(r)}function E(e){var n=e.length;if(n<=4096)return t.apply(String,e);for(var r="",i=0;i<n;)r+=t.apply(String,e.slice(i,i+=4096));return r}function A(e,n,r){var s="";r=i(e.length,r);for(var o=n;o<r;++o)s+=t(127&e[o]);return s}function T(e,n,r){var s="";r=i(e.length,r);for(var o=n;o<r;++o)s+=t(e[o]);return s}function x(e,t,n){var r=e.length;(!t||0>t)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var i="",s=t;s<n;++s)i+=N(e[s]);return i}function R(e,n,r){for(var i=e.slice(n,r),s="",o=0;o<i.length;o+=2)s+=t(i[o]+256*i[o+1]);return s}function D(e,t,n){if(0!=e%1||0>e)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,r,i,s){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function P(e,t,n,r){if(n+r>e.length)throw new RangeError("Index out of range");if(0>n)throw new RangeError("Index out of range")}function L(e,t,n,r,i){return t=+t,n>>>=0,i||P(e,0,n,4),H.write(e,t,n,r,23,4),n+4}function M(e,t,n,r,i){return t=+t,n>>>=0,i||P(e,0,n,8),H.write(e,t,n,r,52,8),n+8}function N(e){return 16>e?"0"+e.toString(16):e.toString(16)}function I(e,t){t=t||1/0;for(var n,r=e.length,i=null,s=[],o=0;o<r;++o){if(55295<(n=e.charCodeAt(o))&&57344>n){if(!i){if(56319<n){-1<(t-=3)&&s.push(239,191,189);continue}if(o+1===r){-1<(t-=3)&&s.push(239,191,189);continue}i=n;continue}if(56320>n){-1<(t-=3)&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&-1<(t-=3)&&s.push(239,191,189);if(i=null,128>n){if(0>(t-=1))break;s.push(n)}else if(2048>n){if(0>(t-=2))break;s.push(192|n>>6,128|63&n)}else if(65536>n){if(0>(t-=3))break;s.push(224|n>>12,128|63&n>>6,128|63&n)}else{if(!(1114112>n))throw new Error("Invalid code point");if(0>(t-=4))break;s.push(240|n>>18,128|63&n>>12,128|63&n>>6,128|63&n)}}return s}function U(e){return W.toByteArray(function(e){if(2>(e=(e=e.split("=")[0]).trim().replace(q,"")).length)return"";for(;0!=e.length%4;)e+="=";return e}(e))}function j(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function F(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function B(e){return e!=e}var W=e("base64-js"),H=e("ieee754");n.Buffer=o,n.SlowBuffer=function(e){return+e!=e&&(e=0),o.alloc(+e)},n.INSPECT_MAX_BYTES=50,n.kMaxLength=2147483647,o.TYPED_ARRAY_SUPPORT=function(){try{var e=/* @__PURE__ */new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||console.error,Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){return o.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){return o.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),o.poolSize=8192,o.from=function(e,t,n){return a(e,t,n)},o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,o.alloc=function(e,t,n){return function(e,t,n){return c(e),0>=e||void 0===t?s(e):"string"==typeof n?s(e).fill(t,n):s(e).fill(t)}(e,t,n)},o.allocUnsafe=function(e){return l(e)},o.allocUnsafeSlow=function(e){return l(e)},o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(F(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),F(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,s=0,a=i(n,r);s<a;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},o.isEncoding=function(e){switch((e+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=o.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var s=e[n];if(F(s,Uint8Array)&&(s=o.from(s)),!o.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,i),i+=s.length}return r},o.byteLength=u,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var e=this.length;if(0!=e%2)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},o.prototype.swap32=function(){var e=this.length;if(0!=e%4)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},o.prototype.swap64=function(){var e=this.length;if(0!=e%8)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},o.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?S(this,0,e):f.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",t=n.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},o.prototype.compare=function(e,t,n,r,s){if(F(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),0>t||n>e.length||0>r||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(s>>>=0)-(r>>>=0),c=(n>>>=0)-(t>>>=0),l=i(a,c),h=this.slice(r,s),d=e.slice(t,n),u=0;u<l;++u)if(h[u]!==d[u]){a=h[u],c=d[u];break}return a<c?-1:c<a?1:0},o.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},o.prototype.indexOf=function(e,t,n){return p(this,e,t,n,!0)},o.prototype.lastIndexOf=function(e,t,n){return p(this,e,t,n,!1)},o.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),0<e.length&&(0>n||0>t)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return y(this,e,t,n);case"utf8":case"utf-8":return b(this,e,t,n);case"ascii":return w(this,e,t,n);case"latin1":case"binary":return v(this,e,t,n);case"base64":return _(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},o.prototype.slice=function(e,t){var n=this.length;0>(e=~~e)?0>(e+=n)&&(e=0):e>n&&(e=n),0>(t=void 0===t?n:~~t)?0>(t+=n)&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return r.__proto__=o.prototype,r},o.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var r=this[e],i=1,s=0;++s<t&&(i*=256);)r+=this[e+s]*i;return r},o.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var r=this[e+--t],i=1;0<t&&(i*=256);)r+=this[e+--t]*i;return r},o.prototype.readUInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var i=this[e],s=1,o=0;++o<t&&(s*=256);)i+=this[e+o]*s;return i>=(s*=128)&&(i-=r(2,8*t)),i},o.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var i=t,s=1,o=this[e+--i];0<i&&(s*=256);)o+=this[e+--i]*s;return o>=(s*=128)&&(o-=r(2,8*t)),o},o.prototype.readInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||D(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt16BE=function(e,t){e>>>=0,t||D(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||D(e,4,this.length),H.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||D(e,4,this.length),H.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||D(e,8,this.length),H.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||D(e,8,this.length),H.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,n,i){(e=+e,t>>>=0,n>>>=0,i)||O(this,e,t,n,r(2,8*n)-1,0);var s=1,o=0;for(this[t]=255&e;++o<n&&(s*=256);)this[t+o]=255&e/s;return t+n},o.prototype.writeUIntBE=function(e,t,n,i){(e=+e,t>>>=0,n>>>=0,i)||O(this,e,t,n,r(2,8*n)-1,0);var s=n-1,o=1;for(this[t+s]=255&e;0<=--s&&(o*=256);)this[t+s]=255&e/o;return t+n},o.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){var s=r(2,8*n-1);O(this,e,t,n,s-1,-s)}var o=0,a=1,c=0;for(this[t]=255&e;++o<n&&(a*=256);)0>e&&0===c&&0!==this[t+o-1]&&(c=1),this[t+o]=255&(e/a|0)-c;return t+n},o.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){var s=r(2,8*n-1);O(this,e,t,n,s-1,-s)}var o=n-1,a=1,c=0;for(this[t+o]=255&e;0<=--o&&(a*=256);)0>e&&0===c&&0!==this[t+o+1]&&(c=1),this[t+o]=255&(e/a|0)-c;return t+n},o.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},o.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},o.prototype.writeDoubleLE=function(e,t,n){return M(this,e,t,!0,n)},o.prototype.writeDoubleBE=function(e,t,n){return M(this,e,t,!1,n)},o.prototype.copy=function(e,t,n,r){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),0<r&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(0>t)throw new RangeError("targetStart out of bounds");if(0>n||n>=this.length)throw new RangeError("Index out of range");if(0>r)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var i=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var s=i-1;0<=s;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return i},o.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!o.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var i=e.charCodeAt(0);("utf8"===r&&128>i||"latin1"===r)&&(e=i)}}else"number"==typeof e&&(e&=255);if(0>t||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var a=o.isBuffer(e)?e:o.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=a[s%c]}return this};var q=/[^+/0-9A-Za-z-_]/g}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:9}],4:[function(e,t,n){(function(r){(function(){n.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"===e||(r++,"%c"===e&&(i=r))}),e.splice(i,0,n)},n.save=function(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}},n.load=function(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e},n.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},n.storage=function(){try{return localStorage}catch(e){}}(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0)}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],n.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(n);const{formatters:i}=t.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":5,_process:12}],5:[function(e,t){t.exports=function(t){function r(e){function t(...e){if(!t.enabled)return;const i=t,s=+/* @__PURE__ */new Date;i.diff=s-(n||s),i.prev=n,i.curr=s,n=s,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,n)=>{if("%%"===t)return"%";o++;const s=r.formatters[n];if("function"==typeof s){const n=e[o];t=s.call(i,n),e.splice(o,1),o--}return t}),r.formatArgs.call(i,e),(i.log||r.log).apply(i,e)}let n,s=null;return t.namespace=e,t.useColors=r.useColors(),t.color=r.selectColor(e),t.extend=i,t.destroy=r.destroy,Object.defineProperty(t,"enabled",{enumerable:!0,configurable:!1,get:()=>null===s?r.enabled(e):s,set:e=>{s=e}}),"function"==typeof r.init&&r.init(t),t}function i(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return r.debug=r,r.default=r,r.coerce=function(e){return e instanceof Error?e.stack||e.message:e},r.disable=function(){const e=[...r.names.map(s),...r.skips.map(s).map(e=>"-"+e)].join(",");return r.enable(""),e},r.enable=function(e){let t;r.save(e),r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(t=0;t<i;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))},r.enabled=function(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=r.skips.length;t<n;t++)if(r.skips[t].test(e))return!1;for(t=0,n=r.names.length;t<n;t++)if(r.names[t].test(e))return!0;return!1},r.humanize=e("ms"),r.destroy=function(){},Object.keys(t).forEach(e=>{r[e]=t[e]}),r.names=[],r.skips=[],r.formatters={},r.selectColor=function(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return r.colors[n(t)%r.colors.length]},r.enable(r.load()),r}},{ms:11}],6:[function(e,t){function n(e,t){for(const n in t)Object.defineProperty(e,n,{value:t[n],enumerable:!0,configurable:!0});return e}t.exports=function(e,t,r){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");r||(r={}),"object"==typeof t&&(r=t,t=""),t&&(r.code=t);try{return n(e,r)}catch(t){r.message=e.message,r.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),n(new i,r)}}},{}],7:[function(e,t){function n(){n.init.call(this)}function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function i(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function s(e,t,n,s){var o,a,c;if(r(n),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]),void 0===c)c=a[t]=n,++e._eventsCount;else if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),0<(o=i(e))&&c.length>o&&!c.warned){c.warned=!0;var l=/* @__PURE__ */new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,console&&console.warn}return e}function o(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function a(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=o.bind(r);return i.listener=n,r.wrapFn=i,i}function c(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):h(i,i.length)}function l(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function h(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function d(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){r.once&&e.removeEventListener(t,i),n(s)})}}var u,f="object"==typeof Reflect?Reflect:null,g=f&&"function"==typeof f.apply?f.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};u=f&&"function"==typeof f.ownKeys?f.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var p=Number.isNaN||function(e){return e!=e};t.exports=n,t.exports.once=function(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,s),r(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}d(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&d(e,"error",t,n)}(e,i,{once:!0})})},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var m=10;Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return m},set:function(e){if("number"!=typeof e||0>e||p(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");m=e}}),n.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||p(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return i(this)},n.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,i=this._events;if(void 0!==i)r=r&&void 0===i.error;else if(!r)return!1;if(r){var s;if(0<t.length&&(s=t[0]),s instanceof Error)throw s;var o=/* @__PURE__ */new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)g(a,this,t);else{var c=a.length,l=h(a,c);for(n=0;n<c;++n)g(l[n],this,t)}return!0},n.prototype.addListener=function(e,t){return s(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return s(this,e,t,!0)},n.prototype.once=function(e,t){return r(t),this.on(e,a(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return r(t),this.prependListener(e,a(this,e,t)),this},n.prototype.removeListener=function(e,t){var n,i,s,o,a;if(r(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;0<=o;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,s=o;break}if(0>s)return this;0===s?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,s),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,n,r=this._events;if(void 0===r)return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;0<=n;n--)this.removeListener(e,t[n]);return this},n.prototype.listeners=function(e){return c(this,e,!0)},n.prototype.rawListeners=function(e){return c(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):l.call(e,t)},n.prototype.listenerCount=l,n.prototype.eventNames=function(){return 0<this._eventsCount?u(this._events):[]}},{}],8:[function(e,t){t.exports=function(){if("undefined"==typeof globalThis)return null;var e={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}},{}],9:[function(e,i,s){s.read=function(e,t,n,i,s){var o,a,c=8*s-i-1,l=(1<<c)-1,h=l>>1,d=-7,u=n?s-1:0,f=n?-1:1,g=e[t+u];for(u+=f,o=g&(1<<-d)-1,g>>=-d,d+=c;0<d;o=256*o+e[t+u],u+=f,d-=8);for(a=o&(1<<-d)-1,o>>=-d,d+=i;0<d;a=256*a+e[t+u],u+=f,d-=8);if(0===o)o=1-h;else{if(o===l)return a?NaN:1/0*(g?-1:1);a+=r(2,i),o-=h}return(g?-1:1)*a*r(2,o-i)},s.write=function(e,i,s,o,a,c){var l,h,d,u=Math.LN2,f=Math.log,g=8*c-a-1,p=(1<<g)-1,m=p>>1,y=23===a?r(2,-24)-r(2,-77):0,b=o?0:c-1,w=o?1:-1,v=0>i||0===i&&0>1/i?1:0;for(i=n(i),isNaN(i)||i===1/0?(h=isNaN(i)?1:0,l=p):(l=t(f(i)/u),1>i*(d=r(2,-l))&&(l--,d*=2),2<=(i+=1<=l+m?y/d:y*r(2,1-m))*d&&(l++,d/=2),l+m>=p?(h=0,l=p):1<=l+m?(h=(i*d-1)*r(2,a),l+=m):(h=i*r(2,m-1)*r(2,a),l=0));8<=a;e[s+b]=255&h,b+=w,h/=256,a-=8);for(l=l<<a|h,g+=a;0<g;e[s+b]=255&l,b+=w,l/=256,g-=8);e[s+b-w]|=128*v}},{}],10:[function(e,t){t.exports="function"==typeof Object.create?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],11:[function(e,t){var r=Math.round;function i(e){var t=n(e);return 864e5<=t?r(e/864e5)+"d":36e5<=t?r(e/36e5)+"h":6e4<=t?r(e/6e4)+"m":1e3<=t?r(e/1e3)+"s":e+"ms"}function s(e){var t=n(e);return 864e5<=t?o(e,t,864e5,"day"):36e5<=t?o(e,t,36e5,"hour"):6e4<=t?o(e,t,6e4,"minute"):1e3<=t?o(e,t,1e3,"second"):e+" ms"}function o(e,t,n,i){return r(e/n)+" "+i+(t>=1.5*n?"s":"")}t.exports=function(e,t){t=t||{};var n=typeof e;if("string"==n&&0<e.length)return function(e){if(!(100<(e+="").length)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();return"years"===r||"year"===r||"yrs"===r||"yr"===r||"y"===r?315576e5*n:"weeks"===r||"week"===r||"w"===r?6048e5*n:"days"===r||"day"===r||"d"===r?864e5*n:"hours"===r||"hour"===r||"hrs"===r||"hr"===r||"h"===r?36e5*n:"minutes"===r||"minute"===r||"mins"===r||"min"===r||"m"===r?6e4*n:"seconds"===r||"second"===r||"secs"===r||"sec"===r||"s"===r?1e3*n:"milliseconds"===r||"millisecond"===r||"msecs"===r||"msec"===r||"ms"===r?n:void 0}}}(e);if("number"===n&&isFinite(e))return t.long?s(e):i(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],12:[function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function i(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(n){try{return l.call(null,e,0)}catch(n){return l.call(this,e,0)}}}function s(){g&&u&&(g=!1,u.length?f=u.concat(f):p=-1,f.length&&o())}function o(){if(!g){var e=i(s);g=!0;for(var t=f.length;t;){for(u=f,f=[];++p<t;)u&&u[p].run();p=-1,t=f.length}u=null,g=!1,function(e){if(h===clearTimeout)return clearTimeout(e);if((h===r||!h)&&clearTimeout)return h=clearTimeout,clearTimeout(e);try{return h(e)}catch(n){try{return h.call(null,e)}catch(n){return h.call(this,e)}}}(e)}}function a(e,t){this.fun=e,this.array=t}function c(){}var l,h,d=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{h="function"==typeof clearTimeout?clearTimeout:r}catch(t){h=r}}();var u,f=[],g=!1,p=-1;d.nextTick=function(e){var t=Array(arguments.length-1);if(1<arguments.length)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];f.push(new a(e,t)),1!==f.length||g||i(o)},a.prototype.run=function(){this.fun.apply(null,this.array)},d.title="browser",d.browser=!0,d.env={},d.argv=[],d.version="",d.versions={},d.on=c,d.addListener=c,d.once=c,d.off=c,d.removeListener=c,d.removeAllListeners=c,d.emit=c,d.prependListener=c,d.prependOnceListener=c,d.listeners=function(){return[]},d.binding=function(){throw new Error("process.binding is not supported")},d.cwd=function(){return"/"},d.chdir=function(){throw new Error("process.chdir is not supported")},d.umask=function(){return 0}},{}],13:[function(e,t){(function(e){(function(){let n;t.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"==typeof window?e:window):e=>(n||(n=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0))}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],14:[function(e,t){(function(n,r){(function(){var i=e("safe-buffer").Buffer,s=r.crypto||r.msCrypto;t.exports=s&&s.getRandomValues?function(e,t){if(e>4294967295)throw new RangeError("requested too many random bytes");var r=i.allocUnsafe(e);if(0<e)if(65536<e)for(var o=0;o<e;o+=65536)s.getRandomValues(r.slice(o,o+65536));else s.getRandomValues(r);return"function"==typeof t?n.nextTick(function(){t(null,r)}):r}:function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{_process:12,"safe-buffer":30}],15:[function(e,t){function n(e,t,n){function r(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var s=function(e){function t(t,n,i){return e.call(this,r(t,n,i))||this}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}(t,e),t}(n);s.prototype.name=n.name,s.prototype.code=e,i[e]=s}function r(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map(function(e){return e+""}),2<n?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(e+"")}var i={};n("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError),n("ERR_INVALID_ARG_TYPE",function(e,t,n){var i,s;if("string"==typeof t&&function(e,t,n){return e.substr(!n||0>n?0:+n,t.length)===t}(t,"not ")?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}(e," argument"))s="The ".concat(e," ").concat(i," ").concat(r(t,"type"));else{var o=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(o," ").concat(i," ").concat(r(t,"type"))}return s+=". Received type ".concat(typeof n)},TypeError),n("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),n("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"}),n("ERR_STREAM_PREMATURE_CLOSE","Premature close"),n("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"}),n("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),n("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),n("ERR_STREAM_WRITE_AFTER_END","write after end"),n("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),n("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError),n("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=i},{}],16:[function(e,t){(function(n){(function(){function r(e){return this instanceof r?(a.call(this,e),c.call(this,e),this.allowHalfOpen=!0,void(e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",i))))):new r(e)}function i(){this._writableState.ended||n.nextTick(s,this)}function s(e){e.end()}var o=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var a=e("./_stream_readable"),c=e("./_stream_writable");e("inherits")(r,a);for(var l,h=o(c.prototype),d=0;d<h.length;d++)l=h[d],r.prototype[l]||(r.prototype[l]=c.prototype[l]);Object.defineProperty(r.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(r.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(r.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(r.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0===this._readableState||void 0===this._writableState||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":18,"./_stream_writable":20,_process:12,inherits:10}],17:[function(e,t){function n(e){return this instanceof n?void r.call(this,e):new n(e)}t.exports=n;var r=e("./_stream_transform");e("inherits")(n,r),n.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":19,inherits:10}],18:[function(e,t){(function(n,r){(function(){function i(t,n,r){k=k||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof k),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=M(this,t,"readableHighWaterMark",r),this.buffer=new P,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(!R&&(R=e("string_decoder/").StringDecoder),this.decoder=new R(t.encoding),this.encoding=t.encoding)}function s(t){if(k=k||e("./_stream_duplex"),!(this instanceof s))return new s(t);var n=this instanceof k;this._readableState=new i(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),E.call(this)}function o(e,t,n,r,i){C("readableAddChunk",t);var s,o=e._readableState;if(null===t)o.reading=!1,function(e,t){if(C("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?h(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,d(e)))}}(e,o);else if(i||(s=c(o,t)),s)B(e,s);else if(o.objectMode||t&&0<t.length)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===A.prototype||(t=function(e){return A.from(e)}(t)),r)o.endEmitted?B(e,new F):a(e,o,t,!0);else if(o.ended)B(e,new U);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||0!==t.length?a(e,o,t,!1):u(e,o)):a(e,o,t,!1)}else r||(o.reading=!1,u(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.length)}function a(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&h(e)),u(e,t)}function c(e,t){var n;return function(e){return A.isBuffer(e)||e instanceof T}(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new I("chunk",["string","Buffer","Uint8Array"],t)),n}function l(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e==e?(e>t.highWaterMark&&(t.highWaterMark=function(e){return 1073741824<=e?e=1073741824:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function h(e){var t=e._readableState;C("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(C("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(d,e))}function d(e){var t=e._readableState;C("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,y(e)}function u(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(f,e,t))}function f(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(C("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function g(e){var t=e._readableState;t.readableListening=0<e.listenerCount("readable"),t.resumeScheduled&&!t.paused?t.flowing=!0:0<e.listenerCount("data")&&e.resume()}function p(e){C("readable nexttick read 0"),e.read(0)}function m(e,t){C("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),y(e),t.flowing&&!t.reading&&e.read(0)}function y(e){var t=e._readableState;for(C("flow",t.flowing);t.flowing&&null!==e.read(););}function b(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function w(e){var t=e._readableState;C("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(v,t,e))}function v(e,t){if(C("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function _(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}var k,C;t.exports=s,s.ReadableState=i,e("events").EventEmitter;var S=function(e,t){return e.listeners(t).length},E=e("./internal/streams/stream"),A=e("buffer").Buffer,T=r.Uint8Array||function(){},x=e("util");C=x&&x.debuglog?x.debuglog("stream"):function(){};var R,D,O,P=e("./internal/streams/buffer_list"),L=e("./internal/streams/destroy"),M=e("./internal/streams/state").getHighWaterMark,N=e("../errors").codes,I=N.ERR_INVALID_ARG_TYPE,U=N.ERR_STREAM_PUSH_AFTER_EOF,j=N.ERR_METHOD_NOT_IMPLEMENTED,F=N.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(s,E);var B=L.errorOrDestroy,W=["error","close","destroy","pause","resume"];Object.defineProperty(s.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),s.prototype.destroy=L.destroy,s.prototype._undestroy=L.undestroy,s.prototype._destroy=function(e,t){t(e)},s.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=A.from(e,t),t=""),n=!0),o(this,e,t,!1,n)},s.prototype.unshift=function(e){return o(this,e,null,!0,!1)},s.prototype.isPaused=function(){return!1===this._readableState.flowing},s.prototype.setEncoding=function(t){R||(R=e("string_decoder/").StringDecoder);var n=new R(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,i="";null!==r;)i+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==i&&this._readableState.buffer.push(i),this._readableState.length=i.length,this},s.prototype.read=function(e){C("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0===t.highWaterMark?0<t.length:t.length>=t.highWaterMark)||t.ended))return C("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?w(this):h(this),null;if(0===(e=l(e,t))&&t.ended)return 0===t.length&&w(this),null;var r=t.needReadable;C("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&C("length less than watermark",r=!0),t.ended||t.reading?C("reading or ended",r=!1):r&&(C("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,!t.reading&&(e=l(n,t)));var i=0<e?b(e,t):null;return null===i?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(!t.ended&&(t.needReadable=!0),n!==e&&t.ended&&w(this)),null!==i&&this.emit("data",i),i},s.prototype._read=function(){B(this,new j("_read()"))},s.prototype.pipe=function(e,t){function r(e,t){C("onunpipe"),e===d&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,s())}function i(){C("onend"),e.end()}function s(){C("cleanup"),e.removeListener("close",c),e.removeListener("finish",l),e.removeListener("drain",g),e.removeListener("error",a),e.removeListener("unpipe",r),d.removeListener("end",i),d.removeListener("end",h),d.removeListener("data",o),p=!0,u.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&g()}function o(t){C("ondata");var n=e.write(t);C("dest.write",n),!1===n&&((1===u.pipesCount&&u.pipes===e||1<u.pipesCount&&-1!==_(u.pipes,e))&&!p&&(C("false write response, pause",u.awaitDrain),u.awaitDrain++),d.pause())}function a(t){C("onerror",t),h(),e.removeListener("error",a),0===S(e,"error")&&B(e,t)}function c(){e.removeListener("finish",l),h()}function l(){C("onfinish"),e.removeListener("close",c),h()}function h(){C("unpipe"),d.unpipe(e)}var d=this,u=this._readableState;switch(u.pipesCount){case 0:u.pipes=e;break;case 1:u.pipes=[u.pipes,e];break;default:u.pipes.push(e)}u.pipesCount+=1,C("pipe count=%d opts=%j",u.pipesCount,t);var f=t&&!1===t.end||e===n.stdout||e===n.stderr?h:i;u.endEmitted?n.nextTick(f):d.once("end",f),e.on("unpipe",r);var g=function(e){return function(){var t=e._readableState;C("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&S(e,"data")&&(t.flowing=!0,y(e))}}(d);e.on("drain",g);var p=!1;return d.on("data",o),function(e,t,n){"function"==typeof e.prependListener?e.prependListener(t,n):e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",a),e.once("close",c),e.once("finish",l),e.emit("pipe",d),u.flowing||(C("pipe resume"),d.resume()),e},s.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=_(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},s.prototype.on=function(e,t){var r=E.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=0<this.listenerCount("readable"),!1!==i.flowing&&this.resume()):"readable"==e&&!i.endEmitted&&!i.readableListening&&(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,C("on readable",i.length,i.reading),i.length?h(this):!i.reading&&n.nextTick(p,this)),r},s.prototype.addListener=s.prototype.on,s.prototype.removeListener=function(e,t){var r=E.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(g,this),r},s.prototype.removeAllListeners=function(e){var t=E.prototype.removeAllListeners.apply(this,arguments);return("readable"===e||void 0===e)&&n.nextTick(g,this),t},s.prototype.resume=function(){var e=this._readableState;return e.flowing||(C("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(m,e,t))}(this,e)),e.paused=!1,this},s.prototype.pause=function(){return C("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(C("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},s.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on("end",function(){if(C("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on("data",function(i){C("wrapped data"),n.decoder&&(i=n.decoder.write(i)),n.objectMode&&null==i||!(n.objectMode||i&&i.length)||t.push(i)||(r=!0,e.pause())}),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var s=0;s<W.length;s++)e.on(W[s],this.emit.bind(this,W[s]));return this._read=function(t){C("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(s.prototype[Symbol.asyncIterator]=function(){return void 0===D&&(D=e("./internal/streams/async_iterator")),D(this)}),Object.defineProperty(s.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(s.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(s.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),s._fromList=b,Object.defineProperty(s.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(s.from=function(t,n){return void 0===O&&(O=e("./internal/streams/from")),O(s,t,n)})}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/async_iterator":21,"./internal/streams/buffer_list":22,"./internal/streams/destroy":23,"./internal/streams/from":25,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,events:7,inherits:10,"string_decoder/":31,util:2}],19:[function(e,t){function n(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new c);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function r(e){return this instanceof r?(d.call(this,e),this._transformState={afterTransform:n.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),void this.on("prefinish",i)):new r(e)}function i(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?s(this,null,null):this._flush(function(t,n){s(e,t,n)})}function s(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new h;if(e._transformState.transforming)throw new l;return e.push(null)}t.exports=r;var o=e("../errors").codes,a=o.ERR_METHOD_NOT_IMPLEMENTED,c=o.ERR_MULTIPLE_CALLBACK,l=o.ERR_TRANSFORM_ALREADY_TRANSFORMING,h=o.ERR_TRANSFORM_WITH_LENGTH_0,d=e("./_stream_duplex");e("inherits")(r,d),r.prototype.push=function(e,t){return this._transformState.needTransform=!1,d.prototype.push.call(this,e,t)},r.prototype._transform=function(e,t,n){n(new a("_transform()"))},r.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},r.prototype._read=function(){var e=this._transformState;null===e.writechunk||e.transforming?e.needTransform=!0:(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform))},r.prototype._destroy=function(e,t){d.prototype._destroy.call(this,e,function(e){t(e)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(e,t){(function(n,r){(function(){function i(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}(t,e)}}function s(){}function o(t,n,r){v=v||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof v),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=T(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var s=!1===t.decodeStrings;this.decodeStrings=!s,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){u(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new i(this)}function a(t){var n=this instanceof(v=v||e("./_stream_duplex"));return n||_.call(a,this)?(this._writableState=new o(t,this,n),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),void C.call(this)):new a(t)}function c(e,t){var r=new N;U(e,r),n.nextTick(t,r)}function l(e,t,r,i){var s;return null===r?s=new M:"string"!=typeof r&&!t.objectMode&&(s=new R("chunk",["string","Buffer"],r)),!s||(U(e,s),n.nextTick(i,s),!1)}function h(e,t,n,r,i,s){if(!n){var o=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=S.from(t,n)),t}(t,r,i);r!==o&&(n=!0,i="buffer",r=o)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else d(e,t,!1,a,r,i,s);return c}function d(e,t,n,r,i,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new L("write")):n?e._writev(i,t.onwrite):e._write(i,s,t.onwrite),t.sync=!1}function u(e,t){var r=e._writableState,i=r.sync,s=r.writecb;if("function"!=typeof s)throw new O;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,i,s){--t.pendingcb,r?(n.nextTick(s,i),n.nextTick(b,e,t),e._writableState.errorEmitted=!0,U(e,i)):(s(i),e._writableState.errorEmitted=!0,U(e,i),b(e,t))}(e,r,i,t,s);else{var o=p(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||g(e,r),i?n.nextTick(f,e,r,o,s):f(e,r,o,s)}}function f(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),b(e,t)}function g(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=Array(r),o=t.corkedRequestsFree;o.entry=n;for(var a=0,c=!0;n;)s[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;s.allBuffers=c,d(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new i(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,h=n.encoding,u=n.callback;if(d(e,t,!1,t.objectMode?1:l.length,l,h,u),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function p(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function m(e,t){e._final(function(n){t.pendingcb--,n&&U(e,n),t.prefinished=!0,e.emit("prefinish"),b(e,t)})}function y(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(m,e,t)))}function b(e,t){var n=p(t);if(n&&(y(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function w(e,t,r){t.ending=!0,b(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}var v;t.exports=a,a.WritableState=o;var _,k={deprecate:e("util-deprecate")},C=e("./internal/streams/stream"),S=e("buffer").Buffer,E=r.Uint8Array||function(){},A=e("./internal/streams/destroy"),T=e("./internal/streams/state").getHighWaterMark,x=e("../errors").codes,R=x.ERR_INVALID_ARG_TYPE,D=x.ERR_METHOD_NOT_IMPLEMENTED,O=x.ERR_MULTIPLE_CALLBACK,P=x.ERR_STREAM_CANNOT_PIPE,L=x.ERR_STREAM_DESTROYED,M=x.ERR_STREAM_NULL_VALUES,N=x.ERR_STREAM_WRITE_AFTER_END,I=x.ERR_UNKNOWN_ENCODING,U=A.errorOrDestroy;e("inherits")(a,C),o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:k.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(_=Function.prototype[Symbol.hasInstance],Object.defineProperty(a,Symbol.hasInstance,{value:function(e){return!!_.call(this,e)||!(this!==a)&&e&&e._writableState instanceof o}})):_=function(e){return e instanceof this},a.prototype.pipe=function(){U(this,new P)},a.prototype.write=function(e,t,n){var r=this._writableState,i=!1,o=!r.objectMode&&function(e){return S.isBuffer(e)||e instanceof E}(e);return o&&!S.isBuffer(e)&&(e=function(e){return S.from(e)}(e)),"function"==typeof t&&(n=t,t=null),o?t="buffer":!t&&(t=r.defaultEncoding),"function"!=typeof n&&(n=s),r.ending?c(this,n):(o||l(this,r,e,n))&&(r.pendingcb++,i=h(this,r,o,e,t,n)),i},a.prototype.cork=function(){this._writableState.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&g(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())))throw new I(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(a.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(a.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),a.prototype._write=function(e,t,n){n(new D("_write()"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||w(this,r,n),this},Object.defineProperty(a.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(a.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),a.prototype.destroy=A.destroy,a.prototype._undestroy=A.undestroy,a.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/destroy":23,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,inherits:10,"util-deprecate":32}],21:[function(e,t){(function(n){(function(){function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){return{value:e,done:t}}function s(e){var t=e[l];if(null!==t){var n=e[p].read();null!==n&&(e[f]=null,e[l]=null,e[h]=null,t(i(n,!1)))}}function o(e){n.nextTick(s,e)}var a,c=e("./end-of-stream"),l=Symbol("lastResolve"),h=Symbol("lastReject"),d=Symbol("error"),u=Symbol("ended"),f=Symbol("lastPromise"),g=Symbol("handlePromise"),p=Symbol("stream"),m=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((a={get stream(){return this[p]},next:function(){var e=this,t=this[d];if(null!==t)return Promise.reject(t);if(this[u])return Promise.resolve(i(void 0,!0));if(this[p].destroyed)return new Promise(function(t,r){n.nextTick(function(){e[d]?r(e[d]):t(i(void 0,!0))})});var r,s=this[f];if(s)r=new Promise(function(e,t){return function(n,r){e.then(function(){t[u]?n(i(void 0,!0)):t[g](n,r)},r)}}(s,this));else{var o=this[p].read();if(null!==o)return Promise.resolve(i(o,!1));r=new Promise(this[g])}return this[f]=r,r}},r(a,Symbol.asyncIterator,function(){return this}),r(a,"return",function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){e?n(e):t(i(void 0,!0))})})}),a),m);t.exports=function(e){var t,n=Object.create(y,(r(t={},p,{value:e,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,h,{value:null,writable:!0}),r(t,d,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,g,{value:function(e,t){var r=n[p].read();r?(n[f]=null,n[l]=null,n[h]=null,e(i(r,!1))):(n[l]=e,n[h]=t)},writable:!0}),t));return n[f]=null,c(e,function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[h];return null!==t&&(n[f]=null,n[l]=null,n[h]=null,t(e)),void(n[d]=e)}var r=n[l];null!==r&&(n[f]=null,n[l]=null,n[h]=null,r(i(void 0,!0))),n[u]=!0}),e.on("readable",o.bind(null,n)),n}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":24,_process:12}],22:[function(e,t){function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){for(var n,r=0;r<t.length;r++)(n=t[r]).enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}function s(e,t,n){o.prototype.copy.call(e,t,n)}var o=e("buffer").Buffer,a=e("util").inspect,c=a&&a.custom||"inspect";t.exports=function(){function e(){(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this.head=null,this.tail=null,this.length=0}return function(e,t,n){t&&i(e.prototype,t),n&&i(e,n)}(e,[{key:"push",value:function(e){var t={data:e,next:null};0<this.length?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return o.alloc(0);for(var t=o.allocUnsafe(e>>>0),n=this.head,r=0;n;)s(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,s=e>i.length?i.length:e;if(r+=s===i.length?i:i.slice(0,e),0===(e-=s)){s===i.length?(++n,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=o.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,s),0===(e-=s)){s===i.length?(++r,this.head=n.next?n.next:this.tail=null):(this.head=n,n.data=i.slice(s));break}++r}return this.length-=r,t}},{key:c,value:function(e,t){return a(this,function(e){for(var t,i=1;i<arguments.length;i++)t=null==arguments[i]?{}:arguments[i],i%2?n(Object(t),!0).forEach(function(n){r(e,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):n(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))});return e}({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:3,util:2}],23:[function(e,t){(function(e){(function(){function n(e,t){i(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function i(e,t){e.emit("error",t)}t.exports={destroy:function(t,s){var o=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(s?s(t):t&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,e.nextTick(i,this,t)):e.nextTick(i,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!s&&t?o._writableState?o._writableState.errorEmitted?e.nextTick(r,o):(o._writableState.errorEmitted=!0,e.nextTick(n,o,t)):e.nextTick(n,o,t):s?(e.nextTick(r,o),s(t)):e.nextTick(r,o)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}}}).call(this)}).call(this,e("_process"))},{_process:12}],24:[function(e,t){function n(){}var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;t.exports=function e(t,i,s){if("function"==typeof i)return e(t,null,i);i||(i={}),s=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}(s||n);var o=i.readable||!1!==i.readable&&t.readable,a=i.writable||!1!==i.writable&&t.writable,c=function(){t.writable||h()},l=t._writableState&&t._writableState.finished,h=function(){a=!1,l=!0,o||s.call(t)},d=t._readableState&&t._readableState.endEmitted,u=function(){o=!1,d=!0,a||s.call(t)},f=function(e){s.call(t,e)},g=function(){var e;return o&&!d?(t._readableState&&t._readableState.ended||(e=new r),s.call(t,e)):a&&!l?(t._writableState&&t._writableState.ended||(e=new r),s.call(t,e)):void 0},p=function(){t.req.on("finish",h)};return function(e){return e.setHeader&&"function"==typeof e.abort}(t)?(t.on("complete",h),t.on("abort",g),t.req?p():t.on("request",p)):a&&!t._writableState&&(t.on("end",c),t.on("close",c)),t.on("end",u),t.on("finish",h),!1!==i.error&&t.on("error",f),t.on("close",g),function(){t.removeListener("complete",h),t.removeListener("abort",g),t.removeListener("request",p),t.req&&t.req.removeListener("finish",h),t.removeListener("end",c),t.removeListener("close",c),t.removeListener("finish",h),t.removeListener("end",u),t.removeListener("error",f),t.removeListener("close",g)}}},{"../../../errors":15}],25:[function(e,t){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(e,t){function n(e){if(e)throw e}function r(t,n,r,i){i=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(i);var s=!1;t.on("close",function(){s=!0}),void 0===a&&(a=e("./end-of-stream")),a(t,{readable:n,writable:r},function(e){return e?i(e):(s=!0,void i())});var o=!1;return function(e){if(!s)return o?void 0:(o=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void i(e||new h("pipe")))}}function i(e){e()}function s(e,t){return e.pipe(t)}function o(e){return e.length&&"function"==typeof e[e.length-1]?e.pop():n}var a,c=e("../../../errors").codes,l=c.ERR_MISSING_ARGS,h=c.ERR_STREAM_DESTROYED;t.exports=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var a=o(t);if(Array.isArray(t[0])&&(t=t[0]),2>t.length)throw new l("streams");var c,h=t.map(function(e,n){var s=n<t.length-1;return r(e,s,0<n,function(e){c||(c=e),e&&h.forEach(i),s||(h.forEach(i),a(c))})});return t.reduce(s)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(e,n){var r=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;n.exports={getHighWaterMark:function(e,n,i,s){var o=function(e,t,n){return null==e.highWaterMark?t?e[n]:null:e.highWaterMark}(n,s,i);if(null!=o){if(!isFinite(o)||t(o)!==o||0>o)throw new r(s?i:"highWaterMark",o);return t(o)}return e.objectMode?16:16384}}},{"../../../errors":15}],28:[function(e,t){t.exports=e("events").EventEmitter},{events:7}],29:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"./lib/internal/streams/end-of-stream.js":24,"./lib/internal/streams/pipeline.js":26}],30:[function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return o(e,t,n)}var s=e("buffer"),o=s.Buffer;o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?t.exports=s:(r(s,n),n.Buffer=i),i.prototype=Object.create(o.prototype),r(o,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0===t?r.fill(0):"string"==typeof n?r.fill(t,n):r.fill(t),r},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s.SlowBuffer(e)}},{buffer:3}],31:[function(e,t,n){function r(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(u.isEncoding===f||!f(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=o,this.end=a,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=c,this.end=l,t=3;break;default:return this.write=h,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=u.allocUnsafe(t)}function i(e){return 127>=e?0:6==e>>5?2:14==e>>4?3:30==e>>3?4:2==e>>6?-1:-2}function s(e){var t=this.lastTotal-this.lastNeed,n=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(1<e.lastNeed&&1<t.length){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(2<e.lastNeed&&2<t.length&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0===n?this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length)):n}function o(e,t){if(0==(e.length-t)%2){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(55296<=r&&56319>=r)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function a(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function c(e,t){var n=(e.length-t)%3;return 0==n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function l(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}var u=e("safe-buffer").Buffer,f=u.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};n.StringDecoder=r,r.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},r.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},r.prototype.text=function(e,t){var n=function(e,t,n){var r=t.length-1;if(r<n)return 0;var s=i(t[r]);return 0<=s?(0<s&&(e.lastNeed=s-1),s):--r<n||-2===s?0:0<=(s=i(t[r]))?(0<s&&(e.lastNeed=s-2),s):--r<n||-2===s?0:0<=(s=i(t[r]))?(0<s&&(2===s?s=0:e.lastNeed=s-3),s):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},r.prototype.fillLast=function(e){return this.lastNeed<=e.length?(e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),void(this.lastNeed-=e.length))}},{"safe-buffer":30}],32:[function(e,t){(function(e){(function(){function n(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===(n+"").toLowerCase()}t.exports=function(e,t){if(n("noDeprecation"))return e;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation"),r=!0}return e.apply(this,arguments)}}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],"/":[function(e,t){function n(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}const r=e("debug")("simple-peer"),i=e("get-browser-rtc"),s=e("randombytes"),o=e("readable-stream"),a=e("queue-microtask"),c=e("err-code"),{Buffer:l}=e("buffer"),h=65536;class d extends o.Duplex{constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this._id=s(4).toString("hex").slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||s(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||d.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},d.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:i(),!this._wrtc)throw"undefined"==typeof window?c(/* @__PURE__ */new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(/* @__PURE__ */new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=/* @__PURE__ */new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void this.destroy(c(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(e=>{this.destroy(c(e,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach(e=>{this.addStream(e)}),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(e=>{this._addIceCandidate(e)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(e=>{this.destroy(c(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(c(/* @__PURE__ */new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch(e=>{!t.address||t.address.endsWith(".local")||this.destroy(c(e,"ERR_ADD_ICE_CANDIDATE"))})}send(e){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}addTransceiver(e,t){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(c(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),e.getTracks().forEach(t=>{this.addTrack(t,e)})}}addTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(e)||/* @__PURE__ */new Map;let r=n.get(t);if(r)throw r.removed?c(/* @__PURE__ */new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(/* @__PURE__ */new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation()}replaceTrack(e,t,n){if(this.destroying)return;if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const r=this._senderMap.get(e),i=r?r.get(n):null;if(!i)throw c(/* @__PURE__ */new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,r),null==i.replaceTrack?this.destroy(c(/* @__PURE__ */new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):i.replaceTrack(t)}removeTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const n=this._senderMap.get(e),r=n?n.get(t):null;if(!r)throw c(/* @__PURE__ */new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{r.removed=!0,this._pc.removeTrack(r)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(r):this.destroy(c(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),e.getTracks().forEach(t=>{this.removeTrack(t,e)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,a(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw c(/* @__PURE__ */new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(e){this._destroy(e,()=>{})}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",e&&(e.message||e)),a(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close"),t()}))}_setupData(e){if(!e.channel)return this.destroy(c(/* @__PURE__ */new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=h),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const t=e.error instanceof Error?e.error:/* @__PURE__ */new Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.destroy(c(t,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1},5e3)}_read(){}_write(e,t,n){if(this.destroyed)return n(c(/* @__PURE__ */new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>h?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(!this.destroyed){const e=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?e():this.once("connect",e)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})}};this._pc.setLocalDescription(e).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))}).catch(e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(e=>{this.destroy(c(e,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(e).then(()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))}).catch(e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(e=>{this.destroy(c(e,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(c(/* @__PURE__ */new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),("connected"===e||"completed"===e)&&(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(c(/* @__PURE__ */new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(c(/* @__PURE__ */new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach(t=>{Object.assign(e,t)}),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(n=>{const r=[];n.forEach(e=>{r.push(t(e))}),e(null,r)},t=>e(t)):0<this._pc.getStats.length?this._pc.getStats(n=>{if(this.destroyed)return;const r=[];n.result().forEach(e=>{const n={};e.names().forEach(t=>{n[t]=e.stat(t)}),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,r.push(t(n))}),e(null,r)},t=>e(t)):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats((t,n)=>{if(this.destroyed)return;t&&(n=[]);const r={},i={},s={};let o=!1;n.forEach(e=>{("remotecandidate"===e.type||"remote-candidate"===e.type)&&(r[e.id]=e),("localcandidate"===e.type||"local-candidate"===e.type)&&(i[e.id]=e),("candidatepair"===e.type||"candidate-pair"===e.type)&&(s[e.id]=e)});const a=e=>{o=!0;let t=i[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=+t.port):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=+t.portNumber):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=+t[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=r[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=+n.port):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=+n.portNumber):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=+n[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)}),o||Object.keys(s).length&&!Object.keys(i).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const t=this._cb;this._cb=null,t(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)})};e()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>h)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=l.from(t)),this.push(t)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach(t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some(e=>e.id===t.id)||(this._remoteStreams.push(t),a(()=>{this._debug("on stream"),this.emit("stream",t)}))})}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],r.apply(null,e)}}d.WEBRTC_SUPPORT=!!i(),d.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},d.channelConfig={},t.exports=d},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})})(),1),uh=(e,t)=>{if(!t)return Tt(e);const n=crypto.getRandomValues(/* @__PURE__ */new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,e).then(e=>{const t=Lt();return qe(t,"AES-GCM"),Kt(t,n),Kt(t,new Uint8Array(e)),yt(t)})},fh=(e,t)=>{if(!t)return Tt(e);const n=$t(e);"AES-GCM"!==gn(n)&&et(on("Unknown encryption algorithm"));const r=Bt(n),i=Bt(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,i).then(e=>new Uint8Array(e))},gh=mt("y-webrtc"),ph=/* @__PURE__ */new Map,mh=/* @__PURE__ */new Map,yh=e=>{let t=!0;e.webrtcConns.forEach(e=>{e.synced||(t=!1)}),(!t&&e.synced||t&&!e.synced)&&(e.synced=t,e.provider.emit("synced",[{synced:t}]),gh("synced ",bt,e.name,Qt," with all peers"))},bh=(e,t,n)=>{const r=$t(t),i=Lt(),s=Ut(r);if(void 0===e)return null;const o=e.awareness,a=e.doc;let c=!1;switch(s){case 0:{ht(i,0);const t=Rl(r,i,a,e);1!==t||e.synced||n(),0===t&&(c=!0);break}case 3:ht(i,1),Kt(i,kl(o,Array.from(o.getStates().keys()))),c=!0;break;case 1:Cl(o,Bt(r),e);break;case 4:{const t=1===Nt(r),n=gn(r);if(n!==e.peerId&&(e.bcConns.has(n)&&!t||!e.bcConns.has(n)&&t)){const r=[],i=[];t?(e.bcConns.add(n),i.push(n)):(e.bcConns.delete(n),r.push(n)),e.provider.emit("peers",[{added:i,removed:r,webrtcPeers:Array.from(e.webrtcConns.keys()),bcPeers:Array.from(e.bcConns)}]),Sh(e)}break}default:return i}return c?i:null},wh=(e,t)=>{gh("send message to ",bt,e.remotePeerId,Qt,Ve," (",e.room.name,")",Ie);try{e.peer.send(yt(t))}catch(n){}},vh=class{constructor(e,t,n,r){gh("establishing connection to ",bt,n),this.room=r,this.remotePeerId=n,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new dh.default({initiator:t,...r.provider.peerOpts}),this.peer.on("signal",t=>{void 0===this.glareToken&&(this.glareToken=Date.now()+Math.random()),Ah(e,r,{to:n,from:r.peerId,type:"signal",token:this.glareToken,signal:t})}),this.peer.on("connect",()=>{gh("connected to ",bt,n),this.connected=!0;const e=r.provider.doc,t=r.awareness,i=Lt();ht(i,0),Sl(i,e),wh(this,i);const s=t.getStates();if(s.size>0){const e=Lt();ht(e,1),Kt(e,kl(t,Array.from(s.keys()))),wh(this,e)}}),this.peer.on("close",()=>{this.connected=!1,this.closed=!0,r.webrtcConns.has(this.remotePeerId)&&(r.webrtcConns.delete(this.remotePeerId),r.provider.emit("peers",[{removed:[this.remotePeerId],added:[],webrtcPeers:Array.from(r.webrtcConns.keys()),bcPeers:Array.from(r.bcConns)}])),yh(r),this.peer.destroy(),gh("closed connection to ",bt,n),Ch(r)}),this.peer.on("error",e=>{gh("Error in connection to ",bt,n,": ",e),Ch(r)}),this.peer.on("data",e=>{const t=((e,t)=>{const n=e.room;return gh("received message from ",bt,e.remotePeerId,Ve," (",n.name,")",Qt,Ie),bh(n,t,()=>{e.synced=!0,gh("synced ",bt,n.name,Qt," with ",bt,e.remotePeerId),yh(n)})})(this,e);null!==t&&wh(this,t)})}destroy(){this.peer.destroy()}},_h=(e,t)=>uh(t,e.key).then(t=>e.mux(()=>((e,t,n=null)=>{const r=hh(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))})(e.name,t))),kh=(e,t)=>{e.bcconnected&&_h(e,t),((e,t)=>{gh("broadcast message in ",bt,e.name,Qt),e.webrtcConns.forEach(e=>{try{e.peer.send(t)}catch(n){}})})(e,t)},Ch=e=>{ph.forEach(t=>{t.connected&&(t.send({type:"subscribe",topics:[e.name]}),e.webrtcConns.size<e.provider.maxConns&&Ah(t,e,{type:"announce",from:e.peerId}))})},Sh=e=>{if(e.provider.filterBcConns){const t=Lt();ht(t,4),bn(t,1),qe(t,e.peerId),_h(e,yt(t))}},Eh=class{constructor(e,t,n,r){this.peerId=Ne(),this.doc=e,this.awareness=t.awareness,this.provider=t,this.synced=!1,this.name=n,this.key=r,this.webrtcConns=/* @__PURE__ */new Map,this.bcConns=/* @__PURE__ */new Set,this.mux=Mt(),this.bcconnected=!1,this._bcSubscriber=e=>fh(new Uint8Array(e),r).then(e=>this.mux(()=>{const t=bh(this,e,()=>{});t&&_h(this,yt(t))})),this._docUpdateHandler=(e,t)=>{const n=Lt();ht(n,0),Tl(n,e),kh(this,yt(n))},this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{const i=e.concat(t).concat(n),s=Lt();ht(s,1),Kt(s,kl(this.awareness,i)),kh(this,yt(s))},this._beforeUnloadHandler=()=>{_l(this.awareness,[e.clientID],"window unload"),mh.forEach(e=>{e.disconnect()})},"undefined"!=typeof window?window.addEventListener("beforeunload",this._beforeUnloadHandler):"undefined"!=typeof process&&process.on("exit",this._beforeUnloadHandler)}connect(){this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),Ch(this);const e=this.name;var t,n;t=e,n=this._bcSubscriber,hh(t).subs.add(n),this.bcconnected=!0,Sh(this);const r=Lt();ht(r,0),Sl(r,this.doc),_h(this,yt(r));const i=Lt();ht(i,0),El(i,this.doc),_h(this,yt(i));const s=Lt();ht(s,3),_h(this,yt(s));const o=Lt();ht(o,1),Kt(o,kl(this.awareness,[this.doc.clientID])),_h(this,yt(o))}disconnect(){ph.forEach(e=>{e.connected&&e.send({type:"unsubscribe",topics:[this.name]})}),_l(this.awareness,[this.doc.clientID],"disconnect");const e=Lt();ht(e,4),bn(e,0),qe(e,this.peerId),_h(this,yt(e)),((e,t)=>{const n=hh(e),r=n.subs.delete(t);r&&0===n.subs.size&&(n.bc.close(),ch.delete(e))})(this.name,this._bcSubscriber),this.bcconnected=!1,this.doc.off("update",this._docUpdateHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.webrtcConns.forEach(e=>e.destroy())}destroy(){this.disconnect(),"undefined"!=typeof window?window.removeEventListener("beforeunload",this._beforeUnloadHandler):"undefined"!=typeof process&&process.off("exit",this._beforeUnloadHandler)}},Ah=(e,t,n)=>{t.key?((e,t)=>{const n=Lt();return We(n,e),uh(yt(n),t)})(n,t.key).then(n=>{e.send({type:"publish",topic:t.name,data:dt(n)})}):e.send({type:"publish",topic:t.name,data:n})},Th=class extends ah{constructor(e){super(e),this.providers=/* @__PURE__ */new Set,this.on("connect",()=>{gh(`connected (${e})`);const t=Array.from(mh.keys());this.send({type:"subscribe",topics:t}),mh.forEach(e=>Ah(this,e,{type:"announce",from:e.peerId}))}),this.on("message",e=>{if("publish"===e.type){const r=e.topic,i=mh.get(r);if(null==i||"string"!=typeof r)return;const s=e=>{const t=i.webrtcConns,n=i.peerId;if(null==e||e.from===n||void 0!==e.to&&e.to!==n||i.bcConns.has(e.from))return;const r=t.has(e.from)?()=>{}:()=>i.provider.emit("peers",[{removed:[],added:[e.from],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}]);switch(e.type){case"announce":t.size<i.provider.maxConns&&(cn(t,e.from,()=>new vh(this,!0,e.from,i)),r());break;case"signal":if("offer"===e.signal.type){const n=t.get(e.from);if(n){const t=e.token,r=n.glareToken;if(r&&r>t)return void gh("offer rejected: ",e.from);n.glareToken=void 0}}if("answer"===e.signal.type){gh("offer answered by: ",e.from);t.get(e.from).glareToken=void 0}e.to===n&&(cn(t,e.from,()=>new vh(this,!1,e.from,i)).peer.signal(e.signal),r())}};i.key?"string"==typeof e.data&&(t=at(e.data),n=i.key,fh(t,n).then(e=>hn($t(new Uint8Array(e))))).then(s):s(e.data)}var t,n}),this.on("disconnect",()=>gh(`disconnect (${e})`))}},xh=e=>{e.emit("status",[{connected:e.connected}])},Rh=class extends it{constructor(e,t,{signaling:n=["wss://y-webrtc-eu.fly.dev"],password:r=null,awareness:i=new vl(t),maxConns:s=20+ot(15*xt()),filterBcConns:o=!0,peerOpts:a={}}={}){super(),this.roomName=e,this.doc=t,this.filterBcConns=o,this.awareness=i,this.shouldConnect=!1,this.signalingUrls=n,this.signalingConns=[],this.maxConns=s,this.peerOpts=a,this.key=r?((e,t)=>{const n=Ue(e).buffer,r=Ue(t).buffer;return crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveKey"]).then(e=>crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:1e5,hash:"SHA-256"},e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]))})(r,e):Tt(null),this.room=null,this.key.then(n=>{this.room=((e,t,n,r)=>{if(mh.has(n))throw on(`A Yjs Doc connected to room "${n}" already exists!`);const i=new Eh(e,t,n,r);return mh.set(n,i),i})(t,this,e,n),this.shouldConnect?this.room.connect():this.room.disconnect(),xh(this)}),this.connect(),this.destroy=this.destroy.bind(this),t.on("destroy",this.destroy)}get connected(){return null!==this.room&&this.shouldConnect}connect(){this.shouldConnect=!0,this.signalingUrls.forEach(e=>{const t=cn(ph,e,()=>new Th(e));this.signalingConns.push(t),t.providers.add(this)}),this.room&&(this.room.connect(),xh(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),0===e.providers.size&&(e.destroy(),ph.delete(e.url))}),this.room&&(this.room.disconnect(),xh(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),mh.delete(this.roomName)}),super.destroy()}};async function Dh(e,t){const n=await async function(e,t){const n=`${e}-${JSON.stringify(t)}`,r=(new TextEncoder).encode(n),i=globalThis.crypto?.subtle??globalThis.window?.crypto?.subtle;if(!i)throw new Error("Web Crypto API subtle.digest is unavailable");return function(e){const t=new DataView(e).getInt32(0,!1);return Math.abs(t)%2147483647+1}(await i.digest("SHA-256",r))}(e,t),r=new Cs({guid:e});r.clientID=n;const i=Bc(t);r.get("content",Fa).applyDelta(i);const s=Us(r);return r.destroy(),s}var Oh={hocuspocus:class{_isConnected=!1;_isSynced=!1;onConnect;onDisconnect;onError;onSyncChange;destroy=()=>{this._isConnected&&this.provider.disconnect()};disconnect=()=>{this._isConnected&&(this.provider.disconnect(),this._isConnected=!1,this._isSynced&&(this._isSynced=!1,this?.onSyncChange?.(!1)))};provider;type="hocuspocus";constructor({awareness:e,doc:t,options:n,wsOptions:r,onConnect:i,onDisconnect:s,onError:o,onSyncChange:a}){this.onConnect=i,this.onDisconnect=s,this.onSyncChange=a,this.onError=o;const c={...n,...t&&{document:t},...e&&{awareness:e},...r&&(()=>{try{return{websocketProvider:new Il(r)}}catch(e){return this.onError?.(e instanceof Error?e:new Error(String(e))),{}}})(),onAwarenessChange:n.onAwarenessChange||(()=>{}),onConnect:()=>{this._isConnected=!0,this.onConnect?.(),n.onConnect?.()},onDisconnect:e=>{this._isConnected=!1,this._isSynced&&(this._isSynced=!1,this.onSyncChange?.(!1)),this.onDisconnect?.(),n.onDisconnect?.(e)},onSynced:e=>{const t=this._isSynced;this._isSynced=!0,t||this.onSyncChange?.(!0),n.onSynced?.(e)}};try{this.provider=new zl(c)}catch(l){this.provider=new zl({...c,connect:!1}),this.onError?.(l instanceof Error?l:new Error(String(l)))}}connect(){try{this.provider.connect()}catch(e){this._isConnected=!1}}get awareness(){return this.provider.awareness}get document(){return this.provider.document}get isConnected(){return this._isConnected}get isSynced(){return this._isSynced}},indexeddb:class{_isConnected=!1;_isDestroyed=!1;_isSynced=!1;onConnect;onDisconnect;onError;onSyncChange;providerOptions;_provider=null;awareness;document;isLocalPersistence=!0;type="indexeddb";constructor({awareness:e,doc:t,options:n,onConnect:r,onDisconnect:i,onError:s,onSyncChange:o}){this.document=t??new Cs,this.awareness=e??new vl(this.document),this.providerOptions=n,this.onConnect=r,this.onDisconnect=i,this.onError=s,this.onSyncChange=o}connect=()=>{if(!this._isDestroyed){if(!this._provider)try{const e=new ih(this.providerOptions.docName,this.document);this._provider=e,e._db.then(()=>{this._provider!==e||this._isDestroyed||this.setConnected(!0)}).catch(t=>{this._provider!==e||this._isDestroyed||(this._provider=null,this.destroyProvider(e,!1),this.handleError(t),this.setSynced(!1),this.setConnected(!1))}),e.whenSynced.then(()=>{this._provider===e&&this._isConnected&&!this._isDestroyed&&this.setSynced(!0)}).catch(e=>{this.handleError(e)})}catch(e){return this.handleError(e),this.setConnected(!1),void this.setSynced(!1)}this._provider.synced&&(this.setConnected(!0),this.setSynced(!0))}};destroy=()=>{this._isDestroyed||(this._isDestroyed=!0,this.disconnect())};disconnect=()=>{const e=this._provider;(e||this._isConnected||this._isSynced)&&(this._provider=null,this.setSynced(!1),this.setConnected(!1),e&&this.destroyProvider(e))};get isConnected(){return this._isConnected}get isConnectionPending(){return!!this._provider&&!this._isConnected&&!this._isDestroyed}get isSyncPending(){return!!this._provider&&!this._isSynced&&!this._isDestroyed}get isSynced(){return this._isSynced}get provider(){return this._provider}destroyProvider(e,t=!0){try{e.destroy().catch(e=>{t&&this.handleError(e)})}catch(n){t&&this.handleError(n)}}handleError(e){this.onError?.(e instanceof Error?e:new Error(String(e)))}setConnected(e){this._isConnected!==e&&(this._isConnected=e,e?this.onConnect?.():this.onDisconnect?.())}setSynced(e){this._isSynced!==e&&(this._isSynced=e,this.onSyncChange?.(e))}},webrtc:class{_isConnected=!1;_isSynced=!1;doc;onSyncChange;provider=null;connect=()=>{if(this.provider)try{this.provider.connect()}catch(e){}};destroy=()=>{if(this.provider)try{this.provider.destroy()}catch(e){}};disconnect=()=>{if(this.provider)try{this.provider.disconnect();const e=this._isSynced;this._isConnected=!1,this._isSynced=!1,e&&this.onSyncChange?.(!1)}catch(e){}};type="webrtc";constructor({awareness:e,doc:t,options:n,onConnect:r,onDisconnect:i,onError:s,onSyncChange:o}){this.onSyncChange=o,this.doc=t||new Cs;try{this.provider=new Rh(n.roomName,this.doc,{awareness:e,filterBcConns:n.filterBcConns,maxConns:n.maxConns,password:n.password,peerOpts:n.peerOpts,signaling:n.signaling}),this.provider.on("status",e=>{const t=this._isConnected;this._isConnected=e.connected,e.connected?(t||r?.(),this._isSynced||(this._isSynced=!0,o?.(!0))):t&&(i?.(),this._isSynced&&(this._isSynced=!1,o?.(!1)))})}catch(a){s?.(a instanceof Error?a:new Error(String(a)))}}get awareness(){return this.provider.awareness}get document(){return this.doc}get isConnected(){return this._isConnected}get isSynced(){return this._isSynced}}},Ph=({type:e,...t})=>{const n=(e=>Oh[e])(e);if(!n)throw new Error(`Provider type "${e}" not found in registry`);return new n(t)},Lh=(e,t,n)=>function(e,t,{cursorStateField:n="selection",cursorDataField:r="data",autoSend:i=!0,data:s}={}){const o=e;o.awareness=t,o.cursorDataField=r,o.selectionStateField=n,o.sendCursorData=e=>{o.awareness.setLocalStateField(o.cursorDataField,e)},o.sendCursorPosition=e=>{const t=o.awareness.getLocalState(),r=null==t?void 0:t[n];if(!e)return void(r&&o.awareness.setLocalStateField(o.selectionStateField,null));const{anchor:i,focus:s}=sl(o.sharedRoot,o,e);r&&oo(i,r)&&oo(s,r)||o.awareness.setLocalStateField(o.selectionStateField,{anchor:i,focus:s})};const a=e=>{const t=bl.get(o);if(!t)return;const n=o.awareness.clientID,r={added:e.added.filter(e=>e!==n),removed:e.removed.filter(e=>e!==n),updated:e.updated.filter(e=>e!==n)};(r.added.length>0||r.removed.length>0||r.updated.length>0)&&t.forEach(e=>e(r))},{connect:c,disconnect:l}=o;return o.connect=()=>{if(c(),o.awareness.on("change",a),a({removed:[],added:Array.from(o.awareness.getStates().keys()),updated:[]}),i){s&&wl.sendCursorData(o,s);const{onChange:e}=o;o.onChange=()=>{e(),fl.connected(o)&&wl.sendCursorPosition(o)}}},o.disconnect=()=>{o.awareness.off("change",a),a({removed:Array.from(o.awareness.getStates().keys()),added:[],updated:[]}),l()},o}(e,t,n),Mh=e=>"object"==typeof e&&null!==e&&"type"in e&&"options"in e,Nh=B({key:X.yjs,extendEditor:({editor:e,getOptions:t})=>{let n=e;const{awareness:r,cursors:i,localOrigin:s,positionStorageOrigin:o,sharedType:a,ydoc:c}=t();if(n=((e,t,n)=>gl(e,t,n))(n,a??c.get("content",Fa),{autoConnect:!1,localOrigin:s,positionStorageOrigin:o}),i)if(r){let e=!0;!1===i.autoSend&&(e=!1),n=Lh(n,r,{...i,autoSend:e})}else n.api.debug.error("Yjs plugin: Internal shared awareness (awareness) is missing but cursors are enabled.");return((e,t)=>yl(e,t))(n)},options:{_isConnected:!1,_isSynced:!1,userId:null,_providers:[],awareness:null,cursors:{},localOrigin:null,positionStorageOrigin:null,providers:[],sharedType:null,ydoc:null,onConnect:()=>{},onDisconnect:()=>{},onError:()=>{},onSyncChange:()=>{}}}).extend(({getOptions:e})=>{const{localOrigin:t,positionStorageOrigin:n,...r}=e();let{awareness:i,ydoc:s}=r;return s||(s=new Cs),i||(i=new vl(s)),{options:{awareness:i,localOrigin:t??void 0,positionStorageOrigin:n??void 0,ydoc:s}}}).extendApi(e=>({connect:t=>{const{getOptions:n}=e,{_providers:r}=n(),i=t?Array.isArray(t)?t:[t]:null;r.forEach(e=>{if(!i||i.includes(e.type))try{e.connect()}catch(t){n().onError?.({error:t instanceof Error?t:new Error(String(t)),type:e.type})}})},destroy:()=>{const{editor:t,getOptions:n}=e,{_providers:r}=n();for(const e of[...r].reverse())try{(e.isConnected||e.isConnectionPending)&&e.destroy()}catch(i){}try{fl.disconnect(t)}catch{}},disconnect:t=>{const{editor:n,getOptions:r}=e,{_providers:i}=r(),s=t?Array.isArray(t)?t:[t]:null;for(const e of[...i].reverse())try{!e.isConnected&&!e.isConnectionPending||null!==s&&!s.includes(e.type)||e.disconnect()}catch(o){}},init:async({id:t,autoConnect:n=!0,autoSelect:r,selection:i,value:s,onReady:o}={})=>{const{editor:a,getOptions:c,setOption:l}=e,{awareness:h,providers:d=[],sharedType:u,ydoc:f}=c(),g=()=>{return(e=u??f.get("content",Fa)).length>0||null!=e._start;var e};if(0===d.length)throw new Error("No providers specified. Please provide provider configurations or instances in the `providers` array.");const p=[];let m=null;const y=new Promise(e=>{m=e});for(const e of d)if(Mh(e)){const{options:t,type:n}=e;let r=null;if(!t)continue;try{const e=Ph({awareness:h,doc:f,options:t,type:n,onConnect:()=>{c().onConnect?.({type:n}),l("_isConnected",!0)},onDisconnect:()=>{c().onDisconnect?.({type:n});const{_providers:e}=c();e.some(e=>e.isConnected)||l("_isConnected",!1)},onError:e=>{c().onError?.({error:e,type:n})},onSyncChange:e=>{c().onSyncChange?.({isSynced:e,type:n}),l("_isSynced",e);const t=p.some(e=>!e.isLocalPersistence),i=!r?.isLocalPersistence||!t||g();e&&m&&i&&(m(),m=null)}});r=e,p.push(e)}catch{}}else p.push(e);if(l("_providers",p),n&&p.length>0){p.forEach(e=>{try{e.connect()}catch(t){c().onError?.({error:t instanceof Error?t:new Error(String(t)),type:e.type})}});const e=5e3;await Promise.race([y,new Promise(t=>{setTimeout(()=>{m=null,t()},e)})])}if(!g()&&!p.some(e=>e.isLocalPersistence&&(e.isConnectionPending||e.isSyncPending))&&null!==s){let e=s;if("string"==typeof s?e=a.api.html.deserialize({element:s}):"function"==typeof s?e=await s(a):s&&(e=s),e&&0!==e?.length||(e=a.api.create.value()),u){const t=Bc(e);f.transact(()=>{u.applyDelta(t)})}else{const n=await Dh(t??a.id,e);f.transact(()=>{Ns(f,n)})}}fl.connect(a),a.tf.init({autoSelect:r,selection:i,shouldNormalizeEditor:!1,value:null}),a.api.onChange(),o?.({editor:a,isAsync:!0,value:a.children})}})),Ih=x(Nh),Uh=Object.defineProperty,jh=Object.defineProperties,Fh=Object.getOwnPropertyDescriptors,Bh=Object.getOwnPropertySymbols,Wh=Object.prototype.hasOwnProperty,Hh=Object.prototype.propertyIsEnumerable,qh=(e,t,n)=>t in e?Uh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Vh=(e,t)=>{for(var n in t||(t={}))Wh.call(t,n)&&qh(e,n,t[n]);if(Bh)for(var n of Bh(t))Hh.call(t,n)&&qh(e,n,t[n]);return e},zh=(e,t)=>jh(e,Fh(t));function $h(e){return"[object Object]"===Object.prototype.toString.call(e)}function Yh(e){if(!$h(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==$h(n)&&!1!==n.hasOwnProperty("isPrototypeOf")}function Jh(e,t){for(const n in e){const r=e[n],i=t[n];if(Yh(r)&&Yh(i)){if(!Jh(r,i))return!1}else if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1}else if(r!==i)return!1}for(const n in t)if(void 0===e[n]&&void 0!==t[n])return!1;return!0}function Qh(e){return function(e){var t,n;const r=[];for(const i of e){if("string"==typeof i.insert&&0===i.insert.length)continue;const e=r[r.length-1];e&&"string"==typeof e.insert&&"string"==typeof i.insert&&(e.attributes===i.attributes||!e.attributes==!i.attributes&&Jh(null!=(t=e.attributes)?t:{},null!=(n=i.attributes)?n:{}))?e.insert+=i.insert:r.push(i)}return r}(e.toDelta())}function Kh({insert:e}){return"string"==typeof e?e.length:1}function Gh(e){return e.reduce((e,t)=>e+Kh(t),0)}function Xh(e,t,n){if(n<1)return[];let r=0;const i=[],s=t+n;for(let o=0;o<e.length&&!(r>=s);o++){const n=e[o],a=Kh(n);if(r+a<=t){r+=a;continue}if("string"!=typeof n.insert){r+=a,i.push(n);continue}const c=Math.max(0,t-r),l=Math.min(a,a-(r+a-s));i.push(zh(Vh({},n),{insert:n.insert.slice(c,l)})),r+=a}return i}function Zh(e){return function(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}(e,z.isText(e)?"text":"children")}function ed(e){var t=e,{children:n}=t,r=((e,t)=>{var n={};for(var r in e)Wh.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&Bh)for(var r of Bh(e))t.indexOf(r)<0&&Hh.call(e,r)&&(n[r]=e[r]);return n})(t,["children"]);const i=new fn;return Object.entries(r).forEach(([e,t])=>{i.setAttribute(e,t)}),i.applyDelta(n.map(e=>z.isText(e)?{insert:e.text,attributes:Zh(e)}:{insert:ed(e)}),{sanitize:!1}),i}function td(e){return e?z.isText(e)?e.text.length:1:0}function nd(e,t,n){var r;if(0===n.length)throw new Error("Path has to a have a length >= 1");if(z.isText(t))throw new Error("Cannot descent into slate text");const[i,...s]=n,o=function(e,t){return e.children.slice(0,t).reduce((e,t)=>e+td(t),0)}(t,i),a=t.children[i],c=Qh(e),l=td(a),h=Xh(c,o,l);if(h.length>1)throw new Error("Path doesn't match yText, yTarget spans multiple nodes");const d=null==(r=h[0])?void 0:r.insert;if(s.length>0){if(!(d instanceof fn))throw new Error("Path doesn't match yText, cannot descent into non-yText");return nd(d,a,s)}return{yParent:e,textRange:{start:o,end:o+l},yTarget:d instanceof fn?d:void 0,slateParent:t,slateTarget:a,targetDelta:h}}function rd(e,t,n={}){const{assoc:r=0,insert:i=!1}=n;let s=0,o=0;for(let c=0;c<e.children.length;c++){const n=e.children[c],i=z.isText(n)?n.text.length:1;i>0&&(o=c);const a=s+i;if(i>0&&(r>=0?a>t:a>=t))return[c,t-s];s+=i}if(t>s+(i?1:0))throw new Error("yOffset out of bounds");if(i)return[e.children.length,0];const a=e.children[o];return[o,z.isText(a)?a.text.length:1]}function id(e){return e.map(e=>"string"==typeof e.insert?e:zh(Vh({},e),{insert:sd(e.insert)}))}function sd(e){const t=new fn,n=e.getAttributes();return Object.entries(n).forEach(([e,n])=>{t.setAttribute(e,n)}),t.applyDelta(id(Qh(e)),{sanitize:!1}),t}function od(e){if(!e.doc)throw new Error("shared type isn't attached to a document")}var ad="__slateYjsStoredPosition_";function cd(e,t,{type:n,index:r,assoc:i}){if(!(n instanceof fn))throw new Error("Absolute position points to a non-XMLText");const s=function(e,t,n){const r=[n];for(;r[0]!==e;){const{parent:e}=r[0];if(!e)throw new Error("yText isn't a descendant of root element");if(!(e instanceof fn))throw new Error("Unexpected y parent type");r.unshift(e)}if(r.length<2)return[];let i=t;return r.reduce((e,t,n)=>{const s=r[n+1];if(!s)return e;let o=0;const a=Qh(t);for(const r of a){if(r.insert===s)break;o+="string"==typeof r.insert?r.insert.length:1}if(z.isText(i))throw new Error("Cannot descent into slate text");const[c]=rd(i,o);return i=i.children[c],e.concat(c)},[])}(e,t,n),o=q.get(t,s);if(z.isText(o))throw new Error("Absolute position doesn't match slateRoot, cannot descent into text");const[a,c]=rd(o,r,{assoc:i}),l=o.children[a];return z.isText(l)?{path:[...s,a],offset:c}:null}function ld(e,t,n){if(!e.doc)throw new Error("sharedRoot isn't attach to a yDoc");const r=Ft(n,e.doc);return r&&cd(e,t,r)}function hd(e,t,n){e.setAttribute(ad+t,Wt(n))}function dd(e,t,n){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.type===t&&(!n||(e.assoc>=0?e.index>=n.start&&e.index<n.end:e.index>n.start&&e.index>=n.end))))}function ud(e,t,n=""){const r={[n]:dd(e,t)};return Qh(t).forEach(({insert:t},i)=>{t instanceof fn&&Object.assign(r,ud(e,t,n?`${n}.${i}`:i.toString()))}),r}function fd(e,t,n,r=0){const i=function(e){return od(e),Object.fromEntries(Object.entries(e.getAttributes()).filter(([e])=>e.startsWith(ad)).map(([t,n])=>[t.slice(25),Ft(qt(n),e.doc)]).filter(([,e])=>e))}(e),s={"":dd(i,t,{start:r,end:r+Gh(n)})};return n.forEach(({insert:e},t)=>{e instanceof fn&&Object.assign(s,ud(i,e,t.toString()))}),s}function gd(e,t,n,r,i=0,s=0,o=""){const a=n[o];a&&Object.entries(a).forEach(([n,r])=>{hd(e,n,Zt(t,r.index-s+i,r.assoc))}),r.forEach(({insert:t},r)=>{t instanceof fn&&gd(e,t,n,Qh(t),0,0,o?`${o}.${r}`:r.toString())})}var pd={insert_node:function(e,t,n){const{yParent:r,textRange:i}=nd(e,t,n.path);if(z.isText(n.node))return r.insert(i.start,n.node.text,Zh(n.node));r.insertEmbed(i.start,ed(n.node))},remove_node:function(e,t,n){const{yParent:r,textRange:i}=nd(e,t,n.path);r.delete(i.start,i.end-i.start)},set_node:function(e,t,n){const{yTarget:r,textRange:i,yParent:s}=nd(e,t,n.path);if(r)return Object.entries(n.newProperties).forEach(([e,t])=>{if(null===t)return r.removeAttribute(e);r.setAttribute(e,t)}),Object.entries(n.properties).forEach(([e])=>{n.newProperties.hasOwnProperty(e)||r.removeAttribute(e)});const o=Vh(Vh({},Object.fromEntries(Object.keys(n.properties).map(e=>[e,null]))),n.newProperties);s.format(i.start,i.end-i.start,o)},merge_node:function(e,t,n){const r=nd(e,t,n.path),i=nd(r.yParent,r.slateParent,ne.previous(n.path.slice(-1)));if(!r.yTarget!=!i.yTarget)throw new Error("Cannot merge y text with y element");if(!i.yTarget||!r.yTarget){const{yParent:e,textRange:i,slateTarget:s}=r;if(!s)throw new Error("Expected Slate target node for merge op.");const o=q.get(t,ne.previous(n.path));if(!z.isText(o))throw new Error("Path points to Y.Text but not a Slate text node.");const a=Zh(s),c=Zh(o),l=Object.keys(a).reduce((e,t)=>t in c?e:zh(Vh({},e),{[t]:null}),{});return e.format(i.start,i.end-i.start,Vh(Vh({},l),c))}const s=i.yTarget.length,o=Qh(r.yTarget),a=id(o),c=fd(e,r.yTarget,o,s),l=[{retain:s},...a];i.yTarget.applyDelta(l,{sanitize:!1}),r.yParent.delete(r.textRange.start,r.textRange.end-r.textRange.start),gd(e,i.yTarget,c,a,s)},move_node:function(e,t,n){const r=ne.parent(n.newPath),i=n.newPath[n.newPath.length-1],s=q.get(t,r);if(z.isText(s))throw new Error("Cannot move slate node into text element");const o=[...r,Math.min(i,s.children.length)],a=nd(e,t,n.path),c=nd(e,t,o),l=id(a.targetDelta),h=fd(e,a.yParent,a.targetDelta);a.yParent.delete(a.textRange.start,a.textRange.end-a.textRange.start);const d=Gh(Qh(c.yParent)),u=Math.min(c.textRange.start,d),f=[{retain:u},...l];c.yParent.applyDelta(f,{sanitize:!1}),gd(e,c.yParent,h,l,u,a.textRange.start)},split_node:function(e,t,n){const r=nd(e,t,n.path);if(!r.slateTarget)throw new Error("Y target without corresponding slate node");if(!r.yTarget){if(!z.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const e={};return r.targetDelta.forEach(t=>{t.attributes&&Object.keys(t.attributes).forEach(t=>{e[t]=null})}),r.yParent.format(r.textRange.start,r.textRange.end-r.textRange.start,Vh(Vh({},e),n.properties))}if(z.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const i=nd(r.yTarget,r.slateTarget,[n.position]),s=r.slateTarget.children.slice(0,n.position).reduce((e,t)=>e+td(t),0),o=r.slateTarget.children.reduce((e,t)=>e+td(t),0),a=Xh(Qh(r.yTarget),s,o-s),c=id(a),l=fd(e,r.yTarget,a,s),h=new fn;h.applyDelta(c,{sanitize:!1}),Object.entries(n.properties).forEach(([e,t])=>{h.setAttribute(e,t)}),r.yTarget.delete(i.textRange.start,r.yTarget.length-i.textRange.start),r.yParent.insertEmbed(r.textRange.end,h),gd(e,h,l,c,0,s)}};zh(Vh(Vh({},{insert_text:function(e,t,n){const{yParent:r,textRange:i}=nd(e,t,n.path),s=q.get(t,n.path);if(!z.isText(s))throw new Error("Cannot insert text into non-text node");r.insert(i.start+n.offset,n.text,Zh(s))},remove_text:function(e,t,n){const{yParent:r,textRange:i}=nd(e,t,n.path);r.delete(i.start+n.offset,n.text.length)}}),pd),{set_selection:()=>{}});var md=/* @__PURE__ */new WeakMap,yd=/* @__PURE__ */new WeakMap,bd=/* @__PURE__ */new WeakSet,wd={isYjsEditor:e=>ue.isEditor(e)&&e.sharedRoot instanceof fn&&"localOrigin"in e&&"positionStorageOrigin"in e&&"function"==typeof e.applyRemoteEvents&&"function"==typeof e.storeLocalChange&&"function"==typeof e.flushLocalChanges&&"function"==typeof e.isLocalOrigin&&"function"==typeof e.connect&&"function"==typeof e.disconnect,localChanges(e){var t;return null!=(t=yd.get(e))?t:[]},applyRemoteEvents(e,t,n){e.applyRemoteEvents(t,n)},storeLocalChange(e,t){e.storeLocalChange(t)},flushLocalChanges(e){e.flushLocalChanges()},connected:e=>bd.has(e),connect(e){e.connect()},disconnect(e){e.disconnect()},isLocal:e=>e.isLocalOrigin(wd.origin(e)),origin(e){const t=md.get(e);return void 0!==t?t:e.localOrigin},withOrigin(e,t,n){const r=wd.origin(e);md.set(e,t),n(),md.set(e,r)},storePosition(e,t,n){const{sharedRoot:r,positionStorageOrigin:i}=e;od(r);const s=function(e,t,n){const{yTarget:r,yParent:i,textRange:s}=nd(e,t,n.path);if(r)throw new Error("Slate point points to a non-text element inside sharedRoot");const o=s.start+n.offset;return Zt(i,o,o===s.end?-1:0)}(r,e,n);r.doc.transact(()=>{hd(r,t,s)},i)},removeStoredPosition(e,t){const{sharedRoot:n,positionStorageOrigin:r}=e;od(n),n.doc.transact(()=>{!function(e,t){e.removeAttribute(ad+t)}(n,t)},r)},position(e,t){const n=function(e,t){const n=e.getAttribute(ad+t);return n?qt(n):null}(e.sharedRoot,t);if(n)return ld(e.sharedRoot,e,n)},storedPositionsRelative(e){return t=e.sharedRoot,Object.fromEntries(Object.entries(t.getAttributes()).filter(([e])=>e.startsWith(ad)).map(([e,t])=>[e.slice(25),sn(t)]));var t}},vd=/* @__PURE__ */new WeakMap,_d={isCursorEditor:e=>wd.isYjsEditor(e)&&e.awareness&&"string"==typeof e.cursorDataField&&"string"==typeof e.selectionStateField&&"function"==typeof e.sendCursorPosition&&"function"==typeof e.sendCursorData,sendCursorPosition(e,t=e.selection){e.sendCursorPosition(t)},sendCursorData(e,t){e.sendCursorData(t)},on(e,t,n){var r;if("change"!==t)return;const i=null!=(r=vd.get(e))?r:/* @__PURE__ */new Set;i.add(n),vd.set(e,i)},off(e,t,n){if("change"!==t)return;const r=vd.get(e);r&&r.delete(n)},cursorState(e,t){var n;if(t===e.awareness.clientID||!wd.connected(e))return null;const r=e.awareness.getStates().get(t);return r?{relativeSelection:null!=(n=r[e.selectionStateField])?n:null,data:r[e.cursorDataField],clientId:t}:null},cursorStates:e=>wd.connected(e)?Object.fromEntries(Array.from(e.awareness.getStates().entries(),([t,n])=>t!==e.awareness.clientID&&n?[t,{relativeSelection:n[e.selectionStateField],data:n[e.cursorDataField]}]:null).filter(Array.isArray)):{}},kd=Object.defineProperty,Cd=Object.defineProperties,Sd=Object.getOwnPropertyDescriptors,Ed=Object.getOwnPropertySymbols,Ad=Object.prototype.hasOwnProperty,Td=Object.prototype.propertyIsEnumerable,xd=(e,t,n)=>t in e?kd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Rd=(e,t)=>{for(var n in t||(t={}))Ad.call(t,n)&&xd(e,n,t[n]);if(Ed)for(var n of Ed(t))Td.call(t,n)&&xd(e,n,t[n]);return e},Dd=/* @__PURE__ */new WeakMap;function Od(e,t){if(!t.relativeSelection)return null;let n=Dd.get(e.children);n||(n=/* @__PURE__ */new WeakMap,Dd.set(e.children,n));let r=n.get(t);if(void 0===r)try{r=function(e,t,n){const r=ld(e,t,n.anchor);if(!r)return null;const i=ld(e,t,n.focus);return i?{anchor:r,focus:i}:null}(e.sharedRoot,e,t.relativeSelection),n.set(t,r)}catch(i){return null}return r}function Pd(){const e=he();if(!_d.isCursorEditor(e))throw new Error("Cannot use useSyncExternalStore outside the context of a RemoteCursorEditor");return e}var Ld=/* @__PURE__ */new WeakMap;function Md(e){const t=Ld.get(e);if(t)return t;const n=function(e){let t={};const n=/* @__PURE__ */new Set,r=n.add.bind(n),i=/* @__PURE__ */new Set;let s=null;return[t=>(i.add(t),s||(s=e=>{e.added.forEach(r),e.removed.forEach(r),e.updated.forEach(r),i.forEach(e=>e())},_d.on(e,"change",s)),()=>{i.delete(t),s&&0===i.size&&(_d.off(e,"change",s),s=null)}),()=>(0===n.size||(n.forEach(n=>{const r=_d.cursorState(e,n);null!==r?t[n]=r:delete t[n.toString()]}),n.clear(),t=Rd({},t)),t)]}(e);return Ld.set(e,n),n}function Nd(){const[e,t]=Md(Pd());return Pr(e,t)}function Id(e,t,{yOffset:n,xOffset:r,shouldGenerateOverlay:i}){const[s,o]=me.edges(t),a=function(e,t){try{return se.toDOMRange(e,t)}catch(n){return null}}(e,t);if(!a)return{caretPosition:null,selectionRects:[]};const c=[],l=ue.nodes(e,{at:t,match:(e,t)=>z.isText(e)&&(!i||i(e,t))});let h=null;const d=me.isBackward(t);for(const[u,f]of l){const i=se.toDOMNode(e,u),l=ne.equals(f,s.path),g=ne.equals(f,o.path);let p=null;if(l||g){const e=document.createRange();e.selectNode(i),l&&e.setStart(a.startContainer,a.startOffset),g&&e.setEnd(a.endContainer,a.endOffset),p=e.getClientRects()}else p=i.getClientRects();const m=d?l:g;for(let e=0;e<p.length;e++){const i=p.item(e);if(!i)continue;const s=m&&(d?0===e:e===p.length-1),o=i.top-n,a=i.left-r;s&&(h={height:i.height,top:o,left:a+(d||me.isCollapsed(t)?0:i.width)}),c.push({width:i.width,height:i.height,top:o,left:a})}}return{selectionRects:c,caretPosition:h}}var Ud=Object.freeze([]);function jd(e={}){var t,n=e,{containerRef:r,shouldGenerateOverlay:i}=n,s=((e,t)=>{var n={};for(var r in e)Ad.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&Ed)for(var r of Ed(e))t.indexOf(r)<0&&Td.call(e,r)&&(n[r]=e[r]);return n})(n,["containerRef","shouldGenerateOverlay"]);const o=Pd(),a=Nd(),c=function(){const[,e]=Dn(e=>e+1,0),t=On(null),n=()=>{t.current&&(cancelAnimationFrame(t.current),t.current=0)};return Tn(n),Tn(()=>n,[]),An((n=!1)=>{n?e():t.current||(t.current=requestAnimationFrame(e))},[])}(),l=On(/* @__PURE__ */new WeakMap),[h,d]=Pn({}),u=!("refreshOnResize"in s)||(null==(t=s.refreshOnResize)||t);return function(e,t){const n=On(t);n.current=t;const[r]=Pn(()=>new ResizeObserver(()=>{n.current()}));Tn(()=>{if(!(null==e?void 0:e.current))return;const{current:t}=e;return r.observe(t),()=>r.unobserve(t)},[r,e])}(u?r:void 0,()=>{l.current=/* @__PURE__ */new WeakMap,c("debounced"!==u)}),xn(()=>{var e,t,n;if(r&&!r.current)return;const s=null==(e=null==r?void 0:r.current)?void 0:e.getBoundingClientRect(),c=null!=(t=null==s?void 0:s.x)?t:0,u=null!=(n=null==s?void 0:s.y)?n:0;let f=Object.keys(h).length!==Object.keys(a).length;const g=Object.fromEntries(Object.entries(a).map(([e,t])=>{const n=t.relativeSelection&&Od(o,t);if(!n)return[e,Ud];const r=l.current.get(n);if(r)return[e,r];const s=Id(o,n,{xOffset:c,yOffset:u,shouldGenerateOverlay:i});return f=!0,l.current.set(n,s),[e,s]}));f&&d(g)}),[Rn(()=>Object.entries(a).map(([e,t])=>{var n,r;const i=t.relativeSelection&&Od(o,t),s=h[e];return a=Rd({},t),c={range:i,caretPosition:null!=(n=null==s?void 0:s.caretPosition)?n:null,selectionRects:null!=(r=null==s?void 0:s.selectionRects)?r:Ud},Cd(a,Sd(c));var a,c}),[a,o,h]),An(()=>{l.current=/* @__PURE__ */new WeakMap,c(!0)},[c])]}function Fd(){return ge(Ih,"_isSynced")?/* @__PURE__ */Un(Bd,{}):null}function Bd(){const e=d(),[t]=jd({containerRef:e});/* @__PURE__ */
|
|
15
|
+
return Un(In,{children:t.map(e=>/* @__PURE__ */Un(Wd,{...e},e.clientId))})}function Wd({caretPosition:e,data:t,selectionRects:n}){if(!t)return null;const r={backgroundColor:(i=t.color,s=.5,i+Math.round(255*Math.min(Math.max(s,0),1)).toString(16).padStart(2,"0").toUpperCase())};var i,s;/* @__PURE__ */
|
|
16
|
+
return jn(In,{children:[n.map((e,t)=>/* @__PURE__ */Un("div",{className:"pointer-events-none absolute",style:{...r,...e}},t)),e&&/* @__PURE__ */Un(Vd,{data:t,caretPosition:e})]})}var Hd=.7,qd=1;function Vd({caretPosition:e,data:t}){const[n,r]=En.useState(!1),i={...e,background:t?.color,opacity:Hd,transition:"opacity 0.2s"},s={...i,opacity:qd},o={background:t?.color,opacity:Hd,transform:"translateY(-100%)",transition:"opacity 0.2s"},a={...o,opacity:qd};/* @__PURE__ */
|
|
17
|
+
return Un("div",{className:"absolute w-0.5",style:n?s:i,children:/* @__PURE__ */Un("div",{className:"absolute top-0 whitespace-nowrap rounded rounded-bl-none px-1.5 py-0.5 text-white text-xs",style:n?a:o,onMouseEnter:()=>{r(!0)},onMouseLeave:()=>{r(!1)},children:t?.name})})}function zd({documentId:e,initialValue:t=re,user:n,authToken:r,className:i,renderToolbar:s,overlays:o}){const a=Li("plate",e),c=n.color??Fi(n.id),l=Boolean(r),h=$({plugins:l?[...Q,Ih.configure({options:{cursors:{data:{color:c,name:n.name}},providers:Ui({documentId:e,token:r})},render:{afterEditable:Fd}})]:Q,skipInitialization:l,value:l?void 0:t},[a,l]);En.useEffect(()=>{if(l)return h.getApi(Ih).yjs.init({id:a,value:t}),()=>{h.getApi(Ih).yjs.destroy()}},[l,h,a]);const[,d]=En.useReducer(e=>e+1,0),u=En.useMemo(()=>h?ls(h):Ir("plate"),[h]);return En.useEffect(()=>{d()},[h]),/* @__PURE__ */Un("div",{className:`flex h-full min-h-0 w-full flex-col ${i??""}`,"data-room":a,children:/* @__PURE__ */jn(U,{editor:h,children:[s?s(u):/* @__PURE__ */Un(zr,{adapter:u}),/* @__PURE__ */jn(pe,{className:"relative min-h-0 flex-1",children:[/* @__PURE__ */Un(te,{placeholder:"Start writing…",variant:"default"}),o]})]})})}function $d(e){/* @__PURE__ */
|
|
18
|
+
return Un(zd,{...e,overlays:/* @__PURE__ */Un(G,{children:/* @__PURE__ */Un(ie,{})}),renderToolbar:()=>/* @__PURE__ */Un(H,{className:fe,children:/* @__PURE__ */Un(F,{})})})}export{b as AIMenu,le as AIToolbarButton,P as AiKit,k as AiPlugin,ce as DEFAULT_PLATE_AI_OPTIONS,re as EMPTY_PLATE_VALUE,H as FixedToolbar,F as FixedToolbarButtons,G as FloatingToolbar,ie as FloatingToolbarButtons,K as MediaKit,Ur as REASON_TOOLBAR,fe as REASON_TOOLBAR_SKIN,Pi as ROOM_PREFIX,zd as ReasonPlateEditor,$d as ReasonPlaygroundEditor,ni as ReasonSidebar,Gi as ReasonTiptapEditor,zr as ReasonToolbar,$r as SIDEBAR_DOCUMENTS_STORAGE_KEY,Li as collaborationRoom,jr as collectToolbarCommands,M as createAiKit,Ii as createCollaborationSession,Ir as createNullAdapter,ls as createPlateAdapter,Xr as createSidebarDocument,zi as createTiptapAdapter,Fi as cursorColorFor,ei as deleteSidebarDocument,_ as getPlateAiController,Ni as hocuspocusUrl,ae as htmlToPlateValue,Gr as listSidebarDocuments,Mi as parseCollaborationRoom,Y as plateBasePlugins,Q as platePlugins,V as plateValueToHtml,Ui as plateYjsProviders,Zr as renameSidebarDocument,ti as subscribeSidebarDocuments};
|