react-reason-editor 1.0.77 → 1.0.78
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-CfgczVyp.cjs +1 -0
- package/dist/Ai-DsWeNKXF.js +1 -0
- package/dist/Ai.cjs +1 -1
- package/dist/Ai.js +1 -1
- package/dist/{Attachment-bBEf8uOc.js → Attachment-BmQoshq_.js} +1 -1
- package/dist/Attachment.cjs +1 -1
- package/dist/Attachment.js +1 -1
- package/dist/{Blockquote-Cw5Zty9X.js → Blockquote-cNS4L62L.js} +1 -1
- package/dist/Blockquote.cjs +1 -1
- package/dist/Blockquote.js +1 -1
- package/dist/{Bold-BwuX7fZs.js → Bold-DiKXbC2z.js} +1 -1
- package/dist/Bold.cjs +1 -1
- package/dist/Bold.js +1 -1
- package/dist/BubbleMenus-CIOMgQ-M.js +216 -0
- package/dist/BubbleMenus-vqNuXWlm.cjs +1 -0
- package/dist/BulletList.cjs +1 -1
- package/dist/BulletList.js +1 -1
- package/dist/{Callout-CJofZEpX.js → Callout-BLkbFKjv.js} +1 -1
- package/dist/{Callout-wjo2BYZi.cjs → Callout-CpkjGEBS.cjs} +1 -1
- package/dist/Callout.cjs +1 -1
- package/dist/Callout.js +1 -1
- package/dist/Clear.cjs +1 -1
- package/dist/Clear.js +1 -1
- package/dist/{Code-CtIvf6_L.js → Code-DvYJ892R.js} +1 -1
- package/dist/Code.cjs +1 -1
- package/dist/Code.js +1 -1
- package/dist/{CodeBlock-DoIb7GC2.js → CodeBlock-B3dLyClh.js} +1 -1
- package/dist/CodeBlock.cjs +1 -1
- package/dist/CodeBlock.js +1 -1
- package/dist/CodeView.cjs +1 -1
- package/dist/CodeView.js +1 -1
- package/dist/{Color-DSs2MkQU.js → Color-Cng09GRR.js} +1 -1
- package/dist/{Color-B9PloDr5.cjs → Color-ZjBs7t7J.cjs} +1 -1
- package/dist/Color.cjs +1 -1
- package/dist/Color.js +1 -1
- package/dist/{Column-BXSoMVXw.cjs → Column-BaMOYvoO.cjs} +1 -1
- package/dist/{Column-CrT9596v.js → Column-DO6MfrOQ.js} +1 -1
- package/dist/Column.cjs +1 -1
- package/dist/Column.js +1 -1
- package/dist/{Drawer-CfcCPGCn.cjs → Drawer-CC24iVYp.cjs} +1 -1
- package/dist/{Drawer-DuQ5tw2t.js → Drawer-CL5Rhqw4.js} +1 -1
- package/dist/Drawer.cjs +1 -1
- package/dist/Drawer.js +1 -1
- package/dist/{Drawio-DQEgw3du.cjs → Drawio-CD_Tea_o.cjs} +1 -1
- package/dist/{Drawio-P620K_Ps.js → Drawio-LEtUoVAY.js} +1 -1
- package/dist/Drawio.cjs +1 -1
- package/dist/Drawio.js +1 -1
- package/dist/{Emoji-CYM4tY7s.js → Emoji-DN3yfwz_.js} +1 -1
- package/dist/Emoji.cjs +1 -1
- package/dist/Emoji.js +1 -1
- package/dist/{ExportPdf-BoD_D91q.js → ExportPdf-CrQVmD4l.js} +1 -1
- package/dist/ExportPdf.cjs +1 -1
- package/dist/ExportPdf.js +1 -1
- package/dist/{ExportWord-Bj9q_cyK.js → ExportWord-BM4ogH_i.js} +1 -1
- package/dist/ExportWord.cjs +1 -1
- package/dist/ExportWord.js +1 -1
- package/dist/FontFamily.cjs +1 -1
- package/dist/FontFamily.js +1 -1
- package/dist/FontSize.cjs +1 -1
- package/dist/FontSize.js +1 -1
- package/dist/{Heading-BHOPoy3X.js → Heading-Bcrl3eKU.js} +1 -1
- package/dist/Heading.cjs +1 -1
- package/dist/Heading.js +1 -1
- package/dist/{Highlight-BxKQNHmT.cjs → Highlight-cO9V18Me.cjs} +1 -1
- package/dist/{Highlight-3SpxpGDw.js → Highlight-uXDlNgw3.js} +1 -1
- package/dist/Highlight.cjs +1 -1
- package/dist/Highlight.js +1 -1
- package/dist/{History-CmI6jUTV.js → History-BoHiw0Bn.js} +1 -1
- package/dist/History.cjs +1 -1
- package/dist/History.js +1 -1
- package/dist/{HorizontalRule-BeLfU92F.js → HorizontalRule-C7mAKdzL.js} +1 -1
- package/dist/HorizontalRule.cjs +1 -1
- package/dist/HorizontalRule.js +1 -1
- package/dist/{Iframe-D-WaYtdF.cjs → Iframe-DGL_MOLf.cjs} +1 -1
- package/dist/{Iframe-C0ozlEX4.js → Iframe-D_IjezyZ.js} +1 -1
- package/dist/Iframe.cjs +1 -1
- package/dist/Iframe.js +1 -1
- package/dist/Image.cjs +1 -1
- package/dist/Image.js +1 -1
- package/dist/{ImageCropper-BVl7AuRL.js → ImageCropper-ChOGJuHZ.js} +1 -1
- package/dist/{ImageCropper-DqHxEOtN.cjs → ImageCropper-DDWnFI2-.cjs} +1 -1
- package/dist/{ImageGif-BSVyqEv6.cjs → ImageGif-3dik7FeU.cjs} +1 -1
- package/dist/{ImageGif-BvthT-Lc.js → ImageGif-D_kKkBU5.js} +1 -1
- package/dist/ImageGif.cjs +1 -1
- package/dist/ImageGif.js +1 -1
- package/dist/{ImportWord-C6EnXbyR.js → ImportWord-CtFBb_n4.js} +1 -1
- package/dist/ImportWord.cjs +1 -1
- package/dist/ImportWord.js +1 -1
- package/dist/{Indent-BuzxHbMb.js → Indent-BIk98fDV.js} +1 -1
- package/dist/{Indent-eL-WNEF4.cjs → Indent-BVMl9zKV.cjs} +1 -1
- package/dist/Indent.cjs +1 -1
- package/dist/Indent.js +1 -1
- package/dist/{Italic-D8ZI09FZ.js → Italic-3mlmsxqN.js} +1 -1
- package/dist/Italic.cjs +1 -1
- package/dist/Italic.js +1 -1
- package/dist/{Katex-46mDLDuw.cjs → Katex-C2AcX_Un.cjs} +1 -1
- package/dist/{Katex-B-lo5eMz.js → Katex-DRPWO2AM.js} +1 -1
- package/dist/Katex.cjs +1 -1
- package/dist/Katex.js +1 -1
- package/dist/LineHeight.cjs +1 -1
- package/dist/LineHeight.js +1 -1
- package/dist/{Link-CDtipqwb.js → Link-D5y_0ekP.js} +1 -1
- package/dist/Link.cjs +1 -1
- package/dist/Link.js +1 -1
- package/dist/{LinkEditBlock-D0V9PwbF.cjs → LinkEditBlock-D78J06F7.cjs} +1 -1
- package/dist/MarkdownPaste.cjs +1 -1
- package/dist/MarkdownPaste.js +1 -1
- package/dist/{Mermaid-DDV93CBT.cjs → Mermaid-B6SL3cf5.cjs} +1 -1
- package/dist/{Mermaid-Cb8MiE1N.js → Mermaid-BaTtCsrD.js} +1 -1
- package/dist/Mermaid.cjs +1 -1
- package/dist/Mermaid.js +1 -1
- package/dist/{MoreMark-CJ3nTD1T.js → MoreMark-Bfsa3STU.js} +1 -1
- package/dist/MoreMark.cjs +1 -1
- package/dist/MoreMark.js +1 -1
- package/dist/OrderedList.cjs +1 -1
- package/dist/OrderedList.js +1 -1
- package/dist/{ReasonDocs-BliNN1Tt.cjs → ReasonDocs-Bjefr26w.cjs} +1 -1
- package/dist/{ReasonDocs-4vxZ3zY7.js → ReasonDocs-_hTAa8-q.js} +1 -1
- package/dist/{RichTextProvider-Dl77gVJI.cjs → RichTextProvider-BuTrDlZY.cjs} +1 -1
- package/dist/{RichTextProvider-E6rbc_J2.js → RichTextProvider-D9EtjDKS.js} +1 -1
- package/dist/SearchAndReplace.cjs +1 -1
- package/dist/SearchAndReplace.js +1 -1
- package/dist/{SlashCommand-DtlUkwyM.js → SlashCommand-Cg-Rvv3o.js} +1 -1
- package/dist/SlashCommand.js +1 -1
- package/dist/{Strike-CWYl45VK.js → Strike-CSxbYwpk.js} +1 -1
- package/dist/Strike.cjs +1 -1
- package/dist/Strike.js +1 -1
- package/dist/{Table-DCLsW5DJ.js → Table-CFcOg-4n.js} +1 -1
- package/dist/{Table-C9RAHNEk.cjs → Table-Do_kTawS.cjs} +1 -1
- package/dist/Table.cjs +1 -1
- package/dist/Table.js +1 -1
- package/dist/TaskList.cjs +1 -1
- package/dist/TaskList.js +1 -1
- package/dist/{TextAlign-D4UgbJ7F.cjs → TextAlign-CcsTIs-9.cjs} +1 -1
- package/dist/{TextAlign-9ezg8E99.js → TextAlign-Dun3_Ozv.js} +1 -1
- package/dist/TextAlign.cjs +1 -1
- package/dist/TextAlign.js +1 -1
- package/dist/TextDirection.cjs +1 -1
- package/dist/TextDirection.js +1 -1
- package/dist/{TextUnderline-C5A078R0.js → TextUnderline-Cqm5NQVW.js} +1 -1
- package/dist/TextUnderline.cjs +1 -1
- package/dist/TextUnderline.js +1 -1
- package/dist/{Twitter-D7ulyHFD.cjs → Twitter-B4IYTs3E.cjs} +1 -1
- package/dist/{Twitter-ByGJ4v1K.js → Twitter-CZHAICpz.js} +1 -1
- package/dist/Twitter.cjs +1 -1
- package/dist/Twitter.js +1 -1
- package/dist/{Video-hhw77FP4.js → Video-5nw_Zeob.js} +1 -1
- package/dist/{Video-ConJGjxP.cjs → Video-CtGR5VVD.cjs} +1 -1
- package/dist/Video.cjs +1 -1
- package/dist/Video.js +1 -1
- package/dist/WordCount.cjs +1 -1
- package/dist/WordCount.js +1 -1
- package/dist/bubble-BhkjoWdo.js +79 -0
- package/dist/bubble.cjs +1 -1
- package/dist/bubble.js +1 -1
- package/dist/{cdn-loader-BGIuN138-wkFA6jnE.cjs → cdn-loader-BGIuN138-7PrAg-Ef.cjs} +1 -1
- package/dist/docs-agent.cjs +1 -1
- package/dist/docs-agent.js +1 -1
- package/dist/editor-kit.cjs +1 -1
- package/dist/editor-kit.js +1 -1
- package/dist/editorConfig-BR7z-P0e.js +18 -0
- package/dist/editorConfig-CHBSp2KG.cjs +1 -0
- package/dist/extensions/Ai/Ai.d.ts +22 -5
- package/dist/extensions/Ai/commands.d.ts +6 -1
- package/dist/extensions/Ai/components/AiMenu.d.ts +6 -5
- package/dist/extensions/Ai/components/RichTextAi.d.ts +12 -0
- package/dist/extensions/Ai/index.d.ts +9 -3
- package/dist/extensions/Ai/lib/completionToContent.d.ts +35 -0
- package/dist/extensions/Ai/lib/createStreamingCompletion.d.ts +27 -0
- package/dist/extensions/Ai/lib/prompt.d.ts +38 -0
- package/dist/extensions/Ai/lib/sanitizeCompletion.d.ts +37 -0
- package/dist/extensions/Ai/types.d.ts +47 -3
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/marked.esm-B7mQ2Kzc.cjs +1 -0
- package/dist/marked.esm-CNm6O672.js +1 -0
- package/dist/{react-BQVDEMs2.cjs → react-Bfe0Tko8.cjs} +1 -1
- package/dist/reason-docs.cjs +1 -1
- package/dist/reason-docs.js +1 -1
- package/dist/{reason-toolbar-skin-9xQLtzeK.js → reason-toolbar-skin-BNYK97ET.js} +1 -1
- package/dist/{reason-toolbar-skin-DyYu9ywU.cjs → reason-toolbar-skin-CD4T53He.cjs} +1 -1
- package/dist/style.css +1 -1
- package/dist/useButtonProps-BBiR6DPI.cjs +1 -0
- package/dist/useButtonProps-Codtb0k0.js +1 -0
- package/package.json +1 -1
- package/dist/Ai-BGpnAE8s.js +0 -1
- package/dist/Ai-CORhNCSN.cjs +0 -1
- package/dist/BubbleMenus-QlttKSIN.cjs +0 -1
- package/dist/BubbleMenus-mwxYB3IU.js +0 -195
- package/dist/MarkdownPaste-C5jQ33SR.js +0 -1
- package/dist/bubble-CpeBzXMe.js +0 -78
- package/dist/editorConfig-D-Tlrdwj.js +0 -18
- package/dist/editorConfig-Du7YaEDm.cjs +0 -1
- package/dist/useButtonProps-BFfsKvCi.cjs +0 -1
- package/dist/useButtonProps-BZwO1Of-.js +0 -1
package/dist/docs-agent.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./rolldown-runtime-BeavJI0R.cjs"),t=require("./dist-2-kjLBhJ.cjs"),n=require("./tooltip-DSRLxJD_.cjs"),r=require("./editorConfig-Du7YaEDm.cjs"),i=require("./reason-toolbar-skin-DyYu9ywU.cjs"),o=require("./dropdown-menu-BNKyUimd.cjs"),s=require("./Transcribe.cjs"),a=require("./dist-D4Q5o5oU.cjs");let c=require("react"),l=e.__toESM(c,1);c=e.__toESM(c);let d=require("@tiptap/core"),u=require("@tiptap/pm/state"),h=require("react/jsx-runtime"),f=require("lucide-react"),p=require("react-dom");p=e.__toESM(p);let g=require("scroll-into-view-if-needed");g=e.__toESM(g);let m=require("use-sync-external-store/shim");require("use-sync-external-store/shim/with-selector");let y=require("use-voice-control/client");var b=class extends a.Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=a.getUnixTime();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&&w(this,t,"timeout")},a.floor(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:a.getUnixTime()});const o=[],s=[],c=[],l=[];null===e?l.push(t):null==i?null!=e&&o.push(t):(s.push(t),a.equalityDeep(i,e)||c.push(t)),(o.length>0||c.length>0||l.length>0)&&this.emit("change",[{added:o,updated:c,removed:l},"local"]),this.emit("update",[{added:o,updated:s,removed:l},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},w=(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:a.getUnixTime()})}r.push(n)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},v=(e,t,n=e.states)=>{const r=t.length,i=a.createEncoder();a.writeVarUint(i,r);for(let o=0;o<r;o++){const r=t[o],s=n.get(r)||null,c=e.meta.get(r).clock;a.writeVarUint(i,r),a.writeVarUint(i,c),a.writeVarString(i,JSON.stringify(s))}return a.toUint8Array(i)},_=(e,t,n)=>{const r=a.createDecoder(t),i=a.getUnixTime(),o=[],s=[],c=[],l=[],d=a.readVarUint(r);for(let u=0;u<d;u++){const t=a.readVarUint(r);let n=a.readVarUint(r);const d=JSON.parse(a.readVarString(r)),u=e.meta.get(t),h=e.states.get(t),f=void 0===u?0:u.clock;(f<n||f===n&&null===d&&e.states.has(t))&&(null===d?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,d),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===u&&null!==d?o.push(t):void 0!==u&&null===d?l.push(t):null!==d&&(a.equalityDeep(d,h)||c.push(t),s.push(t)))}(o.length>0||c.length>0||l.length>0)&&e.emit("change",[{added:o,updated:c,removed:l},n]),(o.length>0||s.length>0||l.length>0)&&e.emit("update",[{added:o,updated:s,removed:l},n])};function S(e){return{engine:e,execute(){},isActive:()=>!1,isEnabled:()=>!1,getValue(){},subscribe:()=>()=>{}}}var E=[{kind:"button",id:"undo",label:"Undo",icon:f.Undo2,shortcut:"⌘Z"},{kind:"button",id:"redo",label:"Redo",icon:f.Redo2,shortcut:"⇧⌘Z"},{kind:"separator",id:"history-divider"},{kind:"button",id:"bold",label:"Bold",icon:f.Bold,shortcut:"⌘B"},{kind:"button",id:"italic",label:"Italic",icon:f.Italic,shortcut:"⌘I"},{kind:"button",id:"underline",label:"Underline",icon:f.Underline,shortcut:"⌘U"},{kind:"button",id:"highlight",label:"Highlight",icon:f.Highlighter,shortcut:"⌘⇧H"},{kind:"separator",id:"marks-divider"},{kind:"menu",id:"block-format",label:"Block Format",icon:f.Rows3,children:[{kind:"button",id:"paragraph",label:"Paragraph",icon:f.Pilcrow},{kind:"button",id:"heading-1",label:"Heading 1",icon:f.Heading1,shortcut:"Ctrl+Alt+1"},{kind:"button",id:"heading-2",label:"Heading 2",icon:f.Heading2,shortcut:"Ctrl+Alt+2"},{kind:"button",id:"heading-3",label:"Heading 3",icon:f.Heading3,shortcut:"Ctrl+Alt+3"},{kind:"button",id:"heading-4",label:"Heading 4",icon:f.Heading4,shortcut:"Ctrl+Alt+4"},{kind:"button",id:"heading-5",label:"Heading 5",icon:f.Heading5,shortcut:"Ctrl+Alt+5"},{kind:"button",id:"heading-6",label:"Heading 6",icon:f.Heading6,shortcut:"Ctrl+Alt+6"},{kind:"separator",id:"block-format-lists-divider"},{kind:"button",id:"bullet-list",label:"Bullet List",icon:f.List,shortcut:"Ctrl+Shift+8"},{kind:"button",id:"ordered-list",label:"Ordered List",icon:f.ListOrdered,shortcut:"Ctrl+Shift+7"},{kind:"button",id:"task-list",label:"Check List",icon:f.ListChecks,shortcut:"Ctrl+Shift+9"},{kind:"separator",id:"block-format-quote-divider"},{kind:"button",id:"blockquote",label:"Blockquote",icon:f.Quote,shortcut:"Ctrl+Shift+B"},{kind:"button",id:"code-block",label:"Code Block",icon:f.Code2,shortcut:"Ctrl+Alt+C"},{kind:"separator",id:"block-format-clear-divider"},{kind:"button",id:"clear-formatting",label:"Clear Format",icon:f.Eraser}]},{kind:"menu",id:"text-styles",label:"Text Styles",icon:f.Type,children:[{kind:"group-label",id:"text-styles-label",label:"Text Styles"},{kind:"button",id:"strike",label:"Strikethrough",icon:f.Strikethrough,shortcut:"Ctrl+Shift+S"},{kind:"button",id:"code",label:"Inline Code",icon:f.Code,shortcut:"Ctrl+E"},{kind:"button",id:"text-color",label:"Text Color",icon:f.Baseline,shortcut:"Alt+Shift+C"},{kind:"button",id:"superscript",label:"Superscript",icon:f.Superscript,shortcut:"Ctrl+."},{kind:"button",id:"subscript",label:"Subscript",icon:f.Subscript,shortcut:"Ctrl+,"},{kind:"separator",id:"text-styles-indent-divider"},{kind:"button",id:"indent",label:"Indent",icon:f.IndentIncrease},{kind:"button",id:"outdent",label:"Outdent",icon:f.IndentDecrease},{kind:"menu",id:"alignment",label:"Alignment",icon:f.AlignLeft,children:[{kind:"button",id:"align-left",label:"Align Left",icon:f.AlignLeft},{kind:"button",id:"align-center",label:"Align Center",icon:f.AlignCenter},{kind:"button",id:"align-right",label:"Align Right",icon:f.AlignRight},{kind:"button",id:"align-justify",label:"Justify",icon:f.AlignJustify}]}]},{kind:"menu",id:"insert",label:"Insert",icon:f.Plus,children:[{kind:"group-label",id:"insert-label",label:"Insert"},{kind:"button",id:"link",label:"Link",icon:f.Link2},{kind:"button",id:"emoji",label:"Emoji",icon:f.Smile},{kind:"button",id:"table",label:"Table",icon:f.Table2},{kind:"button",id:"image",label:"Image",icon:f.Image},{kind:"button",id:"columns",label:"Columns",icon:f.Columns2,shortcut:"Ctrl+Alt+G"},{kind:"button",id:"callout",label:"Callout",icon:f.Info},{kind:"button",id:"horizontal-rule",label:"Divider",icon:f.Minus,shortcut:"Ctrl+Alt+S"},{kind:"button",id:"video",label:"Video",icon:f.Video},{kind:"button",id:"math",label:"Math",icon:f.Sigma}]},{kind:"separator",id:"voice-divider"},{kind:"button",id:"transcribe",label:"Dictate",icon:f.Mic,shortcut:"Ctrl+Shift+D"},{kind:"menu",id:"table-tools",label:"Table",icon:f.Table2,visibleWhenActive:"table",children:[{kind:"group-label",id:"table-rows-label",label:"Rows"},{kind:"button",id:"table.add-row-before",label:"Insert Row Above",icon:f.Rows3},{kind:"button",id:"table.add-row-after",label:"Insert Row Below",icon:f.Rows3},{kind:"button",id:"table.delete-row",label:"Delete Row",icon:f.Trash2},{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:f.Columns2},{kind:"button",id:"table.add-column-after",label:"Insert Column Right",icon:f.Columns2},{kind:"button",id:"table.delete-column",label:"Delete Column",icon:f.Trash2},{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:f.Braces},{kind:"button",id:"table.split-cell",label:"Split Cell",icon:f.Braces},{kind:"button",id:"table.toggle-header-row",label:"Toggle Header Row",icon:f.Rows3},{kind:"separator",id:"table-delete-divider"},{kind:"button",id:"table.delete",label:"Delete Table",icon:f.Trash2}]}];var C="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",k="bg-gray-200 text-gray-900 dark:bg-slate-700 dark:text-white",T="flex w-full cursor-pointer items-center gap-2 text-xs data-disabled:cursor-not-allowed data-disabled:opacity-40";function x({shortcut:e}){return e?(0,h.jsx)("span",{className:"ml-auto pl-4 text-[10px] tracking-widest text-gray-400 dark:text-gray-500",children:e}):null}function R({items:e,adapter:n}){return(0,h.jsx)(h.Fragment,{children:e.map(e=>{if("separator"===e.kind)return(0,h.jsx)(o.DropdownMenuSeparator,{},e.id);if("group-label"===e.kind)return(0,h.jsx)(o.DropdownMenuLabel,{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 t=e.icon;return(0,h.jsxs)(o.DropdownMenuSub,{children:[(0,h.jsxs)(o.DropdownMenuSubTrigger,{className:T,children:[(0,h.jsx)(t,{className:"size-3.5 shrink-0 text-gray-500 dark:text-gray-400"}),e.label]}),(0,h.jsx)(o.DropdownMenuPortal,{children:(0,h.jsx)(o.DropdownMenuSubContent,{className:"min-w-[200px]",children:(0,h.jsx)(R,{items:e.children,adapter:n})})})]},e.id)}const r=e.icon,i=n.isActive(e.id);return(0,h.jsxs)(o.DropdownMenuItem,{"aria-pressed":i,className:t.cn(T,i&&k),"data-command":e.id,"data-state":i?"active":"inactive",disabled:!n.isEnabled(e.id),onSelect:()=>{n.execute(e.id)},children:[(0,h.jsx)(r,{className:"size-3.5 shrink-0 text-gray-500 dark:text-gray-400"}),(0,h.jsx)("span",{className:"truncate",children:e.label}),(0,h.jsx)(x,{shortcut:e.shortcut})]},e.id)})})}function A({item:e,adapter:r}){if("separator"===e.kind)return(0,h.jsx)("div",{className:"mx-1 h-5 w-px bg-gray-200 dark:bg-slate-700"});if("group-label"===e.kind)return(0,h.jsx)("span",{className:"px-1 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:e.label});if("menu"===e.kind){if(e.visibleWhenActive&&!r.isActive(e.visibleWhenActive))return null;const i=e.icon;return(0,h.jsxs)(o.DropdownMenu,{children:[(0,h.jsxs)(n.Tooltip,{children:[(0,h.jsx)(n.TooltipTrigger,{asChild:!0,children:(0,h.jsx)(o.DropdownMenuTrigger,{"aria-label":e.label,className:t.cn(C,"data-[state=open]:bg-gray-200 dark:data-[state=open]:bg-slate-700"),"data-menu":e.id,children:(0,h.jsx)(i,{className:"size-4"})})}),(0,h.jsx)(n.TooltipContent,{side:"bottom",children:e.label})]}),(0,h.jsx)(o.DropdownMenuContent,{align:"start",className:"min-w-[240px]",children:(0,h.jsx)(R,{items:e.children,adapter:r})})]})}const i=e.icon,s=r.isActive(e.id),a=r.isEnabled(e.id);return(0,h.jsxs)(n.Tooltip,{children:[(0,h.jsx)(n.TooltipTrigger,{asChild:!0,children:(0,h.jsx)("button",{"aria-label":e.label,"aria-pressed":s,className:t.cn(C,s&&k),"data-command":e.id,"data-state":s?"active":"inactive",disabled:!a,onClick:()=>{r.execute(e.id)},type:"button",children:(0,h.jsx)(i,{className:"size-4"})})}),(0,h.jsxs)(n.TooltipContent,{side:"bottom",children:[e.label,e.shortcut?(0,h.jsx)("span",{className:"ml-2 text-[10px] tracking-widest opacity-70",children:e.shortcut}):null]})]})}function O({adapter:e,items:r=E,className:i,children:o}){return function(e){const[t,n]=l.useState(0);l.useEffect(()=>{if(e.subscribe)return e.subscribe(()=>n(e=>e+1))},[e])}(e),(0,h.jsx)(n.TooltipProvider,{delayDuration:300,children:(0,h.jsxs)("div",{className:t.cn("flex flex-wrap items-center gap-0.5 border-b border-gray-200 px-2 py-1 dark:border-slate-700",i),"data-engine":e.engine,role:"toolbar",children:[r.map(t=>(0,h.jsx)(A,{adapter:e,item:t},(t.kind,t.id))),o?(0,h.jsx)("div",{className:"ml-auto flex items-center gap-1",children:o}):null]})})}var D="REASON-documents",P="reason-documents-changed";function N(){if("undefined"==typeof window)return[];try{const e=window.localStorage.getItem(D);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function L(e){"undefined"!=typeof window&&(window.localStorage.setItem(D,JSON.stringify(e)),window.dispatchEvent(new Event(P)))}function M(e){return{id:e.id,title:e.title?.trim()||"Untitled Document"}}function U(){return N().filter(e=>!e.isFolder&&!e.isDeleted&&!e.parentId).map(M)}function j(e="Untitled Document"){const t={id:`doc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,title:e,content:"",parentId:null};return L([...N(),t]),M(t)}function I(e,t){const n=t.trim()||"Untitled Document";L(N().map(t=>t.id===e?{...t,title:n}:t))}function B(e){L(N().map(t=>t.id===e?{...t,isDeleted:!0}:t))}function F(e){if("undefined"==typeof window)return()=>{};const t=t=>{"REASON-documents"===t.key&&e()};return window.addEventListener(P,e),window.addEventListener("storage",t),()=>{window.removeEventListener(P,e),window.removeEventListener("storage",t)}}var V=function(e){return e[e.Token=0]="Token",e[e.PermissionDenied=1]="PermissionDenied",e[e.Authenticated=2]="Authenticated",e}({}),W=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var q=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 Y(e){return new Promise(t=>setTimeout(t,e))}function H(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 K(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 s of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const e=n[s];if(!Number.isInteger(e)||e<0)throw new Error(`Value for ${s} 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||H;const o=n.calculateDelay?n.calculateDelay(r,n):n.initialDelay;if(o&&await Y(o),r.attemptNum<1&&n.initialJitter){const e=i(r,n);e&&await Y(e)}return async function t(){if(n.beforeAttempt&&n.beforeAttempt(r,n),r.aborted){const e=new Error("Attempt aborted");throw e.code="ATTEMPT_ABORTED",e}const o=async e=>{if(n.handleError&&await n.handleError(e,r,n),r.aborted||0===r.attemptsRemaining)throw e;r.attemptNum++;const o=i(r,n);return o&&await Y(o),t()};return r.attemptsRemaining>0&&r.attemptsRemaining--,n.timeout?new Promise((t,i)=>{const s=setTimeout(()=>{if(n.handleTimeout)try{t(n.handleTimeout(r,n))}catch(e){i(e)}else{const e=new Error(`Retry timeout (attemptNum: ${r.attemptNum}, timeout: ${n.timeout})`);e.code="ATTEMPT_TIMEOUT",i(e)}},n.timeout);e(r,n).then(e=>{clearTimeout(s),t(e)}).catch(e=>{clearTimeout(s),o(e).then(t).catch(i)})}):e(r,n).catch(o)}()}var z=(e,t)=>{a.writeVarUint(e,0);const n=a.encodeStateVector(t);a.writeVarUint8Array(e,n)},$=(e,t,n)=>{a.writeVarUint(e,1),a.writeVarUint8Array(e,a.encodeStateAsUpdate(t,n))},G=(e,t,n,r)=>{try{a.applyUpdate(t,a.readVarUint8Array(e),n)}catch(i){null!=r&&r(i)}},X=(e,t)=>{a.writeVarUint(e,2),a.writeVarUint8Array(e,t)},Q=G,J=(e,t,n,r,i)=>{const o=a.readVarUint(e);switch(o){case 0:((e,t,n)=>{$(t,n,a.readVarUint8Array(e))})(e,t,n);break;case 1:G(e,n,r,i);break;case 2:Q(e,n,r,i);break;default:throw new Error("Unknown message type")}return o},Z=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={}}},ee=class{constructor(e){this.data=e,this.encoder=a.createEncoder(),this.decoder=a.createDecoder(new Uint8Array(this.data))}peekVarString(){return a.peekVarString(this.decoder)}readVarUint(){return a.readVarUint(this.decoder)}readVarString(){return a.readVarString(this.decoder)}readVarUint8Array(){return a.readVarUint8Array(this.decoder)}writeVarUint(e){return a.writeVarUint(this.encoder,e)}writeVarString(e){return a.writeVarString(this.encoder,e)}writeVarUint8Array(e){return a.writeVarUint8Array(this.encoder,e)}length(){return a.length(this.encoder)}},te=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}({}),ne=function(e){return e.Connecting="connecting",e.Connected="connected",e.Disconnected="disconnected",e}({}),re=class{constructor(){this.encoder=a.createEncoder()}get(e){return e.encoder}toUint8Array(){return a.toUint8Array(this.encoder)}},ie=class extends re{constructor(...e){super(...e),this.type=te.CLOSE,this.description="Ask the server to close the connection"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),this.encoder}},oe=class e extends Z{static{this.DEDUPLICATABLE_TYPES=new Set([te.Awareness,te.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:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=ne.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=ne.Connected,this.emit("status",{status:ne.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===ne.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===ne.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){const t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(ie,{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===ne.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:K(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=ne.Connecting,this.emit("status",{status:ne.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=a.getUnixTime();const t=new Uint8Array(e.data);if(1===t.length&&t[0]===te.Ping)return void this.sendPong();const n=new ee(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){const e=a.createEncoder();a.writeVarUint(e,te.Pong),this.send(a.toUint8Array(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=ne.Connected,this.emit("status",{status:ne.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===ne.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=a.getUnixTime()-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=a.createDecoder(e);return{documentName:a.readVarString(t),messageType:a.readVarUint(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===q.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=ne.Disconnected,this.emit("status",{status:ne.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()}},se=class{constructor(e){this.message=e}apply(e,t){const{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case te.Sync:this.applySyncMessage(e,t);break;case te.Awareness:this.applyAwarenessMessage(e);break;case te.Auth:this.applyAuthMessage(e);break;case te.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case te.Stateless:e.receiveStateless(a.readVarString(n.decoder));break;case te.SyncStatus:this.applySyncStatusMessage(e,1===a.readVarInt(n.decoder));break;case te.CLOSE:{const t={code:1e3,reason:a.readVarString(n.decoder)};e.onClose(),e.configuration.onClose({event:t}),e.forwardClose({event:t});break}}n.length()>i+1&&e.send(re,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(te.Sync);const r=J(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.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;((e,t,n,r)=>{switch(a.readVarUint(e)){case V.Token:t();break;case V.PermissionDenied:n(a.readVarString(e));break;case V.Authenticated:r(a.readVarString(e))}})(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(te.Awareness),t.writeVarUint8Array(v(e.awareness,Array.from(e.awareness.getStates().keys())))}},ae=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return a.toUint8Array(this.encoder)}send(e){e?.send(this.create())}},ce=class extends re{constructor(...e){super(...e),this.type=te.Auth,this.description="Authentication"}get(e){if(void 0===e.token)throw new Error("The authentication message requires `token` as an argument.");var t,n;return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),t=this.encoder,n=e.token,a.writeVarUint(t,V.Token),a.writeVarString(t,n),a.writeVarString(this.encoder,"4.4.0"),this.encoder}},le=class extends re{constructor(...e){super(...e),this.type=te.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 a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),t=void 0===e.states?v(e.awareness,e.clients):v(e.awareness,e.clients,e.states),a.writeVarUint8Array(this.encoder,t),this.encoder}},de=class extends re{constructor(...e){super(...e),this.type=te.Stateless,this.description="A stateless message"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),a.writeVarString(this.encoder,e.payload??""),this.encoder}},ue=class extends re{constructor(...e){super(...e),this.type=te.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 a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),z(this.encoder,e.document),this.encoder}},he=class extends re{constructor(...e){super(...e),this.type=te.Sync,this.description="A document update"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),X(this.encoder,e.update),this.encoder}},fe=class extends Error{constructor(...e){super(...e),this.code=1001}},pe=class extends Z{get effectiveName(){return this.configuration.sessionAwareness?(e=this.configuration.name,t=this.sessionId,e+"\0"+t):this.configuration.name;var e,t}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=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 a.Doc,this.configuration.awareness=void 0!==e.awareness?e.awareness:new b(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:W(this.awareness.getStates())})}),this.awareness?.on("change",()=>{this.emit("awarenessChange",{states:W(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 oe(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(ue,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&w(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(de,{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(ce,{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(he,{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){const i=e.concat(t).concat(n);if(this.batchingEnabled){for(const e of i)this.pendingAwarenessClients.add(e);this.scheduleFlush()}else this.send(le,{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]:a.mergeUpdates(this.pendingUpdates);this.pendingUpdates=[],this.send(he,{update:e,documentName:this.effectiveName})}if(this.pendingAwarenessClients.size>0){const e=Array.from(this.pendingAwarenessClients);this.pendingAwarenessClients.clear(),this.send(le,{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(ue,{document:this.document,documentName:this.effectiveName}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(le,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;const n=new ae(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new ee(e.data),{documentName:n}=function(e){const t=e.indexOf("\0");return-1===t?{documentName:e,sessionId:null}:{documentName:e.substring(0,t),sessionId:e.substring(t+1)}}(t.readVarString());t.writeVarString(this.effectiveName),this.emit("message",{event:e,message:new ee(e.data)}),new se(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&&w(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&&(w(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 fe(`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)}},ge="reason-editor";function me(e,t){if(!t)throw new Error("collaborationRoom: documentId is required");return`${ge}:${e}:${t}`}function ye(){return"undefined"!=typeof process&&(process.env.NEXT_PUBLIC_HOCUSPOCUS_URL??process.env.VITE_HOCUSPOCUS_URL)||"ws://127.0.0.1:1234"}function be({engine:e,documentId:t,token:n,url:r=ye(),onSynced:i}){const o=me(e,t),s=new a.Doc,c=new pe({document:s,name:o,token:n,url:r,onSynced:()=>i?.(!0)});return{room:o,ydoc:s,provider:c,destroy(){c.destroy(),s.destroy()}}}function we({documentId:e,token:t,url:n=ye()}){const r=me("plate",e);return[{type:"hocuspocus",options:{name:r,token:t,url:n}},{type:"indexeddb",options:{docName:r}}]}var ve=["#e11d48","#0891b2","#7c3aed","#ea580c","#16a34a","#2563eb","#db2777","#ca8a04"];function _e(e){let t=0;for(let n=0;n<e.length;n++)t=31*t+e.charCodeAt(n)|0;return ve[Math.abs(t)%ve.length]}var Se={bold:"bold",italic:"italic",underline:"underline",strike:"strike",code:"code",superscript:"superscript",subscript:"subscript",highlight:"highlight","text-color":"textStyle"},Ee={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"}},Ce={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},ke={"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 Te(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function xe(e){return{engine:"tiptap",execute(t,n){!function(e,t,n){const r=()=>e.chain().focus(),i=e.commands,o=ke[t];if(o)return void r()[o]?.().run();const s=Ce[t];if(s)r().setTextAlign?.(s).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=Te(n,"Link URL");if(!e)return;return void r().extendMarkRange("link").setLink({href:e}).run()}case"image":{const e=Te(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=Te(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=Ce[t];if(n)return e.isActive({textAlign:n});const r=Ee[t];if(r)return e.isActive(r.name,r.attrs);const i=Se[t];return i?"text-color"===t?!!e.getAttributes("textStyle").color:e.isActive(i):"link"===t?e.isActive("link"):"transcribe"===t&&!!s.getTranscribeStorage(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(0,y.isTranscriptionSupported)();const r=ke[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=s.subscribeTranscribe(e,t);return()=>{e.off("transaction",t),e.off("selectionUpdate",t),n()}}}}var Re=e=>Array.from(e.entries()).map(([e,t])=>t&&t.user?{clientId:e,...t.user}:{clientId:e}),Ae=()=>null,Oe=d.Extension.create({name:"collaborationCaret",priority:999,addOptions:()=>({provider:null,user:{name:null,color:null},render:e=>{const t=document.createElement("span");t.classList.add("collaboration-carets__caret"),t.setAttribute("style",`border-color: ${e.color}`);const n=document.createElement("div");return n.classList.add("collaboration-carets__label"),n.setAttribute("style",`background-color: ${e.color}`),n.insertBefore(document.createTextNode(e.name),null),t.insertBefore(n,null),t},selectionRender:a.defaultSelectionBuilder,onUpdate:Ae}),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 u.Plugin({key:new u.PluginKey("collaborationCaretAwarenessListener"),view:()=>{const r=()=>{t.users=Re(e.awareness.states)};return e.awareness.setLocalStateField("user",n),t.users=Re(e.awareness.states),e.awareness.on("update",r),{destroy:()=>{e.awareness.off("update",r),t.users=[]}}}}),a.yCursorPlugin(e.awareness,{cursorBuilder:this.options.render,selectionBuilder:this.options.selectionRender})]}});var De={bold:i.KEYS.bold,italic:i.KEYS.italic,underline:i.KEYS.underline,strike:i.KEYS.strikethrough,code:i.KEYS.code,superscript:i.KEYS.sup,subscript:i.KEYS.sub,highlight:i.KEYS.highlight,"text-color":i.KEYS.color},Pe={superscript:i.KEYS.sub,subscript:i.KEYS.sup},Ne={paragraph:i.KEYS.p,"heading-1":i.KEYS.h1,"heading-2":i.KEYS.h2,"heading-3":i.KEYS.h3,"heading-4":i.KEYS.h4,"heading-5":i.KEYS.h5,"heading-6":i.KEYS.h6,blockquote:i.KEYS.blockquote},Le={"bullet-list":i.ListStyleType.Disc,"ordered-list":i.ListStyleType.Decimal,"task-list":i.KEYS.listTodo},Me={"bullet-list":[i.ListStyleType.Disc,i.ListStyleType.Circle,i.ListStyleType.Square],"ordered-list":[i.ListStyleType.Decimal,i.ListStyleType.LowerAlpha,i.ListStyleType.UpperAlpha,i.ListStyleType.LowerRoman,i.ListStyleType.UpperRoman],"task-list":[i.KEYS.listTodo]},Ue={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},je=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 Ie(e){return!!e.selection&&Boolean(i.getTableAbove(e))}function Be(e){if(!Ie(e))return{canMerge:!1,canSplit:!1};const t=i.getSelectedCellEntries(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:o,minRow:s}=i.getSelectedCellsBoundingBox(e,n),a=n.reduce((e,t)=>e+i.getColSpan(t)*i.getRowSpan(t),0)===(t-o+1)*(r-s+1);return{canMerge:e.api.isExpanded()&&a,canSplit:!1}}const[r]=n;return{canMerge:!1,canSplit:i.getColSpan(r)>1||i.getRowSpan(r)>1}}function Fe(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function Ve(e,t){const n=function(e){if(je.has(e)||"table"===e)return i.KEYS.table;switch(e){case"highlight":return i.KEYS.highlight;case"text-color":return i.KEYS.color;case"link":return i.KEYS.link;case"image":return i.KEYS.img;case"video":return i.KEYS.video;case"math":return i.KEYS.equation;case"callout":return i.KEYS.callout;case"columns":return i.KEYS.columnGroup;case"transcribe":return"transcribe";case"emoji":return i.KEYS.emoji;case"code-block":return i.KEYS.codeBlock;case"bullet-list":case"ordered-list":case"task-list":return i.KEYS.list;case"indent":case"outdent":return i.KEYS.indent;case"align-left":case"align-center":case"align-right":case"align-justify":return i.KEYS.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?(0,y.isTranscriptionSupported)()&&!e.api.isReadOnly?.():"table.merge-cells"===t?Be(e).canMerge:"table.split-cell"===t?Be(e).canSplit:je.has(t)?Ie(e):!e.api.isReadOnly?.())}function We(e){return{engine:"plate",execute(t,n){!function(e,t,n){e.tf.focus();const r=De[t];if(r&&"text-color"!==t&&"highlight"!==t)return void e.tf.toggleMark(r,{remove:Pe[t]});const o=Ne[t];if(o)return void e.tf.toggleBlock(o,o===i.KEYS.blockquote?{wrap:!0}:void 0);const s=Le[t];if(s)return void i.toggleList(e,{listStyleType:s});const a=Ue[t];if(a)e.getTransforms(i.TextAlignPlugin).textAlign.setNodes(a);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.KEYS.color]===t?e.tf.removeMarks(i.KEYS.color):e.tf.addMarks({[i.KEYS.color]:t}))}case"highlight":return void(e.api.marks()?.[i.KEYS.highlight]?e.tf.removeMarks(i.KEYS.highlight):e.tf.addMarks({[i.KEYS.highlight]:n?.value??"#fde047"}));case"clear-formatting":return e.tf.removeMarks(Object.values(De)),void e.tf.toggleBlock(i.KEYS.p);case"code-block":return void i.toggleCodeBlock(e);case"link":return void(n?.value?i.upsertLink(e,{url:n.value}):i.triggerFloatingLink(e,{focused:!0}));case"image":{const t=Fe(n,"Image URL");if(!t)return;return void i.insertImage(e,t)}case"video":{const t=Fe(n,"Video URL");if(!t)return;return void i.insertMedia(e,{select:!0,type:i.KEYS.video,url:t})}case"table":return void i.insertTable(e,{colCount:3,rowCount:3},{select:!0});case"horizontal-rule":return void e.tf.insertNodes({children:[{text:""}],type:i.KEYS.hr});case"emoji":return void e.tf.insertText(":");case"math":return void i.insertEquation(e,{select:!0});case"callout":return void i.insertCallout(e,{select:!0});case"columns":return void i.insertColumnGroup(e,{columns:2,select:!0});case"transcribe":return void i.getTranscribeController(e).toggle();case"indent":return void i.indent(e);case"outdent":return void i.outdent(e);case"table.add-row-before":return void i.insertTableRow(e,{before:!0});case"table.add-row-after":return void i.insertTableRow(e);case"table.delete-row":return void i.deleteRow(e);case"table.add-column-before":return void i.insertTableColumn(e,{before:!0});case"table.add-column-after":return void i.insertTableColumn(e);case"table.delete-column":return void i.deleteColumn(e);case"table.merge-cells":return void i.mergeTableCells(e);case"table.split-cell":return void i.splitTableCell(e);case"table.toggle-header-row":{const t=i.getTableAbove(e);if(!t)return;const[n,r]=t;return void e.tf.setNodes({headerRow:!n.headerRow},{at:r})}case"table.delete":return void i.deleteTable(e);default:;}}(e,t,n)},isActive(t){if("transcribe"===t)return i.getTranscribeController(e).getState().listening;if(!e.selection)return!1;try{return function(e,t){if("task-list"===t)return i.someTodoList(e);const n=Me[t];if(n)return i.someList(e,n);const r=De[t];if(r)return Boolean(e.api.marks()?.[r]);const o=Ne[t];if(o)return e.api.some({match:{type:o}});if("code-block"===t)return e.api.some({match:{type:i.KEYS.codeBlock}});if("table"===t)return Ie(e);if("callout"===t)return e.api.some({match:{type:i.KEYS.callout}});if("columns"===t)return e.api.some({match:{type:i.KEYS.column}});if("link"===t)return e.api.some({match:{type:i.KEYS.link}});if("transcribe"===t)return i.getTranscribeController(e).getState().listening;const s=Ue[t];return!!s&&e.api.some({match:e=>e[i.KEYS.textAlign]===s})}(e,t)}catch{return!1}},isEnabled(t){try{return Ve(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.KEYS.color]:"highlight"===t?n?.[i.KEYS.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 o=i.getTranscribeController(e).subscribe(t);return()=>{e.apply=n,o()}}}}var qe=Object.defineProperty,Ye=Object.defineProperties,He=Object.getOwnPropertyDescriptors,Ke=Object.getOwnPropertySymbols,ze=Object.prototype.hasOwnProperty,$e=Object.prototype.propertyIsEnumerable,Ge=(e,t,n)=>t in e?qe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Xe=(e,t)=>{for(var n in t||(t={}))ze.call(t,n)&&Ge(e,n,t[n]);if(Ke)for(var n of Ke(t))$e.call(t,n)&&Ge(e,n,t[n]);return e},Qe=(e,t)=>Ye(e,He(t)),Je=(e,t)=>{var n={};for(var r in e)ze.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&Ke)for(var r of Ke(e))t.indexOf(r)<0&&$e.call(e,r)&&(n[r]=e[r]);return n};function Ze(e){return"[object Object]"===Object.prototype.toString.call(e)}function et(e){if(!Ze(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==Ze(n)&&!1!==n.hasOwnProperty("isPrototypeOf")}function tt(e,t){for(const n in e){const r=e[n],i=t[n];if(et(r)&&et(i)){if(!tt(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 nt(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function rt(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>null!==e))}function it(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&&tt(null!=(t=e.attributes)?t:{},null!=(n=i.attributes)?n:{}))?e.insert+=i.insert:r.push(i)}return r}(e.toDelta())}function ot({insert:e}){return"string"==typeof e?e.length:1}function st(e){return e.reduce((e,t)=>e+ot(t),0)}function at(e,t,n){if(n<1)return[];let r=0;const i=[],o=t+n;for(let s=0;s<e.length&&!(r>=o);s++){const n=e[s],a=ot(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-o));i.push(Qe(Xe({},n),{insert:n.insert.slice(c,l)})),r+=a}return i}function ct(e){return function(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}(e,i.Text.isText(e)?"text":"children")}function lt(e){const t=it(e),n=t.length>0?t.map(dt):[{text:""}];return Qe(Xe({},e.getAttributes()),{children:n})}function dt(e){return"string"==typeof e.insert?Qe(Xe({},e.attributes),{text:e.insert}):lt(e.insert)}function ut(e){return e.map(e=>i.Text.isText(e)?{insert:e.text,attributes:ct(e)}:{insert:ht(e)})}function ht(e){var t=e,{children:n}=t,r=Je(t,["children"]);const i=new a.YXmlText;return Object.entries(r).forEach(([e,t])=>{i.setAttribute(e,t)}),i.applyDelta(ut(n),{sanitize:!1}),i}function ft(e){return e?i.Text.isText(e)?e.text.length:1:0}function pt(e,t,n){var r;if(0===n.length)throw new Error("Path has to a have a length >= 1");if(i.Text.isText(t))throw new Error("Cannot descent into slate text");const[o,...s]=n,c=function(e,t){return e.children.slice(0,t).reduce((e,t)=>e+ft(t),0)}(t,o),l=t.children[o],d=it(e),u=ft(l),h=at(d,c,u);if(h.length>1)throw new Error("Path doesn't match yText, yTarget spans multiple nodes");const f=null==(r=h[0])?void 0:r.insert;if(s.length>0){if(!(f instanceof a.YXmlText))throw new Error("Path doesn't match yText, cannot descent into non-yText");return pt(f,l,s)}return{yParent:e,textRange:{start:c,end:c+u},yTarget:f instanceof a.YXmlText?f:void 0,slateParent:t,slateTarget:l,targetDelta:h}}function gt(e,t,n={}){const{assoc:r=0,insert:o=!1}=n;let s=0,a=0;for(let l=0;l<e.children.length;l++){const n=e.children[l],o=i.Text.isText(n)?n.text.length:1;o>0&&(a=l);const c=s+o;if(o>0&&(r>=0?c>t:c>=t))return[l,t-s];s+=o}if(t>s+(o?1:0))throw new Error("yOffset out of bounds");if(o)return[e.children.length,0];const c=e.children[a];return[a,i.Text.isText(c)?c.text.length:1]}function mt(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 a.YXmlText))throw new Error("Unexpected y parent type");r.unshift(e)}if(r.length<2)return[];let o=t;return r.reduce((e,t,n)=>{const s=r[n+1];if(!s)return e;let a=0;const c=it(t);for(const r of c){if(r.insert===s)break;a+="string"==typeof r.insert?r.insert.length:1}if(i.Text.isText(o))throw new Error("Cannot descent into slate text");const[l]=gt(o,a);return o=o.children[l],e.concat(l)},[])}function yt(e,t,n){const{target:r,changes:o}=n,s=n.delta;if(!(r instanceof a.YXmlText))throw new Error("Unexpected target node type");const c=[],l=mt(e,t,r),d=i.Node.get(t,l);if(i.Text.isText(d))throw new Error("Cannot apply yTextEvent to text node");const u=Array.from(o.keys.entries());if(l.length>0&&u.length>0){const e=Object.fromEntries(u.map(([e,t])=>[e,"delete"===t.action?null:r.getAttribute(e)])),t=Object.fromEntries(u.map(([e])=>[e,d[e]]));c.push({type:"set_node",newProperties:e,properties:t,path:l})}return s.length>0&&c.push(...function(e,t,n){const r=[];let o=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,a]=gt(e,o-n.retain),[c,l]=gt(e,o,{assoc:-1});for(let o=c;o>=s;o--){const d=e.children[o],u=[...t,o];if(!i.Text.isText(d))continue;const h=n.attributes,f=nt(e,...Object.keys(n.attributes));if(o===s||o===c){const e=o===s?a:0,t=o===c?l:d.text.length;if(t!==d.text.length&&r.push({type:"split_node",path:u,position:t,properties:ct(d)}),0!==e){r.push({type:"split_node",path:u,position:e,properties:rt(Xe(Xe({},ct(d)),h))});continue}}r.push({type:"set_node",newProperties:h,path:u,properties:f})}}if("retain"in n&&(o-=n.retain),"delete"in n){const[s,a]=gt(e,o-n.delete),[c,l]=gt(e,o,{assoc:-1});for(let n=0===l?c-1:c;n>=s;n--){const d=e.children[n],u=[...t,n];if(i.Text.isText(d)&&(n===s||n===c)){const e=n===s?a:0,t=n===c?l:d.text.length;r.push({type:"remove_text",offset:e,text:d.text.slice(e,t),path:u}),o-=t-e;continue}r.push({type:"remove_node",node:d,path:u}),o-=ft(d)}return}if("insert"in n){const[a,c]=gt(e,o,{insert:!0}),l=e.children[a],d=[...t,a];if(i.Text.isText(l)){const e=r[r.length-1],t=null!=e&&"insert_node"===e.type?e.node:ct(l);let o=[];if(null==e||"insert_node"!==e.type&&"insert_text"!==e.type&&"split_node"!==e.type&&"set_node"!==e.type||(o=e.path),"string"==typeof n.insert&&tt(null!=(s=n.attributes)?s:{},t)&&i.Path.equals(d,o))return r.push({type:"insert_text",offset:c,text:n.insert,path:d});const a=dt(n);return 0===c?r.push({type:"insert_node",path:d,node:a}):(c<l.text.length&&r.push({type:"split_node",path:d,position:c,properties:ct(l)}),r.push({type:"insert_node",path:i.Path.next(d),node:a}))}return r.push({type:"insert_node",path:d,node:dt(n)})}}),r}(d,l,s)),c}function bt(e,t,n){i.Editor.withoutNormalizing(t,()=>{n.forEach(n=>{(function(e,t,n){if(n instanceof a.YTextEvent)return yt(e,t,n);throw new Error("Unexpected Y event type")})(e,t,n).forEach(e=>{t.apply(e)})})})}function wt(e){return e.map(e=>"string"==typeof e.insert?e:Qe(Xe({},e),{insert:vt(e.insert)}))}function vt(e){const t=new a.YXmlText,n=e.getAttributes();return Object.entries(n).forEach(([e,n])=>{t.setAttribute(e,n)}),t.applyDelta(wt(it(e)),{sanitize:!1}),t}function _t(e){if(!e.doc)throw new Error("shared type isn't attached to a document")}var St="__slateYjsStoredPosition_";function Et(e,t,n){const{yTarget:r,yParent:i,textRange:o}=pt(e,t,n.path);if(r)throw new Error("Slate point points to a non-text element inside sharedRoot");const s=o.start+n.offset;return a.createRelativePositionFromTypeIndex(i,s,s===o.end?-1:0)}function Ct(e,t,n){if(!e.doc)throw new Error("sharedRoot isn't attach to a yDoc");const r=a.createAbsolutePositionFromRelativePosition(n,e.doc);return r&&function(e,t,{type:n,index:r,assoc:o}){if(!(n instanceof a.YXmlText))throw new Error("Absolute position points to a non-XMLText");const s=mt(e,t,n),c=i.Node.get(t,s);if(i.Text.isText(c))throw new Error("Absolute position doesn't match slateRoot, cannot descent into text");const[l,d]=gt(c,r,{assoc:o}),u=c.children[l];return i.Text.isText(u)?{path:[...s,l],offset:d}:null}(e,t,r)}function kt(e,t,n){e.setAttribute(St+t,a.encodeRelativePosition(n))}function Tt(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 xt(e,t,n=""){const r={[n]:Tt(e,t)};return it(t).forEach(({insert:t},i)=>{t instanceof a.YXmlText&&Object.assign(r,xt(e,t,n?`${n}.${i}`:i.toString()))}),r}function Rt(e,t,n,r=0){const i=function(e){return _t(e),Object.fromEntries(Object.entries(e.getAttributes()).filter(([e])=>e.startsWith(St)).map(([t,n])=>[t.slice(25),a.createAbsolutePositionFromRelativePosition(a.decodeRelativePosition(n),e.doc)]).filter(([,e])=>e))}(e),o={"":Tt(i,t,{start:r,end:r+st(n)})};return n.forEach(({insert:e},t)=>{e instanceof a.YXmlText&&Object.assign(o,xt(i,e,t.toString()))}),o}function At(e,t,n,r,i=0,o=0,s=""){const c=n[s];c&&Object.entries(c).forEach(([n,r])=>{kt(e,n,a.createRelativePositionFromTypeIndex(t,r.index-o+i,r.assoc))}),r.forEach(({insert:t},r)=>{t instanceof a.YXmlText&&At(e,t,n,it(t),0,0,s?`${s}.${r}`:r.toString())})}function Ot(e,t,n){return{anchor:Et(e,t,n.anchor),focus:Et(e,t,n.focus)}}function Dt(e,t,n){const r=Ct(e,t,n.anchor);if(!r)return null;const i=Ct(e,t,n.focus);return i?{anchor:r,focus:i}:null}var Pt={insert_node:function(e,t,n){const{yParent:r,textRange:o}=pt(e,t,n.path);if(i.Text.isText(n.node))return r.insert(o.start,n.node.text,ct(n.node));r.insertEmbed(o.start,ht(n.node))},remove_node:function(e,t,n){const{yParent:r,textRange:i}=pt(e,t,n.path);r.delete(i.start,i.end-i.start)},set_node:function(e,t,n){const{yTarget:r,textRange:i,yParent:o}=pt(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 s=Xe(Xe({},Object.fromEntries(Object.keys(n.properties).map(e=>[e,null]))),n.newProperties);o.format(i.start,i.end-i.start,s)},merge_node:function(e,t,n){const r=pt(e,t,n.path),o=pt(r.yParent,r.slateParent,i.Path.previous(n.path.slice(-1)));if(!r.yTarget!=!o.yTarget)throw new Error("Cannot merge y text with y element");if(!o.yTarget||!r.yTarget){const{yParent:e,textRange:o,slateTarget:s}=r;if(!s)throw new Error("Expected Slate target node for merge op.");const a=i.Node.get(t,i.Path.previous(n.path));if(!i.Text.isText(a))throw new Error("Path points to Y.Text but not a Slate text node.");const c=ct(s),l=ct(a),d=Object.keys(c).reduce((e,t)=>t in l?e:Qe(Xe({},e),{[t]:null}),{});return e.format(o.start,o.end-o.start,Xe(Xe({},d),l))}const s=o.yTarget.length,a=it(r.yTarget),c=wt(a),l=Rt(e,r.yTarget,a,s),d=[{retain:s},...c];o.yTarget.applyDelta(d,{sanitize:!1}),r.yParent.delete(r.textRange.start,r.textRange.end-r.textRange.start),At(e,o.yTarget,l,c,s)},move_node:function(e,t,n){const r=i.Path.parent(n.newPath),o=n.newPath[n.newPath.length-1],s=i.Node.get(t,r);if(i.Text.isText(s))throw new Error("Cannot move slate node into text element");const a=[...r,Math.min(o,s.children.length)],c=pt(e,t,n.path),l=pt(e,t,a),d=wt(c.targetDelta),u=Rt(e,c.yParent,c.targetDelta);c.yParent.delete(c.textRange.start,c.textRange.end-c.textRange.start);const h=st(it(l.yParent)),f=Math.min(l.textRange.start,h),p=[{retain:f},...d];l.yParent.applyDelta(p,{sanitize:!1}),At(e,l.yParent,u,d,f,c.textRange.start)},split_node:function(e,t,n){const r=pt(e,t,n.path);if(!r.slateTarget)throw new Error("Y target without corresponding slate node");if(!r.yTarget){if(!i.Text.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,Xe(Xe({},e),n.properties))}if(i.Text.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const o=pt(r.yTarget,r.slateTarget,[n.position]),s=r.slateTarget.children.slice(0,n.position).reduce((e,t)=>e+ft(t),0),c=r.slateTarget.children.reduce((e,t)=>e+ft(t),0),l=at(it(r.yTarget),s,c-s),d=wt(l),u=Rt(e,r.yTarget,l,s),h=new a.YXmlText;h.applyDelta(d,{sanitize:!1}),Object.entries(n.properties).forEach(([e,t])=>{h.setAttribute(e,t)}),r.yTarget.delete(o.textRange.start,r.yTarget.length-o.textRange.start),r.yParent.insertEmbed(r.textRange.end,h),At(e,h,u,d,0,s)}};var Nt=Qe(Xe(Xe({},{insert_text:function(e,t,n){const{yParent:r,textRange:o}=pt(e,t,n.path),s=i.Node.get(t,n.path);if(!i.Text.isText(s))throw new Error("Cannot insert text into non-text node");r.insert(o.start+n.offset,n.text,ct(s))},remove_text:function(e,t,n){const{yParent:r,textRange:i}=pt(e,t,n.path);r.delete(i.start+n.offset,n.text.length)}}),Pt),{set_selection:()=>{}});var Lt=Symbol("slate-yjs-operation"),Mt=Symbol("slate-yjs-position-storage"),Ut=new WeakMap,jt=new WeakMap,It=new WeakSet,Bt={isYjsEditor:e=>i.Editor.isEditor(e)&&e.sharedRoot instanceof a.YXmlText&&"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=jt.get(e))?t:[]},applyRemoteEvents(e,t,n){e.applyRemoteEvents(t,n)},storeLocalChange(e,t){e.storeLocalChange(t)},flushLocalChanges(e){e.flushLocalChanges()},connected:e=>It.has(e),connect(e){e.connect()},disconnect(e){e.disconnect()},isLocal:e=>e.isLocalOrigin(Bt.origin(e)),origin(e){const t=Ut.get(e);return void 0!==t?t:e.localOrigin},withOrigin(e,t,n){const r=Bt.origin(e);Ut.set(e,t),n(),Ut.set(e,r)},storePosition(e,t,n){const{sharedRoot:r,positionStorageOrigin:i}=e;_t(r);const o=Et(r,e,n);r.doc.transact(()=>{kt(r,t,o)},i)},removeStoredPosition(e,t){const{sharedRoot:n,positionStorageOrigin:r}=e;_t(n),n.doc.transact(()=>{!function(e,t){e.removeAttribute(St+t)}(n,t)},r)},position(e,t){const n=function(e,t){const n=e.getAttribute(St+t);return n?a.decodeRelativePosition(n):null}(e.sharedRoot,t);if(n)return Ct(e.sharedRoot,e,n)},storedPositionsRelative(e){return t=e.sharedRoot,Object.fromEntries(Object.entries(t.getAttributes()).filter(([e])=>e.startsWith(St)).map(([e,t])=>[e.slice(25),a.createRelativePositionFromJSON(t)]));var t}};function Ft(e,t,{localOrigin:n,positionStorageOrigin:r,autoConnect:o=!1}={}){const s=e;s.sharedRoot=t,s.localOrigin=null!=n?n:Lt,s.positionStorageOrigin=null!=r?r:Mt,s.applyRemoteEvents=(e,t)=>{Bt.flushLocalChanges(s),i.Editor.withoutNormalizing(s,()=>{Bt.withOrigin(s,t,()=>{bt(s.sharedRoot,s,e)})})},s.isLocalOrigin=e=>e===s.localOrigin;const a=(e,t)=>{s.isLocalOrigin(t.origin)||Bt.applyRemoteEvents(s,e,t.origin)};let c=null;o&&(c=setTimeout(()=>{c=null,Bt.connect(s)})),s.connect=()=>{if(Bt.connected(s))throw new Error("already connected");s.sharedRoot.observeDeep(a);const t=lt(s.sharedRoot);s.children=t.children,It.add(s),i.Editor.normalize(e,{force:!0}),e.operations.length||e.onChange()},s.disconnect=()=>{c&&clearTimeout(c),Bt.flushLocalChanges(s),s.sharedRoot.unobserveDeep(a),It.delete(s)},s.storeLocalChange=t=>{jt.set(s,[...Bt.localChanges(s),{op:t,doc:e.children,origin:Bt.origin(s)}])},s.flushLocalChanges=()=>{_t(s.sharedRoot);const e=Bt.localChanges(s);jt.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=>{_t(s.sharedRoot),s.sharedRoot.doc.transact(()=>{e.forEach(e=>{_t(s.sharedRoot),function(e,t,n){const r=Nt[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:l,onChange:d}=s;return s.apply=e=>{Bt.connected(s)&&Bt.isLocal(s)&&Bt.storeLocalChange(s,e),l(e)},s.onChange=()=>{Bt.connected(s)&&Bt.flushLocalChanges(s),d()},s}var Vt=new WeakMap,Wt=Symbol("slate-yjs-history-without-saving");var qt=new WeakMap,Yt={isCursorEditor:e=>Bt.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=qt.get(e))?r:new Set;i.add(n),qt.set(e,i)},off(e,t,n){if("change"!==t)return;const r=qt.get(e);r&&r.delete(n)},cursorState(e,t){var n;if(t===e.awareness.clientID||!Bt.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=>Bt.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 Ht=e=>a.create((t,n)=>{e.onerror=e=>n(new Error(e.target.error)),e.onsuccess=e=>t(e.target.result)}),Kt=(e,t,n="readwrite")=>{const r=e.transaction(t,n);return t.map(e=>Jt(r,e))},zt=(e,t)=>Ht(e.count(t)),$t=(e,t)=>Ht(e.delete(t)),Gt=(e,t)=>Ht(e.add(t)),Xt=(e,t=null)=>((e,t,n)=>{let r=null;return Qt(e,t,e=>(r=e,!1),n).then(()=>r)})(e,t,"prev"),Qt=(e,t,n,r="next")=>((e,t)=>a.create((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)),Jt=(e,t)=>e.objectStore(t),Zt="custom",en="updates",tn=(e,t=()=>{},n=()=>{})=>{const[r]=Kt(e.db,[en]);return(i=r,c=e._dbref,l=!1,o=IDBKeyRange.lowerBound(c,l),Ht(i.getAll(o,s))).then(i=>{e._destroyed||(t(r),a.transact(e.doc,()=>{i.forEach(t=>a.applyUpdate(e.doc,t))},e,!1),n(r))}).then(()=>Xt(r).then(t=>{e._dbref=t+1})).then(()=>zt(r).then(t=>{e._dbsize=t})).then(()=>r);var i,o,s,c,l},nn=(e,t=!0)=>tn(e).then(n=>{(t||e._dbsize>=500)&&Gt(n,a.encodeStateAsUpdate(e.doc)).then(()=>{return $t(n,(t=e._dbref,r=!0,IDBKeyRange.upperBound(t,r)));var t,r}).then(()=>zt(n).then(t=>{e._dbsize=t}))}),rn=class extends a.Observable{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)=>a.create((n,r)=>{const i=indexedDB.open(e);i.onupgradeneeded=e=>t(e.target.result),i.onerror=e=>r(a.create$1(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=a.create(e=>this.on("synced",()=>e(this))),this._db.then(e=>{this.db=e;tn(this,e=>Gt(e,a.encodeStateAsUpdate(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]=Kt(this.db,[en]);Gt(t,e),++this._dbsize>=500&&(null!==this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{nn(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,Ht(indexedDB.deleteDatabase(e))})}get(e){return this._db.then(t=>{const[n]=Kt(t,[Zt],"readonly");return((e,t)=>Ht(e.get(t)))(n,e)})}set(e,t){return this._db.then(n=>{const[r]=Kt(n,[Zt]);return((e,t,n)=>Ht(e.put(t,n)))(r,t,e)})}del(e){return this._db.then(t=>{const[n]=Kt(t,[Zt]);return $t(n,e)})}},on=3e4,sn=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=a.getUnixTime();const n=t.data,i="string"==typeof n?JSON.parse(n):n;i&&"pong"===i.type&&(clearTimeout(r),r=setTimeout(o,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(sn,a.min(1200*a.log10(e.unsuccessfulReconnects+1),2500),e)),clearTimeout(r)},o=()=>{e.ws===t&&e.send({type:"ping"})};t.onclose=()=>i(null),t.onerror=e=>i(e),t.onopen=()=>{e.lastMessageReceived=a.getUnixTime(),e.connecting=!1,e.connected=!0,e.unsuccessfulReconnects=0,e.emit("connect",[{type:"connect"},e]),r=setTimeout(o,15e3)}}},an=class extends a.Observable{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&&on<a.getUnixTime()-this.lastMessageReceived&&this.ws.close()},15e3),sn(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||sn(this)}},cn=new Map,ln="undefined"==typeof BroadcastChannel?class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.key===e&&null!==this.onmessage&&this.onmessage({data:a.fromBase64(t.newValue||"")}),a.onChange(this._onChange)}postMessage(e){a.varStorage.setItem(this.room,a.toBase64(a.createUint8ArrayFromArrayBuffer(e)))}close(){a.offChange(this._onChange)}}:BroadcastChannel,dn=e=>a.setIfUndefined(cn,e,()=>{const t=a.create$2(),n=new ln(e);return n.onmessage=e=>t.forEach(t=>t(e.data,"broadcastchannel")),{bc:n,subs:t}}),un=e.__commonJSMin((e,t)=>{!function(n){if("object"==typeof e&&void 0!==t)t.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{("undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window).SimplePeer=n()}}(function(){var e=Math.floor,t=Math.abs,n=Math.pow;return function e(t,n,r){function i(s,a){if(!n[s]){if(!t[s]){var c="function"==typeof require&&require;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var d=n[s]={exports:{}};t[s][0].call(d.exports,function(e){return i(t[s][1][e]||e)},d,d.exports,e,t,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t,n){"use strict";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 s[63&e>>18]+s[63&e>>12]+s[63&e>>6]+s[63&e]}function o(e,t,n){for(var r,o=[],s=t;s<n;s+=3)r=(16711680&e[s]<<16)+(65280&e[s+1]<<8)+(255&e[s+2]),o.push(i(r));return o.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),o=i[0],s=i[1],l=new c(function(e,t,n){return 3*(t+n)/4-n}(0,o,s)),d=0,u=0<s?o-4:o;for(n=0;n<u;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[d++]=255&t>>16,l[d++]=255&t>>8,l[d++]=255&t;return 2===s&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,l[d++]=255&t),1===s&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[e.charCodeAt(n+2)]>>2,l[d++]=255&t>>8,l[d++]=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(o(e,c,c+a>l?l:c+a));return 1===r?(t=e[n-1],i.push(s[t>>2]+s[63&t<<4]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(s[t>>10]+s[63&t>>4]+s[63&t<<2]+"=")),i.join("")};for(var s=[],a=[],c="undefined"==typeof Uint8Array?Array:Uint8Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0;d<64;++d)s[d]=l[d],a[l.charCodeAt(d)]=d;a[45]=62,a[95]=63},{}],2:[function(){},{}],3:[function(e,t,r){(function(){(function(){"use strict";var t=String.fromCharCode,i=Math.min;function o(e){if(2147483647<e)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(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"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|h(e,t),r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}(e,t);if(ArrayBuffer.isView(e))return d(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(B(e,ArrayBuffer)||e&&B(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;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),r.__proto__=s.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 s.from(r,t,n);var i=function(e){if(s.isBuffer(e)){var t=0|u(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0===e.length?"Buffer"===e.type&&Array.isArray(e.data)?d(e.data):void 0:"number"!=typeof e.length||F(e.length)?o(0):d(e)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.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),o(0>e?0:0|u(e))}function d(e){for(var t=0>e.length?0:0|u(e.length),n=o(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function u(e){if(e>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647..toString(16)+" bytes");return 0|e}function h(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||B(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 U(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return j(e).length;default:if(i)return r?-1:U(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 R(this,t,n);case"utf8":case"utf-8":return C(this,t,n);case"ascii":return T(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return E(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function p(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function g(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),F(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=s.from(t,r)),s.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 o(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var s,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 d=-1;for(s=n;s<c;s++)if(o(e,s)!==o(t,-1===d?0:s-d))-1!==d&&(s-=s-d),d=-1;else if(-1===d&&(d=s),s-d+1===l)return d*a}else for(n+l>c&&(n=c-l),s=n;0<=s;s--){for(var u=!0,h=0;h<l;h++)if(o(e,s+h)!==o(t,h)){u=!1;break}if(u)return s}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 o=t.length;r>o/2&&(r=o/2);for(var s,a=0;a<r;++a){if(F(s=parseInt(t.substr(2*a,2),16)))return a;e[n+a]=s}return a}function b(e,t,n,r){return I(U(t,e.length-n),e,n,r)}function w(e,t,n,r){return I(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 I(j(t),e,n,r)}function S(e,t,n,r){return I(function(e,t){for(var n,r,i,o=[],s=0;s<e.length&&!(0>(t-=2));++s)n=e.charCodeAt(s),r=n>>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function E(e,t,n){return 0===t&&n===e.length?V.fromByteArray(e):V.fromByteArray(e.slice(t,n))}function C(e,t,n){n=i(e.length,n);for(var r=[],o=t;o<n;){var s,a,c,l,d=e[o],u=null,h=239<d?4:223<d?3:191<d?2:1;if(o+h<=n)1===h?128>d&&(u=d):2===h?128==(192&(s=e[o+1]))&&(127<(l=(31&d)<<6|63&s)&&(u=l)):3===h?(s=e[o+1],a=e[o+2],128==(192&s)&&128==(192&a)&&(2047<(l=(15&d)<<12|(63&s)<<6|63&a)&&(55296>l||57343<l)&&(u=l))):4===h&&(s=e[o+1],a=e[o+2],c=e[o+3],128==(192&s)&&128==(192&a)&&128==(192&c)&&(65535<(l=(15&d)<<18|(63&s)<<12|(63&a)<<6|63&c)&&1114112>l&&(u=l)));null===u?(u=65533,h=1):65535<u&&(u-=65536,r.push(55296|1023&u>>>10),u=56320|1023&u),r.push(u),o+=h}return k(r)}function k(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 T(e,n,r){var o="";r=i(e.length,r);for(var s=n;s<r;++s)o+=t(127&e[s]);return o}function x(e,n,r){var o="";r=i(e.length,r);for(var s=n;s<r;++s)o+=t(e[s]);return o}function R(e,t,n){var r=e.length;(!t||0>t)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var i="",o=t;o<n;++o)i+=M(e[o]);return i}function A(e,n,r){for(var i=e.slice(n,r),o="",s=0;s<i.length;s+=2)o+=t(i[s]+256*i[s+1]);return o}function O(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 D(e,t,n,r,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)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 N(e,t,n,r,i){return t=+t,n>>>=0,i||P(e,0,n,4),W.write(e,t,n,r,23,4),n+4}function L(e,t,n,r,i){return t=+t,n>>>=0,i||P(e,0,n,8),W.write(e,t,n,r,52,8),n+8}function M(e){return 16>e?"0"+e.toString(16):e.toString(16)}function U(e,t){t=t||1/0;for(var n,r=e.length,i=null,o=[],s=0;s<r;++s){if(55295<(n=e.charCodeAt(s))&&57344>n){if(!i){if(56319<n){-1<(t-=3)&&o.push(239,191,189);continue}if(s+1===r){-1<(t-=3)&&o.push(239,191,189);continue}i=n;continue}if(56320>n){-1<(t-=3)&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&-1<(t-=3)&&o.push(239,191,189);if(i=null,128>n){if(0>(t-=1))break;o.push(n)}else if(2048>n){if(0>(t-=2))break;o.push(192|n>>6,128|63&n)}else if(65536>n){if(0>(t-=3))break;o.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;o.push(240|n>>18,128|63&n>>12,128|63&n>>6,128|63&n)}}return o}function j(e){return V.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 I(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 B(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function F(e){return e!=e}var V=e("base64-js"),W=e("ieee754");r.Buffer=s,r.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},r.INSPECT_MAX_BYTES=50,r.kMaxLength=2147483647,s.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),s.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){return s.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){return s.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&s[Symbol.species]===s&&Object.defineProperty(s,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,n){return function(e,t,n){return c(e),0>=e||void 0===t?o(e):"string"==typeof n?o(e).fill(t,n):o(e).fill(t)}(e,t,n)},s.allocUnsafe=function(e){return l(e)},s.allocUnsafeSlow=function(e){return l(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(B(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),B(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.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,o=0,a=i(n,r);o<a;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},s.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}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=s.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var o=e[n];if(B(o,Uint8Array)&&(o=s.from(o)),!s.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(r,i),i+=o.length}return r},s.byteLength=h,s.prototype._isBuffer=!0,s.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)p(this,t,t+1);return this},s.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)p(this,t,t+3),p(this,t+1,t+2);return this},s.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)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?C(this,0,e):f.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},s.prototype.compare=function(e,t,n,r,o){if(B(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.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===o&&(o=this.length),0>t||n>e.length||0>r||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(o>>>=0)-(r>>>=0),c=(n>>>=0)-(t>>>=0),l=i(a,c),d=this.slice(r,o),u=e.slice(t,n),h=0;h<l;++h)if(d[h]!==u[h]){a=d[h],c=u[h];break}return a<c?-1:c<a?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return g(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return g(this,e,t,n,!1)},s.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 o=!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 S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},s.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__=s.prototype,r},s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);for(var r=this[e],i=1,o=0;++o<t&&(i*=256);)r+=this[e+o]*i;return r},s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);for(var r=this[e+--t],i=1;0<t&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||O(e,t,this.length);for(var i=this[e],o=1,s=0;++s<t&&(o*=256);)i+=this[e+s]*o;return i>=(o*=128)&&(i-=n(2,8*t)),i},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||O(e,t,this.length);for(var i=t,o=1,s=this[e+--i];0<i&&(o*=256);)s+=this[e+--i]*o;return s>=(o*=128)&&(s-=n(2,8*t)),s},s.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||O(e,4,this.length),W.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),W.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),W.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),W.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t>>>=0,r>>>=0,i)||D(this,e,t,r,n(2,8*r)-1,0);var o=1,s=0;for(this[t]=255&e;++s<r&&(o*=256);)this[t+s]=255&e/o;return t+r},s.prototype.writeUIntBE=function(e,t,r,i){(e=+e,t>>>=0,r>>>=0,i)||D(this,e,t,r,n(2,8*r)-1,0);var o=r-1,s=1;for(this[t+o]=255&e;0<=--o&&(s*=256);)this[t+o]=255&e/s;return t+r},s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||D(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},s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||D(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},s.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var o=n(2,8*r-1);D(this,e,t,r,o-1,-o)}var s=0,a=1,c=0;for(this[t]=255&e;++s<r&&(a*=256);)0>e&&0===c&&0!==this[t+s-1]&&(c=1),this[t+s]=255&(e/a|0)-c;return t+r},s.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var o=n(2,8*r-1);D(this,e,t,r,o-1,-o)}var s=r-1,a=1,c=0;for(this[t+s]=255&e;0<=--s&&(a*=256);)0>e&&0===c&&0!==this[t+s+1]&&(c=1),this[t+s]=255&(e/a|0)-c;return t+r},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||D(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},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||D(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},s.prototype.writeFloatLE=function(e,t,n){return N(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return N(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.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 o=i-1;0<=o;--o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return i},s.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&&!s.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 o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{var a=s.isBuffer(e)?e:s.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=a[o%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,n){n.exports=function(n){function r(e){function t(...e){if(!t.enabled)return;const i=t,o=+new Date;i.diff=o-(n||o),i.prev=n,i.curr=o,n=o,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,n)=>{if("%%"===t)return"%";s++;const o=r.formatters[n];if("function"==typeof o){const n=e[s];t=o.call(i,n),e.splice(s,1),s--}return t}),r.formatArgs.call(i,e),(i.log||r.log).apply(i,e)}let n,o=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===o?r.enabled(e):o,set:e=>{o=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 o(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(o),...r.skips.map(o).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(n).forEach(e=>{r[e]=n[e]}),r.names=[],r.skips=[],r.formatters={},r.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return r.colors[t(n)%r.colors.length]},r.enable(r.load()),r}},{ms:11}],6:[function(e,t){"use strict";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){"use strict";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 o(e,t,n,o){var s,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]=o?[n,c]:[c,n]:o?c.unshift(n):c.push(n),0<(s=i(e))&&c.length>s&&!c.warned){c.warned=!0;var l=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 s(){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=s.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):d(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 d(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function u(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(o){r.once&&e.removeEventListener(t,i),n(o)})}}var h,f="object"==typeof Reflect?Reflect:null,p=f&&"function"==typeof f.apply?f.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};h=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 g=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,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}u(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&u(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||g(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||g(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 o;if(0<t.length&&(o=t[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)p(a,this,t);else{var c=a.length,l=d(a,c);for(n=0;n<c;++n)p(l[n],this,t)}return!0},n.prototype.addListener=function(e,t){return o(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return o(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,o,s,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(o=-1,s=n.length-1;0<=s;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,o=s;break}if(0>o)return this;0===o?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,o),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;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;0<=r;r--)this.removeListener(e,t[r]);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?h(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(r,i,o){o.read=function(e,t,r,i,o){var s,a,c=8*o-i-1,l=(1<<c)-1,d=l>>1,u=-7,h=r?o-1:0,f=r?-1:1,p=e[t+h];for(h+=f,s=p&(1<<-u)-1,p>>=-u,u+=c;0<u;s=256*s+e[t+h],h+=f,u-=8);for(a=s&(1<<-u)-1,s>>=-u,u+=i;0<u;a=256*a+e[t+h],h+=f,u-=8);if(0===s)s=1-d;else{if(s===l)return a?NaN:1/0*(p?-1:1);a+=n(2,i),s-=d}return(p?-1:1)*a*n(2,s-i)},o.write=function(r,i,o,s,a,c){var l,d,u,h=Math.LN2,f=Math.log,p=8*c-a-1,g=(1<<p)-1,m=g>>1,y=23===a?n(2,-24)-n(2,-77):0,b=s?0:c-1,w=s?1:-1,v=0>i||0===i&&0>1/i?1:0;for(i=t(i),isNaN(i)||i===1/0?(d=isNaN(i)?1:0,l=g):(l=e(f(i)/h),1>i*(u=n(2,-l))&&(l--,u*=2),2<=(i+=1<=l+m?y/u:y*n(2,1-m))*u&&(l++,u/=2),l+m>=g?(d=0,l=g):1<=l+m?(d=(i*u-1)*n(2,a),l+=m):(d=i*n(2,m-1)*n(2,a),l=0));8<=a;r[o+b]=255&d,b+=w,d/=256,a-=8);for(l=l<<a|d,p+=a;0<p;r[o+b]=255&l,b+=w,l/=256,p-=8);r[o+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,n){var r=Math.round;function i(e){var n=t(e);return 864e5<=n?r(e/864e5)+"d":36e5<=n?r(e/36e5)+"h":6e4<=n?r(e/6e4)+"m":1e3<=n?r(e/1e3)+"s":e+"ms"}function o(e){var n=t(e);return 864e5<=n?s(e,n,864e5,"day"):36e5<=n?s(e,n,36e5,"hour"):6e4<=n?s(e,n,6e4,"minute"):1e3<=n?s(e,n,1e3,"second"):e+" ms"}function s(e,t,n,i){return r(e/n)+" "+i+(t>=1.5*n?"s":"")}n.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?o(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 o(){p&&h&&(p=!1,h.length?f=h.concat(f):g=-1,f.length&&s())}function s(){if(!p){var e=i(o);p=!0;for(var t=f.length;t;){for(h=f,f=[];++g<t;)h&&h[g].run();g=-1,t=f.length}h=null,p=!1,function(e){if(d===clearTimeout)return clearTimeout(e);if((d===r||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(n){try{return d.call(null,e)}catch(n){return d.call(this,e)}}}(e)}}function a(e,t){this.fun=e,this.array=t}function c(){}var l,d,u=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{d="function"==typeof clearTimeout?clearTimeout:r}catch(t){d=r}}();var h,f=[],p=!1,g=-1;u.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||p||i(s)},a.prototype.run=function(){this.fun.apply(null,this.array)},u.title="browser",u.browser=!0,u.env={},u.argv=[],u.version="",u.versions={},u.on=c,u.addListener=c,u.once=c,u.off=c,u.removeListener=c,u.removeAllListeners=c,u.emit=c,u.prependListener=c,u.prependOnceListener=c,u.listeners=function(){return[]},u.binding=function(){throw new Error("process.binding is not supported")},u.cwd=function(){return"/"},u.chdir=function(){throw new Error("process.chdir is not supported")},u.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(){"use strict";var i=e("safe-buffer").Buffer,o=r.crypto||r.msCrypto;t.exports=o&&o.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 s=0;s<e;s+=65536)o.getRandomValues(r.slice(s,s+65536));else o.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){"use strict";function n(e,t,n){function r(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var o=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);o.prototype.name=n.name,o.prototype.code=e,i[e]=o}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,o;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"))o="The ".concat(e," ").concat(i," ").concat(r(t,"type"));else{var s=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}(e,".")?"property":"argument";o='The "'.concat(e,'" ').concat(s," ").concat(i," ").concat(r(t,"type"))}return o+=". 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(){"use strict";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(o,this)}function o(e){e.end()}var s=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,d=s(c.prototype),u=0;u<d.length;u++)l=d[u],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){"use strict";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(){"use strict";function i(t,n,r){S=S||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof S),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=L(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&&(!A&&(A=e("string_decoder/").StringDecoder),this.decoder=new A(t.encoding),this.encoding=t.encoding)}function o(t){if(S=S||e("./_stream_duplex"),!(this instanceof o))return new o(t);var n=this instanceof S;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)),k.call(this)}function s(e,t,n,r,i){E("readableAddChunk",t);var o,s=e._readableState;if(null===t)s.reading=!1,function(e,t){if(E("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?d(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,u(e)))}}(e,s);else if(i||(o=c(s,t)),o)F(e,o);else if(s.objectMode||t&&0<t.length)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===T.prototype||(t=function(e){return T.from(e)}(t)),r)s.endEmitted?F(e,new B):a(e,s,t,!0);else if(s.ended)F(e,new j);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?a(e,s,t,!1):h(e,s)):a(e,s,t,!1)}else r||(s.reading=!1,h(e,s));return!s.ended&&(s.length<s.highWaterMark||0===s.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&&d(e)),h(e,t)}function c(e,t){var n;return function(e){return T.isBuffer(e)||e instanceof x}(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new U("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 d(e){var t=e._readableState;E("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(E("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(u,e))}function u(e){var t=e._readableState;E("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 h(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(E("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function p(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 g(e){E("readable nexttick read 0"),e.read(0)}function m(e,t){E("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(E("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;E("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(v,t,e))}function v(e,t){if(E("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 S,E;t.exports=o,o.ReadableState=i,e("events").EventEmitter;var C=function(e,t){return e.listeners(t).length},k=e("./internal/streams/stream"),T=e("buffer").Buffer,x=r.Uint8Array||function(){},R=e("util");E=R&&R.debuglog?R.debuglog("stream"):function(){};var A,O,D,P=e("./internal/streams/buffer_list"),N=e("./internal/streams/destroy"),L=e("./internal/streams/state").getHighWaterMark,M=e("../errors").codes,U=M.ERR_INVALID_ARG_TYPE,j=M.ERR_STREAM_PUSH_AFTER_EOF,I=M.ERR_METHOD_NOT_IMPLEMENTED,B=M.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(o,k);var F=N.errorOrDestroy,V=["error","close","destroy","pause","resume"];Object.defineProperty(o.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),o.prototype.destroy=N.destroy,o.prototype._undestroy=N.undestroy,o.prototype._destroy=function(e,t){t(e)},o.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=T.from(e,t),t=""),n=!0),s(this,e,t,!1,n)},o.prototype.unshift=function(e){return s(this,e,null,!0,!1)},o.prototype.isPaused=function(){return!1===this._readableState.flowing},o.prototype.setEncoding=function(t){A||(A=e("string_decoder/").StringDecoder);var n=new A(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},o.prototype.read=function(e){E("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 E("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?w(this):d(this),null;if(0===(e=l(e,t))&&t.ended)return 0===t.length&&w(this),null;var r,i=t.needReadable;return E("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&E("length less than watermark",i=!0),t.ended||t.reading?E("reading or ended",i=!1):i&&(E("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))),null===(r=0<e?b(e,t):null)?(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!==r&&this.emit("data",r),r},o.prototype._read=function(){F(this,new I("_read()"))},o.prototype.pipe=function(e,t){function r(e,t){E("onunpipe"),e===u&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,o())}function i(){E("onend"),e.end()}function o(){E("cleanup"),e.removeListener("close",c),e.removeListener("finish",l),e.removeListener("drain",p),e.removeListener("error",a),e.removeListener("unpipe",r),u.removeListener("end",i),u.removeListener("end",d),u.removeListener("data",s),g=!0,h.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&p()}function s(t){E("ondata");var n=e.write(t);E("dest.write",n),!1===n&&((1===h.pipesCount&&h.pipes===e||1<h.pipesCount&&-1!==_(h.pipes,e))&&!g&&(E("false write response, pause",h.awaitDrain),h.awaitDrain++),u.pause())}function a(t){E("onerror",t),d(),e.removeListener("error",a),0===C(e,"error")&&F(e,t)}function c(){e.removeListener("finish",l),d()}function l(){E("onfinish"),e.removeListener("close",c),d()}function d(){E("unpipe"),u.unpipe(e)}var u=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,E("pipe count=%d opts=%j",h.pipesCount,t);var f=t&&!1===t.end||e===n.stdout||e===n.stderr?d:i;h.endEmitted?n.nextTick(f):u.once("end",f),e.on("unpipe",r);var p=function(e){return function(){var t=e._readableState;E("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&C(e,"data")&&(t.flowing=!0,y(e))}}(u);e.on("drain",p);var g=!1;return u.on("data",s),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",u),h.flowing||(E("pipe resume"),u.resume()),e},o.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 o=0;o<i;o++)r[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=_(t.pipes,e);return-1===s||(t.pipes.splice(s,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},o.prototype.on=function(e,t){var r=k.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,E("on readable",i.length,i.reading),i.length?d(this):!i.reading&&n.nextTick(g,this)),r},o.prototype.addListener=o.prototype.on,o.prototype.removeListener=function(e,t){var r=k.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(p,this),r},o.prototype.removeAllListeners=function(e){var t=k.prototype.removeAllListeners.apply(this,arguments);return("readable"===e||void 0===e)&&n.nextTick(p,this),t},o.prototype.resume=function(){var e=this._readableState;return e.flowing||(E("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(m,e,t))}(this,e)),e.paused=!1,this},o.prototype.pause=function(){return E("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(E("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},o.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on("end",function(){if(E("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){E("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 o=0;o<V.length;o++)e.on(V[o],this.emit.bind(this,V[o]));return this._read=function(t){E("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(o.prototype[Symbol.asyncIterator]=function(){return void 0===O&&(O=e("./internal/streams/async_iterator")),O(this)}),Object.defineProperty(o.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(o.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(o.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),o._fromList=b,Object.defineProperty(o.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(o.from=function(t,n){return void 0===D&&(D=e("./internal/streams/from")),D(o,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){"use strict";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?(u.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?o(this,null,null):this._flush(function(t,n){o(e,t,n)})}function o(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new d;if(e._transformState.transforming)throw new l;return e.push(null)}t.exports=r;var s=e("../errors").codes,a=s.ERR_METHOD_NOT_IMPLEMENTED,c=s.ERR_MULTIPLE_CALLBACK,l=s.ERR_TRANSFORM_ALREADY_TRANSFORMING,d=s.ERR_TRANSFORM_WITH_LENGTH_0,u=e("./_stream_duplex");e("inherits")(r,u),r.prototype.push=function(e,t){return this._transformState.needTransform=!1,u.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){u.prototype._destroy.call(this,e,function(e){t(e)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(e,t){(function(n,r){(function(){"use strict";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 o(){}function s(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=x(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){h(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 s(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 E.call(this)):new a(t)}function c(e,t){var r=new M;j(e,r),n.nextTick(t,r)}function l(e,t,r,i){var o;return null===r?o=new L:"string"!=typeof r&&!t.objectMode&&(o=new A("chunk",["string","Buffer"],r)),!o||(j(e,o),n.nextTick(i,o),!1)}function d(e,t,n,r,i,o){if(!n){var s=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=C.from(t,n)),t}(t,r,i);r!==s&&(n=!0,i="buffer",r=s)}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:o,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else u(e,t,!1,a,r,i,o);return c}function u(e,t,n,r,i,o,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new N("write")):n?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function h(e,t){var r=e._writableState,i=r.sync,o=r.writecb;if("function"!=typeof o)throw new D;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,i,o){--t.pendingcb,r?(n.nextTick(o,i),n.nextTick(b,e,t),e._writableState.errorEmitted=!0,j(e,i)):(o(i),e._writableState.errorEmitted=!0,j(e,i),b(e,t))}(e,r,i,t,o);else{var s=g(r)||e.destroyed;s||r.corked||r.bufferProcessing||!r.bufferedRequest||p(e,r),i?n.nextTick(f,e,r,s,o):f(e,r,s,o)}}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 p(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,o=Array(r),s=t.corkedRequestsFree;s.entry=n;for(var a=0,c=!0;n;)o[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;o.allBuffers=c,u(e,t,!0,t.length,o,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new i(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,h=n.callback;if(u(e,t,!1,t.objectMode?1:l.length,l,d,h),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function g(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&&j(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=g(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=s;var _,S={deprecate:e("util-deprecate")},E=e("./internal/streams/stream"),C=e("buffer").Buffer,k=r.Uint8Array||function(){},T=e("./internal/streams/destroy"),x=e("./internal/streams/state").getHighWaterMark,R=e("../errors").codes,A=R.ERR_INVALID_ARG_TYPE,O=R.ERR_METHOD_NOT_IMPLEMENTED,D=R.ERR_MULTIPLE_CALLBACK,P=R.ERR_STREAM_CANNOT_PIPE,N=R.ERR_STREAM_DESTROYED,L=R.ERR_STREAM_NULL_VALUES,M=R.ERR_STREAM_WRITE_AFTER_END,U=R.ERR_UNKNOWN_ENCODING,j=T.errorOrDestroy;e("inherits")(a,E),s.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(s.prototype,"buffer",{get:S.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 s}})):_=function(e){return e instanceof this},a.prototype.pipe=function(){j(this,new P)},a.prototype.write=function(e,t,n){var r=this._writableState,i=!1,s=!r.objectMode&&function(e){return C.isBuffer(e)||e instanceof k}(e);return s&&!C.isBuffer(e)&&(e=function(e){return C.from(e)}(e)),"function"==typeof t&&(n=t,t=null),s?t="buffer":!t&&(t=r.defaultEncoding),"function"!=typeof n&&(n=o),r.ending?c(this,n):(s||l(this,r,e,n))&&(r.pendingcb++,i=d(this,r,s,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&&p(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 U(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 O("_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=T.destroy,a.prototype._undestroy=T.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(){"use strict";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 o(e){var t=e[l];if(null!==t){var n=e[g].read();null!==n&&(e[f]=null,e[l]=null,e[d]=null,t(i(n,!1)))}}function s(e){n.nextTick(o,e)}var a,c=e("./end-of-stream"),l=Symbol("lastResolve"),d=Symbol("lastReject"),u=Symbol("error"),h=Symbol("ended"),f=Symbol("lastPromise"),p=Symbol("handlePromise"),g=Symbol("stream"),m=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((a={get stream(){return this[g]},next:function(){var e=this,t=this[u];if(null!==t)return Promise.reject(t);if(this[h])return Promise.resolve(i(void 0,!0));if(this[g].destroyed)return new Promise(function(t,r){n.nextTick(function(){e[u]?r(e[u]):t(i(void 0,!0))})});var r,o=this[f];if(o)r=new Promise(function(e,t){return function(n,r){e.then(function(){t[h]?n(i(void 0,!0)):t[p](n,r)},r)}}(o,this));else{var s=this[g].read();if(null!==s)return Promise.resolve(i(s,!1));r=new Promise(this[p])}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[g].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={},g,{value:e,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,d,{value:null,writable:!0}),r(t,u,{value:null,writable:!0}),r(t,h,{value:e._readableState.endEmitted,writable:!0}),r(t,p,{value:function(e,t){var r=n[g].read();r?(n[f]=null,n[l]=null,n[d]=null,e(i(r,!1))):(n[l]=e,n[d]=t)},writable:!0}),t));return n[f]=null,c(e,function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[d];return null!==t&&(n[f]=null,n[l]=null,n[d]=null,t(e)),void(n[u]=e)}var r=n[l];null!==r&&(n[f]=null,n[l]=null,n[d]=null,r(i(void 0,!0))),n[h]=!0}),e.on("readable",s.bind(null,n)),n}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":24,_process:12}],22:[function(e,t){"use strict";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 o(e,t,n){s.prototype.copy.call(e,t,n)}var s=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 s.alloc(0);for(var t=s.allocUnsafe(e>>>0),n=this.head,r=0;n;)o(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,o=e>i.length?i.length:e;if(r+=o===i.length?i:i.slice(0,e),0===(e-=o)){o===i.length?(++n,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=i.slice(o));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=s.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0===(e-=o)){o===i.length?(++r,this.head=n.next?n.next:this.tail=null):(this.head=n,n.data=i.slice(o));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(){"use strict";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,o){var s=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(o?o(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){!o&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(r,s):(s._writableState.errorEmitted=!0,e.nextTick(n,s,t)):e.nextTick(n,s,t):o?(e.nextTick(r,s),o(t)):e.nextTick(r,s)}),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){"use strict";function n(){}var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;t.exports=function e(t,i,o){if("function"==typeof i)return e(t,null,i);i||(i={}),o=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)}}}(o||n);var s=i.readable||!1!==i.readable&&t.readable,a=i.writable||!1!==i.writable&&t.writable,c=function(){t.writable||d()},l=t._writableState&&t._writableState.finished,d=function(){a=!1,l=!0,s||o.call(t)},u=t._readableState&&t._readableState.endEmitted,h=function(){s=!1,u=!0,a||o.call(t)},f=function(e){o.call(t,e)},p=function(){var e;return s&&!u?(t._readableState&&t._readableState.ended||(e=new r),o.call(t,e)):a&&!l?(t._writableState&&t._writableState.ended||(e=new r),o.call(t,e)):void 0},g=function(){t.req.on("finish",d)};return function(e){return e.setHeader&&"function"==typeof e.abort}(t)?(t.on("complete",d),t.on("abort",p),t.req?g():t.on("request",g)):a&&!t._writableState&&(t.on("end",c),t.on("close",c)),t.on("end",h),t.on("finish",d),!1!==i.error&&t.on("error",f),t.on("close",p),function(){t.removeListener("complete",d),t.removeListener("abort",p),t.removeListener("request",g),t.req&&t.req.removeListener("finish",d),t.removeListener("end",c),t.removeListener("close",c),t.removeListener("finish",d),t.removeListener("end",h),t.removeListener("error",f),t.removeListener("close",p)}}},{"../../../errors":15}],25:[function(e,t){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(e,t){"use strict";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 o=!1;t.on("close",function(){o=!0}),void 0===a&&(a=e("./end-of-stream")),a(t,{readable:n,writable:r},function(e){return e?i(e):(o=!0,void i())});var s=!1;return function(e){if(!o)return s?void 0:(s=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void i(e||new d("pipe")))}}function i(e){e()}function o(e,t){return e.pipe(t)}function s(e){return e.length&&"function"==typeof e[e.length-1]?e.pop():n}var a,c=e("../../../errors").codes,l=c.ERR_MISSING_ARGS,d=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=s(t);if(Array.isArray(t[0])&&(t=t[0]),2>t.length)throw new l("streams");var c,d=t.map(function(e,n){var o=n<t.length-1;return r(e,o,0<n,function(e){c||(c=e),e&&d.forEach(i),o||(d.forEach(i),a(c))})});return t.reduce(o)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(t,n){"use strict";var r=t("../../../errors").codes.ERR_INVALID_OPT_VALUE;n.exports={getHighWaterMark:function(t,n,i,o){var s=function(e,t,n){return null==e.highWaterMark?t?e[n]:null:e.highWaterMark}(n,o,i);if(null!=s){if(!isFinite(s)||e(s)!==s||0>s)throw new r(o?i:"highWaterMark",s);return e(s)}return t.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 s(e,t,n)}var o=e("buffer"),s=o.Buffer;s.from&&s.alloc&&s.allocUnsafe&&s.allocUnsafeSlow?t.exports=o:(r(o,n),n.Buffer=i),i.prototype=Object.create(s.prototype),r(s,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return s(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=s(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 s(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o.SlowBuffer(e)}},{buffer:3}],31:[function(e,t,n){"use strict";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&&(h.isEncoding===f||!f(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=s,this.end=a,t=4;break;case"utf8":this.fillLast=o,t=4;break;case"base64":this.text=c,this.end=l,t=3;break;default:return this.write=d,void(this.end=u)}this.lastNeed=0,this.lastTotal=0,this.lastChar=h.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 o(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 s(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 d(e){return e.toString(this.encoding)}function u(e){return e&&e.length?this.write(e):""}var h=e("safe-buffer").Buffer,f=h.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 o=i(t[r]);return 0<=o?(0<o&&(e.lastNeed=o-1),o):--r<n||-2===o?0:0<=(o=i(t[r]))?(0<o&&(e.lastNeed=o-2),o):--r<n||-2===o?0:0<=(o=i(t[r]))?(0<o&&(2===o?o=0:e.lastNeed=o-3),o):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"),o=e("randombytes"),s=e("readable-stream"),a=e("queue-microtask"),c=e("err-code"),{Buffer:l}=e("buffer"),d=65536;class u extends s.Duplex{constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this._id=o(4).toString("hex").slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||o(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||u.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},u.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(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(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=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(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(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(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(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(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(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(e)||new Map;let r=n.get(t);if(r)throw r.removed?c(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(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(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(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(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(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(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(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(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(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=d),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: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(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>d?(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(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(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(c(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={},o={};let s=!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)&&(o[e.id]=e)});const a=e=>{s=!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(o[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)}),s||Object.keys(o).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>d)&&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)}}u.WEBRTC_SUPPORT=!!i(),u.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},u.channelConfig={},t.exports=u},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})}),hn=e.__toESM(un(),1),fn=(e,t)=>{if(!t)return a.resolve(e);const n=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,e).then(e=>{const t=a.createEncoder();return a.writeVarString(t,"AES-GCM"),a.writeVarUint8Array(t,n),a.writeVarUint8Array(t,new Uint8Array(e)),a.toUint8Array(t)})},pn=(e,t)=>{if(!t)return a.resolve(e);const n=a.createDecoder(e);"AES-GCM"!==a.readVarString(n)&&a.reject(a.create$1("Unknown encryption algorithm"));const r=a.readVarUint8Array(n),i=a.readVarUint8Array(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,i).then(e=>new Uint8Array(e))},gn=a.createModuleLogger("y-webrtc"),mn=new Map,yn=new Map,bn=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}]),gn("synced ",a.BOLD,e.name,a.UNBOLD," with all peers"))},wn=(e,t,n)=>{const r=a.createDecoder(t),i=a.createEncoder(),o=a.readVarUint(r);if(void 0===e)return null;const s=e.awareness,c=e.doc;let l=!1;switch(o){case 0:{a.writeVarUint(i,0);const t=J(r,i,c,e);1!==t||e.synced||n(),0===t&&(l=!0);break}case 3:a.writeVarUint(i,1),a.writeVarUint8Array(i,v(s,Array.from(s.getStates().keys()))),l=!0;break;case 1:_(s,a.readVarUint8Array(r),e);break;case 4:{const t=1===a.readUint8(r),n=a.readVarString(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)}]),kn(e)}break}default:return i}return l?i:null},vn=(e,t)=>{gn("send message to ",a.BOLD,e.remotePeerId,a.UNBOLD,a.GREY," (",e.room.name,")",a.UNCOLOR);try{e.peer.send(a.toUint8Array(t))}catch(n){}},_n=class{constructor(e,t,n,r){gn("establishing connection to ",a.BOLD,n),this.room=r,this.remotePeerId=n,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new hn.default({initiator:t,...r.provider.peerOpts}),this.peer.on("signal",t=>{void 0===this.glareToken&&(this.glareToken=Date.now()+Math.random()),xn(e,r,{to:n,from:r.peerId,type:"signal",token:this.glareToken,signal:t})}),this.peer.on("connect",()=>{gn("connected to ",a.BOLD,n),this.connected=!0;const e=r.provider.doc,t=r.awareness,i=a.createEncoder();a.writeVarUint(i,0),z(i,e),vn(this,i);const o=t.getStates();if(o.size>0){const e=a.createEncoder();a.writeVarUint(e,1),a.writeVarUint8Array(e,v(t,Array.from(o.keys()))),vn(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)}])),bn(r),this.peer.destroy(),gn("closed connection to ",a.BOLD,n),Cn(r)}),this.peer.on("error",e=>{gn("Error in connection to ",a.BOLD,n,": ",e),Cn(r)}),this.peer.on("data",e=>{const t=((e,t)=>{const n=e.room;return gn("received message from ",a.BOLD,e.remotePeerId,a.GREY," (",n.name,")",a.UNBOLD,a.UNCOLOR),wn(n,t,()=>{e.synced=!0,gn("synced ",a.BOLD,n.name,a.UNBOLD," with ",a.BOLD,e.remotePeerId),bn(n)})})(this,e);null!==t&&vn(this,t)})}destroy(){this.peer.destroy()}},Sn=(e,t)=>fn(t,e.key).then(t=>e.mux(()=>((e,t,n=null)=>{const r=dn(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))})(e.name,t))),En=(e,t)=>{e.bcconnected&&Sn(e,t),((e,t)=>{gn("broadcast message in ",a.BOLD,e.name,a.UNBOLD),e.webrtcConns.forEach(e=>{try{e.peer.send(t)}catch(n){}})})(e,t)},Cn=e=>{mn.forEach(t=>{t.connected&&(t.send({type:"subscribe",topics:[e.name]}),e.webrtcConns.size<e.provider.maxConns&&xn(t,e,{type:"announce",from:e.peerId}))})},kn=e=>{if(e.provider.filterBcConns){const t=a.createEncoder();a.writeVarUint(t,4),a.writeUint8(t,1),a.writeVarString(t,e.peerId),Sn(e,a.toUint8Array(t))}},Tn=class{constructor(e,t,n,r){this.peerId=a.uuidv4(),this.doc=e,this.awareness=t.awareness,this.provider=t,this.synced=!1,this.name=n,this.key=r,this.webrtcConns=new Map,this.bcConns=new Set,this.mux=a.createMutex(),this.bcconnected=!1,this._bcSubscriber=e=>pn(new Uint8Array(e),r).then(e=>this.mux(()=>{const t=wn(this,e,()=>{});t&&Sn(this,a.toUint8Array(t))})),this._docUpdateHandler=(e,t)=>{const n=a.createEncoder();a.writeVarUint(n,0),X(n,e),En(this,a.toUint8Array(n))},this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{const i=e.concat(t).concat(n),o=a.createEncoder();a.writeVarUint(o,1),a.writeVarUint8Array(o,v(this.awareness,i)),En(this,a.toUint8Array(o))},this._beforeUnloadHandler=()=>{w(this.awareness,[e.clientID],"window unload"),yn.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),Cn(this);const e=this.name;var t,n;t=e,n=this._bcSubscriber,dn(t).subs.add(n),this.bcconnected=!0,kn(this);const r=a.createEncoder();a.writeVarUint(r,0),z(r,this.doc),Sn(this,a.toUint8Array(r));const i=a.createEncoder();a.writeVarUint(i,0),$(i,this.doc),Sn(this,a.toUint8Array(i));const o=a.createEncoder();a.writeVarUint(o,3),Sn(this,a.toUint8Array(o));const s=a.createEncoder();a.writeVarUint(s,1),a.writeVarUint8Array(s,v(this.awareness,[this.doc.clientID])),Sn(this,a.toUint8Array(s))}disconnect(){mn.forEach(e=>{e.connected&&e.send({type:"unsubscribe",topics:[this.name]})}),w(this.awareness,[this.doc.clientID],"disconnect");const e=a.createEncoder();a.writeVarUint(e,4),a.writeUint8(e,0),a.writeVarString(e,this.peerId),Sn(this,a.toUint8Array(e)),((e,t)=>{const n=dn(e),r=n.subs.delete(t);r&&0===n.subs.size&&(n.bc.close(),cn.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)}},xn=(e,t,n)=>{t.key?((e,t)=>{const n=a.createEncoder();return a.writeAny(n,e),fn(a.toUint8Array(n),t)})(n,t.key).then(n=>{e.send({type:"publish",topic:t.name,data:a.toBase64(n)})}):e.send({type:"publish",topic:t.name,data:n})},Rn=class extends an{constructor(e){super(e),this.providers=new Set,this.on("connect",()=>{gn(`connected (${e})`);const t=Array.from(yn.keys());this.send({type:"subscribe",topics:t}),yn.forEach(e=>xn(this,e,{type:"announce",from:e.peerId}))}),this.on("message",e=>{if("publish"===e.type){const r=e.topic,i=yn.get(r);if(null==i||"string"!=typeof r)return;const o=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&&(a.setIfUndefined(t,e.from,()=>new _n(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 gn("offer rejected: ",e.from);n.glareToken=void 0}}if("answer"===e.signal.type){gn("offer answered by: ",e.from);t.get(e.from).glareToken=void 0}e.to===n&&(a.setIfUndefined(t,e.from,()=>new _n(this,!1,e.from,i)).peer.signal(e.signal),r())}};i.key?"string"==typeof e.data&&(t=a.fromBase64(e.data),n=i.key,pn(t,n).then(e=>a.readAny(a.createDecoder(new Uint8Array(e))))).then(o):o(e.data)}var t,n}),this.on("disconnect",()=>gn(`disconnect (${e})`))}},An=e=>{e.emit("status",[{connected:e.connected}])},On=class extends a.ObservableV2{constructor(e,t,{signaling:n=["wss://y-webrtc-eu.fly.dev"],password:r=null,awareness:i=new b(t),maxConns:o=20+a.floor(15*a.rand()),filterBcConns:s=!0,peerOpts:c={}}={}){super(),this.roomName=e,this.doc=t,this.filterBcConns=s,this.awareness=i,this.shouldConnect=!1,this.signalingUrls=n,this.signalingConns=[],this.maxConns=o,this.peerOpts=c,this.key=r?((e,t)=>{const n=a.encodeUtf8(e).buffer,r=a.encodeUtf8(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):a.resolve(null),this.room=null,this.key.then(n=>{this.room=((e,t,n,r)=>{if(yn.has(n))throw a.create$1(`A Yjs Doc connected to room "${n}" already exists!`);const i=new Tn(e,t,n,r);return yn.set(n,i),i})(t,this,e,n),this.shouldConnect?this.room.connect():this.room.disconnect(),An(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=a.setIfUndefined(mn,e,()=>new Rn(e));this.signalingConns.push(t),t.providers.add(this)}),this.room&&(this.room.connect(),An(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),0===e.providers.size&&(e.destroy(),mn.delete(e.url))}),this.room&&(this.room.disconnect(),An(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),yn.delete(this.roomName)}),super.destroy()}};async function Dn(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 a.Doc({guid:e});r.clientID=n;const i=ut(t);r.get("content",a.YXmlText).applyDelta(i);const o=a.encodeStateAsUpdate(r);return r.destroy(),o}var Pn,Nn,Ln={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:o,onError:s,onSyncChange:a}){this.onConnect=i,this.onDisconnect=o,this.onSyncChange=a,this.onError=s;const c={...n,...t&&{document:t},...e&&{awareness:e},...r&&(()=>{try{return{websocketProvider:new oe(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 pe(c)}catch(l){this.provider=new pe({...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:o,onSyncChange:s}){this.document=t??new a.Doc,this.awareness=e??new b(this.document),this.providerOptions=n,this.onConnect=r,this.onDisconnect=i,this.onError=o,this.onSyncChange=s}connect=()=>{if(!this._isDestroyed){if(!this._provider)try{const e=new rn(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:o,onSyncChange:s}){this.onSyncChange=s,this.doc=t||new a.Doc;try{this.provider=new On(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,s?.(!0))):t&&(i?.(),this._isSynced&&(this._isSynced=!1,s?.(!1)))})}catch(c){o?.(c instanceof Error?c:new Error(String(c)))}}get awareness(){return this.provider.awareness}get document(){return this.doc}get isConnected(){return this._isConnected}get isSynced(){return this._isSynced}}},Mn=({type:e,...t})=>{const n=(e=>Ln[e])(e);if(!n)throw new Error(`Provider type "${e}" not found in registry`);return new n(t)},Un=(e,t,n)=>function(e,t,{cursorStateField:n="selection",cursorDataField:r="data",autoSend:i=!0,data:o}={}){const s=e;s.awareness=t,s.cursorDataField=r,s.selectionStateField=n,s.sendCursorData=e=>{s.awareness.setLocalStateField(s.cursorDataField,e)},s.sendCursorPosition=e=>{const t=s.awareness.getLocalState(),r=null==t?void 0:t[n];if(!e)return void(r&&s.awareness.setLocalStateField(s.selectionStateField,null));const{anchor:i,focus:o}=Ot(s.sharedRoot,s,e);r&&a.compareRelativePositions(i,r)&&a.compareRelativePositions(o,r)||s.awareness.setLocalStateField(s.selectionStateField,{anchor:i,focus:o})};const c=e=>{const t=qt.get(s);if(!t)return;const n=s.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:l,disconnect:d}=s;return s.connect=()=>{if(l(),s.awareness.on("change",c),c({removed:[],added:Array.from(s.awareness.getStates().keys()),updated:[]}),i){o&&Yt.sendCursorData(s,o);const{onChange:e}=s;s.onChange=()=>{e(),Bt.connected(s)&&Yt.sendCursorPosition(s)}}},s.disconnect=()=>{s.awareness.off("change",c),c({removed:Array.from(s.awareness.getStates().keys()),added:[],updated:[]}),d()},s}(e,t,n),jn=(e,t)=>function(e,t={}){var n=t,{withoutSavingOrigin:r=Wt,trackedOrigins:o=new Set([e.localOrigin])}=n,s=Je(n,["withoutSavingOrigin","trackedOrigins"]);const c=e;c.undoManager=new a.UndoManager(c.sharedRoot,Xe({trackedOrigins:o},s)),c.withoutSavingOrigin=r;const{onChange:l,isLocalOrigin:d}=c;c.onChange=()=>{l(),Vt.set(c,c.selection&&Ot(c.sharedRoot,c,c.selection))},c.isLocalOrigin=e=>e===c.withoutSavingOrigin||d(e);const u=({stackItem:e})=>{e.meta.set("selection",c.selection&&Ot(c.sharedRoot,c,c.selection)),e.meta.set("selectionBefore",Vt.get(c))},h=({stackItem:e})=>{e.meta.set("selection",c.selection&&Ot(c.sharedRoot,c,c.selection))},f=({stackItem:e,type:t})=>{const n="undo"===t?c.undoManager.redoStack:c.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 o=e.meta.get("selectionBefore");if(!o)return;const s=Dt(c.sharedRoot,c,o);s&&i.Transforms.select(c,s)},{connect:p,disconnect:g}=c;return c.connect=()=>{p(),c.undoManager.on("stack-item-added",u),c.undoManager.on("stack-item-popped",f),c.undoManager.on("stack-item-updated",h)},c.disconnect=()=>{c.undoManager.off("stack-item-added",u),c.undoManager.off("stack-item-popped",f),c.undoManager.off("stack-item-updated",h),g()},c.undo=()=>{Bt.connected(c)&&(Bt.flushLocalChanges(c),c.undoManager.undo())},c.redo=()=>{Bt.connected(c)&&(Bt.flushLocalChanges(c),c.undoManager.redo())},c}(e,t),In=e=>"object"==typeof e&&null!==e&&"type"in e&&"options"in e,Bn=i.createTSlatePlugin({key:i.KEYS.yjs,extendEditor:({editor:e,getOptions:t})=>{let n=e;const{awareness:r,cursors:i,localOrigin:o,positionStorageOrigin:s,sharedType:c,ydoc:l}=t();if(n=((e,t,n)=>Ft(e,t,n))(n,c??l.get("content",a.YXmlText),{autoConnect:!1,localOrigin:o,positionStorageOrigin:s}),i)if(r){let e=!0;!1===i.autoSend&&(e=!1),n=Un(n,r,{...i,autoSend:e})}else n.api.debug.error("Yjs plugin: Internal shared awareness (awareness) is missing but cursors are enabled.");return jn(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:o}=r;return o||(o=new a.Doc),i||(i=new b(o)),{options:{awareness:i,localOrigin:t??void 0,positionStorageOrigin:n??void 0,ydoc:o}}}).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{Bt.disconnect(t)}catch{}},disconnect:t=>{const{editor:n,getOptions:r}=e,{_providers:i}=r(),o=t?Array.isArray(t)?t:[t]:null;for(const e of[...i].reverse())try{!e.isConnected&&!e.isConnectionPending||null!==o&&!o.includes(e.type)||e.disconnect()}catch(s){}},init:async({id:t,autoConnect:n=!0,autoSelect:r,selection:i,value:o,onReady:s}={})=>{const{editor:c,getOptions:l,setOption:d}=e,{awareness:u,providers:h=[],sharedType:f,ydoc:p}=l(),g=()=>{return(e=f??p.get("content",a.YXmlText)).length>0||null!=e._start;var e};if(0===h.length)throw new Error("No providers specified. Please provide provider configurations or instances in the `providers` array.");const m=[];let y=null;const b=new Promise(e=>{y=e});for(const e of h)if(In(e)){const{options:t,type:n}=e;let r=null;if(!t)continue;try{const e=Mn({awareness:u,doc:p,options:t,type:n,onConnect:()=>{l().onConnect?.({type:n}),d("_isConnected",!0)},onDisconnect:()=>{l().onDisconnect?.({type:n});const{_providers:e}=l();e.some(e=>e.isConnected)||d("_isConnected",!1)},onError:e=>{l().onError?.({error:e,type:n})},onSyncChange:e=>{l().onSyncChange?.({isSynced:e,type:n}),d("_isSynced",e);const t=m.some(e=>!e.isLocalPersistence),i=!r?.isLocalPersistence||!t||g();e&&y&&i&&(y(),y=null)}});r=e,m.push(e)}catch{}}else m.push(e);if(d("_providers",m),n&&m.length>0){m.forEach(e=>{try{e.connect()}catch(t){l().onError?.({error:t instanceof Error?t:new Error(String(t)),type:e.type})}});const e=5e3;await Promise.race([b,new Promise(t=>{setTimeout(()=>{y=null,t()},e)})])}if(!g()&&!m.some(e=>e.isLocalPersistence&&(e.isConnectionPending||e.isSyncPending))&&null!==o){let e=o;if("string"==typeof o?e=c.api.html.deserialize({element:o}):"function"==typeof o?e=await o(c):o&&(e=o),e&&0!==e?.length||(e=c.api.create.value()),f){const t=ut(e);p.transact(()=>{f.applyDelta(t)})}else{const n=await Dn(t??c.id,e);p.transact(()=>{a.applyUpdate(p,n)})}}Bt.connect(c),c.tf.init({autoSelect:r,selection:i,shouldNormalizeEditor:!1,value:null}),c.api.onChange(),s?.({editor:c,isAsync:!0,value:c.children})}})),Fn=i.toPlatePlugin(Bn),Vn=i.require_lib(),Wn=globalThis.Node,qn=(globalThis.Element,globalThis.Text),Yn=(globalThis.Range,globalThis.Selection,globalThis.StaticRange,e=>e&&e.ownerDocument&&e.ownerDocument.defaultView||null),Hn=e=>zn(e)&&8===e.nodeType,Kn=e=>zn(e)&&1===e.nodeType,zn=e=>{var t=Yn(e);return!!t&&e instanceof t.Node},$n=e=>{var t=e&&e.anchorNode&&Yn(e.anchorNode);return!!t&&e instanceof t.Selection},Gn=(e,t,n)=>{if("number"!=typeof t)throw new Error("Expected index to be a number");for(var{childNodes:r}=e,i=r[t],o=t,s=!1,a=!1;(Hn(i)||Kn(i)&&0===i.childNodes.length||Kn(i)&&"false"===i.getAttribute("contenteditable"))&&(!s||!a);)o>=r.length?(s=!0,o=t-1,n="backward"):o<0?(a=!0,o=t+1,n="forward"):(i=r[o],t=o,o+="forward"===n?1:-1);return[i,t]},Xn=(e,t,n)=>{var[r]=Gn(e,t,n);return r},Qn=e=>null!=e.getSelection?e.getSelection():document.getSelection(),Jn=(e,t,n)=>{var{target:r}=t;if(Kn(r)&&r.matches('[contentEditable="false"]'))return!1;var{document:i}=kr.getWindow(e);if(tr(i,r))return kr.hasDOMNode(e,r,{editable:!0});var o=n.find(e=>{var{addedNodes:t,removedNodes:n}=e;for(var i of t)if(i===r||tr(i,r))return!0;for(var o of n)if(o===r||tr(o,r))return!0});return!(!o||o===t)&&Jn(e,o,n)},Zn=(e,t)=>Boolean(e.compareDocumentPosition(t)&Wn.DOCUMENT_POSITION_PRECEDING),er=(e,t)=>{if(!e)return null;for(var n=e;n;){if(n.matches&&n.matches(t))return n;if(n.parentElement)n=n.parentElement;else{if(!n.parentNode||!("host"in n.parentNode))return null;n=n.parentNode.host}}return null},tr=(e,t)=>{if(!e||!t)return!1;if(e.contains(t))return!0;for(var n=t;n;){if(n===e)return!0;if(!n.parentNode)return!1;n="host"in n.parentNode?n.parentNode.host:n.parentNode}return!1},nr=("undefined"!=typeof navigator&&"undefined"!=typeof window&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&window.MSStream,"undefined"!=typeof navigator&&/Mac OS X/.test(navigator.userAgent)),rr="undefined"!=typeof navigator&&/Android/.test(navigator.userAgent),ir="undefined"!=typeof navigator&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),or=("undefined"!=typeof navigator&&/AppleWebKit(?!.*Chrome)/i.test(navigator.userAgent),"undefined"!=typeof navigator&&/Edge?\/(?:[0-6][0-9]|[0-7][0-8])(?:\.)/i.test(navigator.userAgent)),sr="undefined"!=typeof navigator&&/Chrome/i.test(navigator.userAgent),ar="undefined"!=typeof navigator&&/Chrome?\/(?:[0-7][0-5]|[0-6][0-9])(?:\.)/i.test(navigator.userAgent),cr=rr&&"undefined"!=typeof navigator&&/Chrome?\/(?:[0-5]?\d)(?:\.)/i.test(navigator.userAgent);"undefined"!=typeof navigator&&/^(?!.*Seamonkey)(?=.*Firefox\/(?:[0-7][0-9]|[0-8][0-6])(?:\.)).*/i.test(navigator.userAgent),"undefined"!=typeof navigator&&/.*UCBrowser/.test(navigator.userAgent),"undefined"!=typeof navigator&&/.*Wechat/.test(navigator.userAgent)&&/.*MacWechat/.test(navigator.userAgent),"undefined"==typeof window||void 0===window.document||window.document.createElement;"undefined"!=typeof navigator&&/Safari/.test(navigator.userAgent)&&/Version\/(\d+)/.test(navigator.userAgent)&&null!==(Pn=navigator.userAgent.match(/Version\/(\d+)/))&&void 0!==Pn&&Pn[1]&&parseInt(null===(Nn=navigator.userAgent.match(/Version\/(\d+)/))||void 0===Nn?void 0:Nn[1],10);(!ar||!cr)&&!or&&"undefined"!=typeof globalThis&&globalThis.InputEvent&&globalThis.InputEvent.prototype.getTargetRanges;function lr(e){return lr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lr(e)}function dr(e){var t=function(e,t){if("object"!==lr(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!==lr(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===lr(t)?t:String(t)}var ur=0,hr=class{constructor(){var e,t,n;e=this,n=void 0,(t=dr(t="id"))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,this.id="".concat(ur++)}},fr=new WeakMap,pr=new WeakMap,gr=new WeakMap,mr=new WeakMap,yr=new WeakMap,br=new WeakMap,wr=new WeakMap,vr=new WeakMap,_r=new WeakMap,Sr=new WeakMap,Er=new WeakMap,Cr=new WeakMap,kr={androidPendingDiffs:e=>Cr.get(e),androidScheduleFlush:e=>{var t;null===(t=Er.get(e))||void 0===t||t()},blur:e=>{var t=kr.toDOMNode(e,e),n=kr.findDocumentOrShadowRoot(e);_r.set(e,!1),n.activeElement===t&&t.blur()},deselect:e=>{var{selection:t}=e,n=Qn(kr.findDocumentOrShadowRoot(e));n&&n.rangeCount>0&&n.removeAllRanges(),t&&i.Transforms.deselect(e)},findDocumentOrShadowRoot:e=>{var t=kr.toDOMNode(e,e),n=t.getRootNode();return n instanceof Document||n instanceof ShadowRoot?n:t.ownerDocument},findEventRange:(e,t)=>{"nativeEvent"in t&&(t=t.nativeEvent);var{clientX:n,clientY:r,target:o}=t;if(null==n||null==r)throw new Error("Cannot resolve a Slate range from a DOM event: ".concat(t));var s,a=kr.toSlateNode(e,t.target),c=kr.findPath(e,a);if(i.Node.isElement(a)&&i.Editor.isVoid(e,a)){var l=o.getBoundingClientRect(),d=e.isInline(a)?n-l.left<l.left+l.width-n:r-l.top<l.top+l.height-r,u=i.Editor.point(e,c,{edge:d?"start":"end"}),h=d?i.Editor.before(e,u):i.Editor.after(e,u);if(h)return i.Editor.range(e,h)}var{document:f}=kr.getWindow(e);if(f.caretRangeFromPoint)s=f.caretRangeFromPoint(n,r);else{var p=f.caretPositionFromPoint(n,r);p&&((s=f.createRange()).setStart(p.offsetNode,p.offset),s.setEnd(p.offsetNode,p.offset))}if(!s)throw new Error("Cannot resolve a Slate range from a DOM event: ".concat(t));return kr.toSlateRange(e,s,{exactMatch:!1,suppressThrow:!1})},findKey:(e,t)=>{var n=br.get(t);return n||(n=new hr,br.set(t,n)),n},findPath:(e,t)=>{for(var n=[],r=t;;){var o=pr.get(r);if(null==o){if(r===e)return n;break}var s=fr.get(r);if(null==s)break;n.unshift(s),r=o}throw new Error("Unable to find the path for Slate node: ".concat(i.Scrubber.stringify(t)))},focus:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{retries:5};if(!_r.get(e)&&mr.get(e)){if(t.retries<=0)throw new Error("Could not set focus, editor seems stuck with pending operations");if(e.operations.length>0)setTimeout(()=>{kr.focus(e,{retries:t.retries-1})},10);else{var n=kr.toDOMNode(e,e),r=kr.findDocumentOrShadowRoot(e);if(r.activeElement!==n){if(e.selection&&r instanceof Document){var o=Qn(r),s=kr.toDOMRange(e,e.selection);null==o||o.removeAllRanges(),null==o||o.addRange(s)}e.selection||i.Transforms.select(e,i.Editor.start(e,[])),_r.set(e,!0),n.focus({preventScroll:!0})}}}},getWindow:e=>{var t=gr.get(e);if(!t)throw new Error("Unable to find a host window element for this editor");return t},hasDOMNode:function(e,t){var n,{editable:r=!1}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=kr.toDOMNode(e,e);try{n=Kn(t)?t:t.parentElement}catch(o){if(o instanceof Error&&!o.message.includes('Permission denied to access property "nodeType"'))throw o}return!!n&&!(er(n,"[data-slate-editor]")!==i||r&&!n.isContentEditable&&("boolean"!=typeof n.isContentEditable||er(n,'[contenteditable="false"]')!==i)&&!n.getAttribute("data-slate-zero-width"))},hasEditableTarget:(e,t)=>zn(t)&&kr.hasDOMNode(e,t,{editable:!0}),hasRange:(e,t)=>{var{anchor:n,focus:r}=t;return i.Editor.hasPath(e,n.path)&&i.Editor.hasPath(e,r.path)},hasSelectableTarget:(e,t)=>kr.hasEditableTarget(e,t)||kr.isTargetInsideNonReadonlyVoid(e,t),hasTarget:(e,t)=>zn(t)&&kr.hasDOMNode(e,t),insertData:(e,t)=>{e.insertData(t)},insertFragmentData:(e,t)=>e.insertFragmentData(t),insertTextData:(e,t)=>e.insertTextData(t),isComposing:e=>!!Sr.get(e),isFocused:e=>!!_r.get(e),isReadOnly:e=>!!vr.get(e),isTargetInsideNonReadonlyVoid:(e,t)=>{if(vr.get(e))return!1;if(!kr.hasTarget(e,t))return!1;var n=kr.toSlateNode(e,t);return i.Node.isElement(n)&&i.Editor.isVoid(e,n)},setFragmentData:(e,t,n)=>e.setFragmentData(t,n),toDOMNode:(e,t)=>{var n,r=t===e?mr.get(e):null===(n=wr.get(e))||void 0===n?void 0:n.get(kr.findKey(e,t));if(!r)throw new Error("Cannot resolve a DOM node from Slate node: ".concat(i.Scrubber.stringify(t)));return r},toDOMPoint:(e,t)=>{var n,[r]=i.Editor.node(e,t.path),o=kr.toDOMNode(e,r);i.Editor.void(e,{at:t})&&(t={path:t.path,offset:0});for(var s=Array.from(o.querySelectorAll("[data-slate-string], [data-slate-zero-width]")),a=0,c=0;c<s.length;c++){var l=s[c],d=l.childNodes[0];if(null!=d&&null!=d.textContent){var{length:u}=d.textContent,h=l.getAttribute("data-slate-length"),f=a+(null==h?u:parseInt(h,10)),p=s[c+1];if(t.offset===f&&null!=p&&p.hasAttribute("data-slate-mark-placeholder")){var g,m=p.childNodes[0];n=[m instanceof qn?m:p,null!==(g=p.textContent)&&void 0!==g&&g.startsWith("\ufeff")?1:0];break}if(t.offset<=f){n=[d,Math.min(u,Math.max(0,t.offset-a))];break}a=f}}if(!n)throw new Error("Cannot resolve a DOM point from Slate point: ".concat(i.Scrubber.stringify(t)));return n},toDOMRange:(e,t)=>{var{anchor:n,focus:r}=t,o=i.Range.isBackward(t),s=kr.toDOMPoint(e,n),a=i.Range.isCollapsed(t)?s:kr.toDOMPoint(e,r),c=kr.getWindow(e).document.createRange(),[l,d]=o?a:s,[u,h]=o?s:a,f=!!(Kn(l)?l:l.parentElement).getAttribute("data-slate-zero-width"),p=!!(Kn(u)?u:u.parentElement).getAttribute("data-slate-zero-width");return c.setStart(l,f?1:d),c.setEnd(u,p?1:h),c},toSlateNode:(e,t)=>{var n=Kn(t)?t:t.parentElement;n&&!n.hasAttribute("data-slate-node")&&(n=n.closest("[data-slate-node]"));var r=n?yr.get(n):null;if(!r)throw new Error("Cannot resolve a Slate node from DOM node: ".concat(n));return r},toSlatePoint:(e,t,n)=>{var r,o,{exactMatch:s,suppressThrow:a}=n,[c,l]=s?t:(e=>{var[t,n]=e;if(Kn(t)&&t.childNodes.length){var r=n===t.childNodes.length,i=r?n-1:n;for([t,i]=Gn(t,i,r?"backward":"forward"),r=i<n;Kn(t)&&t.childNodes.length;){var o=r?t.childNodes.length-1:0;t=Xn(t,o,r?"backward":"forward")}n=r&&null!=t.textContent?t.textContent.length:0}return[t,n]})(t),d=c.parentNode,u=n.searchDirection,h=null,f=0;if(d){var p,g,m=kr.toDOMNode(e,e),y=d.closest('[data-slate-void="true"]'),b=y&&tr(m,y)?y:null,w=d.closest('[contenteditable="false"]'),v=w&&tr(m,w)?w:null,_=d.closest("[data-slate-leaf]"),S=null;if(_){if(h=_.closest('[data-slate-node="text"]')){var E=kr.getWindow(e).document.createRange();E.setStart(h,0),E.setEnd(c,l);var C=E.cloneContents();[...Array.prototype.slice.call(C.querySelectorAll("[data-slate-zero-width]")),...Array.prototype.slice.call(C.querySelectorAll("[contenteditable=false]"))].forEach(e=>{rr&&!s&&e.hasAttribute("data-slate-zero-width")&&e.textContent.length>0&&"\ufeff"!==e.textContext?e.textContent.startsWith("\ufeff")&&(e.textContent=e.textContent.slice(1)):e.parentNode.removeChild(e)}),f=C.textContent.length,S=h}}else if(b){for(var k=b.querySelectorAll("[data-slate-leaf]"),T=0;T<k.length;T++){var x=k[T];if(kr.hasDOMNode(e,x)){_=x;break}}_?(h=_.closest('[data-slate-node="text"]'),f=(S=_).textContent.length,S.querySelectorAll("[data-slate-zero-width]").forEach(e=>{f-=e.textContent.length})):f=1}else if(v){var R,A,O=e=>e?e.querySelectorAll("[data-slate-leaf]:not(:scope [data-slate-editor] [data-slate-leaf])"):[],D=v.closest('[data-slate-node="element"]');if("backward"===u||!u)(_=null!==(R=[...O(null==D?void 0:D.previousElementSibling),...O(D)].findLast(e=>Zn(v,e)))&&void 0!==R?R:null)&&(u="backward");if("forward"===u||!u)_=null!==(A=[...O(D),...O(null==D?void 0:D.nextElementSibling)].find(e=>((e,t)=>Boolean(e.compareDocumentPosition(t)&Wn.DOCUMENT_POSITION_FOLLOWING))(v,e)))&&void 0!==A?A:null,_&&(u="forward");_&&(h=_.closest('[data-slate-node="text"]'),S=_,"forward"===u?f=0:(f=S.textContent.length,S.querySelectorAll("[data-slate-zero-width]").forEach(e=>{f-=e.textContent.length})))}S&&f===S.textContent.length&&rr&&"z"===S.getAttribute("data-slate-zero-width")&&null!==(p=S.textContent)&&void 0!==p&&p.startsWith("\ufeff")&&(d.hasAttribute("data-slate-zero-width")||ir&&null!==(g=S.textContent)&&void 0!==g&&g.endsWith("\n\n"))&&f--}if(rr&&!h&&!s){var P=d.hasAttribute("data-slate-node")?d:d.closest("[data-slate-node]");if(P&&kr.hasDOMNode(e,P,{editable:!0})){var N,L=kr.toSlateNode(e,P);try{N=kr.findPath(e,L)}catch(j){if(a)return null;throw j}var{path:M,offset:U}=i.Editor.start(e,N);return P.querySelector("[data-slate-leaf]")||(U=l),{path:M,offset:U}}}if(!h){if(a)return null;throw new Error("Cannot resolve a Slate point from DOM point: ".concat(t))}try{r=kr.toSlateNode(e,h)}catch(j){if(a)return null;throw j}try{o=kr.findPath(e,r)}catch(j){if(a)return null;throw j}return{path:o,offset:f}},toSlateRange:(e,t,n)=>{var r,o,s,a,c,l,{exactMatch:d,suppressThrow:u}=n;if($n(t)?t.anchorNode:t.startContainer)if($n(t)){if(ir&&t.rangeCount>1){a=t.focusNode;var h=t.getRangeAt(0),f=t.getRangeAt(t.rangeCount-1);if(a instanceof HTMLTableRowElement&&h.startContainer instanceof HTMLTableRowElement&&f.startContainer instanceof HTMLTableRowElement){function p(e){return e.childElementCount>0?p(e.children[0]):e}var g=h.startContainer,m=f.startContainer,y=p(g.children[h.startOffset]),b=p(m.children[f.startOffset]);c=0,o=b.childNodes.length>0?b.childNodes[0]:b,a=y.childNodes.length>0?y.childNodes[0]:y,s=b instanceof HTMLElement?b.innerHTML.length:0}else h.startContainer===a?(o=f.endContainer,s=f.endOffset,c=h.startOffset):(o=h.startContainer,s=h.endOffset,c=f.startOffset)}else o=t.anchorNode,s=t.anchorOffset,a=t.focusNode,c=t.focusOffset;l=sr&&(e=>{for(var t=e&&e.parentNode;t;){if("[object ShadowRoot]"===t.toString())return!0;t=t.parentNode}return!1})(o)||ir?t.anchorNode===t.focusNode&&t.anchorOffset===t.focusOffset:t.isCollapsed}else o=t.startContainer,s=t.startOffset,a=t.endContainer,c=t.endOffset,l=t.collapsed;if(null==o||null==a||null==s||null==c)throw new Error("Cannot resolve a Slate range from DOM range: ".concat(t));ir&&null!==(r=a.textContent)&&void 0!==r&&r.endsWith("\n\n")&&c===a.textContent.length&&c--;var w=kr.toSlatePoint(e,[o,s],{exactMatch:d,suppressThrow:u});if(!w)return null;var v=Zn(o,a)||o===a&&c<s,_=l?w:kr.toSlatePoint(e,[a,c],{exactMatch:d,suppressThrow:u,searchDirection:v?"forward":"backward"});if(!_)return null;var S={anchor:w,focus:_};return i.Range.isExpanded(S)&&i.Range.isForward(S)&&Kn(a)&&i.Editor.void(e,{at:S.focus,mode:"highest"})&&(S=i.Editor.unhangRange(e,S,{voids:!0})),S}},Tr={bold:"mod+b",compose:["down","left","right","up","backspace","enter"],moveBackward:"left",moveForward:"right",moveWordBackward:"ctrl+left",moveWordForward:"ctrl+right",deleteBackward:"shift?+backspace",deleteForward:"shift?+delete",extendBackward:"shift+left",extendForward:"shift+right",italic:"mod+i",insertSoftBreak:"shift+enter",splitBlock:"enter",undo:"mod+z"},xr={moveLineBackward:"opt+up",moveLineForward:"opt+down",moveWordBackward:"opt+left",moveWordForward:"opt+right",deleteBackward:["ctrl+backspace","ctrl+h"],deleteForward:["ctrl+delete","ctrl+d"],deleteLineBackward:"cmd+shift?+backspace",deleteLineForward:["cmd+shift?+delete","ctrl+k"],deleteWordBackward:"opt+shift?+backspace",deleteWordForward:"opt+shift?+delete",extendLineBackward:"opt+shift+up",extendLineForward:"opt+shift+down",redo:"cmd+shift+z",transposeCharacter:"ctrl+t"},Rr={deleteWordBackward:"ctrl+shift?+backspace",deleteWordForward:"ctrl+shift?+delete",redo:["ctrl+y","ctrl+shift+z"]},Ar=e=>{var t=Tr[e],n=xr[e],r=Rr[e],i=t&&(0,Vn.isHotkey)(t),o=n&&(0,Vn.isHotkey)(n),s=r&&(0,Vn.isHotkey)(r);return e=>!(!i||!i(e))||(!!(nr&&o&&o(e))||!(nr||!s||!s(e)))};Ar("bold"),Ar("compose"),Ar("moveBackward"),Ar("moveForward"),Ar("deleteBackward"),Ar("deleteForward"),Ar("deleteLineBackward"),Ar("deleteLineForward"),Ar("deleteWordBackward"),Ar("deleteWordForward"),Ar("extendBackward"),Ar("extendForward"),Ar("extendLineBackward"),Ar("extendLineForward"),Ar("italic"),Ar("moveLineBackward"),Ar("moveLineForward"),Ar("moveWordBackward"),Ar("moveWordForward"),Ar("redo"),Ar("insertSoftBreak"),Ar("splitBlock"),Ar("transposeCharacter"),Ar("undo"),i.require_direction(),i.require_debounce(),i.require_throttle();function Or(e){return Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Or(e)}function Dr(e){var t=function(e,t){if("object"!==Or(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!==Or(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===Or(t)?t:String(t)}function Pr(e,t,n){return(t=Dr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Nr=(0,c.createContext)(null),Lr=kr,Mr={subtree:!0,childList:!0,characterData:!0,characterDataOldValue:!0},Ur=class extends c.Component{constructor(){super(...arguments),Pr(this,"context",null),Pr(this,"manager",null),Pr(this,"mutationObserver",null)}observe(){var e,{node:t}=this.props;if(!t.current)throw new Error("Failed to attach MutationObserver, `node` is undefined");null===(e=this.mutationObserver)||void 0===e||e.observe(t.current,Mr)}componentDidMount(){var{receivedUserInput:e}=this.props,t=this.context;this.manager=((e,t)=>{var n=[],r=()=>{n=[]};return{registerMutations:r=>{if(t.current){var i=r.filter(t=>Jn(e,t,r));n.push(...i)}},restoreDOM:function(){n.length>0&&(n.reverse().forEach(e=>{"characterData"!==e.type&&(e.removedNodes.forEach(t=>{e.target.insertBefore(t,e.nextSibling)}),e.addedNodes.forEach(t=>{e.target.removeChild(t)}))}),r())},clear:r}})(t,e),this.mutationObserver=new MutationObserver(this.manager.registerMutations),this.observe()}getSnapshotBeforeUpdate(){var e,t,n,r,i=null===(e=this.mutationObserver)||void 0===e?void 0:e.takeRecords();null!=i&&i.length&&(null===(r=this.manager)||void 0===r||r.registerMutations(i));return null===(t=this.mutationObserver)||void 0===t||t.disconnect(),null===(n=this.manager)||void 0===n||n.restoreDOM(),null}componentDidUpdate(){var e;null===(e=this.manager)||void 0===e||e.clear(),this.observe()}componentWillUnmount(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect()}render(){return this.props.children}};Pr(Ur,"contextType",Nr);parseInt(c.default.version.split(".")[0],10);var jr=Object.defineProperty,Ir=Object.defineProperties,Br=Object.getOwnPropertyDescriptors,Fr=Object.getOwnPropertySymbols,Vr=Object.prototype.hasOwnProperty,Wr=Object.prototype.propertyIsEnumerable,qr=(e,t,n)=>t in e?jr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Yr=(e,t)=>{for(var n in t||(t={}))Vr.call(t,n)&&qr(e,n,t[n]);if(Fr)for(var n of Fr(t))Wr.call(t,n)&&qr(e,n,t[n]);return e},Hr=new WeakMap;function Kr(e,t){if(!t.relativeSelection)return null;let n=Hr.get(e.children);n||(n=new WeakMap,Hr.set(e.children,n));let r=n.get(t);if(void 0===r)try{r=Dt(e.sharedRoot,e,t.relativeSelection),n.set(t,r)}catch(i){return null}return r}function zr(){const e=(()=>{var e=(0,c.useContext)(Nr);if(!e)throw new Error("The `useSlateStatic` hook must be used inside the <Slate> component's context.");return e})();if(!Yt.isCursorEditor(e))throw new Error("Cannot use useSyncExternalStore outside the context of a RemoteCursorEditor");return e}var $r=new WeakMap;function Gr(e){const t=$r.get(e);if(t)return t;const n=function(e){let t={};const n=new Set,r=n.add.bind(n),i=new Set;let o=null;return[t=>(i.add(t),o||(o=e=>{e.added.forEach(r),e.removed.forEach(r),e.updated.forEach(r),i.forEach(e=>e())},Yt.on(e,"change",o)),()=>{i.delete(t),o&&0===i.size&&(Yt.off(e,"change",o),o=null)}),()=>(0===n.size||(n.forEach(n=>{const r=Yt.cursorState(e,n);null!==r?t[n]=r:delete t[n.toString()]}),n.clear(),t=Yr({},t)),t)]}(e);return $r.set(e,n),n}function Xr(){const[e,t]=Gr(zr());return(0,m.useSyncExternalStore)(e,t)}function Qr(e,t,{yOffset:n,xOffset:r,shouldGenerateOverlay:o}){const[s,a]=i.Range.edges(t),c=function(e,t){try{return Lr.toDOMRange(e,t)}catch(n){return null}}(e,t);if(!c)return{caretPosition:null,selectionRects:[]};const l=[],d=i.Editor.nodes(e,{at:t,match:(e,t)=>i.Text.isText(e)&&(!o||o(e,t))});let u=null;const h=i.Range.isBackward(t);for(const[f,p]of d){const o=Lr.toDOMNode(e,f),d=i.Path.equals(p,s.path),g=i.Path.equals(p,a.path);let m=null;if(d||g){const e=document.createRange();e.selectNode(o),d&&e.setStart(c.startContainer,c.startOffset),g&&e.setEnd(c.endContainer,c.endOffset),m=e.getClientRects()}else m=o.getClientRects();const y=h?d:g;for(let e=0;e<m.length;e++){const o=m.item(e);if(!o)continue;const s=y&&(h?0===e:e===m.length-1),a=o.top-n,c=o.left-r;s&&(u={height:o.height,top:a,left:c+(h||i.Range.isCollapsed(t)?0:o.width)}),l.push({width:o.width,height:o.height,top:a,left:c})}}return{selectionRects:l,caretPosition:u}}var Jr=Object.freeze([]);function Zr(e={}){var t,n=e,{containerRef:r,shouldGenerateOverlay:i}=n,o=((e,t)=>{var n={};for(var r in e)Vr.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&Fr)for(var r of Fr(e))t.indexOf(r)<0&&Wr.call(e,r)&&(n[r]=e[r]);return n})(n,["containerRef","shouldGenerateOverlay"]);const s=zr(),a=Xr(),c=function(){const[,e]=(0,l.useReducer)(e=>e+1,0),t=(0,l.useRef)(null),n=()=>{t.current&&(cancelAnimationFrame(t.current),t.current=0)};return(0,l.useEffect)(n),(0,l.useEffect)(()=>n,[]),(0,l.useCallback)((n=!1)=>{n?e():t.current||(t.current=requestAnimationFrame(e))},[])}(),d=(0,l.useRef)(new WeakMap),[u,h]=(0,l.useState)({}),f=!("refreshOnResize"in o)||(null==(t=o.refreshOnResize)||t);return function(e,t){const n=(0,l.useRef)(t);n.current=t;const[r]=(0,l.useState)(()=>new ResizeObserver(()=>{n.current()}));(0,l.useEffect)(()=>{if(!(null==e?void 0:e.current))return;const{current:t}=e;return r.observe(t),()=>r.unobserve(t)},[r,e])}(f?r:void 0,()=>{d.current=new WeakMap,c("debounced"!==f)}),(0,l.useLayoutEffect)(()=>{var e,t,n;if(r&&!r.current)return;const o=null==(e=null==r?void 0:r.current)?void 0:e.getBoundingClientRect(),c=null!=(t=null==o?void 0:o.x)?t:0,l=null!=(n=null==o?void 0:o.y)?n:0;let f=Object.keys(u).length!==Object.keys(a).length;const p=Object.fromEntries(Object.entries(a).map(([e,t])=>{const n=t.relativeSelection&&Kr(s,t);if(!n)return[e,Jr];const r=d.current.get(n);if(r)return[e,r];const o=Qr(s,n,{xOffset:c,yOffset:l,shouldGenerateOverlay:i});return f=!0,d.current.set(n,o),[e,o]}));f&&h(p)}),[(0,l.useMemo)(()=>Object.entries(a).map(([e,t])=>{var n,r;const i=t.relativeSelection&&Kr(s,t),o=u[e];return a=Yr({},t),c={range:i,caretPosition:null!=(n=null==o?void 0:o.caretPosition)?n:null,selectionRects:null!=(r=null==o?void 0:o.selectionRects)?r:Jr},Ir(a,Br(c));var a,c}),[a,s,u]),(0,l.useCallback)(()=>{d.current=new WeakMap,c(!0)},[c])]}function ei(){return i.usePluginOption(Fn,"_isSynced")?(0,h.jsx)(ti,{}):null}function ti(){const e=i.useEditorContainerRef(),[t]=Zr({containerRef:e});return(0,h.jsx)(h.Fragment,{children:t.map(e=>(0,h.jsx)(ni,{...e},e.clientId))})}function ni({caretPosition:e,data:t,selectionRects:n}){if(!t)return null;const r={backgroundColor:(i=t.color,o=.5,i+Math.round(255*Math.min(Math.max(o,0),1)).toString(16).padStart(2,"0").toUpperCase())};var i,o;return(0,h.jsxs)(h.Fragment,{children:[n.map((e,t)=>(0,h.jsx)("div",{className:"pointer-events-none absolute",style:{...r,...e}},t)),e&&(0,h.jsx)(oi,{data:t,caretPosition:e})]})}var ri=.7,ii=1;function oi({caretPosition:e,data:t}){const[n,r]=l.useState(!1),i={...e,background:t?.color,opacity:ri,transition:"opacity 0.2s"},o={...i,opacity:ii},s={background:t?.color,opacity:ri,transform:"translateY(-100%)",transition:"opacity 0.2s"},a={...s,opacity:ii};return(0,h.jsx)("div",{className:"absolute w-0.5",style:n?o:i,children:(0,h.jsx)("div",{className:"absolute top-0 whitespace-nowrap rounded rounded-bl-none px-1.5 py-0.5 text-white text-xs",style:n?a:s,onMouseEnter:()=>{r(!0)},onMouseLeave:()=>{r(!1)},children:t?.name})})}function si({documentId:e,initialValue:t=i.EMPTY_PLATE_VALUE,user:n,authToken:r,className:o,renderToolbar:s,overlays:a}){const c=me("plate",e),d=n.color??_e(n.id),u=Boolean(r),f=i.usePlateEditor({plugins:u?[...i.platePlugins,Fn.configure({options:{cursors:{data:{color:d,name:n.name}},providers:we({documentId:e,token:r})},render:{afterEditable:ei}})]:i.platePlugins,skipInitialization:u,value:u?void 0:t},[c,u]);l.useEffect(()=>{if(u)return f.getApi(Fn).yjs.init({id:c,value:t}),()=>{f.getApi(Fn).yjs.destroy()}},[u,f,c]);const[,p]=l.useReducer(e=>e+1,0),g=l.useMemo(()=>f?We(f):S("plate"),[f]);return l.useEffect(()=>{p()},[f]),(0,h.jsx)("div",{className:`flex h-full min-h-0 w-full flex-col ${o??""}`,"data-room":c,children:(0,h.jsxs)(i.Plate,{editor:f,children:[s?s(g):(0,h.jsx)(O,{adapter:g}),(0,h.jsxs)(i.EditorContainer,{className:"relative min-h-0 flex-1",children:[(0,h.jsx)(i.Editor$1,{placeholder:"Start writing…",variant:"default"}),a]})]})})}exports.EMPTY_PLATE_VALUE=i.EMPTY_PLATE_VALUE,exports.FixedToolbar=i.FixedToolbar,exports.FixedToolbarButtons=i.FixedToolbarButtons,exports.FloatingToolbar=i.FloatingToolbar,exports.FloatingToolbarButtons=i.FloatingToolbarButtons,exports.MediaKit=i.MediaKit,exports.REASON_TOOLBAR=E,exports.REASON_TOOLBAR_SKIN=i.REASON_TOOLBAR_SKIN,exports.ROOM_PREFIX=ge,exports.ReasonPlateEditor=si,exports.ReasonPlaygroundEditor=function(e){return(0,h.jsx)(si,{...e,overlays:(0,h.jsx)(i.FloatingToolbar,{children:(0,h.jsx)(i.FloatingToolbarButtons,{})}),renderToolbar:()=>(0,h.jsx)(i.FixedToolbar,{className:i.REASON_TOOLBAR_SKIN,children:(0,h.jsx)(i.FixedToolbarButtons,{})})})},exports.ReasonSidebar=function({activeDocumentId:e,linkForDocument:n,onNavigate:r,className:i}){const[o,s]=l.useState([]),[a,c]=l.useState(null),[d,u]=l.useState(""),p=l.useCallback(()=>{s(U())},[]);l.useEffect(()=>(p(),F(p)),[p]);const g=()=>{a&&I(a,d),c(null)};return(0,h.jsxs)("nav",{"aria-label":"Documents",className:t.cn("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:[(0,h.jsxs)("div",{className:"flex items-center justify-between px-1 pb-2",children:[(0,h.jsx)("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-gray-400",children:"Documents"}),(0,h.jsx)("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:()=>{r(j().id)},type:"button",children:(0,h.jsx)(f.Plus,{className:"size-3.5"})})]}),o.map(i=>{const s=i.id===e,l=a===i.id;return(0,h.jsxs)("div",{className:t.cn("group flex items-center gap-1.5 rounded px-1.5 py-1 text-sm",s?"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:[(0,h.jsx)(f.FileText,{className:"size-3.5 shrink-0 opacity-60"}),l?(0,h.jsx)("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:g,onChange:e=>u(e.target.value),onKeyDown:e=>{"Enter"===e.key&&g(),"Escape"===e.key&&c(null)},value:d}):(0,h.jsx)("a",{className:"min-w-0 flex-1 truncate",href:n(i.id),children:i.title}),!l&&(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-0.5 group-hover:flex",children:[(0,h.jsx)("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),u(e.title)})(i),type:"button",children:(0,h.jsx)(f.Pencil,{className:"size-3"})}),(0,h.jsx)("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(B(t.id),t.id!==e)return;const n=o.find(e=>e.id!==t.id);r(n?n.id:j().id)})(i),type:"button",children:(0,h.jsx)(f.Trash2,{className:"size-3"})})]})]},i.id)}),0===o.length&&(0,h.jsx)("p",{className:"px-1.5 py-2 text-xs text-gray-400",children:"No documents yet."})]})},exports.ReasonTiptapEditor=function({documentId:e,initialContent:t="",user:n,authToken:i,className:o}){const[s,c]=l.useState(null),[d,u]=l.useState(null),f=me("tiptap",e),p=n.color??_e(n.id);l.useEffect(()=>{if(!i)return;const t=be({engine:"tiptap",documentId:e,token:i});return u(t),()=>{u(null),t.destroy()}},[i,e]);const g=l.useMemo(()=>{const e=r.buildExtensions(r.createDefaultConfig());return d?function(e,t,n){return[...e.filter(e=>"undoRedo"!==e?.name),a.Collaboration.configure({document:t.ydoc}),Oe.configure({provider:t.provider,user:n})]}(e,d,{name:n.name,color:p}):e},[d,n.name,p]),m=l.useMemo(()=>s?xe(s):S("tiptap"),[s]);return(0,h.jsx)("div",{className:`flex h-full min-h-0 w-full flex-col ${o??""}`,"data-room":f,children:(0,h.jsx)(r.NovelEditor,{className:"flex min-h-0 flex-1 flex-col",extensions:g,immediatelyRender:!1,initialContent:d?void 0:t,onEditor:c,rebuildKey:d?`collab:${f}`:"local",textDirection:"auto",children:({EditorSurface:e})=>(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(O,{adapter:m}),(0,h.jsx)("div",{className:"relative min-h-0 flex-1 overflow-auto",children:(0,h.jsx)(e,{className:"h-full"})})]})})})},exports.ReasonToolbar=O,exports.SIDEBAR_DOCUMENTS_STORAGE_KEY=D,exports.collaborationRoom=me,exports.collectToolbarCommands=function e(t=E){const n=[];for(const r of t)"button"===r.kind&&n.push(r.id),"menu"===r.kind&&n.push(...e(r.children));return n},exports.createCollaborationSession=be,exports.createNullAdapter=S,exports.createPlateAdapter=We,exports.createSidebarDocument=j,exports.createTiptapAdapter=xe,exports.cursorColorFor=_e,exports.deleteSidebarDocument=B,exports.hocuspocusUrl=ye,exports.htmlToPlateValue=i.htmlToPlateValue,exports.listSidebarDocuments=U,exports.parseCollaborationRoom=function(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},exports.plateBasePlugins=i.plateBasePlugins,exports.platePlugins=i.platePlugins,exports.plateValueToHtml=i.plateValueToHtml,exports.plateYjsProviders=we,exports.renameSidebarDocument=I,exports.subscribeSidebarDocuments=F;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./rolldown-runtime-BeavJI0R.cjs"),t=require("./dist-2-kjLBhJ.cjs"),n=require("./tooltip-DSRLxJD_.cjs"),r=require("./editorConfig-CHBSp2KG.cjs"),i=require("./reason-toolbar-skin-CD4T53He.cjs"),o=require("./dropdown-menu-BNKyUimd.cjs"),s=require("./Transcribe.cjs"),a=require("./dist-D4Q5o5oU.cjs");let c=require("react"),l=e.__toESM(c,1);c=e.__toESM(c);let d=require("@tiptap/core"),u=require("@tiptap/pm/state"),h=require("react/jsx-runtime"),f=require("lucide-react"),p=require("react-dom");p=e.__toESM(p);let g=require("scroll-into-view-if-needed");g=e.__toESM(g);let m=require("use-sync-external-store/shim");require("use-sync-external-store/shim/with-selector");let y=require("use-voice-control/client");var b=class extends a.Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=a.getUnixTime();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&&w(this,t,"timeout")},a.floor(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:a.getUnixTime()});const o=[],s=[],c=[],l=[];null===e?l.push(t):null==i?null!=e&&o.push(t):(s.push(t),a.equalityDeep(i,e)||c.push(t)),(o.length>0||c.length>0||l.length>0)&&this.emit("change",[{added:o,updated:c,removed:l},"local"]),this.emit("update",[{added:o,updated:s,removed:l},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},w=(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:a.getUnixTime()})}r.push(n)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},v=(e,t,n=e.states)=>{const r=t.length,i=a.createEncoder();a.writeVarUint(i,r);for(let o=0;o<r;o++){const r=t[o],s=n.get(r)||null,c=e.meta.get(r).clock;a.writeVarUint(i,r),a.writeVarUint(i,c),a.writeVarString(i,JSON.stringify(s))}return a.toUint8Array(i)},_=(e,t,n)=>{const r=a.createDecoder(t),i=a.getUnixTime(),o=[],s=[],c=[],l=[],d=a.readVarUint(r);for(let u=0;u<d;u++){const t=a.readVarUint(r);let n=a.readVarUint(r);const d=JSON.parse(a.readVarString(r)),u=e.meta.get(t),h=e.states.get(t),f=void 0===u?0:u.clock;(f<n||f===n&&null===d&&e.states.has(t))&&(null===d?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,d),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===u&&null!==d?o.push(t):void 0!==u&&null===d?l.push(t):null!==d&&(a.equalityDeep(d,h)||c.push(t),s.push(t)))}(o.length>0||c.length>0||l.length>0)&&e.emit("change",[{added:o,updated:c,removed:l},n]),(o.length>0||s.length>0||l.length>0)&&e.emit("update",[{added:o,updated:s,removed:l},n])};function S(e){return{engine:e,execute(){},isActive:()=>!1,isEnabled:()=>!1,getValue(){},subscribe:()=>()=>{}}}var E=[{kind:"button",id:"undo",label:"Undo",icon:f.Undo2,shortcut:"⌘Z"},{kind:"button",id:"redo",label:"Redo",icon:f.Redo2,shortcut:"⇧⌘Z"},{kind:"separator",id:"history-divider"},{kind:"button",id:"bold",label:"Bold",icon:f.Bold,shortcut:"⌘B"},{kind:"button",id:"italic",label:"Italic",icon:f.Italic,shortcut:"⌘I"},{kind:"button",id:"underline",label:"Underline",icon:f.Underline,shortcut:"⌘U"},{kind:"button",id:"highlight",label:"Highlight",icon:f.Highlighter,shortcut:"⌘⇧H"},{kind:"separator",id:"marks-divider"},{kind:"menu",id:"block-format",label:"Block Format",icon:f.Rows3,children:[{kind:"button",id:"paragraph",label:"Paragraph",icon:f.Pilcrow},{kind:"button",id:"heading-1",label:"Heading 1",icon:f.Heading1,shortcut:"Ctrl+Alt+1"},{kind:"button",id:"heading-2",label:"Heading 2",icon:f.Heading2,shortcut:"Ctrl+Alt+2"},{kind:"button",id:"heading-3",label:"Heading 3",icon:f.Heading3,shortcut:"Ctrl+Alt+3"},{kind:"button",id:"heading-4",label:"Heading 4",icon:f.Heading4,shortcut:"Ctrl+Alt+4"},{kind:"button",id:"heading-5",label:"Heading 5",icon:f.Heading5,shortcut:"Ctrl+Alt+5"},{kind:"button",id:"heading-6",label:"Heading 6",icon:f.Heading6,shortcut:"Ctrl+Alt+6"},{kind:"separator",id:"block-format-lists-divider"},{kind:"button",id:"bullet-list",label:"Bullet List",icon:f.List,shortcut:"Ctrl+Shift+8"},{kind:"button",id:"ordered-list",label:"Ordered List",icon:f.ListOrdered,shortcut:"Ctrl+Shift+7"},{kind:"button",id:"task-list",label:"Check List",icon:f.ListChecks,shortcut:"Ctrl+Shift+9"},{kind:"separator",id:"block-format-quote-divider"},{kind:"button",id:"blockquote",label:"Blockquote",icon:f.Quote,shortcut:"Ctrl+Shift+B"},{kind:"button",id:"code-block",label:"Code Block",icon:f.Code2,shortcut:"Ctrl+Alt+C"},{kind:"separator",id:"block-format-clear-divider"},{kind:"button",id:"clear-formatting",label:"Clear Format",icon:f.Eraser}]},{kind:"menu",id:"text-styles",label:"Text Styles",icon:f.Type,children:[{kind:"group-label",id:"text-styles-label",label:"Text Styles"},{kind:"button",id:"strike",label:"Strikethrough",icon:f.Strikethrough,shortcut:"Ctrl+Shift+S"},{kind:"button",id:"code",label:"Inline Code",icon:f.Code,shortcut:"Ctrl+E"},{kind:"button",id:"text-color",label:"Text Color",icon:f.Baseline,shortcut:"Alt+Shift+C"},{kind:"button",id:"superscript",label:"Superscript",icon:f.Superscript,shortcut:"Ctrl+."},{kind:"button",id:"subscript",label:"Subscript",icon:f.Subscript,shortcut:"Ctrl+,"},{kind:"separator",id:"text-styles-indent-divider"},{kind:"button",id:"indent",label:"Indent",icon:f.IndentIncrease},{kind:"button",id:"outdent",label:"Outdent",icon:f.IndentDecrease},{kind:"menu",id:"alignment",label:"Alignment",icon:f.AlignLeft,children:[{kind:"button",id:"align-left",label:"Align Left",icon:f.AlignLeft},{kind:"button",id:"align-center",label:"Align Center",icon:f.AlignCenter},{kind:"button",id:"align-right",label:"Align Right",icon:f.AlignRight},{kind:"button",id:"align-justify",label:"Justify",icon:f.AlignJustify}]}]},{kind:"menu",id:"insert",label:"Insert",icon:f.Plus,children:[{kind:"group-label",id:"insert-label",label:"Insert"},{kind:"button",id:"link",label:"Link",icon:f.Link2},{kind:"button",id:"emoji",label:"Emoji",icon:f.Smile},{kind:"button",id:"table",label:"Table",icon:f.Table2},{kind:"button",id:"image",label:"Image",icon:f.Image},{kind:"button",id:"columns",label:"Columns",icon:f.Columns2,shortcut:"Ctrl+Alt+G"},{kind:"button",id:"callout",label:"Callout",icon:f.Info},{kind:"button",id:"horizontal-rule",label:"Divider",icon:f.Minus,shortcut:"Ctrl+Alt+S"},{kind:"button",id:"video",label:"Video",icon:f.Video},{kind:"button",id:"math",label:"Math",icon:f.Sigma}]},{kind:"separator",id:"voice-divider"},{kind:"button",id:"transcribe",label:"Dictate",icon:f.Mic,shortcut:"Ctrl+Shift+D"},{kind:"menu",id:"table-tools",label:"Table",icon:f.Table2,visibleWhenActive:"table",children:[{kind:"group-label",id:"table-rows-label",label:"Rows"},{kind:"button",id:"table.add-row-before",label:"Insert Row Above",icon:f.Rows3},{kind:"button",id:"table.add-row-after",label:"Insert Row Below",icon:f.Rows3},{kind:"button",id:"table.delete-row",label:"Delete Row",icon:f.Trash2},{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:f.Columns2},{kind:"button",id:"table.add-column-after",label:"Insert Column Right",icon:f.Columns2},{kind:"button",id:"table.delete-column",label:"Delete Column",icon:f.Trash2},{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:f.Braces},{kind:"button",id:"table.split-cell",label:"Split Cell",icon:f.Braces},{kind:"button",id:"table.toggle-header-row",label:"Toggle Header Row",icon:f.Rows3},{kind:"separator",id:"table-delete-divider"},{kind:"button",id:"table.delete",label:"Delete Table",icon:f.Trash2}]}];var C="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",k="bg-gray-200 text-gray-900 dark:bg-slate-700 dark:text-white",T="flex w-full cursor-pointer items-center gap-2 text-xs data-disabled:cursor-not-allowed data-disabled:opacity-40";function x({shortcut:e}){return e?(0,h.jsx)("span",{className:"ml-auto pl-4 text-[10px] tracking-widest text-gray-400 dark:text-gray-500",children:e}):null}function R({items:e,adapter:n}){return(0,h.jsx)(h.Fragment,{children:e.map(e=>{if("separator"===e.kind)return(0,h.jsx)(o.DropdownMenuSeparator,{},e.id);if("group-label"===e.kind)return(0,h.jsx)(o.DropdownMenuLabel,{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 t=e.icon;return(0,h.jsxs)(o.DropdownMenuSub,{children:[(0,h.jsxs)(o.DropdownMenuSubTrigger,{className:T,children:[(0,h.jsx)(t,{className:"size-3.5 shrink-0 text-gray-500 dark:text-gray-400"}),e.label]}),(0,h.jsx)(o.DropdownMenuPortal,{children:(0,h.jsx)(o.DropdownMenuSubContent,{className:"min-w-[200px]",children:(0,h.jsx)(R,{items:e.children,adapter:n})})})]},e.id)}const r=e.icon,i=n.isActive(e.id);return(0,h.jsxs)(o.DropdownMenuItem,{"aria-pressed":i,className:t.cn(T,i&&k),"data-command":e.id,"data-state":i?"active":"inactive",disabled:!n.isEnabled(e.id),onSelect:()=>{n.execute(e.id)},children:[(0,h.jsx)(r,{className:"size-3.5 shrink-0 text-gray-500 dark:text-gray-400"}),(0,h.jsx)("span",{className:"truncate",children:e.label}),(0,h.jsx)(x,{shortcut:e.shortcut})]},e.id)})})}function A({item:e,adapter:r}){if("separator"===e.kind)return(0,h.jsx)("div",{className:"mx-1 h-5 w-px bg-gray-200 dark:bg-slate-700"});if("group-label"===e.kind)return(0,h.jsx)("span",{className:"px-1 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:e.label});if("menu"===e.kind){if(e.visibleWhenActive&&!r.isActive(e.visibleWhenActive))return null;const i=e.icon;return(0,h.jsxs)(o.DropdownMenu,{children:[(0,h.jsxs)(n.Tooltip,{children:[(0,h.jsx)(n.TooltipTrigger,{asChild:!0,children:(0,h.jsx)(o.DropdownMenuTrigger,{"aria-label":e.label,className:t.cn(C,"data-[state=open]:bg-gray-200 dark:data-[state=open]:bg-slate-700"),"data-menu":e.id,children:(0,h.jsx)(i,{className:"size-4"})})}),(0,h.jsx)(n.TooltipContent,{side:"bottom",children:e.label})]}),(0,h.jsx)(o.DropdownMenuContent,{align:"start",className:"min-w-[240px]",children:(0,h.jsx)(R,{items:e.children,adapter:r})})]})}const i=e.icon,s=r.isActive(e.id),a=r.isEnabled(e.id);return(0,h.jsxs)(n.Tooltip,{children:[(0,h.jsx)(n.TooltipTrigger,{asChild:!0,children:(0,h.jsx)("button",{"aria-label":e.label,"aria-pressed":s,className:t.cn(C,s&&k),"data-command":e.id,"data-state":s?"active":"inactive",disabled:!a,onClick:()=>{r.execute(e.id)},type:"button",children:(0,h.jsx)(i,{className:"size-4"})})}),(0,h.jsxs)(n.TooltipContent,{side:"bottom",children:[e.label,e.shortcut?(0,h.jsx)("span",{className:"ml-2 text-[10px] tracking-widest opacity-70",children:e.shortcut}):null]})]})}function O({adapter:e,items:r=E,className:i,children:o}){return function(e){const[t,n]=l.useState(0);l.useEffect(()=>{if(e.subscribe)return e.subscribe(()=>n(e=>e+1))},[e])}(e),(0,h.jsx)(n.TooltipProvider,{delayDuration:300,children:(0,h.jsxs)("div",{className:t.cn("flex flex-wrap items-center gap-0.5 border-b border-gray-200 px-2 py-1 dark:border-slate-700",i),"data-engine":e.engine,role:"toolbar",children:[r.map(t=>(0,h.jsx)(A,{adapter:e,item:t},(t.kind,t.id))),o?(0,h.jsx)("div",{className:"ml-auto flex items-center gap-1",children:o}):null]})})}var D="REASON-documents",P="reason-documents-changed";function N(){if("undefined"==typeof window)return[];try{const e=window.localStorage.getItem(D);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function L(e){"undefined"!=typeof window&&(window.localStorage.setItem(D,JSON.stringify(e)),window.dispatchEvent(new Event(P)))}function M(e){return{id:e.id,title:e.title?.trim()||"Untitled Document"}}function U(){return N().filter(e=>!e.isFolder&&!e.isDeleted&&!e.parentId).map(M)}function j(e="Untitled Document"){const t={id:`doc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,title:e,content:"",parentId:null};return L([...N(),t]),M(t)}function I(e,t){const n=t.trim()||"Untitled Document";L(N().map(t=>t.id===e?{...t,title:n}:t))}function B(e){L(N().map(t=>t.id===e?{...t,isDeleted:!0}:t))}function F(e){if("undefined"==typeof window)return()=>{};const t=t=>{"REASON-documents"===t.key&&e()};return window.addEventListener(P,e),window.addEventListener("storage",t),()=>{window.removeEventListener(P,e),window.removeEventListener("storage",t)}}var V=function(e){return e[e.Token=0]="Token",e[e.PermissionDenied=1]="PermissionDenied",e[e.Authenticated=2]="Authenticated",e}({}),W=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var q=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 Y(e){return new Promise(t=>setTimeout(t,e))}function H(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 K(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 s of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const e=n[s];if(!Number.isInteger(e)||e<0)throw new Error(`Value for ${s} 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||H;const o=n.calculateDelay?n.calculateDelay(r,n):n.initialDelay;if(o&&await Y(o),r.attemptNum<1&&n.initialJitter){const e=i(r,n);e&&await Y(e)}return async function t(){if(n.beforeAttempt&&n.beforeAttempt(r,n),r.aborted){const e=new Error("Attempt aborted");throw e.code="ATTEMPT_ABORTED",e}const o=async e=>{if(n.handleError&&await n.handleError(e,r,n),r.aborted||0===r.attemptsRemaining)throw e;r.attemptNum++;const o=i(r,n);return o&&await Y(o),t()};return r.attemptsRemaining>0&&r.attemptsRemaining--,n.timeout?new Promise((t,i)=>{const s=setTimeout(()=>{if(n.handleTimeout)try{t(n.handleTimeout(r,n))}catch(e){i(e)}else{const e=new Error(`Retry timeout (attemptNum: ${r.attemptNum}, timeout: ${n.timeout})`);e.code="ATTEMPT_TIMEOUT",i(e)}},n.timeout);e(r,n).then(e=>{clearTimeout(s),t(e)}).catch(e=>{clearTimeout(s),o(e).then(t).catch(i)})}):e(r,n).catch(o)}()}var z=(e,t)=>{a.writeVarUint(e,0);const n=a.encodeStateVector(t);a.writeVarUint8Array(e,n)},$=(e,t,n)=>{a.writeVarUint(e,1),a.writeVarUint8Array(e,a.encodeStateAsUpdate(t,n))},G=(e,t,n,r)=>{try{a.applyUpdate(t,a.readVarUint8Array(e),n)}catch(i){null!=r&&r(i)}},X=(e,t)=>{a.writeVarUint(e,2),a.writeVarUint8Array(e,t)},Q=G,J=(e,t,n,r,i)=>{const o=a.readVarUint(e);switch(o){case 0:((e,t,n)=>{$(t,n,a.readVarUint8Array(e))})(e,t,n);break;case 1:G(e,n,r,i);break;case 2:Q(e,n,r,i);break;default:throw new Error("Unknown message type")}return o},Z=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={}}},ee=class{constructor(e){this.data=e,this.encoder=a.createEncoder(),this.decoder=a.createDecoder(new Uint8Array(this.data))}peekVarString(){return a.peekVarString(this.decoder)}readVarUint(){return a.readVarUint(this.decoder)}readVarString(){return a.readVarString(this.decoder)}readVarUint8Array(){return a.readVarUint8Array(this.decoder)}writeVarUint(e){return a.writeVarUint(this.encoder,e)}writeVarString(e){return a.writeVarString(this.encoder,e)}writeVarUint8Array(e){return a.writeVarUint8Array(this.encoder,e)}length(){return a.length(this.encoder)}},te=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}({}),ne=function(e){return e.Connecting="connecting",e.Connected="connected",e.Disconnected="disconnected",e}({}),re=class{constructor(){this.encoder=a.createEncoder()}get(e){return e.encoder}toUint8Array(){return a.toUint8Array(this.encoder)}},ie=class extends re{constructor(...e){super(...e),this.type=te.CLOSE,this.description="Ask the server to close the connection"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),this.encoder}},oe=class e extends Z{static{this.DEDUPLICATABLE_TYPES=new Set([te.Awareness,te.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:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=ne.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=ne.Connected,this.emit("status",{status:ne.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===ne.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===ne.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){const t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(ie,{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===ne.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:K(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=ne.Connecting,this.emit("status",{status:ne.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=a.getUnixTime();const t=new Uint8Array(e.data);if(1===t.length&&t[0]===te.Ping)return void this.sendPong();const n=new ee(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){const e=a.createEncoder();a.writeVarUint(e,te.Pong),this.send(a.toUint8Array(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=ne.Connected,this.emit("status",{status:ne.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===ne.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=a.getUnixTime()-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=a.createDecoder(e);return{documentName:a.readVarString(t),messageType:a.readVarUint(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===q.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=ne.Disconnected,this.emit("status",{status:ne.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()}},se=class{constructor(e){this.message=e}apply(e,t){const{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case te.Sync:this.applySyncMessage(e,t);break;case te.Awareness:this.applyAwarenessMessage(e);break;case te.Auth:this.applyAuthMessage(e);break;case te.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case te.Stateless:e.receiveStateless(a.readVarString(n.decoder));break;case te.SyncStatus:this.applySyncStatusMessage(e,1===a.readVarInt(n.decoder));break;case te.CLOSE:{const t={code:1e3,reason:a.readVarString(n.decoder)};e.onClose(),e.configuration.onClose({event:t}),e.forwardClose({event:t});break}}n.length()>i+1&&e.send(re,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(te.Sync);const r=J(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.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;((e,t,n,r)=>{switch(a.readVarUint(e)){case V.Token:t();break;case V.PermissionDenied:n(a.readVarString(e));break;case V.Authenticated:r(a.readVarString(e))}})(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(te.Awareness),t.writeVarUint8Array(v(e.awareness,Array.from(e.awareness.getStates().keys())))}},ae=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return a.toUint8Array(this.encoder)}send(e){e?.send(this.create())}},ce=class extends re{constructor(...e){super(...e),this.type=te.Auth,this.description="Authentication"}get(e){if(void 0===e.token)throw new Error("The authentication message requires `token` as an argument.");var t,n;return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),t=this.encoder,n=e.token,a.writeVarUint(t,V.Token),a.writeVarString(t,n),a.writeVarString(this.encoder,"4.4.0"),this.encoder}},le=class extends re{constructor(...e){super(...e),this.type=te.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 a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),t=void 0===e.states?v(e.awareness,e.clients):v(e.awareness,e.clients,e.states),a.writeVarUint8Array(this.encoder,t),this.encoder}},de=class extends re{constructor(...e){super(...e),this.type=te.Stateless,this.description="A stateless message"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),a.writeVarString(this.encoder,e.payload??""),this.encoder}},ue=class extends re{constructor(...e){super(...e),this.type=te.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 a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),z(this.encoder,e.document),this.encoder}},he=class extends re{constructor(...e){super(...e),this.type=te.Sync,this.description="A document update"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),X(this.encoder,e.update),this.encoder}},fe=class extends Error{constructor(...e){super(...e),this.code=1001}},pe=class extends Z{get effectiveName(){return this.configuration.sessionAwareness?(e=this.configuration.name,t=this.sessionId,e+"\0"+t):this.configuration.name;var e,t}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=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 a.Doc,this.configuration.awareness=void 0!==e.awareness?e.awareness:new b(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:W(this.awareness.getStates())})}),this.awareness?.on("change",()=>{this.emit("awarenessChange",{states:W(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 oe(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(ue,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&w(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(de,{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(ce,{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(he,{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){const i=e.concat(t).concat(n);if(this.batchingEnabled){for(const e of i)this.pendingAwarenessClients.add(e);this.scheduleFlush()}else this.send(le,{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]:a.mergeUpdates(this.pendingUpdates);this.pendingUpdates=[],this.send(he,{update:e,documentName:this.effectiveName})}if(this.pendingAwarenessClients.size>0){const e=Array.from(this.pendingAwarenessClients);this.pendingAwarenessClients.clear(),this.send(le,{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(ue,{document:this.document,documentName:this.effectiveName}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(le,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;const n=new ae(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new ee(e.data),{documentName:n}=function(e){const t=e.indexOf("\0");return-1===t?{documentName:e,sessionId:null}:{documentName:e.substring(0,t),sessionId:e.substring(t+1)}}(t.readVarString());t.writeVarString(this.effectiveName),this.emit("message",{event:e,message:new ee(e.data)}),new se(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&&w(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&&(w(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 fe(`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)}},ge="reason-editor";function me(e,t){if(!t)throw new Error("collaborationRoom: documentId is required");return`${ge}:${e}:${t}`}function ye(){return"undefined"!=typeof process&&(process.env.NEXT_PUBLIC_HOCUSPOCUS_URL??process.env.VITE_HOCUSPOCUS_URL)||"ws://127.0.0.1:1234"}function be({engine:e,documentId:t,token:n,url:r=ye(),onSynced:i}){const o=me(e,t),s=new a.Doc,c=new pe({document:s,name:o,token:n,url:r,onSynced:()=>i?.(!0)});return{room:o,ydoc:s,provider:c,destroy(){c.destroy(),s.destroy()}}}function we({documentId:e,token:t,url:n=ye()}){const r=me("plate",e);return[{type:"hocuspocus",options:{name:r,token:t,url:n}},{type:"indexeddb",options:{docName:r}}]}var ve=["#e11d48","#0891b2","#7c3aed","#ea580c","#16a34a","#2563eb","#db2777","#ca8a04"];function _e(e){let t=0;for(let n=0;n<e.length;n++)t=31*t+e.charCodeAt(n)|0;return ve[Math.abs(t)%ve.length]}var Se={bold:"bold",italic:"italic",underline:"underline",strike:"strike",code:"code",superscript:"superscript",subscript:"subscript",highlight:"highlight","text-color":"textStyle"},Ee={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"}},Ce={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},ke={"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 Te(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function xe(e){return{engine:"tiptap",execute(t,n){!function(e,t,n){const r=()=>e.chain().focus(),i=e.commands,o=ke[t];if(o)return void r()[o]?.().run();const s=Ce[t];if(s)r().setTextAlign?.(s).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=Te(n,"Link URL");if(!e)return;return void r().extendMarkRange("link").setLink({href:e}).run()}case"image":{const e=Te(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=Te(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=Ce[t];if(n)return e.isActive({textAlign:n});const r=Ee[t];if(r)return e.isActive(r.name,r.attrs);const i=Se[t];return i?"text-color"===t?!!e.getAttributes("textStyle").color:e.isActive(i):"link"===t?e.isActive("link"):"transcribe"===t&&!!s.getTranscribeStorage(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(0,y.isTranscriptionSupported)();const r=ke[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=s.subscribeTranscribe(e,t);return()=>{e.off("transaction",t),e.off("selectionUpdate",t),n()}}}}var Re=e=>Array.from(e.entries()).map(([e,t])=>t&&t.user?{clientId:e,...t.user}:{clientId:e}),Ae=()=>null,Oe=d.Extension.create({name:"collaborationCaret",priority:999,addOptions:()=>({provider:null,user:{name:null,color:null},render:e=>{const t=document.createElement("span");t.classList.add("collaboration-carets__caret"),t.setAttribute("style",`border-color: ${e.color}`);const n=document.createElement("div");return n.classList.add("collaboration-carets__label"),n.setAttribute("style",`background-color: ${e.color}`),n.insertBefore(document.createTextNode(e.name),null),t.insertBefore(n,null),t},selectionRender:a.defaultSelectionBuilder,onUpdate:Ae}),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 u.Plugin({key:new u.PluginKey("collaborationCaretAwarenessListener"),view:()=>{const r=()=>{t.users=Re(e.awareness.states)};return e.awareness.setLocalStateField("user",n),t.users=Re(e.awareness.states),e.awareness.on("update",r),{destroy:()=>{e.awareness.off("update",r),t.users=[]}}}}),a.yCursorPlugin(e.awareness,{cursorBuilder:this.options.render,selectionBuilder:this.options.selectionRender})]}});var De={bold:i.KEYS.bold,italic:i.KEYS.italic,underline:i.KEYS.underline,strike:i.KEYS.strikethrough,code:i.KEYS.code,superscript:i.KEYS.sup,subscript:i.KEYS.sub,highlight:i.KEYS.highlight,"text-color":i.KEYS.color},Pe={superscript:i.KEYS.sub,subscript:i.KEYS.sup},Ne={paragraph:i.KEYS.p,"heading-1":i.KEYS.h1,"heading-2":i.KEYS.h2,"heading-3":i.KEYS.h3,"heading-4":i.KEYS.h4,"heading-5":i.KEYS.h5,"heading-6":i.KEYS.h6,blockquote:i.KEYS.blockquote},Le={"bullet-list":i.ListStyleType.Disc,"ordered-list":i.ListStyleType.Decimal,"task-list":i.KEYS.listTodo},Me={"bullet-list":[i.ListStyleType.Disc,i.ListStyleType.Circle,i.ListStyleType.Square],"ordered-list":[i.ListStyleType.Decimal,i.ListStyleType.LowerAlpha,i.ListStyleType.UpperAlpha,i.ListStyleType.LowerRoman,i.ListStyleType.UpperRoman],"task-list":[i.KEYS.listTodo]},Ue={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},je=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 Ie(e){return!!e.selection&&Boolean(i.getTableAbove(e))}function Be(e){if(!Ie(e))return{canMerge:!1,canSplit:!1};const t=i.getSelectedCellEntries(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:o,minRow:s}=i.getSelectedCellsBoundingBox(e,n),a=n.reduce((e,t)=>e+i.getColSpan(t)*i.getRowSpan(t),0)===(t-o+1)*(r-s+1);return{canMerge:e.api.isExpanded()&&a,canSplit:!1}}const[r]=n;return{canMerge:!1,canSplit:i.getColSpan(r)>1||i.getRowSpan(r)>1}}function Fe(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function Ve(e,t){const n=function(e){if(je.has(e)||"table"===e)return i.KEYS.table;switch(e){case"highlight":return i.KEYS.highlight;case"text-color":return i.KEYS.color;case"link":return i.KEYS.link;case"image":return i.KEYS.img;case"video":return i.KEYS.video;case"math":return i.KEYS.equation;case"callout":return i.KEYS.callout;case"columns":return i.KEYS.columnGroup;case"transcribe":return"transcribe";case"emoji":return i.KEYS.emoji;case"code-block":return i.KEYS.codeBlock;case"bullet-list":case"ordered-list":case"task-list":return i.KEYS.list;case"indent":case"outdent":return i.KEYS.indent;case"align-left":case"align-center":case"align-right":case"align-justify":return i.KEYS.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?(0,y.isTranscriptionSupported)()&&!e.api.isReadOnly?.():"table.merge-cells"===t?Be(e).canMerge:"table.split-cell"===t?Be(e).canSplit:je.has(t)?Ie(e):!e.api.isReadOnly?.())}function We(e){return{engine:"plate",execute(t,n){!function(e,t,n){e.tf.focus();const r=De[t];if(r&&"text-color"!==t&&"highlight"!==t)return void e.tf.toggleMark(r,{remove:Pe[t]});const o=Ne[t];if(o)return void e.tf.toggleBlock(o,o===i.KEYS.blockquote?{wrap:!0}:void 0);const s=Le[t];if(s)return void i.toggleList(e,{listStyleType:s});const a=Ue[t];if(a)e.getTransforms(i.TextAlignPlugin).textAlign.setNodes(a);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.KEYS.color]===t?e.tf.removeMarks(i.KEYS.color):e.tf.addMarks({[i.KEYS.color]:t}))}case"highlight":return void(e.api.marks()?.[i.KEYS.highlight]?e.tf.removeMarks(i.KEYS.highlight):e.tf.addMarks({[i.KEYS.highlight]:n?.value??"#fde047"}));case"clear-formatting":return e.tf.removeMarks(Object.values(De)),void e.tf.toggleBlock(i.KEYS.p);case"code-block":return void i.toggleCodeBlock(e);case"link":return void(n?.value?i.upsertLink(e,{url:n.value}):i.triggerFloatingLink(e,{focused:!0}));case"image":{const t=Fe(n,"Image URL");if(!t)return;return void i.insertImage(e,t)}case"video":{const t=Fe(n,"Video URL");if(!t)return;return void i.insertMedia(e,{select:!0,type:i.KEYS.video,url:t})}case"table":return void i.insertTable(e,{colCount:3,rowCount:3},{select:!0});case"horizontal-rule":return void e.tf.insertNodes({children:[{text:""}],type:i.KEYS.hr});case"emoji":return void e.tf.insertText(":");case"math":return void i.insertEquation(e,{select:!0});case"callout":return void i.insertCallout(e,{select:!0});case"columns":return void i.insertColumnGroup(e,{columns:2,select:!0});case"transcribe":return void i.getTranscribeController(e).toggle();case"indent":return void i.indent(e);case"outdent":return void i.outdent(e);case"table.add-row-before":return void i.insertTableRow(e,{before:!0});case"table.add-row-after":return void i.insertTableRow(e);case"table.delete-row":return void i.deleteRow(e);case"table.add-column-before":return void i.insertTableColumn(e,{before:!0});case"table.add-column-after":return void i.insertTableColumn(e);case"table.delete-column":return void i.deleteColumn(e);case"table.merge-cells":return void i.mergeTableCells(e);case"table.split-cell":return void i.splitTableCell(e);case"table.toggle-header-row":{const t=i.getTableAbove(e);if(!t)return;const[n,r]=t;return void e.tf.setNodes({headerRow:!n.headerRow},{at:r})}case"table.delete":return void i.deleteTable(e);default:;}}(e,t,n)},isActive(t){if("transcribe"===t)return i.getTranscribeController(e).getState().listening;if(!e.selection)return!1;try{return function(e,t){if("task-list"===t)return i.someTodoList(e);const n=Me[t];if(n)return i.someList(e,n);const r=De[t];if(r)return Boolean(e.api.marks()?.[r]);const o=Ne[t];if(o)return e.api.some({match:{type:o}});if("code-block"===t)return e.api.some({match:{type:i.KEYS.codeBlock}});if("table"===t)return Ie(e);if("callout"===t)return e.api.some({match:{type:i.KEYS.callout}});if("columns"===t)return e.api.some({match:{type:i.KEYS.column}});if("link"===t)return e.api.some({match:{type:i.KEYS.link}});if("transcribe"===t)return i.getTranscribeController(e).getState().listening;const s=Ue[t];return!!s&&e.api.some({match:e=>e[i.KEYS.textAlign]===s})}(e,t)}catch{return!1}},isEnabled(t){try{return Ve(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.KEYS.color]:"highlight"===t?n?.[i.KEYS.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 o=i.getTranscribeController(e).subscribe(t);return()=>{e.apply=n,o()}}}}var qe=Object.defineProperty,Ye=Object.defineProperties,He=Object.getOwnPropertyDescriptors,Ke=Object.getOwnPropertySymbols,ze=Object.prototype.hasOwnProperty,$e=Object.prototype.propertyIsEnumerable,Ge=(e,t,n)=>t in e?qe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Xe=(e,t)=>{for(var n in t||(t={}))ze.call(t,n)&&Ge(e,n,t[n]);if(Ke)for(var n of Ke(t))$e.call(t,n)&&Ge(e,n,t[n]);return e},Qe=(e,t)=>Ye(e,He(t)),Je=(e,t)=>{var n={};for(var r in e)ze.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&Ke)for(var r of Ke(e))t.indexOf(r)<0&&$e.call(e,r)&&(n[r]=e[r]);return n};function Ze(e){return"[object Object]"===Object.prototype.toString.call(e)}function et(e){if(!Ze(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==Ze(n)&&!1!==n.hasOwnProperty("isPrototypeOf")}function tt(e,t){for(const n in e){const r=e[n],i=t[n];if(et(r)&&et(i)){if(!tt(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 nt(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function rt(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>null!==e))}function it(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&&tt(null!=(t=e.attributes)?t:{},null!=(n=i.attributes)?n:{}))?e.insert+=i.insert:r.push(i)}return r}(e.toDelta())}function ot({insert:e}){return"string"==typeof e?e.length:1}function st(e){return e.reduce((e,t)=>e+ot(t),0)}function at(e,t,n){if(n<1)return[];let r=0;const i=[],o=t+n;for(let s=0;s<e.length&&!(r>=o);s++){const n=e[s],a=ot(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-o));i.push(Qe(Xe({},n),{insert:n.insert.slice(c,l)})),r+=a}return i}function ct(e){return function(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}(e,i.Text.isText(e)?"text":"children")}function lt(e){const t=it(e),n=t.length>0?t.map(dt):[{text:""}];return Qe(Xe({},e.getAttributes()),{children:n})}function dt(e){return"string"==typeof e.insert?Qe(Xe({},e.attributes),{text:e.insert}):lt(e.insert)}function ut(e){return e.map(e=>i.Text.isText(e)?{insert:e.text,attributes:ct(e)}:{insert:ht(e)})}function ht(e){var t=e,{children:n}=t,r=Je(t,["children"]);const i=new a.YXmlText;return Object.entries(r).forEach(([e,t])=>{i.setAttribute(e,t)}),i.applyDelta(ut(n),{sanitize:!1}),i}function ft(e){return e?i.Text.isText(e)?e.text.length:1:0}function pt(e,t,n){var r;if(0===n.length)throw new Error("Path has to a have a length >= 1");if(i.Text.isText(t))throw new Error("Cannot descent into slate text");const[o,...s]=n,c=function(e,t){return e.children.slice(0,t).reduce((e,t)=>e+ft(t),0)}(t,o),l=t.children[o],d=it(e),u=ft(l),h=at(d,c,u);if(h.length>1)throw new Error("Path doesn't match yText, yTarget spans multiple nodes");const f=null==(r=h[0])?void 0:r.insert;if(s.length>0){if(!(f instanceof a.YXmlText))throw new Error("Path doesn't match yText, cannot descent into non-yText");return pt(f,l,s)}return{yParent:e,textRange:{start:c,end:c+u},yTarget:f instanceof a.YXmlText?f:void 0,slateParent:t,slateTarget:l,targetDelta:h}}function gt(e,t,n={}){const{assoc:r=0,insert:o=!1}=n;let s=0,a=0;for(let l=0;l<e.children.length;l++){const n=e.children[l],o=i.Text.isText(n)?n.text.length:1;o>0&&(a=l);const c=s+o;if(o>0&&(r>=0?c>t:c>=t))return[l,t-s];s+=o}if(t>s+(o?1:0))throw new Error("yOffset out of bounds");if(o)return[e.children.length,0];const c=e.children[a];return[a,i.Text.isText(c)?c.text.length:1]}function mt(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 a.YXmlText))throw new Error("Unexpected y parent type");r.unshift(e)}if(r.length<2)return[];let o=t;return r.reduce((e,t,n)=>{const s=r[n+1];if(!s)return e;let a=0;const c=it(t);for(const r of c){if(r.insert===s)break;a+="string"==typeof r.insert?r.insert.length:1}if(i.Text.isText(o))throw new Error("Cannot descent into slate text");const[l]=gt(o,a);return o=o.children[l],e.concat(l)},[])}function yt(e,t,n){const{target:r,changes:o}=n,s=n.delta;if(!(r instanceof a.YXmlText))throw new Error("Unexpected target node type");const c=[],l=mt(e,t,r),d=i.Node.get(t,l);if(i.Text.isText(d))throw new Error("Cannot apply yTextEvent to text node");const u=Array.from(o.keys.entries());if(l.length>0&&u.length>0){const e=Object.fromEntries(u.map(([e,t])=>[e,"delete"===t.action?null:r.getAttribute(e)])),t=Object.fromEntries(u.map(([e])=>[e,d[e]]));c.push({type:"set_node",newProperties:e,properties:t,path:l})}return s.length>0&&c.push(...function(e,t,n){const r=[];let o=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,a]=gt(e,o-n.retain),[c,l]=gt(e,o,{assoc:-1});for(let o=c;o>=s;o--){const d=e.children[o],u=[...t,o];if(!i.Text.isText(d))continue;const h=n.attributes,f=nt(e,...Object.keys(n.attributes));if(o===s||o===c){const e=o===s?a:0,t=o===c?l:d.text.length;if(t!==d.text.length&&r.push({type:"split_node",path:u,position:t,properties:ct(d)}),0!==e){r.push({type:"split_node",path:u,position:e,properties:rt(Xe(Xe({},ct(d)),h))});continue}}r.push({type:"set_node",newProperties:h,path:u,properties:f})}}if("retain"in n&&(o-=n.retain),"delete"in n){const[s,a]=gt(e,o-n.delete),[c,l]=gt(e,o,{assoc:-1});for(let n=0===l?c-1:c;n>=s;n--){const d=e.children[n],u=[...t,n];if(i.Text.isText(d)&&(n===s||n===c)){const e=n===s?a:0,t=n===c?l:d.text.length;r.push({type:"remove_text",offset:e,text:d.text.slice(e,t),path:u}),o-=t-e;continue}r.push({type:"remove_node",node:d,path:u}),o-=ft(d)}return}if("insert"in n){const[a,c]=gt(e,o,{insert:!0}),l=e.children[a],d=[...t,a];if(i.Text.isText(l)){const e=r[r.length-1],t=null!=e&&"insert_node"===e.type?e.node:ct(l);let o=[];if(null==e||"insert_node"!==e.type&&"insert_text"!==e.type&&"split_node"!==e.type&&"set_node"!==e.type||(o=e.path),"string"==typeof n.insert&&tt(null!=(s=n.attributes)?s:{},t)&&i.Path.equals(d,o))return r.push({type:"insert_text",offset:c,text:n.insert,path:d});const a=dt(n);return 0===c?r.push({type:"insert_node",path:d,node:a}):(c<l.text.length&&r.push({type:"split_node",path:d,position:c,properties:ct(l)}),r.push({type:"insert_node",path:i.Path.next(d),node:a}))}return r.push({type:"insert_node",path:d,node:dt(n)})}}),r}(d,l,s)),c}function bt(e,t,n){i.Editor.withoutNormalizing(t,()=>{n.forEach(n=>{(function(e,t,n){if(n instanceof a.YTextEvent)return yt(e,t,n);throw new Error("Unexpected Y event type")})(e,t,n).forEach(e=>{t.apply(e)})})})}function wt(e){return e.map(e=>"string"==typeof e.insert?e:Qe(Xe({},e),{insert:vt(e.insert)}))}function vt(e){const t=new a.YXmlText,n=e.getAttributes();return Object.entries(n).forEach(([e,n])=>{t.setAttribute(e,n)}),t.applyDelta(wt(it(e)),{sanitize:!1}),t}function _t(e){if(!e.doc)throw new Error("shared type isn't attached to a document")}var St="__slateYjsStoredPosition_";function Et(e,t,n){const{yTarget:r,yParent:i,textRange:o}=pt(e,t,n.path);if(r)throw new Error("Slate point points to a non-text element inside sharedRoot");const s=o.start+n.offset;return a.createRelativePositionFromTypeIndex(i,s,s===o.end?-1:0)}function Ct(e,t,n){if(!e.doc)throw new Error("sharedRoot isn't attach to a yDoc");const r=a.createAbsolutePositionFromRelativePosition(n,e.doc);return r&&function(e,t,{type:n,index:r,assoc:o}){if(!(n instanceof a.YXmlText))throw new Error("Absolute position points to a non-XMLText");const s=mt(e,t,n),c=i.Node.get(t,s);if(i.Text.isText(c))throw new Error("Absolute position doesn't match slateRoot, cannot descent into text");const[l,d]=gt(c,r,{assoc:o}),u=c.children[l];return i.Text.isText(u)?{path:[...s,l],offset:d}:null}(e,t,r)}function kt(e,t,n){e.setAttribute(St+t,a.encodeRelativePosition(n))}function Tt(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 xt(e,t,n=""){const r={[n]:Tt(e,t)};return it(t).forEach(({insert:t},i)=>{t instanceof a.YXmlText&&Object.assign(r,xt(e,t,n?`${n}.${i}`:i.toString()))}),r}function Rt(e,t,n,r=0){const i=function(e){return _t(e),Object.fromEntries(Object.entries(e.getAttributes()).filter(([e])=>e.startsWith(St)).map(([t,n])=>[t.slice(25),a.createAbsolutePositionFromRelativePosition(a.decodeRelativePosition(n),e.doc)]).filter(([,e])=>e))}(e),o={"":Tt(i,t,{start:r,end:r+st(n)})};return n.forEach(({insert:e},t)=>{e instanceof a.YXmlText&&Object.assign(o,xt(i,e,t.toString()))}),o}function At(e,t,n,r,i=0,o=0,s=""){const c=n[s];c&&Object.entries(c).forEach(([n,r])=>{kt(e,n,a.createRelativePositionFromTypeIndex(t,r.index-o+i,r.assoc))}),r.forEach(({insert:t},r)=>{t instanceof a.YXmlText&&At(e,t,n,it(t),0,0,s?`${s}.${r}`:r.toString())})}function Ot(e,t,n){return{anchor:Et(e,t,n.anchor),focus:Et(e,t,n.focus)}}function Dt(e,t,n){const r=Ct(e,t,n.anchor);if(!r)return null;const i=Ct(e,t,n.focus);return i?{anchor:r,focus:i}:null}var Pt={insert_node:function(e,t,n){const{yParent:r,textRange:o}=pt(e,t,n.path);if(i.Text.isText(n.node))return r.insert(o.start,n.node.text,ct(n.node));r.insertEmbed(o.start,ht(n.node))},remove_node:function(e,t,n){const{yParent:r,textRange:i}=pt(e,t,n.path);r.delete(i.start,i.end-i.start)},set_node:function(e,t,n){const{yTarget:r,textRange:i,yParent:o}=pt(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 s=Xe(Xe({},Object.fromEntries(Object.keys(n.properties).map(e=>[e,null]))),n.newProperties);o.format(i.start,i.end-i.start,s)},merge_node:function(e,t,n){const r=pt(e,t,n.path),o=pt(r.yParent,r.slateParent,i.Path.previous(n.path.slice(-1)));if(!r.yTarget!=!o.yTarget)throw new Error("Cannot merge y text with y element");if(!o.yTarget||!r.yTarget){const{yParent:e,textRange:o,slateTarget:s}=r;if(!s)throw new Error("Expected Slate target node for merge op.");const a=i.Node.get(t,i.Path.previous(n.path));if(!i.Text.isText(a))throw new Error("Path points to Y.Text but not a Slate text node.");const c=ct(s),l=ct(a),d=Object.keys(c).reduce((e,t)=>t in l?e:Qe(Xe({},e),{[t]:null}),{});return e.format(o.start,o.end-o.start,Xe(Xe({},d),l))}const s=o.yTarget.length,a=it(r.yTarget),c=wt(a),l=Rt(e,r.yTarget,a,s),d=[{retain:s},...c];o.yTarget.applyDelta(d,{sanitize:!1}),r.yParent.delete(r.textRange.start,r.textRange.end-r.textRange.start),At(e,o.yTarget,l,c,s)},move_node:function(e,t,n){const r=i.Path.parent(n.newPath),o=n.newPath[n.newPath.length-1],s=i.Node.get(t,r);if(i.Text.isText(s))throw new Error("Cannot move slate node into text element");const a=[...r,Math.min(o,s.children.length)],c=pt(e,t,n.path),l=pt(e,t,a),d=wt(c.targetDelta),u=Rt(e,c.yParent,c.targetDelta);c.yParent.delete(c.textRange.start,c.textRange.end-c.textRange.start);const h=st(it(l.yParent)),f=Math.min(l.textRange.start,h),p=[{retain:f},...d];l.yParent.applyDelta(p,{sanitize:!1}),At(e,l.yParent,u,d,f,c.textRange.start)},split_node:function(e,t,n){const r=pt(e,t,n.path);if(!r.slateTarget)throw new Error("Y target without corresponding slate node");if(!r.yTarget){if(!i.Text.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,Xe(Xe({},e),n.properties))}if(i.Text.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const o=pt(r.yTarget,r.slateTarget,[n.position]),s=r.slateTarget.children.slice(0,n.position).reduce((e,t)=>e+ft(t),0),c=r.slateTarget.children.reduce((e,t)=>e+ft(t),0),l=at(it(r.yTarget),s,c-s),d=wt(l),u=Rt(e,r.yTarget,l,s),h=new a.YXmlText;h.applyDelta(d,{sanitize:!1}),Object.entries(n.properties).forEach(([e,t])=>{h.setAttribute(e,t)}),r.yTarget.delete(o.textRange.start,r.yTarget.length-o.textRange.start),r.yParent.insertEmbed(r.textRange.end,h),At(e,h,u,d,0,s)}};var Nt=Qe(Xe(Xe({},{insert_text:function(e,t,n){const{yParent:r,textRange:o}=pt(e,t,n.path),s=i.Node.get(t,n.path);if(!i.Text.isText(s))throw new Error("Cannot insert text into non-text node");r.insert(o.start+n.offset,n.text,ct(s))},remove_text:function(e,t,n){const{yParent:r,textRange:i}=pt(e,t,n.path);r.delete(i.start+n.offset,n.text.length)}}),Pt),{set_selection:()=>{}});var Lt=Symbol("slate-yjs-operation"),Mt=Symbol("slate-yjs-position-storage"),Ut=new WeakMap,jt=new WeakMap,It=new WeakSet,Bt={isYjsEditor:e=>i.Editor.isEditor(e)&&e.sharedRoot instanceof a.YXmlText&&"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=jt.get(e))?t:[]},applyRemoteEvents(e,t,n){e.applyRemoteEvents(t,n)},storeLocalChange(e,t){e.storeLocalChange(t)},flushLocalChanges(e){e.flushLocalChanges()},connected:e=>It.has(e),connect(e){e.connect()},disconnect(e){e.disconnect()},isLocal:e=>e.isLocalOrigin(Bt.origin(e)),origin(e){const t=Ut.get(e);return void 0!==t?t:e.localOrigin},withOrigin(e,t,n){const r=Bt.origin(e);Ut.set(e,t),n(),Ut.set(e,r)},storePosition(e,t,n){const{sharedRoot:r,positionStorageOrigin:i}=e;_t(r);const o=Et(r,e,n);r.doc.transact(()=>{kt(r,t,o)},i)},removeStoredPosition(e,t){const{sharedRoot:n,positionStorageOrigin:r}=e;_t(n),n.doc.transact(()=>{!function(e,t){e.removeAttribute(St+t)}(n,t)},r)},position(e,t){const n=function(e,t){const n=e.getAttribute(St+t);return n?a.decodeRelativePosition(n):null}(e.sharedRoot,t);if(n)return Ct(e.sharedRoot,e,n)},storedPositionsRelative(e){return t=e.sharedRoot,Object.fromEntries(Object.entries(t.getAttributes()).filter(([e])=>e.startsWith(St)).map(([e,t])=>[e.slice(25),a.createRelativePositionFromJSON(t)]));var t}};function Ft(e,t,{localOrigin:n,positionStorageOrigin:r,autoConnect:o=!1}={}){const s=e;s.sharedRoot=t,s.localOrigin=null!=n?n:Lt,s.positionStorageOrigin=null!=r?r:Mt,s.applyRemoteEvents=(e,t)=>{Bt.flushLocalChanges(s),i.Editor.withoutNormalizing(s,()=>{Bt.withOrigin(s,t,()=>{bt(s.sharedRoot,s,e)})})},s.isLocalOrigin=e=>e===s.localOrigin;const a=(e,t)=>{s.isLocalOrigin(t.origin)||Bt.applyRemoteEvents(s,e,t.origin)};let c=null;o&&(c=setTimeout(()=>{c=null,Bt.connect(s)})),s.connect=()=>{if(Bt.connected(s))throw new Error("already connected");s.sharedRoot.observeDeep(a);const t=lt(s.sharedRoot);s.children=t.children,It.add(s),i.Editor.normalize(e,{force:!0}),e.operations.length||e.onChange()},s.disconnect=()=>{c&&clearTimeout(c),Bt.flushLocalChanges(s),s.sharedRoot.unobserveDeep(a),It.delete(s)},s.storeLocalChange=t=>{jt.set(s,[...Bt.localChanges(s),{op:t,doc:e.children,origin:Bt.origin(s)}])},s.flushLocalChanges=()=>{_t(s.sharedRoot);const e=Bt.localChanges(s);jt.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=>{_t(s.sharedRoot),s.sharedRoot.doc.transact(()=>{e.forEach(e=>{_t(s.sharedRoot),function(e,t,n){const r=Nt[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:l,onChange:d}=s;return s.apply=e=>{Bt.connected(s)&&Bt.isLocal(s)&&Bt.storeLocalChange(s,e),l(e)},s.onChange=()=>{Bt.connected(s)&&Bt.flushLocalChanges(s),d()},s}var Vt=new WeakMap,Wt=Symbol("slate-yjs-history-without-saving");var qt=new WeakMap,Yt={isCursorEditor:e=>Bt.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=qt.get(e))?r:new Set;i.add(n),qt.set(e,i)},off(e,t,n){if("change"!==t)return;const r=qt.get(e);r&&r.delete(n)},cursorState(e,t){var n;if(t===e.awareness.clientID||!Bt.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=>Bt.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 Ht=e=>a.create((t,n)=>{e.onerror=e=>n(new Error(e.target.error)),e.onsuccess=e=>t(e.target.result)}),Kt=(e,t,n="readwrite")=>{const r=e.transaction(t,n);return t.map(e=>Jt(r,e))},zt=(e,t)=>Ht(e.count(t)),$t=(e,t)=>Ht(e.delete(t)),Gt=(e,t)=>Ht(e.add(t)),Xt=(e,t=null)=>((e,t,n)=>{let r=null;return Qt(e,t,e=>(r=e,!1),n).then(()=>r)})(e,t,"prev"),Qt=(e,t,n,r="next")=>((e,t)=>a.create((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)),Jt=(e,t)=>e.objectStore(t),Zt="custom",en="updates",tn=(e,t=()=>{},n=()=>{})=>{const[r]=Kt(e.db,[en]);return(i=r,c=e._dbref,l=!1,o=IDBKeyRange.lowerBound(c,l),Ht(i.getAll(o,s))).then(i=>{e._destroyed||(t(r),a.transact(e.doc,()=>{i.forEach(t=>a.applyUpdate(e.doc,t))},e,!1),n(r))}).then(()=>Xt(r).then(t=>{e._dbref=t+1})).then(()=>zt(r).then(t=>{e._dbsize=t})).then(()=>r);var i,o,s,c,l},nn=(e,t=!0)=>tn(e).then(n=>{(t||e._dbsize>=500)&&Gt(n,a.encodeStateAsUpdate(e.doc)).then(()=>{return $t(n,(t=e._dbref,r=!0,IDBKeyRange.upperBound(t,r)));var t,r}).then(()=>zt(n).then(t=>{e._dbsize=t}))}),rn=class extends a.Observable{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)=>a.create((n,r)=>{const i=indexedDB.open(e);i.onupgradeneeded=e=>t(e.target.result),i.onerror=e=>r(a.create$1(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=a.create(e=>this.on("synced",()=>e(this))),this._db.then(e=>{this.db=e;tn(this,e=>Gt(e,a.encodeStateAsUpdate(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]=Kt(this.db,[en]);Gt(t,e),++this._dbsize>=500&&(null!==this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{nn(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,Ht(indexedDB.deleteDatabase(e))})}get(e){return this._db.then(t=>{const[n]=Kt(t,[Zt],"readonly");return((e,t)=>Ht(e.get(t)))(n,e)})}set(e,t){return this._db.then(n=>{const[r]=Kt(n,[Zt]);return((e,t,n)=>Ht(e.put(t,n)))(r,t,e)})}del(e){return this._db.then(t=>{const[n]=Kt(t,[Zt]);return $t(n,e)})}},on=3e4,sn=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=a.getUnixTime();const n=t.data,i="string"==typeof n?JSON.parse(n):n;i&&"pong"===i.type&&(clearTimeout(r),r=setTimeout(o,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(sn,a.min(1200*a.log10(e.unsuccessfulReconnects+1),2500),e)),clearTimeout(r)},o=()=>{e.ws===t&&e.send({type:"ping"})};t.onclose=()=>i(null),t.onerror=e=>i(e),t.onopen=()=>{e.lastMessageReceived=a.getUnixTime(),e.connecting=!1,e.connected=!0,e.unsuccessfulReconnects=0,e.emit("connect",[{type:"connect"},e]),r=setTimeout(o,15e3)}}},an=class extends a.Observable{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&&on<a.getUnixTime()-this.lastMessageReceived&&this.ws.close()},15e3),sn(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||sn(this)}},cn=new Map,ln="undefined"==typeof BroadcastChannel?class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.key===e&&null!==this.onmessage&&this.onmessage({data:a.fromBase64(t.newValue||"")}),a.onChange(this._onChange)}postMessage(e){a.varStorage.setItem(this.room,a.toBase64(a.createUint8ArrayFromArrayBuffer(e)))}close(){a.offChange(this._onChange)}}:BroadcastChannel,dn=e=>a.setIfUndefined(cn,e,()=>{const t=a.create$2(),n=new ln(e);return n.onmessage=e=>t.forEach(t=>t(e.data,"broadcastchannel")),{bc:n,subs:t}}),un=e.__commonJSMin((e,t)=>{!function(n){if("object"==typeof e&&void 0!==t)t.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{("undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window).SimplePeer=n()}}(function(){var e=Math.floor,t=Math.abs,n=Math.pow;return function e(t,n,r){function i(s,a){if(!n[s]){if(!t[s]){var c="function"==typeof require&&require;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var d=n[s]={exports:{}};t[s][0].call(d.exports,function(e){return i(t[s][1][e]||e)},d,d.exports,e,t,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t,n){"use strict";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 s[63&e>>18]+s[63&e>>12]+s[63&e>>6]+s[63&e]}function o(e,t,n){for(var r,o=[],s=t;s<n;s+=3)r=(16711680&e[s]<<16)+(65280&e[s+1]<<8)+(255&e[s+2]),o.push(i(r));return o.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),o=i[0],s=i[1],l=new c(function(e,t,n){return 3*(t+n)/4-n}(0,o,s)),d=0,u=0<s?o-4:o;for(n=0;n<u;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[d++]=255&t>>16,l[d++]=255&t>>8,l[d++]=255&t;return 2===s&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,l[d++]=255&t),1===s&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[e.charCodeAt(n+2)]>>2,l[d++]=255&t>>8,l[d++]=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(o(e,c,c+a>l?l:c+a));return 1===r?(t=e[n-1],i.push(s[t>>2]+s[63&t<<4]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(s[t>>10]+s[63&t>>4]+s[63&t<<2]+"=")),i.join("")};for(var s=[],a=[],c="undefined"==typeof Uint8Array?Array:Uint8Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0;d<64;++d)s[d]=l[d],a[l.charCodeAt(d)]=d;a[45]=62,a[95]=63},{}],2:[function(){},{}],3:[function(e,t,r){(function(){(function(){"use strict";var t=String.fromCharCode,i=Math.min;function o(e){if(2147483647<e)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(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"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|h(e,t),r=o(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}(e,t);if(ArrayBuffer.isView(e))return d(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(B(e,ArrayBuffer)||e&&B(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;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),r.__proto__=s.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 s.from(r,t,n);var i=function(e){if(s.isBuffer(e)){var t=0|u(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0===e.length?"Buffer"===e.type&&Array.isArray(e.data)?d(e.data):void 0:"number"!=typeof e.length||F(e.length)?o(0):d(e)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.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),o(0>e?0:0|u(e))}function d(e){for(var t=0>e.length?0:0|u(e.length),n=o(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function u(e){if(e>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647..toString(16)+" bytes");return 0|e}function h(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||B(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 U(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return j(e).length;default:if(i)return r?-1:U(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 R(this,t,n);case"utf8":case"utf-8":return C(this,t,n);case"ascii":return T(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return E(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function p(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function g(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),F(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=s.from(t,r)),s.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 o(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var s,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 d=-1;for(s=n;s<c;s++)if(o(e,s)!==o(t,-1===d?0:s-d))-1!==d&&(s-=s-d),d=-1;else if(-1===d&&(d=s),s-d+1===l)return d*a}else for(n+l>c&&(n=c-l),s=n;0<=s;s--){for(var u=!0,h=0;h<l;h++)if(o(e,s+h)!==o(t,h)){u=!1;break}if(u)return s}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 o=t.length;r>o/2&&(r=o/2);for(var s,a=0;a<r;++a){if(F(s=parseInt(t.substr(2*a,2),16)))return a;e[n+a]=s}return a}function b(e,t,n,r){return I(U(t,e.length-n),e,n,r)}function w(e,t,n,r){return I(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 I(j(t),e,n,r)}function S(e,t,n,r){return I(function(e,t){for(var n,r,i,o=[],s=0;s<e.length&&!(0>(t-=2));++s)n=e.charCodeAt(s),r=n>>8,i=n%256,o.push(i),o.push(r);return o}(t,e.length-n),e,n,r)}function E(e,t,n){return 0===t&&n===e.length?V.fromByteArray(e):V.fromByteArray(e.slice(t,n))}function C(e,t,n){n=i(e.length,n);for(var r=[],o=t;o<n;){var s,a,c,l,d=e[o],u=null,h=239<d?4:223<d?3:191<d?2:1;if(o+h<=n)1===h?128>d&&(u=d):2===h?128==(192&(s=e[o+1]))&&(127<(l=(31&d)<<6|63&s)&&(u=l)):3===h?(s=e[o+1],a=e[o+2],128==(192&s)&&128==(192&a)&&(2047<(l=(15&d)<<12|(63&s)<<6|63&a)&&(55296>l||57343<l)&&(u=l))):4===h&&(s=e[o+1],a=e[o+2],c=e[o+3],128==(192&s)&&128==(192&a)&&128==(192&c)&&(65535<(l=(15&d)<<18|(63&s)<<12|(63&a)<<6|63&c)&&1114112>l&&(u=l)));null===u?(u=65533,h=1):65535<u&&(u-=65536,r.push(55296|1023&u>>>10),u=56320|1023&u),r.push(u),o+=h}return k(r)}function k(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 T(e,n,r){var o="";r=i(e.length,r);for(var s=n;s<r;++s)o+=t(127&e[s]);return o}function x(e,n,r){var o="";r=i(e.length,r);for(var s=n;s<r;++s)o+=t(e[s]);return o}function R(e,t,n){var r=e.length;(!t||0>t)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var i="",o=t;o<n;++o)i+=M(e[o]);return i}function A(e,n,r){for(var i=e.slice(n,r),o="",s=0;s<i.length;s+=2)o+=t(i[s]+256*i[s+1]);return o}function O(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 D(e,t,n,r,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)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 N(e,t,n,r,i){return t=+t,n>>>=0,i||P(e,0,n,4),W.write(e,t,n,r,23,4),n+4}function L(e,t,n,r,i){return t=+t,n>>>=0,i||P(e,0,n,8),W.write(e,t,n,r,52,8),n+8}function M(e){return 16>e?"0"+e.toString(16):e.toString(16)}function U(e,t){t=t||1/0;for(var n,r=e.length,i=null,o=[],s=0;s<r;++s){if(55295<(n=e.charCodeAt(s))&&57344>n){if(!i){if(56319<n){-1<(t-=3)&&o.push(239,191,189);continue}if(s+1===r){-1<(t-=3)&&o.push(239,191,189);continue}i=n;continue}if(56320>n){-1<(t-=3)&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&-1<(t-=3)&&o.push(239,191,189);if(i=null,128>n){if(0>(t-=1))break;o.push(n)}else if(2048>n){if(0>(t-=2))break;o.push(192|n>>6,128|63&n)}else if(65536>n){if(0>(t-=3))break;o.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;o.push(240|n>>18,128|63&n>>12,128|63&n>>6,128|63&n)}}return o}function j(e){return V.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 I(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 B(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function F(e){return e!=e}var V=e("base64-js"),W=e("ieee754");r.Buffer=s,r.SlowBuffer=function(e){return+e!=e&&(e=0),s.alloc(+e)},r.INSPECT_MAX_BYTES=50,r.kMaxLength=2147483647,s.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),s.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||console.error,Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){return s.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){return s.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&s[Symbol.species]===s&&Object.defineProperty(s,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),s.poolSize=8192,s.from=function(e,t,n){return a(e,t,n)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,n){return function(e,t,n){return c(e),0>=e||void 0===t?o(e):"string"==typeof n?o(e).fill(t,n):o(e).fill(t)}(e,t,n)},s.allocUnsafe=function(e){return l(e)},s.allocUnsafeSlow=function(e){return l(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(B(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),B(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.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,o=0,a=i(n,r);o<a;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},s.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}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=s.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var o=e[n];if(B(o,Uint8Array)&&(o=s.from(o)),!s.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(r,i),i+=o.length}return r},s.byteLength=h,s.prototype._isBuffer=!0,s.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)p(this,t,t+1);return this},s.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)p(this,t,t+3),p(this,t+1,t+2);return this},s.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)p(this,t,t+7),p(this,t+1,t+6),p(this,t+2,t+5),p(this,t+3,t+4);return this},s.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?C(this,0,e):f.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},s.prototype.compare=function(e,t,n,r,o){if(B(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.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===o&&(o=this.length),0>t||n>e.length||0>r||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(o>>>=0)-(r>>>=0),c=(n>>>=0)-(t>>>=0),l=i(a,c),d=this.slice(r,o),u=e.slice(t,n),h=0;h<l;++h)if(d[h]!==u[h]){a=d[h],c=u[h];break}return a<c?-1:c<a?1:0},s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},s.prototype.indexOf=function(e,t,n){return g(this,e,t,n,!0)},s.prototype.lastIndexOf=function(e,t,n){return g(this,e,t,n,!1)},s.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 o=!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 S(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},s.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__=s.prototype,r},s.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);for(var r=this[e],i=1,o=0;++o<t&&(i*=256);)r+=this[e+o]*i;return r},s.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||O(e,t,this.length);for(var r=this[e+--t],i=1;0<t&&(i*=256);)r+=this[e+--t]*i;return r},s.prototype.readUInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||O(e,t,this.length);for(var i=this[e],o=1,s=0;++s<t&&(o*=256);)i+=this[e+s]*o;return i>=(o*=128)&&(i-=n(2,8*t)),i},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||O(e,t,this.length);for(var i=t,o=1,s=this[e+--i];0<i&&(o*=256);)s+=this[e+--i]*o;return s>=(o*=128)&&(s-=n(2,8*t)),s},s.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||O(e,4,this.length),W.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),W.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),W.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),W.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t>>>=0,r>>>=0,i)||D(this,e,t,r,n(2,8*r)-1,0);var o=1,s=0;for(this[t]=255&e;++s<r&&(o*=256);)this[t+s]=255&e/o;return t+r},s.prototype.writeUIntBE=function(e,t,r,i){(e=+e,t>>>=0,r>>>=0,i)||D(this,e,t,r,n(2,8*r)-1,0);var o=r-1,s=1;for(this[t+o]=255&e;0<=--o&&(s*=256);)this[t+o]=255&e/s;return t+r},s.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||D(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},s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||D(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},s.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var o=n(2,8*r-1);D(this,e,t,r,o-1,-o)}var s=0,a=1,c=0;for(this[t]=255&e;++s<r&&(a*=256);)0>e&&0===c&&0!==this[t+s-1]&&(c=1),this[t+s]=255&(e/a|0)-c;return t+r},s.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var o=n(2,8*r-1);D(this,e,t,r,o-1,-o)}var s=r-1,a=1,c=0;for(this[t+s]=255&e;0<=--s&&(a*=256);)0>e&&0===c&&0!==this[t+s+1]&&(c=1),this[t+s]=255&(e/a|0)-c;return t+r},s.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||D(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},s.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||D(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},s.prototype.writeFloatLE=function(e,t,n){return N(this,e,t,!0,n)},s.prototype.writeFloatBE=function(e,t,n){return N(this,e,t,!1,n)},s.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},s.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},s.prototype.copy=function(e,t,n,r){if(!s.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 o=i-1;0<=o;--o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return i},s.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&&!s.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 o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{var a=s.isBuffer(e)?e:s.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<n-t;++o)this[o+t]=a[o%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,n){n.exports=function(n){function r(e){function t(...e){if(!t.enabled)return;const i=t,o=+new Date;i.diff=o-(n||o),i.prev=n,i.curr=o,n=o,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,n)=>{if("%%"===t)return"%";s++;const o=r.formatters[n];if("function"==typeof o){const n=e[s];t=o.call(i,n),e.splice(s,1),s--}return t}),r.formatArgs.call(i,e),(i.log||r.log).apply(i,e)}let n,o=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===o?r.enabled(e):o,set:e=>{o=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 o(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(o),...r.skips.map(o).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(n).forEach(e=>{r[e]=n[e]}),r.names=[],r.skips=[],r.formatters={},r.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return r.colors[t(n)%r.colors.length]},r.enable(r.load()),r}},{ms:11}],6:[function(e,t){"use strict";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){"use strict";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 o(e,t,n,o){var s,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]=o?[n,c]:[c,n]:o?c.unshift(n):c.push(n),0<(s=i(e))&&c.length>s&&!c.warned){c.warned=!0;var l=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 s(){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=s.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):d(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 d(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function u(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(o){r.once&&e.removeEventListener(t,i),n(o)})}}var h,f="object"==typeof Reflect?Reflect:null,p=f&&"function"==typeof f.apply?f.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};h=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 g=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,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}u(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&u(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||g(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||g(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 o;if(0<t.length&&(o=t[0]),o instanceof Error)throw o;var s=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw s.context=o,s}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)p(a,this,t);else{var c=a.length,l=d(a,c);for(n=0;n<c;++n)p(l[n],this,t)}return!0},n.prototype.addListener=function(e,t){return o(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return o(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,o,s,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(o=-1,s=n.length-1;0<=s;s--)if(n[s]===t||n[s].listener===t){a=n[s].listener,o=s;break}if(0>o)return this;0===o?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,o),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;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;0<=r;r--)this.removeListener(e,t[r]);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?h(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(r,i,o){o.read=function(e,t,r,i,o){var s,a,c=8*o-i-1,l=(1<<c)-1,d=l>>1,u=-7,h=r?o-1:0,f=r?-1:1,p=e[t+h];for(h+=f,s=p&(1<<-u)-1,p>>=-u,u+=c;0<u;s=256*s+e[t+h],h+=f,u-=8);for(a=s&(1<<-u)-1,s>>=-u,u+=i;0<u;a=256*a+e[t+h],h+=f,u-=8);if(0===s)s=1-d;else{if(s===l)return a?NaN:1/0*(p?-1:1);a+=n(2,i),s-=d}return(p?-1:1)*a*n(2,s-i)},o.write=function(r,i,o,s,a,c){var l,d,u,h=Math.LN2,f=Math.log,p=8*c-a-1,g=(1<<p)-1,m=g>>1,y=23===a?n(2,-24)-n(2,-77):0,b=s?0:c-1,w=s?1:-1,v=0>i||0===i&&0>1/i?1:0;for(i=t(i),isNaN(i)||i===1/0?(d=isNaN(i)?1:0,l=g):(l=e(f(i)/h),1>i*(u=n(2,-l))&&(l--,u*=2),2<=(i+=1<=l+m?y/u:y*n(2,1-m))*u&&(l++,u/=2),l+m>=g?(d=0,l=g):1<=l+m?(d=(i*u-1)*n(2,a),l+=m):(d=i*n(2,m-1)*n(2,a),l=0));8<=a;r[o+b]=255&d,b+=w,d/=256,a-=8);for(l=l<<a|d,p+=a;0<p;r[o+b]=255&l,b+=w,l/=256,p-=8);r[o+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,n){var r=Math.round;function i(e){var n=t(e);return 864e5<=n?r(e/864e5)+"d":36e5<=n?r(e/36e5)+"h":6e4<=n?r(e/6e4)+"m":1e3<=n?r(e/1e3)+"s":e+"ms"}function o(e){var n=t(e);return 864e5<=n?s(e,n,864e5,"day"):36e5<=n?s(e,n,36e5,"hour"):6e4<=n?s(e,n,6e4,"minute"):1e3<=n?s(e,n,1e3,"second"):e+" ms"}function s(e,t,n,i){return r(e/n)+" "+i+(t>=1.5*n?"s":"")}n.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?o(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 o(){p&&h&&(p=!1,h.length?f=h.concat(f):g=-1,f.length&&s())}function s(){if(!p){var e=i(o);p=!0;for(var t=f.length;t;){for(h=f,f=[];++g<t;)h&&h[g].run();g=-1,t=f.length}h=null,p=!1,function(e){if(d===clearTimeout)return clearTimeout(e);if((d===r||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(n){try{return d.call(null,e)}catch(n){return d.call(this,e)}}}(e)}}function a(e,t){this.fun=e,this.array=t}function c(){}var l,d,u=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{d="function"==typeof clearTimeout?clearTimeout:r}catch(t){d=r}}();var h,f=[],p=!1,g=-1;u.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||p||i(s)},a.prototype.run=function(){this.fun.apply(null,this.array)},u.title="browser",u.browser=!0,u.env={},u.argv=[],u.version="",u.versions={},u.on=c,u.addListener=c,u.once=c,u.off=c,u.removeListener=c,u.removeAllListeners=c,u.emit=c,u.prependListener=c,u.prependOnceListener=c,u.listeners=function(){return[]},u.binding=function(){throw new Error("process.binding is not supported")},u.cwd=function(){return"/"},u.chdir=function(){throw new Error("process.chdir is not supported")},u.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(){"use strict";var i=e("safe-buffer").Buffer,o=r.crypto||r.msCrypto;t.exports=o&&o.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 s=0;s<e;s+=65536)o.getRandomValues(r.slice(s,s+65536));else o.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){"use strict";function n(e,t,n){function r(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var o=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);o.prototype.name=n.name,o.prototype.code=e,i[e]=o}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,o;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"))o="The ".concat(e," ").concat(i," ").concat(r(t,"type"));else{var s=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}(e,".")?"property":"argument";o='The "'.concat(e,'" ').concat(s," ").concat(i," ").concat(r(t,"type"))}return o+=". 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(){"use strict";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(o,this)}function o(e){e.end()}var s=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,d=s(c.prototype),u=0;u<d.length;u++)l=d[u],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){"use strict";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(){"use strict";function i(t,n,r){S=S||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof S),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=L(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&&(!A&&(A=e("string_decoder/").StringDecoder),this.decoder=new A(t.encoding),this.encoding=t.encoding)}function o(t){if(S=S||e("./_stream_duplex"),!(this instanceof o))return new o(t);var n=this instanceof S;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)),k.call(this)}function s(e,t,n,r,i){E("readableAddChunk",t);var o,s=e._readableState;if(null===t)s.reading=!1,function(e,t){if(E("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?d(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,u(e)))}}(e,s);else if(i||(o=c(s,t)),o)F(e,o);else if(s.objectMode||t&&0<t.length)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===T.prototype||(t=function(e){return T.from(e)}(t)),r)s.endEmitted?F(e,new B):a(e,s,t,!0);else if(s.ended)F(e,new j);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?a(e,s,t,!1):h(e,s)):a(e,s,t,!1)}else r||(s.reading=!1,h(e,s));return!s.ended&&(s.length<s.highWaterMark||0===s.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&&d(e)),h(e,t)}function c(e,t){var n;return function(e){return T.isBuffer(e)||e instanceof x}(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new U("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 d(e){var t=e._readableState;E("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(E("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(u,e))}function u(e){var t=e._readableState;E("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 h(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(E("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function p(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 g(e){E("readable nexttick read 0"),e.read(0)}function m(e,t){E("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(E("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;E("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(v,t,e))}function v(e,t){if(E("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 S,E;t.exports=o,o.ReadableState=i,e("events").EventEmitter;var C=function(e,t){return e.listeners(t).length},k=e("./internal/streams/stream"),T=e("buffer").Buffer,x=r.Uint8Array||function(){},R=e("util");E=R&&R.debuglog?R.debuglog("stream"):function(){};var A,O,D,P=e("./internal/streams/buffer_list"),N=e("./internal/streams/destroy"),L=e("./internal/streams/state").getHighWaterMark,M=e("../errors").codes,U=M.ERR_INVALID_ARG_TYPE,j=M.ERR_STREAM_PUSH_AFTER_EOF,I=M.ERR_METHOD_NOT_IMPLEMENTED,B=M.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(o,k);var F=N.errorOrDestroy,V=["error","close","destroy","pause","resume"];Object.defineProperty(o.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),o.prototype.destroy=N.destroy,o.prototype._undestroy=N.undestroy,o.prototype._destroy=function(e,t){t(e)},o.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=T.from(e,t),t=""),n=!0),s(this,e,t,!1,n)},o.prototype.unshift=function(e){return s(this,e,null,!0,!1)},o.prototype.isPaused=function(){return!1===this._readableState.flowing},o.prototype.setEncoding=function(t){A||(A=e("string_decoder/").StringDecoder);var n=new A(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},o.prototype.read=function(e){E("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 E("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?w(this):d(this),null;if(0===(e=l(e,t))&&t.ended)return 0===t.length&&w(this),null;var r,i=t.needReadable;return E("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&E("length less than watermark",i=!0),t.ended||t.reading?E("reading or ended",i=!1):i&&(E("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))),null===(r=0<e?b(e,t):null)?(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!==r&&this.emit("data",r),r},o.prototype._read=function(){F(this,new I("_read()"))},o.prototype.pipe=function(e,t){function r(e,t){E("onunpipe"),e===u&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,o())}function i(){E("onend"),e.end()}function o(){E("cleanup"),e.removeListener("close",c),e.removeListener("finish",l),e.removeListener("drain",p),e.removeListener("error",a),e.removeListener("unpipe",r),u.removeListener("end",i),u.removeListener("end",d),u.removeListener("data",s),g=!0,h.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&p()}function s(t){E("ondata");var n=e.write(t);E("dest.write",n),!1===n&&((1===h.pipesCount&&h.pipes===e||1<h.pipesCount&&-1!==_(h.pipes,e))&&!g&&(E("false write response, pause",h.awaitDrain),h.awaitDrain++),u.pause())}function a(t){E("onerror",t),d(),e.removeListener("error",a),0===C(e,"error")&&F(e,t)}function c(){e.removeListener("finish",l),d()}function l(){E("onfinish"),e.removeListener("close",c),d()}function d(){E("unpipe"),u.unpipe(e)}var u=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,E("pipe count=%d opts=%j",h.pipesCount,t);var f=t&&!1===t.end||e===n.stdout||e===n.stderr?d:i;h.endEmitted?n.nextTick(f):u.once("end",f),e.on("unpipe",r);var p=function(e){return function(){var t=e._readableState;E("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&C(e,"data")&&(t.flowing=!0,y(e))}}(u);e.on("drain",p);var g=!1;return u.on("data",s),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",u),h.flowing||(E("pipe resume"),u.resume()),e},o.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 o=0;o<i;o++)r[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=_(t.pipes,e);return-1===s||(t.pipes.splice(s,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},o.prototype.on=function(e,t){var r=k.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,E("on readable",i.length,i.reading),i.length?d(this):!i.reading&&n.nextTick(g,this)),r},o.prototype.addListener=o.prototype.on,o.prototype.removeListener=function(e,t){var r=k.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(p,this),r},o.prototype.removeAllListeners=function(e){var t=k.prototype.removeAllListeners.apply(this,arguments);return("readable"===e||void 0===e)&&n.nextTick(p,this),t},o.prototype.resume=function(){var e=this._readableState;return e.flowing||(E("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(m,e,t))}(this,e)),e.paused=!1,this},o.prototype.pause=function(){return E("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(E("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},o.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on("end",function(){if(E("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){E("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 o=0;o<V.length;o++)e.on(V[o],this.emit.bind(this,V[o]));return this._read=function(t){E("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(o.prototype[Symbol.asyncIterator]=function(){return void 0===O&&(O=e("./internal/streams/async_iterator")),O(this)}),Object.defineProperty(o.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(o.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(o.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),o._fromList=b,Object.defineProperty(o.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(o.from=function(t,n){return void 0===D&&(D=e("./internal/streams/from")),D(o,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){"use strict";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?(u.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?o(this,null,null):this._flush(function(t,n){o(e,t,n)})}function o(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new d;if(e._transformState.transforming)throw new l;return e.push(null)}t.exports=r;var s=e("../errors").codes,a=s.ERR_METHOD_NOT_IMPLEMENTED,c=s.ERR_MULTIPLE_CALLBACK,l=s.ERR_TRANSFORM_ALREADY_TRANSFORMING,d=s.ERR_TRANSFORM_WITH_LENGTH_0,u=e("./_stream_duplex");e("inherits")(r,u),r.prototype.push=function(e,t){return this._transformState.needTransform=!1,u.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){u.prototype._destroy.call(this,e,function(e){t(e)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(e,t){(function(n,r){(function(){"use strict";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 o(){}function s(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=x(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){h(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 s(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 E.call(this)):new a(t)}function c(e,t){var r=new M;j(e,r),n.nextTick(t,r)}function l(e,t,r,i){var o;return null===r?o=new L:"string"!=typeof r&&!t.objectMode&&(o=new A("chunk",["string","Buffer"],r)),!o||(j(e,o),n.nextTick(i,o),!1)}function d(e,t,n,r,i,o){if(!n){var s=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=C.from(t,n)),t}(t,r,i);r!==s&&(n=!0,i="buffer",r=s)}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:o,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else u(e,t,!1,a,r,i,o);return c}function u(e,t,n,r,i,o,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new N("write")):n?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function h(e,t){var r=e._writableState,i=r.sync,o=r.writecb;if("function"!=typeof o)throw new D;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,i,o){--t.pendingcb,r?(n.nextTick(o,i),n.nextTick(b,e,t),e._writableState.errorEmitted=!0,j(e,i)):(o(i),e._writableState.errorEmitted=!0,j(e,i),b(e,t))}(e,r,i,t,o);else{var s=g(r)||e.destroyed;s||r.corked||r.bufferProcessing||!r.bufferedRequest||p(e,r),i?n.nextTick(f,e,r,s,o):f(e,r,s,o)}}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 p(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,o=Array(r),s=t.corkedRequestsFree;s.entry=n;for(var a=0,c=!0;n;)o[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;o.allBuffers=c,u(e,t,!0,t.length,o,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new i(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,h=n.callback;if(u(e,t,!1,t.objectMode?1:l.length,l,d,h),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function g(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&&j(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=g(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=s;var _,S={deprecate:e("util-deprecate")},E=e("./internal/streams/stream"),C=e("buffer").Buffer,k=r.Uint8Array||function(){},T=e("./internal/streams/destroy"),x=e("./internal/streams/state").getHighWaterMark,R=e("../errors").codes,A=R.ERR_INVALID_ARG_TYPE,O=R.ERR_METHOD_NOT_IMPLEMENTED,D=R.ERR_MULTIPLE_CALLBACK,P=R.ERR_STREAM_CANNOT_PIPE,N=R.ERR_STREAM_DESTROYED,L=R.ERR_STREAM_NULL_VALUES,M=R.ERR_STREAM_WRITE_AFTER_END,U=R.ERR_UNKNOWN_ENCODING,j=T.errorOrDestroy;e("inherits")(a,E),s.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(s.prototype,"buffer",{get:S.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 s}})):_=function(e){return e instanceof this},a.prototype.pipe=function(){j(this,new P)},a.prototype.write=function(e,t,n){var r=this._writableState,i=!1,s=!r.objectMode&&function(e){return C.isBuffer(e)||e instanceof k}(e);return s&&!C.isBuffer(e)&&(e=function(e){return C.from(e)}(e)),"function"==typeof t&&(n=t,t=null),s?t="buffer":!t&&(t=r.defaultEncoding),"function"!=typeof n&&(n=o),r.ending?c(this,n):(s||l(this,r,e,n))&&(r.pendingcb++,i=d(this,r,s,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&&p(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 U(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 O("_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=T.destroy,a.prototype._undestroy=T.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(){"use strict";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 o(e){var t=e[l];if(null!==t){var n=e[g].read();null!==n&&(e[f]=null,e[l]=null,e[d]=null,t(i(n,!1)))}}function s(e){n.nextTick(o,e)}var a,c=e("./end-of-stream"),l=Symbol("lastResolve"),d=Symbol("lastReject"),u=Symbol("error"),h=Symbol("ended"),f=Symbol("lastPromise"),p=Symbol("handlePromise"),g=Symbol("stream"),m=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((a={get stream(){return this[g]},next:function(){var e=this,t=this[u];if(null!==t)return Promise.reject(t);if(this[h])return Promise.resolve(i(void 0,!0));if(this[g].destroyed)return new Promise(function(t,r){n.nextTick(function(){e[u]?r(e[u]):t(i(void 0,!0))})});var r,o=this[f];if(o)r=new Promise(function(e,t){return function(n,r){e.then(function(){t[h]?n(i(void 0,!0)):t[p](n,r)},r)}}(o,this));else{var s=this[g].read();if(null!==s)return Promise.resolve(i(s,!1));r=new Promise(this[p])}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[g].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={},g,{value:e,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,d,{value:null,writable:!0}),r(t,u,{value:null,writable:!0}),r(t,h,{value:e._readableState.endEmitted,writable:!0}),r(t,p,{value:function(e,t){var r=n[g].read();r?(n[f]=null,n[l]=null,n[d]=null,e(i(r,!1))):(n[l]=e,n[d]=t)},writable:!0}),t));return n[f]=null,c(e,function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[d];return null!==t&&(n[f]=null,n[l]=null,n[d]=null,t(e)),void(n[u]=e)}var r=n[l];null!==r&&(n[f]=null,n[l]=null,n[d]=null,r(i(void 0,!0))),n[h]=!0}),e.on("readable",s.bind(null,n)),n}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":24,_process:12}],22:[function(e,t){"use strict";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 o(e,t,n){s.prototype.copy.call(e,t,n)}var s=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 s.alloc(0);for(var t=s.allocUnsafe(e>>>0),n=this.head,r=0;n;)o(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,o=e>i.length?i.length:e;if(r+=o===i.length?i:i.slice(0,e),0===(e-=o)){o===i.length?(++n,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=i.slice(o));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=s.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0===(e-=o)){o===i.length?(++r,this.head=n.next?n.next:this.tail=null):(this.head=n,n.data=i.slice(o));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(){"use strict";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,o){var s=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(o?o(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){!o&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(r,s):(s._writableState.errorEmitted=!0,e.nextTick(n,s,t)):e.nextTick(n,s,t):o?(e.nextTick(r,s),o(t)):e.nextTick(r,s)}),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){"use strict";function n(){}var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;t.exports=function e(t,i,o){if("function"==typeof i)return e(t,null,i);i||(i={}),o=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)}}}(o||n);var s=i.readable||!1!==i.readable&&t.readable,a=i.writable||!1!==i.writable&&t.writable,c=function(){t.writable||d()},l=t._writableState&&t._writableState.finished,d=function(){a=!1,l=!0,s||o.call(t)},u=t._readableState&&t._readableState.endEmitted,h=function(){s=!1,u=!0,a||o.call(t)},f=function(e){o.call(t,e)},p=function(){var e;return s&&!u?(t._readableState&&t._readableState.ended||(e=new r),o.call(t,e)):a&&!l?(t._writableState&&t._writableState.ended||(e=new r),o.call(t,e)):void 0},g=function(){t.req.on("finish",d)};return function(e){return e.setHeader&&"function"==typeof e.abort}(t)?(t.on("complete",d),t.on("abort",p),t.req?g():t.on("request",g)):a&&!t._writableState&&(t.on("end",c),t.on("close",c)),t.on("end",h),t.on("finish",d),!1!==i.error&&t.on("error",f),t.on("close",p),function(){t.removeListener("complete",d),t.removeListener("abort",p),t.removeListener("request",g),t.req&&t.req.removeListener("finish",d),t.removeListener("end",c),t.removeListener("close",c),t.removeListener("finish",d),t.removeListener("end",h),t.removeListener("error",f),t.removeListener("close",p)}}},{"../../../errors":15}],25:[function(e,t){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(e,t){"use strict";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 o=!1;t.on("close",function(){o=!0}),void 0===a&&(a=e("./end-of-stream")),a(t,{readable:n,writable:r},function(e){return e?i(e):(o=!0,void i())});var s=!1;return function(e){if(!o)return s?void 0:(s=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void i(e||new d("pipe")))}}function i(e){e()}function o(e,t){return e.pipe(t)}function s(e){return e.length&&"function"==typeof e[e.length-1]?e.pop():n}var a,c=e("../../../errors").codes,l=c.ERR_MISSING_ARGS,d=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=s(t);if(Array.isArray(t[0])&&(t=t[0]),2>t.length)throw new l("streams");var c,d=t.map(function(e,n){var o=n<t.length-1;return r(e,o,0<n,function(e){c||(c=e),e&&d.forEach(i),o||(d.forEach(i),a(c))})});return t.reduce(o)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(t,n){"use strict";var r=t("../../../errors").codes.ERR_INVALID_OPT_VALUE;n.exports={getHighWaterMark:function(t,n,i,o){var s=function(e,t,n){return null==e.highWaterMark?t?e[n]:null:e.highWaterMark}(n,o,i);if(null!=s){if(!isFinite(s)||e(s)!==s||0>s)throw new r(o?i:"highWaterMark",s);return e(s)}return t.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 s(e,t,n)}var o=e("buffer"),s=o.Buffer;s.from&&s.alloc&&s.allocUnsafe&&s.allocUnsafeSlow?t.exports=o:(r(o,n),n.Buffer=i),i.prototype=Object.create(s.prototype),r(s,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return s(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=s(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 s(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o.SlowBuffer(e)}},{buffer:3}],31:[function(e,t,n){"use strict";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&&(h.isEncoding===f||!f(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=s,this.end=a,t=4;break;case"utf8":this.fillLast=o,t=4;break;case"base64":this.text=c,this.end=l,t=3;break;default:return this.write=d,void(this.end=u)}this.lastNeed=0,this.lastTotal=0,this.lastChar=h.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 o(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 s(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 d(e){return e.toString(this.encoding)}function u(e){return e&&e.length?this.write(e):""}var h=e("safe-buffer").Buffer,f=h.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 o=i(t[r]);return 0<=o?(0<o&&(e.lastNeed=o-1),o):--r<n||-2===o?0:0<=(o=i(t[r]))?(0<o&&(e.lastNeed=o-2),o):--r<n||-2===o?0:0<=(o=i(t[r]))?(0<o&&(2===o?o=0:e.lastNeed=o-3),o):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"),o=e("randombytes"),s=e("readable-stream"),a=e("queue-microtask"),c=e("err-code"),{Buffer:l}=e("buffer"),d=65536;class u extends s.Duplex{constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this._id=o(4).toString("hex").slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||o(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||u.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},u.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(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(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=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(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(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(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(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(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(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(e)||new Map;let r=n.get(t);if(r)throw r.removed?c(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(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(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(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(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(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(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(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(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(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=d),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: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(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>d?(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(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(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(c(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={},o={};let s=!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)&&(o[e.id]=e)});const a=e=>{s=!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(o[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)}),s||Object.keys(o).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>d)&&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)}}u.WEBRTC_SUPPORT=!!i(),u.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},u.channelConfig={},t.exports=u},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})}),hn=e.__toESM(un(),1),fn=(e,t)=>{if(!t)return a.resolve(e);const n=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,e).then(e=>{const t=a.createEncoder();return a.writeVarString(t,"AES-GCM"),a.writeVarUint8Array(t,n),a.writeVarUint8Array(t,new Uint8Array(e)),a.toUint8Array(t)})},pn=(e,t)=>{if(!t)return a.resolve(e);const n=a.createDecoder(e);"AES-GCM"!==a.readVarString(n)&&a.reject(a.create$1("Unknown encryption algorithm"));const r=a.readVarUint8Array(n),i=a.readVarUint8Array(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,i).then(e=>new Uint8Array(e))},gn=a.createModuleLogger("y-webrtc"),mn=new Map,yn=new Map,bn=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}]),gn("synced ",a.BOLD,e.name,a.UNBOLD," with all peers"))},wn=(e,t,n)=>{const r=a.createDecoder(t),i=a.createEncoder(),o=a.readVarUint(r);if(void 0===e)return null;const s=e.awareness,c=e.doc;let l=!1;switch(o){case 0:{a.writeVarUint(i,0);const t=J(r,i,c,e);1!==t||e.synced||n(),0===t&&(l=!0);break}case 3:a.writeVarUint(i,1),a.writeVarUint8Array(i,v(s,Array.from(s.getStates().keys()))),l=!0;break;case 1:_(s,a.readVarUint8Array(r),e);break;case 4:{const t=1===a.readUint8(r),n=a.readVarString(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)}]),kn(e)}break}default:return i}return l?i:null},vn=(e,t)=>{gn("send message to ",a.BOLD,e.remotePeerId,a.UNBOLD,a.GREY," (",e.room.name,")",a.UNCOLOR);try{e.peer.send(a.toUint8Array(t))}catch(n){}},_n=class{constructor(e,t,n,r){gn("establishing connection to ",a.BOLD,n),this.room=r,this.remotePeerId=n,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new hn.default({initiator:t,...r.provider.peerOpts}),this.peer.on("signal",t=>{void 0===this.glareToken&&(this.glareToken=Date.now()+Math.random()),xn(e,r,{to:n,from:r.peerId,type:"signal",token:this.glareToken,signal:t})}),this.peer.on("connect",()=>{gn("connected to ",a.BOLD,n),this.connected=!0;const e=r.provider.doc,t=r.awareness,i=a.createEncoder();a.writeVarUint(i,0),z(i,e),vn(this,i);const o=t.getStates();if(o.size>0){const e=a.createEncoder();a.writeVarUint(e,1),a.writeVarUint8Array(e,v(t,Array.from(o.keys()))),vn(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)}])),bn(r),this.peer.destroy(),gn("closed connection to ",a.BOLD,n),Cn(r)}),this.peer.on("error",e=>{gn("Error in connection to ",a.BOLD,n,": ",e),Cn(r)}),this.peer.on("data",e=>{const t=((e,t)=>{const n=e.room;return gn("received message from ",a.BOLD,e.remotePeerId,a.GREY," (",n.name,")",a.UNBOLD,a.UNCOLOR),wn(n,t,()=>{e.synced=!0,gn("synced ",a.BOLD,n.name,a.UNBOLD," with ",a.BOLD,e.remotePeerId),bn(n)})})(this,e);null!==t&&vn(this,t)})}destroy(){this.peer.destroy()}},Sn=(e,t)=>fn(t,e.key).then(t=>e.mux(()=>((e,t,n=null)=>{const r=dn(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))})(e.name,t))),En=(e,t)=>{e.bcconnected&&Sn(e,t),((e,t)=>{gn("broadcast message in ",a.BOLD,e.name,a.UNBOLD),e.webrtcConns.forEach(e=>{try{e.peer.send(t)}catch(n){}})})(e,t)},Cn=e=>{mn.forEach(t=>{t.connected&&(t.send({type:"subscribe",topics:[e.name]}),e.webrtcConns.size<e.provider.maxConns&&xn(t,e,{type:"announce",from:e.peerId}))})},kn=e=>{if(e.provider.filterBcConns){const t=a.createEncoder();a.writeVarUint(t,4),a.writeUint8(t,1),a.writeVarString(t,e.peerId),Sn(e,a.toUint8Array(t))}},Tn=class{constructor(e,t,n,r){this.peerId=a.uuidv4(),this.doc=e,this.awareness=t.awareness,this.provider=t,this.synced=!1,this.name=n,this.key=r,this.webrtcConns=new Map,this.bcConns=new Set,this.mux=a.createMutex(),this.bcconnected=!1,this._bcSubscriber=e=>pn(new Uint8Array(e),r).then(e=>this.mux(()=>{const t=wn(this,e,()=>{});t&&Sn(this,a.toUint8Array(t))})),this._docUpdateHandler=(e,t)=>{const n=a.createEncoder();a.writeVarUint(n,0),X(n,e),En(this,a.toUint8Array(n))},this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{const i=e.concat(t).concat(n),o=a.createEncoder();a.writeVarUint(o,1),a.writeVarUint8Array(o,v(this.awareness,i)),En(this,a.toUint8Array(o))},this._beforeUnloadHandler=()=>{w(this.awareness,[e.clientID],"window unload"),yn.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),Cn(this);const e=this.name;var t,n;t=e,n=this._bcSubscriber,dn(t).subs.add(n),this.bcconnected=!0,kn(this);const r=a.createEncoder();a.writeVarUint(r,0),z(r,this.doc),Sn(this,a.toUint8Array(r));const i=a.createEncoder();a.writeVarUint(i,0),$(i,this.doc),Sn(this,a.toUint8Array(i));const o=a.createEncoder();a.writeVarUint(o,3),Sn(this,a.toUint8Array(o));const s=a.createEncoder();a.writeVarUint(s,1),a.writeVarUint8Array(s,v(this.awareness,[this.doc.clientID])),Sn(this,a.toUint8Array(s))}disconnect(){mn.forEach(e=>{e.connected&&e.send({type:"unsubscribe",topics:[this.name]})}),w(this.awareness,[this.doc.clientID],"disconnect");const e=a.createEncoder();a.writeVarUint(e,4),a.writeUint8(e,0),a.writeVarString(e,this.peerId),Sn(this,a.toUint8Array(e)),((e,t)=>{const n=dn(e),r=n.subs.delete(t);r&&0===n.subs.size&&(n.bc.close(),cn.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)}},xn=(e,t,n)=>{t.key?((e,t)=>{const n=a.createEncoder();return a.writeAny(n,e),fn(a.toUint8Array(n),t)})(n,t.key).then(n=>{e.send({type:"publish",topic:t.name,data:a.toBase64(n)})}):e.send({type:"publish",topic:t.name,data:n})},Rn=class extends an{constructor(e){super(e),this.providers=new Set,this.on("connect",()=>{gn(`connected (${e})`);const t=Array.from(yn.keys());this.send({type:"subscribe",topics:t}),yn.forEach(e=>xn(this,e,{type:"announce",from:e.peerId}))}),this.on("message",e=>{if("publish"===e.type){const r=e.topic,i=yn.get(r);if(null==i||"string"!=typeof r)return;const o=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&&(a.setIfUndefined(t,e.from,()=>new _n(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 gn("offer rejected: ",e.from);n.glareToken=void 0}}if("answer"===e.signal.type){gn("offer answered by: ",e.from);t.get(e.from).glareToken=void 0}e.to===n&&(a.setIfUndefined(t,e.from,()=>new _n(this,!1,e.from,i)).peer.signal(e.signal),r())}};i.key?"string"==typeof e.data&&(t=a.fromBase64(e.data),n=i.key,pn(t,n).then(e=>a.readAny(a.createDecoder(new Uint8Array(e))))).then(o):o(e.data)}var t,n}),this.on("disconnect",()=>gn(`disconnect (${e})`))}},An=e=>{e.emit("status",[{connected:e.connected}])},On=class extends a.ObservableV2{constructor(e,t,{signaling:n=["wss://y-webrtc-eu.fly.dev"],password:r=null,awareness:i=new b(t),maxConns:o=20+a.floor(15*a.rand()),filterBcConns:s=!0,peerOpts:c={}}={}){super(),this.roomName=e,this.doc=t,this.filterBcConns=s,this.awareness=i,this.shouldConnect=!1,this.signalingUrls=n,this.signalingConns=[],this.maxConns=o,this.peerOpts=c,this.key=r?((e,t)=>{const n=a.encodeUtf8(e).buffer,r=a.encodeUtf8(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):a.resolve(null),this.room=null,this.key.then(n=>{this.room=((e,t,n,r)=>{if(yn.has(n))throw a.create$1(`A Yjs Doc connected to room "${n}" already exists!`);const i=new Tn(e,t,n,r);return yn.set(n,i),i})(t,this,e,n),this.shouldConnect?this.room.connect():this.room.disconnect(),An(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=a.setIfUndefined(mn,e,()=>new Rn(e));this.signalingConns.push(t),t.providers.add(this)}),this.room&&(this.room.connect(),An(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),0===e.providers.size&&(e.destroy(),mn.delete(e.url))}),this.room&&(this.room.disconnect(),An(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),yn.delete(this.roomName)}),super.destroy()}};async function Dn(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 a.Doc({guid:e});r.clientID=n;const i=ut(t);r.get("content",a.YXmlText).applyDelta(i);const o=a.encodeStateAsUpdate(r);return r.destroy(),o}var Pn,Nn,Ln={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:o,onError:s,onSyncChange:a}){this.onConnect=i,this.onDisconnect=o,this.onSyncChange=a,this.onError=s;const c={...n,...t&&{document:t},...e&&{awareness:e},...r&&(()=>{try{return{websocketProvider:new oe(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 pe(c)}catch(l){this.provider=new pe({...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:o,onSyncChange:s}){this.document=t??new a.Doc,this.awareness=e??new b(this.document),this.providerOptions=n,this.onConnect=r,this.onDisconnect=i,this.onError=o,this.onSyncChange=s}connect=()=>{if(!this._isDestroyed){if(!this._provider)try{const e=new rn(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:o,onSyncChange:s}){this.onSyncChange=s,this.doc=t||new a.Doc;try{this.provider=new On(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,s?.(!0))):t&&(i?.(),this._isSynced&&(this._isSynced=!1,s?.(!1)))})}catch(c){o?.(c instanceof Error?c:new Error(String(c)))}}get awareness(){return this.provider.awareness}get document(){return this.doc}get isConnected(){return this._isConnected}get isSynced(){return this._isSynced}}},Mn=({type:e,...t})=>{const n=(e=>Ln[e])(e);if(!n)throw new Error(`Provider type "${e}" not found in registry`);return new n(t)},Un=(e,t,n)=>function(e,t,{cursorStateField:n="selection",cursorDataField:r="data",autoSend:i=!0,data:o}={}){const s=e;s.awareness=t,s.cursorDataField=r,s.selectionStateField=n,s.sendCursorData=e=>{s.awareness.setLocalStateField(s.cursorDataField,e)},s.sendCursorPosition=e=>{const t=s.awareness.getLocalState(),r=null==t?void 0:t[n];if(!e)return void(r&&s.awareness.setLocalStateField(s.selectionStateField,null));const{anchor:i,focus:o}=Ot(s.sharedRoot,s,e);r&&a.compareRelativePositions(i,r)&&a.compareRelativePositions(o,r)||s.awareness.setLocalStateField(s.selectionStateField,{anchor:i,focus:o})};const c=e=>{const t=qt.get(s);if(!t)return;const n=s.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:l,disconnect:d}=s;return s.connect=()=>{if(l(),s.awareness.on("change",c),c({removed:[],added:Array.from(s.awareness.getStates().keys()),updated:[]}),i){o&&Yt.sendCursorData(s,o);const{onChange:e}=s;s.onChange=()=>{e(),Bt.connected(s)&&Yt.sendCursorPosition(s)}}},s.disconnect=()=>{s.awareness.off("change",c),c({removed:Array.from(s.awareness.getStates().keys()),added:[],updated:[]}),d()},s}(e,t,n),jn=(e,t)=>function(e,t={}){var n=t,{withoutSavingOrigin:r=Wt,trackedOrigins:o=new Set([e.localOrigin])}=n,s=Je(n,["withoutSavingOrigin","trackedOrigins"]);const c=e;c.undoManager=new a.UndoManager(c.sharedRoot,Xe({trackedOrigins:o},s)),c.withoutSavingOrigin=r;const{onChange:l,isLocalOrigin:d}=c;c.onChange=()=>{l(),Vt.set(c,c.selection&&Ot(c.sharedRoot,c,c.selection))},c.isLocalOrigin=e=>e===c.withoutSavingOrigin||d(e);const u=({stackItem:e})=>{e.meta.set("selection",c.selection&&Ot(c.sharedRoot,c,c.selection)),e.meta.set("selectionBefore",Vt.get(c))},h=({stackItem:e})=>{e.meta.set("selection",c.selection&&Ot(c.sharedRoot,c,c.selection))},f=({stackItem:e,type:t})=>{const n="undo"===t?c.undoManager.redoStack:c.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 o=e.meta.get("selectionBefore");if(!o)return;const s=Dt(c.sharedRoot,c,o);s&&i.Transforms.select(c,s)},{connect:p,disconnect:g}=c;return c.connect=()=>{p(),c.undoManager.on("stack-item-added",u),c.undoManager.on("stack-item-popped",f),c.undoManager.on("stack-item-updated",h)},c.disconnect=()=>{c.undoManager.off("stack-item-added",u),c.undoManager.off("stack-item-popped",f),c.undoManager.off("stack-item-updated",h),g()},c.undo=()=>{Bt.connected(c)&&(Bt.flushLocalChanges(c),c.undoManager.undo())},c.redo=()=>{Bt.connected(c)&&(Bt.flushLocalChanges(c),c.undoManager.redo())},c}(e,t),In=e=>"object"==typeof e&&null!==e&&"type"in e&&"options"in e,Bn=i.createTSlatePlugin({key:i.KEYS.yjs,extendEditor:({editor:e,getOptions:t})=>{let n=e;const{awareness:r,cursors:i,localOrigin:o,positionStorageOrigin:s,sharedType:c,ydoc:l}=t();if(n=((e,t,n)=>Ft(e,t,n))(n,c??l.get("content",a.YXmlText),{autoConnect:!1,localOrigin:o,positionStorageOrigin:s}),i)if(r){let e=!0;!1===i.autoSend&&(e=!1),n=Un(n,r,{...i,autoSend:e})}else n.api.debug.error("Yjs plugin: Internal shared awareness (awareness) is missing but cursors are enabled.");return jn(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:o}=r;return o||(o=new a.Doc),i||(i=new b(o)),{options:{awareness:i,localOrigin:t??void 0,positionStorageOrigin:n??void 0,ydoc:o}}}).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{Bt.disconnect(t)}catch{}},disconnect:t=>{const{editor:n,getOptions:r}=e,{_providers:i}=r(),o=t?Array.isArray(t)?t:[t]:null;for(const e of[...i].reverse())try{!e.isConnected&&!e.isConnectionPending||null!==o&&!o.includes(e.type)||e.disconnect()}catch(s){}},init:async({id:t,autoConnect:n=!0,autoSelect:r,selection:i,value:o,onReady:s}={})=>{const{editor:c,getOptions:l,setOption:d}=e,{awareness:u,providers:h=[],sharedType:f,ydoc:p}=l(),g=()=>{return(e=f??p.get("content",a.YXmlText)).length>0||null!=e._start;var e};if(0===h.length)throw new Error("No providers specified. Please provide provider configurations or instances in the `providers` array.");const m=[];let y=null;const b=new Promise(e=>{y=e});for(const e of h)if(In(e)){const{options:t,type:n}=e;let r=null;if(!t)continue;try{const e=Mn({awareness:u,doc:p,options:t,type:n,onConnect:()=>{l().onConnect?.({type:n}),d("_isConnected",!0)},onDisconnect:()=>{l().onDisconnect?.({type:n});const{_providers:e}=l();e.some(e=>e.isConnected)||d("_isConnected",!1)},onError:e=>{l().onError?.({error:e,type:n})},onSyncChange:e=>{l().onSyncChange?.({isSynced:e,type:n}),d("_isSynced",e);const t=m.some(e=>!e.isLocalPersistence),i=!r?.isLocalPersistence||!t||g();e&&y&&i&&(y(),y=null)}});r=e,m.push(e)}catch{}}else m.push(e);if(d("_providers",m),n&&m.length>0){m.forEach(e=>{try{e.connect()}catch(t){l().onError?.({error:t instanceof Error?t:new Error(String(t)),type:e.type})}});const e=5e3;await Promise.race([b,new Promise(t=>{setTimeout(()=>{y=null,t()},e)})])}if(!g()&&!m.some(e=>e.isLocalPersistence&&(e.isConnectionPending||e.isSyncPending))&&null!==o){let e=o;if("string"==typeof o?e=c.api.html.deserialize({element:o}):"function"==typeof o?e=await o(c):o&&(e=o),e&&0!==e?.length||(e=c.api.create.value()),f){const t=ut(e);p.transact(()=>{f.applyDelta(t)})}else{const n=await Dn(t??c.id,e);p.transact(()=>{a.applyUpdate(p,n)})}}Bt.connect(c),c.tf.init({autoSelect:r,selection:i,shouldNormalizeEditor:!1,value:null}),c.api.onChange(),s?.({editor:c,isAsync:!0,value:c.children})}})),Fn=i.toPlatePlugin(Bn),Vn=i.require_lib(),Wn=globalThis.Node,qn=(globalThis.Element,globalThis.Text),Yn=(globalThis.Range,globalThis.Selection,globalThis.StaticRange,e=>e&&e.ownerDocument&&e.ownerDocument.defaultView||null),Hn=e=>zn(e)&&8===e.nodeType,Kn=e=>zn(e)&&1===e.nodeType,zn=e=>{var t=Yn(e);return!!t&&e instanceof t.Node},$n=e=>{var t=e&&e.anchorNode&&Yn(e.anchorNode);return!!t&&e instanceof t.Selection},Gn=(e,t,n)=>{if("number"!=typeof t)throw new Error("Expected index to be a number");for(var{childNodes:r}=e,i=r[t],o=t,s=!1,a=!1;(Hn(i)||Kn(i)&&0===i.childNodes.length||Kn(i)&&"false"===i.getAttribute("contenteditable"))&&(!s||!a);)o>=r.length?(s=!0,o=t-1,n="backward"):o<0?(a=!0,o=t+1,n="forward"):(i=r[o],t=o,o+="forward"===n?1:-1);return[i,t]},Xn=(e,t,n)=>{var[r]=Gn(e,t,n);return r},Qn=e=>null!=e.getSelection?e.getSelection():document.getSelection(),Jn=(e,t,n)=>{var{target:r}=t;if(Kn(r)&&r.matches('[contentEditable="false"]'))return!1;var{document:i}=kr.getWindow(e);if(tr(i,r))return kr.hasDOMNode(e,r,{editable:!0});var o=n.find(e=>{var{addedNodes:t,removedNodes:n}=e;for(var i of t)if(i===r||tr(i,r))return!0;for(var o of n)if(o===r||tr(o,r))return!0});return!(!o||o===t)&&Jn(e,o,n)},Zn=(e,t)=>Boolean(e.compareDocumentPosition(t)&Wn.DOCUMENT_POSITION_PRECEDING),er=(e,t)=>{if(!e)return null;for(var n=e;n;){if(n.matches&&n.matches(t))return n;if(n.parentElement)n=n.parentElement;else{if(!n.parentNode||!("host"in n.parentNode))return null;n=n.parentNode.host}}return null},tr=(e,t)=>{if(!e||!t)return!1;if(e.contains(t))return!0;for(var n=t;n;){if(n===e)return!0;if(!n.parentNode)return!1;n="host"in n.parentNode?n.parentNode.host:n.parentNode}return!1},nr=("undefined"!=typeof navigator&&"undefined"!=typeof window&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&window.MSStream,"undefined"!=typeof navigator&&/Mac OS X/.test(navigator.userAgent)),rr="undefined"!=typeof navigator&&/Android/.test(navigator.userAgent),ir="undefined"!=typeof navigator&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),or=("undefined"!=typeof navigator&&/AppleWebKit(?!.*Chrome)/i.test(navigator.userAgent),"undefined"!=typeof navigator&&/Edge?\/(?:[0-6][0-9]|[0-7][0-8])(?:\.)/i.test(navigator.userAgent)),sr="undefined"!=typeof navigator&&/Chrome/i.test(navigator.userAgent),ar="undefined"!=typeof navigator&&/Chrome?\/(?:[0-7][0-5]|[0-6][0-9])(?:\.)/i.test(navigator.userAgent),cr=rr&&"undefined"!=typeof navigator&&/Chrome?\/(?:[0-5]?\d)(?:\.)/i.test(navigator.userAgent);"undefined"!=typeof navigator&&/^(?!.*Seamonkey)(?=.*Firefox\/(?:[0-7][0-9]|[0-8][0-6])(?:\.)).*/i.test(navigator.userAgent),"undefined"!=typeof navigator&&/.*UCBrowser/.test(navigator.userAgent),"undefined"!=typeof navigator&&/.*Wechat/.test(navigator.userAgent)&&/.*MacWechat/.test(navigator.userAgent),"undefined"==typeof window||void 0===window.document||window.document.createElement;"undefined"!=typeof navigator&&/Safari/.test(navigator.userAgent)&&/Version\/(\d+)/.test(navigator.userAgent)&&null!==(Pn=navigator.userAgent.match(/Version\/(\d+)/))&&void 0!==Pn&&Pn[1]&&parseInt(null===(Nn=navigator.userAgent.match(/Version\/(\d+)/))||void 0===Nn?void 0:Nn[1],10);(!ar||!cr)&&!or&&"undefined"!=typeof globalThis&&globalThis.InputEvent&&globalThis.InputEvent.prototype.getTargetRanges;function lr(e){return lr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},lr(e)}function dr(e){var t=function(e,t){if("object"!==lr(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!==lr(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===lr(t)?t:String(t)}var ur=0,hr=class{constructor(){var e,t,n;e=this,n=void 0,(t=dr(t="id"))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,this.id="".concat(ur++)}},fr=new WeakMap,pr=new WeakMap,gr=new WeakMap,mr=new WeakMap,yr=new WeakMap,br=new WeakMap,wr=new WeakMap,vr=new WeakMap,_r=new WeakMap,Sr=new WeakMap,Er=new WeakMap,Cr=new WeakMap,kr={androidPendingDiffs:e=>Cr.get(e),androidScheduleFlush:e=>{var t;null===(t=Er.get(e))||void 0===t||t()},blur:e=>{var t=kr.toDOMNode(e,e),n=kr.findDocumentOrShadowRoot(e);_r.set(e,!1),n.activeElement===t&&t.blur()},deselect:e=>{var{selection:t}=e,n=Qn(kr.findDocumentOrShadowRoot(e));n&&n.rangeCount>0&&n.removeAllRanges(),t&&i.Transforms.deselect(e)},findDocumentOrShadowRoot:e=>{var t=kr.toDOMNode(e,e),n=t.getRootNode();return n instanceof Document||n instanceof ShadowRoot?n:t.ownerDocument},findEventRange:(e,t)=>{"nativeEvent"in t&&(t=t.nativeEvent);var{clientX:n,clientY:r,target:o}=t;if(null==n||null==r)throw new Error("Cannot resolve a Slate range from a DOM event: ".concat(t));var s,a=kr.toSlateNode(e,t.target),c=kr.findPath(e,a);if(i.Node.isElement(a)&&i.Editor.isVoid(e,a)){var l=o.getBoundingClientRect(),d=e.isInline(a)?n-l.left<l.left+l.width-n:r-l.top<l.top+l.height-r,u=i.Editor.point(e,c,{edge:d?"start":"end"}),h=d?i.Editor.before(e,u):i.Editor.after(e,u);if(h)return i.Editor.range(e,h)}var{document:f}=kr.getWindow(e);if(f.caretRangeFromPoint)s=f.caretRangeFromPoint(n,r);else{var p=f.caretPositionFromPoint(n,r);p&&((s=f.createRange()).setStart(p.offsetNode,p.offset),s.setEnd(p.offsetNode,p.offset))}if(!s)throw new Error("Cannot resolve a Slate range from a DOM event: ".concat(t));return kr.toSlateRange(e,s,{exactMatch:!1,suppressThrow:!1})},findKey:(e,t)=>{var n=br.get(t);return n||(n=new hr,br.set(t,n)),n},findPath:(e,t)=>{for(var n=[],r=t;;){var o=pr.get(r);if(null==o){if(r===e)return n;break}var s=fr.get(r);if(null==s)break;n.unshift(s),r=o}throw new Error("Unable to find the path for Slate node: ".concat(i.Scrubber.stringify(t)))},focus:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{retries:5};if(!_r.get(e)&&mr.get(e)){if(t.retries<=0)throw new Error("Could not set focus, editor seems stuck with pending operations");if(e.operations.length>0)setTimeout(()=>{kr.focus(e,{retries:t.retries-1})},10);else{var n=kr.toDOMNode(e,e),r=kr.findDocumentOrShadowRoot(e);if(r.activeElement!==n){if(e.selection&&r instanceof Document){var o=Qn(r),s=kr.toDOMRange(e,e.selection);null==o||o.removeAllRanges(),null==o||o.addRange(s)}e.selection||i.Transforms.select(e,i.Editor.start(e,[])),_r.set(e,!0),n.focus({preventScroll:!0})}}}},getWindow:e=>{var t=gr.get(e);if(!t)throw new Error("Unable to find a host window element for this editor");return t},hasDOMNode:function(e,t){var n,{editable:r=!1}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=kr.toDOMNode(e,e);try{n=Kn(t)?t:t.parentElement}catch(o){if(o instanceof Error&&!o.message.includes('Permission denied to access property "nodeType"'))throw o}return!!n&&!(er(n,"[data-slate-editor]")!==i||r&&!n.isContentEditable&&("boolean"!=typeof n.isContentEditable||er(n,'[contenteditable="false"]')!==i)&&!n.getAttribute("data-slate-zero-width"))},hasEditableTarget:(e,t)=>zn(t)&&kr.hasDOMNode(e,t,{editable:!0}),hasRange:(e,t)=>{var{anchor:n,focus:r}=t;return i.Editor.hasPath(e,n.path)&&i.Editor.hasPath(e,r.path)},hasSelectableTarget:(e,t)=>kr.hasEditableTarget(e,t)||kr.isTargetInsideNonReadonlyVoid(e,t),hasTarget:(e,t)=>zn(t)&&kr.hasDOMNode(e,t),insertData:(e,t)=>{e.insertData(t)},insertFragmentData:(e,t)=>e.insertFragmentData(t),insertTextData:(e,t)=>e.insertTextData(t),isComposing:e=>!!Sr.get(e),isFocused:e=>!!_r.get(e),isReadOnly:e=>!!vr.get(e),isTargetInsideNonReadonlyVoid:(e,t)=>{if(vr.get(e))return!1;if(!kr.hasTarget(e,t))return!1;var n=kr.toSlateNode(e,t);return i.Node.isElement(n)&&i.Editor.isVoid(e,n)},setFragmentData:(e,t,n)=>e.setFragmentData(t,n),toDOMNode:(e,t)=>{var n,r=t===e?mr.get(e):null===(n=wr.get(e))||void 0===n?void 0:n.get(kr.findKey(e,t));if(!r)throw new Error("Cannot resolve a DOM node from Slate node: ".concat(i.Scrubber.stringify(t)));return r},toDOMPoint:(e,t)=>{var n,[r]=i.Editor.node(e,t.path),o=kr.toDOMNode(e,r);i.Editor.void(e,{at:t})&&(t={path:t.path,offset:0});for(var s=Array.from(o.querySelectorAll("[data-slate-string], [data-slate-zero-width]")),a=0,c=0;c<s.length;c++){var l=s[c],d=l.childNodes[0];if(null!=d&&null!=d.textContent){var{length:u}=d.textContent,h=l.getAttribute("data-slate-length"),f=a+(null==h?u:parseInt(h,10)),p=s[c+1];if(t.offset===f&&null!=p&&p.hasAttribute("data-slate-mark-placeholder")){var g,m=p.childNodes[0];n=[m instanceof qn?m:p,null!==(g=p.textContent)&&void 0!==g&&g.startsWith("\ufeff")?1:0];break}if(t.offset<=f){n=[d,Math.min(u,Math.max(0,t.offset-a))];break}a=f}}if(!n)throw new Error("Cannot resolve a DOM point from Slate point: ".concat(i.Scrubber.stringify(t)));return n},toDOMRange:(e,t)=>{var{anchor:n,focus:r}=t,o=i.Range.isBackward(t),s=kr.toDOMPoint(e,n),a=i.Range.isCollapsed(t)?s:kr.toDOMPoint(e,r),c=kr.getWindow(e).document.createRange(),[l,d]=o?a:s,[u,h]=o?s:a,f=!!(Kn(l)?l:l.parentElement).getAttribute("data-slate-zero-width"),p=!!(Kn(u)?u:u.parentElement).getAttribute("data-slate-zero-width");return c.setStart(l,f?1:d),c.setEnd(u,p?1:h),c},toSlateNode:(e,t)=>{var n=Kn(t)?t:t.parentElement;n&&!n.hasAttribute("data-slate-node")&&(n=n.closest("[data-slate-node]"));var r=n?yr.get(n):null;if(!r)throw new Error("Cannot resolve a Slate node from DOM node: ".concat(n));return r},toSlatePoint:(e,t,n)=>{var r,o,{exactMatch:s,suppressThrow:a}=n,[c,l]=s?t:(e=>{var[t,n]=e;if(Kn(t)&&t.childNodes.length){var r=n===t.childNodes.length,i=r?n-1:n;for([t,i]=Gn(t,i,r?"backward":"forward"),r=i<n;Kn(t)&&t.childNodes.length;){var o=r?t.childNodes.length-1:0;t=Xn(t,o,r?"backward":"forward")}n=r&&null!=t.textContent?t.textContent.length:0}return[t,n]})(t),d=c.parentNode,u=n.searchDirection,h=null,f=0;if(d){var p,g,m=kr.toDOMNode(e,e),y=d.closest('[data-slate-void="true"]'),b=y&&tr(m,y)?y:null,w=d.closest('[contenteditable="false"]'),v=w&&tr(m,w)?w:null,_=d.closest("[data-slate-leaf]"),S=null;if(_){if(h=_.closest('[data-slate-node="text"]')){var E=kr.getWindow(e).document.createRange();E.setStart(h,0),E.setEnd(c,l);var C=E.cloneContents();[...Array.prototype.slice.call(C.querySelectorAll("[data-slate-zero-width]")),...Array.prototype.slice.call(C.querySelectorAll("[contenteditable=false]"))].forEach(e=>{rr&&!s&&e.hasAttribute("data-slate-zero-width")&&e.textContent.length>0&&"\ufeff"!==e.textContext?e.textContent.startsWith("\ufeff")&&(e.textContent=e.textContent.slice(1)):e.parentNode.removeChild(e)}),f=C.textContent.length,S=h}}else if(b){for(var k=b.querySelectorAll("[data-slate-leaf]"),T=0;T<k.length;T++){var x=k[T];if(kr.hasDOMNode(e,x)){_=x;break}}_?(h=_.closest('[data-slate-node="text"]'),f=(S=_).textContent.length,S.querySelectorAll("[data-slate-zero-width]").forEach(e=>{f-=e.textContent.length})):f=1}else if(v){var R,A,O=e=>e?e.querySelectorAll("[data-slate-leaf]:not(:scope [data-slate-editor] [data-slate-leaf])"):[],D=v.closest('[data-slate-node="element"]');if("backward"===u||!u)(_=null!==(R=[...O(null==D?void 0:D.previousElementSibling),...O(D)].findLast(e=>Zn(v,e)))&&void 0!==R?R:null)&&(u="backward");if("forward"===u||!u)_=null!==(A=[...O(D),...O(null==D?void 0:D.nextElementSibling)].find(e=>((e,t)=>Boolean(e.compareDocumentPosition(t)&Wn.DOCUMENT_POSITION_FOLLOWING))(v,e)))&&void 0!==A?A:null,_&&(u="forward");_&&(h=_.closest('[data-slate-node="text"]'),S=_,"forward"===u?f=0:(f=S.textContent.length,S.querySelectorAll("[data-slate-zero-width]").forEach(e=>{f-=e.textContent.length})))}S&&f===S.textContent.length&&rr&&"z"===S.getAttribute("data-slate-zero-width")&&null!==(p=S.textContent)&&void 0!==p&&p.startsWith("\ufeff")&&(d.hasAttribute("data-slate-zero-width")||ir&&null!==(g=S.textContent)&&void 0!==g&&g.endsWith("\n\n"))&&f--}if(rr&&!h&&!s){var P=d.hasAttribute("data-slate-node")?d:d.closest("[data-slate-node]");if(P&&kr.hasDOMNode(e,P,{editable:!0})){var N,L=kr.toSlateNode(e,P);try{N=kr.findPath(e,L)}catch(j){if(a)return null;throw j}var{path:M,offset:U}=i.Editor.start(e,N);return P.querySelector("[data-slate-leaf]")||(U=l),{path:M,offset:U}}}if(!h){if(a)return null;throw new Error("Cannot resolve a Slate point from DOM point: ".concat(t))}try{r=kr.toSlateNode(e,h)}catch(j){if(a)return null;throw j}try{o=kr.findPath(e,r)}catch(j){if(a)return null;throw j}return{path:o,offset:f}},toSlateRange:(e,t,n)=>{var r,o,s,a,c,l,{exactMatch:d,suppressThrow:u}=n;if($n(t)?t.anchorNode:t.startContainer)if($n(t)){if(ir&&t.rangeCount>1){a=t.focusNode;var h=t.getRangeAt(0),f=t.getRangeAt(t.rangeCount-1);if(a instanceof HTMLTableRowElement&&h.startContainer instanceof HTMLTableRowElement&&f.startContainer instanceof HTMLTableRowElement){function p(e){return e.childElementCount>0?p(e.children[0]):e}var g=h.startContainer,m=f.startContainer,y=p(g.children[h.startOffset]),b=p(m.children[f.startOffset]);c=0,o=b.childNodes.length>0?b.childNodes[0]:b,a=y.childNodes.length>0?y.childNodes[0]:y,s=b instanceof HTMLElement?b.innerHTML.length:0}else h.startContainer===a?(o=f.endContainer,s=f.endOffset,c=h.startOffset):(o=h.startContainer,s=h.endOffset,c=f.startOffset)}else o=t.anchorNode,s=t.anchorOffset,a=t.focusNode,c=t.focusOffset;l=sr&&(e=>{for(var t=e&&e.parentNode;t;){if("[object ShadowRoot]"===t.toString())return!0;t=t.parentNode}return!1})(o)||ir?t.anchorNode===t.focusNode&&t.anchorOffset===t.focusOffset:t.isCollapsed}else o=t.startContainer,s=t.startOffset,a=t.endContainer,c=t.endOffset,l=t.collapsed;if(null==o||null==a||null==s||null==c)throw new Error("Cannot resolve a Slate range from DOM range: ".concat(t));ir&&null!==(r=a.textContent)&&void 0!==r&&r.endsWith("\n\n")&&c===a.textContent.length&&c--;var w=kr.toSlatePoint(e,[o,s],{exactMatch:d,suppressThrow:u});if(!w)return null;var v=Zn(o,a)||o===a&&c<s,_=l?w:kr.toSlatePoint(e,[a,c],{exactMatch:d,suppressThrow:u,searchDirection:v?"forward":"backward"});if(!_)return null;var S={anchor:w,focus:_};return i.Range.isExpanded(S)&&i.Range.isForward(S)&&Kn(a)&&i.Editor.void(e,{at:S.focus,mode:"highest"})&&(S=i.Editor.unhangRange(e,S,{voids:!0})),S}},Tr={bold:"mod+b",compose:["down","left","right","up","backspace","enter"],moveBackward:"left",moveForward:"right",moveWordBackward:"ctrl+left",moveWordForward:"ctrl+right",deleteBackward:"shift?+backspace",deleteForward:"shift?+delete",extendBackward:"shift+left",extendForward:"shift+right",italic:"mod+i",insertSoftBreak:"shift+enter",splitBlock:"enter",undo:"mod+z"},xr={moveLineBackward:"opt+up",moveLineForward:"opt+down",moveWordBackward:"opt+left",moveWordForward:"opt+right",deleteBackward:["ctrl+backspace","ctrl+h"],deleteForward:["ctrl+delete","ctrl+d"],deleteLineBackward:"cmd+shift?+backspace",deleteLineForward:["cmd+shift?+delete","ctrl+k"],deleteWordBackward:"opt+shift?+backspace",deleteWordForward:"opt+shift?+delete",extendLineBackward:"opt+shift+up",extendLineForward:"opt+shift+down",redo:"cmd+shift+z",transposeCharacter:"ctrl+t"},Rr={deleteWordBackward:"ctrl+shift?+backspace",deleteWordForward:"ctrl+shift?+delete",redo:["ctrl+y","ctrl+shift+z"]},Ar=e=>{var t=Tr[e],n=xr[e],r=Rr[e],i=t&&(0,Vn.isHotkey)(t),o=n&&(0,Vn.isHotkey)(n),s=r&&(0,Vn.isHotkey)(r);return e=>!(!i||!i(e))||(!!(nr&&o&&o(e))||!(nr||!s||!s(e)))};Ar("bold"),Ar("compose"),Ar("moveBackward"),Ar("moveForward"),Ar("deleteBackward"),Ar("deleteForward"),Ar("deleteLineBackward"),Ar("deleteLineForward"),Ar("deleteWordBackward"),Ar("deleteWordForward"),Ar("extendBackward"),Ar("extendForward"),Ar("extendLineBackward"),Ar("extendLineForward"),Ar("italic"),Ar("moveLineBackward"),Ar("moveLineForward"),Ar("moveWordBackward"),Ar("moveWordForward"),Ar("redo"),Ar("insertSoftBreak"),Ar("splitBlock"),Ar("transposeCharacter"),Ar("undo"),i.require_direction(),i.require_debounce(),i.require_throttle();function Or(e){return Or="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Or(e)}function Dr(e){var t=function(e,t){if("object"!==Or(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!==Or(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===Or(t)?t:String(t)}function Pr(e,t,n){return(t=Dr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Nr=(0,c.createContext)(null),Lr=kr,Mr={subtree:!0,childList:!0,characterData:!0,characterDataOldValue:!0},Ur=class extends c.Component{constructor(){super(...arguments),Pr(this,"context",null),Pr(this,"manager",null),Pr(this,"mutationObserver",null)}observe(){var e,{node:t}=this.props;if(!t.current)throw new Error("Failed to attach MutationObserver, `node` is undefined");null===(e=this.mutationObserver)||void 0===e||e.observe(t.current,Mr)}componentDidMount(){var{receivedUserInput:e}=this.props,t=this.context;this.manager=((e,t)=>{var n=[],r=()=>{n=[]};return{registerMutations:r=>{if(t.current){var i=r.filter(t=>Jn(e,t,r));n.push(...i)}},restoreDOM:function(){n.length>0&&(n.reverse().forEach(e=>{"characterData"!==e.type&&(e.removedNodes.forEach(t=>{e.target.insertBefore(t,e.nextSibling)}),e.addedNodes.forEach(t=>{e.target.removeChild(t)}))}),r())},clear:r}})(t,e),this.mutationObserver=new MutationObserver(this.manager.registerMutations),this.observe()}getSnapshotBeforeUpdate(){var e,t,n,r,i=null===(e=this.mutationObserver)||void 0===e?void 0:e.takeRecords();null!=i&&i.length&&(null===(r=this.manager)||void 0===r||r.registerMutations(i));return null===(t=this.mutationObserver)||void 0===t||t.disconnect(),null===(n=this.manager)||void 0===n||n.restoreDOM(),null}componentDidUpdate(){var e;null===(e=this.manager)||void 0===e||e.clear(),this.observe()}componentWillUnmount(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect()}render(){return this.props.children}};Pr(Ur,"contextType",Nr);parseInt(c.default.version.split(".")[0],10);var jr=Object.defineProperty,Ir=Object.defineProperties,Br=Object.getOwnPropertyDescriptors,Fr=Object.getOwnPropertySymbols,Vr=Object.prototype.hasOwnProperty,Wr=Object.prototype.propertyIsEnumerable,qr=(e,t,n)=>t in e?jr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Yr=(e,t)=>{for(var n in t||(t={}))Vr.call(t,n)&&qr(e,n,t[n]);if(Fr)for(var n of Fr(t))Wr.call(t,n)&&qr(e,n,t[n]);return e},Hr=new WeakMap;function Kr(e,t){if(!t.relativeSelection)return null;let n=Hr.get(e.children);n||(n=new WeakMap,Hr.set(e.children,n));let r=n.get(t);if(void 0===r)try{r=Dt(e.sharedRoot,e,t.relativeSelection),n.set(t,r)}catch(i){return null}return r}function zr(){const e=(()=>{var e=(0,c.useContext)(Nr);if(!e)throw new Error("The `useSlateStatic` hook must be used inside the <Slate> component's context.");return e})();if(!Yt.isCursorEditor(e))throw new Error("Cannot use useSyncExternalStore outside the context of a RemoteCursorEditor");return e}var $r=new WeakMap;function Gr(e){const t=$r.get(e);if(t)return t;const n=function(e){let t={};const n=new Set,r=n.add.bind(n),i=new Set;let o=null;return[t=>(i.add(t),o||(o=e=>{e.added.forEach(r),e.removed.forEach(r),e.updated.forEach(r),i.forEach(e=>e())},Yt.on(e,"change",o)),()=>{i.delete(t),o&&0===i.size&&(Yt.off(e,"change",o),o=null)}),()=>(0===n.size||(n.forEach(n=>{const r=Yt.cursorState(e,n);null!==r?t[n]=r:delete t[n.toString()]}),n.clear(),t=Yr({},t)),t)]}(e);return $r.set(e,n),n}function Xr(){const[e,t]=Gr(zr());return(0,m.useSyncExternalStore)(e,t)}function Qr(e,t,{yOffset:n,xOffset:r,shouldGenerateOverlay:o}){const[s,a]=i.Range.edges(t),c=function(e,t){try{return Lr.toDOMRange(e,t)}catch(n){return null}}(e,t);if(!c)return{caretPosition:null,selectionRects:[]};const l=[],d=i.Editor.nodes(e,{at:t,match:(e,t)=>i.Text.isText(e)&&(!o||o(e,t))});let u=null;const h=i.Range.isBackward(t);for(const[f,p]of d){const o=Lr.toDOMNode(e,f),d=i.Path.equals(p,s.path),g=i.Path.equals(p,a.path);let m=null;if(d||g){const e=document.createRange();e.selectNode(o),d&&e.setStart(c.startContainer,c.startOffset),g&&e.setEnd(c.endContainer,c.endOffset),m=e.getClientRects()}else m=o.getClientRects();const y=h?d:g;for(let e=0;e<m.length;e++){const o=m.item(e);if(!o)continue;const s=y&&(h?0===e:e===m.length-1),a=o.top-n,c=o.left-r;s&&(u={height:o.height,top:a,left:c+(h||i.Range.isCollapsed(t)?0:o.width)}),l.push({width:o.width,height:o.height,top:a,left:c})}}return{selectionRects:l,caretPosition:u}}var Jr=Object.freeze([]);function Zr(e={}){var t,n=e,{containerRef:r,shouldGenerateOverlay:i}=n,o=((e,t)=>{var n={};for(var r in e)Vr.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&Fr)for(var r of Fr(e))t.indexOf(r)<0&&Wr.call(e,r)&&(n[r]=e[r]);return n})(n,["containerRef","shouldGenerateOverlay"]);const s=zr(),a=Xr(),c=function(){const[,e]=(0,l.useReducer)(e=>e+1,0),t=(0,l.useRef)(null),n=()=>{t.current&&(cancelAnimationFrame(t.current),t.current=0)};return(0,l.useEffect)(n),(0,l.useEffect)(()=>n,[]),(0,l.useCallback)((n=!1)=>{n?e():t.current||(t.current=requestAnimationFrame(e))},[])}(),d=(0,l.useRef)(new WeakMap),[u,h]=(0,l.useState)({}),f=!("refreshOnResize"in o)||(null==(t=o.refreshOnResize)||t);return function(e,t){const n=(0,l.useRef)(t);n.current=t;const[r]=(0,l.useState)(()=>new ResizeObserver(()=>{n.current()}));(0,l.useEffect)(()=>{if(!(null==e?void 0:e.current))return;const{current:t}=e;return r.observe(t),()=>r.unobserve(t)},[r,e])}(f?r:void 0,()=>{d.current=new WeakMap,c("debounced"!==f)}),(0,l.useLayoutEffect)(()=>{var e,t,n;if(r&&!r.current)return;const o=null==(e=null==r?void 0:r.current)?void 0:e.getBoundingClientRect(),c=null!=(t=null==o?void 0:o.x)?t:0,l=null!=(n=null==o?void 0:o.y)?n:0;let f=Object.keys(u).length!==Object.keys(a).length;const p=Object.fromEntries(Object.entries(a).map(([e,t])=>{const n=t.relativeSelection&&Kr(s,t);if(!n)return[e,Jr];const r=d.current.get(n);if(r)return[e,r];const o=Qr(s,n,{xOffset:c,yOffset:l,shouldGenerateOverlay:i});return f=!0,d.current.set(n,o),[e,o]}));f&&h(p)}),[(0,l.useMemo)(()=>Object.entries(a).map(([e,t])=>{var n,r;const i=t.relativeSelection&&Kr(s,t),o=u[e];return a=Yr({},t),c={range:i,caretPosition:null!=(n=null==o?void 0:o.caretPosition)?n:null,selectionRects:null!=(r=null==o?void 0:o.selectionRects)?r:Jr},Ir(a,Br(c));var a,c}),[a,s,u]),(0,l.useCallback)(()=>{d.current=new WeakMap,c(!0)},[c])]}function ei(){return i.usePluginOption(Fn,"_isSynced")?(0,h.jsx)(ti,{}):null}function ti(){const e=i.useEditorContainerRef(),[t]=Zr({containerRef:e});return(0,h.jsx)(h.Fragment,{children:t.map(e=>(0,h.jsx)(ni,{...e},e.clientId))})}function ni({caretPosition:e,data:t,selectionRects:n}){if(!t)return null;const r={backgroundColor:(i=t.color,o=.5,i+Math.round(255*Math.min(Math.max(o,0),1)).toString(16).padStart(2,"0").toUpperCase())};var i,o;return(0,h.jsxs)(h.Fragment,{children:[n.map((e,t)=>(0,h.jsx)("div",{className:"pointer-events-none absolute",style:{...r,...e}},t)),e&&(0,h.jsx)(oi,{data:t,caretPosition:e})]})}var ri=.7,ii=1;function oi({caretPosition:e,data:t}){const[n,r]=l.useState(!1),i={...e,background:t?.color,opacity:ri,transition:"opacity 0.2s"},o={...i,opacity:ii},s={background:t?.color,opacity:ri,transform:"translateY(-100%)",transition:"opacity 0.2s"},a={...s,opacity:ii};return(0,h.jsx)("div",{className:"absolute w-0.5",style:n?o:i,children:(0,h.jsx)("div",{className:"absolute top-0 whitespace-nowrap rounded rounded-bl-none px-1.5 py-0.5 text-white text-xs",style:n?a:s,onMouseEnter:()=>{r(!0)},onMouseLeave:()=>{r(!1)},children:t?.name})})}function si({documentId:e,initialValue:t=i.EMPTY_PLATE_VALUE,user:n,authToken:r,className:o,renderToolbar:s,overlays:a}){const c=me("plate",e),d=n.color??_e(n.id),u=Boolean(r),f=i.usePlateEditor({plugins:u?[...i.platePlugins,Fn.configure({options:{cursors:{data:{color:d,name:n.name}},providers:we({documentId:e,token:r})},render:{afterEditable:ei}})]:i.platePlugins,skipInitialization:u,value:u?void 0:t},[c,u]);l.useEffect(()=>{if(u)return f.getApi(Fn).yjs.init({id:c,value:t}),()=>{f.getApi(Fn).yjs.destroy()}},[u,f,c]);const[,p]=l.useReducer(e=>e+1,0),g=l.useMemo(()=>f?We(f):S("plate"),[f]);return l.useEffect(()=>{p()},[f]),(0,h.jsx)("div",{className:`flex h-full min-h-0 w-full flex-col ${o??""}`,"data-room":c,children:(0,h.jsxs)(i.Plate,{editor:f,children:[s?s(g):(0,h.jsx)(O,{adapter:g}),(0,h.jsxs)(i.EditorContainer,{className:"relative min-h-0 flex-1",children:[(0,h.jsx)(i.Editor$1,{placeholder:"Start writing…",variant:"default"}),a]})]})})}exports.EMPTY_PLATE_VALUE=i.EMPTY_PLATE_VALUE,exports.FixedToolbar=i.FixedToolbar,exports.FixedToolbarButtons=i.FixedToolbarButtons,exports.FloatingToolbar=i.FloatingToolbar,exports.FloatingToolbarButtons=i.FloatingToolbarButtons,exports.MediaKit=i.MediaKit,exports.REASON_TOOLBAR=E,exports.REASON_TOOLBAR_SKIN=i.REASON_TOOLBAR_SKIN,exports.ROOM_PREFIX=ge,exports.ReasonPlateEditor=si,exports.ReasonPlaygroundEditor=function(e){return(0,h.jsx)(si,{...e,overlays:(0,h.jsx)(i.FloatingToolbar,{children:(0,h.jsx)(i.FloatingToolbarButtons,{})}),renderToolbar:()=>(0,h.jsx)(i.FixedToolbar,{className:i.REASON_TOOLBAR_SKIN,children:(0,h.jsx)(i.FixedToolbarButtons,{})})})},exports.ReasonSidebar=function({activeDocumentId:e,linkForDocument:n,onNavigate:r,className:i}){const[o,s]=l.useState([]),[a,c]=l.useState(null),[d,u]=l.useState(""),p=l.useCallback(()=>{s(U())},[]);l.useEffect(()=>(p(),F(p)),[p]);const g=()=>{a&&I(a,d),c(null)};return(0,h.jsxs)("nav",{"aria-label":"Documents",className:t.cn("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:[(0,h.jsxs)("div",{className:"flex items-center justify-between px-1 pb-2",children:[(0,h.jsx)("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-gray-400",children:"Documents"}),(0,h.jsx)("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:()=>{r(j().id)},type:"button",children:(0,h.jsx)(f.Plus,{className:"size-3.5"})})]}),o.map(i=>{const s=i.id===e,l=a===i.id;return(0,h.jsxs)("div",{className:t.cn("group flex items-center gap-1.5 rounded px-1.5 py-1 text-sm",s?"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:[(0,h.jsx)(f.FileText,{className:"size-3.5 shrink-0 opacity-60"}),l?(0,h.jsx)("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:g,onChange:e=>u(e.target.value),onKeyDown:e=>{"Enter"===e.key&&g(),"Escape"===e.key&&c(null)},value:d}):(0,h.jsx)("a",{className:"min-w-0 flex-1 truncate",href:n(i.id),children:i.title}),!l&&(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-0.5 group-hover:flex",children:[(0,h.jsx)("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),u(e.title)})(i),type:"button",children:(0,h.jsx)(f.Pencil,{className:"size-3"})}),(0,h.jsx)("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(B(t.id),t.id!==e)return;const n=o.find(e=>e.id!==t.id);r(n?n.id:j().id)})(i),type:"button",children:(0,h.jsx)(f.Trash2,{className:"size-3"})})]})]},i.id)}),0===o.length&&(0,h.jsx)("p",{className:"px-1.5 py-2 text-xs text-gray-400",children:"No documents yet."})]})},exports.ReasonTiptapEditor=function({documentId:e,initialContent:t="",user:n,authToken:i,className:o}){const[s,c]=l.useState(null),[d,u]=l.useState(null),f=me("tiptap",e),p=n.color??_e(n.id);l.useEffect(()=>{if(!i)return;const t=be({engine:"tiptap",documentId:e,token:i});return u(t),()=>{u(null),t.destroy()}},[i,e]);const g=l.useMemo(()=>{const e=r.buildExtensions(r.createDefaultConfig());return d?function(e,t,n){return[...e.filter(e=>"undoRedo"!==e?.name),a.Collaboration.configure({document:t.ydoc}),Oe.configure({provider:t.provider,user:n})]}(e,d,{name:n.name,color:p}):e},[d,n.name,p]),m=l.useMemo(()=>s?xe(s):S("tiptap"),[s]);return(0,h.jsx)("div",{className:`flex h-full min-h-0 w-full flex-col ${o??""}`,"data-room":f,children:(0,h.jsx)(r.NovelEditor,{className:"flex min-h-0 flex-1 flex-col",extensions:g,immediatelyRender:!1,initialContent:d?void 0:t,onEditor:c,rebuildKey:d?`collab:${f}`:"local",textDirection:"auto",children:({EditorSurface:e})=>(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(O,{adapter:m}),(0,h.jsx)("div",{className:"relative min-h-0 flex-1 overflow-auto",children:(0,h.jsx)(e,{className:"h-full"})})]})})})},exports.ReasonToolbar=O,exports.SIDEBAR_DOCUMENTS_STORAGE_KEY=D,exports.collaborationRoom=me,exports.collectToolbarCommands=function e(t=E){const n=[];for(const r of t)"button"===r.kind&&n.push(r.id),"menu"===r.kind&&n.push(...e(r.children));return n},exports.createCollaborationSession=be,exports.createNullAdapter=S,exports.createPlateAdapter=We,exports.createSidebarDocument=j,exports.createTiptapAdapter=xe,exports.cursorColorFor=_e,exports.deleteSidebarDocument=B,exports.hocuspocusUrl=ye,exports.htmlToPlateValue=i.htmlToPlateValue,exports.listSidebarDocuments=U,exports.parseCollaborationRoom=function(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},exports.plateBasePlugins=i.plateBasePlugins,exports.platePlugins=i.platePlugins,exports.plateValueToHtml=i.plateValueToHtml,exports.plateYjsProviders=we,exports.renameSidebarDocument=I,exports.subscribeSidebarDocuments=F;
|