@realsee/live 0.7.2 → 0.7.3-alpha.0
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/README.md +5 -3
- package/dist/index.cjs.js +3 -3
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.es.js +1785 -1781
- package/dist/index.es.js.map +1 -1
- package/docs/README.md +5 -3
- package/docs/classes/BrowserRTC.md +2 -2
- package/docs/classes/BrowserRTC4Chime.md +1 -1
- package/docs/classes/CoreRTC.md +1 -1
- package/docs/classes/Live.md +30 -30
- package/docs/classes/VRWebViewRTC.md +1 -1
- package/docs/functions/clearLiveInstanceIfNeed.md +1 -1
- package/docs/interfaces/RTCProtocol.md +1 -1
- package/docs/type-aliases/LiveBuiltInData.md +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -53,7 +53,7 @@ const live = createLive({
|
|
|
53
53
|
在创建 `live` 实例时配置了两个参数:
|
|
54
54
|
|
|
55
55
|
- `url`:连接 WebSocket 服务的 URL,如果在创建 `live` 实例阶段并不知道 URL ,您可以在合适的时机通过 `live.connect({ url })` 方法进行 WebScoket 连接。
|
|
56
|
-
- `getTicket()`:是一个异步回调函数,其返回值是连接 WebScoket 服务的 **"门票"**,关于如何获取 `ticket` 请查阅 [VR 带看 API]()。
|
|
56
|
+
- `getTicket()`:是一个异步回调函数,其返回值是连接 WebScoket 服务的 **"门票"**,关于如何获取 `ticket` 请查阅 [VR 带看 API](https://developers.realsee.com/docs/#/docs/live/server/README)。
|
|
57
57
|
|
|
58
58
|
> 关于 `createLive()` 函数的更多参数配置请参考 [LiveOptions](https://unpkg.com/@realsee/live/docs/interfaces/live.LiveOptions.html) 。
|
|
59
59
|
|
|
@@ -196,7 +196,7 @@ live.on('ws.readyStateUpdate', (readyState: WebSocketState) => {
|
|
|
196
196
|
|
|
197
197
|
- `weakNetwork(): void` 弱网提醒事件。
|
|
198
198
|
|
|
199
|
-
`live.$RTC` 实例需满足 [RTC 协议](),其事件通过 `live.$RTC.on('/*事件名*/', /*事件回调*/)` 方式来监听,比如监听语音房间内正在说话的用户及其音量:
|
|
199
|
+
`live.$RTC` 实例需满足 [RTC 协议](https://unpkg.com/@realsee/live/docs/interfaces/rtc.RTCProtocol.html),其事件通过 `live.$RTC.on('/*事件名*/', /*事件回调*/)` 方式来监听,比如监听语音房间内正在说话的用户及其音量:
|
|
200
200
|
|
|
201
201
|
```ts
|
|
202
202
|
live.$RTC.on('userVolumes', (userVolumes: UserVolume[]) => {
|
|
@@ -301,8 +301,10 @@ yarn add trtc-js-sdk
|
|
|
301
301
|
```tsx
|
|
302
302
|
import { createLive, BrowserRTC } from '@realsee/live'
|
|
303
303
|
|
|
304
|
-
const rtcInstance = new
|
|
304
|
+
const rtcInstance = new BrowserRTC({
|
|
305
305
|
getVoiceSign: () => {},
|
|
306
|
+
// 可选:处理自动播放策略
|
|
307
|
+
// autoPlayConfirm: ({ onConfirm }) => showDialogThen(onConfirm)
|
|
306
308
|
})
|
|
307
309
|
|
|
308
310
|
const live = createLive({
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var hn=Object.defineProperty;var un=(i,e,t)=>e in i?hn(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var a=(i,e,t)=>un(i,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ht=require("trtc-js-sdk"),Q=require("amazon-chime-sdk-js"),dn=require("@realsee/jsbridge-x"),y=require("react"),ve=Symbol("$$REALSEE_LIVE_EVENT$$");function Be(i){return i[ve]||(i[ve]={}),i[ve]}function fn(i){var e;(e=i[ve])!=null&&e.length||delete i[ve]}class Re{hasListener(e){const t=Be(this);return t&&t[e]&&t[e].length>0}on(e,t,n){const s=Be(this);return s[e]||(s[e]=[]),s[e].push([t,n||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){const n=Be(this);if(!e){fn(this);return}if(n[e]||(n[e]=[]),t===void 0){n[e].length=0;return}const s=n[e].findIndex(r=>r[0]===t);s!==-1&&n[e].splice(s,1)}emit(e,...t){let n=!1;const r=Be(this)[e]||[];for(let o of r.slice()){const[c,l=!1]=o,h=c(...t);l&&this.off(e,c),h===!1&&(n=!0)}return n}}class tt extends Re{}var se=(i=>(i.RealseeBrowserRTC="RealseeBrowserRTC",i.RealseeVRWebViewRTC="RealseeVRWebViewRTC",i.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",i))(se||{}),Tt=(i=>(i.RealseeXTRTC="trtc",i.RealseeXChimeRTC="chime",i))(Tt||{});const gn=()=>{const i=new Date,e=i.getFullYear(),t=(i.getMonth()+1).toString().padStart(2,"0"),n=i.getDate().toString().padStart(2,"0"),s=i.getHours().toString().padStart(2,"0"),r=i.getMinutes().toString().padStart(2,"0"),o=i.getSeconds().toString().padStart(2,"0"),c=i.getMilliseconds().toString().padStart(3,"0");return`[${e}-${t}-${n} ${s}:${r}:${o}.${c}]`},Ee=(i,e=[])=>{const t=`Realsee Live ${gn()} <${i}> `;switch(i){case"INFO":console.info(t,...e);break;case"ERROR":console.error(t,...e);break;case"WARN":console.warn(t,...e);break;case"DEBUG":console.debug(t,...e);break;default:console.log(t,...e)}},w={log:(...i)=>Ee("LOG",i),info:(...i)=>Ee("INFO",i),error:(...i)=>Ee("ERROR",i),warn:(...i)=>Ee("WARN",i),debug:(...i)=>Ee("DEBUG",i)};function ee(){return((1+Math.random())*65536|0).toString(16).substring(1)}function Te(){return[ee(),ee(),"4"+ee().substring(0,3),ee(),ee(),ee()+ee()+ee()].join("-").toLowerCase()}class ai extends tt{constructor(t){super();a(this,"type",se.RealseeBrowserRTC);a(this,"joined",!1);a(this,"micro",!1);a(this,"voiceId","");a(this,"_getVoiceSign",()=>{throw new Error("方法 getVoiceSign 未实现")});a(this,"_autoPlayConfirm");a(this,"checkRequirement",()=>ht.checkSystemRequirements());a(this,"$dom",document.createElement("div"));a(this,"_trtc",{client:null,stream:null});a(this,"join",async t=>{var r;this.emit("joinWillStart");const n=await this._getVoiceSign({voiceId:t.voiceId,roomId:t.roomId,userId:t.userId});this._trtc.client=ht.createClient({mode:"rtc",...n,enableAutoPlayDialog:typeof this._autoPlayConfirm!="function"}),(r=this._trtc.client)==null||r.enableAudioVolumeEvaluation(),this._registerRtcEvent();let s=await new Promise(o=>{var c;(c=this._trtc.client)==null||c.join({roomId:Number(t.voiceId)}).then(()=>o(!0)).catch(()=>o(!1))});return this.joined=s,s?(this._trtc.stream=ht.createStream({userId:n.userId,audio:!0,video:!1}),s=await new Promise(o=>{var c;(c=this._trtc.stream)==null||c.initialize().then(()=>o(!0)).catch(()=>o(!1))}),s=await new Promise(o=>{var c;(c=this._trtc.client)==null||c.publish(this._trtc.stream).then(()=>o(!0)).catch(()=>o(!1))}),this.joined=s,this.joined&&this.emit("joined"),s):!1});a(this,"_handleStreamAdded",t=>{var s;const n=t.stream;console.log("远端流增加: "+n.getId()),(s=this._trtc.client)==null||s.subscribe(n)});a(this,"_handleStreamSubscribed",t=>{const n=t.stream;console.log("远端流订阅成功:"+n.getId());const r=`rs-rtc-remote_stream-${n.getId()}`,o=document.createElement("div");o.id=r,this.$dom.appendChild(o),typeof this._autoPlayConfirm=="function"?(n.play(r).catch(c=>{}),n.on("error",c=>{if(c.getCode()===16451){const h=()=>n.resume();this._autoPlayConfirm({onConfirm:h})}})):n.play(r)});this._getVoiceSign=t.getVoiceSign,this._autoPlayConfirm=t.autoPlayConfirm,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${Te()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise(async t=>{var n,s;this.joined=!1,this._trtc.stream&&(await((n=this._trtc.client)==null?void 0:n.unpublish(this._trtc.stream)),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),(s=this._trtc.client)==null||s.leave().then(()=>this._trtc.client=null).then(()=>t(!0)).catch(()=>t(!1)),t(!0)})}detectMicro(){return new Promise(t=>{const n={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(n).then(()=>t(!0)).catch(s=>{w.error(s.message),t(!1)})}catch(s){console.error(s),t(!1)}})}toggleMicro(t){var n,s,r,o;return Promise.resolve((t?(s=(n=this._trtc)==null?void 0:n.stream)==null?void 0:s.unmuteAudio():(o=(r=this._trtc)==null?void 0:r.stream)==null?void 0:o.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var t,n,s,r;(t=this._trtc.client)==null||t.on("stream-added",this._handleStreamAdded),(n=this._trtc.client)==null||n.on("stream-subscribed",this._handleStreamSubscribed),(s=this._trtc.client)==null||s.on("audio-volume",o=>this.emit("userVolumes",o.result.map(({userId:c,audioVolume:l})=>({userId:c,audioVolume:l})))),(r=this._trtc.client)==null||r.on("error",o=>this.emit("error",o))}}class St extends tt{constructor(t){super();a(this,"type",se.RealseeBrowserChimeRTC);a(this,"joined",!1);a(this,"micro",!1);a(this,"voiceId","");a(this,"userId","");a(this,"logger");a(this,"deviceController");a(this,"meetingSession");a(this,"audioInput");a(this,"audioOutput");a(this,"deviceChangeObserver",{});a(this,"audioVideoObserver",{});a(this,"audioMixObserver");a(this,"_getVoiceSign",()=>{throw new Error("方法 getVoiceSign 未实现")});a(this,"_autoPlayConfirm");a(this,"$dom",document.createElement("div"));a(this,"$audio",document.createElement("audio"));a(this,"_initDom",()=>{this.$audio.id=`rs-rtc-${Te()}`,this.$dom.id=`rs-rtc-${Te()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom)});a(this,"initObservers",()=>{this.deviceChangeObserver={audioInputsChanged:t=>{this.logger.info(`audioInputsChanged ${typeof t}`),t==null||t.forEach(n=>{this.logger.info(`Device ID: ${n.deviceId} Microphone: ${n.label}`)})},audioOutputsChanged:t=>{this.logger.info(`audioOutputsChanged ${typeof t}`),t==null||t.forEach(n=>{this.logger.info(`Device ID: ${n.deviceId} Speaker: ${n.label}`)})},audioInputMuteStateChanged:(t,n)=>{this.logger.info(`Device ${t.toString()} ${n?"is muted in hardware":"is not muted"}`)}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started")},audioVideoDidStop:t=>{this.logger.info(`Stopped with a session status code: ${t.statusCode()}`)},audioVideoDidStartConnecting:t=>{t&&this.logger.info("Attempting to reconnect")}},this.audioMixObserver={meetingAudioStreamBecameActive:t=>{if(this.$audio.paused){const n=()=>this.$audio.play().then(()=>{}).catch(s=>{if(w.error("播放远端流失败!",s),typeof this._autoPlayConfirm=="function"){const r=()=>n();this._autoPlayConfirm({onConfirm:r})}});n()}},meetingAudioStreamBecameInactive:t=>{}}});a(this,"_registerRtcEvent",()=>{var n,s,r,o,c,l;const t=((r=(s=(n=this.meetingSession)==null?void 0:n.configuration)==null?void 0:s.credentials)==null?void 0:r.attendeeId)||"";if(t){const h=new Map,u=()=>{const d=[];return h.forEach((g,m)=>{d.push({userId:g.userId,volume:g.muted||g.signalStrength===0||!g.volume?0:g.volume})}),d};(o=this.meetingSession)==null||o.audioVideo.realtimeSubscribeToAttendeeIdPresence((d,g,m)=>{var b;if(!g){h.delete(d),this.emit("userVolumes",u());return}(b=this.meetingSession)==null||b.audioVideo.realtimeSubscribeToVolumeIndicator(d,(p,_,I,N)=>{new Q.DefaultModality(p).base()===p&&(h.set(p,{userId:m||p,volume:_,muted:I,signalStrength:N}),this.emit("userVolumes",u()))})}),(c=this.meetingSession)==null||c.audioVideo.realtimeSubscribeToVolumeIndicator(t,(d,g,m,b)=>{new Q.DefaultModality(d).base()===d&&b!==null&&b!==1&&this.emit("weakNetwork")}),(l=this.meetingSession)==null||l.audioVideo.realtimeSubscribeToFatalError(d=>this.emit("error",d))}});this._getVoiceSign=t.getVoiceSign,this._autoPlayConfirm=t.autoPlayConfirm,this._initDom(),this.logger=new Q.ConsoleLogger("WebRTCLogger",t.logLevel||Q.LogLevel.INFO),this.deviceController=new Q.DefaultDeviceController(this.logger),this.initObservers()}async join(t){return new Promise(async(n,s)=>{var r,o;this.emit("joinWillStart");try{const{sdkAppId:c,userId:l,roomId:h,userSig:u}=await this._getVoiceSign({...t,roomId:t.roomId||0});this.userId=l;const{attendence:d,vendor_wrapper:g}=JSON.parse(decodeURIComponent(u)),m=new Q.MeetingSessionConfiguration({Meeting:g},{Attendee:{ExternalUserId:d.external_user_id,AttendeeId:d.attendee_id,JoinToken:d.join_token}});this.meetingSession=new Q.DefaultMeetingSession(m,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);const b={audioVideoDidStart:()=>{var p;(p=this.meetingSession)==null||p.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),n(!0)},audioVideoDidStop:()=>{this.joined=!1,n(!1)}};this.meetingSession.audioVideo.addObserver(b),this.audioMixObserver&&this.meetingSession.audioVideo.addAudioMixObserver(this.audioMixObserver),this.meetingSession.audioVideo.setDeviceLabelTrigger(async()=>await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}));try{const p=await this.meetingSession.audioVideo.listAudioInputDevices();w.info("audioInputDevices ===>",p);const _=((r=p[0])==null?void 0:r.deviceId)||"default";await this.meetingSession.audioVideo.startAudioInput(_)}catch(p){w.error(`设置语音输入设备失败:${p.message}`)}try{const p=await this.meetingSession.audioVideo.listAudioOutputDevices();w.info("audioOutputDevices ===>",p);const _=((o=p[0])==null?void 0:o.deviceId)||"default";await this.meetingSession.audioVideo.chooseAudioOutput(_)}catch(p){w.error(`设置语音输出设备失败:${p.message}`)}this.meetingSession.audioVideo.start()}catch(c){this.emit("error",c),this.logger.error(c.message),n(!1)}})}quit(){return this.joined?new Promise((t,n)=>{var r,o;this.joined=!1;const s={audioVideoDidStop:async c=>{var h;const l=c.statusCode();(h=this.meetingSession)==null||h.deviceController.destroy(),l===Q.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),t(!0)):(this.logger.info(`Stopped with a session status code: ${l}`),t(!0))}};(r=this.meetingSession)==null||r.audioVideo.addObserver(s),(o=this.meetingSession)==null||o.audioVideo.stop()}):Promise.resolve(!0)}async detectMicro(){return new Promise(t=>{const n={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(n).then(()=>t(!0)).catch(()=>t(!1))}catch(s){this.logger.error(s.message),t(!1)}})}async toggleMicro(t){var s,r,o;t?(s=this.meetingSession)==null||s.audioVideo.realtimeUnmuteLocalAudio():(r=this.meetingSession)==null||r.audioVideo.realtimeMuteLocalAudio();const n=(o=this.meetingSession)==null?void 0:o.audioVideo.realtimeIsLocalAudioMuted();return n!==void 0?t!==n:!1}shock(){throw new Error("Method not implemented.")}}var le=(i=>(i[i.Success=0]="Success",i[i.Failure=1]="Failure",i[i.ReJoin=2]="ReJoin",i[i.NoMicroPermission=3]="NoMicroPermission",i[i.Unknown=500]="Unknown",i))(le||{});class hi extends tt{constructor({jsBridge:t,getVoiceSign:n}){super();a(this,"type",se.RealseeVRWebViewRTC);a(this,"joined",!1);a(this,"micro",!1);a(this,"voiceId","");a(this,"_joinOptions",null);a(this,"options");a(this,"handleUserVolumes",t=>{this.emit("userVolumes",t)});a(this,"handleWeakNetwork",t=>{t&&this.emit("weakNetwork")});a(this,"join",async t=>{this._joinOptions=t,this.emit("joinWillStart");const{sdkAppId:n,userId:s,userSig:r}=await this.getVoiceSignOrEmitError(t);return!n||!s||!r?!1:(this.type=t.type,this.jsBridge.webViewType==="WxMiniProgramWebView"?this.handleWxMiniProgramWebViewJoin({sdkAppId:n,userId:s,userSig:r,voiceId:t.voiceId}):this.handleAppWebViewJoin({sdkAppId:n,userId:s,userSig:r,voiceId:t.voiceId}))});a(this,"reJoin",async()=>this._joinOptions?this.join({voiceId:this._joinOptions.voiceId,userId:this._joinOptions.userId,roomId:this._joinOptions.roomId,type:this._joinOptions.type}):(this.emitErrorAndSetJoinedFalse("重连失败:未找到加入房间参数。"),!1));a(this,"getVoiceSignOrEmitError",async t=>{try{return await this.options.getVoiceSign(t)}catch(n){return this.emitErrorAndSetJoinedFalse("加入房间失败:rtc 签名请求异常"),{}}});a(this,"handleWxMiniProgramWebViewJoin",async t=>{const[n,s]=await this.joinRoomOrEmitError(t);return s?!1:this.handleJoinResult(n)});a(this,"handleAppWebViewJoin",t=>new Promise(n=>{this.off("inner.rtc.success");const s=r=>{this.off("inner.rtc.fail",s),this.off("inner.rtc.success",s),n(this.handleJoinResult(r))};this.once("inner.rtc.fail",s),this.once("inner.rtc.success",s);try{const{sdkAppId:r,userId:o,userSig:c,voiceId:l}=t;this.jsBridge.callAndListen(`live/join?sdkAppID=${r}&userID=${o}&roomID=${l}&userSig=${c}`,h=>{h===!0?this.emit("inner.rtc.success",h):typeof h=="object"?h.code===le.Success||h.code===le.ReJoin?this.emit("inner.rtc.success",h):this.emit("inner.rtc.fail",h):this.emit("inner.rtc.fail",h)})}catch(r){n(this.handleJoinResult({message:r.message,code:le.Unknown}))}}));a(this,"joinRoomOrEmitError",async({sdkAppId:t,userId:n,voiceId:s,userSig:r})=>{try{return await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${t}&userID=${n}&roomID=${Number(s)}&userSig=${r}`)}catch(o){return this.emitErrorAndSetJoinedFalse("加入房间失败:"+o.message),[null,o]}});a(this,"handleJoinResult",t=>{switch(!0){case t===!0:case(typeof t=="object"&&t.code===le.Success):case(typeof t=="object"&&t.code===le.ReJoin):{this.emit("joined"),this.joined=!0;break}default:{this.joined=!1;const n=typeof t=="object"?t.message:"加入房间失败:未知异常。";this.emit("error",new Error(n,{cause:t}))}}return this.joined});a(this,"emitErrorAndSetJoinedFalse",t=>{this.emit("error",new Error(t)),this.joined=!1});a(this,"quit",async()=>{const[t,n]=await this.jsBridge.callAndBackfeed("live/quit");return t===null&&this.emit("error",n||new Error("退出房间失败:未知异常。")),this.joined=!1,!!t});a(this,"detectMicro",async()=>{const[t,n]=await this.jsBridge.detectMicro();return t===null?(this.emit("error",n||new Error("麦克风监测异常!")),!1):t});a(this,"toggleMicro",async t=>{const[n,s]=await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${t?1:0}`);return n===null?(this.emit("error",s||new Error("麦克风监测异常!")),!1):(this.micro=n,n)});a(this,"shock",()=>{this.jsBridge.shock(1)});this.options={jsBridge:t,getVoiceSign:n},this.jsBridge.webViewType!=="WxMiniProgramWebView"&&this.jsBridge.callAndListen("live/userVolumes",this.handleUserVolumes),this.jsBridge.callAndListen("live/weakNetwork",this.handleWeakNetwork),this.on("inner.rtc.fail",this.handleJoinResult)}get jsBridge(){return this.options.jsBridge}}var x=(i=>(i.SelfUserInfo="SELF_USER_INFO",i.RoomInfo="ROOM_INFO",i.RTCInfo="RTC_INFO",i.UserList="USER_LIST",i.BuiltinMsg="BUILTIN_MSG",i.CustomEvent="CUSTOM_EVENT",i.KeyframeSync="KEYFRAME_SYNC",i.UserKickOut="USER_KICK_OUT",i))(x||{}),F=(i=>(i.UserChange="user_change",i.RoomChange="room_change",i))(F||{}),K=(i=>(i.UserMicroStatus="change_micro_status",i.UserMicroStatusSync="sync_micro_status",i.UserPermission="change_permission",i.UserStatus="change_status",i.UserInfo="change_info",i.RoomClose="close",i))(K||{}),te=(i=>(i.OPEN="OPEN",i.CLOSE="CLOSE",i))(te||{});function pn(i){try{const e=JSON.parse(i),t={code:e.code,message:e.message,command:e.command,roomCode:e.room_code,appID:e.app_id,requestId:e.request_id,frontRequestId:e.front_request_id,triggerUserID:e.trigger_user_id,data:e.data||{}},n=Object.keys(t).filter(s=>t[s]===void 0);return n.length>0&&console.warn(`推送数据格式异常:${n.join(" ")} 值不存在!`),t}catch(e){return!1}}var V=(i=>(i[i.NOTINITIALIZED=-1]="NOTINITIALIZED",i[i.CONNECTING=0]="CONNECTING",i[i.OPEN=1]="OPEN",i[i.CLOSED=3]="CLOSED",i))(V||{}),ui=(i=>(i[i.Normal=0]="Normal",i[i.Removed=1]="Removed",i[i.Replaced=2]="Replaced",i))(ui||{}),di=(i=>(i.WAIT_ENTER="WAIT_ENTER",i.ONLINE="ONLINE",i.LEAVE="LEAVE",i.KICK_OUT="KICK_OUT",i.BE_REPLACE="BE_REPLACE",i.EXCEPTION="EXCEPTION",i))(di||{}),Je=(i=>(i[i.NOTINITIALIZED=-1]="NOTINITIALIZED",i[i.CONNECTING=0]="CONNECTING",i[i.OPEN=1]="OPEN",i[i.CLOSING=2]="CLOSING",i[i.CLOSED=3]="CLOSED",i))(Je||{}),fi=(i=>(i.Error="Error",i.Close="Close",i.MicroAuth="MicroAuth",i.DuplicateConnect="DuplicateConnect",i.IllegalURL="IllegalURL",i.Unknown="Unknown",i.IllegalArgs="IllegalArgs",i))(fi||{}),gi=(i=>(i.Err_1000="CLOSE_NORMAL",i.Err_1001="CLOSE_GOING_AWAY",i.Err_1002="CLOSE_PROTOCOL_ERROR",i.Err_1003="CLOSE_UNSUPPORTED",i.Err_1006="CLOSE_ABNORMAL",i.Err_1007="Unsupported Data",i.Err_1008="Policy Violation",i.Err_1009="CLOSE_TOO_LARGE",i.Err_unknown="unknown",i))(gi||{});function pi(i){switch(i){case 1e3:return"CLOSE_NORMAL";case 1001:return"CLOSE_GOING_AWAY";case 1002:return"CLOSE_PROTOCOL_ERROR";case 1003:return"CLOSE_UNSUPPORTED";case 1006:return"CLOSE_ABNORMAL";case 1007:return"Unsupported Data";case 1008:return"Policy Violation";case 1009:return"CLOSE_TOO_LARGE"}return"unknown"}function _n(i,e={}){const t=new URL(i,"http://localhost"),n=new URLSearchParams(t.search);return Object.entries(e).forEach(([s,r])=>{n.append(s,String(r))}),i.split("?")[0]+"?"+n.toString()}const mn=(()=>{var t;const i=typeof process!="undefined"&&((t=process.versions)==null?void 0:t.node)!=null;return typeof window!="undefined"&&"Deno"in window||i||typeof window=="undefined"})(),Ae=mn?"":navigator.userAgent,wn=/android/i.test(Ae),bn=/iPhone|iPad\s+OS/i.test(Ae),yn=/MicroMessenger/i.test(Ae)&&/miniProgram/i.test(Ae),Sn=/realsee/i.test(Ae);function qe(i){return Object.prototype.toString.call(i)==="[object Object]"}function it(i,e){return i===e?!0:i==null||e==null||typeof i!=typeof e?!1:Number.isNaN(i)&&Number.isNaN(e)}function Cn(i,e){if(i===e)return!0;if(i==null||e==null)return!1;const t=Object.keys(i),n=Object.keys(e);return t.length!==n.length?!1:t.every(s=>it(i[s],e[s]))}function En(i,e){return i===e?!0:i==null||e==null||i.length!==e.length?!1:i.every((t,n)=>it(t,e[n]))}function kn(i,e){return it(i,e)?!0:qe(i)&&qe(e)?Cn(i,e):Array.isArray(i)&&Array.isArray(e)?En(i,e):!1}function At(i,e){return it(i,e)?!0:qe(i)&&qe(e)?In(i,e):Array.isArray(i)&&Array.isArray(e)?vn(i,e):!1}function vn(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(!At(i[t],e[t]))return!1;return!0}function In(i,e){if(i===e)return!0;if(i==null||e==null)return!1;const t=Object.keys(i),n=Object.keys(e);return t.length!==n.length?!1:t.every(s=>At(i[s],e[s]))}function On(i,e,t={deep:!1}){return t.deep?At(i,e):kn(i,e)}class Rn extends Re{constructor(t){super();a(this,"_realWebSocket");a(this,"_url");a(this,"_protocols");a(this,"_readyState",Je.NOTINITIALIZED);a(this,"_options",{timeout:1e4,shouldReconnect:(t,n)=>{if(!(t.code===1008||t.code===1011))return[0,1e3,2e3][n.attempts%3]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1});a(this,"_connectTimeout");a(this,"_attempts",0);a(this,"_reconnects",-1);a(this,"_reconnectWhenOnlineAgain",!1);a(this,"_explicitlyClosed",!1);a(this,"_pendingReconnect");a(this,"_connectivityEventsAttached",!1);a(this,"_heathCheckTimer");a(this,"_healthCheck",async()=>{if(this._realWebSocket){const t=this._realWebSocket.readyState;t!==this._readyState&&(this._readyState=t,this._readyState===Je.CLOSING&&this.emit("closing"))}await new Promise(t=>setTimeout(t,2e3)),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)});a(this,"_clearConnectTimeoutIfNeed",()=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0)});a(this,"_clearHeathCheckIfNeed",()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0)});a(this,"_startHealthCheck",()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)});a(this,"_stopHealthCheck",()=>{this._clearHeathCheckIfNeed()});a(this,"_clearPendingReconnectIfNeeded",()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)});a(this,"_online",t=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(t))});a(this,"_offline",()=>{var t;this._reconnectWhenOnlineAgain=!0,(t=this._realWebSocket)==null||t.close(1e3,"offline")});a(this,"_detachConnectivityEvents",()=>{this._connectivityEventsAttached&&(globalThis==null||globalThis.removeEventListener("online",this._online),globalThis==null||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)});a(this,"_attachConnectivityEvents",()=>{this._connectivityEventsAttached||(globalThis==null||globalThis.addEventListener("online",this._online),globalThis==null||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)});a(this,"send",t=>{var n,s,r;((n=this._realWebSocket)==null?void 0:n.readyState)===((s=this._realWebSocket)==null?void 0:s.OPEN)&&((r=this._realWebSocket)==null||r.send(t))});a(this,"close",(t,n)=>{var s;return typeof t!="number"&&(n=t,t=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),(s=this._realWebSocket)==null?void 0:s.close(t,n)});a(this,"open",t=>{var n,s;t&&(this._url=t),((n=this._realWebSocket)==null?void 0:n.readyState)!==WebSocket.OPEN&&((s=this._realWebSocket)==null?void 0:s.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())});a(this,"_createWebSocket",()=>{var s;const t=typeof this._url=="string"?this._url:(s=this._url)==null?void 0:s.call(this,this);if(!t)return;this._clearConnectTimeoutIfNeed(),this._clearPendingReconnectIfNeeded(),this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(t,this._protocols||void 0),this._attempts++,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));const n=()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("timeout",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))};this._connectTimeout=setTimeout(n,this._options.timeout),this._dispatchWebSocketEvent(),this._options.ignoreConnectivityEvents||this._attachConnectivityEvents()});a(this,"_removeWebSocketEvent",()=>{var t,n,s,r;(t=this._realWebSocket)==null||t.removeEventListener("open",this._webSocketOpenHandler),(n=this._realWebSocket)==null||n.removeEventListener("close",this._webSocketCloseHandler),(s=this._realWebSocket)==null||s.removeEventListener("error",this._webSocketErrorHandler),(r=this._realWebSocket)==null||r.removeEventListener("message",this._webSocketMessageHandler)});a(this,"_dispatchWebSocketEvent",()=>{var t,n,s,r;(t=this._realWebSocket)==null||t.addEventListener("open",this._webSocketOpenHandler),(n=this._realWebSocket)==null||n.addEventListener("close",this._webSocketCloseHandler),(s=this._realWebSocket)==null||s.addEventListener("error",this._webSocketErrorHandler),(r=this._realWebSocket)==null||r.addEventListener("message",this._webSocketMessageHandler)});a(this,"_webSocketOpenHandler",t=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const n=++this._reconnects,s=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(t,{detail:{reconnects:n,attempts:s}}))});a(this,"_webSocketCloseHandler",t=>(this._reconnect(t),this._stopHealthCheck(),this.emit("close",t)));a(this,"_webSocketErrorHandler",t=>this.emit("error",new CustomEvent("error",{detail:{error:t}})));a(this,"_webSocketMessageHandler",t=>this.emit("message",t));t&&this.setOptions(t),this._startHealthCheck()}get attempts(){return this._attempts}setOptions(t){if(!t)return;this._url=t.url,this._protocols=t.protocols;const n=Object.assign(this._options,t.robustOptions||{});if(typeof(n==null?void 0:n.timeout)!="number")throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if(typeof(n==null?void 0:n.shouldReconnect)!="function")throw new Error("shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.");this._options=n,this._options.automaticOpen&&this._createWebSocket()}_reconnect(t){var o,c,l;if(!this._options.should1000Reconnect&&t.code===1e3||this._explicitlyClosed){this._attempts=0;return}if(this._connectivityEventsAttached&&((o=globalThis==null?void 0:globalThis.navigator)==null?void 0:o.onLine)===!1){this._reconnectWhenOnlineAgain=!0;return}const r=(l=(c=this._options).shouldReconnect)==null?void 0:l.call(c,t,this);typeof r=="number"?(console.log(`Reconnecting in ${r}ms...`),this._pendingReconnect=setTimeout(this._createWebSocket,r)):console.log("No reconnection will be attempted.")}}class Tn extends Re{constructor(){super();a(this,"_ws",new Rn({url:"",robustOptions:{should1000Reconnect:!0,ignoreConnectivityEvents:!0}}));a(this,"_state",V.NOTINITIALIZED);a(this,"_addWebSocketEventListeners",()=>{this._ws.on("close",this._handleCloseEvent),this._ws.on("closing",this._handleClosingEvent),this._ws.on("connecting",this._handleConnectingEvent),this._ws.on("error",this._handleErrorEvent),this._ws.on("message",this._handleMessageEvent),this._ws.on("open",this._handleOpenEvent),this._ws.on("timeout",this._handleTimeoutEvent)});a(this,"_removeWebSocketEventListeners",()=>{this._ws.off("close",this._handleCloseEvent),this._ws.off("closing",this._handleClosingEvent),this._ws.off("connecting",this._handleConnectingEvent),this._ws.off("error",this._handleErrorEvent),this._ws.off("message",this._handleMessageEvent),this._ws.off("open",this._handleOpenEvent),this._ws.off("timeout",this._handleTimeoutEvent)});a(this,"_handleCloseEvent",t=>{w.info(`live room closed bacause of ${t.code}-${t.reason||pi(t.code)}`),this.state=V.CLOSED});a(this,"_handleClosingEvent",()=>{var t;w.info("live room is closing, onLine:",(t=globalThis==null?void 0:globalThis.navigator)==null?void 0:t.onLine),this.state=V.CLOSED});a(this,"_handleConnectingEvent",t=>{w.info("live room is connecting"),this.state=V.CONNECTING,t.detail.reconnects>0&&this.emit("reconnecting",t.detail)});a(this,"_handleErrorEvent",t=>{w.error("live room error",t),this.state=V.CLOSED});a(this,"_handleMessageEvent",t=>{let n=(()=>{try{return JSON.parse(t.data)}catch(s){return t.data}})();this.emit("message",n)});a(this,"_handleOpenEvent",t=>{w.info("live room open",t.detail),this.state=V.OPEN,t.detail.reconnects>0&&this.emit("reconnected",t.detail)});a(this,"_handleTimeoutEvent",t=>{w.error("live room connect timeout!",t.detail),this.state=V.CLOSED});a(this,"dispose",async()=>(this._removeWebSocketEventListeners(),await this.close("live room close by controller disposed!")));a(this,"open",t=>this._ws.open(t));a(this,"close",(t,n)=>new Promise(s=>{this._ws.once("close",()=>s(!0)),this._ws.close(t,n)}));a(this,"sendMessage",(t="")=>{if(t==null)throw new Error("live message is empty!");if(this.state!==V.OPEN)throw new Error("live has not yet been initialized!");return this._ws.send(JSON.stringify(t))});a(this,"readyClose",()=>{this._ws&&(this._ws._explicitlyClosed=!0)});this._addWebSocketEventListeners()}set state(t){const n=JSON.parse(JSON.stringify(this._state));this._state=t,this.emit("stateChange",this.state,n)}get state(){return this._state}}const G=()=>new Map,Ct=i=>{const e=G();return i.forEach((t,n)=>{e.set(n,t)}),e},we=(i,e,t)=>{let n=i.get(e);return n===void 0&&i.set(e,n=t()),n},An=(i,e)=>{const t=[];for(const[n,s]of i)t.push(e(s,n));return t},Ln=(i,e)=>{for(const[t,n]of i)if(e(n,t))return!0;return!1},fe=()=>new Set,ut=i=>i[i.length-1],ge=Array.from,Mn=Array.isArray;class Dn{constructor(){this._observers=G()}on(e,t){return we(this._observers,e,fe).add(t),t}once(e,t){const n=(...s)=>{this.off(e,n),t(...s)};this.on(e,n)}off(e,t){const n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return ge((this._observers.get(e)||G()).values()).forEach(n=>n(...t))}destroy(){this._observers=G()}}const ae=Math.floor,We=Math.abs,_i=(i,e)=>i<e?i:e,be=(i,e)=>i>e?i:e,Nn=i=>i!==0?i<0:1/i<0,Wt=1,Pt=2,dt=4,ft=8,Vn=32,mi=64,He=128,Un=31,Kt=63,Ie=127,jn=2147483647,Bn=Number.isInteger||(i=>typeof i=="number"&&isFinite(i)&&ae(i)===i),xn=i=>i.toLowerCase(),$n=/^\s*/g,Fn=i=>i.replace($n,""),Wn=/([A-Z])/g,Gt=(i,e)=>Fn(i.replace(Wn,t=>`${e}${xn(t)}`)),Pn=i=>{const e=unescape(encodeURIComponent(i)),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.codePointAt(s);return n},Le=typeof TextEncoder!="undefined"?new TextEncoder:null,Kn=i=>Le.encode(i),Gn=Le?Kn:Pn;let gt=typeof TextDecoder=="undefined"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});gt&>.decode(new Uint8Array).length===1&&(gt=null);class je{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Lt=()=>new je,Jn=i=>{let e=i.cpos;for(let t=0;t<i.bufs.length;t++)e+=i.bufs[t].length;return e},z=i=>{const e=new Uint8Array(Jn(i));let t=0;for(let n=0;n<i.bufs.length;n++){const s=i.bufs[n];e.set(s,t),t+=s.length}return e.set(new Uint8Array(i.cbuf.buffer,0,i.cpos),t),e},qn=(i,e)=>{const t=i.cbuf.length;t-i.cpos<e&&(i.bufs.push(new Uint8Array(i.cbuf.buffer,0,i.cpos)),i.cbuf=new Uint8Array(be(t,e)*2),i.cpos=0)},A=(i,e)=>{const t=i.cbuf.length;i.cpos===t&&(i.bufs.push(i.cbuf),i.cbuf=new Uint8Array(t*2),i.cpos=0),i.cbuf[i.cpos++]=e},Et=A,C=(i,e)=>{for(;e>Ie;)A(i,He|Ie&e),e=ae(e/128);A(i,Ie&e)},Mt=(i,e)=>{const t=Nn(e);for(t&&(e=-e),A(i,(e>Kt?He:0)|(t?mi:0)|Kt&e),e=ae(e/64);e>0;)A(i,(e>Ie?He:0)|Ie&e),e=ae(e/128)},kt=new Uint8Array(3e4),Hn=kt.length/3,zn=(i,e)=>{if(e.length<Hn){const t=Le.encodeInto(e,kt).written||0;C(i,t);for(let n=0;n<t;n++)A(i,kt[n])}else $(i,Gn(e))},Yn=(i,e)=>{const t=unescape(encodeURIComponent(e)),n=t.length;C(i,n);for(let s=0;s<n;s++)A(i,t.codePointAt(s))},de=Le&&Le.encodeInto?zn:Yn,Dt=(i,e)=>{const t=i.cbuf.length,n=i.cpos,s=_i(t-n,e.length),r=e.length-s;i.cbuf.set(e.subarray(0,s),n),i.cpos+=s,r>0&&(i.bufs.push(i.cbuf),i.cbuf=new Uint8Array(be(t*2,r)),i.cbuf.set(e.subarray(s)),i.cpos=r)},$=(i,e)=>{C(i,e.byteLength),Dt(i,e)},Nt=(i,e)=>{qn(i,e);const t=new DataView(i.cbuf.buffer,i.cpos,e);return i.cpos+=e,t},Xn=(i,e)=>Nt(i,4).setFloat32(0,e,!1),Zn=(i,e)=>Nt(i,8).setFloat64(0,e,!1),Qn=(i,e)=>Nt(i,8).setBigInt64(0,e,!1),Jt=new DataView(new ArrayBuffer(4)),es=i=>(Jt.setFloat32(0,i),Jt.getFloat32(0)===i),Me=(i,e)=>{switch(typeof e){case"string":A(i,119),de(i,e);break;case"number":Bn(e)&&We(e)<=jn?(A(i,125),Mt(i,e)):es(e)?(A(i,124),Xn(i,e)):(A(i,123),Zn(i,e));break;case"bigint":A(i,122),Qn(i,e);break;case"object":if(e===null)A(i,126);else if(Mn(e)){A(i,117),C(i,e.length);for(let t=0;t<e.length;t++)Me(i,e[t])}else if(e instanceof Uint8Array)A(i,116),$(i,e);else{A(i,118);const t=Object.keys(e);C(i,t.length);for(let n=0;n<t.length;n++){const s=t[n];de(i,s),Me(i,e[s])}}break;case"boolean":A(i,e?120:121);break;default:A(i,127)}};class qt extends je{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&C(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Ht=i=>{i.count>0&&(Mt(i.encoder,i.count===1?i.s:-i.s),i.count>1&&C(i.encoder,i.count-2))};class Pe{constructor(){this.encoder=new je,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Ht(this),this.count=1,this.s=e)}toUint8Array(){return Ht(this),z(this.encoder)}}const zt=i=>{if(i.count>0){const e=i.diff*2+(i.count===1?0:1);Mt(i.encoder,e),i.count>1&&C(i.encoder,i.count-2)}};class pt{constructor(){this.encoder=new je,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(zt(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return zt(this),z(this.encoder)}}class ts{constructor(){this.sarr=[],this.s="",this.lensE=new Pe}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new je;return this.sarr.push(this.s),this.s="",de(e,this.sarr.join("")),Dt(e,this.lensE.toUint8Array()),z(e)}}const pe=i=>new Error(i),J=()=>{throw pe("Method unimplemented")},he=()=>{throw pe("Unexpected case")},is=crypto.getRandomValues.bind(crypto),wi=()=>is(new Uint32Array(1))[0],ns="10000000-1000-4000-8000"+-1e11,ss=()=>ns.replace(/[018]/g,i=>(i^wi()&15>>i/4).toString(16)),Yt=i=>new Promise(i);Promise.all.bind(Promise);const Xt=i=>i===void 0?null:i;class rs{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}}let bi=new rs,os=!0;try{typeof localStorage!="undefined"&&localStorage&&(bi=localStorage,os=!1)}catch(i){}const cs=bi,ls=Object.assign,as=Object.keys,hs=(i,e)=>{for(const t in i)e(i[t],t)},Zt=i=>as(i).length,us=i=>{for(const e in i)return!1;return!0},ds=(i,e)=>{for(const t in i)if(!e(i[t],t))return!1;return!0},fs=(i,e)=>Object.prototype.hasOwnProperty.call(i,e),gs=(i,e)=>i===e||Zt(i)===Zt(e)&&ds(i,(t,n)=>(t!==void 0||fs(e,n))&&e[n]===t),ps=Object.freeze,yi=i=>{for(const e in i){const t=i[e];(typeof t=="object"||typeof t=="function")&&yi(i[e])}return ps(i)},Vt=(i,e,t=0)=>{try{for(;t<i.length;t++)i[t](...e)}finally{t<i.length&&Vt(i,e,t+1)}},_s=(i,e)=>e.includes(i),De=typeof process!="undefined"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process!="undefined"?process:0)==="[object process]";let P;const ms=()=>{if(P===void 0)if(De){P=G();const i=process.argv;let e=null;for(let t=0;t<i.length;t++){const n=i[t];n[0]==="-"?(e!==null&&P.set(e,""),e=n):e!==null&&(P.set(e,n),e=null)}e!==null&&P.set(e,"")}else typeof location=="object"?(P=G(),(location.search||"?").slice(1).split("&").forEach(i=>{if(i.length!==0){const[e,t]=i.split("=");P.set(`--${Gt(e,"-")}`,t),P.set(`-${Gt(e,"-")}`,t)}})):P=G();return P},vt=i=>ms().has(i),ze=i=>Xt(De?process.env[i.toUpperCase().replaceAll("-","_")]:cs.getItem(i)),Si=i=>vt("--"+i)||ze(i)!==null;Si("production");const ws=De&&_s(process.env.FORCE_COLOR,["true","1","2"]),bs=ws||!vt("--no-colors")&&!Si("no-color")&&(!De||process.stdout.isTTY)&&(!De||vt("--color")||ze("COLORTERM")!==null||(ze("TERM")||"").includes("color"));class ys{constructor(e,t){this.left=e,this.right=t}}const H=(i,e)=>new ys(i,e);typeof DOMParser!="undefined"&&new DOMParser;const Ss=i=>An(i,(e,t)=>`${t}:${e};`).join(""),Z=Symbol,Ci=Z(),Ei=Z(),Cs=Z(),Es=Z(),ks=Z(),ki=Z(),vs=Z(),Ut=Z(),Is=Z(),Os=i=>{var s;i.length===1&&((s=i[0])==null?void 0:s.constructor)===Function&&(i=i[0]());const e=[],t=[];let n=0;for(;n<i.length;n++){const r=i[n];if(r===void 0)break;if(r.constructor===String||r.constructor===Number)e.push(r);else if(r.constructor===Object)break}for(n>0&&t.push(e.join(""));n<i.length;n++){const r=i[n];r instanceof Symbol||t.push(r)}return t},Rs={[Ci]:H("font-weight","bold"),[Ei]:H("font-weight","normal"),[Cs]:H("color","blue"),[ks]:H("color","green"),[Es]:H("color","grey"),[ki]:H("color","red"),[vs]:H("color","purple"),[Ut]:H("color","orange"),[Is]:H("color","black")},Ts=i=>{var o;i.length===1&&((o=i[0])==null?void 0:o.constructor)===Function&&(i=i[0]());const e=[],t=[],n=G();let s=[],r=0;for(;r<i.length;r++){const c=i[r],l=Rs[c];if(l!==void 0)n.set(l.left,l.right);else{if(c===void 0)break;if(c.constructor===String||c.constructor===Number){const h=Ss(n);r>0||h.length>0?(e.push("%c"+c),t.push(h)):e.push(c)}else break}}for(r>0&&(s=t,s.unshift(e.join("")));r<i.length;r++){const c=i[r];c instanceof Symbol||s.push(c)}return s},vi=bs?Ts:Os,As=(...i)=>{console.log(...vi(i)),Ii.forEach(e=>e.print(i))},Ls=(...i)=>{console.warn(...vi(i)),i.unshift(Ut),Ii.forEach(e=>e.print(i))},Ii=fe(),Oi=i=>({[Symbol.iterator](){return this},next:i}),Ms=(i,e)=>Oi(()=>{let t;do t=i.next();while(!t.done&&!e(t.value));return t}),_t=(i,e)=>Oi(()=>{const{done:t,value:n}=i.next();return{done:t,value:t?void 0:e(n)}});class Ds{constructor(e,t){this.clock=e,this.len=t}}class Ns{constructor(){this.clients=new Map}}const Ri=(i,e,t)=>e.clients.forEach((n,s)=>{const r=i.doc.store.clients.get(s);for(let o=0;o<n.length;o++){const c=n[o];Vi(i,r,c.clock,c.len,t)}}),Vs=(i,e)=>{let t=0,n=i.length-1;for(;t<=n;){const s=ae((t+n)/2),r=i[s],o=r.clock;if(o<=e){if(e<o+r.len)return s;t=s+1}else n=s-1}return null},Ti=(i,e)=>{const t=i.clients.get(e.client);return t!==void 0&&Vs(t,e.clock)!==null},Ai=i=>{i.clients.forEach(e=>{e.sort((s,r)=>s.clock-r.clock);let t,n;for(t=1,n=1;t<e.length;t++){const s=e[n-1],r=e[t];s.clock+s.len>=r.clock?s.len=be(s.len,r.clock+r.len-s.clock):(n<t&&(e[n]=r),n++)}e.length=n})},Li=(i,e,t,n)=>{we(i.clients,e,()=>[]).push(new Ds(t,n))},Us=(i,e)=>{C(i.restEncoder,e.clients.size),ge(e.clients.entries()).sort((t,n)=>n[0]-t[0]).forEach(([t,n])=>{i.resetDsCurVal(),C(i.restEncoder,t);const s=n.length;C(i.restEncoder,s);for(let r=0;r<s;r++){const o=n[r];i.writeDsClock(o.clock),i.writeDsLen(o.len)}})},Mi=wi;class ye extends Dn{constructor({guid:e=ss(),collectionid:t=null,gc:n=!0,gcFilter:s=()=>!0,meta:r=null,autoLoad:o=!1,shouldLoad:c=!0}={}){super(),this.gc=n,this.gcFilter=s,this.clientID=Mi(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Js,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=c,this.autoLoad=o,this.meta=r,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Yt(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const l=()=>Yt(h=>{const u=d=>{(d===void 0||d===!0)&&(this.off("sync",u),h())};this.on("sync",u)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=l()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const e=this._item;e!==null&&!this.shouldLoad&&k(e.parent.doc,t=>{t.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(ge(this.subdocs).map(e=>e.guid))}transact(e,t=null){return k(this,e,t)}get(e,t=D){const n=we(this.share,e,()=>{const r=new t;return r._integrate(this,null),r}),s=n.constructor;if(t!==D&&s!==t)if(s===D){const r=new t;r._map=n._map,n._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=r}),r._start=n._start;for(let o=r._start;o!==null;o=o.right)o.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return n}getArray(e=""){return this.get(e,Oe)}getText(e=""){return this.get(e,Qe)}getMap(e=""){return this.get(e,Ze)}getXmlElement(e=""){return this.get(e,Ue)}getXmlFragment(e=""){return this.get(e,_e)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,ge(this.subdocs).forEach(t=>t.destroy());const e=this._item;if(e!==null){this._item=null;const t=e.content;t.doc=new ye({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,k(e.parent.doc,n=>{const s=t.doc;e.deleted||n.subdocsAdded.add(s),n.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class js{constructor(){this.restEncoder=Lt()}toUint8Array(){return z(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){C(this.restEncoder,e)}writeDsLen(e){C(this.restEncoder,e)}}class Bs extends js{writeLeftID(e){C(this.restEncoder,e.client),C(this.restEncoder,e.clock)}writeRightID(e){C(this.restEncoder,e.client),C(this.restEncoder,e.clock)}writeClient(e){C(this.restEncoder,e)}writeInfo(e){Et(this.restEncoder,e)}writeString(e){de(this.restEncoder,e)}writeParentInfo(e){C(this.restEncoder,e?1:0)}writeTypeRef(e){C(this.restEncoder,e)}writeLen(e){C(this.restEncoder,e)}writeAny(e){Me(this.restEncoder,e)}writeBuf(e){$(this.restEncoder,e)}writeJSON(e){de(this.restEncoder,JSON.stringify(e))}writeKey(e){de(this.restEncoder,e)}}class xs{constructor(){this.restEncoder=Lt(),this.dsCurrVal=0}toUint8Array(){return z(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,C(this.restEncoder,t)}writeDsLen(e){e===0&&he(),C(this.restEncoder,e-1),this.dsCurrVal+=e}}class $s extends xs{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new pt,this.clientEncoder=new Pe,this.leftClockEncoder=new pt,this.rightClockEncoder=new pt,this.infoEncoder=new qt(Et),this.stringEncoder=new ts,this.parentInfoEncoder=new qt(Et),this.typeRefEncoder=new Pe,this.lenEncoder=new Pe}toUint8Array(){const e=Lt();return C(e,0),$(e,this.keyClockEncoder.toUint8Array()),$(e,this.clientEncoder.toUint8Array()),$(e,this.leftClockEncoder.toUint8Array()),$(e,this.rightClockEncoder.toUint8Array()),$(e,z(this.infoEncoder)),$(e,this.stringEncoder.toUint8Array()),$(e,z(this.parentInfoEncoder)),$(e,this.typeRefEncoder.toUint8Array()),$(e,this.lenEncoder.toUint8Array()),Dt(e,z(this.restEncoder)),z(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Me(this.restEncoder,e)}writeBuf(e){$(this.restEncoder,e)}writeJSON(e){Me(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}}const Fs=(i,e,t,n)=>{n=be(n,e[0].id.clock);const s=Y(e,n);C(i.restEncoder,e.length-s),i.writeClient(t),C(i.restEncoder,n);const r=e[s];r.write(i,n-r.id.clock);for(let o=s+1;o<e.length;o++)e[o].write(i,0)},Ws=(i,e,t)=>{const n=new Map;t.forEach((s,r)=>{B(e,r)>s&&n.set(r,s)}),jt(e).forEach((s,r)=>{t.has(r)||n.set(r,0)}),C(i.restEncoder,n.size),ge(n.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{Fs(i,e.clients.get(s),s,r)})},Ps=(i,e)=>Ws(i,e.doc.store,e.beforeState);class Ks{constructor(){this.l=[]}}const Qt=()=>new Ks,ei=(i,e)=>i.l.push(e),ti=(i,e)=>{const t=i.l,n=t.length;i.l=t.filter(s=>e!==s),n===i.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Di=(i,e,t)=>Vt(i.l,[e,t]);class Ke{constructor(e,t){this.client=e,this.clock=t}}const xe=(i,e)=>i===e||i!==null&&e!==null&&i.client===e.client&&i.clock===e.clock,v=(i,e)=>new Ke(i,e),Gs=i=>{for(const[e,t]of i.doc.share.entries())if(t===i)return e;throw he()},ue=(i,e)=>e===void 0?!i.deleted:e.sv.has(i.id.client)&&(e.sv.get(i.id.client)||0)>i.id.clock&&!Ti(e.ds,i.id),It=(i,e)=>{const t=we(i.meta,It,fe),n=i.doc.store;t.has(e)||(e.sv.forEach((s,r)=>{s<B(n,r)&&re(i,v(r,s))}),Ri(i,e.ds,s=>{}),t.add(e))};class Js{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const jt=i=>{const e=new Map;return i.clients.forEach((t,n)=>{const s=t[t.length-1];e.set(n,s.id.clock+s.length)}),e},B=(i,e)=>{const t=i.clients.get(e);if(t===void 0)return 0;const n=t[t.length-1];return n.id.clock+n.length},Ni=(i,e)=>{let t=i.clients.get(e.id.client);if(t===void 0)t=[],i.clients.set(e.id.client,t);else{const n=t[t.length-1];if(n.id.clock+n.length!==e.id.clock)throw he()}t.push(e)},Y=(i,e)=>{let t=0,n=i.length-1,s=i[n],r=s.id.clock;if(r===e)return n;let o=ae(e/(r+s.length-1)*n);for(;t<=n;){if(s=i[o],r=s.id.clock,r<=e){if(e<r+s.length)return o;t=o+1}else n=o-1;o=ae((t+n)/2)}throw he()},qs=(i,e)=>{const t=i.clients.get(e.client);return t[Y(t,e.clock)]},mt=qs,Ot=(i,e,t)=>{const n=Y(e,t),s=e[n];return s.id.clock<t&&s instanceof U?(e.splice(n+1,0,Qi(i,s,t-s.id.clock)),n+1):n},re=(i,e)=>{const t=i.doc.store.clients.get(e.client);return t[Ot(i,t,e.clock)]},ii=(i,e,t)=>{const n=e.clients.get(t.client),s=Y(n,t.clock),r=n[s];return t.clock!==r.id.clock+r.length-1&&r.constructor!==ie&&n.splice(s+1,0,Qi(i,r,t.clock-r.id.clock+1)),r},Hs=(i,e,t)=>{const n=i.clients.get(e.id.client);n[Y(n,e.id.clock)]=t},Vi=(i,e,t,n,s)=>{if(n===0)return;const r=t+n;let o=Ot(i,e,t),c;do c=e[o++],r<c.id.clock+c.length&&Ot(i,e,r),s(c);while(o<e.length&&e[o].id.clock<r)};class zs{constructor(e,t,n){this.doc=e,this.deleteSet=new Ns,this.beforeState=jt(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const ni=(i,e)=>e.deleteSet.clients.size===0&&!Ln(e.afterState,(t,n)=>e.beforeState.get(n)!==t)?!1:(Ai(e.deleteSet),Ps(i,e),Us(i,e.deleteSet),!0),si=(i,e,t)=>{const n=e._item;(n===null||n.id.clock<(i.beforeState.get(n.id.client)||0)&&!n.deleted)&&we(i.changed,e,fe).add(t)},Ge=(i,e)=>{let t=i[e],n=i[e-1],s=e;for(;s>0;t=n,n=i[--s-1]){if(n.deleted===t.deleted&&n.constructor===t.constructor&&n.mergeWith(t)){t instanceof U&&t.parentSub!==null&&t.parent._map.get(t.parentSub)===t&&t.parent._map.set(t.parentSub,n);continue}break}const r=e-s;return r&&i.splice(e+1-r,r),r},Ys=(i,e,t)=>{for(const[n,s]of i.clients.entries()){const r=e.clients.get(n);for(let o=s.length-1;o>=0;o--){const c=s[o],l=c.clock+c.len;for(let h=Y(r,c.clock),u=r[h];h<r.length&&u.id.clock<l;u=r[++h]){const d=r[h];if(c.clock+c.len<=d.id.clock)break;d instanceof U&&d.deleted&&!d.keep&&t(d)&&d.gc(e,!1)}}}},Xs=(i,e)=>{i.clients.forEach((t,n)=>{const s=e.clients.get(n);for(let r=t.length-1;r>=0;r--){const o=t[r],c=_i(s.length-1,1+Y(s,o.clock+o.len-1));for(let l=c,h=s[l];l>0&&h.id.clock>=o.clock;h=s[l])l-=1+Ge(s,l)}})},Ui=(i,e)=>{if(e<i.length){const t=i[e],n=t.doc,s=n.store,r=t.deleteSet,o=t._mergeStructs;try{Ai(r),t.afterState=jt(t.doc.store),n.emit("beforeObserverCalls",[t,n]);const c=[];t.changed.forEach((l,h)=>c.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(t,l)})),c.push(()=>{t.changedParentTypes.forEach((l,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(l=l.filter(u=>u.target._item===null||!u.target._item.deleted),l.forEach(u=>{u.currentTarget=h,u._path=null}),l.sort((u,d)=>u.path.length-d.path.length),Di(h._dEH,l,t))})}),c.push(()=>n.emit("afterTransaction",[t,n])),Vt(c,[]),t._needFormattingCleanup&&ar(t)}finally{n.gc&&Ys(r,s,n.gcFilter),Xs(r,s),t.afterState.forEach((u,d)=>{const g=t.beforeState.get(d)||0;if(g!==u){const m=s.clients.get(d),b=be(Y(m,g),1);for(let p=m.length-1;p>=b;)p-=1+Ge(m,p)}});for(let u=o.length-1;u>=0;u--){const{client:d,clock:g}=o[u].id,m=s.clients.get(d),b=Y(m,g);b+1<m.length&&Ge(m,b+1)>1||b>0&&Ge(m,b)}if(!t.local&&t.afterState.get(n.clientID)!==t.beforeState.get(n.clientID)&&(As(Ut,Ci,"[yjs] ",Ei,ki,"Changed the client-id because another client seems to be using it."),n.clientID=Mi()),n.emit("afterTransactionCleanup",[t,n]),n._observers.has("update")){const u=new Bs;ni(u,t)&&n.emit("update",[u.toUint8Array(),t.origin,n,t])}if(n._observers.has("updateV2")){const u=new $s;ni(u,t)&&n.emit("updateV2",[u.toUint8Array(),t.origin,n,t])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:h}=t;(c.size>0||h.size>0||l.size>0)&&(c.forEach(u=>{u.clientID=n.clientID,u.collectionid==null&&(u.collectionid=n.collectionid),n.subdocs.add(u)}),h.forEach(u=>n.subdocs.delete(u)),n.emit("subdocs",[{loaded:l,added:c,removed:h},n,t]),h.forEach(u=>u.destroy())),i.length<=e+1?(n._transactionCleanups=[],n.emit("afterAllTransactions",[n,i])):Ui(i,e+1)}}},k=(i,e,t=null,n=!0)=>{const s=i._transactionCleanups;let r=!1,o=null;i._transaction===null&&(r=!0,i._transaction=new zs(i,t,n),s.push(i._transaction),s.length===1&&i.emit("beforeAllTransactions",[i]),i.emit("beforeTransaction",[i._transaction,i]));try{o=e(i._transaction)}finally{if(r){const c=i._transaction===s[0];i._transaction=null,c&&Ui(s,0)}}return o},ri="You must not compute changes after the event-handler fired.";class nt{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Zs(this.currentTarget,this.target))}deletes(e){return Ti(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw pe(ri);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach(s=>{if(s!==null){const r=t._map.get(s);let o,c;if(this.adds(r)){let l=r.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(r))if(l!==null&&this.deletes(l))o="delete",c=ut(l.content.getContent());else return;else l!==null&&this.deletes(l)?(o="update",c=ut(l.content.getContent())):(o="add",c=void 0)}else if(this.deletes(r))o="delete",c=ut(r.content.getContent());else return;e.set(s,{action:o,oldValue:c})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw pe(ri);const t=this.target,n=fe(),s=fe(),r=[];if(e={added:n,deleted:s,delta:r,keys:this.keys},this.transaction.changed.get(t).has(null)){let c=null;const l=()=>{c&&r.push(c)};for(let h=t._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((c===null||c.delete===void 0)&&(l(),c={delete:0}),c.delete+=h.length,s.add(h)):this.adds(h)?((c===null||c.insert===void 0)&&(l(),c={insert:[]}),c.insert=c.insert.concat(h.content.getContent()),n.add(h)):((c===null||c.retain===void 0)&&(l(),c={retain:0}),c.retain+=h.length);c!==null&&c.retain===void 0&&l()}this._changes=e}return e}}const Zs=(i,e)=>{const t=[];for(;e._item!==null&&e!==i;){if(e._item.parentSub!==null)t.unshift(e._item.parentSub);else{let n=0,s=e._item.parent._start;for(;s!==e._item&&s!==null;)!s.deleted&&s.countable&&(n+=s.length),s=s.right;t.unshift(n)}e=e._item.parent}return t},j=()=>{Ls("Invalid access: Add Yjs type to a document before reading data.")},ji=80;let Bt=0;class Qs{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Bt++}}const er=i=>{i.timestamp=Bt++},Bi=(i,e,t)=>{i.p.marker=!1,i.p=e,e.marker=!0,i.index=t,i.timestamp=Bt++},tr=(i,e,t)=>{if(i.length>=ji){const n=i.reduce((s,r)=>s.timestamp<r.timestamp?s:r);return Bi(n,e,t),n}else{const n=new Qs(e,t);return i.push(n),n}},st=(i,e)=>{if(i._start===null||e===0||i._searchMarker===null)return null;const t=i._searchMarker.length===0?null:i._searchMarker.reduce((r,o)=>We(e-r.index)<We(e-o.index)?r:o);let n=i._start,s=0;for(t!==null&&(n=t.p,s=t.index,er(t));n.right!==null&&s<e;){if(!n.deleted&&n.countable){if(e<s+n.length)break;s+=n.length}n=n.right}for(;n.left!==null&&s>e;)n=n.left,!n.deleted&&n.countable&&(s-=n.length);for(;n.left!==null&&n.left.id.client===n.id.client&&n.left.id.clock+n.left.length===n.id.clock;)n=n.left,!n.deleted&&n.countable&&(s-=n.length);return t!==null&&We(t.index-s)<n.parent.length/ji?(Bi(t,n,s),t):tr(i._searchMarker,n,s)},Ne=(i,e,t)=>{for(let n=i.length-1;n>=0;n--){const s=i[n];if(t>0){let r=s.p;for(r.marker=!1;r&&(r.deleted||!r.countable);)r=r.left,r&&!r.deleted&&r.countable&&(s.index-=r.length);if(r===null||r.marker===!0){i.splice(n,1);continue}s.p=r,r.marker=!0}(e<s.index||t>0&&e===s.index)&&(s.index=be(e,s.index+t))}},rt=(i,e,t)=>{const n=i,s=e.changedParentTypes;for(;we(s,i,()=>[]).push(t),i._item!==null;)i=i._item.parent;Di(n._eH,t,e)};class D{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Qt(),this._dEH=Qt(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw J()}clone(){throw J()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){ei(this._eH,e)}observeDeep(e){ei(this._dEH,e)}unobserve(e){ti(this._eH,e)}unobserveDeep(e){ti(this._dEH,e)}toJSON(){}}const xi=(i,e,t)=>{var o;(o=i.doc)!=null||j(),e<0&&(e=i._length+e),t<0&&(t=i._length+t);let n=t-e;const s=[];let r=i._start;for(;r!==null&&n>0;){if(r.countable&&!r.deleted){const c=r.content.getContent();if(c.length<=e)e-=c.length;else{for(let l=e;l<c.length&&n>0;l++)s.push(c[l]),n--;e=0}}r=r.right}return s},$i=i=>{var n;(n=i.doc)!=null||j();const e=[];let t=i._start;for(;t!==null;){if(t.countable&&!t.deleted){const s=t.content.getContent();for(let r=0;r<s.length;r++)e.push(s[r])}t=t.right}return e},Ve=(i,e)=>{var s;let t=0,n=i._start;for((s=i.doc)!=null||j();n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let o=0;o<r.length;o++)e(r[o],t++,i)}n=n.right}},Fi=(i,e)=>{const t=[];return Ve(i,(n,s)=>{t.push(e(n,s,i))}),t},ir=i=>{let e=i._start,t=null,n=0;return{[Symbol.iterator](){return this},next:()=>{if(t===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};t=e.content.getContent(),n=0,e=e.right}const s=t[n++];return t.length<=n&&(t=null),{done:!1,value:s}}}},Wi=(i,e)=>{var s;(s=i.doc)!=null||j();const t=st(i,e);let n=i._start;for(t!==null&&(n=t.p,e-=t.index);n!==null;n=n.right)if(!n.deleted&&n.countable){if(e<n.length)return n.content.getContent()[e];e-=n.length}},Ye=(i,e,t,n)=>{let s=t;const r=i.doc,o=r.clientID,c=r.store,l=t===null?e._start:t.right;let h=[];const u=()=>{h.length>0&&(s=new U(v(o,B(c,o)),s,s&&s.lastId,l,l&&l.id,e,null,new me(h)),s.integrate(i,0),h=[])};n.forEach(d=>{if(d===null)h.push(d);else switch(d.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(d);break;default:switch(u(),d.constructor){case Uint8Array:case ArrayBuffer:s=new U(v(o,B(c,o)),s,s&&s.lastId,l,l&&l.id,e,null,new ot(new Uint8Array(d))),s.integrate(i,0);break;case ye:s=new U(v(o,B(c,o)),s,s&&s.lastId,l,l&&l.id,e,null,new ct(d)),s.integrate(i,0);break;default:if(d instanceof D)s=new U(v(o,B(c,o)),s,s&&s.lastId,l,l&&l.id,e,null,new oe(d)),s.integrate(i,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},Pi=()=>pe("Length exceeded!"),Ki=(i,e,t,n)=>{if(t>e._length)throw Pi();if(t===0)return e._searchMarker&&Ne(e._searchMarker,t,n.length),Ye(i,e,null,n);const s=t,r=st(e,t);let o=e._start;for(r!==null&&(o=r.p,t-=r.index,t===0&&(o=o.prev,t+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(t<=o.length){t<o.length&&re(i,v(o.id.client,o.id.clock+t));break}t-=o.length}return e._searchMarker&&Ne(e._searchMarker,s,n.length),Ye(i,e,o,n)},nr=(i,e,t)=>{let s=(e._searchMarker||[]).reduce((r,o)=>o.index>r.index?o:r,{index:0,p:e._start}).p;if(s)for(;s.right;)s=s.right;return Ye(i,e,s,t)},Gi=(i,e,t,n)=>{if(n===0)return;const s=t,r=n,o=st(e,t);let c=e._start;for(o!==null&&(c=o.p,t-=o.index);c!==null&&t>0;c=c.right)!c.deleted&&c.countable&&(t<c.length&&re(i,v(c.id.client,c.id.clock+t)),t-=c.length);for(;n>0&&c!==null;)c.deleted||(n<c.length&&re(i,v(c.id.client,c.id.clock+n)),c.delete(i),n-=c.length),c=c.right;if(n>0)throw Pi();e._searchMarker&&Ne(e._searchMarker,s,-r+n)},Xe=(i,e,t)=>{const n=e._map.get(t);n!==void 0&&n.delete(i)},xt=(i,e,t,n)=>{const s=e._map.get(t)||null,r=i.doc,o=r.clientID;let c;if(n==null)c=new me([n]);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:c=new me([n]);break;case Uint8Array:c=new ot(n);break;case ye:c=new ct(n);break;default:if(n instanceof D)c=new oe(n);else throw new Error("Unexpected content type")}new U(v(o,B(r.store,o)),s,s&&s.lastId,null,null,e,t,c).integrate(i,0)},$t=(i,e)=>{var n;(n=i.doc)!=null||j();const t=i._map.get(e);return t!==void 0&&!t.deleted?t.content.getContent()[t.length-1]:void 0},Ji=i=>{var t;const e={};return(t=i.doc)!=null||j(),i._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},qi=(i,e)=>{var n;(n=i.doc)!=null||j();const t=i._map.get(e);return t!==void 0&&!t.deleted},sr=(i,e)=>{const t={};return i._map.forEach((n,s)=>{let r=n;for(;r!==null&&(!e.sv.has(r.id.client)||r.id.clock>=(e.sv.get(r.id.client)||0));)r=r.left;r!==null&&ue(r,e)&&(t[s]=r.content.getContent()[r.length-1])}),t},$e=i=>{var e;return(e=i.doc)!=null||j(),Ms(i._map.entries(),t=>!t[1].deleted)};class rr extends nt{}class Oe extends D{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Oe;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Oe}clone(){const e=new Oe;return e.insert(0,this.toArray().map(t=>t instanceof D?t.clone():t)),e}get length(){var e;return(e=this.doc)!=null||j(),this._length}_callObserver(e,t){super._callObserver(e,t),rt(this,e,new rr(this,e))}insert(e,t){this.doc!==null?k(this.doc,n=>{Ki(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){this.doc!==null?k(this.doc,t=>{nr(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc!==null?k(this.doc,n=>{Gi(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return Wi(this,e)}toArray(){return $i(this)}slice(e=0,t=this.length){return xi(this,e,t)}toJSON(){return this.map(e=>e instanceof D?e.toJSON():e)}map(e){return Fi(this,e)}forEach(e){Ve(this,e)}[Symbol.iterator](){return ir(this)}_write(e){e.writeTypeRef(pr)}}class or extends nt{constructor(e,t,n){super(e,t),this.keysChanged=n}}class Ze extends D{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((n,s)=>{this.set(s,n)}),this._prelimContent=null}_copy(){return new Ze}clone(){const e=new Ze;return this.forEach((t,n)=>{e.set(n,t instanceof D?t.clone():t)}),e}_callObserver(e,t){rt(this,e,new or(this,e,t))}toJSON(){var t;(t=this.doc)!=null||j();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof D?r.toJSON():r}}),e}get size(){return[...$e(this)].length}keys(){return _t($e(this),e=>e[0])}values(){return _t($e(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return _t($e(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){var t;(t=this.doc)!=null||j(),this._map.forEach((n,s)=>{n.deleted||e(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?k(this.doc,t=>{Xe(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return this.doc!==null?k(this.doc,n=>{xt(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return $t(this,e)}has(e){return qi(this,e)}clear(){this.doc!==null?k(this.doc,e=>{this.forEach(function(t,n,s){Xe(e,s,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(_r)}}const ne=(i,e)=>i===e||typeof i=="object"&&typeof e=="object"&&i&&e&&gs(i,e);class Rt{constructor(e,t,n,s){this.left=e,this.right=t,this.index=n,this.currentAttributes=s}forward(){switch(this.right===null&&he(),this.right.content.constructor){case L:this.right.deleted||Se(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const oi=(i,e,t)=>{for(;e.right!==null&&t>0;){switch(e.right.content.constructor){case L:e.right.deleted||Se(e.currentAttributes,e.right.content);break;default:e.right.deleted||(t<e.right.length&&re(i,v(e.right.id.client,e.right.id.clock+t)),e.index+=e.right.length,t-=e.right.length);break}e.left=e.right,e.right=e.right.right}return e},Fe=(i,e,t,n)=>{const s=new Map,r=n?st(e,t):null;if(r){const o=new Rt(r.p.left,r.p,r.index,s);return oi(i,o,t-r.index)}else{const o=new Rt(null,e._start,0,s);return oi(i,o,t)}},Hi=(i,e,t,n)=>{for(;t.right!==null&&(t.right.deleted===!0||t.right.content.constructor===L&&ne(n.get(t.right.content.key),t.right.content.value));)t.right.deleted||n.delete(t.right.content.key),t.forward();const s=i.doc,r=s.clientID;n.forEach((o,c)=>{const l=t.left,h=t.right,u=new U(v(r,B(s.store,r)),l,l&&l.lastId,h,h&&h.id,e,null,new L(c,o));u.integrate(i,0),t.right=u,t.forward()})},Se=(i,e)=>{const{key:t,value:n}=e;n===null?i.delete(t):i.set(t,n)},zi=(i,e)=>{var t;for(;i.right!==null;){if(!(i.right.deleted||i.right.content.constructor===L&&ne((t=e[i.right.content.key])!=null?t:null,i.right.content.value)))break;i.forward()}},Yi=(i,e,t,n)=>{var c;const s=i.doc,r=s.clientID,o=new Map;for(const l in n){const h=n[l],u=(c=t.currentAttributes.get(l))!=null?c:null;if(!ne(u,h)){o.set(l,u);const{left:d,right:g}=t;t.right=new U(v(r,B(s.store,r)),d,d&&d.lastId,g,g&&g.id,e,null,new L(l,h)),t.right.integrate(i,0),t.forward()}}return o},wt=(i,e,t,n,s)=>{t.currentAttributes.forEach((g,m)=>{s[m]===void 0&&(s[m]=null)});const r=i.doc,o=r.clientID;zi(t,s);const c=Yi(i,e,t,s),l=n.constructor===String?new X(n):n instanceof D?new oe(n):new Ce(n);let{left:h,right:u,index:d}=t;e._searchMarker&&Ne(e._searchMarker,t.index,l.getLength()),u=new U(v(o,B(r.store,o)),h,h&&h.lastId,u,u&&u.id,e,null,l),u.integrate(i,0),t.right=u,t.index=d,t.forward(),Hi(i,e,t,c)},ci=(i,e,t,n,s)=>{const r=i.doc,o=r.clientID;zi(t,s);const c=Yi(i,e,t,s);e:for(;t.right!==null&&(n>0||c.size>0&&(t.right.deleted||t.right.content.constructor===L));){if(!t.right.deleted)switch(t.right.content.constructor){case L:{const{key:l,value:h}=t.right.content,u=s[l];if(u!==void 0){if(ne(u,h))c.delete(l);else{if(n===0)break e;c.set(l,h)}t.right.delete(i)}else t.currentAttributes.set(l,h);break}default:n<t.right.length&&re(i,v(t.right.id.client,t.right.id.clock+n)),n-=t.right.length;break}t.forward()}if(n>0){let l="";for(;n>0;n--)l+=`
|
|
2
|
-
`;t.right=new U(v(o,B(r.store,o)),t.left,t.left&&t.left.lastId,t.right,t.right&&t.right.id,e,null,new X(l)),t.right.integrate(i,0),t.forward()}
|
|
3
|
-
`?o.insert.slice(0,-1):o.insert;(typeof c!="string"||c.length>0)&&wt(n,this,s,c,o.attributes||{})}else o.retain!==void 0?ci(n,this,s,o.retain,o.attributes||{}):o.delete!==void 0&&li(n,s,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){var d;(d=this.doc)!=null||j();const s=[],r=new Map,o=this.doc;let c="",l=this._start;function h(){if(c.length>0){const g={};let m=!1;r.forEach((p,_)=>{m=!0,g[_]=p});const b={insert:c};m&&(b.attributes=g),s.push(b),c=""}}const u=()=>{for(;l!==null;){if(ue(l,e)||t!==void 0&&ue(l,t))switch(l.content.constructor){case X:{const g=r.get("ychange");e!==void 0&&!ue(l,e)?(g===void 0||g.user!==l.id.client||g.type!=="removed")&&(h(),r.set("ychange",n?n("removed",l.id):{type:"removed"})):t!==void 0&&!ue(l,t)?(g===void 0||g.user!==l.id.client||g.type!=="added")&&(h(),r.set("ychange",n?n("added",l.id):{type:"added"})):g!==void 0&&(h(),r.delete("ychange")),c+=l.content.str;break}case oe:case Ce:{h();const g={insert:l.content.getContent()[0]};if(r.size>0){const m={};g.attributes=m,r.forEach((b,p)=>{m[p]=b})}s.push(g);break}case L:ue(l,e)&&(h(),Se(r,l.content));break}l=l.right}h()};return e||t?k(o,g=>{e&&It(g,e),t&&It(g,t),u()},"cleanup"):u(),s}insert(e,t,n){if(t.length<=0)return;const s=this.doc;s!==null?k(s,r=>{const o=Fe(r,this,e,!n);n||(n={},o.currentAttributes.forEach((c,l)=>{n[l]=c})),wt(r,this,o,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const s=this.doc;s!==null?k(s,r=>{const o=Fe(r,this,e,!n);wt(r,this,o,t,n||{})}):this._pending.push(()=>this.insertEmbed(e,t,n||{}))}delete(e,t){if(t===0)return;const n=this.doc;n!==null?k(n,s=>{li(s,Fe(s,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,n){if(t===0)return;const s=this.doc;s!==null?k(s,r=>{const o=Fe(r,this,e,!1);o.right!==null&&ci(r,this,o,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){this.doc!==null?k(this.doc,t=>{Xe(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){this.doc!==null?k(this.doc,n=>{xt(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return $t(this,e)}getAttributes(){return Ji(this)}_write(e){e.writeTypeRef(mr)}}class bt{constructor(e,t=()=>!0){var n;this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,(n=e.doc)!=null||j()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===Ue||t.constructor===_e)&&t._start!==null)e=t._start;else for(;e!==null;)if(e.right!==null){e=e.right;break}else e.parent===this._root?e=null:e=e.parent._item;while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class _e extends D{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new _e}clone(){const e=new _e;return e.insert(0,this.toArray().map(t=>t instanceof D?t.clone():t)),e}get length(){var e;return(e=this.doc)!=null||j(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new bt(this,e)}querySelector(e){e=e.toUpperCase();const n=new bt(this,s=>s.nodeName&&s.nodeName.toUpperCase()===e).next();return n.done?null:n.value}querySelectorAll(e){return e=e.toUpperCase(),ge(new bt(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){rt(this,e,new ur(this,t,e))}toString(){return Fi(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const s=e.createDocumentFragment();return n!==void 0&&n._createAssociation(s,this),Ve(this,r=>{s.insertBefore(r.toDOM(e,t,n),null)}),s}insert(e,t){this.doc!==null?k(this.doc,n=>{Ki(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(this.doc!==null)k(this.doc,n=>{const s=e&&e instanceof D?e._item:e;Ye(n,this,s,t)});else{const n=this._prelimContent,s=e===null?0:n.findIndex(r=>r===e)+1;if(s===0&&e!==null)throw pe("Reference item not found");n.splice(s,0,...t)}}delete(e,t=1){this.doc!==null?k(this.doc,n=>{Gi(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return $i(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Wi(this,e)}slice(e=0,t=this.length){return xi(this,e,t)}forEach(e){Ve(this,e)}_write(e){e.writeTypeRef(br)}}class Ue extends _e{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((n,s)=>{this.setAttribute(s,n)}),this._prelimAttrs=null}_copy(){return new Ue(this.nodeName)}clone(){const e=new Ue(this.nodeName),t=this.getAttributes();return hs(t,(n,s)=>{typeof n=="string"&&e.setAttribute(s,n)}),e.insert(0,this.toArray().map(n=>n instanceof D?n.clone():n)),e}toString(){const e=this.getAttributes(),t=[],n=[];for(const c in e)n.push(c);n.sort();const s=n.length;for(let c=0;c<s;c++){const l=n[c];t.push(l+'="'+e[l]+'"')}const r=this.nodeName.toLocaleLowerCase(),o=t.length>0?" "+t.join(" "):"";return`<${r}${o}>${super.toString()}</${r}>`}removeAttribute(e){this.doc!==null?k(this.doc,t=>{Xe(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){this.doc!==null?k(this.doc,n=>{xt(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return $t(this,e)}hasAttribute(e){return qi(this,e)}getAttributes(e){return e?sr(this,e):Ji(this)}toDOM(e=document,t={},n){const s=e.createElement(this.nodeName),r=this.getAttributes();for(const o in r){const c=r[o];typeof c=="string"&&s.setAttribute(o,c)}return Ve(this,o=>{s.appendChild(o.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(s,this),s}_write(e){e.writeTypeRef(wr),e.writeKey(this.nodeName)}}class ur extends nt{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(s=>{s===null?this.childListChanged=!0:this.attributesChanged.add(s)})}}class Zi{constructor(e,t){this.id=e,this.length=t}get deleted(){throw J()}mergeWith(e){return!1}write(e,t,n){throw J()}integrate(e,t){throw J()}}const dr=0;class ie extends Zi{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Ni(e.doc.store,this)}write(e,t){e.writeInfo(dr),e.writeLen(this.length-t)}getMissing(e,t){return null}}class ot{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ot(this.content)}splice(e){throw J()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class et{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new et(this.len)}splice(e){const t=new et(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Li(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}const fr=(i,e)=>new ye({guid:i,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class ct{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new ct(fr(this.doc.guid,this.opts))}splice(e){throw J()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}class Ce{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Ce(this.embed)}splice(e){throw J()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class L{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new L(this.key,this.value)}splice(e){throw J()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const gr=ze("node_env")==="development";class me{constructor(e){this.arr=e,gr&&yi(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new me(this.arr)}splice(e){const t=new me(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let s=t;s<n;s++){const r=this.arr[s];e.writeAny(r)}}getRef(){return 8}}class X{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new X(this.str)}splice(e){const t=new X(this.str.slice(e));this.str=this.str.slice(0,e);const n=this.str.charCodeAt(e-1);return n>=55296&&n<=56319&&(this.str=this.str.slice(0,e-1)+"�",t.str="�"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}}const pr=0,_r=1,mr=2,wr=3,br=4;class oe{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new oe(this.type._copy())}splice(e){throw J()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(n=>{n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(n=>{for(;n!==null;)n.gc(e,!0),n=n.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}const Qi=(i,e,t)=>{const{client:n,clock:s}=e.id,r=new U(v(n,s+t),e,v(n,s+t-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t));return e.deleted&&r.markDeleted(),e.keep&&(r.keep=!0),e.redone!==null&&(r.redone=v(e.redone.client,e.redone.clock+t)),e.right=r,r.right!==null&&(r.right.left=r),i._mergeStructs.push(r),r.parentSub!==null&&r.right===null&&r.parent._map.set(r.parentSub,r),e.length=t,r};class U extends Zi{constructor(e,t,n,s,r,o,c,l){super(e,l.getLength()),this.origin=n,this.left=t,this.right=s,this.rightOrigin=r,this.parent=o,this.parentSub=c,this.redone=null,this.content=l,this.info=this.content.isCountable()?Pt:0}set marker(e){(this.info&ft)>0!==e&&(this.info^=ft)}get marker(){return(this.info&ft)>0}get keep(){return(this.info&Wt)>0}set keep(e){this.keep!==e&&(this.info^=Wt)}get countable(){return(this.info&Pt)>0}get deleted(){return(this.info&dt)>0}set deleted(e){this.deleted!==e&&(this.info^=dt)}markDeleted(){this.info|=dt}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=B(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=B(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Ke&&this.id.client!==this.parent.client&&this.parent.clock>=B(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=ii(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=re(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ie||this.right&&this.right.constructor===ie)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===U&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===U&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Ke){const n=mt(t,this.parent);n.constructor===ie?this.parent=null:this.parent=n.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=ii(e,e.doc.store,v(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let n=this.left,s;if(n!==null)s=n.right;else if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start;const r=new Set,o=new Set;for(;s!==null&&s!==this.right;){if(o.add(s),r.add(s),xe(this.origin,s.origin)){if(s.id.client<this.id.client)n=s,r.clear();else if(xe(this.rightOrigin,s.rightOrigin))break}else if(s.origin!==null&&o.has(mt(e.doc.store,s.origin)))r.has(mt(e.doc.store,s.origin))||(n=s,r.clear());else break;s=s.right}this.left=n}if(this.left!==null){const n=this.left.right;this.right=n,this.left.right=this}else{let n;if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start,this.parent._start=this;this.right=n}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Ni(e.doc.store,this),this.content.integrate(e,this),si(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new ie(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:v(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&xe(e.origin,this.lastId)&&this.right===e&&xe(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach(n=>{n.p===e&&(n.p=this,!this.deleted&&this.countable&&(n.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),Li(e.deleteSet,this.id.client,this.id.clock,this.length),si(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw he();this.content.gc(e),t?Hs(e,this,new ie(this.id,this.length)):this.content=new et(this.length)}write(e,t){const n=t>0?v(this.id.client,this.id.clock+t-1):this.origin,s=this.rightOrigin,r=this.parentSub,o=this.content.getRef()&Un|(n===null?0:He)|(s===null?0:mi)|(r===null?0:Vn);if(e.writeInfo(o),n!==null&&e.writeLeftID(n),s!==null&&e.writeRightID(s),n===null&&s===null){const c=this.parent;if(c._item!==void 0){const l=c._item;if(l===null){const h=Gs(c);e.writeParentInfo(!0),e.writeString(h)}else e.writeParentInfo(!1),e.writeLeftID(l.id)}else c.constructor===String?(e.writeParentInfo(!0),e.writeString(c)):c.constructor===Ke?(e.writeParentInfo(!1),e.writeLeftID(c)):he();r!==null&&e.writeString(r)}this.content.write(e,t)}}const en=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:{},tn="__ $YJS$ __";en[tn]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");en[tn]=!0;const ke=i=>Promise.reject("unimplemented method GetVoiceSign"),yt=(i,e={},t=[])=>({command:i,front_request_id:Te(),data:{...e,to_user_ids:Array.isArray(t)?t:[t]}}),nn=()=>{var i,e;window!=null&&window.__Realsee_Live__&&((e=(i=window==null?void 0:window.__Realsee_Live__)==null?void 0:i.dispose)==null||e.call(i),window.__Realsee_Live__=null)};class sn extends Re{constructor(t){super();a(this,"_options",{});a(this,"keyframes",new Re);a(this,"_yDoc");a(this,"_buildInData");a(this,"_initializeKeyframesObservers",()=>{this._yDoc.getMap("keyframes").observe(this._handleKeyframesChange)});a(this,"_handleKeyframesChange",t=>{var o;const{transaction:n,target:s,changes:r}=t;if(s===this._buildInData.keyframes)if(n.origin.triggerUserId===((o=this.selfInfo)==null?void 0:o.id)){const c=yt(x.KeyframeSync,this.snapshot,void 0);try{this._controller.sendMessage(c)}catch(l){w.error("Failed to send keyframe sync message:",l)}}else r.keys.forEach((c,l)=>{const h=c.oldValue,u=this.getFramesByKey(l),d=n.origin.frontRequestId;this.keyframes.emit(l,u,h,d)}),r.keys.size!==0&&this.emit("keyframes",this.snapshot,n.origin.frontRequestId)});a(this,"getFramesByKey",t=>this.snapshot[t]);a(this,"sendKeyframe",(t,n)=>{var s;return this.state!==V.OPEN?(w.warn("Attempted to send keyframe while connection is not open"),!1):(this._yDoc.transact(()=>{this._buildInData.keyframes.set(t,n)},{triggerUserId:(s=this.selfInfo)==null?void 0:s.id,frontRequestId:""}),!0)});a(this,"_controller",new Tn);a(this,"_initializeOptions",t=>{var n;this._options=Object.assign({initialMicroStatus:te.OPEN},t),this._options.jsBridge=this._initializeJsBridge(t),this._options.getVoiceSign=(n=t.getVoiceSign)!=null?n:ke,this._options.autoPlayConfirm=t.autoPlayConfirm,this._options.rtc=this._initializeRTC(t)});a(this,"_initializeJsBridge",t=>{if(t.jsBridge)return t.jsBridge;if(t.useBuiltInJsBridge)return new dn});a(this,"_initializeRTC",t=>{if(t.rtc)return t.rtc;if(t.rtcType)return this._createBuiltInRTC(t);if(t.useBuiltInRTC)return this._createDefaultRTC(t)});a(this,"_createBuiltInRTC",t=>{var n;if(!t.getVoiceSign){w.error("GetVoiceSign method must be passed when using built-in RTC instances");return}switch(t.rtcType){case se.RealseeVRWebViewRTC:return this._createVRWebViewRTC();case se.RealseeBrowserChimeRTC:return new St({getVoiceSign:(n=this._options.getVoiceSign)!=null?n:ke,logLevel:t.__debug__?0:1});case se.RealseeBrowserRTC:return this._createBrowserRTC();default:w.error("unknown built-in RTC type");return}});a(this,"_createVRWebViewRTC",()=>{var t;if(this._options.jsBridge)return new hi({jsBridge:this._options.jsBridge,getVoiceSign:(t=this._options.getVoiceSign)!=null?t:ke});w.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances")});a(this,"_createBrowserRTC",()=>{var t;if(!this._options.autoPlayConfirm){w.error("autoPlayConfirm method must be passed when using built-in RealseeBrowserRTC instances");return}return new ai({getVoiceSign:(t=this._options.getVoiceSign)!=null?t:ke,autoPlayConfirm:this._options.autoPlayConfirm})});a(this,"_createDefaultRTC",t=>{var n;if(!t.getVoiceSign){w.error("GetVoiceSign method must be passed when using built-in RTC instances");return}if(this._options.jsBridge){if(Sn&&(wn||bn)||yn)return this._createVRWebViewRTC();{const s=(n=this._options.getVoiceSign)!=null?n:ke;return t.builtInRTCType===Tt.RealseeXChimeRTC?new St({getVoiceSign:s}):this._createBrowserRTC()}}else{w.error("jsBridge instance must be passed when using built-in RTC instances");return}});a(this,"_autoConnect",()=>{this._options.url&&this._options.getTicket&&this.connect()});a(this,"_debugSetup",()=>{this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this})});a(this,"_addLiveControllerEventListeners",()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage)});a(this,"_removeLiveControllerEventListeners",()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage)});a(this,"_handleStateChange",(t,n)=>{w.info(`State changed from ${n} to ${t}`),this.emit("stateChange",t,n)});a(this,"_handleMessage",async t=>{var n,s,r,o,c,l;if(w.debug("Received message:",t),typeof t=="object"){const{command:h,data:u={},frontRequestId:d,code:g,message:m,triggerUserId:b}=t;if(g==="SUCCESS")switch(h){case x.SelfUserInfo:{const p=u;On(this.selfInfo,p,{deep:!0})||(this._buildInData.selfInfo=p,this.emit("selfInfoUpdate",this._buildInData.selfInfo,d));break}case x.RoomInfo:{const p=u;this._buildInData.roomInfo=Object.assign({},p);const _=p.last_frame||{};this._yDoc.transact(()=>{for(const I in _)this._buildInData.keyframes.set(I,_[I])},{triggerUserId:"readyKeyframeSync",frontRequestId:d}),this.emit("readyKeyframeSync",p.last_frame||{});break}case x.RTCInfo:{w.info("RTC info updated:",u);const{voice_id:p,type:_}=u;if(this._buildInData.rtcInfo={voiceId:p,type:_},(n=this.$RTC)!=null&&n.joined)w.warn("已加入语音房间,无需重复加入!");else if(await((o=this.$RTC)==null?void 0:o.join({voiceId:p,userId:((s=this.selfInfo)==null?void 0:s.id)||"",roomId:(r=this.roomInfo)==null?void 0:r.info.room_code,type:_}))){const N=(c=this._options.initialMicroStatus)!=null?c:te.OPEN;await this.toggleMicro(N===te.OPEN)}else w.error("加入语音房间失败");break}case x.UserList:{const p=u;this._buildInData.userList=p,this.emit("userListUpdate",this.userList,d);break}case x.CustomEvent:{const p=u;this.emit("broadcast",p,d);break}case x.KeyframeSync:{const p=u;if(b===((l=this.selfInfo)==null?void 0:l.id))return;this._yDoc.transact(()=>{for(const _ in p)this._buildInData.keyframes.set(_,p[_])},{triggerUserId:b,frontRequestId:d});break}case x.BuiltinMsg:{const p=u;this.emit("builtinEvent",p),p.event_type===F.UserChange&&this.emit("userChange",p),p.event_type===F.RoomChange&&this.emit("roomChange",p),p.event_type===F.UserChange&&p.action===K.UserMicroStatus&&await this.toggleMicro(p.data.status===te.OPEN),p.event_type===F.RoomChange&&p.action===K.RoomClose&&await this._exit();break}case x.UserKickOut:{this.emit("kickOut");break}default:w.warn("Unknown command received:",h)}else w.error("Error in message:",m),this.emit("error",t)}});a(this,"_clearLiveData",()=>{this._buildInData.keyframes.clear(),this._buildInData={keyframes:this._yDoc.getMap("keyframes")}});a(this,"connect",async(t={})=>{var s,r,o,c;if(w.info("Attempting to connect with options:",t),this._options.url=(r=(s=t.url)!=null?s:this._options.url)!=null?r:"",this._options.getTicket=(o=t.getTicket)!=null?o:this._options.getTicket,this._options.initialMicroStatus=(c=t.rtcMicStatus)!=null?c:this._options.initialMicroStatus,!/^ws(s):\/\//.test(this._options.url)||typeof this._options.getTicket!="function")return new Error("Invalid connection parameters");if(this._options.rtc&&!await this._options.rtc.detectMicro())return new Error("Failed to obtain microphone authorization");const n=this.state;if(n===V.CONNECTING||n===V.OPEN)if(t.force)await this._controller.close("force close by connect").catch(console.warn);else return new Error("已有Live实例正在连接中,请勿重复连接!");this._clearLiveData();try{const l=await this._options.getTicket(),h=_n(this._options.url,{ticket:l,force:+!!t.force});return this._controller.open(h),w.info("Connection established successfully"),!0}catch(l){return w.error("Failed to connect:",l),new Error("Failed to connect")}});a(this,"_exit",async()=>{var t;this._clearLiveData();try{await((t=this.$RTC)==null?void 0:t.quit())}catch(n){w.warn(n)}return this.state!==V.OPEN?!0:await this._controller.close()});a(this,"exit",async()=>this.close());a(this,"close",async()=>{var t;await this._controller.readyClose();try{await((t=this.$RTC)==null?void 0:t.quit())}catch(n){w.warn(n)}await this.updateStatus(F.RoomChange,K.RoomClose,{})});a(this,"dispose",async()=>(this._removeLiveControllerEventListeners(),this._clearLiveData(),await this._controller.dispose()));a(this,"setSelfInfo",async t=>await this.updateStatus(F.UserChange,K.UserInfo,t));a(this,"broadcast",(t,n,s)=>this.state!==V.OPEN?!1:new Promise((r,o)=>{const c=yt(x.CustomEvent,t,n),l=c.front_request_id,h=s?setTimeout(()=>{o(new Error("RESPONSE TIMEOUT")),this.off("broadcast",u)},s):void 0,u=(d,g)=>{g===l&&(h&&clearTimeout(h),this.off("broadcast",u),r(d))};this.on("broadcast",u);try{this._controller.sendMessage(c)}catch(d){o(d)}}));a(this,"toggleMicro",async t=>{var s,r,o;if(!((r=(s=this.selfInfo)==null?void 0:s.permission)!=null&&r.control_own_micro))return!1;const n=await((o=this.$RTC)==null?void 0:o.toggleMicro(t));return n&&await this.updateStatus(F.UserChange,K.UserMicroStatus,{status:t?te.OPEN:te.CLOSE},[]),n});a(this,"forbidMicro",async(t,n)=>{var s,r;return typeof this._options.canForbidUserMicro=="function"&&!this._options.canForbidUserMicro(n)||!((r=(s=this.selfInfo)==null?void 0:s.permission)!=null&&r.control_other_micro)?!1:await this.updateStatus(F.UserChange,K.UserMicroStatus,{status:t},n)});a(this,"forbidSync",async(t,n)=>{var s,r;return typeof this._options.canForbidUserSync=="function"&&!this._options.canForbidUserSync(n)||!((r=(s=this.selfInfo)==null?void 0:s.permission)!=null&&r.control_other_sync)?!1:await this.updateStatus(F.UserChange,K.UserPermission,{sync_frame:t},n)});a(this,"kick",async t=>{var n,s;return typeof this._options.canForbidUserKick=="function"&&!this._options.canForbidUserKick(t)||!((s=(n=this.selfInfo)==null?void 0:n.permission)!=null&&s.change_other_status)?!1:await this.updateStatus(F.UserChange,K.UserStatus,{status:"KICK_OUT"},t)});a(this,"getSnapshotForKey",t=>this.snapshot[t]);w.info("Initializing Live instance with options:",t),this._addLiveControllerEventListeners(),this._yDoc=new ye({guid:Te()}),this._buildInData={keyframes:this._yDoc.getMap("keyframes")},this._initializeKeyframesObservers(),this._initializeOptions(t),this._autoConnect(),this._debugSetup()}get options(){return Object.freeze(this._options||{})}get state(){return this._controller.state}get readyState(){return this._controller.state}get url(){return this.options.url}get $RTC(){return this._options.rtc}get jsBridge(){return this._options.jsBridge}get snapshot(){return this._buildInData.keyframes.toJSON()}get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}async updateStatus(t,n,s,r){if(this.state!==V.OPEN)return!1;const o=Object.assign({event_type:t,action:n},{data:s}),c=yt(x.BuiltinMsg,o,r);try{return this._controller.sendMessage(c),!0}catch(l){return w.error(l),!1}}}const rn=i=>(nn(),new sn(i));function yr(i){const e=y.createContext(null),t=rn(i),n=t.jsBridge,s=f=>y.createElement(e.Provider,{value:t},f.children),r=()=>{const f=y.useContext(e);if(!f)throw new Error("LiveProvider never found.");return f},o=()=>t,c=()=>t.$RTC,l=()=>c(),h=()=>async f=>await t.connect(f);function u(f,E,T=[]){const S=r(),O=[S,name,...T],M=()=>S.keyframes.off(f,E);return y.useEffect(()=>(S.keyframes.on(f,E),M),O),M}function d(){const f=r(),E=y.useCallback(async R=>{await f.connect(R)},[f]),T=y.useCallback(R=>{f.toggleMicro(R)},[f]),S=y.useCallback(async(R,q,at=0)=>{await f.broadcast(R,q,at)},[f]),O=y.useCallback(async()=>{await f.exit()},[f]),M=y.useCallback(async R=>{await f.kick(R)},[f]),W=y.useCallback(async(R,q=[])=>{await f.forbidMicro(R,q)},[f]),ce=y.useCallback((R,q=[])=>{f.forbidSync(R,q)},[f]),lt=y.useCallback(R=>f.getFramesByKey(R),[f]),on=y.useCallback((R,q)=>{f.sendKeyframe(R,q)},[f]),cn=y.useCallback(R=>{f.setSelfInfo(R)},[f]),ln=y.useCallback((R,q,at,an)=>{f.updateStatus(R,q,at,an)},[f]);return{connect:E,broadcast:S,exit:O,kick:M,toggleMicro:T,forbidMicro:W,forbidSync:ce,sendKeyframe:on,getFramesByKey:lt,setSelfInfo:cn,updateStatus:ln}}function g(f){const E=r(),[T,S]=y.useState(E.getFramesByKey(f));y.useEffect(()=>{const M=lt=>S(lt),W=f,ce=M;return E.keyframes.on(W,ce),()=>E.keyframes.off(W,ce)},[E]);const O=y.useCallback(M=>E.sendKeyframe(f,M),[E]);return[T,O]}function m(f,E,T=[]){const S=r(),O=()=>S.off(f,E),M=[S,f,...T];return y.useEffect(()=>(S.on(f,E),O),M),O}function b(){const f=r(),[E,T]=y.useState(f.state);return y.useEffect(()=>{const S=O=>T(O);return f.on("stateChange",S),()=>f.off("stateChange",S)},[f]),E}function p(){const f=r();return{join:W=>f.$RTC.join(W),quit:()=>f.$RTC.quit(),shock:()=>{var W,ce;return(ce=(W=f.$RTC).shock)==null?void 0:ce.call(W)},toggleMicro:W=>f.$RTC.toggleMicro(W),detectMicro:()=>f.$RTC.detectMicro()}}function _(f,E,T=[]){const S=r(),O=()=>S.$RTC.off(f,E),M=[S,f,...T];return y.useEffect(()=>(S.$RTC.on(f,E),O),M),O}function I(){const f=r(),[E,T]=y.useState(f.selfInfo||{}),S=M=>T(M);y.useEffect(()=>(f.on("selfInfoUpdate",S),()=>f.off("selfInfoUpdate",S)),[f]);const O=y.useCallback(async M=>await f.setSelfInfo(M),[f]);return[E,O]}function N(){const f=r(),[E,T]=y.useState(f.snapshot);return y.useEffect(()=>{const S=O=>T(O);return f.on("keyframes",S),()=>f.off("keyframes",S)},[f]),E}function Ft(){const f=r(),[E,T]=y.useState(f.userList),S=O=>T(O);return y.useEffect(()=>(f.on("userListUpdate",S),()=>f.off("userListUpdate",S)),[f]),E}return{live:t,jsBridge:n,LiveProvider:s,unsafe__useLiveInstance:o,unsafe__useRTCInstance:l,useConnect:h,useKeyframe:g,useKeyframeUpdateCallback:u,useLiveAction:d,useLiveEventCallback:m,useLiveState:b,useRTCAction:p,useRTCEventCallback:_,useSelfInfo:I,useKeyframesSnapshot:N,useUserList:Ft}}console.log("%c@realsee/live@0.7.2 (2024/10/25 18:50:56)","background: linear-gradient(to right, #1890ff, #52c41a); color: white; padding: 3px 6px; border-radius: 4px; font-weight: bold; text-shadow: 0 1px 0 rgba(0,0,0,0.2);");exports.BrowserRTC=ai;exports.BrowserRTC4Chime=St;exports.BuiltInRTCType=Tt;exports.BuiltinActionType=K;exports.BuiltinEventType=F;exports.Command=x;exports.CoreRTC=tt;exports.Live=sn;exports.LiveState=V;exports.MemUserStatus=di;exports.MicroStatus=te;exports.RTCJoinedInfoCodeEnum=le;exports.RTCType=se;exports.UserStatus=ui;exports.VRWebViewRTC=hi;exports.WebSocketCloseError=gi;exports.WebSocketErrorType=fi;exports.WebSocketState=Je;exports._clearLiveInstanceIfNeed=nn;exports.createLive=rn;exports.createLiveReact=yr;exports.parseLiveMsg=pn;exports.parseWSClsErr=pi;
|
|
1
|
+
"use strict";var pn=Object.defineProperty;var _n=(i,e,t)=>e in i?pn(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var a=(i,e,t)=>_n(i,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ht=require("trtc-js-sdk"),Q=require("amazon-chime-sdk-js"),mn=require("@realsee/jsbridge-x"),b=require("react"),de=Symbol("$$REALSEE_LIVE_EVENT$$");function Be(i){return i[de]||(i[de]={}),i[de]}function Pt(i){const e=i[de];if(!e)return;Object.keys(e).some(n=>Array.isArray(e[n])&&e[n].length>0)||delete i[de]}class Ae{hasListener(e){const t=Be(this);return t&&t[e]&&t[e].length>0}on(e,t,n){const s=Be(this);return s[e]||(s[e]=[]),s[e].push([t,n||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){const n=Be(this);if(!e){delete this[de];return}if(n[e]||(n[e]=[]),t===void 0){n[e].length=0,Pt(this);return}const s=n[e].findIndex(r=>r[0]===t);s!==-1&&n[e].splice(s,1),Pt(this)}emit(e,...t){let n=!1;const r=Be(this)[e]||[];for(let o of r.slice()){const[c,l=!1]=o,h=c(...t);l&&this.off(e,c),h===!1&&(n=!0)}return n}}class tt extends Ae{}var se=(i=>(i.RealseeBrowserRTC="RealseeBrowserRTC",i.RealseeVRWebViewRTC="RealseeVRWebViewRTC",i.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",i))(se||{}),Tt=(i=>(i.RealseeXTRTC="trtc",i.RealseeXChimeRTC="chime",i))(Tt||{});const wn=()=>{const i=new Date,e=i.getFullYear(),t=(i.getMonth()+1).toString().padStart(2,"0"),n=i.getDate().toString().padStart(2,"0"),s=i.getHours().toString().padStart(2,"0"),r=i.getMinutes().toString().padStart(2,"0"),o=i.getSeconds().toString().padStart(2,"0"),c=i.getMilliseconds().toString().padStart(3,"0");return`[${e}-${t}-${n} ${s}:${r}:${o}.${c}]`},ve=(i,e=[])=>{const t=`Realsee Live ${wn()} <${i}> `;switch(i){case"INFO":console.info(t,...e);break;case"ERROR":console.error(t,...e);break;case"WARN":console.warn(t,...e);break;case"DEBUG":console.debug(t,...e);break;default:console.log(t,...e)}},m={log:(...i)=>ve("LOG",i),info:(...i)=>ve("INFO",i),error:(...i)=>ve("ERROR",i),warn:(...i)=>ve("WARN",i),debug:(...i)=>ve("DEBUG",i)};function ee(){return((1+Math.random())*65536|0).toString(16).substring(1)}function Te(){return[ee(),ee(),"4"+ee().substring(0,3),ee(),ee(),ee()+ee()+ee()].join("-").toLowerCase()}class fi extends tt{constructor(t){super();a(this,"type",se.RealseeBrowserRTC);a(this,"joined",!1);a(this,"micro",!1);a(this,"voiceId","");a(this,"_getVoiceSign",()=>{throw new Error("方法 getVoiceSign 未实现")});a(this,"_autoPlayConfirm");a(this,"checkRequirement",()=>ht.checkSystemRequirements());a(this,"$dom",document.createElement("div"));a(this,"_trtc",{client:null,stream:null});a(this,"join",async t=>{var r;this.emit("joinWillStart");const n=await this._getVoiceSign({voiceId:t.voiceId,roomId:t.roomId,userId:t.userId});this._trtc.client=ht.createClient({mode:"rtc",...n,enableAutoPlayDialog:typeof this._autoPlayConfirm!="function"}),(r=this._trtc.client)==null||r.enableAudioVolumeEvaluation(),this._registerRtcEvent();let s=await new Promise(o=>{var c;(c=this._trtc.client)==null||c.join({roomId:Number(t.voiceId)}).then(()=>o(!0)).catch(()=>o(!1))});return this.joined=s,s?(this._trtc.stream=ht.createStream({userId:n.userId,audio:!0,video:!1}),s=await new Promise(o=>{var c;(c=this._trtc.stream)==null||c.initialize().then(()=>o(!0)).catch(()=>o(!1))}),s=await new Promise(o=>{var c;(c=this._trtc.client)==null||c.publish(this._trtc.stream).then(()=>o(!0)).catch(()=>o(!1))}),this.joined=s,this.joined&&this.emit("joined"),s):!1});a(this,"_handleStreamAdded",t=>{var s;const n=t.stream;m.info("远端流增加:",n.getId()),(s=this._trtc.client)==null||s.subscribe(n)});a(this,"_handleStreamSubscribed",t=>{const n=t.stream;m.info("远端流订阅成功:",n.getId());const r=`rs-rtc-remote_stream-${n.getId()}`,o=document.createElement("div");o.id=r,this.$dom.appendChild(o),typeof this._autoPlayConfirm=="function"?(n.play(r).catch(c=>{m.warn("远端流播放失败(将尝试用户确认恢复)")}),n.on("error",c=>{if(c.getCode()===16451){const h=()=>n.resume();this._autoPlayConfirm({onConfirm:h})}})):n.play(r)});this._getVoiceSign=t.getVoiceSign,this._autoPlayConfirm=t.autoPlayConfirm,this._initParentDom()}_initParentDom(){this.$dom.id=`rs-rtc-${Te()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom)}quit(){return new Promise(async t=>{var n,s;this.joined=!1,this._trtc.stream&&(await((n=this._trtc.client)==null?void 0:n.unpublish(this._trtc.stream)),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),(s=this._trtc.client)==null||s.leave().then(()=>this._trtc.client=null).then(()=>t(!0)).catch(()=>t(!1)),t(!0)})}detectMicro(){return new Promise(t=>{const n={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(n).then(()=>t(!0)).catch(s=>{m.error(s.message),t(!1)})}catch(s){console.error(s),t(!1)}})}toggleMicro(t){return new Promise(n=>{var s,r,o,c;try{t?((r=(s=this._trtc)==null?void 0:s.stream)==null||r.unmuteAudio(),this.micro=!0):((c=(o=this._trtc)==null?void 0:o.stream)==null||c.muteAudio(),this.micro=!1),n(!0)}catch(l){n(!1)}})}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){var t,n,s,r;(t=this._trtc.client)==null||t.on("stream-added",this._handleStreamAdded),(n=this._trtc.client)==null||n.on("stream-subscribed",this._handleStreamSubscribed),(s=this._trtc.client)==null||s.on("audio-volume",o=>this.emit("userVolumes",o.result.map(({userId:c,audioVolume:l})=>({userId:c,audioVolume:l})))),(r=this._trtc.client)==null||r.on("error",o=>this.emit("error",o))}}class Ct extends tt{constructor(t){super();a(this,"type",se.RealseeBrowserChimeRTC);a(this,"joined",!1);a(this,"micro",!1);a(this,"voiceId","");a(this,"userId","");a(this,"logger");a(this,"deviceController");a(this,"meetingSession");a(this,"audioInput");a(this,"audioOutput");a(this,"deviceChangeObserver",{});a(this,"audioVideoObserver",{});a(this,"audioMixObserver");a(this,"_getVoiceSign",()=>{throw new Error("方法 getVoiceSign 未实现")});a(this,"_autoPlayConfirm");a(this,"$dom",document.createElement("div"));a(this,"$audio",document.createElement("audio"));a(this,"_initDom",()=>{this.$audio.id=`rs-rtc-${Te()}`,this.$dom.id=`rs-rtc-${Te()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom)});a(this,"initObservers",()=>{this.deviceChangeObserver={audioInputsChanged:t=>{this.logger.info(`audioInputsChanged ${typeof t}`),t==null||t.forEach(n=>{this.logger.info(`Device ID: ${n.deviceId} Microphone: ${n.label}`)})},audioOutputsChanged:t=>{this.logger.info(`audioOutputsChanged ${typeof t}`),t==null||t.forEach(n=>{this.logger.info(`Device ID: ${n.deviceId} Speaker: ${n.label}`)})},audioInputMuteStateChanged:(t,n)=>{this.logger.info(`Device ${t.toString()} ${n?"is muted in hardware":"is not muted"}`)}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started")},audioVideoDidStop:t=>{this.logger.info(`Stopped with a session status code: ${t.statusCode()}`)},audioVideoDidStartConnecting:t=>{t&&this.logger.info("Attempting to reconnect")}},this.audioMixObserver={meetingAudioStreamBecameActive:t=>{if(this.$audio.paused){const n=()=>this.$audio.play().then(()=>{}).catch(s=>{if(m.error("播放远端流失败!",s),typeof this._autoPlayConfirm=="function"){const r=()=>n();this._autoPlayConfirm({onConfirm:r})}});n()}},meetingAudioStreamBecameInactive:t=>{}}});a(this,"_registerRtcEvent",()=>{var n,s,r,o,c,l;const t=((r=(s=(n=this.meetingSession)==null?void 0:n.configuration)==null?void 0:s.credentials)==null?void 0:r.attendeeId)||"";if(t){const h=new Map,u=()=>{const d=[];return h.forEach((g,w)=>{d.push({userId:g.userId,volume:g.muted||g.signalStrength===0||!g.volume?0:g.volume})}),d};(o=this.meetingSession)==null||o.audioVideo.realtimeSubscribeToAttendeeIdPresence((d,g,w)=>{var y;if(!g){h.delete(d),this.emit("userVolumes",u());return}(y=this.meetingSession)==null||y.audioVideo.realtimeSubscribeToVolumeIndicator(d,(p,_,I,N)=>{new Q.DefaultModality(p).base()===p&&(h.set(p,{userId:w||p,volume:_,muted:I,signalStrength:N}),this.emit("userVolumes",u()))})}),(c=this.meetingSession)==null||c.audioVideo.realtimeSubscribeToVolumeIndicator(t,(d,g,w,y)=>{new Q.DefaultModality(d).base()===d&&y!==null&&y!==1&&this.emit("weakNetwork")}),(l=this.meetingSession)==null||l.audioVideo.realtimeSubscribeToFatalError(d=>this.emit("error",d))}});this._getVoiceSign=t.getVoiceSign,this._autoPlayConfirm=t.autoPlayConfirm,this._initDom(),this.logger=new Q.ConsoleLogger("WebRTCLogger",t.logLevel||Q.LogLevel.INFO),this.deviceController=new Q.DefaultDeviceController(this.logger),this.initObservers()}async join(t){return new Promise(async(n,s)=>{var r,o;this.emit("joinWillStart");try{const{sdkAppId:c,userId:l,roomId:h,userSig:u}=await this._getVoiceSign({...t,roomId:t.roomId||0});this.userId=l;const{attendence:d,vendor_wrapper:g}=JSON.parse(decodeURIComponent(u)),w=new Q.MeetingSessionConfiguration({Meeting:g},{Attendee:{ExternalUserId:d.external_user_id,AttendeeId:d.attendee_id,JoinToken:d.join_token}});this.meetingSession=new Q.DefaultMeetingSession(w,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);const y={audioVideoDidStart:()=>{var p;(p=this.meetingSession)==null||p.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),n(!0)},audioVideoDidStop:()=>{this.joined=!1,n(!1)}};this.meetingSession.audioVideo.addObserver(y),this.audioMixObserver&&this.meetingSession.audioVideo.addAudioMixObserver(this.audioMixObserver),this.meetingSession.audioVideo.setDeviceLabelTrigger(async()=>await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}));try{const p=await this.meetingSession.audioVideo.listAudioInputDevices();m.info("audioInputDevices ===>",p);const _=((r=p[0])==null?void 0:r.deviceId)||"default";await this.meetingSession.audioVideo.startAudioInput(_)}catch(p){m.error(`设置语音输入设备失败:${p.message}`)}try{const p=await this.meetingSession.audioVideo.listAudioOutputDevices();m.info("audioOutputDevices ===>",p);const _=((o=p[0])==null?void 0:o.deviceId)||"default";await this.meetingSession.audioVideo.chooseAudioOutput(_)}catch(p){m.error(`设置语音输出设备失败:${p.message}`)}this.meetingSession.audioVideo.start()}catch(c){this.emit("error",c),this.logger.error(c.message),n(!1)}})}quit(){return this.joined?new Promise((t,n)=>{var r,o;this.joined=!1;const s={audioVideoDidStop:async c=>{var h;const l=c.statusCode();(h=this.meetingSession)==null||h.deviceController.destroy(),l===Q.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),t(!0)):(this.logger.info(`Stopped with a session status code: ${l}`),t(!0))}};(r=this.meetingSession)==null||r.audioVideo.addObserver(s),(o=this.meetingSession)==null||o.audioVideo.stop()}):Promise.resolve(!0)}async detectMicro(){return new Promise(t=>{const n={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(n).then(()=>t(!0)).catch(()=>t(!1))}catch(s){this.logger.error(s.message),t(!1)}})}async toggleMicro(t){var s,r,o;t?(s=this.meetingSession)==null||s.audioVideo.realtimeUnmuteLocalAudio():(r=this.meetingSession)==null||r.audioVideo.realtimeMuteLocalAudio();const n=(o=this.meetingSession)==null?void 0:o.audioVideo.realtimeIsLocalAudioMuted();return n!==void 0?t!==n:!1}shock(){throw new Error("Method not implemented.")}}var le=(i=>(i[i.Success=0]="Success",i[i.Failure=1]="Failure",i[i.ReJoin=2]="ReJoin",i[i.NoMicroPermission=3]="NoMicroPermission",i[i.Unknown=500]="Unknown",i))(le||{});class gi extends tt{constructor({jsBridge:t,getVoiceSign:n}){super();a(this,"type",se.RealseeVRWebViewRTC);a(this,"joined",!1);a(this,"micro",!1);a(this,"voiceId","");a(this,"_joinOptions",null);a(this,"options");a(this,"handleUserVolumes",t=>{this.emit("userVolumes",t)});a(this,"handleWeakNetwork",t=>{t&&this.emit("weakNetwork")});a(this,"join",async t=>{this._joinOptions=t,this.emit("joinWillStart");const{sdkAppId:n,userId:s,userSig:r}=await this.getVoiceSignOrEmitError(t);return!n||!s||!r?!1:(this.type=t.type,this.jsBridge.webViewType==="WxMiniProgramWebView"?this.handleWxMiniProgramWebViewJoin({sdkAppId:n,userId:s,userSig:r,voiceId:t.voiceId}):this.handleAppWebViewJoin({sdkAppId:n,userId:s,userSig:r,voiceId:t.voiceId}))});a(this,"reJoin",async()=>this._joinOptions?this.join({voiceId:this._joinOptions.voiceId,userId:this._joinOptions.userId,roomId:this._joinOptions.roomId,type:this._joinOptions.type}):(this.emitErrorAndSetJoinedFalse("重连失败:未找到加入房间参数。"),!1));a(this,"getVoiceSignOrEmitError",async t=>{try{return await this.options.getVoiceSign(t)}catch(n){return this.emitErrorAndSetJoinedFalse("加入房间失败:rtc 签名请求异常"),{}}});a(this,"handleWxMiniProgramWebViewJoin",async t=>{const[n,s]=await this.joinRoomOrEmitError(t);return s?!1:this.handleJoinResult(n)});a(this,"handleAppWebViewJoin",t=>new Promise(n=>{this.off("inner.rtc.success");const s=r=>{this.off("inner.rtc.fail",s),this.off("inner.rtc.success",s),n(this.handleJoinResult(r))};this.once("inner.rtc.fail",s),this.once("inner.rtc.success",s);try{const{sdkAppId:r,userId:o,userSig:c,voiceId:l}=t;this.jsBridge.callAndListen(`live/join?sdkAppID=${r}&userID=${o}&roomID=${l}&userSig=${c}`,h=>{h===!0?this.emit("inner.rtc.success",h):typeof h=="object"?h.code===le.Success||h.code===le.ReJoin?this.emit("inner.rtc.success",h):this.emit("inner.rtc.fail",h):this.emit("inner.rtc.fail",h)})}catch(r){n(this.handleJoinResult({message:r.message,code:le.Unknown}))}}));a(this,"joinRoomOrEmitError",async({sdkAppId:t,userId:n,voiceId:s,userSig:r})=>{try{return await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${t}&userID=${n}&roomID=${Number(s)}&userSig=${r}`)}catch(o){return this.emitErrorAndSetJoinedFalse("加入房间失败:"+o.message),[null,o]}});a(this,"handleJoinResult",t=>{switch(!0){case t===!0:case(typeof t=="object"&&t.code===le.Success):case(typeof t=="object"&&t.code===le.ReJoin):{this.emit("joined"),this.joined=!0;break}default:{this.joined=!1;const n=typeof t=="object"?t.message:"加入房间失败:未知异常。";this.emit("error",new Error(n,{cause:t}))}}return this.joined});a(this,"emitErrorAndSetJoinedFalse",t=>{this.emit("error",new Error(t)),this.joined=!1});a(this,"quit",async()=>{const[t,n]=await this.jsBridge.callAndBackfeed("live/quit");return t===null&&this.emit("error",n||new Error("退出房间失败:未知异常。")),this.joined=!1,!!t});a(this,"detectMicro",async()=>{const[t,n]=await this.jsBridge.detectMicro();return t===null?(this.emit("error",n||new Error("麦克风监测异常!")),!1):t});a(this,"toggleMicro",async t=>{const[n,s]=await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${t?1:0}`);return n===null?(this.emit("error",s||new Error("麦克风监测异常!")),!1):(this.micro=n,n)});a(this,"shock",()=>{this.jsBridge.shock(1)});this.options={jsBridge:t,getVoiceSign:n},this.jsBridge.webViewType!=="WxMiniProgramWebView"&&this.jsBridge.callAndListen("live/userVolumes",this.handleUserVolumes),this.jsBridge.callAndListen("live/weakNetwork",this.handleWeakNetwork),this.on("inner.rtc.fail",this.handleJoinResult)}get jsBridge(){return this.options.jsBridge}}var $=(i=>(i.SelfUserInfo="SELF_USER_INFO",i.RoomInfo="ROOM_INFO",i.RTCInfo="RTC_INFO",i.UserList="USER_LIST",i.BuiltinMsg="BUILTIN_MSG",i.CustomEvent="CUSTOM_EVENT",i.KeyframeSync="KEYFRAME_SYNC",i.UserKickOut="USER_KICK_OUT",i))($||{}),F=(i=>(i.UserChange="user_change",i.RoomChange="room_change",i))(F||{}),K=(i=>(i.UserMicroStatus="change_micro_status",i.UserMicroStatusSync="sync_micro_status",i.UserPermission="change_permission",i.UserStatus="change_status",i.UserInfo="change_info",i.RoomClose="close",i))(K||{}),te=(i=>(i.OPEN="OPEN",i.CLOSE="CLOSE",i))(te||{});function yn(i){try{const e=JSON.parse(i),t={code:e.code,message:e.message,command:e.command,roomCode:e.room_code,appID:e.app_id,requestId:e.request_id,frontRequestId:e.front_request_id,triggerUserID:e.trigger_user_id,data:e.data||{}},n=Object.keys(t).filter(s=>t[s]===void 0);return n.length>0&&console.warn(`推送数据格式异常:${n.join(" ")} 值不存在!`),t}catch(e){return!1}}var V=(i=>(i[i.NOTINITIALIZED=-1]="NOTINITIALIZED",i[i.CONNECTING=0]="CONNECTING",i[i.OPEN=1]="OPEN",i[i.CLOSED=3]="CLOSED",i))(V||{}),pi=(i=>(i[i.Normal=0]="Normal",i[i.Removed=1]="Removed",i[i.Replaced=2]="Replaced",i))(pi||{}),_i=(i=>(i.WAIT_ENTER="WAIT_ENTER",i.ONLINE="ONLINE",i.LEAVE="LEAVE",i.KICK_OUT="KICK_OUT",i.BE_REPLACE="BE_REPLACE",i.EXCEPTION="EXCEPTION",i))(_i||{}),Ge=(i=>(i[i.NOTINITIALIZED=-1]="NOTINITIALIZED",i[i.CONNECTING=0]="CONNECTING",i[i.OPEN=1]="OPEN",i[i.CLOSING=2]="CLOSING",i[i.CLOSED=3]="CLOSED",i))(Ge||{}),mi=(i=>(i.Error="Error",i.Close="Close",i.MicroAuth="MicroAuth",i.DuplicateConnect="DuplicateConnect",i.IllegalURL="IllegalURL",i.Unknown="Unknown",i.IllegalArgs="IllegalArgs",i))(mi||{}),wi=(i=>(i.Err_1000="CLOSE_NORMAL",i.Err_1001="CLOSE_GOING_AWAY",i.Err_1002="CLOSE_PROTOCOL_ERROR",i.Err_1003="CLOSE_UNSUPPORTED",i.Err_1006="CLOSE_ABNORMAL",i.Err_1007="Unsupported Data",i.Err_1008="Policy Violation",i.Err_1009="CLOSE_TOO_LARGE",i.Err_unknown="unknown",i))(wi||{});function yi(i){switch(i){case 1e3:return"CLOSE_NORMAL";case 1001:return"CLOSE_GOING_AWAY";case 1002:return"CLOSE_PROTOCOL_ERROR";case 1003:return"CLOSE_UNSUPPORTED";case 1006:return"CLOSE_ABNORMAL";case 1007:return"Unsupported Data";case 1008:return"Policy Violation";case 1009:return"CLOSE_TOO_LARGE"}return"unknown"}function bn(i,e={}){var c;const t=new URL(i,"http://localhost"),n=new URLSearchParams(t.search);for(const[l,h]of Object.entries(e))n.set(l,String(h));const s=n.toString(),r=i.split("#")[0].split("?")[0],o=(c=t.hash)!=null?c:"";return`${r}${s?`?${s}`:""}${o}`}const bi=(()=>{var t;const i=typeof process!="undefined"&&((t=process.versions)==null?void 0:t.node)!=null;return typeof window!="undefined"&&"Deno"in window||i||typeof window=="undefined"})(),ge=bi?"":navigator.userAgent,Sn=/android/i.test(ge),Cn=/iPhone|iPad|iPod|iPadOS/i.test(ge)||!bi&&/Macintosh/.test(ge)&&"ontouchend"in globalThis,Kt=/MicroMessenger/i.test(ge)&&/miniProgram/i.test(ge),Jt=/realsee/i.test(ge);function qe(i){return Object.prototype.toString.call(i)==="[object Object]"}function it(i,e){return i===e?!0:i==null||e==null||typeof i!=typeof e?!1:Number.isNaN(i)&&Number.isNaN(e)}function En(i,e){if(i===e)return!0;if(i==null||e==null)return!1;const t=Object.keys(i),n=Object.keys(e);return t.length!==n.length?!1:t.every(s=>it(i[s],e[s]))}function kn(i,e){return i===e?!0:i==null||e==null||i.length!==e.length?!1:i.every((t,n)=>it(t,e[n]))}function vn(i,e){return it(i,e)?!0:qe(i)&&qe(e)?En(i,e):Array.isArray(i)&&Array.isArray(e)?kn(i,e):!1}function Lt(i,e){return it(i,e)?!0:qe(i)&&qe(e)?On(i,e):Array.isArray(i)&&Array.isArray(e)?In(i,e):!1}function In(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(!Lt(i[t],e[t]))return!1;return!0}function On(i,e){if(i===e)return!0;if(i==null||e==null)return!1;const t=Object.keys(i),n=Object.keys(e);return t.length!==n.length?!1:t.every(s=>Lt(i[s],e[s]))}function Rn(i,e,t={deep:!1}){return t.deep?Lt(i,e):vn(i,e)}class An extends Ae{constructor(t){super();a(this,"_realWebSocket");a(this,"_url");a(this,"_protocols");a(this,"_readyState",Ge.NOTINITIALIZED);a(this,"_options",{timeout:1e4,shouldReconnect:(t,n)=>{if(!(t.code===1008||t.code===1011))return[0,1e3,2e3][n.attempts%3]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1});a(this,"_connectTimeout");a(this,"_attempts",0);a(this,"_reconnects",-1);a(this,"_reconnectWhenOnlineAgain",!1);a(this,"_explicitlyClosed",!1);a(this,"_pendingReconnect");a(this,"_connectivityEventsAttached",!1);a(this,"_heathCheckTimer");a(this,"_healthCheck",async()=>{if(this._realWebSocket){const t=this._realWebSocket.readyState;t!==this._readyState&&(this._readyState=t,this._readyState===Ge.CLOSING&&this.emit("closing"))}await new Promise(t=>setTimeout(t,2e3)),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)});a(this,"_clearConnectTimeoutIfNeed",()=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0)});a(this,"_clearHeathCheckIfNeed",()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0)});a(this,"_startHealthCheck",()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck)});a(this,"_stopHealthCheck",()=>{this._clearHeathCheckIfNeed()});a(this,"_clearPendingReconnectIfNeeded",()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0)});a(this,"_online",t=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(t))});a(this,"_offline",()=>{var t;this._reconnectWhenOnlineAgain=!0,(t=this._realWebSocket)==null||t.close(1e3,"offline")});a(this,"_detachConnectivityEvents",()=>{this._connectivityEventsAttached&&(globalThis==null||globalThis.removeEventListener("online",this._online),globalThis==null||globalThis.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1)});a(this,"_attachConnectivityEvents",()=>{this._connectivityEventsAttached||(globalThis==null||globalThis.addEventListener("online",this._online),globalThis==null||globalThis.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0)});a(this,"send",t=>{var n,s,r;((n=this._realWebSocket)==null?void 0:n.readyState)===((s=this._realWebSocket)==null?void 0:s.OPEN)&&((r=this._realWebSocket)==null||r.send(t))});a(this,"close",(t,n)=>{var s;return typeof t!="number"&&(n=t,t=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),(s=this._realWebSocket)==null?void 0:s.close(t,n)});a(this,"open",t=>{var n,s;t&&(this._url=t),((n=this._realWebSocket)==null?void 0:n.readyState)!==WebSocket.OPEN&&((s=this._realWebSocket)==null?void 0:s.readyState)!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket())});a(this,"_createWebSocket",()=>{var s;const t=typeof this._url=="string"?this._url:(s=this._url)==null?void 0:s.call(this,this);if(!t)return;this._clearConnectTimeoutIfNeed(),this._clearPendingReconnectIfNeeded(),this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(t,this._protocols||void 0),this._attempts++,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));const n=()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("timeout",{detail:{attempts:this._attempts,reconnects:this._reconnects}}))};this._connectTimeout=setTimeout(n,this._options.timeout),this._dispatchWebSocketEvent(),this._options.ignoreConnectivityEvents||this._attachConnectivityEvents()});a(this,"_removeWebSocketEvent",()=>{var t,n,s,r;(t=this._realWebSocket)==null||t.removeEventListener("open",this._webSocketOpenHandler),(n=this._realWebSocket)==null||n.removeEventListener("close",this._webSocketCloseHandler),(s=this._realWebSocket)==null||s.removeEventListener("error",this._webSocketErrorHandler),(r=this._realWebSocket)==null||r.removeEventListener("message",this._webSocketMessageHandler)});a(this,"_dispatchWebSocketEvent",()=>{var t,n,s,r;(t=this._realWebSocket)==null||t.addEventListener("open",this._webSocketOpenHandler),(n=this._realWebSocket)==null||n.addEventListener("close",this._webSocketCloseHandler),(s=this._realWebSocket)==null||s.addEventListener("error",this._webSocketErrorHandler),(r=this._realWebSocket)==null||r.addEventListener("message",this._webSocketMessageHandler)});a(this,"_webSocketOpenHandler",t=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);const n=++this._reconnects,s=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(t,{detail:{reconnects:n,attempts:s}}))});a(this,"_webSocketCloseHandler",t=>(this._reconnect(t),this._stopHealthCheck(),this.emit("close",t)));a(this,"_webSocketErrorHandler",t=>this.emit("error",new CustomEvent("error",{detail:{error:t}})));a(this,"_webSocketMessageHandler",t=>this.emit("message",t));t&&this.setOptions(t),this._startHealthCheck()}get attempts(){return this._attempts}setOptions(t){if(!t)return;this._url=t.url,this._protocols=t.protocols;const n=Object.assign(this._options,t.robustOptions||{});if(typeof(n==null?void 0:n.timeout)!="number")throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if(typeof(n==null?void 0:n.shouldReconnect)!="function")throw new Error("shouldReconnect must be a function that returns the number of milliseconds to wait for a reconnect attempt, or null or undefined to not reconnect.");this._options=n,this._options.automaticOpen&&this._createWebSocket()}_reconnect(t){var o,c,l;if(!this._options.should1000Reconnect&&t.code===1e3||this._explicitlyClosed){this._attempts=0;return}if(this._connectivityEventsAttached&&((o=globalThis==null?void 0:globalThis.navigator)==null?void 0:o.onLine)===!1){this._reconnectWhenOnlineAgain=!0;return}const r=(l=(c=this._options).shouldReconnect)==null?void 0:l.call(c,t,this);typeof r=="number"?(m.debug(`RobustWebSocket: Reconnecting in ${r}ms...`),this._pendingReconnect=setTimeout(this._createWebSocket,r)):m.debug("RobustWebSocket: No reconnection will be attempted.")}}class Tn extends Ae{constructor(){super();a(this,"_ws",new An({url:"",robustOptions:{should1000Reconnect:!0,ignoreConnectivityEvents:!0}}));a(this,"_state",V.NOTINITIALIZED);a(this,"_addWebSocketEventListeners",()=>{this._ws.on("close",this._handleCloseEvent),this._ws.on("closing",this._handleClosingEvent),this._ws.on("connecting",this._handleConnectingEvent),this._ws.on("error",this._handleErrorEvent),this._ws.on("message",this._handleMessageEvent),this._ws.on("open",this._handleOpenEvent),this._ws.on("timeout",this._handleTimeoutEvent)});a(this,"_removeWebSocketEventListeners",()=>{this._ws.off("close",this._handleCloseEvent),this._ws.off("closing",this._handleClosingEvent),this._ws.off("connecting",this._handleConnectingEvent),this._ws.off("error",this._handleErrorEvent),this._ws.off("message",this._handleMessageEvent),this._ws.off("open",this._handleOpenEvent),this._ws.off("timeout",this._handleTimeoutEvent)});a(this,"_handleCloseEvent",t=>{m.info(`live room closed bacause of ${t.code}-${t.reason||yi(t.code)}`),this.state=V.CLOSED});a(this,"_handleClosingEvent",()=>{var t;m.info("live room is closing, onLine:",(t=globalThis==null?void 0:globalThis.navigator)==null?void 0:t.onLine),this.state=V.CLOSED});a(this,"_handleConnectingEvent",t=>{m.info("live room is connecting"),this.state=V.CONNECTING,t.detail.reconnects>0&&this.emit("reconnecting",t.detail)});a(this,"_handleErrorEvent",t=>{m.error("live room error",t),this.state=V.CLOSED});a(this,"_handleMessageEvent",t=>{let n=(()=>{try{return JSON.parse(t.data)}catch(s){return t.data}})();this.emit("message",n)});a(this,"_handleOpenEvent",t=>{m.info("live room open",t.detail),this.state=V.OPEN,t.detail.reconnects>0&&this.emit("reconnected",t.detail)});a(this,"_handleTimeoutEvent",t=>{m.error("live room connect timeout!",t.detail),this.state=V.CLOSED});a(this,"dispose",async()=>(this._removeWebSocketEventListeners(),await this.close("live room close by controller disposed!")));a(this,"open",t=>this._ws.open(t));a(this,"close",(t,n)=>new Promise(s=>{this._ws.once("close",()=>s(!0)),this._ws.close(t,n)}));a(this,"sendMessage",(t="")=>{if(t==null)throw new Error("live message is empty!");if(this.state!==V.OPEN)throw new Error("live has not yet been initialized!");return this._ws.send(JSON.stringify(t))});a(this,"readyClose",()=>{this._ws&&(this._ws._explicitlyClosed=!0)});this._addWebSocketEventListeners()}set state(t){const n=JSON.parse(JSON.stringify(this._state));this._state=t,this.emit("stateChange",this.state,n)}get state(){return this._state}}const J=()=>new Map,Et=i=>{const e=J();return i.forEach((t,n)=>{e.set(n,t)}),e},be=(i,e,t)=>{let n=i.get(e);return n===void 0&&i.set(e,n=t()),n},Ln=(i,e)=>{const t=[];for(const[n,s]of i)t.push(e(s,n));return t},Mn=(i,e)=>{for(const[t,n]of i)if(e(n,t))return!0;return!1},pe=()=>new Set,ut=i=>i[i.length-1],_e=Array.from,Dn=Array.isArray;class Nn{constructor(){this._observers=J()}on(e,t){return be(this._observers,e,pe).add(t),t}once(e,t){const n=(...s)=>{this.off(e,n),t(...s)};this.on(e,n)}off(e,t){const n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return _e((this._observers.get(e)||J()).values()).forEach(n=>n(...t))}destroy(){this._observers=J()}}const ae=Math.floor,We=Math.abs,Si=(i,e)=>i<e?i:e,Se=(i,e)=>i>e?i:e,Vn=i=>i!==0?i<0:1/i<0,Gt=1,qt=2,dt=4,ft=8,Un=32,Ci=64,He=128,jn=31,Ht=63,Oe=127,Bn=2147483647,$n=Number.isInteger||(i=>typeof i=="number"&&isFinite(i)&&ae(i)===i),xn=i=>i.toLowerCase(),Fn=/^\s*/g,Wn=i=>i.replace(Fn,""),Pn=/([A-Z])/g,zt=(i,e)=>Wn(i.replace(Pn,t=>`${e}${xn(t)}`)),Kn=i=>{const e=unescape(encodeURIComponent(i)),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.codePointAt(s);return n},Le=typeof TextEncoder!="undefined"?new TextEncoder:null,Jn=i=>Le.encode(i),Gn=Le?Jn:Kn;let gt=typeof TextDecoder=="undefined"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});gt&>.decode(new Uint8Array).length===1&&(gt=null);class je{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Mt=()=>new je,qn=i=>{let e=i.cpos;for(let t=0;t<i.bufs.length;t++)e+=i.bufs[t].length;return e},z=i=>{const e=new Uint8Array(qn(i));let t=0;for(let n=0;n<i.bufs.length;n++){const s=i.bufs[n];e.set(s,t),t+=s.length}return e.set(new Uint8Array(i.cbuf.buffer,0,i.cpos),t),e},Hn=(i,e)=>{const t=i.cbuf.length;t-i.cpos<e&&(i.bufs.push(new Uint8Array(i.cbuf.buffer,0,i.cpos)),i.cbuf=new Uint8Array(Se(t,e)*2),i.cpos=0)},T=(i,e)=>{const t=i.cbuf.length;i.cpos===t&&(i.bufs.push(i.cbuf),i.cbuf=new Uint8Array(t*2),i.cpos=0),i.cbuf[i.cpos++]=e},kt=T,C=(i,e)=>{for(;e>Oe;)T(i,He|Oe&e),e=ae(e/128);T(i,Oe&e)},Dt=(i,e)=>{const t=Vn(e);for(t&&(e=-e),T(i,(e>Ht?He:0)|(t?Ci:0)|Ht&e),e=ae(e/64);e>0;)T(i,(e>Oe?He:0)|Oe&e),e=ae(e/128)},vt=new Uint8Array(3e4),zn=vt.length/3,Yn=(i,e)=>{if(e.length<zn){const t=Le.encodeInto(e,vt).written||0;C(i,t);for(let n=0;n<t;n++)T(i,vt[n])}else x(i,Gn(e))},Xn=(i,e)=>{const t=unescape(encodeURIComponent(e)),n=t.length;C(i,n);for(let s=0;s<n;s++)T(i,t.codePointAt(s))},fe=Le&&Le.encodeInto?Yn:Xn,Nt=(i,e)=>{const t=i.cbuf.length,n=i.cpos,s=Si(t-n,e.length),r=e.length-s;i.cbuf.set(e.subarray(0,s),n),i.cpos+=s,r>0&&(i.bufs.push(i.cbuf),i.cbuf=new Uint8Array(Se(t*2,r)),i.cbuf.set(e.subarray(s)),i.cpos=r)},x=(i,e)=>{C(i,e.byteLength),Nt(i,e)},Vt=(i,e)=>{Hn(i,e);const t=new DataView(i.cbuf.buffer,i.cpos,e);return i.cpos+=e,t},Zn=(i,e)=>Vt(i,4).setFloat32(0,e,!1),Qn=(i,e)=>Vt(i,8).setFloat64(0,e,!1),es=(i,e)=>Vt(i,8).setBigInt64(0,e,!1),Yt=new DataView(new ArrayBuffer(4)),ts=i=>(Yt.setFloat32(0,i),Yt.getFloat32(0)===i),Me=(i,e)=>{switch(typeof e){case"string":T(i,119),fe(i,e);break;case"number":$n(e)&&We(e)<=Bn?(T(i,125),Dt(i,e)):ts(e)?(T(i,124),Zn(i,e)):(T(i,123),Qn(i,e));break;case"bigint":T(i,122),es(i,e);break;case"object":if(e===null)T(i,126);else if(Dn(e)){T(i,117),C(i,e.length);for(let t=0;t<e.length;t++)Me(i,e[t])}else if(e instanceof Uint8Array)T(i,116),x(i,e);else{T(i,118);const t=Object.keys(e);C(i,t.length);for(let n=0;n<t.length;n++){const s=t[n];fe(i,s),Me(i,e[s])}}break;case"boolean":T(i,e?120:121);break;default:T(i,127)}};class Xt extends je{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&C(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Zt=i=>{i.count>0&&(Dt(i.encoder,i.count===1?i.s:-i.s),i.count>1&&C(i.encoder,i.count-2))};class Pe{constructor(){this.encoder=new je,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Zt(this),this.count=1,this.s=e)}toUint8Array(){return Zt(this),z(this.encoder)}}const Qt=i=>{if(i.count>0){const e=i.diff*2+(i.count===1?0:1);Dt(i.encoder,e),i.count>1&&C(i.encoder,i.count-2)}};class pt{constructor(){this.encoder=new je,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Qt(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Qt(this),z(this.encoder)}}class is{constructor(){this.sarr=[],this.s="",this.lensE=new Pe}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new je;return this.sarr.push(this.s),this.s="",fe(e,this.sarr.join("")),Nt(e,this.lensE.toUint8Array()),z(e)}}const me=i=>new Error(i),G=()=>{throw me("Method unimplemented")},he=()=>{throw me("Unexpected case")},ns=crypto.getRandomValues.bind(crypto),Ei=()=>ns(new Uint32Array(1))[0],ss="10000000-1000-4000-8000"+-1e11,rs=()=>ss.replace(/[018]/g,i=>(i^Ei()&15>>i/4).toString(16)),ei=i=>new Promise(i);Promise.all.bind(Promise);const ti=i=>i===void 0?null:i;class os{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}}let ki=new os,cs=!0;try{typeof localStorage!="undefined"&&localStorage&&(ki=localStorage,cs=!1)}catch(i){}const ls=ki,as=Object.assign,hs=Object.keys,us=(i,e)=>{for(const t in i)e(i[t],t)},ii=i=>hs(i).length,ds=i=>{for(const e in i)return!1;return!0},fs=(i,e)=>{for(const t in i)if(!e(i[t],t))return!1;return!0},gs=(i,e)=>Object.prototype.hasOwnProperty.call(i,e),ps=(i,e)=>i===e||ii(i)===ii(e)&&fs(i,(t,n)=>(t!==void 0||gs(e,n))&&e[n]===t),_s=Object.freeze,vi=i=>{for(const e in i){const t=i[e];(typeof t=="object"||typeof t=="function")&&vi(i[e])}return _s(i)},Ut=(i,e,t=0)=>{try{for(;t<i.length;t++)i[t](...e)}finally{t<i.length&&Ut(i,e,t+1)}},ms=(i,e)=>e.includes(i),De=typeof process!="undefined"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process!="undefined"?process:0)==="[object process]";let P;const ws=()=>{if(P===void 0)if(De){P=J();const i=process.argv;let e=null;for(let t=0;t<i.length;t++){const n=i[t];n[0]==="-"?(e!==null&&P.set(e,""),e=n):e!==null&&(P.set(e,n),e=null)}e!==null&&P.set(e,"")}else typeof location=="object"?(P=J(),(location.search||"?").slice(1).split("&").forEach(i=>{if(i.length!==0){const[e,t]=i.split("=");P.set(`--${zt(e,"-")}`,t),P.set(`-${zt(e,"-")}`,t)}})):P=J();return P},It=i=>ws().has(i),ze=i=>ti(De?process.env[i.toUpperCase().replaceAll("-","_")]:ls.getItem(i)),Ii=i=>It("--"+i)||ze(i)!==null;Ii("production");const ys=De&&ms(process.env.FORCE_COLOR,["true","1","2"]),bs=ys||!It("--no-colors")&&!Ii("no-color")&&(!De||process.stdout.isTTY)&&(!De||It("--color")||ze("COLORTERM")!==null||(ze("TERM")||"").includes("color"));class Ss{constructor(e,t){this.left=e,this.right=t}}const H=(i,e)=>new Ss(i,e);typeof DOMParser!="undefined"&&new DOMParser;const Cs=i=>Ln(i,(e,t)=>`${t}:${e};`).join(""),Z=Symbol,Oi=Z(),Ri=Z(),Es=Z(),ks=Z(),vs=Z(),Ai=Z(),Is=Z(),jt=Z(),Os=Z(),Rs=i=>{var s;i.length===1&&((s=i[0])==null?void 0:s.constructor)===Function&&(i=i[0]());const e=[],t=[];let n=0;for(;n<i.length;n++){const r=i[n];if(r===void 0)break;if(r.constructor===String||r.constructor===Number)e.push(r);else if(r.constructor===Object)break}for(n>0&&t.push(e.join(""));n<i.length;n++){const r=i[n];r instanceof Symbol||t.push(r)}return t},As={[Oi]:H("font-weight","bold"),[Ri]:H("font-weight","normal"),[Es]:H("color","blue"),[vs]:H("color","green"),[ks]:H("color","grey"),[Ai]:H("color","red"),[Is]:H("color","purple"),[jt]:H("color","orange"),[Os]:H("color","black")},Ts=i=>{var o;i.length===1&&((o=i[0])==null?void 0:o.constructor)===Function&&(i=i[0]());const e=[],t=[],n=J();let s=[],r=0;for(;r<i.length;r++){const c=i[r],l=As[c];if(l!==void 0)n.set(l.left,l.right);else{if(c===void 0)break;if(c.constructor===String||c.constructor===Number){const h=Cs(n);r>0||h.length>0?(e.push("%c"+c),t.push(h)):e.push(c)}else break}}for(r>0&&(s=t,s.unshift(e.join("")));r<i.length;r++){const c=i[r];c instanceof Symbol||s.push(c)}return s},Ti=bs?Ts:Rs,Ls=(...i)=>{console.log(...Ti(i)),Li.forEach(e=>e.print(i))},Ms=(...i)=>{console.warn(...Ti(i)),i.unshift(jt),Li.forEach(e=>e.print(i))},Li=pe(),Mi=i=>({[Symbol.iterator](){return this},next:i}),Ds=(i,e)=>Mi(()=>{let t;do t=i.next();while(!t.done&&!e(t.value));return t}),_t=(i,e)=>Mi(()=>{const{done:t,value:n}=i.next();return{done:t,value:t?void 0:e(n)}});class Ns{constructor(e,t){this.clock=e,this.len=t}}class Vs{constructor(){this.clients=new Map}}const Di=(i,e,t)=>e.clients.forEach((n,s)=>{const r=i.doc.store.clients.get(s);for(let o=0;o<n.length;o++){const c=n[o];xi(i,r,c.clock,c.len,t)}}),Us=(i,e)=>{let t=0,n=i.length-1;for(;t<=n;){const s=ae((t+n)/2),r=i[s],o=r.clock;if(o<=e){if(e<o+r.len)return s;t=s+1}else n=s-1}return null},Ni=(i,e)=>{const t=i.clients.get(e.client);return t!==void 0&&Us(t,e.clock)!==null},Vi=i=>{i.clients.forEach(e=>{e.sort((s,r)=>s.clock-r.clock);let t,n;for(t=1,n=1;t<e.length;t++){const s=e[n-1],r=e[t];s.clock+s.len>=r.clock?s.len=Se(s.len,r.clock+r.len-s.clock):(n<t&&(e[n]=r),n++)}e.length=n})},Ui=(i,e,t,n)=>{be(i.clients,e,()=>[]).push(new Ns(t,n))},js=(i,e)=>{C(i.restEncoder,e.clients.size),_e(e.clients.entries()).sort((t,n)=>n[0]-t[0]).forEach(([t,n])=>{i.resetDsCurVal(),C(i.restEncoder,t);const s=n.length;C(i.restEncoder,s);for(let r=0;r<s;r++){const o=n[r];i.writeDsClock(o.clock),i.writeDsLen(o.len)}})},ji=Ei;class Ce extends Nn{constructor({guid:e=rs(),collectionid:t=null,gc:n=!0,gcFilter:s=()=>!0,meta:r=null,autoLoad:o=!1,shouldLoad:c=!0}={}){super(),this.gc=n,this.gcFilter=s,this.clientID=ji(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new qs,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=c,this.autoLoad=o,this.meta=r,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=ei(h=>{this.on("load",()=>{this.isLoaded=!0,h(this)})});const l=()=>ei(h=>{const u=d=>{(d===void 0||d===!0)&&(this.off("sync",u),h())};this.on("sync",u)});this.on("sync",h=>{h===!1&&this.isSynced&&(this.whenSynced=l()),this.isSynced=h===void 0||h===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const e=this._item;e!==null&&!this.shouldLoad&&k(e.parent.doc,t=>{t.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(_e(this.subdocs).map(e=>e.guid))}transact(e,t=null){return k(this,e,t)}get(e,t=D){const n=be(this.share,e,()=>{const r=new t;return r._integrate(this,null),r}),s=n.constructor;if(t!==D&&s!==t)if(s===D){const r=new t;r._map=n._map,n._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=r}),r._start=n._start;for(let o=r._start;o!==null;o=o.right)o.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return n}getArray(e=""){return this.get(e,Re)}getText(e=""){return this.get(e,Qe)}getMap(e=""){return this.get(e,Ze)}getXmlElement(e=""){return this.get(e,Ue)}getXmlFragment(e=""){return this.get(e,we)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,_e(this.subdocs).forEach(t=>t.destroy());const e=this._item;if(e!==null){this._item=null;const t=e.content;t.doc=new Ce({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,k(e.parent.doc,n=>{const s=t.doc;e.deleted||n.subdocsAdded.add(s),n.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Bs{constructor(){this.restEncoder=Mt()}toUint8Array(){return z(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){C(this.restEncoder,e)}writeDsLen(e){C(this.restEncoder,e)}}class $s extends Bs{writeLeftID(e){C(this.restEncoder,e.client),C(this.restEncoder,e.clock)}writeRightID(e){C(this.restEncoder,e.client),C(this.restEncoder,e.clock)}writeClient(e){C(this.restEncoder,e)}writeInfo(e){kt(this.restEncoder,e)}writeString(e){fe(this.restEncoder,e)}writeParentInfo(e){C(this.restEncoder,e?1:0)}writeTypeRef(e){C(this.restEncoder,e)}writeLen(e){C(this.restEncoder,e)}writeAny(e){Me(this.restEncoder,e)}writeBuf(e){x(this.restEncoder,e)}writeJSON(e){fe(this.restEncoder,JSON.stringify(e))}writeKey(e){fe(this.restEncoder,e)}}class xs{constructor(){this.restEncoder=Mt(),this.dsCurrVal=0}toUint8Array(){return z(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,C(this.restEncoder,t)}writeDsLen(e){e===0&&he(),C(this.restEncoder,e-1),this.dsCurrVal+=e}}class Fs extends xs{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new pt,this.clientEncoder=new Pe,this.leftClockEncoder=new pt,this.rightClockEncoder=new pt,this.infoEncoder=new Xt(kt),this.stringEncoder=new is,this.parentInfoEncoder=new Xt(kt),this.typeRefEncoder=new Pe,this.lenEncoder=new Pe}toUint8Array(){const e=Mt();return C(e,0),x(e,this.keyClockEncoder.toUint8Array()),x(e,this.clientEncoder.toUint8Array()),x(e,this.leftClockEncoder.toUint8Array()),x(e,this.rightClockEncoder.toUint8Array()),x(e,z(this.infoEncoder)),x(e,this.stringEncoder.toUint8Array()),x(e,z(this.parentInfoEncoder)),x(e,this.typeRefEncoder.toUint8Array()),x(e,this.lenEncoder.toUint8Array()),Nt(e,z(this.restEncoder)),z(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Me(this.restEncoder,e)}writeBuf(e){x(this.restEncoder,e)}writeJSON(e){Me(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}}const Ws=(i,e,t,n)=>{n=Se(n,e[0].id.clock);const s=Y(e,n);C(i.restEncoder,e.length-s),i.writeClient(t),C(i.restEncoder,n);const r=e[s];r.write(i,n-r.id.clock);for(let o=s+1;o<e.length;o++)e[o].write(i,0)},Ps=(i,e,t)=>{const n=new Map;t.forEach((s,r)=>{B(e,r)>s&&n.set(r,s)}),Bt(e).forEach((s,r)=>{t.has(r)||n.set(r,0)}),C(i.restEncoder,n.size),_e(n.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{Ws(i,e.clients.get(s),s,r)})},Ks=(i,e)=>Ps(i,e.doc.store,e.beforeState);class Js{constructor(){this.l=[]}}const ni=()=>new Js,si=(i,e)=>i.l.push(e),ri=(i,e)=>{const t=i.l,n=t.length;i.l=t.filter(s=>e!==s),n===i.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Bi=(i,e,t)=>Ut(i.l,[e,t]);class Ke{constructor(e,t){this.client=e,this.clock=t}}const $e=(i,e)=>i===e||i!==null&&e!==null&&i.client===e.client&&i.clock===e.clock,v=(i,e)=>new Ke(i,e),Gs=i=>{for(const[e,t]of i.doc.share.entries())if(t===i)return e;throw he()},ue=(i,e)=>e===void 0?!i.deleted:e.sv.has(i.id.client)&&(e.sv.get(i.id.client)||0)>i.id.clock&&!Ni(e.ds,i.id),Ot=(i,e)=>{const t=be(i.meta,Ot,pe),n=i.doc.store;t.has(e)||(e.sv.forEach((s,r)=>{s<B(n,r)&&re(i,v(r,s))}),Di(i,e.ds,s=>{}),t.add(e))};class qs{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Bt=i=>{const e=new Map;return i.clients.forEach((t,n)=>{const s=t[t.length-1];e.set(n,s.id.clock+s.length)}),e},B=(i,e)=>{const t=i.clients.get(e);if(t===void 0)return 0;const n=t[t.length-1];return n.id.clock+n.length},$i=(i,e)=>{let t=i.clients.get(e.id.client);if(t===void 0)t=[],i.clients.set(e.id.client,t);else{const n=t[t.length-1];if(n.id.clock+n.length!==e.id.clock)throw he()}t.push(e)},Y=(i,e)=>{let t=0,n=i.length-1,s=i[n],r=s.id.clock;if(r===e)return n;let o=ae(e/(r+s.length-1)*n);for(;t<=n;){if(s=i[o],r=s.id.clock,r<=e){if(e<r+s.length)return o;t=o+1}else n=o-1;o=ae((t+n)/2)}throw he()},Hs=(i,e)=>{const t=i.clients.get(e.client);return t[Y(t,e.clock)]},mt=Hs,Rt=(i,e,t)=>{const n=Y(e,t),s=e[n];return s.id.clock<t&&s instanceof U?(e.splice(n+1,0,rn(i,s,t-s.id.clock)),n+1):n},re=(i,e)=>{const t=i.doc.store.clients.get(e.client);return t[Rt(i,t,e.clock)]},oi=(i,e,t)=>{const n=e.clients.get(t.client),s=Y(n,t.clock),r=n[s];return t.clock!==r.id.clock+r.length-1&&r.constructor!==ie&&n.splice(s+1,0,rn(i,r,t.clock-r.id.clock+1)),r},zs=(i,e,t)=>{const n=i.clients.get(e.id.client);n[Y(n,e.id.clock)]=t},xi=(i,e,t,n,s)=>{if(n===0)return;const r=t+n;let o=Rt(i,e,t),c;do c=e[o++],r<c.id.clock+c.length&&Rt(i,e,r),s(c);while(o<e.length&&e[o].id.clock<r)};class Ys{constructor(e,t,n){this.doc=e,this.deleteSet=new Vs,this.beforeState=Bt(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const ci=(i,e)=>e.deleteSet.clients.size===0&&!Mn(e.afterState,(t,n)=>e.beforeState.get(n)!==t)?!1:(Vi(e.deleteSet),Ks(i,e),js(i,e.deleteSet),!0),li=(i,e,t)=>{const n=e._item;(n===null||n.id.clock<(i.beforeState.get(n.id.client)||0)&&!n.deleted)&&be(i.changed,e,pe).add(t)},Je=(i,e)=>{let t=i[e],n=i[e-1],s=e;for(;s>0;t=n,n=i[--s-1]){if(n.deleted===t.deleted&&n.constructor===t.constructor&&n.mergeWith(t)){t instanceof U&&t.parentSub!==null&&t.parent._map.get(t.parentSub)===t&&t.parent._map.set(t.parentSub,n);continue}break}const r=e-s;return r&&i.splice(e+1-r,r),r},Xs=(i,e,t)=>{for(const[n,s]of i.clients.entries()){const r=e.clients.get(n);for(let o=s.length-1;o>=0;o--){const c=s[o],l=c.clock+c.len;for(let h=Y(r,c.clock),u=r[h];h<r.length&&u.id.clock<l;u=r[++h]){const d=r[h];if(c.clock+c.len<=d.id.clock)break;d instanceof U&&d.deleted&&!d.keep&&t(d)&&d.gc(e,!1)}}}},Zs=(i,e)=>{i.clients.forEach((t,n)=>{const s=e.clients.get(n);for(let r=t.length-1;r>=0;r--){const o=t[r],c=Si(s.length-1,1+Y(s,o.clock+o.len-1));for(let l=c,h=s[l];l>0&&h.id.clock>=o.clock;h=s[l])l-=1+Je(s,l)}})},Fi=(i,e)=>{if(e<i.length){const t=i[e],n=t.doc,s=n.store,r=t.deleteSet,o=t._mergeStructs;try{Vi(r),t.afterState=Bt(t.doc.store),n.emit("beforeObserverCalls",[t,n]);const c=[];t.changed.forEach((l,h)=>c.push(()=>{(h._item===null||!h._item.deleted)&&h._callObserver(t,l)})),c.push(()=>{t.changedParentTypes.forEach((l,h)=>{h._dEH.l.length>0&&(h._item===null||!h._item.deleted)&&(l=l.filter(u=>u.target._item===null||!u.target._item.deleted),l.forEach(u=>{u.currentTarget=h,u._path=null}),l.sort((u,d)=>u.path.length-d.path.length),Bi(h._dEH,l,t))})}),c.push(()=>n.emit("afterTransaction",[t,n])),Ut(c,[]),t._needFormattingCleanup&&hr(t)}finally{n.gc&&Xs(r,s,n.gcFilter),Zs(r,s),t.afterState.forEach((u,d)=>{const g=t.beforeState.get(d)||0;if(g!==u){const w=s.clients.get(d),y=Se(Y(w,g),1);for(let p=w.length-1;p>=y;)p-=1+Je(w,p)}});for(let u=o.length-1;u>=0;u--){const{client:d,clock:g}=o[u].id,w=s.clients.get(d),y=Y(w,g);y+1<w.length&&Je(w,y+1)>1||y>0&&Je(w,y)}if(!t.local&&t.afterState.get(n.clientID)!==t.beforeState.get(n.clientID)&&(Ls(jt,Oi,"[yjs] ",Ri,Ai,"Changed the client-id because another client seems to be using it."),n.clientID=ji()),n.emit("afterTransactionCleanup",[t,n]),n._observers.has("update")){const u=new $s;ci(u,t)&&n.emit("update",[u.toUint8Array(),t.origin,n,t])}if(n._observers.has("updateV2")){const u=new Fs;ci(u,t)&&n.emit("updateV2",[u.toUint8Array(),t.origin,n,t])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:h}=t;(c.size>0||h.size>0||l.size>0)&&(c.forEach(u=>{u.clientID=n.clientID,u.collectionid==null&&(u.collectionid=n.collectionid),n.subdocs.add(u)}),h.forEach(u=>n.subdocs.delete(u)),n.emit("subdocs",[{loaded:l,added:c,removed:h},n,t]),h.forEach(u=>u.destroy())),i.length<=e+1?(n._transactionCleanups=[],n.emit("afterAllTransactions",[n,i])):Fi(i,e+1)}}},k=(i,e,t=null,n=!0)=>{const s=i._transactionCleanups;let r=!1,o=null;i._transaction===null&&(r=!0,i._transaction=new Ys(i,t,n),s.push(i._transaction),s.length===1&&i.emit("beforeAllTransactions",[i]),i.emit("beforeTransaction",[i._transaction,i]));try{o=e(i._transaction)}finally{if(r){const c=i._transaction===s[0];i._transaction=null,c&&Fi(s,0)}}return o},ai="You must not compute changes after the event-handler fired.";class nt{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Qs(this.currentTarget,this.target))}deletes(e){return Ni(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw me(ai);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach(s=>{if(s!==null){const r=t._map.get(s);let o,c;if(this.adds(r)){let l=r.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(r))if(l!==null&&this.deletes(l))o="delete",c=ut(l.content.getContent());else return;else l!==null&&this.deletes(l)?(o="update",c=ut(l.content.getContent())):(o="add",c=void 0)}else if(this.deletes(r))o="delete",c=ut(r.content.getContent());else return;e.set(s,{action:o,oldValue:c})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw me(ai);const t=this.target,n=pe(),s=pe(),r=[];if(e={added:n,deleted:s,delta:r,keys:this.keys},this.transaction.changed.get(t).has(null)){let c=null;const l=()=>{c&&r.push(c)};for(let h=t._start;h!==null;h=h.right)h.deleted?this.deletes(h)&&!this.adds(h)&&((c===null||c.delete===void 0)&&(l(),c={delete:0}),c.delete+=h.length,s.add(h)):this.adds(h)?((c===null||c.insert===void 0)&&(l(),c={insert:[]}),c.insert=c.insert.concat(h.content.getContent()),n.add(h)):((c===null||c.retain===void 0)&&(l(),c={retain:0}),c.retain+=h.length);c!==null&&c.retain===void 0&&l()}this._changes=e}return e}}const Qs=(i,e)=>{const t=[];for(;e._item!==null&&e!==i;){if(e._item.parentSub!==null)t.unshift(e._item.parentSub);else{let n=0,s=e._item.parent._start;for(;s!==e._item&&s!==null;)!s.deleted&&s.countable&&(n+=s.length),s=s.right;t.unshift(n)}e=e._item.parent}return t},j=()=>{Ms("Invalid access: Add Yjs type to a document before reading data.")},Wi=80;let $t=0;class er{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=$t++}}const tr=i=>{i.timestamp=$t++},Pi=(i,e,t)=>{i.p.marker=!1,i.p=e,e.marker=!0,i.index=t,i.timestamp=$t++},ir=(i,e,t)=>{if(i.length>=Wi){const n=i.reduce((s,r)=>s.timestamp<r.timestamp?s:r);return Pi(n,e,t),n}else{const n=new er(e,t);return i.push(n),n}},st=(i,e)=>{if(i._start===null||e===0||i._searchMarker===null)return null;const t=i._searchMarker.length===0?null:i._searchMarker.reduce((r,o)=>We(e-r.index)<We(e-o.index)?r:o);let n=i._start,s=0;for(t!==null&&(n=t.p,s=t.index,tr(t));n.right!==null&&s<e;){if(!n.deleted&&n.countable){if(e<s+n.length)break;s+=n.length}n=n.right}for(;n.left!==null&&s>e;)n=n.left,!n.deleted&&n.countable&&(s-=n.length);for(;n.left!==null&&n.left.id.client===n.id.client&&n.left.id.clock+n.left.length===n.id.clock;)n=n.left,!n.deleted&&n.countable&&(s-=n.length);return t!==null&&We(t.index-s)<n.parent.length/Wi?(Pi(t,n,s),t):ir(i._searchMarker,n,s)},Ne=(i,e,t)=>{for(let n=i.length-1;n>=0;n--){const s=i[n];if(t>0){let r=s.p;for(r.marker=!1;r&&(r.deleted||!r.countable);)r=r.left,r&&!r.deleted&&r.countable&&(s.index-=r.length);if(r===null||r.marker===!0){i.splice(n,1);continue}s.p=r,r.marker=!0}(e<s.index||t>0&&e===s.index)&&(s.index=Se(e,s.index+t))}},rt=(i,e,t)=>{const n=i,s=e.changedParentTypes;for(;be(s,i,()=>[]).push(t),i._item!==null;)i=i._item.parent;Bi(n._eH,t,e)};class D{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=ni(),this._dEH=ni(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw G()}clone(){throw G()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){si(this._eH,e)}observeDeep(e){si(this._dEH,e)}unobserve(e){ri(this._eH,e)}unobserveDeep(e){ri(this._dEH,e)}toJSON(){}}const Ki=(i,e,t)=>{var o;(o=i.doc)!=null||j(),e<0&&(e=i._length+e),t<0&&(t=i._length+t);let n=t-e;const s=[];let r=i._start;for(;r!==null&&n>0;){if(r.countable&&!r.deleted){const c=r.content.getContent();if(c.length<=e)e-=c.length;else{for(let l=e;l<c.length&&n>0;l++)s.push(c[l]),n--;e=0}}r=r.right}return s},Ji=i=>{var n;(n=i.doc)!=null||j();const e=[];let t=i._start;for(;t!==null;){if(t.countable&&!t.deleted){const s=t.content.getContent();for(let r=0;r<s.length;r++)e.push(s[r])}t=t.right}return e},Ve=(i,e)=>{var s;let t=0,n=i._start;for((s=i.doc)!=null||j();n!==null;){if(n.countable&&!n.deleted){const r=n.content.getContent();for(let o=0;o<r.length;o++)e(r[o],t++,i)}n=n.right}},Gi=(i,e)=>{const t=[];return Ve(i,(n,s)=>{t.push(e(n,s,i))}),t},nr=i=>{let e=i._start,t=null,n=0;return{[Symbol.iterator](){return this},next:()=>{if(t===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};t=e.content.getContent(),n=0,e=e.right}const s=t[n++];return t.length<=n&&(t=null),{done:!1,value:s}}}},qi=(i,e)=>{var s;(s=i.doc)!=null||j();const t=st(i,e);let n=i._start;for(t!==null&&(n=t.p,e-=t.index);n!==null;n=n.right)if(!n.deleted&&n.countable){if(e<n.length)return n.content.getContent()[e];e-=n.length}},Ye=(i,e,t,n)=>{let s=t;const r=i.doc,o=r.clientID,c=r.store,l=t===null?e._start:t.right;let h=[];const u=()=>{h.length>0&&(s=new U(v(o,B(c,o)),s,s&&s.lastId,l,l&&l.id,e,null,new ye(h)),s.integrate(i,0),h=[])};n.forEach(d=>{if(d===null)h.push(d);else switch(d.constructor){case Number:case Object:case Boolean:case Array:case String:h.push(d);break;default:switch(u(),d.constructor){case Uint8Array:case ArrayBuffer:s=new U(v(o,B(c,o)),s,s&&s.lastId,l,l&&l.id,e,null,new ot(new Uint8Array(d))),s.integrate(i,0);break;case Ce:s=new U(v(o,B(c,o)),s,s&&s.lastId,l,l&&l.id,e,null,new ct(d)),s.integrate(i,0);break;default:if(d instanceof D)s=new U(v(o,B(c,o)),s,s&&s.lastId,l,l&&l.id,e,null,new oe(d)),s.integrate(i,0);else throw new Error("Unexpected content type in insert operation")}}}),u()},Hi=()=>me("Length exceeded!"),zi=(i,e,t,n)=>{if(t>e._length)throw Hi();if(t===0)return e._searchMarker&&Ne(e._searchMarker,t,n.length),Ye(i,e,null,n);const s=t,r=st(e,t);let o=e._start;for(r!==null&&(o=r.p,t-=r.index,t===0&&(o=o.prev,t+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(t<=o.length){t<o.length&&re(i,v(o.id.client,o.id.clock+t));break}t-=o.length}return e._searchMarker&&Ne(e._searchMarker,s,n.length),Ye(i,e,o,n)},sr=(i,e,t)=>{let s=(e._searchMarker||[]).reduce((r,o)=>o.index>r.index?o:r,{index:0,p:e._start}).p;if(s)for(;s.right;)s=s.right;return Ye(i,e,s,t)},Yi=(i,e,t,n)=>{if(n===0)return;const s=t,r=n,o=st(e,t);let c=e._start;for(o!==null&&(c=o.p,t-=o.index);c!==null&&t>0;c=c.right)!c.deleted&&c.countable&&(t<c.length&&re(i,v(c.id.client,c.id.clock+t)),t-=c.length);for(;n>0&&c!==null;)c.deleted||(n<c.length&&re(i,v(c.id.client,c.id.clock+n)),c.delete(i),n-=c.length),c=c.right;if(n>0)throw Hi();e._searchMarker&&Ne(e._searchMarker,s,-r+n)},Xe=(i,e,t)=>{const n=e._map.get(t);n!==void 0&&n.delete(i)},xt=(i,e,t,n)=>{const s=e._map.get(t)||null,r=i.doc,o=r.clientID;let c;if(n==null)c=new ye([n]);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:c=new ye([n]);break;case Uint8Array:c=new ot(n);break;case Ce:c=new ct(n);break;default:if(n instanceof D)c=new oe(n);else throw new Error("Unexpected content type")}new U(v(o,B(r.store,o)),s,s&&s.lastId,null,null,e,t,c).integrate(i,0)},Ft=(i,e)=>{var n;(n=i.doc)!=null||j();const t=i._map.get(e);return t!==void 0&&!t.deleted?t.content.getContent()[t.length-1]:void 0},Xi=i=>{var t;const e={};return(t=i.doc)!=null||j(),i._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},Zi=(i,e)=>{var n;(n=i.doc)!=null||j();const t=i._map.get(e);return t!==void 0&&!t.deleted},rr=(i,e)=>{const t={};return i._map.forEach((n,s)=>{let r=n;for(;r!==null&&(!e.sv.has(r.id.client)||r.id.clock>=(e.sv.get(r.id.client)||0));)r=r.left;r!==null&&ue(r,e)&&(t[s]=r.content.getContent()[r.length-1])}),t},xe=i=>{var e;return(e=i.doc)!=null||j(),Ds(i._map.entries(),t=>!t[1].deleted)};class or extends nt{}class Re extends D{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Re;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Re}clone(){const e=new Re;return e.insert(0,this.toArray().map(t=>t instanceof D?t.clone():t)),e}get length(){var e;return(e=this.doc)!=null||j(),this._length}_callObserver(e,t){super._callObserver(e,t),rt(this,e,new or(this,e))}insert(e,t){this.doc!==null?k(this.doc,n=>{zi(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){this.doc!==null?k(this.doc,t=>{sr(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc!==null?k(this.doc,n=>{Yi(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return qi(this,e)}toArray(){return Ji(this)}slice(e=0,t=this.length){return Ki(this,e,t)}toJSON(){return this.map(e=>e instanceof D?e.toJSON():e)}map(e){return Gi(this,e)}forEach(e){Ve(this,e)}[Symbol.iterator](){return nr(this)}_write(e){e.writeTypeRef(_r)}}class cr extends nt{constructor(e,t,n){super(e,t),this.keysChanged=n}}class Ze extends D{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((n,s)=>{this.set(s,n)}),this._prelimContent=null}_copy(){return new Ze}clone(){const e=new Ze;return this.forEach((t,n)=>{e.set(n,t instanceof D?t.clone():t)}),e}_callObserver(e,t){rt(this,e,new cr(this,e,t))}toJSON(){var t;(t=this.doc)!=null||j();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof D?r.toJSON():r}}),e}get size(){return[...xe(this)].length}keys(){return _t(xe(this),e=>e[0])}values(){return _t(xe(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return _t(xe(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){var t;(t=this.doc)!=null||j(),this._map.forEach((n,s)=>{n.deleted||e(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?k(this.doc,t=>{Xe(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return this.doc!==null?k(this.doc,n=>{xt(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return Ft(this,e)}has(e){return Zi(this,e)}clear(){this.doc!==null?k(this.doc,e=>{this.forEach(function(t,n,s){Xe(e,s,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(mr)}}const ne=(i,e)=>i===e||typeof i=="object"&&typeof e=="object"&&i&&e&&ps(i,e);class At{constructor(e,t,n,s){this.left=e,this.right=t,this.index=n,this.currentAttributes=s}forward(){switch(this.right===null&&he(),this.right.content.constructor){case L:this.right.deleted||Ee(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const hi=(i,e,t)=>{for(;e.right!==null&&t>0;){switch(e.right.content.constructor){case L:e.right.deleted||Ee(e.currentAttributes,e.right.content);break;default:e.right.deleted||(t<e.right.length&&re(i,v(e.right.id.client,e.right.id.clock+t)),e.index+=e.right.length,t-=e.right.length);break}e.left=e.right,e.right=e.right.right}return e},Fe=(i,e,t,n)=>{const s=new Map,r=n?st(e,t):null;if(r){const o=new At(r.p.left,r.p,r.index,s);return hi(i,o,t-r.index)}else{const o=new At(null,e._start,0,s);return hi(i,o,t)}},Qi=(i,e,t,n)=>{for(;t.right!==null&&(t.right.deleted===!0||t.right.content.constructor===L&&ne(n.get(t.right.content.key),t.right.content.value));)t.right.deleted||n.delete(t.right.content.key),t.forward();const s=i.doc,r=s.clientID;n.forEach((o,c)=>{const l=t.left,h=t.right,u=new U(v(r,B(s.store,r)),l,l&&l.lastId,h,h&&h.id,e,null,new L(c,o));u.integrate(i,0),t.right=u,t.forward()})},Ee=(i,e)=>{const{key:t,value:n}=e;n===null?i.delete(t):i.set(t,n)},en=(i,e)=>{var t;for(;i.right!==null;){if(!(i.right.deleted||i.right.content.constructor===L&&ne((t=e[i.right.content.key])!=null?t:null,i.right.content.value)))break;i.forward()}},tn=(i,e,t,n)=>{var c;const s=i.doc,r=s.clientID,o=new Map;for(const l in n){const h=n[l],u=(c=t.currentAttributes.get(l))!=null?c:null;if(!ne(u,h)){o.set(l,u);const{left:d,right:g}=t;t.right=new U(v(r,B(s.store,r)),d,d&&d.lastId,g,g&&g.id,e,null,new L(l,h)),t.right.integrate(i,0),t.forward()}}return o},wt=(i,e,t,n,s)=>{t.currentAttributes.forEach((g,w)=>{s[w]===void 0&&(s[w]=null)});const r=i.doc,o=r.clientID;en(t,s);const c=tn(i,e,t,s),l=n.constructor===String?new X(n):n instanceof D?new oe(n):new ke(n);let{left:h,right:u,index:d}=t;e._searchMarker&&Ne(e._searchMarker,t.index,l.getLength()),u=new U(v(o,B(r.store,o)),h,h&&h.lastId,u,u&&u.id,e,null,l),u.integrate(i,0),t.right=u,t.index=d,t.forward(),Qi(i,e,t,c)},ui=(i,e,t,n,s)=>{const r=i.doc,o=r.clientID;en(t,s);const c=tn(i,e,t,s);e:for(;t.right!==null&&(n>0||c.size>0&&(t.right.deleted||t.right.content.constructor===L));){if(!t.right.deleted)switch(t.right.content.constructor){case L:{const{key:l,value:h}=t.right.content,u=s[l];if(u!==void 0){if(ne(u,h))c.delete(l);else{if(n===0)break e;c.set(l,h)}t.right.delete(i)}else t.currentAttributes.set(l,h);break}default:n<t.right.length&&re(i,v(t.right.id.client,t.right.id.clock+n)),n-=t.right.length;break}t.forward()}if(n>0){let l="";for(;n>0;n--)l+=`
|
|
2
|
+
`;t.right=new U(v(o,B(r.store,o)),t.left,t.left&&t.left.lastId,t.right,t.right&&t.right.id,e,null,new X(l)),t.right.integrate(i,0),t.forward()}Qi(i,e,t,c)},nn=(i,e,t,n,s)=>{var h,u;let r=e;const o=J();for(;r&&(!r.countable||r.deleted);){if(!r.deleted&&r.content.constructor===L){const d=r.content;o.set(d.key,d)}r=r.right}let c=0,l=!1;for(;e!==r;){if(t===e&&(l=!0),!e.deleted){const d=e.content;switch(d.constructor){case L:{const{key:g,value:w}=d,y=(h=n.get(g))!=null?h:null;(o.get(g)!==d||y===w)&&(e.delete(i),c++,!l&&((u=s.get(g))!=null?u:null)===w&&y!==w&&(y===null?s.delete(g):s.set(g,y))),!l&&!e.deleted&&Ee(s,d);break}}}e=e.right}return c},lr=(i,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const t=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===L){const n=e.content.key;t.has(n)?e.delete(i):t.add(n)}e=e.left}},ar=i=>{let e=0;return k(i.doc,t=>{let n=i._start,s=i._start,r=J();const o=Et(r);for(;s;){if(s.deleted===!1)switch(s.content.constructor){case L:Ee(o,s.content);break;default:e+=nn(t,n,s,r,o),r=Et(o),n=s;break}s=s.right}}),e},hr=i=>{const e=new Set,t=i.doc;for(const[n,s]of i.afterState.entries()){const r=i.beforeState.get(n)||0;s!==r&&xi(i,t.store.clients.get(n),r,s,o=>{!o.deleted&&o.content.constructor===L&&o.constructor!==ie&&e.add(o.parent)})}k(t,n=>{Di(i,i.deleteSet,s=>{if(s instanceof ie||!s.parent._hasFormatting||e.has(s.parent))return;const r=s.parent;s.content.constructor===L?e.add(r):lr(n,s)});for(const s of e)ar(s)})},di=(i,e,t)=>{const n=t,s=Et(e.currentAttributes),r=e.right;for(;t>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case oe:case ke:case X:t<e.right.length&&re(i,v(e.right.id.client,e.right.id.clock+t)),t-=e.right.length,e.right.delete(i);break}e.forward()}r&&nn(i,r,e.right,s,e.currentAttributes);const o=(e.left||e.right).parent;return o._searchMarker&&Ne(o._searchMarker,e.index,-n+t),e};class ur extends nt{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(s=>{s===null?this.childListChanged=!0:this.keysChanged.add(s)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,t=[];k(e,n=>{var w,y,p;const s=new Map,r=new Map;let o=this.target._start,c=null;const l={};let h="",u=0,d=0;const g=()=>{if(c!==null){let _=null;switch(c){case"delete":d>0&&(_={delete:d}),d=0;break;case"insert":(typeof h=="object"||h.length>0)&&(_={insert:h},s.size>0&&(_.attributes={},s.forEach((I,N)=>{I!==null&&(_.attributes[N]=I)}))),h="";break;case"retain":u>0&&(_={retain:u},ds(l)||(_.attributes=as({},l))),u=0;break}_&&t.push(_),c=null}};for(;o!==null;){switch(o.content.constructor){case oe:case ke:this.adds(o)?this.deletes(o)||(g(),c="insert",h=o.content.getContent()[0],g()):this.deletes(o)?(c!=="delete"&&(g(),c="delete"),d+=1):o.deleted||(c!=="retain"&&(g(),c="retain"),u+=1);break;case X:this.adds(o)?this.deletes(o)||(c!=="insert"&&(g(),c="insert"),h+=o.content.str):this.deletes(o)?(c!=="delete"&&(g(),c="delete"),d+=o.length):o.deleted||(c!=="retain"&&(g(),c="retain"),u+=o.length);break;case L:{const{key:_,value:I}=o.content;if(this.adds(o)){if(!this.deletes(o)){const N=(w=s.get(_))!=null?w:null;ne(N,I)?I!==null&&o.delete(n):(c==="retain"&&g(),ne(I,(y=r.get(_))!=null?y:null)?delete l[_]:l[_]=I)}}else if(this.deletes(o)){r.set(_,I);const N=(p=s.get(_))!=null?p:null;ne(N,I)||(c==="retain"&&g(),l[_]=N)}else if(!o.deleted){r.set(_,I);const N=l[_];N!==void 0&&(ne(N,I)?N!==null&&o.delete(n):(c==="retain"&&g(),I===null?delete l[_]:l[_]=I))}o.deleted||(c==="insert"&&g(),Ee(s,o.content));break}}o=o.right}for(g();t.length>0;){const _=t[t.length-1];if(_.retain!==void 0&&_.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}}class Qe extends D{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){var e;return(e=this.doc)!=null||j(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(n=>n())}catch(n){console.error(n)}this._pending=null}_copy(){return new Qe}clone(){const e=new Qe;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new ur(this,e,t);rt(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){var n;(n=this.doc)!=null||j();let e="",t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===X&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc!==null?k(this.doc,n=>{const s=new At(null,this._start,0,new Map);for(let r=0;r<e.length;r++){const o=e[r];if(o.insert!==void 0){const c=!t&&typeof o.insert=="string"&&r===e.length-1&&s.right===null&&o.insert.slice(-1)===`
|
|
3
|
+
`?o.insert.slice(0,-1):o.insert;(typeof c!="string"||c.length>0)&&wt(n,this,s,c,o.attributes||{})}else o.retain!==void 0?ui(n,this,s,o.retain,o.attributes||{}):o.delete!==void 0&&di(n,s,o.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){var d;(d=this.doc)!=null||j();const s=[],r=new Map,o=this.doc;let c="",l=this._start;function h(){if(c.length>0){const g={};let w=!1;r.forEach((p,_)=>{w=!0,g[_]=p});const y={insert:c};w&&(y.attributes=g),s.push(y),c=""}}const u=()=>{for(;l!==null;){if(ue(l,e)||t!==void 0&&ue(l,t))switch(l.content.constructor){case X:{const g=r.get("ychange");e!==void 0&&!ue(l,e)?(g===void 0||g.user!==l.id.client||g.type!=="removed")&&(h(),r.set("ychange",n?n("removed",l.id):{type:"removed"})):t!==void 0&&!ue(l,t)?(g===void 0||g.user!==l.id.client||g.type!=="added")&&(h(),r.set("ychange",n?n("added",l.id):{type:"added"})):g!==void 0&&(h(),r.delete("ychange")),c+=l.content.str;break}case oe:case ke:{h();const g={insert:l.content.getContent()[0]};if(r.size>0){const w={};g.attributes=w,r.forEach((y,p)=>{w[p]=y})}s.push(g);break}case L:ue(l,e)&&(h(),Ee(r,l.content));break}l=l.right}h()};return e||t?k(o,g=>{e&&Ot(g,e),t&&Ot(g,t),u()},"cleanup"):u(),s}insert(e,t,n){if(t.length<=0)return;const s=this.doc;s!==null?k(s,r=>{const o=Fe(r,this,e,!n);n||(n={},o.currentAttributes.forEach((c,l)=>{n[l]=c})),wt(r,this,o,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const s=this.doc;s!==null?k(s,r=>{const o=Fe(r,this,e,!n);wt(r,this,o,t,n||{})}):this._pending.push(()=>this.insertEmbed(e,t,n||{}))}delete(e,t){if(t===0)return;const n=this.doc;n!==null?k(n,s=>{di(s,Fe(s,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,n){if(t===0)return;const s=this.doc;s!==null?k(s,r=>{const o=Fe(r,this,e,!1);o.right!==null&&ui(r,this,o,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){this.doc!==null?k(this.doc,t=>{Xe(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){this.doc!==null?k(this.doc,n=>{xt(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return Ft(this,e)}getAttributes(){return Xi(this)}_write(e){e.writeTypeRef(wr)}}class yt{constructor(e,t=()=>!0){var n;this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,(n=e.doc)!=null||j()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===Ue||t.constructor===we)&&t._start!==null)e=t._start;else for(;e!==null;)if(e.right!==null){e=e.right;break}else e.parent===this._root?e=null:e=e.parent._item;while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class we extends D{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new we}clone(){const e=new we;return e.insert(0,this.toArray().map(t=>t instanceof D?t.clone():t)),e}get length(){var e;return(e=this.doc)!=null||j(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new yt(this,e)}querySelector(e){e=e.toUpperCase();const n=new yt(this,s=>s.nodeName&&s.nodeName.toUpperCase()===e).next();return n.done?null:n.value}querySelectorAll(e){return e=e.toUpperCase(),_e(new yt(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){rt(this,e,new dr(this,t,e))}toString(){return Gi(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const s=e.createDocumentFragment();return n!==void 0&&n._createAssociation(s,this),Ve(this,r=>{s.insertBefore(r.toDOM(e,t,n),null)}),s}insert(e,t){this.doc!==null?k(this.doc,n=>{zi(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(this.doc!==null)k(this.doc,n=>{const s=e&&e instanceof D?e._item:e;Ye(n,this,s,t)});else{const n=this._prelimContent,s=e===null?0:n.findIndex(r=>r===e)+1;if(s===0&&e!==null)throw me("Reference item not found");n.splice(s,0,...t)}}delete(e,t=1){this.doc!==null?k(this.doc,n=>{Yi(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return Ji(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return qi(this,e)}slice(e=0,t=this.length){return Ki(this,e,t)}forEach(e){Ve(this,e)}_write(e){e.writeTypeRef(br)}}class Ue extends we{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((n,s)=>{this.setAttribute(s,n)}),this._prelimAttrs=null}_copy(){return new Ue(this.nodeName)}clone(){const e=new Ue(this.nodeName),t=this.getAttributes();return us(t,(n,s)=>{typeof n=="string"&&e.setAttribute(s,n)}),e.insert(0,this.toArray().map(n=>n instanceof D?n.clone():n)),e}toString(){const e=this.getAttributes(),t=[],n=[];for(const c in e)n.push(c);n.sort();const s=n.length;for(let c=0;c<s;c++){const l=n[c];t.push(l+'="'+e[l]+'"')}const r=this.nodeName.toLocaleLowerCase(),o=t.length>0?" "+t.join(" "):"";return`<${r}${o}>${super.toString()}</${r}>`}removeAttribute(e){this.doc!==null?k(this.doc,t=>{Xe(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){this.doc!==null?k(this.doc,n=>{xt(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return Ft(this,e)}hasAttribute(e){return Zi(this,e)}getAttributes(e){return e?rr(this,e):Xi(this)}toDOM(e=document,t={},n){const s=e.createElement(this.nodeName),r=this.getAttributes();for(const o in r){const c=r[o];typeof c=="string"&&s.setAttribute(o,c)}return Ve(this,o=>{s.appendChild(o.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(s,this),s}_write(e){e.writeTypeRef(yr),e.writeKey(this.nodeName)}}class dr extends nt{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(s=>{s===null?this.childListChanged=!0:this.attributesChanged.add(s)})}}class sn{constructor(e,t){this.id=e,this.length=t}get deleted(){throw G()}mergeWith(e){return!1}write(e,t,n){throw G()}integrate(e,t){throw G()}}const fr=0;class ie extends sn{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),$i(e.doc.store,this)}write(e,t){e.writeInfo(fr),e.writeLen(this.length-t)}getMissing(e,t){return null}}class ot{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ot(this.content)}splice(e){throw G()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class et{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new et(this.len)}splice(e){const t=new et(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Ui(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}const gr=(i,e)=>new Ce({guid:i,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class ct{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new ct(gr(this.doc.guid,this.opts))}splice(e){throw G()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}class ke{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new ke(this.embed)}splice(e){throw G()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class L{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new L(this.key,this.value)}splice(e){throw G()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const pr=ze("node_env")==="development";class ye{constructor(e){this.arr=e,pr&&vi(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new ye(this.arr)}splice(e){const t=new ye(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let s=t;s<n;s++){const r=this.arr[s];e.writeAny(r)}}getRef(){return 8}}class X{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new X(this.str)}splice(e){const t=new X(this.str.slice(e));this.str=this.str.slice(0,e);const n=this.str.charCodeAt(e-1);return n>=55296&&n<=56319&&(this.str=this.str.slice(0,e-1)+"�",t.str="�"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}}const _r=0,mr=1,wr=2,yr=3,br=4;class oe{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new oe(this.type._copy())}splice(e){throw G()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(n=>{n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(n=>{for(;n!==null;)n.gc(e,!0),n=n.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}const rn=(i,e,t)=>{const{client:n,clock:s}=e.id,r=new U(v(n,s+t),e,v(n,s+t-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t));return e.deleted&&r.markDeleted(),e.keep&&(r.keep=!0),e.redone!==null&&(r.redone=v(e.redone.client,e.redone.clock+t)),e.right=r,r.right!==null&&(r.right.left=r),i._mergeStructs.push(r),r.parentSub!==null&&r.right===null&&r.parent._map.set(r.parentSub,r),e.length=t,r};class U extends sn{constructor(e,t,n,s,r,o,c,l){super(e,l.getLength()),this.origin=n,this.left=t,this.right=s,this.rightOrigin=r,this.parent=o,this.parentSub=c,this.redone=null,this.content=l,this.info=this.content.isCountable()?qt:0}set marker(e){(this.info&ft)>0!==e&&(this.info^=ft)}get marker(){return(this.info&ft)>0}get keep(){return(this.info&Gt)>0}set keep(e){this.keep!==e&&(this.info^=Gt)}get countable(){return(this.info&qt)>0}get deleted(){return(this.info&dt)>0}set deleted(e){this.deleted!==e&&(this.info^=dt)}markDeleted(){this.info|=dt}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=B(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=B(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Ke&&this.id.client!==this.parent.client&&this.parent.clock>=B(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=oi(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=re(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ie||this.right&&this.right.constructor===ie)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===U&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===U&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Ke){const n=mt(t,this.parent);n.constructor===ie?this.parent=null:this.parent=n.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=oi(e,e.doc.store,v(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let n=this.left,s;if(n!==null)s=n.right;else if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start;const r=new Set,o=new Set;for(;s!==null&&s!==this.right;){if(o.add(s),r.add(s),$e(this.origin,s.origin)){if(s.id.client<this.id.client)n=s,r.clear();else if($e(this.rightOrigin,s.rightOrigin))break}else if(s.origin!==null&&o.has(mt(e.doc.store,s.origin)))r.has(mt(e.doc.store,s.origin))||(n=s,r.clear());else break;s=s.right}this.left=n}if(this.left!==null){const n=this.left.right;this.right=n,this.left.right=this}else{let n;if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start,this.parent._start=this;this.right=n}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),$i(e.doc.store,this),this.content.integrate(e,this),li(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new ie(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:v(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&$e(e.origin,this.lastId)&&this.right===e&&$e(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach(n=>{n.p===e&&(n.p=this,!this.deleted&&this.countable&&(n.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),Ui(e.deleteSet,this.id.client,this.id.clock,this.length),li(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw he();this.content.gc(e),t?zs(e,this,new ie(this.id,this.length)):this.content=new et(this.length)}write(e,t){const n=t>0?v(this.id.client,this.id.clock+t-1):this.origin,s=this.rightOrigin,r=this.parentSub,o=this.content.getRef()&jn|(n===null?0:He)|(s===null?0:Ci)|(r===null?0:Un);if(e.writeInfo(o),n!==null&&e.writeLeftID(n),s!==null&&e.writeRightID(s),n===null&&s===null){const c=this.parent;if(c._item!==void 0){const l=c._item;if(l===null){const h=Gs(c);e.writeParentInfo(!0),e.writeString(h)}else e.writeParentInfo(!1),e.writeLeftID(l.id)}else c.constructor===String?(e.writeParentInfo(!0),e.writeString(c)):c.constructor===Ke?(e.writeParentInfo(!1),e.writeLeftID(c)):he();r!==null&&e.writeString(r)}this.content.write(e,t)}}const on=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:{},cn="__ $YJS$ __";on[cn]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");on[cn]=!0;const Ie=i=>Promise.reject(new Error("unimplemented method GetVoiceSign")),bt=(i,e={},t=[])=>({command:i,front_request_id:Te(),data:{...e,to_user_ids:Array.isArray(t)?t:[t]}}),ln=()=>{var i,e;window!=null&&window.__Realsee_Live__&&((e=(i=window==null?void 0:window.__Realsee_Live__)==null?void 0:i.dispose)==null||e.call(i),window.__Realsee_Live__=null)};class an extends Ae{constructor(t){super();a(this,"_options",{});a(this,"keyframes",new Ae);a(this,"_yDoc");a(this,"_buildInData");a(this,"_initializeKeyframesObservers",()=>{this._yDoc.getMap("keyframes").observe(this._handleKeyframesChange)});a(this,"_handleKeyframesChange",t=>{var o;const{transaction:n,target:s,changes:r}=t;if(s===this._buildInData.keyframes)if(n.origin.triggerUserId===((o=this.selfInfo)==null?void 0:o.id)){const c=bt($.KeyframeSync,this.snapshot,void 0);try{this._controller.sendMessage(c)}catch(l){m.error("Failed to send keyframe sync message:",l)}}else r.keys.forEach((c,l)=>{const h=c.oldValue,u=this.getFramesByKey(l),d=n.origin.frontRequestId;this.keyframes.emit(l,u,h,d)}),r.keys.size!==0&&this.emit("keyframes",this.snapshot,n.origin.frontRequestId)});a(this,"getFramesByKey",t=>this.snapshot[t]);a(this,"sendKeyframe",(t,n)=>{var s;return this.state!==V.OPEN?(m.warn("Attempted to send keyframe while connection is not open"),!1):(this._yDoc.transact(()=>{this._buildInData.keyframes.set(t,n)},{triggerUserId:(s=this.selfInfo)==null?void 0:s.id,frontRequestId:""}),!0)});a(this,"_controller",new Tn);a(this,"_initializeOptions",t=>{var n;this._options=Object.assign({initialMicroStatus:te.OPEN},t),this._options.jsBridge=this._initializeJsBridge(t),this._options.getVoiceSign=(n=t.getVoiceSign)!=null?n:Ie,this._options.autoPlayConfirm=t.autoPlayConfirm,this._options.rtc=this._initializeRTC(t)});a(this,"_initializeJsBridge",t=>{if(t.jsBridge)return t.jsBridge;if(t.useBuiltInJsBridge)return new mn});a(this,"_initializeRTC",t=>{if(t.rtc)return t.rtc;if(t.rtcType)return this._createBuiltInRTC(t);if(t.useBuiltInRTC)return this._createDefaultRTC(t)});a(this,"_createBuiltInRTC",t=>{var n;if(!t.getVoiceSign){m.error("GetVoiceSign method must be passed when using built-in RTC instances");return}switch(t.rtcType){case se.RealseeVRWebViewRTC:return this._createVRWebViewRTC();case se.RealseeBrowserChimeRTC:return new Ct({getVoiceSign:(n=this._options.getVoiceSign)!=null?n:Ie,logLevel:t.__debug__?0:1});case se.RealseeBrowserRTC:return this._createBrowserRTC();default:m.error("unknown built-in RTC type");return}});a(this,"_createVRWebViewRTC",()=>{var t;if(this._options.jsBridge)return new gi({jsBridge:this._options.jsBridge,getVoiceSign:(t=this._options.getVoiceSign)!=null?t:Ie});m.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances")});a(this,"_createBrowserRTC",()=>{var t;if(!this._options.autoPlayConfirm){m.error("autoPlayConfirm method must be passed when using built-in RealseeBrowserRTC instances");return}return new fi({getVoiceSign:(t=this._options.getVoiceSign)!=null?t:Ie,autoPlayConfirm:this._options.autoPlayConfirm})});a(this,"_createDefaultRTC",t=>{var s;const n=(s=this._options.getVoiceSign)!=null?s:Ie;return!this._options.jsBridge||!Jt&&!Kt?t.builtInRTCType===Tt.RealseeXChimeRTC?new Ct({getVoiceSign:n}):this._createBrowserRTC():Jt&&(Sn||Cn)||Kt?this._createVRWebViewRTC():this._createBrowserRTC()});a(this,"_autoConnect",()=>{this._options.url&&this._options.getTicket&&this.connect()});a(this,"_debugSetup",()=>{this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this})});a(this,"_addLiveControllerEventListeners",()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage)});a(this,"_removeLiveControllerEventListeners",()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage)});a(this,"_handleStateChange",(t,n)=>{m.info(`State changed from ${n} to ${t}`),this.emit("stateChange",t,n)});a(this,"_handleMessage",async t=>{var n,s,r,o,c,l;if(m.debug("Received message:",t),typeof t=="object"){const{command:h,data:u={},frontRequestId:d,code:g,message:w,triggerUserId:y}=t;if(g==="SUCCESS")switch(h){case $.SelfUserInfo:{const p=u;Rn(this.selfInfo,p,{deep:!0})||(this._buildInData.selfInfo=p,this.emit("selfInfoUpdate",this._buildInData.selfInfo,d));break}case $.RoomInfo:{const p=u;this._buildInData.roomInfo=Object.assign({},p);const _=p.last_frame||{};this._yDoc.transact(()=>{for(const I in _)this._buildInData.keyframes.set(I,_[I])},{triggerUserId:"readyKeyframeSync",frontRequestId:d}),this.emit("readyKeyframeSync",p.last_frame||{});break}case $.RTCInfo:{m.info("RTC info updated:",u);const{voice_id:p,type:_}=u;if(this._buildInData.rtcInfo={voiceId:p,type:_},(n=this.$RTC)!=null&&n.joined)m.warn("已加入语音房间,无需重复加入!");else if(await((o=this.$RTC)==null?void 0:o.join({voiceId:p,userId:((s=this.selfInfo)==null?void 0:s.id)||"",roomId:(r=this.roomInfo)==null?void 0:r.info.room_code,type:_}))){const N=(c=this._options.initialMicroStatus)!=null?c:te.OPEN;await this.toggleMicro(N===te.OPEN)}else m.error("加入语音房间失败");break}case $.UserList:{const p=u;this._buildInData.userList=p,this.emit("userListUpdate",this.userList,d);break}case $.CustomEvent:{const p=u;this.emit("broadcast",p,d);break}case $.KeyframeSync:{const p=u;if(y===((l=this.selfInfo)==null?void 0:l.id))return;this._yDoc.transact(()=>{for(const _ in p)this._buildInData.keyframes.set(_,p[_])},{triggerUserId:y,frontRequestId:d});break}case $.BuiltinMsg:{const p=u;this.emit("builtinEvent",p),p.event_type===F.UserChange&&this.emit("userChange",p),p.event_type===F.RoomChange&&this.emit("roomChange",p),p.event_type===F.UserChange&&p.action===K.UserMicroStatus&&await this.toggleMicro(p.data.status===te.OPEN),p.event_type===F.RoomChange&&p.action===K.RoomClose&&await this._exit();break}case $.UserKickOut:{this.emit("kickOut");break}default:m.warn("Unknown command received:",h)}else m.error("Error in message:",w),this.emit("error",t)}});a(this,"_clearLiveData",()=>{this._buildInData.keyframes.clear(),this._buildInData={keyframes:this._yDoc.getMap("keyframes")}});a(this,"connect",async(t={})=>{var s,r,o,c;if(m.info("Attempting to connect with options:",t),this._options.url=(r=(s=t.url)!=null?s:this._options.url)!=null?r:"",this._options.getTicket=(o=t.getTicket)!=null?o:this._options.getTicket,this._options.initialMicroStatus=(c=t.rtcMicStatus)!=null?c:this._options.initialMicroStatus,!/^wss?:\/\//.test(this._options.url)||typeof this._options.getTicket!="function")return new Error("Invalid connection parameters");if(this._options.rtc&&!await this._options.rtc.detectMicro())return new Error("Failed to obtain microphone authorization");const n=this.state;if(n===V.CONNECTING||n===V.OPEN)if(t.force)await this._controller.close("force close by connect").catch(console.warn);else return new Error("已有Live实例正在连接中,请勿重复连接!");this._clearLiveData();try{const l=await this._options.getTicket(),h=bn(this._options.url,{ticket:l,force:+!!t.force});return this._controller.open(h),m.info("Connection established successfully"),!0}catch(l){return m.error("Failed to connect:",l),new Error("Failed to connect")}});a(this,"_exit",async()=>{var t;this._clearLiveData();try{await((t=this.$RTC)==null?void 0:t.quit())}catch(n){m.warn(n)}return this.state!==V.OPEN?!0:await this._controller.close()});a(this,"exit",async()=>this.close());a(this,"close",async()=>{var t;await this._controller.readyClose();try{await((t=this.$RTC)==null?void 0:t.quit())}catch(n){m.warn(n)}await this.updateStatus(F.RoomChange,K.RoomClose,{})});a(this,"dispose",async()=>{this._removeLiveControllerEventListeners();try{this._yDoc.getMap("keyframes").unobserve(this._handleKeyframesChange),this._yDoc.destroy()}catch(t){m.warn(t)}return this._clearLiveData(),await this._controller.dispose()});a(this,"setSelfInfo",async t=>await this.updateStatus(F.UserChange,K.UserInfo,t));a(this,"broadcast",(t,n,s)=>this.state!==V.OPEN?!1:new Promise((r,o)=>{const c=bt($.CustomEvent,t,n),l=c.front_request_id,h=s?setTimeout(()=>{o(new Error("RESPONSE TIMEOUT")),this.off("broadcast",u)},s):void 0,u=(d,g)=>{g===l&&(h&&clearTimeout(h),this.off("broadcast",u),r(d))};this.on("broadcast",u);try{this._controller.sendMessage(c)}catch(d){o(d)}}));a(this,"toggleMicro",async t=>{var s,r,o;if(!((r=(s=this.selfInfo)==null?void 0:s.permission)!=null&&r.control_own_micro))return!1;const n=await((o=this.$RTC)==null?void 0:o.toggleMicro(t));return n&&await this.updateStatus(F.UserChange,K.UserMicroStatus,{status:t?te.OPEN:te.CLOSE},[]),n});a(this,"forbidMicro",async(t,n)=>{var s,r;return typeof this._options.canForbidUserMicro=="function"&&!this._options.canForbidUserMicro(n)||!((r=(s=this.selfInfo)==null?void 0:s.permission)!=null&&r.control_other_micro)?!1:await this.updateStatus(F.UserChange,K.UserMicroStatus,{status:t},n)});a(this,"forbidSync",async(t,n)=>{var s,r;return typeof this._options.canForbidUserSync=="function"&&!this._options.canForbidUserSync(n)||!((r=(s=this.selfInfo)==null?void 0:s.permission)!=null&&r.control_other_sync)?!1:await this.updateStatus(F.UserChange,K.UserPermission,{sync_frame:t},n)});a(this,"kick",async t=>{var n,s;return typeof this._options.canForbidUserKick=="function"&&!this._options.canForbidUserKick(t)||!((s=(n=this.selfInfo)==null?void 0:n.permission)!=null&&s.change_other_status)?!1:await this.updateStatus(F.UserChange,K.UserStatus,{status:"KICK_OUT"},t)});a(this,"getSnapshotForKey",t=>this.snapshot[t]);m.info("Initializing Live instance with options:",t),this._addLiveControllerEventListeners(),this._yDoc=new Ce({guid:Te()}),this._buildInData={keyframes:this._yDoc.getMap("keyframes")},this._initializeKeyframesObservers(),this._initializeOptions(t),this._autoConnect(),this._debugSetup()}get options(){return Object.freeze(this._options||{})}get state(){return this._controller.state}get readyState(){return this._controller.state}get url(){return this.options.url}get $RTC(){return this._options.rtc}get jsBridge(){return this._options.jsBridge}get snapshot(){return this._buildInData.keyframes.toJSON()}get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}async updateStatus(t,n,s,r){if(this.state!==V.OPEN)return!1;const o=Object.assign({event_type:t,action:n},{data:s}),c=bt($.BuiltinMsg,o,r);try{return this._controller.sendMessage(c),!0}catch(l){return m.error(l),!1}}}const hn=i=>(ln(),new an(i));function Sr(i){const e=b.createContext(null),t=hn(i),n=t.jsBridge,s=f=>b.createElement(e.Provider,{value:t},f.children),r=()=>{const f=b.useContext(e);if(!f)throw new Error("LiveProvider never found.");return f},o=()=>t,c=()=>t.$RTC,l=()=>c(),h=()=>async f=>await t.connect(f);function u(f,E,A=[]){const S=r(),O=[S,f,...A],M=()=>S.keyframes.off(f,E);return b.useEffect(()=>(S.keyframes.on(f,E),M),O),M}function d(){const f=r(),E=b.useCallback(async R=>{await f.connect(R)},[f]),A=b.useCallback(R=>{f.toggleMicro(R)},[f]),S=b.useCallback(async(R,q,at=0)=>{await f.broadcast(R,q,at)},[f]),O=b.useCallback(async()=>{await f.exit()},[f]),M=b.useCallback(async R=>{await f.kick(R)},[f]),W=b.useCallback(async(R,q=[])=>{await f.forbidMicro(R,q)},[f]),ce=b.useCallback((R,q=[])=>{f.forbidSync(R,q)},[f]),lt=b.useCallback(R=>f.getFramesByKey(R),[f]),un=b.useCallback((R,q)=>{f.sendKeyframe(R,q)},[f]),dn=b.useCallback(R=>{f.setSelfInfo(R)},[f]),fn=b.useCallback((R,q,at,gn)=>{f.updateStatus(R,q,at,gn)},[f]);return{connect:E,broadcast:S,exit:O,kick:M,toggleMicro:A,forbidMicro:W,forbidSync:ce,sendKeyframe:un,getFramesByKey:lt,setSelfInfo:dn,updateStatus:fn}}function g(f){const E=r(),[A,S]=b.useState(E.getFramesByKey(f));b.useEffect(()=>{const M=lt=>S(lt),W=f,ce=M;return E.keyframes.on(W,ce),()=>E.keyframes.off(W,ce)},[E]);const O=b.useCallback(M=>E.sendKeyframe(f,M),[E]);return[A,O]}function w(f,E,A=[]){const S=r(),O=()=>S.off(f,E),M=[S,f,...A];return b.useEffect(()=>(S.on(f,E),O),M),O}function y(){const f=r(),[E,A]=b.useState(f.state);return b.useEffect(()=>{const S=O=>A(O);return f.on("stateChange",S),()=>f.off("stateChange",S)},[f]),E}function p(){const f=r();return{join:W=>f.$RTC.join(W),quit:()=>f.$RTC.quit(),shock:()=>{var W,ce;return(ce=(W=f.$RTC).shock)==null?void 0:ce.call(W)},toggleMicro:W=>f.$RTC.toggleMicro(W),detectMicro:()=>f.$RTC.detectMicro()}}function _(f,E,A=[]){const S=r(),O=()=>S.$RTC.off(f,E),M=[S,f,...A];return b.useEffect(()=>(S.$RTC.on(f,E),O),M),O}function I(){const f=r(),[E,A]=b.useState(f.selfInfo||{}),S=M=>A(M);b.useEffect(()=>(f.on("selfInfoUpdate",S),()=>f.off("selfInfoUpdate",S)),[f]);const O=b.useCallback(async M=>await f.setSelfInfo(M),[f]);return[E,O]}function N(){const f=r(),[E,A]=b.useState(f.snapshot);return b.useEffect(()=>{const S=O=>A(O);return f.on("keyframes",S),()=>f.off("keyframes",S)},[f]),E}function Wt(){const f=r(),[E,A]=b.useState(f.userList),S=O=>A(O);return b.useEffect(()=>(f.on("userListUpdate",S),()=>f.off("userListUpdate",S)),[f]),E}return{live:t,jsBridge:n,LiveProvider:s,unsafe__useLiveInstance:o,unsafe__useRTCInstance:l,useConnect:h,useKeyframe:g,useKeyframeUpdateCallback:u,useLiveAction:d,useLiveEventCallback:w,useLiveState:y,useRTCAction:p,useRTCEventCallback:_,useSelfInfo:I,useKeyframesSnapshot:N,useUserList:Wt}}const St=globalThis.__REALSEE_LIVE_BADGE_LOG__;(St==null||St)&&console.log("%c@realsee/live@0.7.3-alpha.0 (9/18/2025, 4:04:20 PM)","background: linear-gradient(to right, #1890ff, #52c41a); color: white; padding: 3px 6px; border-radius: 4px; font-weight: bold; text-shadow: 0 1px 0 rgba(0,0,0,0.2);");exports.BrowserRTC=fi;exports.BrowserRTC4Chime=Ct;exports.BuiltInRTCType=Tt;exports.BuiltinActionType=K;exports.BuiltinEventType=F;exports.Command=$;exports.CoreRTC=tt;exports.Live=an;exports.LiveState=V;exports.MemUserStatus=_i;exports.MicroStatus=te;exports.RTCJoinedInfoCodeEnum=le;exports.RTCType=se;exports.UserStatus=pi;exports.VRWebViewRTC=gi;exports.WebSocketCloseError=wi;exports.WebSocketErrorType=mi;exports.WebSocketState=Ge;exports._clearLiveInstanceIfNeed=ln;exports.createLive=hn;exports.createLiveReact=Sr;exports.parseLiveMsg=yn;exports.parseWSClsErr=yi;
|