@realsee/live 0.7.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +33 -84
- package/dist/index.esm.js +7 -27
- package/package.json +1 -4
package/dist/index.cjs.js
CHANGED
|
@@ -1,92 +1,41 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var Et = require('trtc-js-sdk');
|
|
4
4
|
var amazonChimeSdkJs = require('amazon-chime-sdk-js');
|
|
5
|
-
var
|
|
6
|
-
var
|
|
7
|
-
var N = require('lib0/array');
|
|
8
|
-
var x = require('lib0/math');
|
|
9
|
-
var M = require('lib0/map');
|
|
10
|
-
var u = require('lib0/encoding');
|
|
11
|
-
require('lib0/decoding');
|
|
12
|
-
var Be = require('lib0/random');
|
|
13
|
-
var ze = require('lib0/promise');
|
|
14
|
-
require('lib0/buffer');
|
|
15
|
-
var k = require('lib0/error');
|
|
16
|
-
var C = require('lib0/binary');
|
|
17
|
-
var mt = require('lib0/function');
|
|
18
|
-
var pe = require('lib0/set');
|
|
19
|
-
var P = require('lib0/logging');
|
|
20
|
-
require('lib0/time');
|
|
21
|
-
require('lib0/string');
|
|
22
|
-
var re = require('lib0/iterator');
|
|
23
|
-
var F = require('lib0/object');
|
|
24
|
-
var jt = require('lib0/environment');
|
|
25
|
-
var L = require('react');
|
|
5
|
+
var Xs = require('@realsee/jsbridge-x');
|
|
6
|
+
var U = require('react');
|
|
26
7
|
|
|
27
8
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
28
9
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
if (e) {
|
|
33
|
-
Object.keys(e).forEach(function (k) {
|
|
34
|
-
if (k !== 'default') {
|
|
35
|
-
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
36
|
-
Object.defineProperty(n, k, d.get ? d : {
|
|
37
|
-
enumerable: true,
|
|
38
|
-
get: function () { return e[k]; }
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
n.default = e;
|
|
44
|
-
return Object.freeze(n);
|
|
45
|
-
}
|
|
10
|
+
var Et__default = /*#__PURE__*/_interopDefault(Et);
|
|
11
|
+
var Xs__default = /*#__PURE__*/_interopDefault(Xs);
|
|
12
|
+
var U__default = /*#__PURE__*/_interopDefault(U);
|
|
46
13
|
|
|
47
|
-
var Je__default = /*#__PURE__*/_interopDefault(Je);
|
|
48
|
-
|
|
49
|
-
var N__namespace = /*#__PURE__*/_interopNamespace(N);
|
|
50
|
-
var x__namespace = /*#__PURE__*/_interopNamespace(x);
|
|
51
|
-
var M__namespace = /*#__PURE__*/_interopNamespace(M);
|
|
52
|
-
var u__namespace = /*#__PURE__*/_interopNamespace(u);
|
|
53
|
-
var Be__namespace = /*#__PURE__*/_interopNamespace(Be);
|
|
54
|
-
var ze__namespace = /*#__PURE__*/_interopNamespace(ze);
|
|
55
|
-
var k__namespace = /*#__PURE__*/_interopNamespace(k);
|
|
56
|
-
var C__namespace = /*#__PURE__*/_interopNamespace(C);
|
|
57
|
-
var mt__namespace = /*#__PURE__*/_interopNamespace(mt);
|
|
58
|
-
var pe__namespace = /*#__PURE__*/_interopNamespace(pe);
|
|
59
|
-
var P__namespace = /*#__PURE__*/_interopNamespace(P);
|
|
60
|
-
var re__namespace = /*#__PURE__*/_interopNamespace(re);
|
|
61
|
-
var F__namespace = /*#__PURE__*/_interopNamespace(F);
|
|
62
|
-
var jt__namespace = /*#__PURE__*/_interopNamespace(jt);
|
|
63
|
-
var L__default = /*#__PURE__*/_interopDefault(L);
|
|
14
|
+
var ke=Symbol("$$REALSEE_LIVE_EVENT$$");function Ge(n){return n[ke]||(n[ke]={}),n[ke]}function ni(n){n[ke]?.length||delete n[ke];}var N=class{hasListener(e){let t=Ge(this);return t&&t[e]&&t[e].length>0}on(e,t,r){let i=Ge(this);return i[e]||(i[e]=[]),i[e].push([t,r||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){let r=Ge(this);if(!e){ni(this);return}if(r[e]||(r[e]=[]),t===void 0){r[e].length=0;return}let i=r[e].findIndex(s=>s[0]===t);i!==-1&&r[e].splice(i,1);}emit(e,...t){let r=!1,s=Ge(this)[e]||[];for(let o of s.slice()){let[c,a=!1]=o,l=c(...t);a&&this.off(e,c),l===!1&&(r=!0);}return r}};var J=class extends N{};var ri=(r=>(r.RealseeBrowserRTC="RealseeBrowserRTC",r.RealseeVRWebViewRTC="RealseeVRWebViewRTC",r.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",r))(ri||{}),ii=(t=>(t.RealseeXTRTC="trtc",t.RealseeXChimeRTC="chime",t))(ii||{});var si=()=>{let n=new Date,e=n.getFullYear(),t=(n.getMonth()+1).toString().padStart(2,"0"),r=n.getDate().toString().padStart(2,"0"),i=n.getHours().toString().padStart(2,"0"),s=n.getMinutes().toString().padStart(2,"0"),o=n.getSeconds().toString().padStart(2,"0"),c=n.getMilliseconds().toString().padStart(3,"0");return `[${e}-${t}-${r} ${i}:${s}:${o}.${c}]`};var Ce=(n,e=[])=>{let t=`Realsee Live ${si()} <${n}> `;switch(n){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);}},oi={log:(...n)=>Ce("LOG",n),info:(...n)=>Ce("INFO",n),error:(...n)=>Ce("ERROR",n),warn:(...n)=>Ce("WARN",n),debug:(...n)=>Ce("DEBUG",n)},m=oi;function X(){return ((1+Math.random())*65536|0).toString(16).substring(1)}function Z(){return [X(),X(),"4"+X().substring(0,3),X(),X(),X()+X()+X()].join("-").toLowerCase()}var xe=class extends J{type="RealseeBrowserRTC";joined=!1;micro=!1;voiceId="";_getVoiceSign=()=>{throw new Error("\u65B9\u6CD5 getVoiceSign \u672A\u5B9E\u73B0")};_autoPlayConfirm;checkRequirement=()=>Et__default.default.checkSystemRequirements();$dom=document.createElement("div");_trtc={client:null,stream:null};constructor(e){super(),this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initParentDom();}_initParentDom(){this.$dom.id=`rs-rtc-${Z()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom);}join=async e=>{this.emit("joinWillStart");let t=await this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=Et__default.default.createClient({mode:"rtc",...t,enableAutoPlayDialog:typeof this._autoPlayConfirm!="function"}),this._trtc.client?.enableAudioVolumeEvaluation(),this._registerRtcEvent();let r=await new Promise(i=>{this._trtc.client?.join({roomId:Number(e.voiceId)}).then(()=>i(!0)).catch(()=>i(!1));});return this.joined=r,r?(this._trtc.stream=Et__default.default.createStream({userId:t.userId,audio:!0,video:!1}),r=await new Promise(i=>{this._trtc.stream?.initialize().then(()=>i(!0)).catch(()=>i(!1));}),r=await new Promise(i=>{this._trtc.client?.publish(this._trtc.stream).then(()=>i(!0)).catch(()=>i(!1));}),this.joined=r,this.joined&&this.emit("joined"),r):!1};quit(){return new Promise(async e=>{this.joined=!1,this._trtc.stream&&(await this._trtc.client?.unpublish(this._trtc.stream),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),this._trtc.client?.leave().then(()=>this._trtc.client=null).then(()=>e(!0)).catch(()=>e(!1)),e(!0);})}detectMicro(){return new Promise(e=>{let t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then(()=>e(!0)).catch(r=>{m.error(r.message),e(!1);});}catch(r){console.error(r),e(!1);}})}toggleMicro(e){return Promise.resolve((e?this._trtc?.stream?.unmuteAudio():this._trtc?.stream?.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){this._trtc.client?.on("stream-added",this._handleStreamAdded),this._trtc.client?.on("stream-subscribed",this._handleStreamSubscribed),this._trtc.client?.on("audio-volume",e=>this.emit("userVolumes",e.result.map(({userId:t,audioVolume:r})=>({userId:t,audioVolume:r})))),this._trtc.client?.on("error",e=>this.emit("error",e));}_handleStreamAdded=e=>{let t=e.stream;console.log("\u8FDC\u7AEF\u6D41\u589E\u52A0: "+t.getId()),this._trtc.client?.subscribe(t);};_handleStreamSubscribed=e=>{let t=e.stream;console.log("\u8FDC\u7AEF\u6D41\u8BA2\u9605\u6210\u529F\uFF1A"+t.getId());let i=`rs-rtc-remote_stream-${t.getId()}`,s=document.createElement("div");s.id=i,this.$dom.appendChild(s),typeof this._autoPlayConfirm=="function"?(t.play(i).catch(o=>{}),t.on("error",o=>{if(o.getCode()===16451){let a=()=>t.resume();this._autoPlayConfirm({onConfirm:a});}})):t.play(i);}};var fe=class extends J{type="RealseeBrowserChimeRTC";joined=!1;micro=!1;voiceId="";userId="";logger;deviceController;meetingSession;audioInput;audioOutput;deviceChangeObserver={};audioVideoObserver={};audioMixObserver;_getVoiceSign=()=>{throw new Error("\u65B9\u6CD5 getVoiceSign \u672A\u5B9E\u73B0")};_autoPlayConfirm;$dom=document.createElement("div");$audio=document.createElement("audio");constructor(e){super(),this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initDom(),this.logger=new amazonChimeSdkJs.ConsoleLogger("WebRTCLogger",e.logLevel||amazonChimeSdkJs.LogLevel.INFO),this.deviceController=new amazonChimeSdkJs.DefaultDeviceController(this.logger),this.initObservers();}_initDom=()=>{this.$audio.id=`rs-rtc-${Z()}`,this.$dom.id=`rs-rtc-${Z()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom);};initObservers=()=>{this.deviceChangeObserver={audioInputsChanged:e=>{this.logger.info(`audioInputsChanged ${typeof e}`),e?.forEach(t=>{this.logger.info(`Device ID: ${t.deviceId} Microphone: ${t.label}`);});},audioOutputsChanged:e=>{this.logger.info(`audioOutputsChanged ${typeof e}`),e?.forEach(t=>{this.logger.info(`Device ID: ${t.deviceId} Speaker: ${t.label}`);});},audioInputMuteStateChanged:(e,t)=>{this.logger.info(`Device ${e.toString()} ${t?"is muted in hardware":"is not muted"}`);}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started");},audioVideoDidStop:e=>{this.logger.info(`Stopped with a session status code: ${e.statusCode()}`);},audioVideoDidStartConnecting:e=>{e&&this.logger.info("Attempting to reconnect");}},this.audioMixObserver={meetingAudioStreamBecameActive:e=>{if(this.$audio.paused){let t=()=>this.$audio.play().then(()=>{}).catch(r=>{if(m.error("\u64AD\u653E\u8FDC\u7AEF\u6D41\u5931\u8D25\uFF01",r),typeof this._autoPlayConfirm=="function"){let i=()=>t();this._autoPlayConfirm({onConfirm:i});}});t();}},meetingAudioStreamBecameInactive:e=>{}};};async join(e){return new Promise(async(t,r)=>{this.emit("joinWillStart");try{let{sdkAppId:i,userId:s,roomId:o,userSig:c}=await this._getVoiceSign({...e,roomId:e.roomId||0});this.userId=s;let{attendence:a,vendor_wrapper:l}=JSON.parse(decodeURIComponent(c)),d=new amazonChimeSdkJs.MeetingSessionConfiguration({Meeting:l},{Attendee:{ExternalUserId:a.external_user_id,AttendeeId:a.attendee_id,JoinToken:a.join_token}});this.meetingSession=new amazonChimeSdkJs.DefaultMeetingSession(d,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);let u={audioVideoDidStart:()=>{this.meetingSession?.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),t(!0);},audioVideoDidStop:()=>{this.joined=!1,t(!1);}};this.meetingSession.audioVideo.addObserver(u),this.audioMixObserver&&this.meetingSession.audioVideo.addAudioMixObserver(this.audioMixObserver),this.meetingSession.audioVideo.setDeviceLabelTrigger(async()=>await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}));try{let p=await this.meetingSession.audioVideo.listAudioInputDevices();m.info("audioInputDevices ===>",p);let g=p[0]?.deviceId||"default";await this.meetingSession.audioVideo.startAudioInput(g);}catch(p){m.error(`\u8BBE\u7F6E\u8BED\u97F3\u8F93\u5165\u8BBE\u5907\u5931\u8D25:${p.message}`);}try{let p=await this.meetingSession.audioVideo.listAudioOutputDevices();m.info("audioOutputDevices ===>",p);let g=p[0]?.deviceId||"default";await this.meetingSession.audioVideo.chooseAudioOutput(g);}catch(p){m.error(`\u8BBE\u7F6E\u8BED\u97F3\u8F93\u51FA\u8BBE\u5907\u5931\u8D25:${p.message}`);}this.meetingSession.audioVideo.start();}catch(i){this.emit("error",i),this.logger.error(i.message),t(!1);}})}_registerRtcEvent=()=>{let e=this.meetingSession?.configuration?.credentials?.attendeeId||"";if(e){let t=new Map,r=()=>{let i=[];return t.forEach((s,o)=>{i.push({userId:s.userId,volume:s.muted||s.signalStrength===0||!s.volume?0:s.volume});}),i};this.meetingSession?.audioVideo.realtimeSubscribeToAttendeeIdPresence((i,s,o)=>{if(!s){t.delete(i),this.emit("userVolumes",r());return}this.meetingSession?.audioVideo.realtimeSubscribeToVolumeIndicator(i,(c,a,l,d)=>{new amazonChimeSdkJs.DefaultModality(c).base()===c&&(t.set(c,{userId:o||c,volume:a,muted:l,signalStrength:d}),this.emit("userVolumes",r()));});}),this.meetingSession?.audioVideo.realtimeSubscribeToVolumeIndicator(e,(i,s,o,c)=>{new amazonChimeSdkJs.DefaultModality(i).base()===i&&c!==null&&c!==1&&this.emit("weakNetwork");}),this.meetingSession?.audioVideo.realtimeSubscribeToFatalError(i=>this.emit("error",i));}};quit(){return this.joined?new Promise((e,t)=>{this.joined=!1;let r={audioVideoDidStop:async i=>{let s=i.statusCode();this.meetingSession?.deviceController.destroy(),s===amazonChimeSdkJs.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${s}`),e(!0));}};this.meetingSession?.audioVideo.addObserver(r),this.meetingSession?.audioVideo.stop();}):Promise.resolve(!0)}async detectMicro(){return new Promise(e=>{let t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then(()=>e(!0)).catch(()=>e(!1));}catch(r){this.logger.error(r.message),e(!1);}})}async toggleMicro(e){e?this.meetingSession?.audioVideo.realtimeUnmuteLocalAudio():this.meetingSession?.audioVideo.realtimeMuteLocalAudio();let t=this.meetingSession?.audioVideo.realtimeIsLocalAudioMuted();return t!==void 0?e!==t:!1}shock(){throw new Error("Method not implemented.")}};var fi=(s=>(s[s.Success=0]="Success",s[s.Failure=1]="Failure",s[s.ReJoin=2]="ReJoin",s[s.NoMicroPermission=3]="NoMicroPermission",s[s.Unknown=500]="Unknown",s))(fi||{});var Ie=class extends J{type="RealseeVRWebViewRTC";joined=!1;micro=!1;voiceId="";_joinOptions=null;options;get jsBridge(){return this.options.jsBridge}constructor({jsBridge:e,getVoiceSign:t}){super(),this.options={jsBridge:e,getVoiceSign:t},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);}handleUserVolumes=e=>{this.emit("userVolumes",e);};handleWeakNetwork=e=>{e&&this.emit("weakNetwork");};join=async e=>{this._joinOptions=e,this.emit("joinWillStart");let{sdkAppId:t,userId:r,userSig:i}=await this.getVoiceSignOrEmitError(e);return !t||!r||!i?!1:(this.type=e.type,this.jsBridge.webViewType==="WxMiniProgramWebView"?this.handleWxMiniProgramWebViewJoin({sdkAppId:t,userId:r,userSig:i,voiceId:e.voiceId}):this.handleAppWebViewJoin({sdkAppId:t,userId:r,userSig:i,voiceId:e.voiceId}))};reJoin=async()=>this._joinOptions?this.join({voiceId:this._joinOptions.voiceId,userId:this._joinOptions.userId,roomId:this._joinOptions.roomId,type:this._joinOptions.type}):(this.emitErrorAndSetJoinedFalse("\u91CD\u8FDE\u5931\u8D25\uFF1A\u672A\u627E\u5230\u52A0\u5165\u623F\u95F4\u53C2\u6570\u3002"),!1);getVoiceSignOrEmitError=async e=>{try{return await this.options.getVoiceSign(e)}catch{return this.emitErrorAndSetJoinedFalse("\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1Artc \u7B7E\u540D\u8BF7\u6C42\u5F02\u5E38"),{}}};handleWxMiniProgramWebViewJoin=async e=>{let[t,r]=await this.joinRoomOrEmitError(e);return r?!1:this.handleJoinResult(t)};handleAppWebViewJoin=e=>new Promise(t=>{this.off("inner.rtc.success");let r=i=>{this.off("inner.rtc.fail",r),this.off("inner.rtc.success",r),t(this.handleJoinResult(i));};this.once("inner.rtc.fail",r),this.once("inner.rtc.success",r);try{let{sdkAppId:i,userId:s,userSig:o,voiceId:c}=e;this.jsBridge.callAndListen(`live/join?sdkAppID=${i}&userID=${s}&roomID=${c}&userSig=${o}`,a=>{a===!0?this.emit("inner.rtc.success",a):typeof a=="object"?a.code===0||a.code===2?this.emit("inner.rtc.success",a):this.emit("inner.rtc.fail",a):this.emit("inner.rtc.fail",a);});}catch(i){t(this.handleJoinResult({message:i.message,code:500}));}});joinRoomOrEmitError=async({sdkAppId:e,userId:t,voiceId:r,userSig:i})=>{try{return await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${e}&userID=${t}&roomID=${Number(r)}&userSig=${i}`)}catch(s){return this.emitErrorAndSetJoinedFalse("\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1A"+s.message),[null,s]}};handleJoinResult=e=>{switch(!0){case e===!0:case(typeof e=="object"&&e.code===0):case(typeof e=="object"&&e.code===2):{this.emit("joined"),this.joined=!0;break}default:{this.joined=!1;let t=typeof e=="object"?e.message:"\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1A\u672A\u77E5\u5F02\u5E38\u3002";this.emit("error",new Error(t,{cause:e}));}}return this.joined};emitErrorAndSetJoinedFalse=e=>{this.emit("error",new Error(e)),this.joined=!1;};quit=async()=>{let[e,t]=await this.jsBridge.callAndBackfeed("live/quit");return e===null&&this.emit("error",t||new Error("\u9000\u51FA\u623F\u95F4\u5931\u8D25\uFF1A\u672A\u77E5\u5F02\u5E38\u3002")),this.joined=!1,!!e};detectMicro=async()=>{let[e,t]=await this.jsBridge.detectMicro();return e===null?(this.emit("error",t||new Error("\u9EA6\u514B\u98CE\u76D1\u6D4B\u5F02\u5E38\uFF01")),!1):e};toggleMicro=async e=>{let[t,r]=await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${e?1:0}`);return t===null?(this.emit("error",r||new Error("\u9EA6\u514B\u98CE\u76D1\u6D4B\u5F02\u5E38\uFF01")),!1):(this.micro=t,t)};shock=()=>{this.jsBridge.shock(1);}};var gi=(a=>(a.SelfUserInfo="SELF_USER_INFO",a.RoomInfo="ROOM_INFO",a.RTCInfo="RTC_INFO",a.UserList="USER_LIST",a.BuiltinMsg="BUILTIN_MSG",a.CustomEvent="CUSTOM_EVENT",a.KeyframeSync="KEYFRAME_SYNC",a.UserKickOut="USER_KICK_OUT",a))(gi||{}),pi=(t=>(t.UserChange="user_change",t.RoomChange="room_change",t))(pi||{}),mi=(o=>(o.UserMicroStatus="change_micro_status",o.UserMicroStatusSync="sync_micro_status",o.UserPermission="change_permission",o.UserStatus="change_status",o.UserInfo="change_info",o.RoomClose="close",o))(mi||{}),yi=(t=>(t.OPEN="OPEN",t.CLOSE="CLOSE",t))(yi||{});function Po(n){try{let e=JSON.parse(n),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||{}},r=Object.keys(t).filter(i=>t[i]===void 0);return r.length>0&&console.warn(`\u63A8\u9001\u6570\u636E\u683C\u5F0F\u5F02\u5E38\uFF1A${r.join(" ")} \u503C\u4E0D\u5B58\u5728\uFF01`),t}catch{return !1}}var wi=(i=>(i[i.NOTINITIALIZED=-1]="NOTINITIALIZED",i[i.CONNECTING=0]="CONNECTING",i[i.OPEN=1]="OPEN",i[i.CLOSED=3]="CLOSED",i))(wi||{});var _i=(r=>(r[r.Normal=0]="Normal",r[r.Removed=1]="Removed",r[r.Replaced=2]="Replaced",r))(_i||{}),bi=(o=>(o.WAIT_ENTER="WAIT_ENTER",o.ONLINE="ONLINE",o.LEAVE="LEAVE",o.KICK_OUT="KICK_OUT",o.BE_REPLACE="BE_REPLACE",o.EXCEPTION="EXCEPTION",o))(bi||{});var Si=(s=>(s[s.NOTINITIALIZED=-1]="NOTINITIALIZED",s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(Si||{}),vi=(c=>(c.Error="Error",c.Close="Close",c.MicroAuth="MicroAuth",c.DuplicateConnect="DuplicateConnect",c.IllegalURL="IllegalURL",c.Unknown="Unknown",c.IllegalArgs="IllegalArgs",c))(vi||{}),Ei=(l=>(l.Err_1000="CLOSE_NORMAL",l.Err_1001="CLOSE_GOING_AWAY",l.Err_1002="CLOSE_PROTOCOL_ERROR",l.Err_1003="CLOSE_UNSUPPORTED",l.Err_1006="CLOSE_ABNORMAL",l.Err_1007="Unsupported Data",l.Err_1008="Policy Violation",l.Err_1009="CLOSE_TOO_LARGE",l.Err_unknown="unknown",l))(Ei||{});function Sn(n){switch(n){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 vn(n,e={}){let t=new URL(n,"http://localhost"),r=new URLSearchParams(t.search);return Object.entries(e).forEach(([i,s])=>{r.append(i,String(s));}),n.split("?")[0]+"?"+r.toString()}var En=(()=>{let n=typeof process<"u"&&process.versions?.node!=null;return typeof window<"u"&&"Deno"in window||n||typeof window>"u"})();var Te=En?"":navigator.userAgent,kn=/android/i.test(Te),Cn=/iPhone|iPad\s+OS/i.test(Te),xn=/MicroMessenger/i.test(Te)&&/miniProgram/i.test(Te),In=/realsee/i.test(Te);function qe(n){return Object.prototype.toString.call(n)==="[object Object]"}function Je(n,e){return n===e?!0:n==null||e==null||typeof n!=typeof e?!1:Number.isNaN(n)&&Number.isNaN(e)}function ki(n,e){if(n===e)return !0;if(n==null||e==null)return !1;let t=Object.keys(n),r=Object.keys(e);return t.length!==r.length?!1:t.every(i=>Je(n[i],e[i]))}function Ci(n,e){return n===e?!0:n==null||e==null||n.length!==e.length?!1:n.every((t,r)=>Je(t,e[r]))}function xi(n,e){return Je(n,e)?!0:qe(n)&&qe(e)?ki(n,e):Array.isArray(n)&&Array.isArray(e)?Ci(n,e):!1}function kt(n,e){return Je(n,e)?!0:qe(n)&&qe(e)?Ti(n,e):Array.isArray(n)&&Array.isArray(e)?Ii(n,e):!1}function Ii(n,e){if(n.length!==e.length)return !1;for(let t=0,r=n.length;t<r;t++)if(!kt(n[t],e[t]))return !1;return !0}function Ti(n,e){if(n===e)return !0;if(n==null||e==null)return !1;let t=Object.keys(n),r=Object.keys(e);return t.length!==r.length?!1:t.every(i=>kt(n[i],e[i]))}function Tn(n,e,t={deep:!1}){return t.deep?kt(n,e):xi(n,e)}var He=class extends N{_realWebSocket;_url;_protocols;_readyState=-1;_options={timeout:1e4,shouldReconnect:(e,t)=>{if(!(e.code===1008||e.code===1011))return [0,1e3,2e3][t.attempts%3]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1};_connectTimeout;_attempts=0;_reconnects=-1;_reconnectWhenOnlineAgain=!1;_explicitlyClosed=!1;_pendingReconnect;_connectivityEventsAttached=!1;_heathCheckTimer;get attempts(){return this._attempts}constructor(e){super(),e&&this.setOptions(e),this._startHealthCheck();}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;let t=Object.assign(this._options,e.robustOptions||{});if(typeof t?.timeout!="number")throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if(typeof t?.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=t,this._options.automaticOpen&&this._createWebSocket();}_healthCheck=async()=>{if(this._realWebSocket){let e=this._realWebSocket.readyState;e!==this._readyState&&(this._readyState=e,this._readyState===2&&this.emit("closing"));}await new Promise(e=>setTimeout(e,2e3)),this._heathCheckTimer=requestAnimationFrame(this._healthCheck);};_clearConnectTimeoutIfNeed=()=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);};_clearHeathCheckIfNeed=()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0);};_startHealthCheck=()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck);};_stopHealthCheck=()=>{this._clearHeathCheckIfNeed();};_clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0);};_online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e));};_offline=()=>{this._reconnectWhenOnlineAgain=!0,this._realWebSocket?.close(1e3,"offline");};_detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(globalThis?.removeEventListener("online",this._online),globalThis?.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1);};_attachConnectivityEvents=()=>{this._connectivityEventsAttached||(globalThis?.addEventListener("online",this._online),globalThis?.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0);};send=e=>{this._realWebSocket?.readyState===this._realWebSocket?.OPEN&&this._realWebSocket?.send(e);};close=(e,t)=>(typeof e!="number"&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),this._realWebSocket?.close(e,t));open=e=>{e&&(this._url=e),this._realWebSocket?.readyState!==WebSocket.OPEN&&this._realWebSocket?.readyState!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket());};_createWebSocket=()=>{let e=typeof this._url=="string"?this._url:this._url?.(this);if(!e)return;this._clearConnectTimeoutIfNeed(),this._clearPendingReconnectIfNeeded(),this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(e,this._protocols||void 0),this._attempts++,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));let t=()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("timeout",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));};this._connectTimeout=setTimeout(t,this._options.timeout),this._dispatchWebSocketEvent(),this._options.ignoreConnectivityEvents||this._attachConnectivityEvents();};_removeWebSocketEvent=()=>{this._realWebSocket?.removeEventListener("open",this._webSocketOpenHandler),this._realWebSocket?.removeEventListener("close",this._webSocketCloseHandler),this._realWebSocket?.removeEventListener("error",this._webSocketErrorHandler),this._realWebSocket?.removeEventListener("message",this._webSocketMessageHandler);};_dispatchWebSocketEvent=()=>{this._realWebSocket?.addEventListener("open",this._webSocketOpenHandler),this._realWebSocket?.addEventListener("close",this._webSocketCloseHandler),this._realWebSocket?.addEventListener("error",this._webSocketErrorHandler),this._realWebSocket?.addEventListener("message",this._webSocketMessageHandler);};_webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);let t=++this._reconnects,r=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:r}}))};_webSocketCloseHandler=e=>(this._reconnect(e),this._stopHealthCheck(),this.emit("close",e));_webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}}));_webSocketMessageHandler=e=>this.emit("message",e);_reconnect(e){if(!this._options.should1000Reconnect&&e.code===1e3||this._explicitlyClosed){this._attempts=0;return}if(this._connectivityEventsAttached&&globalThis?.navigator?.onLine===!1){this._reconnectWhenOnlineAgain=!0;return}let i=this._options.shouldReconnect?.(e,this);typeof i=="number"?(console.log(`Reconnecting in ${i}ms...`),this._pendingReconnect=setTimeout(this._createWebSocket,i)):console.log("No reconnection will be attempted.");}};var ze=class extends N{_ws=new He({url:"",robustOptions:{should1000Reconnect:!0,ignoreConnectivityEvents:!0}});_state=-1;set state(e){let t=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,t);}get state(){return this._state}constructor(){super(),this._addWebSocketEventListeners();}_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);};_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);};_handleCloseEvent=e=>{m.info(`live room closed bacause of ${e.code}-${e.reason||Sn(e.code)}`),this.state=3;};_handleClosingEvent=()=>{m.info("live room is closing, onLine:",globalThis?.navigator?.onLine),this.state=3;};_handleConnectingEvent=e=>{m.info("live room is connecting"),this.state=0,e.detail.reconnects>0&&this.emit("reconnecting",e.detail);};_handleErrorEvent=e=>{m.error("live room error",e),this.state=3;};_handleMessageEvent=e=>{let t=(()=>{try{return JSON.parse(e.data)}catch{return e.data}})();this.emit("message",t);};_handleOpenEvent=e=>{m.info("live room open",e.detail),this.state=1,e.detail.reconnects>0&&this.emit("reconnected",e.detail);};_handleTimeoutEvent=e=>{m.error("live room connect timeout!",e.detail),this.state=3;};dispose=async()=>(this._removeWebSocketEventListeners(),await this.close("live room close by controller disposed!"));open=e=>this._ws.open(e);close=(e,t)=>new Promise(r=>{this._ws.once("close",()=>r(!0)),this._ws.close(e,t);});sendMessage(e=""){if(e==null)throw new Error("live message is empty!");if(this.state!==1)throw new Error("live has not yet been initialized!");return this._ws.send(JSON.stringify(e))}readyClose(){this._ws&&(this._ws._explicitlyClosed=!0);}};var L=()=>new Map,Ye=n=>{let e=L();return n.forEach((t,r)=>{e.set(r,t);}),e},Q=(n,e,t)=>{let r=n.get(e);return r===void 0&&n.set(e,r=t()),r},Rn=(n,e)=>{let t=[];for(let[r,i]of n)t.push(e(i,r));return t},Dn=(n,e)=>{for(let[t,r]of n)if(e(r,t))return !0;return !1};var H=()=>new Set;var Xe=n=>n[n.length-1];var ee=Array.from;var xt=Array.isArray;var Ze=class{constructor(){this._observers=L();}on(e,t){return Q(this._observers,e,H).add(t),t}once(e,t){let r=(...i)=>{this.off(e,r),t(...i);};this.on(e,r);}off(e,t){let r=this._observers.get(e);r!==void 0&&(r.delete(t),r.size===0&&this._observers.delete(e));}emit(e,t){return ee((this._observers.get(e)||L()).values()).forEach(r=>r(...t))}destroy(){this._observers=L();}};var P=Math.floor;var ge=Math.abs;var Qe=(n,e)=>n<e?n:e,te=(n,e)=>n>e?n:e;var Un=n=>n!==0?n<0:1/n<0;var On=Number.isInteger||(n=>typeof n=="number"&&isFinite(n)&&P(n)===n);var Ui=n=>n.toLowerCase(),Oi=/^\s*/g,Ai=n=>n.replace(Oi,""),Li=/([A-Z])/g,Dt=(n,e)=>Ai(n.replace(Li,t=>`${e}${Ui(t)}`));var Vi=n=>{let e=unescape(encodeURIComponent(n)),t=e.length,r=new Uint8Array(t);for(let i=0;i<t;i++)r[i]=e.codePointAt(i);return r},pe=typeof TextEncoder<"u"?new TextEncoder:null,Mi=n=>pe.encode(n),An=pe?Mi:Vi;var Rt=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Rt&&Rt.decode(new Uint8Array).length===1&&(Rt=null);var ce=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[];}},nt=()=>new ce;var Ki=n=>{let e=n.cpos;for(let t=0;t<n.bufs.length;t++)e+=n.bufs[t].length;return e};var j=n=>{let e=new Uint8Array(Ki(n)),t=0;for(let r=0;r<n.bufs.length;r++){let i=n.bufs[r];e.set(i,t),t+=i.length;}return e.set(new Uint8Array(n.cbuf.buffer,0,n.cpos),t),e},Pi=(n,e)=>{let t=n.cbuf.length;t-n.cpos<e&&(n.bufs.push(new Uint8Array(n.cbuf.buffer,0,n.cpos)),n.cbuf=new Uint8Array(te(t,e)*2),n.cpos=0);},T=(n,e)=>{let t=n.cbuf.length;n.cpos===t&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(t*2),n.cpos=0),n.cbuf[n.cpos++]=e;};var rt=T;var w=(n,e)=>{for(;e>127;)T(n,128|127&e),e=P(e/128);T(n,127&e);},it=(n,e)=>{let t=Un(e);for(t&&(e=-e),T(n,(e>63?128:0)|(t?64:0)|63&e),e=P(e/64);e>0;)T(n,(e>127?128:0)|127&e),e=P(e/128);},Ot=new Uint8Array(3e4),ji=Ot.length/3,Fi=(n,e)=>{if(e.length<ji){let t=pe.encodeInto(e,Ot).written||0;w(n,t);for(let r=0;r<t;r++)T(n,Ot[r]);}else V(n,An(e));},Wi=(n,e)=>{let t=unescape(encodeURIComponent(e)),r=t.length;w(n,r);for(let i=0;i<r;i++)T(n,t.codePointAt(i));},ae=pe&&pe.encodeInto?Fi:Wi;var st=(n,e)=>{let t=n.cbuf.length,r=n.cpos,i=Qe(t-r,e.length),s=e.length-i;n.cbuf.set(e.subarray(0,i),r),n.cpos+=i,s>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(te(t*2,s)),n.cbuf.set(e.subarray(i)),n.cpos=s);},V=(n,e)=>{w(n,e.byteLength),st(n,e);},At=(n,e)=>{Pi(n,e);let t=new DataView(n.cbuf.buffer,n.cpos,e);return n.cpos+=e,t},$i=(n,e)=>At(n,4).setFloat32(0,e,!1),Gi=(n,e)=>At(n,8).setFloat64(0,e,!1),qi=(n,e)=>At(n,8).setBigInt64(0,e,!1);var Vn=new DataView(new ArrayBuffer(4)),Ji=n=>(Vn.setFloat32(0,n),Vn.getFloat32(0)===n),me=(n,e)=>{switch(typeof e){case"string":T(n,119),ae(n,e);break;case"number":On(e)&&ge(e)<=2147483647?(T(n,125),it(n,e)):Ji(e)?(T(n,124),$i(n,e)):(T(n,123),Gi(n,e));break;case"bigint":T(n,122),qi(n,e);break;case"object":if(e===null)T(n,126);else if(xt(e)){T(n,117),w(n,e.length);for(let t=0;t<e.length;t++)me(n,e[t]);}else if(e instanceof Uint8Array)T(n,116),V(n,e);else {T(n,118);let t=Object.keys(e);w(n,t.length);for(let r=0;r<t.length;r++){let i=t[r];ae(n,i),me(n,e[i]);}}break;case"boolean":T(n,e?120:121);break;default:T(n,127);}},De=class extends ce{constructor(e){super(),this.w=e,this.s=null,this.count=0;}write(e){this.s===e?this.count++:(this.count>0&&w(this,this.count-1),this.count=1,this.w(this,e),this.s=e);}};var Mn=n=>{n.count>0&&(it(n.encoder,n.count===1?n.s:-n.s),n.count>1&&w(n.encoder,n.count-2));},le=class{constructor(){this.encoder=new ce,this.s=0,this.count=0;}write(e){this.s===e?this.count++:(Mn(this),this.count=1,this.s=e);}toUint8Array(){return Mn(this),j(this.encoder)}};var Nn=n=>{if(n.count>0){let e=n.diff*2+(n.count===1?0:1);it(n.encoder,e),n.count>1&&w(n.encoder,n.count-2);}},ye=class{constructor(){this.encoder=new ce,this.s=0,this.count=0,this.diff=0;}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Nn(this),this.count=1,this.diff=e-this.s,this.s=e);}toUint8Array(){return Nn(this),j(this.encoder)}},tt=class{constructor(){this.sarr=[],this.s="",this.lensE=new le;}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length);}toUint8Array(){let e=new ce;return this.sarr.push(this.s),this.s="",ae(e,this.sarr.join("")),st(e,this.lensE.toUint8Array()),j(e)}};var de=n=>new Error(n),B=()=>{throw de("Method unimplemented")},ne=()=>{throw de("Unexpected case")};var Bn=crypto.getRandomValues.bind(crypto);var Lt=()=>Bn(new Uint32Array(1))[0];var Yi="10000000-1000-4000-8000"+-1e11,Kn=()=>Yi.replace(/[018]/g,n=>(n^Lt()&15>>n/4).toString(16));var Vt=n=>new Promise(n);Promise.all.bind(Promise);var Mt=n=>n===void 0?null:n;var Nt=class{constructor(){this.map=new Map;}setItem(e,t){this.map.set(e,t);}getItem(e){return this.map.get(e)}},jn=new Nt,ts=!0;try{typeof localStorage<"u"&&localStorage&&(jn=localStorage,ts=!1);}catch{}var Fn=jn;var $n=Object.assign,rs=Object.keys,Gn=(n,e)=>{for(let t in n)e(n[t],t);};var Wn=n=>rs(n).length;var qn=n=>{for(let e in n)return !1;return !0},is=(n,e)=>{for(let t in n)if(!e(n[t],t))return !1;return !0},ss=(n,e)=>Object.prototype.hasOwnProperty.call(n,e),Jn=(n,e)=>n===e||Wn(n)===Wn(e)&&is(n,(t,r)=>(t!==void 0||ss(e,r))&&e[r]===t),os=Object.freeze,Bt=n=>{for(let e in n){let t=n[e];(typeof t=="object"||typeof t=="function")&&Bt(n[e]);}return os(n)};var Ue=(n,e,t=0)=>{try{for(;t<n.length;t++)n[t](...e);}finally{t<n.length&&Ue(n,e,t+1);}};var Hn=(n,e)=>e.includes(n);var Oe=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";var F,as=[],ls=()=>{if(F===void 0)if(Oe){F=L();let n=process.argv,e=null;for(let t=0;t<n.length;t++){let r=n[t];r[0]==="-"?(e!==null&&F.set(e,""),e=r):e!==null?(F.set(e,r),e=null):as.push(r);}e!==null&&F.set(e,"");}else typeof location=="object"?(F=L(),(location.search||"?").slice(1).split("&").forEach(n=>{if(n.length!==0){let[e,t]=n.split("=");F.set(`--${Dt(e,"-")}`,t),F.set(`-${Dt(e,"-")}`,t);}})):F=L();return F},Kt=n=>ls().has(n);var Ae=n=>Oe?Mt(process.env[n.toUpperCase().replaceAll("-","_")]):Mt(Fn.getItem(n));var Yn=n=>Kt("--"+n)||Ae(n)!==null;Yn("production");var ds=Oe&&Hn(process.env.FORCE_COLOR,["true","1","2"]),Xn=ds||!Kt("--no-colors")&&!Yn("no-color")&&(!Oe||process.stdout.isTTY)&&(!Oe||Kt("--color")||Ae("COLORTERM")!==null||(Ae("TERM")||"").includes("color"));var Pt=class{constructor(e,t){this.left=e,this.right=t;}},W=(n,e)=>new Pt(n,e);typeof DOMParser<"u"?new DOMParser:null;var Qn=n=>Rn(n,(e,t)=>`${t}:${e};`).join("");var $=Symbol;var Le=$(),Ve=$(),jt=$(),Ft=$(),Wt=$(),Me=$(),$t=$(),we=$(),Gt=$(),er=n=>{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());let e=[],t=[],r=0;for(;r<n.length;r++){let i=n[r];if(i===void 0)break;if(i.constructor===String||i.constructor===Number)e.push(i);else if(i.constructor===Object)break}for(r>0&&t.push(e.join(""));r<n.length;r++){let i=n[r];i instanceof Symbol||t.push(i);}return t};var ps={[Le]:W("font-weight","bold"),[Ve]:W("font-weight","normal"),[jt]:W("color","blue"),[Wt]:W("color","green"),[Ft]:W("color","grey"),[Me]:W("color","red"),[$t]:W("color","purple"),[we]:W("color","orange"),[Gt]:W("color","black")},ms=n=>{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());let e=[],t=[],r=L(),i=[],s=0;for(;s<n.length;s++){let o=n[s],c=ps[o];if(c!==void 0)r.set(c.left,c.right);else {if(o===void 0)break;if(o.constructor===String||o.constructor===Number){let a=Qn(r);s>0||a.length>0?(e.push("%c"+o),t.push(a)):e.push(o);}else break}}for(s>0&&(i=t,i.unshift(e.join("")));s<n.length;s++){let o=n[s];o instanceof Symbol||i.push(o);}return i},tr=Xn?ms:er,nr=(...n)=>{console.log(...tr(n)),ir.forEach(e=>e.print(n));},rr=(...n)=>{console.warn(...tr(n)),n.unshift(we),ir.forEach(e=>e.print(n));};var ir=H();var sr=n=>({[Symbol.iterator](){return this},next:n}),or=(n,e)=>sr(()=>{let t;do t=n.next();while(!t.done&&!e(t.value));return t}),ot=(n,e)=>sr(()=>{let{done:t,value:r}=n.next();return {done:t,value:t?void 0:e(r)}});var Ht=class{constructor(e,t){this.clock=e,this.len=t;}},ht=class{constructor(){this.clients=new Map;}},_r=(n,e,t)=>e.clients.forEach((r,i)=>{let s=n.doc.store.clients.get(i);for(let o=0;o<r.length;o++){let c=r[o];xr(n,s,c.clock,c.len,t);}}),Ss=(n,e)=>{let t=0,r=n.length-1;for(;t<=r;){let i=P((t+r)/2),s=n[i],o=s.clock;if(o<=e){if(e<o+s.len)return i;t=i+1;}else r=i-1;}return null},br=(n,e)=>{let t=n.clients.get(e.client);return t!==void 0&&Ss(t,e.clock)!==null},Sr=n=>{n.clients.forEach(e=>{e.sort((i,s)=>i.clock-s.clock);let t,r;for(t=1,r=1;t<e.length;t++){let i=e[r-1],s=e[t];i.clock+i.len>=s.clock?i.len=te(i.len,s.clock+s.len-i.clock):(r<t&&(e[r]=s),r++);}e.length=r;});};var vr=(n,e,t,r)=>{Q(n.clients,e,()=>[]).push(new Ht(t,r));};var Es=(n,e)=>{w(n.restEncoder,e.clients.size),ee(e.clients.entries()).sort((t,r)=>r[0]-t[0]).forEach(([t,r])=>{n.resetDsCurVal(),w(n.restEncoder,t);let i=r.length;w(n.restEncoder,i);for(let s=0;s<i;s++){let o=r[s];n.writeDsClock(o.clock),n.writeDsLen(o.len);}});};var Er=Lt,ue=class n extends Ze{constructor({guid:e=Kn(),collectionid:t=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:c=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=Er(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new nn,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=c,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Vt(l=>{this.on("load",()=>{this.isLoaded=!0,l(this);});});let a=()=>Vt(l=>{let d=u=>{(u===void 0||u===!0)&&(this.off("sync",d),l());};this.on("sync",d);});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=a()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this]);}),this.whenSynced=a();}load(){let e=this._item;e!==null&&!this.shouldLoad&&S(e.parent.doc,t=>{t.subdocsLoaded.add(this);},null,!0),this.shouldLoad=!0;}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(ee(this.subdocs).map(e=>e.guid))}transact(e,t=null){return S(this,e,t)}get(e,t=C){let r=Q(this.share,e,()=>{let s=new t;return s._integrate(this,null),s}),i=r.constructor;if(t!==C&&i!==t)if(i===C){let s=new t;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s;}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(e,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,an)}getText(e=""){return this.get(e,un)}getMap(e=""){return this.get(e,dn)}getXmlElement(e=""){return this.get(e,gt)}getXmlFragment(e=""){return this.get(e,je)}toJSON(){let e={};return this.share.forEach((t,r)=>{e[r]=t.toJSON();}),e}destroy(){this.isDestroyed=!0,ee(this.subdocs).forEach(t=>t.destroy());let e=this._item;if(e!==null){this._item=null;let t=e.content;t.doc=new n({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,S(e.parent.doc,r=>{let i=t.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this);},null,!0);}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy();}};var zt=class{constructor(){this.restEncoder=nt();}toUint8Array(){return j(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){w(this.restEncoder,e);}writeDsLen(e){w(this.restEncoder,e);}},Yt=class extends zt{writeLeftID(e){w(this.restEncoder,e.client),w(this.restEncoder,e.clock);}writeRightID(e){w(this.restEncoder,e.client),w(this.restEncoder,e.clock);}writeClient(e){w(this.restEncoder,e);}writeInfo(e){rt(this.restEncoder,e);}writeString(e){ae(this.restEncoder,e);}writeParentInfo(e){w(this.restEncoder,e?1:0);}writeTypeRef(e){w(this.restEncoder,e);}writeLen(e){w(this.restEncoder,e);}writeAny(e){me(this.restEncoder,e);}writeBuf(e){V(this.restEncoder,e);}writeJSON(e){ae(this.restEncoder,JSON.stringify(e));}writeKey(e){ae(this.restEncoder,e);}},Xt=class{constructor(){this.restEncoder=nt(),this.dsCurrVal=0;}toUint8Array(){return j(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0;}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,w(this.restEncoder,t);}writeDsLen(e){e===0&&ne(),w(this.restEncoder,e-1),this.dsCurrVal+=e;}},Zt=class extends Xt{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new ye,this.clientEncoder=new le,this.leftClockEncoder=new ye,this.rightClockEncoder=new ye,this.infoEncoder=new De(rt),this.stringEncoder=new tt,this.parentInfoEncoder=new De(rt),this.typeRefEncoder=new le,this.lenEncoder=new le;}toUint8Array(){let e=nt();return w(e,0),V(e,this.keyClockEncoder.toUint8Array()),V(e,this.clientEncoder.toUint8Array()),V(e,this.leftClockEncoder.toUint8Array()),V(e,this.rightClockEncoder.toUint8Array()),V(e,j(this.infoEncoder)),V(e,this.stringEncoder.toUint8Array()),V(e,j(this.parentInfoEncoder)),V(e,this.typeRefEncoder.toUint8Array()),V(e,this.lenEncoder.toUint8Array()),st(e,j(this.restEncoder)),j(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){V(this.restEncoder,e);}writeJSON(e){me(this.restEncoder,e);}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t);}},ks=(n,e,t,r)=>{r=te(r,e[0].id.clock);let i=z(e,r);w(n.restEncoder,e.length-i),n.writeClient(t),w(n.restEncoder,r);let s=e[i];s.write(n,r-s.id.clock);for(let o=i+1;o<e.length;o++)e[o].write(n,0);},Cs=(n,e,t)=>{let r=new Map;t.forEach((i,s)=>{M(e,s)>i&&r.set(s,i);}),pn(e).forEach((i,s)=>{t.has(s)||r.set(s,0);}),w(n.restEncoder,r.size),ee(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{ks(n,e.clients.get(i),i,s);});};var xs=(n,e)=>Cs(n,e.doc.store,e.beforeState);var Qt=class{constructor(){this.l=[];}},lr=()=>new Qt,dr=(n,e)=>n.l.push(e),hr=(n,e)=>{let t=n.l,r=t.length;n.l=t.filter(i=>e!==i),r===n.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.");},kr=(n,e,t)=>Ue(n.l,[e,t]),be=class{constructor(e,t){this.client=e,this.clock=t;}},ct=(n,e)=>n===e||n!==null&&e!==null&&n.client===e.client&&n.clock===e.clock,v=(n,e)=>new be(n,e);var Is=n=>{for(let[e,t]of n.doc.share.entries())if(t===n)return e;throw ne()};var _e=(n,e)=>e===void 0?!n.deleted:e.sv.has(n.id.client)&&(e.sv.get(n.id.client)||0)>n.id.clock&&!br(e.ds,n.id),tn=(n,e)=>{let t=Q(n.meta,tn,H),r=n.doc.store;t.has(e)||(e.sv.forEach((i,s)=>{i<M(r,s)&&ie(n,v(s,i));}),_r(n,e.ds,i=>{}),t.add(e));};var nn=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null;}},pn=n=>{let e=new Map;return n.clients.forEach((t,r)=>{let i=t[t.length-1];e.set(r,i.id.clock+i.length);}),e},M=(n,e)=>{let t=n.clients.get(e);if(t===void 0)return 0;let r=t[t.length-1];return r.id.clock+r.length},Cr=(n,e)=>{let t=n.clients.get(e.id.client);if(t===void 0)t=[],n.clients.set(e.id.client,t);else {let r=t[t.length-1];if(r.id.clock+r.length!==e.id.clock)throw ne()}t.push(e);},z=(n,e)=>{let t=0,r=n.length-1,i=n[r],s=i.id.clock;if(s===e)return r;let o=P(e/(s+i.length-1)*r);for(;t<=r;){if(i=n[o],s=i.id.clock,s<=e){if(e<s+i.length)return o;t=o+1;}else r=o-1;o=P((t+r)/2);}throw ne()},Rs=(n,e)=>{let t=n.clients.get(e.client);return t[z(t,e.clock)]},qt=Rs,rn=(n,e,t)=>{let r=z(e,t),i=e[r];return i.id.clock<t&&i instanceof A?(e.splice(r+1,0,Wr(n,i,t-i.id.clock)),r+1):r},ie=(n,e)=>{let t=n.doc.store.clients.get(e.client);return t[rn(n,t,e.clock)]},ur=(n,e,t)=>{let r=e.clients.get(t.client),i=z(r,t.clock),s=r[i];return t.clock!==s.id.clock+s.length-1&&s.constructor!==G&&r.splice(i+1,0,Wr(n,s,t.clock-s.id.clock+1)),s},Ds=(n,e,t)=>{let r=n.clients.get(e.id.client);r[z(r,e.id.clock)]=t;},xr=(n,e,t,r,i)=>{if(r===0)return;let s=t+r,o=rn(n,e,t),c;do c=e[o++],s<c.id.clock+c.length&&rn(n,e,s),i(c);while(o<e.length&&e[o].id.clock<s)},sn=class{constructor(e,t,r){this.doc=e,this.deleteSet=new ht,this.beforeState=pn(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=r,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1;}},fr=(n,e)=>e.deleteSet.clients.size===0&&!Dn(e.afterState,(t,r)=>e.beforeState.get(r)!==t)?!1:(Sr(e.deleteSet),xs(n,e),Es(n,e.deleteSet),!0),gr=(n,e,t)=>{let r=e._item;(r===null||r.id.clock<(n.beforeState.get(r.id.client)||0)&&!r.deleted)&&Q(n.changed,e,H).add(t);},dt=(n,e)=>{let t=n[e],r=n[e-1],i=e;for(;i>0;t=r,r=n[--i-1]){if(r.deleted===t.deleted&&r.constructor===t.constructor&&r.mergeWith(t)){t instanceof A&&t.parentSub!==null&&t.parent._map.get(t.parentSub)===t&&t.parent._map.set(t.parentSub,r);continue}break}let s=e-i;return s&&n.splice(e+1-s,s),s},Us=(n,e,t)=>{for(let[r,i]of n.clients.entries()){let s=e.clients.get(r);for(let o=i.length-1;o>=0;o--){let c=i[o],a=c.clock+c.len;for(let l=z(s,c.clock),d=s[l];l<s.length&&d.id.clock<a;d=s[++l]){let u=s[l];if(c.clock+c.len<=u.id.clock)break;u instanceof A&&u.deleted&&!u.keep&&t(u)&&u.gc(e,!1);}}}},Os=(n,e)=>{n.clients.forEach((t,r)=>{let i=e.clients.get(r);for(let s=t.length-1;s>=0;s--){let o=t[s],c=Qe(i.length-1,1+z(i,o.clock+o.len-1));for(let a=c,l=i[a];a>0&&l.id.clock>=o.clock;l=i[a])a-=1+dt(i,a);}});};var Ir=(n,e)=>{if(e<n.length){let t=n[e],r=t.doc,i=r.store,s=t.deleteSet,o=t._mergeStructs;try{Sr(s),t.afterState=pn(t.doc.store),r.emit("beforeObserverCalls",[t,r]);let c=[];t.changed.forEach((a,l)=>c.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(t,a);})),c.push(()=>{t.changedParentTypes.forEach((a,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(a=a.filter(d=>d.target._item===null||!d.target._item.deleted),a.forEach(d=>{d.currentTarget=l,d._path=null;}),a.sort((d,u)=>d.path.length-u.path.length),kr(l._dEH,a,t));});}),c.push(()=>r.emit("afterTransaction",[t,r])),Ue(c,[]),t._needFormattingCleanup&&js(t);}finally{r.gc&&Us(s,i,r.gcFilter),Os(s,i),t.afterState.forEach((d,u)=>{let p=t.beforeState.get(u)||0;if(p!==d){let g=i.clients.get(u),_=te(z(g,p),1);for(let x=g.length-1;x>=_;)x-=1+dt(g,x);}});for(let d=o.length-1;d>=0;d--){let{client:u,clock:p}=o[d].id,g=i.clients.get(u),_=z(g,p);_+1<g.length&&dt(g,_+1)>1||_>0&&dt(g,_);}if(!t.local&&t.afterState.get(r.clientID)!==t.beforeState.get(r.clientID)&&(nr(we,Le,"[yjs] ",Ve,Me,"Changed the client-id because another client seems to be using it."),r.clientID=Er()),r.emit("afterTransactionCleanup",[t,r]),r._observers.has("update")){let d=new Yt;fr(d,t)&&r.emit("update",[d.toUint8Array(),t.origin,r,t]);}if(r._observers.has("updateV2")){let d=new Zt;fr(d,t)&&r.emit("updateV2",[d.toUint8Array(),t.origin,r,t]);}let{subdocsAdded:c,subdocsLoaded:a,subdocsRemoved:l}=t;(c.size>0||l.size>0||a.size>0)&&(c.forEach(d=>{d.clientID=r.clientID,d.collectionid==null&&(d.collectionid=r.collectionid),r.subdocs.add(d);}),l.forEach(d=>r.subdocs.delete(d)),r.emit("subdocs",[{loaded:a,added:c,removed:l},r,t]),l.forEach(d=>d.destroy())),n.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,n])):Ir(n,e+1);}}},S=(n,e,t=null,r=!0)=>{let i=n._transactionCleanups,s=!1,o=null;n._transaction===null&&(s=!0,n._transaction=new sn(n,t,r),i.push(n._transaction),i.length===1&&n.emit("beforeAllTransactions",[n]),n.emit("beforeTransaction",[n._transaction,n]));try{o=e(n._transaction);}finally{if(s){let c=n._transaction===i[0];n._transaction=null,c&&Ir(i,0);}}return o};var pr="You must not compute changes after the event-handler fired.",Se=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null;}get path(){return this._path||(this._path=As(this.currentTarget,this.target))}deletes(e){return br(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw de(pr);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(i=>{if(i!==null){let s=t._map.get(i),o,c;if(this.adds(s)){let a=s.left;for(;a!==null&&this.adds(a);)a=a.left;if(this.deletes(s))if(a!==null&&this.deletes(a))o="delete",c=Xe(a.content.getContent());else return;else a!==null&&this.deletes(a)?(o="update",c=Xe(a.content.getContent())):(o="add",c=void 0);}else if(this.deletes(s))o="delete",c=Xe(s.content.getContent());else return;e.set(i,{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 de(pr);let t=this.target,r=H(),i=H(),s=[];if(e={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(t).has(null)){let c=null,a=()=>{c&&s.push(c);};for(let l=t._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((c===null||c.delete===void 0)&&(a(),c={delete:0}),c.delete+=l.length,i.add(l)):this.adds(l)?((c===null||c.insert===void 0)&&(a(),c={insert:[]}),c.insert=c.insert.concat(l.content.getContent()),r.add(l)):((c===null||c.retain===void 0)&&(a(),c={retain:0}),c.retain+=l.length);c!==null&&c.retain===void 0&&a();}this._changes=e;}return e}},As=(n,e)=>{let t=[];for(;e._item!==null&&e!==n;){if(e._item.parentSub!==null)t.unshift(e._item.parentSub);else {let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;t.unshift(r);}e=e._item.parent;}return t},O=()=>{rr("Invalid access: Add Yjs type to a document before reading data.");},Tr=80,mn=0,on=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=mn++;}},Ls=n=>{n.timestamp=mn++;},Rr=(n,e,t)=>{n.p.marker=!1,n.p=e,e.marker=!0,n.index=t,n.timestamp=mn++;},Vs=(n,e,t)=>{if(n.length>=Tr){let r=n.reduce((i,s)=>i.timestamp<s.timestamp?i:s);return Rr(r,e,t),r}else {let r=new on(e,t);return n.push(r),r}},wt=(n,e)=>{if(n._start===null||e===0||n._searchMarker===null)return null;let t=n._searchMarker.length===0?null:n._searchMarker.reduce((s,o)=>ge(e-s.index)<ge(e-o.index)?s:o),r=n._start,i=0;for(t!==null&&(r=t.p,i=t.index,Ls(t));r.right!==null&&i<e;){if(!r.deleted&&r.countable){if(e<i+r.length)break;i+=r.length;}r=r.right;}for(;r.left!==null&&i>e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return t!==null&&ge(t.index-i)<r.parent.length/Tr?(Rr(t,r,i),t):Vs(n._searchMarker,r,i)},Be=(n,e,t)=>{for(let r=n.length-1;r>=0;r--){let i=n[r];if(t>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){n.splice(r,1);continue}i.p=s,s.marker=!0;}(e<i.index||t>0&&e===i.index)&&(i.index=te(e,i.index+t));}};var _t=(n,e,t)=>{let r=n,i=e.changedParentTypes;for(;Q(i,n,()=>[]).push(t),n._item!==null;)n=n._item.parent;kr(r._eH,t,e);},C=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=lr(),this._dEH=lr(),this._searchMarker=null;}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t;}_copy(){throw B()}clone(){throw B()}_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){dr(this._eH,e);}observeDeep(e){dr(this._dEH,e);}unobserve(e){hr(this._eH,e);}unobserveDeep(e){hr(this._dEH,e);}toJSON(){}},Dr=(n,e,t)=>{n.doc??O(),e<0&&(e=n._length+e),t<0&&(t=n._length+t);let r=t-e,i=[],s=n._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){let o=s.content.getContent();if(o.length<=e)e-=o.length;else {for(let c=e;c<o.length&&r>0;c++)i.push(o[c]),r--;e=0;}}s=s.right;}return i},Ur=n=>{n.doc??O();let e=[],t=n._start;for(;t!==null;){if(t.countable&&!t.deleted){let r=t.content.getContent();for(let i=0;i<r.length;i++)e.push(r[i]);}t=t.right;}return e};var Ke=(n,e)=>{let t=0,r=n._start;for(n.doc??O();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let s=0;s<i.length;s++)e(i[s],t++,n);}r=r.right;}},Or=(n,e)=>{let t=[];return Ke(n,(r,i)=>{t.push(e(r,i,n));}),t},Ms=n=>{let e=n._start,t=null,r=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(),r=0,e=e.right;}let i=t[r++];return t.length<=r&&(t=null),{done:!1,value:i}}}},Ar=(n,e)=>{n.doc??O();let t=wt(n,e),r=n._start;for(t!==null&&(r=t.p,e-=t.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e<r.length)return r.content.getContent()[e];e-=r.length;}},ut=(n,e,t,r)=>{let i=t,s=n.doc,o=s.clientID,c=s.store,a=t===null?e._start:t.right,l=[],d=()=>{l.length>0&&(i=new A(v(o,M(c,o)),i,i&&i.lastId,a,a&&a.id,e,null,new Fe(l)),i.integrate(n,0),l=[]);};r.forEach(u=>{if(u===null)l.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(u);break;default:switch(d(),u.constructor){case Uint8Array:case ArrayBuffer:i=new A(v(o,M(c,o)),i,i&&i.lastId,a,a&&a.id,e,null,new mt(new Uint8Array(u))),i.integrate(n,0);break;case ue:i=new A(v(o,M(c,o)),i,i&&i.lastId,a,a&&a.id,e,null,new yt(u)),i.integrate(n,0);break;default:if(u instanceof C)i=new A(v(o,M(c,o)),i,i&&i.lastId,a,a&&a.id,e,null,new oe(u)),i.integrate(n,0);else throw new Error("Unexpected content type in insert operation")}}}),d();},Lr=()=>de("Length exceeded!"),Vr=(n,e,t,r)=>{if(t>e._length)throw Lr();if(t===0)return e._searchMarker&&Be(e._searchMarker,t,r.length),ut(n,e,null,r);let i=t,s=wt(e,t),o=e._start;for(s!==null&&(o=s.p,t-=s.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&&ie(n,v(o.id.client,o.id.clock+t));break}t-=o.length;}return e._searchMarker&&Be(e._searchMarker,i,r.length),ut(n,e,o,r)},Ns=(n,e,t)=>{let i=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return ut(n,e,i,t)},Mr=(n,e,t,r)=>{if(r===0)return;let i=t,s=r,o=wt(e,t),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&&ie(n,v(c.id.client,c.id.clock+t)),t-=c.length);for(;r>0&&c!==null;)c.deleted||(r<c.length&&ie(n,v(c.id.client,c.id.clock+r)),c.delete(n),r-=c.length),c=c.right;if(r>0)throw Lr();e._searchMarker&&Be(e._searchMarker,i,-s+r);},ft=(n,e,t)=>{let r=e._map.get(t);r!==void 0&&r.delete(n);},yn=(n,e,t,r)=>{let i=e._map.get(t)||null,s=n.doc,o=s.clientID,c;if(r==null)c=new Fe([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:c=new Fe([r]);break;case Uint8Array:c=new mt(r);break;case ue:c=new yt(r);break;default:if(r instanceof C)c=new oe(r);else throw new Error("Unexpected content type")}new A(v(o,M(s.store,o)),i,i&&i.lastId,null,null,e,t,c).integrate(n,0);},wn=(n,e)=>{n.doc??O();let t=n._map.get(e);return t!==void 0&&!t.deleted?t.content.getContent()[t.length-1]:void 0},Nr=n=>{let e={};return n.doc??O(),n._map.forEach((t,r)=>{t.deleted||(e[r]=t.content.getContent()[t.length-1]);}),e},Br=(n,e)=>{n.doc??O();let t=n._map.get(e);return t!==void 0&&!t.deleted};var Bs=(n,e)=>{let t={};return n._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&_e(s,e)&&(t[i]=s.content.getContent()[s.length-1]);}),t},at=n=>(n.doc??O(),or(n._map.entries(),e=>!e[1].deleted)),cn=class extends Se{},an=class n extends C{constructor(){super(),this._prelimContent=[],this._searchMarker=[];}static from(e){let t=new n;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null;}_copy(){return new n}clone(){let e=new n;return e.insert(0,this.toArray().map(t=>t instanceof C?t.clone():t)),e}get length(){return this.doc??O(),this._length}_callObserver(e,t){super._callObserver(e,t),_t(this,e,new cn(this,e));}insert(e,t){this.doc!==null?S(this.doc,r=>{Vr(r,this,e,t);}):this._prelimContent.splice(e,0,...t);}push(e){this.doc!==null?S(this.doc,t=>{Ns(t,this,e);}):this._prelimContent.push(...e);}unshift(e){this.insert(0,e);}delete(e,t=1){this.doc!==null?S(this.doc,r=>{Mr(r,this,e,t);}):this._prelimContent.splice(e,t);}get(e){return Ar(this,e)}toArray(){return Ur(this)}slice(e=0,t=this.length){return Dr(this,e,t)}toJSON(){return this.map(e=>e instanceof C?e.toJSON():e)}map(e){return Or(this,e)}forEach(e){Ke(this,e);}[Symbol.iterator](){return Ms(this)}_write(e){e.writeTypeRef(Gs);}};var ln=class extends Se{constructor(e,t,r){super(e,t),this.keysChanged=r;}},dn=class n extends C{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((r,i)=>{this.set(i,r);}),this._prelimContent=null;}_copy(){return new n}clone(){let e=new n;return this.forEach((t,r)=>{e.set(r,t instanceof C?t.clone():t);}),e}_callObserver(e,t){_t(this,e,new ln(this,e,t));}toJSON(){this.doc??O();let e={};return this._map.forEach((t,r)=>{if(!t.deleted){let i=t.content.getContent()[t.length-1];e[r]=i instanceof C?i.toJSON():i;}}),e}get size(){return [...at(this)].length}keys(){return ot(at(this),e=>e[0])}values(){return ot(at(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return ot(at(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??O(),this._map.forEach((t,r)=>{t.deleted||e(t.content.getContent()[t.length-1],r,this);});}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?S(this.doc,t=>{ft(t,this,e);}):this._prelimContent.delete(e);}set(e,t){return this.doc!==null?S(this.doc,r=>{yn(r,this,e,t);}):this._prelimContent.set(e,t),t}get(e){return wn(this,e)}has(e){return Br(this,e)}clear(){this.doc!==null?S(this.doc,e=>{this.forEach(function(t,r,i){ft(e,i,r);});}):this._prelimContent.clear();}_write(e){e.writeTypeRef(qs);}};var re=(n,e)=>n===e||typeof n=="object"&&typeof e=="object"&&n&&e&&Jn(n,e),Pe=class{constructor(e,t,r,i){this.left=e,this.right=t,this.index=r,this.currentAttributes=i;}forward(){switch(this.right===null&&ne(),this.right.content.constructor){case R: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;}},mr=(n,e,t)=>{for(;e.right!==null&&t>0;){switch(e.right.content.constructor){case R:e.right.deleted||Ee(e.currentAttributes,e.right.content);break;default:e.right.deleted||(t<e.right.length&&ie(n,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},lt=(n,e,t,r)=>{let i=new Map,s=r?wt(e,t):null;if(s){let o=new Pe(s.p.left,s.p,s.index,i);return mr(n,o,t-s.index)}else {let o=new Pe(null,e._start,0,i);return mr(n,o,t)}},Kr=(n,e,t,r)=>{for(;t.right!==null&&(t.right.deleted===!0||t.right.content.constructor===R&&re(r.get(t.right.content.key),t.right.content.value));)t.right.deleted||r.delete(t.right.content.key),t.forward();let i=n.doc,s=i.clientID;r.forEach((o,c)=>{let a=t.left,l=t.right,d=new A(v(s,M(i.store,s)),a,a&&a.lastId,l,l&&l.id,e,null,new R(c,o));d.integrate(n,0),t.right=d,t.forward();});},Ee=(n,e)=>{let{key:t,value:r}=e;r===null?n.delete(t):n.set(t,r);},Pr=(n,e)=>{for(;n.right!==null;){if(!(n.right.deleted||n.right.content.constructor===R&&re(e[n.right.content.key]??null,n.right.content.value)))break;n.forward();}},jr=(n,e,t,r)=>{let i=n.doc,s=i.clientID,o=new Map;for(let c in r){let a=r[c],l=t.currentAttributes.get(c)??null;if(!re(l,a)){o.set(c,l);let{left:d,right:u}=t;t.right=new A(v(s,M(i.store,s)),d,d&&d.lastId,u,u&&u.id,e,null,new R(c,a)),t.right.integrate(n,0),t.forward();}}return o},Jt=(n,e,t,r,i)=>{t.currentAttributes.forEach((p,g)=>{i[g]===void 0&&(i[g]=null);});let s=n.doc,o=s.clientID;Pr(t,i);let c=jr(n,e,t,i),a=r.constructor===String?new se(r):r instanceof C?new oe(r):new ve(r),{left:l,right:d,index:u}=t;e._searchMarker&&Be(e._searchMarker,t.index,a.getLength()),d=new A(v(o,M(s.store,o)),l,l&&l.lastId,d,d&&d.id,e,null,a),d.integrate(n,0),t.right=d,t.index=u,t.forward(),Kr(n,e,t,c);},yr=(n,e,t,r,i)=>{let s=n.doc,o=s.clientID;Pr(t,i);let c=jr(n,e,t,i);e:for(;t.right!==null&&(r>0||c.size>0&&(t.right.deleted||t.right.content.constructor===R));){if(!t.right.deleted)switch(t.right.content.constructor){case R:{let{key:a,value:l}=t.right.content,d=i[a];if(d!==void 0){if(re(d,l))c.delete(a);else {if(r===0)break e;c.set(a,l);}t.right.delete(n);}else t.currentAttributes.set(a,l);break}default:r<t.right.length&&ie(n,v(t.right.id.client,t.right.id.clock+r)),r-=t.right.length;break}t.forward();}if(r>0){let a="";for(;r>0;r--)a+=`
|
|
15
|
+
`;t.right=new A(v(o,M(s.store,o)),t.left,t.left&&t.left.lastId,t.right,t.right&&t.right.id,e,null,new se(a)),t.right.integrate(n,0),t.forward();}Kr(n,e,t,c);},Fr=(n,e,t,r,i)=>{let s=e,o=L();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===R){let l=s.content;o.set(l.key,l);}s=s.right;}let c=0,a=!1;for(;e!==s;){if(t===e&&(a=!0),!e.deleted){let l=e.content;switch(l.constructor){case R:{let{key:d,value:u}=l,p=r.get(d)??null;(o.get(d)!==l||p===u)&&(e.delete(n),c++,!a&&(i.get(d)??null)===u&&p!==u&&(p===null?i.delete(d):i.set(d,p))),!a&&!e.deleted&&Ee(i,l);break}}}e=e.right;}return c},Ks=(n,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;let t=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===R){let r=e.content.key;t.has(r)?e.delete(n):t.add(r);}e=e.left;}},Ps=n=>{let e=0;return S(n.doc,t=>{let r=n._start,i=n._start,s=L(),o=Ye(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case R:Ee(o,i.content);break;default:e+=Fr(t,r,i,s,o),s=Ye(o),r=i;break}i=i.right;}}),e},js=n=>{let e=new Set,t=n.doc;for(let[r,i]of n.afterState.entries()){let s=n.beforeState.get(r)||0;i!==s&&xr(n,t.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===R&&o.constructor!==G&&e.add(o.parent);});}S(t,r=>{_r(n,n.deleteSet,i=>{if(i instanceof G||!i.parent._hasFormatting||e.has(i.parent))return;let s=i.parent;i.content.constructor===R?e.add(s):Ks(r,i);});for(let i of e)Ps(i);});},wr=(n,e,t)=>{let r=t,i=Ye(e.currentAttributes),s=e.right;for(;t>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case oe:case ve:case se:t<e.right.length&&ie(n,v(e.right.id.client,e.right.id.clock+t)),t-=e.right.length,e.right.delete(n);break}e.forward();}s&&Fr(n,s,e.right,i,e.currentAttributes);let o=(e.left||e.right).parent;return o._searchMarker&&Be(o._searchMarker,e.index,-r+t),e},hn=class extends Se{constructor(e,t,r){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,r.forEach(i=>{i===null?this.childListChanged=!0:this.keysChanged.add(i);});}get changes(){if(this._changes===null){let 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){let e=this.target.doc,t=[];S(e,r=>{let i=new Map,s=new Map,o=this.target._start,c=null,a={},l="",d=0,u=0,p=()=>{if(c!==null){let g=null;switch(c){case"delete":u>0&&(g={delete:u}),u=0;break;case"insert":(typeof l=="object"||l.length>0)&&(g={insert:l},i.size>0&&(g.attributes={},i.forEach((_,x)=>{_!==null&&(g.attributes[x]=_);}))),l="";break;case"retain":d>0&&(g={retain:d},qn(a)||(g.attributes=$n({},a))),d=0;break}g&&t.push(g),c=null;}};for(;o!==null;){switch(o.content.constructor){case oe:case ve:this.adds(o)?this.deletes(o)||(p(),c="insert",l=o.content.getContent()[0],p()):this.deletes(o)?(c!=="delete"&&(p(),c="delete"),u+=1):o.deleted||(c!=="retain"&&(p(),c="retain"),d+=1);break;case se:this.adds(o)?this.deletes(o)||(c!=="insert"&&(p(),c="insert"),l+=o.content.str):this.deletes(o)?(c!=="delete"&&(p(),c="delete"),u+=o.length):o.deleted||(c!=="retain"&&(p(),c="retain"),d+=o.length);break;case R:{let{key:g,value:_}=o.content;if(this.adds(o)){if(!this.deletes(o)){let x=i.get(g)??null;re(x,_)?_!==null&&o.delete(r):(c==="retain"&&p(),re(_,s.get(g)??null)?delete a[g]:a[g]=_);}}else if(this.deletes(o)){s.set(g,_);let x=i.get(g)??null;re(x,_)||(c==="retain"&&p(),a[g]=x);}else if(!o.deleted){s.set(g,_);let x=a[g];x!==void 0&&(re(x,_)?x!==null&&o.delete(r):(c==="retain"&&p(),_===null?delete a[g]:a[g]=_));}o.deleted||(c==="insert"&&p(),Ee(i,o.content));break}}o=o.right;}for(p();t.length>0;){let g=t[t.length-1];if(g.retain!==void 0&&g.attributes===void 0)t.pop();else break}}),this._delta=t;}return this._delta}},un=class n extends C{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1;}get length(){return this.doc??O(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(r=>r());}catch(r){console.error(r);}this._pending=null;}_copy(){return new n}clone(){let e=new n;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);let r=new hn(this,e,t);_t(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0);}toString(){this.doc??O();let e="",t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===se&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc!==null?S(this.doc,r=>{let i=new Pe(null,this._start,0,new Map);for(let s=0;s<e.length;s++){let o=e[s];if(o.insert!==void 0){let c=!t&&typeof o.insert=="string"&&s===e.length-1&&i.right===null&&o.insert.slice(-1)===`
|
|
16
|
+
`?o.insert.slice(0,-1):o.insert;(typeof c!="string"||c.length>0)&&Jt(r,this,i,c,o.attributes||{});}else o.retain!==void 0?yr(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&wr(r,i,o.delete);}}):this._pending.push(()=>this.applyDelta(e));}toDelta(e,t,r){this.doc??O();let i=[],s=new Map,o=this.doc,c="",a=this._start;function l(){if(c.length>0){let u={},p=!1;s.forEach((_,x)=>{p=!0,u[x]=_;});let g={insert:c};p&&(g.attributes=u),i.push(g),c="";}}let d=()=>{for(;a!==null;){if(_e(a,e)||t!==void 0&&_e(a,t))switch(a.content.constructor){case se:{let u=s.get("ychange");e!==void 0&&!_e(a,e)?(u===void 0||u.user!==a.id.client||u.type!=="removed")&&(l(),s.set("ychange",r?r("removed",a.id):{type:"removed"})):t!==void 0&&!_e(a,t)?(u===void 0||u.user!==a.id.client||u.type!=="added")&&(l(),s.set("ychange",r?r("added",a.id):{type:"added"})):u!==void 0&&(l(),s.delete("ychange")),c+=a.content.str;break}case oe:case ve:{l();let u={insert:a.content.getContent()[0]};if(s.size>0){let p={};u.attributes=p,s.forEach((g,_)=>{p[_]=g;});}i.push(u);break}case R:_e(a,e)&&(l(),Ee(s,a.content));break}a=a.right;}l();};return e||t?S(o,u=>{e&&tn(u,e),t&&tn(u,t),d();},"cleanup"):d(),i}insert(e,t,r){if(t.length<=0)return;let i=this.doc;i!==null?S(i,s=>{let o=lt(s,this,e,!r);r||(r={},o.currentAttributes.forEach((c,a)=>{r[a]=c;})),Jt(s,this,o,t,r);}):this._pending.push(()=>this.insert(e,t,r));}insertEmbed(e,t,r){let i=this.doc;i!==null?S(i,s=>{let o=lt(s,this,e,!r);Jt(s,this,o,t,r||{});}):this._pending.push(()=>this.insertEmbed(e,t,r||{}));}delete(e,t){if(t===0)return;let r=this.doc;r!==null?S(r,i=>{wr(i,lt(i,this,e,!0),t);}):this._pending.push(()=>this.delete(e,t));}format(e,t,r){if(t===0)return;let i=this.doc;i!==null?S(i,s=>{let o=lt(s,this,e,!1);o.right!==null&&yr(s,this,o,t,r);}):this._pending.push(()=>this.format(e,t,r));}removeAttribute(e){this.doc!==null?S(this.doc,t=>{ft(t,this,e);}):this._pending.push(()=>this.removeAttribute(e));}setAttribute(e,t){this.doc!==null?S(this.doc,r=>{yn(r,this,e,t);}):this._pending.push(()=>this.setAttribute(e,t));}getAttribute(e){return wn(this,e)}getAttributes(){return Nr(this)}_write(e){e.writeTypeRef(Js);}};var Ne=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??O();}[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===gt||t.constructor===je)&&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})}},je=class n extends C{constructor(){super(),this._prelimContent=[];}get firstChild(){let 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 n}clone(){let e=new n;return e.insert(0,this.toArray().map(t=>t instanceof C?t.clone():t)),e}get length(){return this.doc??O(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Ne(this,e)}querySelector(e){e=e.toUpperCase();let r=new Ne(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),ee(new Ne(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){_t(this,e,new fn(this,t,e));}toString(){return Or(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},r){let i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),Ke(this,s=>{i.insertBefore(s.toDOM(e,t,r),null);}),i}insert(e,t){this.doc!==null?S(this.doc,r=>{Vr(r,this,e,t);}):this._prelimContent.splice(e,0,...t);}insertAfter(e,t){if(this.doc!==null)S(this.doc,r=>{let i=e&&e instanceof C?e._item:e;ut(r,this,i,t);});else {let r=this._prelimContent,i=e===null?0:r.findIndex(s=>s===e)+1;if(i===0&&e!==null)throw de("Reference item not found");r.splice(i,0,...t);}}delete(e,t=1){this.doc!==null?S(this.doc,r=>{Mr(r,this,e,t);}):this._prelimContent.splice(e,t);}toArray(){return Ur(this)}push(e){this.insert(this.length,e);}unshift(e){this.insert(0,e);}get(e){return Ar(this,e)}slice(e=0,t=this.length){return Dr(this,e,t)}forEach(e){Ke(this,e);}_write(e){e.writeTypeRef(zs);}};var gt=class n extends je{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map;}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r);}),this._prelimAttrs=null;}_copy(){return new n(this.nodeName)}clone(){let e=new n(this.nodeName),t=this.getAttributes();return Gn(t,(r,i)=>{typeof r=="string"&&e.setAttribute(i,r);}),e.insert(0,this.toArray().map(r=>r instanceof C?r.clone():r)),e}toString(){let e=this.getAttributes(),t=[],r=[];for(let c in e)r.push(c);r.sort();let i=r.length;for(let c=0;c<i;c++){let a=r[c];t.push(a+'="'+e[a]+'"');}let s=this.nodeName.toLocaleLowerCase(),o=t.length>0?" "+t.join(" "):"";return `<${s}${o}>${super.toString()}</${s}>`}removeAttribute(e){this.doc!==null?S(this.doc,t=>{ft(t,this,e);}):this._prelimAttrs.delete(e);}setAttribute(e,t){this.doc!==null?S(this.doc,r=>{yn(r,this,e,t);}):this._prelimAttrs.set(e,t);}getAttribute(e){return wn(this,e)}hasAttribute(e){return Br(this,e)}getAttributes(e){return e?Bs(this,e):Nr(this)}toDOM(e=document,t={},r){let i=e.createElement(this.nodeName),s=this.getAttributes();for(let o in s){let c=s[o];typeof c=="string"&&i.setAttribute(o,c);}return Ke(this,o=>{i.appendChild(o.toDOM(e,t,r));}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(Hs),e.writeKey(this.nodeName);}};var fn=class extends Se{constructor(e,t,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i);});}};var pt=class{constructor(e,t){this.id=e,this.length=t;}get deleted(){throw B()}mergeWith(e){return !1}write(e,t,r){throw B()}integrate(e,t){throw B()}},Fs=0,G=class extends pt{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),Cr(e.doc.store,this);}write(e,t){e.writeInfo(Fs),e.writeLen(this.length-t);}getMissing(e,t){return null}},mt=class n{constructor(e){this.content=e;}getLength(){return 1}getContent(){return [this.content]}isCountable(){return !0}copy(){return new n(this.content)}splice(e){throw B()}mergeWith(e){return !1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content);}getRef(){return 3}};var gn=class n{constructor(e){this.len=e;}getLength(){return this.len}getContent(){return []}isCountable(){return !1}copy(){return new n(this.len)}splice(e){let t=new n(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){vr(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}};var Ws=(n,e)=>new ue({guid:n,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1}),yt=class n{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;let 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 n(Ws(this.doc.guid,this.opts))}splice(e){throw B()}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}};var ve=class n{constructor(e){this.embed=e;}getLength(){return 1}getContent(){return [this.embed]}isCountable(){return !0}copy(){return new n(this.embed)}splice(e){throw B()}mergeWith(e){return !1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed);}getRef(){return 5}};var R=class n{constructor(e,t){this.key=e,this.value=t;}getLength(){return 1}getContent(){return []}isCountable(){return !1}copy(){return new n(this.key,this.value)}splice(e){throw B()}mergeWith(e){return !1}integrate(e,t){let r=t.parent;r._searchMarker=null,r._hasFormatting=!0;}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value);}getRef(){return 6}};var $s=Ae("node_env")==="development",Fe=class n{constructor(e){this.arr=e,$s&&Bt(e);}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return !0}copy(){return new n(this.arr)}splice(e){let t=new n(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){let r=this.arr.length;e.writeLen(r-t);for(let i=t;i<r;i++){let s=this.arr[i];e.writeAny(s);}}getRef(){return 8}};var se=class n{constructor(e){this.str=e;}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return !0}copy(){return new n(this.str)}splice(e){let t=new n(this.str.slice(e));this.str=this.str.slice(0,e);let r=this.str.charCodeAt(e-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"\uFFFD",t.str="\uFFFD"+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}};var Gs=0,qs=1,Js=2,Hs=3,zs=4;var oe=class n{constructor(e){this.type=e;}getLength(){return 1}getContent(){return [this.type]}isCountable(){return !0}copy(){return new n(this.type._copy())}splice(e){throw B()}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(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.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(r=>{for(;r!==null;)r.gc(e,!0),r=r.left;}),this.type._map=new Map;}write(e,t){this.type._write(e);}getRef(){return 7}};var Wr=(n,e,t)=>{let{client:r,clock:i}=e.id,s=new A(v(r,i+t),e,v(r,i+t-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=v(e.redone.client,e.redone.clock+t)),e.right=s,s.right!==null&&(s.right.left=s),n._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=t,s};var A=class n extends pt{constructor(e,t,r,i,s,o,c,a){super(e,a.getLength()),this.origin=r,this.left=t,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=c,this.redone=null,this.content=a,this.info=this.content.isCountable()?2:0;}set marker(e){(this.info&8)>0!==e&&(this.info^=8);}get marker(){return (this.info&8)>0}get keep(){return (this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1);}get countable(){return (this.info&2)>0}get deleted(){return (this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4);}markDeleted(){this.info|=4;}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=M(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=M(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===be&&this.id.client!==this.parent.client&&this.parent.clock>=M(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=ur(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=ie(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===G||this.right&&this.right.constructor===G)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===n&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===n&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===be){let r=qt(t,this.parent);r.constructor===G?this.parent=null:this.parent=r.content.type;}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=ur(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 r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;let s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),ct(this.origin,i.origin)){if(i.id.client<this.id.client)r=i,s.clear();else if(ct(this.rightOrigin,i.rightOrigin))break}else if(i.origin!==null&&o.has(qt(e.doc.store,i.origin)))s.has(qt(e.doc.store,i.origin))||(r=i,s.clear());else break;i=i.right;}this.left=r;}if(this.left!==null){let r=this.left.right;this.right=r,this.left.right=this;}else {let r;if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start,this.parent._start=this;this.right=r;}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),Cr(e.doc.store,this),this.content.integrate(e,this),gr(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e);}else new G(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&&ct(e.origin,this.lastId)&&this.right===e&&ct(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)){let t=this.parent._searchMarker;return t&&t.forEach(r=>{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.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){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),vr(e.deleteSet,this.id.client,this.id.clock,this.length),gr(e,t,this.parentSub),this.content.delete(e);}}gc(e,t){if(!this.deleted)throw ne();this.content.gc(e),t?Ds(e,this,new G(this.id,this.length)):this.content=new gn(this.length);}write(e,t){let r=t>0?v(this.id.client,this.id.clock+t-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&31|(r===null?0:128)|(i===null?0:64)|(s===null?0:32);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){let c=this.parent;if(c._item!==void 0){let a=c._item;if(a===null){let l=Is(c);e.writeParentInfo(!0),e.writeString(l);}else e.writeParentInfo(!1),e.writeLeftID(a.id);}else c.constructor===String?(e.writeParentInfo(!0),e.writeString(c)):c.constructor===be?(e.writeParentInfo(!1),e.writeLeftID(c)):ne();s!==null&&e.writeString(s);}this.content.write(e,t);}};var $r=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Gr="__ $YJS$ __";$r[Gr]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");$r[Gr]=!0;var We=n=>Promise.reject("unimplemented method GetVoiceSign"),_n=(n,e={},t=[])=>({command:n,front_request_id:Z(),data:{...e,to_user_ids:Array.isArray(t)?t:[t]}}),qr=()=>{window?.__Realsee_Live__&&(window?.__Realsee_Live__?.dispose?.(),window.__Realsee_Live__=null);},bt=class extends N{_options={};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}keyframes=new N;_yDoc;_buildInData;constructor(e){super(),m.info("Initializing Live instance with options:",e),this._addLiveControllerEventListeners(),this._yDoc=new ue({guid:Z()}),this._buildInData={keyframes:this._yDoc.getMap("keyframes")},this._initializeKeyframesObservers(),this._initializeOptions(e),this._autoConnect(),this._debugSetup();}get _buildInKeyframes(){return this._buildInData.keyframes}get snapshot(){return this._buildInData.keyframes.toJSON()}_initializeKeyframesObservers=()=>{this._buildInKeyframes.observe(this._handleKeyframesChange);};_handleKeyframesChange=e=>{let{transaction:t,target:r,changes:i}=e;if(r===this._buildInKeyframes)if(t.origin.triggerUserId===this.selfInfo?.id){let s=_n("KEYFRAME_SYNC",this.snapshot,void 0);try{this._controller.sendMessage(s);}catch(o){m.error("Failed to send keyframe sync message:",o);}}else i.keys.forEach((s,o)=>{let c=s.oldValue,a=this.getFramesByKey(o),l=t.origin.frontRequestId;this.keyframes.emit(o,a,c,l);}),i.keys.size!==0&&this.emit("keyframes",this.snapshot,t.origin.frontRequestId);};getFramesByKey=e=>this.snapshot[e];sendKeyframe=(e,t)=>this.state!==1?(m.warn("Attempted to send keyframe while connection is not open"),!1):(this._yDoc.transact(()=>{this._buildInKeyframes.set(e,t);},{triggerUserId:this.selfInfo?.id,frontRequestId:""}),!0);get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}_controller=new ze;_initializeOptions(e){this._options=Object.assign({initialMicroStatus:"OPEN"},e),this._options.jsBridge=this._initializeJsBridge(e),this._options.getVoiceSign=e.getVoiceSign??We,this._options.autoPlayConfirm=e.autoPlayConfirm,this._options.rtc=this._initializeRTC(e);}_initializeJsBridge(e){if(e.jsBridge)return e.jsBridge;if(e.useBuiltInJsBridge)return new Xs__default.default}_initializeRTC(e){if(e.rtc)return e.rtc;if(e.rtcType)return this._createBuiltInRTC(e);if(e.useBuiltInRTC)return this._createDefaultRTC(e)}_createBuiltInRTC(e){if(!e.getVoiceSign){m.error("GetVoiceSign method must be passed when using built-in RTC instances");return}switch(e.rtcType){case"RealseeVRWebViewRTC":return this._createVRWebViewRTC();case"RealseeBrowserChimeRTC":return new fe({getVoiceSign:this._options.getVoiceSign??We,logLevel:e.__debug__?0:1});case"RealseeBrowserRTC":return this._createBrowserRTC();default:m.error("unknown built-in RTC type");return}}_createVRWebViewRTC(){if(this._options.jsBridge)return new Ie({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign??We});m.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");}_createBrowserRTC(){if(!this._options.autoPlayConfirm){m.error("autoPlayConfirm method must be passed when using built-in RealseeBrowserRTC instances");return}return new xe({getVoiceSign:this._options.getVoiceSign??We,autoPlayConfirm:this._options.autoPlayConfirm})}_createDefaultRTC(e){if(!e.getVoiceSign){m.error("GetVoiceSign method must be passed when using built-in RTC instances");return}if(this._options.jsBridge){if(In&&(kn||Cn)||xn)return this._createVRWebViewRTC();{let t=this._options.getVoiceSign??We;return e.builtInRTCType==="chime"?new fe({getVoiceSign:t}):this._createBrowserRTC()}}else {m.error("jsBridge instance must be passed when using built-in RTC instances");return}}_autoConnect(){this._options.url&&this._options.getTicket&&this.connect();}_debugSetup(){this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this});}_addLiveControllerEventListeners=()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage);};_removeLiveControllerEventListeners=()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage);};_handleStateChange=(e,t)=>{m.info(`State changed from ${t} to ${e}`),this.emit("stateChange",e,t);};_handleMessage=async e=>{if(m.debug("Received message:",e),typeof e=="object"){let{command:t,data:r={},frontRequestId:i,code:s,message:o,triggerUserId:c}=e;if(s==="SUCCESS")switch(t){case"SELF_USER_INFO":{let a=r;Tn(this.selfInfo,a,{deep:!0})||(this._buildInData.selfInfo=a,this.emit("selfInfoUpdate",this._buildInData.selfInfo,i));break}case"ROOM_INFO":{let a=r;this._buildInData.roomInfo=Object.assign({},a);let l=a.last_frame||{};this._yDoc.transact(()=>{for(let d in l)this._buildInKeyframes.set(d,l[d]);},{triggerUserId:"readyKeyframeSync",frontRequestId:i}),this.emit("readyKeyframeSync",a.last_frame||{});break}case"RTC_INFO":{m.info("RTC info updated:",r);let{voice_id:a,type:l}=r;if(this._buildInData.rtcInfo={voiceId:a,type:l},this.$RTC?.joined)m.warn("\u5DF2\u52A0\u5165\u8BED\u97F3\u623F\u95F4\uFF0C\u65E0\u9700\u91CD\u590D\u52A0\u5165\uFF01");else if(await this.$RTC?.join({voiceId:a,userId:this.selfInfo?.id||"",roomId:this.roomInfo?.info.room_code,type:l})){let u=this._options.initialMicroStatus??"OPEN";await this.toggleMicro(u==="OPEN");}else m.error("\u52A0\u5165\u8BED\u97F3\u623F\u95F4\u5931\u8D25");break}case"USER_LIST":{let a=r;this._buildInData.userList=a,this.emit("userListUpdate",this.userList,i);break}case"CUSTOM_EVENT":{let a=r;this.emit("broadcast",a,i);break}case"KEYFRAME_SYNC":{let a=r;if(c===this.selfInfo?.id)return;this._yDoc.transact(()=>{for(let l in a)this._buildInKeyframes.set(l,a[l]);},{triggerUserId:c,frontRequestId:i});break}case"BUILTIN_MSG":{let a=r;this.emit("builtinEvent",a),a.event_type==="user_change"&&this.emit("userChange",a),a.event_type==="room_change"&&this.emit("roomChange",a),a.event_type==="user_change"&&a.action==="change_micro_status"&&await this.toggleMicro(a.data.status==="OPEN"),a.event_type==="room_change"&&a.action==="close"&&await this._exit();break}case"USER_KICK_OUT":{this.emit("kickOut");break}default:m.warn("Unknown command received:",t);}else m.error("Error in message:",o),this.emit("error",e);}};_clearLiveData=()=>{this._buildInKeyframes.clear(),this._buildInData={keyframes:this._yDoc.getMap("keyframes")};};connect=async(e={})=>{if(m.info("Attempting to connect with options:",e),this._options.url=e.url??this._options.url??"",this._options.getTicket=e.getTicket??this._options.getTicket,this._options.initialMicroStatus=e.rtcMicStatus??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");let t=this.state;if(t===0||t===1)if(e.force)await this._controller.close("force close by connect").catch(console.warn);else return new Error("\u5DF2\u6709Live\u5B9E\u4F8B\u6B63\u5728\u8FDE\u63A5\u4E2D\uFF0C\u8BF7\u52FF\u91CD\u590D\u8FDE\u63A5\uFF01");this._clearLiveData();try{let r=await this._options.getTicket(),i=vn(this._options.url,{ticket:r,force:+!!e.force});return this._controller.open(i),m.info("Connection established successfully"),!0}catch(r){return m.error("Failed to connect:",r),new Error("Failed to connect")}};_exit=async()=>{this._clearLiveData();try{await this.$RTC?.quit();}catch(e){m.warn(e);}return this.state!==1?!0:await this._controller.close()};exit=async()=>this.close();close=async()=>{await this._controller.readyClose();try{await this.$RTC?.quit();}catch(e){m.warn(e);}await this.updateStatus("room_change","close",{});};dispose=async()=>(this._removeLiveControllerEventListeners(),this._clearLiveData(),await this._controller.dispose());async updateStatus(e,t,r,i){if(this.state!==1)return !1;let s=Object.assign({event_type:e,action:t},{data:r}),o=_n("BUILTIN_MSG",s,i);try{return this._controller.sendMessage(o),!0}catch(c){return m.error(c),!1}}setSelfInfo=async e=>await this.updateStatus("user_change","change_info",e);broadcast(e,t,r){return this.state!==1?!1:new Promise((i,s)=>{let o=_n("CUSTOM_EVENT",e,t),c=o.front_request_id,a=r?setTimeout(()=>{s(new Error("RESPONSE TIMEOUT")),this.off("broadcast",l);},r):void 0,l=(d,u)=>{u===c&&(a&&clearTimeout(a),this.off("broadcast",l),i(d));};this.on("broadcast",l);try{this._controller.sendMessage(o);}catch(d){s(d);}})}toggleMicro=async e=>{if(!this.selfInfo?.permission?.control_own_micro)return !1;let t=await this.$RTC?.toggleMicro(e);return t&&await this.updateStatus("user_change","change_micro_status",{status:e?"OPEN":"CLOSE"},[]),t};forbidMicro=async(e,t)=>typeof this._options.canForbidUserMicro=="function"&&!this._options.canForbidUserMicro(t)||!this.selfInfo?.permission?.control_other_micro?!1:await this.updateStatus("user_change","change_micro_status",{status:e},t);forbidSync=async(e,t)=>typeof this._options.canForbidUserSync=="function"&&!this._options.canForbidUserSync(t)||!this.selfInfo?.permission?.control_other_sync?!1:await this.updateStatus("user_change","change_permission",{sync_frame:e},t);kick=async e=>typeof this._options.canForbidUserKick=="function"&&!this._options.canForbidUserKick(e)||!this.selfInfo?.permission?.change_other_status?!1:await this.updateStatus("user_change","change_status",{status:"KICK_OUT"},e);getSnapshotForKey(e){return this.snapshot[e]}};var Jr=n=>(qr(),new bt(n));function qa(n){let e=U.createContext(null),t=Jr(n),r=t.jsBridge,i=h=>U__default.default.createElement(e.Provider,{value:t},h.children),s=()=>{let h=U__default.default.useContext(e);if(!h)throw new Error("LiveProvider never found.");return h},o=()=>t,c=()=>t.$RTC,a=()=>c(),l=()=>async h=>await t.connect(h);function d(h,b,I=[]){let y=s(),E=[y,name,...I],D=()=>y.keyframes.off(h,b);return U__default.default.useEffect(()=>(y.keyframes.on(h,b),D),E),D}function u(){let h=s(),b=U.useCallback(async k=>{await h.connect(k);},[h]),I=U.useCallback(k=>{h.toggleMicro(k);},[h]),y=U.useCallback(async(k,q,vt=0)=>{await h.broadcast(k,q,vt);},[h]),E=U.useCallback(async()=>{await h.exit();},[h]),D=U.useCallback(async k=>{await h.kick(k);},[h]),Y=U.useCallback(async(k,q=[])=>{await h.forbidMicro(k,q);},[h]),$e=U.useCallback((k,q=[])=>{h.forbidSync(k,q);},[h]),St=U.useCallback(k=>h.getFramesByKey(k),[h]),Zr=U.useCallback((k,q)=>{h.sendKeyframe(k,q);},[h]),Qr=U.useCallback(k=>{h.setSelfInfo(k);},[h]),ei=U.useCallback((k,q,vt,ti)=>{h.updateStatus(k,q,vt,ti);},[h]);return {connect:b,broadcast:y,exit:E,kick:D,toggleMicro:I,forbidMicro:Y,forbidSync:$e,sendKeyframe:Zr,getFramesByKey:St,setSelfInfo:Qr,updateStatus:ei}}function p(h){let b=s(),[I,y]=U__default.default.useState(b.getFramesByKey(h));U__default.default.useEffect(()=>{let D=St=>y(St),Y=h,$e=D;return b.keyframes.on(Y,$e),()=>b.keyframes.off(Y,$e)},[b]);let E=U__default.default.useCallback(D=>b.sendKeyframe(h,D),[b]);return [I,E]}function g(h,b,I=[]){let y=s(),E=()=>y.off(h,b),D=[y,h,...I];return U__default.default.useEffect(()=>(y.on(h,b),E),D),E}function _(){let h=s(),[b,I]=U__default.default.useState(h.state);return U__default.default.useEffect(()=>{let y=E=>I(E);return h.on("stateChange",y),()=>h.off("stateChange",y)},[h]),b}function x(){let h=s();return {join:Y=>h.$RTC.join(Y),quit:()=>h.$RTC.quit(),shock:()=>h.$RTC.shock?.(),toggleMicro:Y=>h.$RTC.toggleMicro(Y),detectMicro:()=>h.$RTC.detectMicro()}}function Hr(h,b,I=[]){let y=s(),E=()=>y.$RTC.off(h,b),D=[y,h,...I];return U__default.default.useEffect(()=>(y.$RTC.on(h,b),E),D),E}function zr(){let h=s(),[b,I]=U__default.default.useState(h.selfInfo||{}),y=D=>I(D);U__default.default.useEffect(()=>(h.on("selfInfoUpdate",y),()=>h.off("selfInfoUpdate",y)),[h]);let E=U__default.default.useCallback(async D=>await h.setSelfInfo(D),[h]);return [b,E]}function Yr(){let h=s(),[b,I]=U__default.default.useState(h.snapshot);return U__default.default.useEffect(()=>{let y=E=>I(E);return h.on("keyframes",y),()=>h.off("keyframes",y)},[h]),b}function Xr(){let h=s(),[b,I]=U__default.default.useState(h.userList),y=E=>I(E);return U__default.default.useEffect(()=>(h.on("userListUpdate",y),()=>h.off("userListUpdate",y)),[h]),b}return {live:t,jsBridge:r,LiveProvider:i,unsafe__useLiveInstance:o,unsafe__useRTCInstance:a,useConnect:l,useKeyframe:p,useKeyframeUpdateCallback:d,useLiveAction:u,useLiveEventCallback:g,useLiveState:_,useRTCAction:x,useRTCEventCallback:Hr,useSelfInfo:zr,useKeyframesSnapshot:Yr,useUserList:Xr}}console.log(`%c${process.env.__REALSEE_LIVE_VERSION__}`,"background: #237804; color: white; padding: 2px 4px; border-radius: 4px;");
|
|
64
17
|
|
|
65
|
-
var le=Symbol("$$REALSEE_LIVE_EVENT$$");function ve(i){return i[le]||(i[le]={}),i[le]}function In(i){i[le]?.length||delete i[le];}var j=class{hasListener(e){let t=ve(this);return t&&t[e]&&t[e].length>0}on(e,t,n){let r=ve(this);return r[e]||(r[e]=[]),r[e].push([t,n||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){let n=ve(this);if(!e){In(this);return}if(n[e]||(n[e]=[]),t===void 0){n[e].length=0;return}let r=n[e].findIndex(s=>s[0]===t);r!==-1&&n[e].splice(r,1);}emit(e,...t){let n=!1,s=ve(this)[e]||[];for(let o of s.slice()){let[c,a=!1]=o,l=c(...t);a&&this.off(e,c),l===!1&&(n=!0);}return n}};var G=class extends j{};var Tn=(n=>(n.RealseeBrowserRTC="RealseeBrowserRTC",n.RealseeVRWebViewRTC="RealseeVRWebViewRTC",n.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",n))(Tn||{}),Rn=(t=>(t.RealseeXTRTC="trtc",t.RealseeXChimeRTC="chime",t))(Rn||{});var Dn=()=>{let i=new Date,e=i.getFullYear(),t=(i.getMonth()+1).toString().padStart(2,"0"),n=i.getDate().toString().padStart(2,"0"),r=i.getHours().toString().padStart(2,"0"),s=i.getMinutes().toString().padStart(2,"0"),o=i.getSeconds().toString().padStart(2,"0"),c=i.getMilliseconds().toString().padStart(3,"0");return `[${e}-${t}-${n} ${r}:${s}:${o}.${c}]`};var de=(i,e=[])=>{let t=`Realsee Live ${Dn()} <${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);}},On={log:(...i)=>de("LOG",i),info:(...i)=>de("INFO",i),error:(...i)=>de("ERROR",i),warn:(...i)=>de("WARN",i),debug:(...i)=>de("DEBUG",i)},m=On;function z(){return ((1+Math.random())*65536|0).toString(16).substring(1)}function Y(){return [z(),z(),"4"+z().substring(0,3),z(),z(),z()+z()+z()].join("-").toLowerCase()}var he=class extends G{type="RealseeBrowserRTC";joined=!1;micro=!1;voiceId="";_getVoiceSign=()=>{throw new Error("\u65B9\u6CD5 getVoiceSign \u672A\u5B9E\u73B0")};_autoPlayConfirm;checkRequirement=()=>Je__default.default.checkSystemRequirements();$dom=document.createElement("div");_trtc={client:null,stream:null};constructor(e){super(),this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initParentDom();}_initParentDom(){this.$dom.id=`rs-rtc-${Y()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom);}join=async e=>{this.emit("joinWillStart");let t=await this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=Je__default.default.createClient({mode:"rtc",...t,enableAutoPlayDialog:typeof this._autoPlayConfirm!="function"}),this._trtc.client?.enableAudioVolumeEvaluation(),this._registerRtcEvent();let n=await new Promise(r=>{this._trtc.client?.join({roomId:Number(e.voiceId)}).then(()=>r(!0)).catch(()=>r(!1));});return this.joined=n,n?(this._trtc.stream=Je__default.default.createStream({userId:t.userId,audio:!0,video:!1}),n=await new Promise(r=>{this._trtc.stream?.initialize().then(()=>r(!0)).catch(()=>r(!1));}),n=await new Promise(r=>{this._trtc.client?.publish(this._trtc.stream).then(()=>r(!0)).catch(()=>r(!1));}),this.joined=n,this.joined&&this.emit("joined"),n):!1};quit(){return new Promise(async e=>{this.joined=!1,this._trtc.stream&&(await this._trtc.client?.unpublish(this._trtc.stream),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),this._trtc.client?.leave().then(()=>this._trtc.client=null).then(()=>e(!0)).catch(()=>e(!1)),e(!0);})}detectMicro(){return new Promise(e=>{let t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then(()=>e(!0)).catch(n=>{m.error(n.message),e(!1);});}catch(n){console.error(n),e(!1);}})}toggleMicro(e){return Promise.resolve((e?this._trtc?.stream?.unmuteAudio():this._trtc?.stream?.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){this._trtc.client?.on("stream-added",this._handleStreamAdded),this._trtc.client?.on("stream-subscribed",this._handleStreamSubscribed),this._trtc.client?.on("audio-volume",e=>this.emit("userVolumes",e.result.map(({userId:t,audioVolume:n})=>({userId:t,audioVolume:n})))),this._trtc.client?.on("error",e=>this.emit("error",e));}_handleStreamAdded=e=>{let t=e.stream;console.log("\u8FDC\u7AEF\u6D41\u589E\u52A0: "+t.getId()),this._trtc.client?.subscribe(t);};_handleStreamSubscribed=e=>{let t=e.stream;console.log("\u8FDC\u7AEF\u6D41\u8BA2\u9605\u6210\u529F\uFF1A"+t.getId());let r=`rs-rtc-remote_stream-${t.getId()}`,s=document.createElement("div");s.id=r,this.$dom.appendChild(s),typeof this._autoPlayConfirm=="function"?(t.play(r).catch(o=>{}),t.on("error",o=>{if(o.getCode()===16451){let a=()=>t.resume();this._autoPlayConfirm({onConfirm:a});}})):t.play(r);}};var ne=class extends G{type="RealseeBrowserChimeRTC";joined=!1;micro=!1;voiceId="";userId="";logger;deviceController;meetingSession;audioInput;audioOutput;deviceChangeObserver={};audioVideoObserver={};audioMixObserver;_getVoiceSign=()=>{throw new Error("\u65B9\u6CD5 getVoiceSign \u672A\u5B9E\u73B0")};_autoPlayConfirm;$dom=document.createElement("div");$audio=document.createElement("audio");constructor(e){super(),this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initDom(),this.logger=new amazonChimeSdkJs.ConsoleLogger("WebRTCLogger",e.logLevel||amazonChimeSdkJs.LogLevel.INFO),this.deviceController=new amazonChimeSdkJs.DefaultDeviceController(this.logger),this.initObservers();}_initDom=()=>{this.$audio.id=`rs-rtc-${Y()}`,this.$dom.id=`rs-rtc-${Y()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom);};initObservers=()=>{this.deviceChangeObserver={audioInputsChanged:e=>{this.logger.info(`audioInputsChanged ${typeof e}`),e?.forEach(t=>{this.logger.info(`Device ID: ${t.deviceId} Microphone: ${t.label}`);});},audioOutputsChanged:e=>{this.logger.info(`audioOutputsChanged ${typeof e}`),e?.forEach(t=>{this.logger.info(`Device ID: ${t.deviceId} Speaker: ${t.label}`);});},audioInputMuteStateChanged:(e,t)=>{this.logger.info(`Device ${e.toString()} ${t?"is muted in hardware":"is not muted"}`);}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started");},audioVideoDidStop:e=>{this.logger.info(`Stopped with a session status code: ${e.statusCode()}`);},audioVideoDidStartConnecting:e=>{e&&this.logger.info("Attempting to reconnect");}},this.audioMixObserver={meetingAudioStreamBecameActive:e=>{if(this.$audio.paused){let t=()=>this.$audio.play().then(()=>{}).catch(n=>{if(m.error("\u64AD\u653E\u8FDC\u7AEF\u6D41\u5931\u8D25\uFF01",n),typeof this._autoPlayConfirm=="function"){let r=()=>t();this._autoPlayConfirm({onConfirm:r});}});t();}},meetingAudioStreamBecameInactive:e=>{}};};async join(e){return new Promise(async(t,n)=>{this.emit("joinWillStart");try{let{sdkAppId:r,userId:s,roomId:o,userSig:c}=await this._getVoiceSign({...e,roomId:e.roomId||0});this.userId=s;let{attendence:a,vendor_wrapper:l}=JSON.parse(decodeURIComponent(c)),d=new amazonChimeSdkJs.MeetingSessionConfiguration({Meeting:l},{Attendee:{ExternalUserId:a.external_user_id,AttendeeId:a.attendee_id,JoinToken:a.join_token}});this.meetingSession=new amazonChimeSdkJs.DefaultMeetingSession(d,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);let f={audioVideoDidStart:()=>{this.meetingSession?.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),t(!0);},audioVideoDidStop:()=>{this.joined=!1,t(!1);}};this.meetingSession.audioVideo.addObserver(f),this.audioMixObserver&&this.meetingSession.audioVideo.addAudioMixObserver(this.audioMixObserver),this.meetingSession.audioVideo.setDeviceLabelTrigger(async()=>await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}));try{let p=await this.meetingSession.audioVideo.listAudioInputDevices();m.info("audioInputDevices ===>",p);let g=p[0]?.deviceId||"default";await this.meetingSession.audioVideo.startAudioInput(g);}catch(p){m.error(`\u8BBE\u7F6E\u8BED\u97F3\u8F93\u5165\u8BBE\u5907\u5931\u8D25:${p.message}`);}try{let p=await this.meetingSession.audioVideo.listAudioOutputDevices();m.info("audioOutputDevices ===>",p);let g=p[0]?.deviceId||"default";await this.meetingSession.audioVideo.chooseAudioOutput(g);}catch(p){m.error(`\u8BBE\u7F6E\u8BED\u97F3\u8F93\u51FA\u8BBE\u5907\u5931\u8D25:${p.message}`);}this.meetingSession.audioVideo.start();}catch(r){this.emit("error",r),this.logger.error(r.message),t(!1);}})}_registerRtcEvent=()=>{let e=this.meetingSession?.configuration?.credentials?.attendeeId||"";if(e){let t=new Map,n=()=>{let r=[];return t.forEach((s,o)=>{r.push({userId:s.userId,volume:s.muted||s.signalStrength===0||!s.volume?0:s.volume});}),r};this.meetingSession?.audioVideo.realtimeSubscribeToAttendeeIdPresence((r,s,o)=>{if(!s){t.delete(r),this.emit("userVolumes",n());return}this.meetingSession?.audioVideo.realtimeSubscribeToVolumeIndicator(r,(c,a,l,d)=>{new amazonChimeSdkJs.DefaultModality(c).base()===c&&(t.set(c,{userId:o||c,volume:a,muted:l,signalStrength:d}),this.emit("userVolumes",n()));});}),this.meetingSession?.audioVideo.realtimeSubscribeToVolumeIndicator(e,(r,s,o,c)=>{new amazonChimeSdkJs.DefaultModality(r).base()===r&&c!==null&&c!==1&&this.emit("weakNetwork");}),this.meetingSession?.audioVideo.realtimeSubscribeToFatalError(r=>this.emit("error",r));}};quit(){return this.joined?new Promise((e,t)=>{this.joined=!1;let n={audioVideoDidStop:async r=>{let s=r.statusCode();this.meetingSession?.deviceController.destroy(),s===amazonChimeSdkJs.MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${s}`),e(!0));}};this.meetingSession?.audioVideo.addObserver(n),this.meetingSession?.audioVideo.stop();}):Promise.resolve(!0)}async detectMicro(){return new Promise(e=>{let t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then(()=>e(!0)).catch(()=>e(!1));}catch(n){this.logger.error(n.message),e(!1);}})}async toggleMicro(e){e?this.meetingSession?.audioVideo.realtimeUnmuteLocalAudio():this.meetingSession?.audioVideo.realtimeMuteLocalAudio();let t=this.meetingSession?.audioVideo.realtimeIsLocalAudioMuted();return t!==void 0?e!==t:!1}shock(){throw new Error("Method not implemented.")}};var Kn=(s=>(s[s.Success=0]="Success",s[s.Failure=1]="Failure",s[s.ReJoin=2]="ReJoin",s[s.NoMicroPermission=3]="NoMicroPermission",s[s.Unknown=500]="Unknown",s))(Kn||{});var ue=class extends G{type="RealseeVRWebViewRTC";joined=!1;micro=!1;voiceId="";_joinOptions=null;options;get jsBridge(){return this.options.jsBridge}constructor({jsBridge:e,getVoiceSign:t}){super(),this.options={jsBridge:e,getVoiceSign:t},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);}handleUserVolumes=e=>{this.emit("userVolumes",e);};handleWeakNetwork=e=>{e&&this.emit("weakNetwork");};join=async e=>{this._joinOptions=e,this.emit("joinWillStart");let{sdkAppId:t,userId:n,userSig:r}=await this.getVoiceSignOrEmitError(e);return !t||!n||!r?!1:(this.type=e.type,this.jsBridge.webViewType==="WxMiniProgramWebView"?this.handleWxMiniProgramWebViewJoin({sdkAppId:t,userId:n,userSig:r,voiceId:e.voiceId}):this.handleAppWebViewJoin({sdkAppId:t,userId:n,userSig:r,voiceId:e.voiceId}))};reJoin=async()=>this._joinOptions?this.join({voiceId:this._joinOptions.voiceId,userId:this._joinOptions.userId,roomId:this._joinOptions.roomId,type:this._joinOptions.type}):(this.emitErrorAndSetJoinedFalse("\u91CD\u8FDE\u5931\u8D25\uFF1A\u672A\u627E\u5230\u52A0\u5165\u623F\u95F4\u53C2\u6570\u3002"),!1);getVoiceSignOrEmitError=async e=>{try{return await this.options.getVoiceSign(e)}catch{return this.emitErrorAndSetJoinedFalse("\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1Artc \u7B7E\u540D\u8BF7\u6C42\u5F02\u5E38"),{}}};handleWxMiniProgramWebViewJoin=async e=>{let[t,n]=await this.joinRoomOrEmitError(e);return n?!1:this.handleJoinResult(t)};handleAppWebViewJoin=e=>new Promise(t=>{this.off("inner.rtc.success");let n=r=>{this.off("inner.rtc.fail",n),this.off("inner.rtc.success",n),t(this.handleJoinResult(r));};this.once("inner.rtc.fail",n),this.once("inner.rtc.success",n);try{let{sdkAppId:r,userId:s,userSig:o,voiceId:c}=e;this.jsBridge.callAndListen(`live/join?sdkAppID=${r}&userID=${s}&roomID=${c}&userSig=${o}`,a=>{a===!0?this.emit("inner.rtc.success",a):typeof a=="object"?a.code===0||a.code===2?this.emit("inner.rtc.success",a):this.emit("inner.rtc.fail",a):this.emit("inner.rtc.fail",a);});}catch(r){t(this.handleJoinResult({message:r.message,code:500}));}});joinRoomOrEmitError=async({sdkAppId:e,userId:t,voiceId:n,userSig:r})=>{try{return await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${e}&userID=${t}&roomID=${Number(n)}&userSig=${r}`)}catch(s){return this.emitErrorAndSetJoinedFalse("\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1A"+s.message),[null,s]}};handleJoinResult=e=>{switch(!0){case e===!0:case(typeof e=="object"&&e.code===0):case(typeof e=="object"&&e.code===2):{this.emit("joined"),this.joined=!0;break}default:{this.joined=!1;let t=typeof e=="object"?e.message:"\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1A\u672A\u77E5\u5F02\u5E38\u3002";this.emit("error",new Error(t,{cause:e}));}}return this.joined};emitErrorAndSetJoinedFalse=e=>{this.emit("error",new Error(e)),this.joined=!1;};quit=async()=>{let[e,t]=await this.jsBridge.callAndBackfeed("live/quit");return e===null&&this.emit("error",t||new Error("\u9000\u51FA\u623F\u95F4\u5931\u8D25\uFF1A\u672A\u77E5\u5F02\u5E38\u3002")),this.joined=!1,!!e};detectMicro=async()=>{let[e,t]=await this.jsBridge.detectMicro();return e===null?(this.emit("error",t||new Error("\u9EA6\u514B\u98CE\u76D1\u6D4B\u5F02\u5E38\uFF01")),!1):e};toggleMicro=async e=>{let[t,n]=await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${e?1:0}`);return t===null?(this.emit("error",n||new Error("\u9EA6\u514B\u98CE\u76D1\u6D4B\u5F02\u5E38\uFF01")),!1):(this.micro=t,t)};shock=()=>{this.jsBridge.shock(1);}};var Nn=(a=>(a.SelfUserInfo="SELF_USER_INFO",a.RoomInfo="ROOM_INFO",a.RTCInfo="RTC_INFO",a.UserList="USER_LIST",a.BuiltinMsg="BUILTIN_MSG",a.CustomEvent="CUSTOM_EVENT",a.KeyframeSync="KEYFRAME_SYNC",a.UserKickOut="USER_KICK_OUT",a))(Nn||{}),Bn=(t=>(t.UserChange="user_change",t.RoomChange="room_change",t))(Bn||{}),Pn=(o=>(o.UserMicroStatus="change_micro_status",o.UserMicroStatusSync="sync_micro_status",o.UserPermission="change_permission",o.UserStatus="change_status",o.UserInfo="change_info",o.RoomClose="close",o))(Pn||{}),jn=(t=>(t.OPEN="OPEN",t.CLOSE="CLOSE",t))(jn||{});function kr(i){try{let 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(r=>t[r]===void 0);return n.length>0&&console.warn(`\u63A8\u9001\u6570\u636E\u683C\u5F0F\u5F02\u5E38\uFF1A${n.join(" ")} \u503C\u4E0D\u5B58\u5728\uFF01`),t}catch{return !1}}var Wn=(r=>(r[r.NOTINITIALIZED=-1]="NOTINITIALIZED",r[r.CONNECTING=0]="CONNECTING",r[r.OPEN=1]="OPEN",r[r.CLOSED=3]="CLOSED",r))(Wn||{});var $n=(n=>(n[n.Normal=0]="Normal",n[n.Removed=1]="Removed",n[n.Replaced=2]="Replaced",n))($n||{}),Fn=(o=>(o.WAIT_ENTER="WAIT_ENTER",o.ONLINE="ONLINE",o.LEAVE="LEAVE",o.KICK_OUT="KICK_OUT",o.BE_REPLACE="BE_REPLACE",o.EXCEPTION="EXCEPTION",o))(Fn||{});var Jn=(s=>(s[s.NOTINITIALIZED=-1]="NOTINITIALIZED",s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(Jn||{}),Gn=(c=>(c.Error="Error",c.Close="Close",c.MicroAuth="MicroAuth",c.DuplicateConnect="DuplicateConnect",c.IllegalURL="IllegalURL",c.Unknown="Unknown",c.IllegalArgs="IllegalArgs",c))(Gn||{}),qn=(l=>(l.Err_1000="CLOSE_NORMAL",l.Err_1001="CLOSE_GOING_AWAY",l.Err_1002="CLOSE_PROTOCOL_ERROR",l.Err_1003="CLOSE_UNSUPPORTED",l.Err_1006="CLOSE_ABNORMAL",l.Err_1007="Unsupported Data",l.Err_1008="Policy Violation",l.Err_1009="CLOSE_TOO_LARGE",l.Err_unknown="unknown",l))(qn||{});function vt(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 Ct(i,e={}){let t=new URL(i,"http://localhost"),n=new URLSearchParams(t.search);return Object.entries(e).forEach(([r,s])=>{n.append(r,String(s));}),i.split("?")[0]+"?"+n.toString()}var Et=(()=>{let i=typeof process<"u"&&process.versions?.node!=null;return typeof window<"u"&&"Deno"in window||i||typeof window>"u"})();var fe=Et?"":navigator.userAgent,It=/android/i.test(fe),Tt=/iPhone|iPad\s+OS/i.test(fe),Rt=/MicroMessenger/i.test(fe)&&/miniProgram/i.test(fe),Dt=/realsee/i.test(fe);function Ce(i){return Object.prototype.toString.call(i)==="[object Object]"}function Ee(i,e){return i===e?!0:i==null||e==null||typeof i!=typeof e?!1:Number.isNaN(i)&&Number.isNaN(e)}function Hn(i,e){if(i===e)return !0;if(i==null||e==null)return !1;let t=Object.keys(i),n=Object.keys(e);return t.length!==n.length?!1:t.every(r=>Ee(i[r],e[r]))}function zn(i,e){return i===e?!0:i==null||e==null||i.length!==e.length?!1:i.every((t,n)=>Ee(t,e[n]))}function Yn(i,e){return Ee(i,e)?!0:Ce(i)&&Ce(e)?Hn(i,e):Array.isArray(i)&&Array.isArray(e)?zn(i,e):!1}function Ge(i,e){return Ee(i,e)?!0:Ce(i)&&Ce(e)?Zn(i,e):Array.isArray(i)&&Array.isArray(e)?Xn(i,e):!1}function Xn(i,e){if(i.length!==e.length)return !1;for(let t=0,n=i.length;t<n;t++)if(!Ge(i[t],e[t]))return !1;return !0}function Zn(i,e){if(i===e)return !0;if(i==null||e==null)return !1;let t=Object.keys(i),n=Object.keys(e);return t.length!==n.length?!1:t.every(r=>Ge(i[r],e[r]))}function Ot(i,e,t={deep:!1}){return t.deep?Ge(i,e):Yn(i,e)}var Ie=class extends j{_realWebSocket;_url;_protocols;_readyState=-1;_options={timeout:1e4,shouldReconnect:(e,t)=>{if(!(e.code===1008||e.code===1011))return [0,1e3,2e3][t.attempts%3]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1};_connectTimeout;_attempts=0;_reconnects=-1;_reconnectWhenOnlineAgain=!1;_explicitlyClosed=!1;_pendingReconnect;_connectivityEventsAttached=!1;_heathCheckTimer;get attempts(){return this._attempts}constructor(e){super(),e&&this.setOptions(e),this._startHealthCheck();}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;let t=Object.assign(this._options,e.robustOptions||{});if(typeof t?.timeout!="number")throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if(typeof t?.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=t,this._options.automaticOpen&&this._createWebSocket();}_healthCheck=async()=>{if(this._realWebSocket){let e=this._realWebSocket.readyState;e!==this._readyState&&(this._readyState=e,this._readyState===2&&this.emit("closing"));}await new Promise(e=>setTimeout(e,2e3)),this._heathCheckTimer=requestAnimationFrame(this._healthCheck);};_clearConnectTimeoutIfNeed=()=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);};_clearHeathCheckIfNeed=()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0);};_startHealthCheck=()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck);};_stopHealthCheck=()=>{this._clearHeathCheckIfNeed();};_clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0);};_online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e));};_offline=()=>{this._reconnectWhenOnlineAgain=!0,this._realWebSocket?.close(1e3,"offline");};_detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(globalThis?.removeEventListener("online",this._online),globalThis?.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1);};_attachConnectivityEvents=()=>{this._connectivityEventsAttached||(globalThis?.addEventListener("online",this._online),globalThis?.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0);};send=e=>{this._realWebSocket?.readyState===this._realWebSocket?.OPEN&&this._realWebSocket?.send(e);};close=(e,t)=>(typeof e!="number"&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),this._realWebSocket?.close(e,t));open=e=>{e&&(this._url=e),this._realWebSocket?.readyState!==WebSocket.OPEN&&this._realWebSocket?.readyState!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket());};_createWebSocket=()=>{let e=typeof this._url=="string"?this._url:this._url?.(this);if(!e)return;this._clearConnectTimeoutIfNeed(),this._clearPendingReconnectIfNeeded(),this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(e,this._protocols||void 0),this._attempts++,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));let t=()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("timeout",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));};this._connectTimeout=setTimeout(t,this._options.timeout),this._dispatchWebSocketEvent(),this._options.ignoreConnectivityEvents||this._attachConnectivityEvents();};_removeWebSocketEvent=()=>{this._realWebSocket?.removeEventListener("open",this._webSocketOpenHandler),this._realWebSocket?.removeEventListener("close",this._webSocketCloseHandler),this._realWebSocket?.removeEventListener("error",this._webSocketErrorHandler),this._realWebSocket?.removeEventListener("message",this._webSocketMessageHandler);};_dispatchWebSocketEvent=()=>{this._realWebSocket?.addEventListener("open",this._webSocketOpenHandler),this._realWebSocket?.addEventListener("close",this._webSocketCloseHandler),this._realWebSocket?.addEventListener("error",this._webSocketErrorHandler),this._realWebSocket?.addEventListener("message",this._webSocketMessageHandler);};_webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);let t=++this._reconnects,n=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:n}}))};_webSocketCloseHandler=e=>(this._reconnect(e),this._stopHealthCheck(),this.emit("close",e));_webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}}));_webSocketMessageHandler=e=>this.emit("message",e);_reconnect(e){if(!this._options.should1000Reconnect&&e.code===1e3||this._explicitlyClosed){this._attempts=0;return}if(this._connectivityEventsAttached&&globalThis?.navigator?.onLine===!1){this._reconnectWhenOnlineAgain=!0;return}let r=this._options.shouldReconnect?.(e,this);typeof r=="number"?(console.log(`Reconnecting in ${r}ms...`),this._pendingReconnect=setTimeout(this._createWebSocket,r)):console.log("No reconnection will be attempted.");}};var Te=class extends j{_ws=new Ie({url:"",robustOptions:{should1000Reconnect:!0,ignoreConnectivityEvents:!0}});_state=-1;set state(e){let t=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,t);}get state(){return this._state}constructor(){super(),this._addWebSocketEventListeners();}_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);};_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);};_handleCloseEvent=e=>{m.info(`live room closed bacause of ${e.code}-${e.reason||vt(e.code)}`),this.state=3;};_handleClosingEvent=()=>{m.info("live room is closing, onLine:",globalThis?.navigator?.onLine),this.state=3;};_handleConnectingEvent=e=>{m.info("live room is connecting"),this.state=0,e.detail.reconnects>0&&this.emit("reconnecting",e.detail);};_handleErrorEvent=e=>{m.error("live room error",e),this.state=3;};_handleMessageEvent=e=>{let t=(()=>{try{return JSON.parse(e.data)}catch{return e.data}})();this.emit("message",t);};_handleOpenEvent=e=>{m.info("live room open",e.detail),this.state=1,e.detail.reconnects>0&&this.emit("reconnected",e.detail);};_handleTimeoutEvent=e=>{m.error("live room connect timeout!",e.detail),this.state=3;};dispose=async()=>(this._removeWebSocketEventListeners(),await this.close("live room close by controller disposed!"));open=e=>this._ws.open(e);close=(e,t)=>new Promise(n=>{this._ws.once("close",()=>n(!0)),this._ws.close(e,t);});sendMessage(e=""){if(e==null)throw new Error("live message is empty!");if(this.state!==1)throw new Error("live has not yet been initialized!");return this._ws.send(JSON.stringify(e))}readyClose(){this._ws&&(this._ws._explicitlyClosed=!0);}};var Ye=class{constructor(e,t){this.clock=e,this.len=t;}},Le=class{constructor(){this.clients=new Map;}},Wt=(i,e,t)=>e.clients.forEach((n,r)=>{let s=i.doc.store.clients.get(r);for(let o=0;o<n.length;o++){let c=n[o];zt(i,s,c.clock,c.len,t);}}),ri=(i,e)=>{let t=0,n=i.length-1;for(;t<=n;){let r=x__namespace.floor((t+n)/2),s=i[r],o=s.clock;if(o<=e){if(e<o+s.len)return r;t=r+1;}else n=r-1;}return null},$t=(i,e)=>{let t=i.clients.get(e.client);return t!==void 0&&ri(t,e.clock)!==null},Ft=i=>{i.clients.forEach(e=>{e.sort((r,s)=>r.clock-s.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],s=e[t];r.clock+r.len>=s.clock?r.len=x__namespace.max(r.len,s.clock+s.len-r.clock):(n<t&&(e[n]=s),n++);}e.length=n;});};var Jt=(i,e,t,n)=>{M__namespace.setIfUndefined(i.clients,e,()=>[]).push(new Ye(t,n));};var oi=(i,e)=>{u__namespace.writeVarUint(i.restEncoder,e.clients.size),N__namespace.from(e.clients.entries()).sort((t,n)=>n[0]-t[0]).forEach(([t,n])=>{i.resetDsCurVal(),u__namespace.writeVarUint(i.restEncoder,t);let r=n.length;u__namespace.writeVarUint(i.restEncoder,r);for(let s=0;s<r;s++){let o=n[s];i.writeDsClock(o.clock),i.writeDsLen(o.len);}});};var Gt=Be__namespace.uint32,te=class i extends observable.ObservableV2{constructor({guid:e=Be__namespace.uuidv4(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:c=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Gt(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new rt,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=c,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=ze__namespace.create(l=>{this.on("load",()=>{this.isLoaded=!0,l(this);});});let a=()=>ze__namespace.create(l=>{let d=f=>{(f===void 0||f===!0)&&(this.off("sync",d),l());};this.on("sync",d);});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=a()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this]);}),this.whenSynced=a();}load(){let e=this._item;e!==null&&!this.shouldLoad&&b(e.parent.doc,t=>{t.subdocsLoaded.add(this);},null,!0),this.shouldLoad=!0;}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(N__namespace.from(this.subdocs).map(e=>e.guid))}transact(e,t=null){return b(this,e,t)}get(e,t=T){let n=M__namespace.setIfUndefined(this.share,e,()=>{let s=new t;return s._integrate(this,null),s}),r=n.constructor;if(t!==T&&r!==t)if(r===T){let s=new t;s._map=n._map,n._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s;}),s._start=n._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=n._length,this.share.set(e,s),s._integrate(this,null),s}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,lt)}getText(e=""){return this.get(e,ft)}getMap(e=""){return this.get(e,ht)}getXmlElement(e=""){return this.get(e,xe)}getXmlFragment(e=""){return this.get(e,_e)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON();}),e}destroy(){this.isDestroyed=!0,N__namespace.from(this.subdocs).forEach(t=>t.destroy());let e=this._item;if(e!==null){this._item=null;let t=e.content;t.doc=new i({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,b(e.parent.doc,n=>{let r=t.doc;e.deleted||n.subdocsAdded.add(r),n.subdocsRemoved.add(this);},null,!0);}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy();}};var Xe=class{constructor(){this.restEncoder=u__namespace.createEncoder();}toUint8Array(){return u__namespace.toUint8Array(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){u__namespace.writeVarUint(this.restEncoder,e);}writeDsLen(e){u__namespace.writeVarUint(this.restEncoder,e);}},Ze=class extends Xe{writeLeftID(e){u__namespace.writeVarUint(this.restEncoder,e.client),u__namespace.writeVarUint(this.restEncoder,e.clock);}writeRightID(e){u__namespace.writeVarUint(this.restEncoder,e.client),u__namespace.writeVarUint(this.restEncoder,e.clock);}writeClient(e){u__namespace.writeVarUint(this.restEncoder,e);}writeInfo(e){u__namespace.writeUint8(this.restEncoder,e);}writeString(e){u__namespace.writeVarString(this.restEncoder,e);}writeParentInfo(e){u__namespace.writeVarUint(this.restEncoder,e?1:0);}writeTypeRef(e){u__namespace.writeVarUint(this.restEncoder,e);}writeLen(e){u__namespace.writeVarUint(this.restEncoder,e);}writeAny(e){u__namespace.writeAny(this.restEncoder,e);}writeBuf(e){u__namespace.writeVarUint8Array(this.restEncoder,e);}writeJSON(e){u__namespace.writeVarString(this.restEncoder,JSON.stringify(e));}writeKey(e){u__namespace.writeVarString(this.restEncoder,e);}},Qe=class{constructor(){this.restEncoder=u__namespace.createEncoder(),this.dsCurrVal=0;}toUint8Array(){return u__namespace.toUint8Array(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0;}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,u__namespace.writeVarUint(this.restEncoder,t);}writeDsLen(e){e===0&&k__namespace.unexpectedCase(),u__namespace.writeVarUint(this.restEncoder,e-1),this.dsCurrVal+=e;}},et=class extends Qe{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new u__namespace.IntDiffOptRleEncoder,this.clientEncoder=new u__namespace.UintOptRleEncoder,this.leftClockEncoder=new u__namespace.IntDiffOptRleEncoder,this.rightClockEncoder=new u__namespace.IntDiffOptRleEncoder,this.infoEncoder=new u__namespace.RleEncoder(u__namespace.writeUint8),this.stringEncoder=new u__namespace.StringEncoder,this.parentInfoEncoder=new u__namespace.RleEncoder(u__namespace.writeUint8),this.typeRefEncoder=new u__namespace.UintOptRleEncoder,this.lenEncoder=new u__namespace.UintOptRleEncoder;}toUint8Array(){let e=u__namespace.createEncoder();return u__namespace.writeVarUint(e,0),u__namespace.writeVarUint8Array(e,this.keyClockEncoder.toUint8Array()),u__namespace.writeVarUint8Array(e,this.clientEncoder.toUint8Array()),u__namespace.writeVarUint8Array(e,this.leftClockEncoder.toUint8Array()),u__namespace.writeVarUint8Array(e,this.rightClockEncoder.toUint8Array()),u__namespace.writeVarUint8Array(e,u__namespace.toUint8Array(this.infoEncoder)),u__namespace.writeVarUint8Array(e,this.stringEncoder.toUint8Array()),u__namespace.writeVarUint8Array(e,u__namespace.toUint8Array(this.parentInfoEncoder)),u__namespace.writeVarUint8Array(e,this.typeRefEncoder.toUint8Array()),u__namespace.writeVarUint8Array(e,this.lenEncoder.toUint8Array()),u__namespace.writeUint8Array(e,u__namespace.toUint8Array(this.restEncoder)),u__namespace.toUint8Array(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){u__namespace.writeAny(this.restEncoder,e);}writeBuf(e){u__namespace.writeVarUint8Array(this.restEncoder,e);}writeJSON(e){u__namespace.writeAny(this.restEncoder,e);}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t);}},ci=(i,e,t,n)=>{n=x__namespace.max(n,e[0].id.clock);let r=q(e,n);u__namespace.writeVarUint(i.restEncoder,e.length-r),i.writeClient(t),u__namespace.writeVarUint(i.restEncoder,n);let s=e[r];s.write(i,n-s.id.clock);for(let o=r+1;o<e.length;o++)e[o].write(i,0);},ai=(i,e,t)=>{let n=new Map;t.forEach((r,s)=>{K(e,s)>r&&n.set(s,r);}),yt(e).forEach((r,s)=>{t.has(s)||n.set(s,0);}),u__namespace.writeVarUint(i.restEncoder,n.size),N__namespace.from(n.entries()).sort((r,s)=>s[0]-r[0]).forEach(([r,s])=>{ci(i,e.clients.get(r),r,s);});};var li=(i,e)=>ai(i,e.doc.store,e.beforeState);var tt=class{constructor(){this.l=[];}},Ut=()=>new tt,Lt=(i,e)=>i.l.push(e),Vt=(i,e)=>{let t=i.l,n=t.length;i.l=t.filter(r=>e!==r),n===i.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.");},qt=(i,e,t)=>mt__namespace.callAll(i.l,[e,t]),se=class{constructor(e,t){this.client=e,this.clock=t;}},Re=(i,e)=>i===e||i!==null&&e!==null&&i.client===e.client&&i.clock===e.clock,v=(i,e)=>new se(i,e);var di=i=>{for(let[e,t]of i.doc.share.entries())if(t===i)return e;throw k__namespace.unexpectedCase()};var ie=(i,e)=>e===void 0?!i.deleted:e.sv.has(i.id.client)&&(e.sv.get(i.id.client)||0)>i.id.clock&&!$t(e.ds,i.id),it=(i,e)=>{let t=M__namespace.setIfUndefined(i.meta,it,pe__namespace.create),n=i.doc.store;t.has(e)||(e.sv.forEach((r,s)=>{r<K(n,s)&&Z(i,v(s,r));}),Wt(i,e.ds,r=>{}),t.add(e));};var rt=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null;}},yt=i=>{let e=new Map;return i.clients.forEach((t,n)=>{let r=t[t.length-1];e.set(n,r.id.clock+r.length);}),e},K=(i,e)=>{let t=i.clients.get(e);if(t===void 0)return 0;let n=t[t.length-1];return n.id.clock+n.length},Ht=(i,e)=>{let t=i.clients.get(e.id.client);if(t===void 0)t=[],i.clients.set(e.id.client,t);else {let n=t[t.length-1];if(n.id.clock+n.length!==e.id.clock)throw k__namespace.unexpectedCase()}t.push(e);},q=(i,e)=>{let t=0,n=i.length-1,r=i[n],s=r.id.clock;if(s===e)return n;let o=x__namespace.floor(e/(s+r.length-1)*n);for(;t<=n;){if(r=i[o],s=r.id.clock,s<=e){if(e<s+r.length)return o;t=o+1;}else n=o-1;o=x__namespace.floor((t+n)/2);}throw k__namespace.unexpectedCase()},ui=(i,e)=>{let t=i.clients.get(e.client);return t[q(t,e.clock)]},qe=ui,st=(i,e,t)=>{let n=q(e,t),r=e[n];return r.id.clock<t&&r instanceof A?(e.splice(n+1,0,fn(i,r,t-r.id.clock)),n+1):n},Z=(i,e)=>{let t=i.doc.store.clients.get(e.client);return t[st(i,t,e.clock)]},At=(i,e,t)=>{let n=e.clients.get(t.client),r=q(n,t.clock),s=n[r];return t.clock!==s.id.clock+s.length-1&&s.constructor!==$&&n.splice(r+1,0,fn(i,s,t.clock-s.id.clock+1)),s},fi=(i,e,t)=>{let n=i.clients.get(e.id.client);n[q(n,e.id.clock)]=t;},zt=(i,e,t,n,r)=>{if(n===0)return;let s=t+n,o=st(i,e,t),c;do c=e[o++],s<c.id.clock+c.length&&st(i,e,s),r(c);while(o<e.length&&e[o].id.clock<s)},ot=class{constructor(e,t,n){this.doc=e,this.deleteSet=new Le,this.beforeState=yt(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;}},xt=(i,e)=>e.deleteSet.clients.size===0&&!M__namespace.any(e.afterState,(t,n)=>e.beforeState.get(n)!==t)?!1:(Ft(e.deleteSet),li(i,e),oi(i,e.deleteSet),!0),Mt=(i,e,t)=>{let n=e._item;(n===null||n.id.clock<(i.beforeState.get(n.id.client)||0)&&!n.deleted)&&M__namespace.setIfUndefined(i.changed,e,pe__namespace.create).add(t);},Ue=(i,e)=>{let t=i[e],n=i[e-1],r=e;for(;r>0;t=n,n=i[--r-1]){if(n.deleted===t.deleted&&n.constructor===t.constructor&&n.mergeWith(t)){t instanceof A&&t.parentSub!==null&&t.parent._map.get(t.parentSub)===t&&t.parent._map.set(t.parentSub,n);continue}break}let s=e-r;return s&&i.splice(e+1-s,s),s},gi=(i,e,t)=>{for(let[n,r]of i.clients.entries()){let s=e.clients.get(n);for(let o=r.length-1;o>=0;o--){let c=r[o],a=c.clock+c.len;for(let l=q(s,c.clock),d=s[l];l<s.length&&d.id.clock<a;d=s[++l]){let f=s[l];if(c.clock+c.len<=f.id.clock)break;f instanceof A&&f.deleted&&!f.keep&&t(f)&&f.gc(e,!1);}}}},pi=(i,e)=>{i.clients.forEach((t,n)=>{let r=e.clients.get(n);for(let s=t.length-1;s>=0;s--){let o=t[s],c=x__namespace.min(r.length-1,1+q(r,o.clock+o.len-1));for(let a=c,l=r[a];a>0&&l.id.clock>=o.clock;l=r[a])a-=1+Ue(r,a);}});};var Yt=(i,e)=>{if(e<i.length){let t=i[e],n=t.doc,r=n.store,s=t.deleteSet,o=t._mergeStructs;try{Ft(s),t.afterState=yt(t.doc.store),n.emit("beforeObserverCalls",[t,n]);let c=[];t.changed.forEach((a,l)=>c.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(t,a);})),c.push(()=>{t.changedParentTypes.forEach((a,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(a=a.filter(d=>d.target._item===null||!d.target._item.deleted),a.forEach(d=>{d.currentTarget=l,d._path=null;}),a.sort((d,f)=>d.path.length-f.path.length),qt(l._dEH,a,t));});}),c.push(()=>n.emit("afterTransaction",[t,n])),mt.callAll(c,[]),t._needFormattingCleanup&&Ci(t);}finally{n.gc&&gi(s,r,n.gcFilter),pi(s,r),t.afterState.forEach((d,f)=>{let p=t.beforeState.get(f)||0;if(p!==d){let g=r.clients.get(f),w=x__namespace.max(q(g,p),1);for(let R=g.length-1;R>=w;)R-=1+Ue(g,R);}});for(let d=o.length-1;d>=0;d--){let{client:f,clock:p}=o[d].id,g=r.clients.get(f),w=q(g,p);w+1<g.length&&Ue(g,w+1)>1||w>0&&Ue(g,w);}if(!t.local&&t.afterState.get(n.clientID)!==t.beforeState.get(n.clientID)&&(P__namespace.print(P__namespace.ORANGE,P__namespace.BOLD,"[yjs] ",P__namespace.UNBOLD,P__namespace.RED,"Changed the client-id because another client seems to be using it."),n.clientID=Gt()),n.emit("afterTransactionCleanup",[t,n]),n._observers.has("update")){let d=new Ze;xt(d,t)&&n.emit("update",[d.toUint8Array(),t.origin,n,t]);}if(n._observers.has("updateV2")){let d=new et;xt(d,t)&&n.emit("updateV2",[d.toUint8Array(),t.origin,n,t]);}let{subdocsAdded:c,subdocsLoaded:a,subdocsRemoved:l}=t;(c.size>0||l.size>0||a.size>0)&&(c.forEach(d=>{d.clientID=n.clientID,d.collectionid==null&&(d.collectionid=n.collectionid),n.subdocs.add(d);}),l.forEach(d=>n.subdocs.delete(d)),n.emit("subdocs",[{loaded:a,added:c,removed:l},n,t]),l.forEach(d=>d.destroy())),i.length<=e+1?(n._transactionCleanups=[],n.emit("afterAllTransactions",[n,i])):Yt(i,e+1);}}},b=(i,e,t=null,n=!0)=>{let r=i._transactionCleanups,s=!1,o=null;i._transaction===null&&(s=!0,i._transaction=new ot(i,t,n),r.push(i._transaction),r.length===1&&i.emit("beforeAllTransactions",[i]),i.emit("beforeTransaction",[i._transaction,i]));try{o=e(i._transaction);}finally{if(s){let c=i._transaction===r[0];i._transaction=null,c&&Yt(r,0);}}return o};var Kt="You must not compute changes after the event-handler fired.",oe=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null;}get path(){return this._path||(this._path=mi(this.currentTarget,this.target))}deletes(e){return $t(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw k__namespace.create(Kt);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(r=>{if(r!==null){let s=t._map.get(r),o,c;if(this.adds(s)){let a=s.left;for(;a!==null&&this.adds(a);)a=a.left;if(this.deletes(s))if(a!==null&&this.deletes(a))o="delete",c=N__namespace.last(a.content.getContent());else return;else a!==null&&this.deletes(a)?(o="update",c=N__namespace.last(a.content.getContent())):(o="add",c=void 0);}else if(this.deletes(s))o="delete",c=N__namespace.last(s.content.getContent());else return;e.set(r,{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 k__namespace.create(Kt);let t=this.target,n=pe__namespace.create(),r=pe__namespace.create(),s=[];if(e={added:n,deleted:r,delta:s,keys:this.keys},this.transaction.changed.get(t).has(null)){let c=null,a=()=>{c&&s.push(c);};for(let l=t._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((c===null||c.delete===void 0)&&(a(),c={delete:0}),c.delete+=l.length,r.add(l)):this.adds(l)?((c===null||c.insert===void 0)&&(a(),c={insert:[]}),c.insert=c.insert.concat(l.content.getContent()),n.add(l)):((c===null||c.retain===void 0)&&(a(),c={retain:0}),c.retain+=l.length);c!==null&&c.retain===void 0&&a();}this._changes=e;}return e}},mi=(i,e)=>{let t=[];for(;e._item!==null&&e!==i;){if(e._item.parentSub!==null)t.unshift(e._item.parentSub);else {let n=0,r=e._item.parent._start;for(;r!==e._item&&r!==null;)!r.deleted&&r.countable&&(n+=r.length),r=r.right;t.unshift(n);}e=e._item.parent;}return t},V=()=>{P__namespace.warn("Invalid access: Add Yjs type to a document before reading data.");},Xt=80,wt=0,ct=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=wt++;}},yi=i=>{i.timestamp=wt++;},Zt=(i,e,t)=>{i.p.marker=!1,i.p=e,e.marker=!0,i.index=t,i.timestamp=wt++;},wi=(i,e,t)=>{if(i.length>=Xt){let n=i.reduce((r,s)=>r.timestamp<s.timestamp?r:s);return Zt(n,e,t),n}else {let n=new ct(e,t);return i.push(n),n}},Pe=(i,e)=>{if(i._start===null||e===0||i._searchMarker===null)return null;let t=i._searchMarker.length===0?null:i._searchMarker.reduce((s,o)=>x__namespace.abs(e-s.index)<x__namespace.abs(e-o.index)?s:o),n=i._start,r=0;for(t!==null&&(n=t.p,r=t.index,yi(t));n.right!==null&&r<e;){if(!n.deleted&&n.countable){if(e<r+n.length)break;r+=n.length;}n=n.right;}for(;n.left!==null&&r>e;)n=n.left,!n.deleted&&n.countable&&(r-=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&&(r-=n.length);return t!==null&&x__namespace.abs(t.index-r)<n.parent.length/Xt?(Zt(t,n,r),t):wi(i._searchMarker,n,r)},me=(i,e,t)=>{for(let n=i.length-1;n>=0;n--){let r=i[n];if(t>0){let s=r.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(r.index-=s.length);if(s===null||s.marker===!0){i.splice(n,1);continue}r.p=s,s.marker=!0;}(e<r.index||t>0&&e===r.index)&&(r.index=x__namespace.max(e,r.index+t));}};var je=(i,e,t)=>{let n=i,r=e.changedParentTypes;for(;M__namespace.setIfUndefined(r,i,()=>[]).push(t),i._item!==null;)i=i._item.parent;qt(n._eH,t,e);},T=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Ut(),this._dEH=Ut(),this._searchMarker=null;}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t;}_copy(){throw k__namespace.methodUnimplemented()}clone(){throw k__namespace.methodUnimplemented()}_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){Lt(this._eH,e);}observeDeep(e){Lt(this._dEH,e);}unobserve(e){Vt(this._eH,e);}unobserveDeep(e){Vt(this._dEH,e);}toJSON(){}},Qt=(i,e,t)=>{i.doc??V(),e<0&&(e=i._length+e),t<0&&(t=i._length+t);let n=t-e,r=[],s=i._start;for(;s!==null&&n>0;){if(s.countable&&!s.deleted){let o=s.content.getContent();if(o.length<=e)e-=o.length;else {for(let c=e;c<o.length&&n>0;c++)r.push(o[c]),n--;e=0;}}s=s.right;}return r},en=i=>{i.doc??V();let e=[],t=i._start;for(;t!==null;){if(t.countable&&!t.deleted){let n=t.content.getContent();for(let r=0;r<n.length;r++)e.push(n[r]);}t=t.right;}return e};var ye=(i,e)=>{let t=0,n=i._start;for(i.doc??V();n!==null;){if(n.countable&&!n.deleted){let r=n.content.getContent();for(let s=0;s<r.length;s++)e(r[s],t++,i);}n=n.right;}},tn=(i,e)=>{let t=[];return ye(i,(n,r)=>{t.push(e(n,r,i));}),t},_i=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;}let r=t[n++];return t.length<=n&&(t=null),{done:!1,value:r}}}},nn=(i,e)=>{i.doc??V();let t=Pe(i,e),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;}},Ve=(i,e,t,n)=>{let r=t,s=i.doc,o=s.clientID,c=s.store,a=t===null?e._start:t.right,l=[],d=()=>{l.length>0&&(r=new A(v(o,K(c,o)),r,r&&r.lastId,a,a&&a.id,e,null,new be(l)),r.integrate(i,0),l=[]);};n.forEach(f=>{if(f===null)l.push(f);else switch(f.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(f);break;default:switch(d(),f.constructor){case Uint8Array:case ArrayBuffer:r=new A(v(o,K(c,o)),r,r&&r.lastId,a,a&&a.id,e,null,new Ke(new Uint8Array(f))),r.integrate(i,0);break;case te:r=new A(v(o,K(c,o)),r,r&&r.lastId,a,a&&a.id,e,null,new Ne(f)),r.integrate(i,0);break;default:if(f instanceof T)r=new A(v(o,K(c,o)),r,r&&r.lastId,a,a&&a.id,e,null,new ee(f)),r.integrate(i,0);else throw new Error("Unexpected content type in insert operation")}}}),d();},rn=()=>k__namespace.create("Length exceeded!"),sn=(i,e,t,n)=>{if(t>e._length)throw rn();if(t===0)return e._searchMarker&&me(e._searchMarker,t,n.length),Ve(i,e,null,n);let r=t,s=Pe(e,t),o=e._start;for(s!==null&&(o=s.p,t-=s.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&&Z(i,v(o.id.client,o.id.clock+t));break}t-=o.length;}return e._searchMarker&&me(e._searchMarker,r,n.length),Ve(i,e,o,n)},bi=(i,e,t)=>{let r=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(r)for(;r.right;)r=r.right;return Ve(i,e,r,t)},on=(i,e,t,n)=>{if(n===0)return;let r=t,s=n,o=Pe(e,t),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&&Z(i,v(c.id.client,c.id.clock+t)),t-=c.length);for(;n>0&&c!==null;)c.deleted||(n<c.length&&Z(i,v(c.id.client,c.id.clock+n)),c.delete(i),n-=c.length),c=c.right;if(n>0)throw rn();e._searchMarker&&me(e._searchMarker,r,-s+n);},Ae=(i,e,t)=>{let n=e._map.get(t);n!==void 0&&n.delete(i);},_t=(i,e,t,n)=>{let r=e._map.get(t)||null,s=i.doc,o=s.clientID,c;if(n==null)c=new be([n]);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:c=new be([n]);break;case Uint8Array:c=new Ke(n);break;case te:c=new Ne(n);break;default:if(n instanceof T)c=new ee(n);else throw new Error("Unexpected content type")}new A(v(o,K(s.store,o)),r,r&&r.lastId,null,null,e,t,c).integrate(i,0);},bt=(i,e)=>{i.doc??V();let t=i._map.get(e);return t!==void 0&&!t.deleted?t.content.getContent()[t.length-1]:void 0},cn=i=>{let e={};return i.doc??V(),i._map.forEach((t,n)=>{t.deleted||(e[n]=t.content.getContent()[t.length-1]);}),e},an=(i,e)=>{i.doc??V();let t=i._map.get(e);return t!==void 0&&!t.deleted};var Si=(i,e)=>{let t={};return i._map.forEach((n,r)=>{let s=n;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&ie(s,e)&&(t[r]=s.content.getContent()[s.length-1]);}),t},De=i=>(i.doc??V(),re__namespace.iteratorFilter(i._map.entries(),e=>!e[1].deleted)),at=class extends oe{},lt=class i extends T{constructor(){super(),this._prelimContent=[],this._searchMarker=[];}static from(e){let t=new i;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null;}_copy(){return new i}clone(){let e=new i;return e.insert(0,this.toArray().map(t=>t instanceof T?t.clone():t)),e}get length(){return this.doc??V(),this._length}_callObserver(e,t){super._callObserver(e,t),je(this,e,new at(this,e));}insert(e,t){this.doc!==null?b(this.doc,n=>{sn(n,this,e,t);}):this._prelimContent.splice(e,0,...t);}push(e){this.doc!==null?b(this.doc,t=>{bi(t,this,e);}):this._prelimContent.push(...e);}unshift(e){this.insert(0,e);}delete(e,t=1){this.doc!==null?b(this.doc,n=>{on(n,this,e,t);}):this._prelimContent.splice(e,t);}get(e){return nn(this,e)}toArray(){return en(this)}slice(e=0,t=this.length){return Qt(this,e,t)}toJSON(){return this.map(e=>e instanceof T?e.toJSON():e)}map(e){return tn(this,e)}forEach(e){ye(this,e);}[Symbol.iterator](){return _i(this)}_write(e){e.writeTypeRef(Ri);}};var dt=class extends oe{constructor(e,t,n){super(e,t),this.keysChanged=n;}},ht=class i extends T{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,r)=>{this.set(r,n);}),this._prelimContent=null;}_copy(){return new i}clone(){let e=new i;return this.forEach((t,n)=>{e.set(n,t instanceof T?t.clone():t);}),e}_callObserver(e,t){je(this,e,new dt(this,e,t));}toJSON(){this.doc??V();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof T?r.toJSON():r;}}),e}get size(){return [...De(this)].length}keys(){return re__namespace.iteratorMap(De(this),e=>e[0])}values(){return re__namespace.iteratorMap(De(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return re__namespace.iteratorMap(De(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??V(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this);});}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?b(this.doc,t=>{Ae(t,this,e);}):this._prelimContent.delete(e);}set(e,t){return this.doc!==null?b(this.doc,n=>{_t(n,this,e,t);}):this._prelimContent.set(e,t),t}get(e){return bt(this,e)}has(e){return an(this,e)}clear(){this.doc!==null?b(this.doc,e=>{this.forEach(function(t,n,r){Ae(e,r,n);});}):this._prelimContent.clear();}_write(e){e.writeTypeRef(Di);}};var X=(i,e)=>i===e||typeof i=="object"&&typeof e=="object"&&i&&e&&F__namespace.equalFlat(i,e),we=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r;}forward(){switch(this.right===null&&k__namespace.unexpectedCase(),this.right.content.constructor){case O:this.right.deleted||ae(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;}},Nt=(i,e,t)=>{for(;e.right!==null&&t>0;){switch(e.right.content.constructor){case O:e.right.deleted||ae(e.currentAttributes,e.right.content);break;default:e.right.deleted||(t<e.right.length&&Z(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},Oe=(i,e,t,n)=>{let r=new Map,s=n?Pe(e,t):null;if(s){let o=new we(s.p.left,s.p,s.index,r);return Nt(i,o,t-s.index)}else {let o=new we(null,e._start,0,r);return Nt(i,o,t)}},ln=(i,e,t,n)=>{for(;t.right!==null&&(t.right.deleted===!0||t.right.content.constructor===O&&X(n.get(t.right.content.key),t.right.content.value));)t.right.deleted||n.delete(t.right.content.key),t.forward();let r=i.doc,s=r.clientID;n.forEach((o,c)=>{let a=t.left,l=t.right,d=new A(v(s,K(r.store,s)),a,a&&a.lastId,l,l&&l.id,e,null,new O(c,o));d.integrate(i,0),t.right=d,t.forward();});},ae=(i,e)=>{let{key:t,value:n}=e;n===null?i.delete(t):i.set(t,n);},dn=(i,e)=>{for(;i.right!==null;){if(!(i.right.deleted||i.right.content.constructor===O&&X(e[i.right.content.key]??null,i.right.content.value)))break;i.forward();}},hn=(i,e,t,n)=>{let r=i.doc,s=r.clientID,o=new Map;for(let c in n){let a=n[c],l=t.currentAttributes.get(c)??null;if(!X(l,a)){o.set(c,l);let{left:d,right:f}=t;t.right=new A(v(s,K(r.store,s)),d,d&&d.lastId,f,f&&f.id,e,null,new O(c,a)),t.right.integrate(i,0),t.forward();}}return o},He=(i,e,t,n,r)=>{t.currentAttributes.forEach((p,g)=>{r[g]===void 0&&(r[g]=null);});let s=i.doc,o=s.clientID;dn(t,r);let c=hn(i,e,t,r),a=n.constructor===String?new Q(n):n instanceof T?new ee(n):new ce(n),{left:l,right:d,index:f}=t;e._searchMarker&&me(e._searchMarker,t.index,a.getLength()),d=new A(v(o,K(s.store,o)),l,l&&l.lastId,d,d&&d.id,e,null,a),d.integrate(i,0),t.right=d,t.index=f,t.forward(),ln(i,e,t,c);},Bt=(i,e,t,n,r)=>{let s=i.doc,o=s.clientID;dn(t,r);let c=hn(i,e,t,r);e:for(;t.right!==null&&(n>0||c.size>0&&(t.right.deleted||t.right.content.constructor===O));){if(!t.right.deleted)switch(t.right.content.constructor){case O:{let{key:a,value:l}=t.right.content,d=r[a];if(d!==void 0){if(X(d,l))c.delete(a);else {if(n===0)break e;c.set(a,l);}t.right.delete(i);}else t.currentAttributes.set(a,l);break}default:n<t.right.length&&Z(i,v(t.right.id.client,t.right.id.clock+n)),n-=t.right.length;break}t.forward();}if(n>0){let a="";for(;n>0;n--)a+=`
|
|
66
|
-
|
|
67
|
-
`?o.insert.slice(0,-1):o.insert;(typeof c!="string"||c.length>0)&&He(n,this,r,c,o.attributes||{});}else o.retain!==void 0?Bt(n,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&Pt(n,r,o.delete);}}):this._pending.push(()=>this.applyDelta(e));}toDelta(e,t,n){this.doc??V();let r=[],s=new Map,o=this.doc,c="",a=this._start;function l(){if(c.length>0){let f={},p=!1;s.forEach((w,R)=>{p=!0,f[R]=w;});let g={insert:c};p&&(g.attributes=f),r.push(g),c="";}}let d=()=>{for(;a!==null;){if(ie(a,e)||t!==void 0&&ie(a,t))switch(a.content.constructor){case Q:{let f=s.get("ychange");e!==void 0&&!ie(a,e)?(f===void 0||f.user!==a.id.client||f.type!=="removed")&&(l(),s.set("ychange",n?n("removed",a.id):{type:"removed"})):t!==void 0&&!ie(a,t)?(f===void 0||f.user!==a.id.client||f.type!=="added")&&(l(),s.set("ychange",n?n("added",a.id):{type:"added"})):f!==void 0&&(l(),s.delete("ychange")),c+=a.content.str;break}case ee:case ce:{l();let f={insert:a.content.getContent()[0]};if(s.size>0){let p={};f.attributes=p,s.forEach((g,w)=>{p[w]=g;});}r.push(f);break}case O:ie(a,e)&&(l(),ae(s,a.content));break}a=a.right;}l();};return e||t?b(o,f=>{e&&it(f,e),t&&it(f,t),d();},"cleanup"):d(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r!==null?b(r,s=>{let o=Oe(s,this,e,!n);n||(n={},o.currentAttributes.forEach((c,a)=>{n[a]=c;})),He(s,this,o,t,n);}):this._pending.push(()=>this.insert(e,t,n));}insertEmbed(e,t,n){let r=this.doc;r!==null?b(r,s=>{let o=Oe(s,this,e,!n);He(s,this,o,t,n||{});}):this._pending.push(()=>this.insertEmbed(e,t,n||{}));}delete(e,t){if(t===0)return;let n=this.doc;n!==null?b(n,r=>{Pt(r,Oe(r,this,e,!0),t);}):this._pending.push(()=>this.delete(e,t));}format(e,t,n){if(t===0)return;let r=this.doc;r!==null?b(r,s=>{let o=Oe(s,this,e,!1);o.right!==null&&Bt(s,this,o,t,n);}):this._pending.push(()=>this.format(e,t,n));}removeAttribute(e){this.doc!==null?b(this.doc,t=>{Ae(t,this,e);}):this._pending.push(()=>this.removeAttribute(e));}setAttribute(e,t){this.doc!==null?b(this.doc,n=>{_t(n,this,e,t);}):this._pending.push(()=>this.setAttribute(e,t));}getAttribute(e){return bt(this,e)}getAttributes(){return cn(this)}_write(e){e.writeTypeRef(Oi);}};var ge=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??V();}[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===xe||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})}},_e=class i extends T{constructor(){super(),this._prelimContent=[];}get firstChild(){let 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 i}clone(){let e=new i;return e.insert(0,this.toArray().map(t=>t instanceof T?t.clone():t)),e}get length(){return this.doc??V(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new ge(this,e)}querySelector(e){e=e.toUpperCase();let n=new ge(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return n.done?null:n.value}querySelectorAll(e){return e=e.toUpperCase(),N__namespace.from(new ge(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){je(this,e,new gt(this,t,e));}toString(){return tn(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),ye(this,s=>{r.insertBefore(s.toDOM(e,t,n),null);}),r}insert(e,t){this.doc!==null?b(this.doc,n=>{sn(n,this,e,t);}):this._prelimContent.splice(e,0,...t);}insertAfter(e,t){if(this.doc!==null)b(this.doc,n=>{let r=e&&e instanceof T?e._item:e;Ve(n,this,r,t);});else {let n=this._prelimContent,r=e===null?0:n.findIndex(s=>s===e)+1;if(r===0&&e!==null)throw k__namespace.create("Reference item not found");n.splice(r,0,...t);}}delete(e,t=1){this.doc!==null?b(this.doc,n=>{on(n,this,e,t);}):this._prelimContent.splice(e,t);}toArray(){return en(this)}push(e){this.insert(this.length,e);}unshift(e){this.insert(0,e);}get(e){return nn(this,e)}slice(e=0,t=this.length){return Qt(this,e,t)}forEach(e){ye(this,e);}_write(e){e.writeTypeRef(Li);}};var xe=class i extends _e{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map;}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((n,r)=>{this.setAttribute(r,n);}),this._prelimAttrs=null;}_copy(){return new i(this.nodeName)}clone(){let e=new i(this.nodeName),t=this.getAttributes();return F__namespace.forEach(t,(n,r)=>{typeof n=="string"&&e.setAttribute(r,n);}),e.insert(0,this.toArray().map(n=>n instanceof T?n.clone():n)),e}toString(){let e=this.getAttributes(),t=[],n=[];for(let c in e)n.push(c);n.sort();let r=n.length;for(let c=0;c<r;c++){let a=n[c];t.push(a+'="'+e[a]+'"');}let s=this.nodeName.toLocaleLowerCase(),o=t.length>0?" "+t.join(" "):"";return `<${s}${o}>${super.toString()}</${s}>`}removeAttribute(e){this.doc!==null?b(this.doc,t=>{Ae(t,this,e);}):this._prelimAttrs.delete(e);}setAttribute(e,t){this.doc!==null?b(this.doc,n=>{_t(n,this,e,t);}):this._prelimAttrs.set(e,t);}getAttribute(e){return bt(this,e)}hasAttribute(e){return an(this,e)}getAttributes(e){return e?Si(this,e):cn(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),s=this.getAttributes();for(let o in s){let c=s[o];typeof c=="string"&&r.setAttribute(o,c);}return ye(this,o=>{r.appendChild(o.toDOM(e,t,n));}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Ui),e.writeKey(this.nodeName);}};var gt=class extends oe{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r);});}};var Me=class{constructor(e,t){this.id=e,this.length=t;}get deleted(){throw k__namespace.methodUnimplemented()}mergeWith(e){return !1}write(e,t,n){throw k__namespace.methodUnimplemented()}integrate(e,t){throw k__namespace.methodUnimplemented()}},Ei=0,$=class extends Me{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),Ht(e.doc.store,this);}write(e,t){e.writeInfo(Ei),e.writeLen(this.length-t);}getMissing(e,t){return null}},Ke=class i{constructor(e){this.content=e;}getLength(){return 1}getContent(){return [this.content]}isCountable(){return !0}copy(){return new i(this.content)}splice(e){throw k__namespace.methodUnimplemented()}mergeWith(e){return !1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content);}getRef(){return 3}};var pt=class i{constructor(e){this.len=e;}getLength(){return this.len}getContent(){return []}isCountable(){return !1}copy(){return new i(this.len)}splice(e){let t=new i(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Jt(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}};var Ii=(i,e)=>new te({guid:i,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1}),Ne=class i{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;let 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 i(Ii(this.doc.guid,this.opts))}splice(e){throw k__namespace.methodUnimplemented()}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}};var ce=class i{constructor(e){this.embed=e;}getLength(){return 1}getContent(){return [this.embed]}isCountable(){return !0}copy(){return new i(this.embed)}splice(e){throw k__namespace.methodUnimplemented()}mergeWith(e){return !1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed);}getRef(){return 5}};var O=class i{constructor(e,t){this.key=e,this.value=t;}getLength(){return 1}getContent(){return []}isCountable(){return !1}copy(){return new i(this.key,this.value)}splice(e){throw k__namespace.methodUnimplemented()}mergeWith(e){return !1}integrate(e,t){let 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}};var Ti=jt__namespace.getVariable("node_env")==="development",be=class i{constructor(e){this.arr=e,Ti&&F__namespace.deepFreeze(e);}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return !0}copy(){return new i(this.arr)}splice(e){let t=new i(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){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let s=this.arr[r];e.writeAny(s);}}getRef(){return 8}};var Q=class i{constructor(e){this.str=e;}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return !0}copy(){return new i(this.str)}splice(e){let t=new i(this.str.slice(e));this.str=this.str.slice(0,e);let n=this.str.charCodeAt(e-1);return n>=55296&&n<=56319&&(this.str=this.str.slice(0,e-1)+"\uFFFD",t.str="\uFFFD"+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}};var Ri=0,Di=1,Oi=2,Ui=3,Li=4;var ee=class i{constructor(e){this.type=e;}getLength(){return 1}getContent(){return [this.type]}isCountable(){return !0}copy(){return new i(this.type._copy())}splice(e){throw k__namespace.methodUnimplemented()}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}};var fn=(i,e,t)=>{let{client:n,clock:r}=e.id,s=new A(v(n,r+t),e,v(n,r+t-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=v(e.redone.client,e.redone.clock+t)),e.right=s,s.right!==null&&(s.right.left=s),i._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=t,s};var A=class i extends Me{constructor(e,t,n,r,s,o,c,a){super(e,a.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=s,this.parent=o,this.parentSub=c,this.redone=null,this.content=a,this.info=this.content.isCountable()?C__namespace.BIT2:0;}set marker(e){(this.info&C__namespace.BIT4)>0!==e&&(this.info^=C__namespace.BIT4);}get marker(){return (this.info&C__namespace.BIT4)>0}get keep(){return (this.info&C__namespace.BIT1)>0}set keep(e){this.keep!==e&&(this.info^=C__namespace.BIT1);}get countable(){return (this.info&C__namespace.BIT2)>0}get deleted(){return (this.info&C__namespace.BIT3)>0}set deleted(e){this.deleted!==e&&(this.info^=C__namespace.BIT3);}markDeleted(){this.info|=C__namespace.BIT3;}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=K(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=K(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===se&&this.id.client!==this.parent.client&&this.parent.clock>=K(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=At(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Z(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===$||this.right&&this.right.constructor===$)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===i&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===i&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===se){let n=qe(t,this.parent);n.constructor===$?this.parent=null:this.parent=n.content.type;}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=At(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,r;if(n!==null)r=n.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;let s=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),s.add(r),Re(this.origin,r.origin)){if(r.id.client<this.id.client)n=r,s.clear();else if(Re(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&o.has(qe(e.doc.store,r.origin)))s.has(qe(e.doc.store,r.origin))||(n=r,s.clear());else break;r=r.right;}this.left=n;}if(this.left!==null){let 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),Ht(e.doc.store,this),this.content.integrate(e,this),Mt(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e);}else new $(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&&Re(e.origin,this.lastId)&&this.right===e&&Re(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)){let 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){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),Jt(e.deleteSet,this.id.client,this.id.clock,this.length),Mt(e,t,this.parentSub),this.content.delete(e);}}gc(e,t){if(!this.deleted)throw k__namespace.unexpectedCase();this.content.gc(e),t?fi(e,this,new $(this.id,this.length)):this.content=new pt(this.length);}write(e,t){let n=t>0?v(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&C__namespace.BITS5|(n===null?0:C__namespace.BIT8)|(r===null?0:C__namespace.BIT7)|(s===null?0:C__namespace.BIT6);if(e.writeInfo(o),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let c=this.parent;if(c._item!==void 0){let a=c._item;if(a===null){let l=di(c);e.writeParentInfo(!0),e.writeString(l);}else e.writeParentInfo(!1),e.writeLeftID(a.id);}else c.constructor===String?(e.writeParentInfo(!0),e.writeString(c)):c.constructor===se?(e.writeParentInfo(!1),e.writeLeftID(c)):k__namespace.unexpectedCase();s!==null&&e.writeString(s);}this.content.write(e,t);}};var gn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},pn="__ $YJS$ __";gn[pn]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");gn[pn]=!0;var Se=i=>Promise.reject("unimplemented method GetVoiceSign"),St=(i,e={},t=[])=>({command:i,front_request_id:Y(),data:{...e,to_user_ids:Array.isArray(t)?t:[t]}}),mn=()=>{window?.__Realsee_Live__&&(window?.__Realsee_Live__?.dispose?.(),window.__Realsee_Live__=null);},We=class extends j{_options={};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}keyframes=new j;_yDoc;_buildInData;constructor(e){super(),m.info("Initializing Live instance with options:",e),this._addLiveControllerEventListeners(),this._yDoc=new te({guid:Y()}),this._buildInData={keyframes:this._yDoc.getMap("keyframes")},this._initializeKeyframesObservers(),this._initializeOptions(e),this._autoConnect(),this._debugSetup();}get _buildInKeyframes(){return this._buildInData.keyframes}get snapshot(){return this._buildInData.keyframes.toJSON()}_initializeKeyframesObservers=()=>{this._buildInKeyframes.observe(this._handleKeyframesChange);};_handleKeyframesChange=e=>{let{transaction:t,target:n,changes:r}=e;if(n===this._buildInKeyframes)if(t.origin.triggerUserId===this.selfInfo?.id){let s=St("KEYFRAME_SYNC",this.snapshot,void 0);try{this._controller.sendMessage(s);}catch(o){m.error("Failed to send keyframe sync message:",o);}}else r.keys.forEach((s,o)=>{let c=s.oldValue,a=this.getFramesByKey(o),l=t.origin.frontRequestId;this.keyframes.emit(o,a,c,l);}),r.keys.size!==0&&this.emit("keyframes",this.snapshot,t.origin.frontRequestId);};getFramesByKey=e=>this.snapshot[e];sendKeyframe=(e,t)=>this.state!==1?(m.warn("Attempted to send keyframe while connection is not open"),!1):(this._yDoc.transact(()=>{this._buildInKeyframes.set(e,t);},{triggerUserId:this.selfInfo?.id,frontRequestId:""}),!0);get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}_controller=new Te;_initializeOptions(e){this._options=Object.assign({initialMicroStatus:"OPEN"},e),this._options.jsBridge=this._initializeJsBridge(e),this._options.getVoiceSign=e.getVoiceSign??Se,this._options.autoPlayConfirm=e.autoPlayConfirm,this._options.rtc=this._initializeRTC(e);}_initializeJsBridge(e){if(e.jsBridge)return e.jsBridge;if(e.useBuiltInJsBridge)return new Ai__default.default}_initializeRTC(e){if(e.rtc)return e.rtc;if(e.rtcType)return this._createBuiltInRTC(e);if(e.useBuiltInRTC)return this._createDefaultRTC(e)}_createBuiltInRTC(e){if(!e.getVoiceSign){m.error("GetVoiceSign method must be passed when using built-in RTC instances");return}switch(e.rtcType){case"RealseeVRWebViewRTC":return this._createVRWebViewRTC();case"RealseeBrowserChimeRTC":return new ne({getVoiceSign:this._options.getVoiceSign??Se,logLevel:e.__debug__?0:1});case"RealseeBrowserRTC":return this._createBrowserRTC();default:m.error("unknown built-in RTC type");return}}_createVRWebViewRTC(){if(this._options.jsBridge)return new ue({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign??Se});m.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");}_createBrowserRTC(){if(!this._options.autoPlayConfirm){m.error("autoPlayConfirm method must be passed when using built-in RealseeBrowserRTC instances");return}return new he({getVoiceSign:this._options.getVoiceSign??Se,autoPlayConfirm:this._options.autoPlayConfirm})}_createDefaultRTC(e){if(!e.getVoiceSign){m.error("GetVoiceSign method must be passed when using built-in RTC instances");return}if(this._options.jsBridge){if(Dt&&(It||Tt)||Rt)return this._createVRWebViewRTC();{let t=this._options.getVoiceSign??Se;return e.builtInRTCType==="chime"?new ne({getVoiceSign:t}):this._createBrowserRTC()}}else {m.error("jsBridge instance must be passed when using built-in RTC instances");return}}_autoConnect(){this._options.url&&this._options.getTicket&&this.connect();}_debugSetup(){this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this});}_addLiveControllerEventListeners=()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage);};_removeLiveControllerEventListeners=()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage);};_handleStateChange=(e,t)=>{m.info(`State changed from ${t} to ${e}`),this.emit("stateChange",e,t);};_handleMessage=async e=>{if(m.debug("Received message:",e),typeof e=="object"){let{command:t,data:n={},frontRequestId:r,code:s,message:o,triggerUserId:c}=e;if(s==="SUCCESS")switch(t){case"SELF_USER_INFO":{let a=n;Ot(this.selfInfo,a,{deep:!0})||(this._buildInData.selfInfo=a,this.emit("selfInfoUpdate",this._buildInData.selfInfo,r));break}case"ROOM_INFO":{let a=n;this._buildInData.roomInfo=Object.assign({},a);let l=a.last_frame||{};this._yDoc.transact(()=>{for(let d in l)this._buildInKeyframes.set(d,l[d]);},{triggerUserId:"readyKeyframeSync",frontRequestId:r}),this.emit("readyKeyframeSync",a.last_frame||{});break}case"RTC_INFO":{m.info("RTC info updated:",n);let{voice_id:a,type:l}=n;if(this._buildInData.rtcInfo={voiceId:a,type:l},this.$RTC?.joined)m.warn("\u5DF2\u52A0\u5165\u8BED\u97F3\u623F\u95F4\uFF0C\u65E0\u9700\u91CD\u590D\u52A0\u5165\uFF01");else if(await this.$RTC?.join({voiceId:a,userId:this.selfInfo?.id||"",roomId:this.roomInfo?.info.room_code,type:l})){let f=this._options.initialMicroStatus??"OPEN";await this.toggleMicro(f==="OPEN");}else m.error("\u52A0\u5165\u8BED\u97F3\u623F\u95F4\u5931\u8D25");break}case"USER_LIST":{let a=n;this._buildInData.userList=a,this.emit("userListUpdate",this.userList,r);break}case"CUSTOM_EVENT":{let a=n;this.emit("broadcast",a,r);break}case"KEYFRAME_SYNC":{let a=n;if(c===this.selfInfo?.id)return;this._yDoc.transact(()=>{for(let l in a)this._buildInKeyframes.set(l,a[l]);},{triggerUserId:c,frontRequestId:r});break}case"BUILTIN_MSG":{let a=n;this.emit("builtinEvent",a),a.event_type==="user_change"&&this.emit("userChange",a),a.event_type==="room_change"&&this.emit("roomChange",a),a.event_type==="user_change"&&a.action==="change_micro_status"&&await this.toggleMicro(a.data.status==="OPEN"),a.event_type==="room_change"&&a.action==="close"&&await this._exit();break}case"USER_KICK_OUT":{this.emit("kickOut");break}default:m.warn("Unknown command received:",t);}else m.error("Error in message:",o),this.emit("error",e);}};_clearLiveData=()=>{this._buildInKeyframes.clear(),this._buildInData={keyframes:this._yDoc.getMap("keyframes")};};connect=async(e={})=>{if(m.info("Attempting to connect with options:",e),this._options.url=e.url??this._options.url??"",this._options.getTicket=e.getTicket??this._options.getTicket,this._options.initialMicroStatus=e.rtcMicStatus??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");let t=this.state;if(t===0||t===1)if(e.force)await this._controller.close("force close by connect").catch(console.warn);else return new Error("\u5DF2\u6709Live\u5B9E\u4F8B\u6B63\u5728\u8FDE\u63A5\u4E2D\uFF0C\u8BF7\u52FF\u91CD\u590D\u8FDE\u63A5\uFF01");this._clearLiveData();try{let n=await this._options.getTicket(),r=Ct(this._options.url,{ticket:n,force:+!!e.force});return this._controller.open(r),m.info("Connection established successfully"),!0}catch(n){return m.error("Failed to connect:",n),new Error("Failed to connect")}};_exit=async()=>{this._clearLiveData();try{await this.$RTC?.quit();}catch(e){m.warn(e);}return this.state!==1?!0:await this._controller.close()};exit=async()=>this.close();close=async()=>{await this._controller.readyClose();try{await this.$RTC?.quit();}catch(e){m.warn(e);}await this.updateStatus("room_change","close",{});};dispose=async()=>(this._removeLiveControllerEventListeners(),this._clearLiveData(),await this._controller.dispose());async updateStatus(e,t,n,r){if(this.state!==1)return !1;let s=Object.assign({event_type:e,action:t},{data:n}),o=St("BUILTIN_MSG",s,r);try{return this._controller.sendMessage(o),!0}catch(c){return m.error(c),!1}}setSelfInfo=async e=>await this.updateStatus("user_change","change_info",e);broadcast(e,t,n){return this.state!==1?!1:new Promise((r,s)=>{let o=St("CUSTOM_EVENT",e,t),c=o.front_request_id,a=n?setTimeout(()=>{s(new Error("RESPONSE TIMEOUT")),this.off("broadcast",l);},n):void 0,l=(d,f)=>{f===c&&(a&&clearTimeout(a),this.off("broadcast",l),r(d));};this.on("broadcast",l);try{this._controller.sendMessage(o);}catch(d){s(d);}})}toggleMicro=async e=>{if(!this.selfInfo?.permission?.control_own_micro)return !1;let t=await this.$RTC?.toggleMicro(e);return t&&await this.updateStatus("user_change","change_micro_status",{status:e?"OPEN":"CLOSE"},[]),t};forbidMicro=async(e,t)=>typeof this._options.canForbidUserMicro=="function"&&!this._options.canForbidUserMicro(t)||!this.selfInfo?.permission?.control_other_micro?!1:await this.updateStatus("user_change","change_micro_status",{status:e},t);forbidSync=async(e,t)=>typeof this._options.canForbidUserSync=="function"&&!this._options.canForbidUserSync(t)||!this.selfInfo?.permission?.control_other_sync?!1:await this.updateStatus("user_change","change_permission",{sync_frame:e},t);kick=async e=>typeof this._options.canForbidUserKick=="function"&&!this._options.canForbidUserKick(e)||!this.selfInfo?.permission?.change_other_status?!1:await this.updateStatus("user_change","change_status",{status:"KICK_OUT"},e);getSnapshotForKey(e){return this.snapshot[e]}};var yn=i=>(mn(),new We(i));function bs(i){let e=L.createContext(null),t=yn(i),n=t.jsBridge,r=h=>L__default.default.createElement(e.Provider,{value:t},h.children),s=()=>{let h=L__default.default.useContext(e);if(!h)throw new Error("LiveProvider never found.");return h},o=()=>t,c=()=>t.$RTC,a=()=>c(),l=()=>async h=>await t.connect(h);function d(h,_,D=[]){let y=s(),E=[y,name,...D],U=()=>y.keyframes.off(h,_);return L__default.default.useEffect(()=>(y.keyframes.on(h,_),U),E),U}function f(){let h=s(),_=L.useCallback(async I=>{await h.connect(I);},[h]),D=L.useCallback(I=>{h.toggleMicro(I);},[h]),y=L.useCallback(async(I,J,Fe=0)=>{await h.broadcast(I,J,Fe);},[h]),E=L.useCallback(async()=>{await h.exit();},[h]),U=L.useCallback(async I=>{await h.kick(I);},[h]),H=L.useCallback(async(I,J=[])=>{await h.forbidMicro(I,J);},[h]),ke=L.useCallback((I,J=[])=>{h.forbidSync(I,J);},[h]),$e=L.useCallback(I=>h.getFramesByKey(I),[h]),kn=L.useCallback((I,J)=>{h.sendKeyframe(I,J);},[h]),vn=L.useCallback(I=>{h.setSelfInfo(I);},[h]),Cn=L.useCallback((I,J,Fe,En)=>{h.updateStatus(I,J,Fe,En);},[h]);return {connect:_,broadcast:y,exit:E,kick:U,toggleMicro:D,forbidMicro:H,forbidSync:ke,sendKeyframe:kn,getFramesByKey:$e,setSelfInfo:vn,updateStatus:Cn}}function p(h){let _=s(),[D,y]=L__default.default.useState(_.getFramesByKey(h));L__default.default.useEffect(()=>{let U=$e=>y($e),H=h,ke=U;return _.keyframes.on(H,ke),()=>_.keyframes.off(H,ke)},[_]);let E=L__default.default.useCallback(U=>_.sendKeyframe(h,U),[_]);return [D,E]}function g(h,_,D=[]){let y=s(),E=()=>y.off(h,_),U=[y,h,...D];return L__default.default.useEffect(()=>(y.on(h,_),E),U),E}function w(){let h=s(),[_,D]=L__default.default.useState(h.state);return L__default.default.useEffect(()=>{let y=E=>D(E);return h.on("stateChange",y),()=>h.off("stateChange",y)},[h]),_}function R(){let h=s();return {join:H=>h.$RTC.join(H),quit:()=>h.$RTC.quit(),shock:()=>h.$RTC.shock?.(),toggleMicro:H=>h.$RTC.toggleMicro(H),detectMicro:()=>h.$RTC.detectMicro()}}function wn(h,_,D=[]){let y=s(),E=()=>y.$RTC.off(h,_),U=[y,h,...D];return L__default.default.useEffect(()=>(y.$RTC.on(h,_),E),U),E}function _n(){let h=s(),[_,D]=L__default.default.useState(h.selfInfo||{}),y=U=>D(U);L__default.default.useEffect(()=>(h.on("selfInfoUpdate",y),()=>h.off("selfInfoUpdate",y)),[h]);let E=L__default.default.useCallback(async U=>await h.setSelfInfo(U),[h]);return [_,E]}function bn(){let h=s(),[_,D]=L__default.default.useState(h.snapshot);return L__default.default.useEffect(()=>{let y=E=>D(E);return h.on("keyframes",y),()=>h.off("keyframes",y)},[h]),_}function Sn(){let h=s(),[_,D]=L__default.default.useState(h.userList),y=E=>D(E);return L__default.default.useEffect(()=>(h.on("userListUpdate",y),()=>h.off("userListUpdate",y)),[h]),_}return {live:t,jsBridge:n,LiveProvider:r,unsafe__useLiveInstance:o,unsafe__useRTCInstance:a,useConnect:l,useKeyframe:p,useKeyframeUpdateCallback:d,useLiveAction:f,useLiveEventCallback:g,useLiveState:w,useRTCAction:R,useRTCEventCallback:wn,useSelfInfo:_n,useKeyframesSnapshot:bn,useUserList:Sn}}console.log(`%c${process.env.__REALSEE_LIVE_VERSION__}`,"background: #237804; color: white; padding: 2px 4px; border-radius: 4px;");
|
|
68
|
-
|
|
69
|
-
exports.
|
|
70
|
-
exports.
|
|
71
|
-
exports.
|
|
72
|
-
exports.
|
|
73
|
-
exports.
|
|
74
|
-
exports.
|
|
75
|
-
exports.
|
|
76
|
-
exports.
|
|
77
|
-
exports.
|
|
78
|
-
exports.
|
|
79
|
-
exports.
|
|
80
|
-
exports.
|
|
81
|
-
exports.
|
|
82
|
-
exports.
|
|
83
|
-
exports.
|
|
84
|
-
exports.
|
|
85
|
-
exports.
|
|
86
|
-
exports.
|
|
87
|
-
exports.
|
|
88
|
-
exports.
|
|
89
|
-
exports.createLive = yn;
|
|
90
|
-
exports.createLiveReact = bs;
|
|
91
|
-
exports.parseLiveMsg = kr;
|
|
92
|
-
exports.parseWSClsErr = vt;
|
|
18
|
+
exports.BrowserRTC = xe;
|
|
19
|
+
exports.BrowserRTC4Chime = fe;
|
|
20
|
+
exports.BuiltInRTCType = ii;
|
|
21
|
+
exports.BuiltinActionType = mi;
|
|
22
|
+
exports.BuiltinEventType = pi;
|
|
23
|
+
exports.Command = gi;
|
|
24
|
+
exports.CoreRTC = J;
|
|
25
|
+
exports.Live = bt;
|
|
26
|
+
exports.LiveState = wi;
|
|
27
|
+
exports.MemUserStatus = bi;
|
|
28
|
+
exports.MicroStatus = yi;
|
|
29
|
+
exports.RTCJoinedInfoCodeEnum = fi;
|
|
30
|
+
exports.RTCType = ri;
|
|
31
|
+
exports.Subscribe = N;
|
|
32
|
+
exports.UserStatus = _i;
|
|
33
|
+
exports.VRWebViewRTC = Ie;
|
|
34
|
+
exports.WebSocketCloseError = Ei;
|
|
35
|
+
exports.WebSocketErrorType = vi;
|
|
36
|
+
exports.WebSocketState = Si;
|
|
37
|
+
exports._clearLiveInstanceIfNeed = qr;
|
|
38
|
+
exports.createLive = Jr;
|
|
39
|
+
exports.createLiveReact = qa;
|
|
40
|
+
exports.parseLiveMsg = Po;
|
|
41
|
+
exports.parseWSClsErr = Sn;
|
package/dist/index.esm.js
CHANGED
|
@@ -1,30 +1,10 @@
|
|
|
1
|
-
import
|
|
1
|
+
import vt from 'trtc-js-sdk';
|
|
2
2
|
import { ConsoleLogger, LogLevel, DefaultDeviceController, MeetingSessionConfiguration, DefaultMeetingSession, DefaultModality, MeetingSessionStatusCode } from 'amazon-chime-sdk-js';
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import * as K from 'lib0/array';
|
|
6
|
-
import * as A from 'lib0/math';
|
|
7
|
-
import * as x from 'lib0/map';
|
|
8
|
-
import * as u from 'lib0/encoding';
|
|
9
|
-
import 'lib0/decoding';
|
|
10
|
-
import * as Ne from 'lib0/random';
|
|
11
|
-
import * as He from 'lib0/promise';
|
|
12
|
-
import 'lib0/buffer';
|
|
13
|
-
import * as S from 'lib0/error';
|
|
14
|
-
import * as v from 'lib0/binary';
|
|
15
|
-
import * as pt from 'lib0/function';
|
|
16
|
-
import { callAll } from 'lib0/function';
|
|
17
|
-
import * as ge from 'lib0/set';
|
|
18
|
-
import * as B from 'lib0/logging';
|
|
19
|
-
import 'lib0/time';
|
|
20
|
-
import 'lib0/string';
|
|
21
|
-
import * as ie from 'lib0/iterator';
|
|
22
|
-
import * as $ from 'lib0/object';
|
|
23
|
-
import * as Pt from 'lib0/environment';
|
|
24
|
-
import U, { createContext, useCallback } from 'react';
|
|
3
|
+
import Ys from '@realsee/jsbridge-x';
|
|
4
|
+
import D, { createContext, useCallback } from 'react';
|
|
25
5
|
|
|
26
|
-
var ae=Symbol("$$REALSEE_LIVE_EVENT$$");function ke(i){return i[ae]||(i[ae]={}),i[ae]}function En(i){i[ae]?.length||delete i[ae];}var P=class{hasListener(e){let t=ke(this);return t&&t[e]&&t[e].length>0}on(e,t,n){let r=ke(this);return r[e]||(r[e]=[]),r[e].push([t,n||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){let n=ke(this);if(!e){En(this);return}if(n[e]||(n[e]=[]),t===void 0){n[e].length=0;return}let r=n[e].findIndex(s=>s[0]===t);r!==-1&&n[e].splice(r,1);}emit(e,...t){let n=!1,s=ke(this)[e]||[];for(let o of s.slice()){let[c,a=!1]=o,l=c(...t);a&&this.off(e,c),l===!1&&(n=!0);}return n}};var J=class extends P{};var In=(n=>(n.RealseeBrowserRTC="RealseeBrowserRTC",n.RealseeVRWebViewRTC="RealseeVRWebViewRTC",n.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",n))(In||{}),Tn=(t=>(t.RealseeXTRTC="trtc",t.RealseeXChimeRTC="chime",t))(Tn||{});var Rn=()=>{let i=new Date,e=i.getFullYear(),t=(i.getMonth()+1).toString().padStart(2,"0"),n=i.getDate().toString().padStart(2,"0"),r=i.getHours().toString().padStart(2,"0"),s=i.getMinutes().toString().padStart(2,"0"),o=i.getSeconds().toString().padStart(2,"0"),c=i.getMilliseconds().toString().padStart(3,"0");return `[${e}-${t}-${n} ${r}:${s}:${o}.${c}]`};var le=(i,e=[])=>{let t=`Realsee Live ${Rn()} <${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);}},Dn={log:(...i)=>le("LOG",i),info:(...i)=>le("INFO",i),error:(...i)=>le("ERROR",i),warn:(...i)=>le("WARN",i),debug:(...i)=>le("DEBUG",i)},m=Dn;function H(){return ((1+Math.random())*65536|0).toString(16).substring(1)}function z(){return [H(),H(),"4"+H().substring(0,3),H(),H(),H()+H()+H()].join("-").toLowerCase()}var de=class extends J{type="RealseeBrowserRTC";joined=!1;micro=!1;voiceId="";_getVoiceSign=()=>{throw new Error("\u65B9\u6CD5 getVoiceSign \u672A\u5B9E\u73B0")};_autoPlayConfirm;checkRequirement=()=>Fe.checkSystemRequirements();$dom=document.createElement("div");_trtc={client:null,stream:null};constructor(e){super(),this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initParentDom();}_initParentDom(){this.$dom.id=`rs-rtc-${z()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom);}join=async e=>{this.emit("joinWillStart");let t=await this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=Fe.createClient({mode:"rtc",...t,enableAutoPlayDialog:typeof this._autoPlayConfirm!="function"}),this._trtc.client?.enableAudioVolumeEvaluation(),this._registerRtcEvent();let n=await new Promise(r=>{this._trtc.client?.join({roomId:Number(e.voiceId)}).then(()=>r(!0)).catch(()=>r(!1));});return this.joined=n,n?(this._trtc.stream=Fe.createStream({userId:t.userId,audio:!0,video:!1}),n=await new Promise(r=>{this._trtc.stream?.initialize().then(()=>r(!0)).catch(()=>r(!1));}),n=await new Promise(r=>{this._trtc.client?.publish(this._trtc.stream).then(()=>r(!0)).catch(()=>r(!1));}),this.joined=n,this.joined&&this.emit("joined"),n):!1};quit(){return new Promise(async e=>{this.joined=!1,this._trtc.stream&&(await this._trtc.client?.unpublish(this._trtc.stream),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),this._trtc.client?.leave().then(()=>this._trtc.client=null).then(()=>e(!0)).catch(()=>e(!1)),e(!0);})}detectMicro(){return new Promise(e=>{let t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then(()=>e(!0)).catch(n=>{m.error(n.message),e(!1);});}catch(n){console.error(n),e(!1);}})}toggleMicro(e){return Promise.resolve((e?this._trtc?.stream?.unmuteAudio():this._trtc?.stream?.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){this._trtc.client?.on("stream-added",this._handleStreamAdded),this._trtc.client?.on("stream-subscribed",this._handleStreamSubscribed),this._trtc.client?.on("audio-volume",e=>this.emit("userVolumes",e.result.map(({userId:t,audioVolume:n})=>({userId:t,audioVolume:n})))),this._trtc.client?.on("error",e=>this.emit("error",e));}_handleStreamAdded=e=>{let t=e.stream;console.log("\u8FDC\u7AEF\u6D41\u589E\u52A0: "+t.getId()),this._trtc.client?.subscribe(t);};_handleStreamSubscribed=e=>{let t=e.stream;console.log("\u8FDC\u7AEF\u6D41\u8BA2\u9605\u6210\u529F\uFF1A"+t.getId());let r=`rs-rtc-remote_stream-${t.getId()}`,s=document.createElement("div");s.id=r,this.$dom.appendChild(s),typeof this._autoPlayConfirm=="function"?(t.play(r).catch(o=>{}),t.on("error",o=>{if(o.getCode()===16451){let a=()=>t.resume();this._autoPlayConfirm({onConfirm:a});}})):t.play(r);}};var te=class extends J{type="RealseeBrowserChimeRTC";joined=!1;micro=!1;voiceId="";userId="";logger;deviceController;meetingSession;audioInput;audioOutput;deviceChangeObserver={};audioVideoObserver={};audioMixObserver;_getVoiceSign=()=>{throw new Error("\u65B9\u6CD5 getVoiceSign \u672A\u5B9E\u73B0")};_autoPlayConfirm;$dom=document.createElement("div");$audio=document.createElement("audio");constructor(e){super(),this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initDom(),this.logger=new ConsoleLogger("WebRTCLogger",e.logLevel||LogLevel.INFO),this.deviceController=new DefaultDeviceController(this.logger),this.initObservers();}_initDom=()=>{this.$audio.id=`rs-rtc-${z()}`,this.$dom.id=`rs-rtc-${z()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom);};initObservers=()=>{this.deviceChangeObserver={audioInputsChanged:e=>{this.logger.info(`audioInputsChanged ${typeof e}`),e?.forEach(t=>{this.logger.info(`Device ID: ${t.deviceId} Microphone: ${t.label}`);});},audioOutputsChanged:e=>{this.logger.info(`audioOutputsChanged ${typeof e}`),e?.forEach(t=>{this.logger.info(`Device ID: ${t.deviceId} Speaker: ${t.label}`);});},audioInputMuteStateChanged:(e,t)=>{this.logger.info(`Device ${e.toString()} ${t?"is muted in hardware":"is not muted"}`);}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started");},audioVideoDidStop:e=>{this.logger.info(`Stopped with a session status code: ${e.statusCode()}`);},audioVideoDidStartConnecting:e=>{e&&this.logger.info("Attempting to reconnect");}},this.audioMixObserver={meetingAudioStreamBecameActive:e=>{if(this.$audio.paused){let t=()=>this.$audio.play().then(()=>{}).catch(n=>{if(m.error("\u64AD\u653E\u8FDC\u7AEF\u6D41\u5931\u8D25\uFF01",n),typeof this._autoPlayConfirm=="function"){let r=()=>t();this._autoPlayConfirm({onConfirm:r});}});t();}},meetingAudioStreamBecameInactive:e=>{}};};async join(e){return new Promise(async(t,n)=>{this.emit("joinWillStart");try{let{sdkAppId:r,userId:s,roomId:o,userSig:c}=await this._getVoiceSign({...e,roomId:e.roomId||0});this.userId=s;let{attendence:a,vendor_wrapper:l}=JSON.parse(decodeURIComponent(c)),d=new MeetingSessionConfiguration({Meeting:l},{Attendee:{ExternalUserId:a.external_user_id,AttendeeId:a.attendee_id,JoinToken:a.join_token}});this.meetingSession=new DefaultMeetingSession(d,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);let f={audioVideoDidStart:()=>{this.meetingSession?.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),t(!0);},audioVideoDidStop:()=>{this.joined=!1,t(!1);}};this.meetingSession.audioVideo.addObserver(f),this.audioMixObserver&&this.meetingSession.audioVideo.addAudioMixObserver(this.audioMixObserver),this.meetingSession.audioVideo.setDeviceLabelTrigger(async()=>await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}));try{let p=await this.meetingSession.audioVideo.listAudioInputDevices();m.info("audioInputDevices ===>",p);let g=p[0]?.deviceId||"default";await this.meetingSession.audioVideo.startAudioInput(g);}catch(p){m.error(`\u8BBE\u7F6E\u8BED\u97F3\u8F93\u5165\u8BBE\u5907\u5931\u8D25:${p.message}`);}try{let p=await this.meetingSession.audioVideo.listAudioOutputDevices();m.info("audioOutputDevices ===>",p);let g=p[0]?.deviceId||"default";await this.meetingSession.audioVideo.chooseAudioOutput(g);}catch(p){m.error(`\u8BBE\u7F6E\u8BED\u97F3\u8F93\u51FA\u8BBE\u5907\u5931\u8D25:${p.message}`);}this.meetingSession.audioVideo.start();}catch(r){this.emit("error",r),this.logger.error(r.message),t(!1);}})}_registerRtcEvent=()=>{let e=this.meetingSession?.configuration?.credentials?.attendeeId||"";if(e){let t=new Map,n=()=>{let r=[];return t.forEach((s,o)=>{r.push({userId:s.userId,volume:s.muted||s.signalStrength===0||!s.volume?0:s.volume});}),r};this.meetingSession?.audioVideo.realtimeSubscribeToAttendeeIdPresence((r,s,o)=>{if(!s){t.delete(r),this.emit("userVolumes",n());return}this.meetingSession?.audioVideo.realtimeSubscribeToVolumeIndicator(r,(c,a,l,d)=>{new DefaultModality(c).base()===c&&(t.set(c,{userId:o||c,volume:a,muted:l,signalStrength:d}),this.emit("userVolumes",n()));});}),this.meetingSession?.audioVideo.realtimeSubscribeToVolumeIndicator(e,(r,s,o,c)=>{new DefaultModality(r).base()===r&&c!==null&&c!==1&&this.emit("weakNetwork");}),this.meetingSession?.audioVideo.realtimeSubscribeToFatalError(r=>this.emit("error",r));}};quit(){return this.joined?new Promise((e,t)=>{this.joined=!1;let n={audioVideoDidStop:async r=>{let s=r.statusCode();this.meetingSession?.deviceController.destroy(),s===MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${s}`),e(!0));}};this.meetingSession?.audioVideo.addObserver(n),this.meetingSession?.audioVideo.stop();}):Promise.resolve(!0)}async detectMicro(){return new Promise(e=>{let t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then(()=>e(!0)).catch(()=>e(!1));}catch(n){this.logger.error(n.message),e(!1);}})}async toggleMicro(e){e?this.meetingSession?.audioVideo.realtimeUnmuteLocalAudio():this.meetingSession?.audioVideo.realtimeMuteLocalAudio();let t=this.meetingSession?.audioVideo.realtimeIsLocalAudioMuted();return t!==void 0?e!==t:!1}shock(){throw new Error("Method not implemented.")}};var Mn=(s=>(s[s.Success=0]="Success",s[s.Failure=1]="Failure",s[s.ReJoin=2]="ReJoin",s[s.NoMicroPermission=3]="NoMicroPermission",s[s.Unknown=500]="Unknown",s))(Mn||{});var he=class extends J{type="RealseeVRWebViewRTC";joined=!1;micro=!1;voiceId="";_joinOptions=null;options;get jsBridge(){return this.options.jsBridge}constructor({jsBridge:e,getVoiceSign:t}){super(),this.options={jsBridge:e,getVoiceSign:t},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);}handleUserVolumes=e=>{this.emit("userVolumes",e);};handleWeakNetwork=e=>{e&&this.emit("weakNetwork");};join=async e=>{this._joinOptions=e,this.emit("joinWillStart");let{sdkAppId:t,userId:n,userSig:r}=await this.getVoiceSignOrEmitError(e);return !t||!n||!r?!1:(this.type=e.type,this.jsBridge.webViewType==="WxMiniProgramWebView"?this.handleWxMiniProgramWebViewJoin({sdkAppId:t,userId:n,userSig:r,voiceId:e.voiceId}):this.handleAppWebViewJoin({sdkAppId:t,userId:n,userSig:r,voiceId:e.voiceId}))};reJoin=async()=>this._joinOptions?this.join({voiceId:this._joinOptions.voiceId,userId:this._joinOptions.userId,roomId:this._joinOptions.roomId,type:this._joinOptions.type}):(this.emitErrorAndSetJoinedFalse("\u91CD\u8FDE\u5931\u8D25\uFF1A\u672A\u627E\u5230\u52A0\u5165\u623F\u95F4\u53C2\u6570\u3002"),!1);getVoiceSignOrEmitError=async e=>{try{return await this.options.getVoiceSign(e)}catch{return this.emitErrorAndSetJoinedFalse("\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1Artc \u7B7E\u540D\u8BF7\u6C42\u5F02\u5E38"),{}}};handleWxMiniProgramWebViewJoin=async e=>{let[t,n]=await this.joinRoomOrEmitError(e);return n?!1:this.handleJoinResult(t)};handleAppWebViewJoin=e=>new Promise(t=>{this.off("inner.rtc.success");let n=r=>{this.off("inner.rtc.fail",n),this.off("inner.rtc.success",n),t(this.handleJoinResult(r));};this.once("inner.rtc.fail",n),this.once("inner.rtc.success",n);try{let{sdkAppId:r,userId:s,userSig:o,voiceId:c}=e;this.jsBridge.callAndListen(`live/join?sdkAppID=${r}&userID=${s}&roomID=${c}&userSig=${o}`,a=>{a===!0?this.emit("inner.rtc.success",a):typeof a=="object"?a.code===0||a.code===2?this.emit("inner.rtc.success",a):this.emit("inner.rtc.fail",a):this.emit("inner.rtc.fail",a);});}catch(r){t(this.handleJoinResult({message:r.message,code:500}));}});joinRoomOrEmitError=async({sdkAppId:e,userId:t,voiceId:n,userSig:r})=>{try{return await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${e}&userID=${t}&roomID=${Number(n)}&userSig=${r}`)}catch(s){return this.emitErrorAndSetJoinedFalse("\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1A"+s.message),[null,s]}};handleJoinResult=e=>{switch(!0){case e===!0:case(typeof e=="object"&&e.code===0):case(typeof e=="object"&&e.code===2):{this.emit("joined"),this.joined=!0;break}default:{this.joined=!1;let t=typeof e=="object"?e.message:"\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1A\u672A\u77E5\u5F02\u5E38\u3002";this.emit("error",new Error(t,{cause:e}));}}return this.joined};emitErrorAndSetJoinedFalse=e=>{this.emit("error",new Error(e)),this.joined=!1;};quit=async()=>{let[e,t]=await this.jsBridge.callAndBackfeed("live/quit");return e===null&&this.emit("error",t||new Error("\u9000\u51FA\u623F\u95F4\u5931\u8D25\uFF1A\u672A\u77E5\u5F02\u5E38\u3002")),this.joined=!1,!!e};detectMicro=async()=>{let[e,t]=await this.jsBridge.detectMicro();return e===null?(this.emit("error",t||new Error("\u9EA6\u514B\u98CE\u76D1\u6D4B\u5F02\u5E38\uFF01")),!1):e};toggleMicro=async e=>{let[t,n]=await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${e?1:0}`);return t===null?(this.emit("error",n||new Error("\u9EA6\u514B\u98CE\u76D1\u6D4B\u5F02\u5E38\uFF01")),!1):(this.micro=t,t)};shock=()=>{this.jsBridge.shock(1);}};var Kn=(a=>(a.SelfUserInfo="SELF_USER_INFO",a.RoomInfo="ROOM_INFO",a.RTCInfo="RTC_INFO",a.UserList="USER_LIST",a.BuiltinMsg="BUILTIN_MSG",a.CustomEvent="CUSTOM_EVENT",a.KeyframeSync="KEYFRAME_SYNC",a.UserKickOut="USER_KICK_OUT",a))(Kn||{}),Nn=(t=>(t.UserChange="user_change",t.RoomChange="room_change",t))(Nn||{}),Bn=(o=>(o.UserMicroStatus="change_micro_status",o.UserMicroStatusSync="sync_micro_status",o.UserPermission="change_permission",o.UserStatus="change_status",o.UserInfo="change_info",o.RoomClose="close",o))(Bn||{}),Pn=(t=>(t.OPEN="OPEN",t.CLOSE="CLOSE",t))(Pn||{});function hr(i){try{let 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(r=>t[r]===void 0);return n.length>0&&console.warn(`\u63A8\u9001\u6570\u636E\u683C\u5F0F\u5F02\u5E38\uFF1A${n.join(" ")} \u503C\u4E0D\u5B58\u5728\uFF01`),t}catch{return !1}}var jn=(r=>(r[r.NOTINITIALIZED=-1]="NOTINITIALIZED",r[r.CONNECTING=0]="CONNECTING",r[r.OPEN=1]="OPEN",r[r.CLOSED=3]="CLOSED",r))(jn||{});var Wn=(n=>(n[n.Normal=0]="Normal",n[n.Removed=1]="Removed",n[n.Replaced=2]="Replaced",n))(Wn||{}),$n=(o=>(o.WAIT_ENTER="WAIT_ENTER",o.ONLINE="ONLINE",o.LEAVE="LEAVE",o.KICK_OUT="KICK_OUT",o.BE_REPLACE="BE_REPLACE",o.EXCEPTION="EXCEPTION",o))($n||{});var Fn=(s=>(s[s.NOTINITIALIZED=-1]="NOTINITIALIZED",s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(Fn||{}),Jn=(c=>(c.Error="Error",c.Close="Close",c.MicroAuth="MicroAuth",c.DuplicateConnect="DuplicateConnect",c.IllegalURL="IllegalURL",c.Unknown="Unknown",c.IllegalArgs="IllegalArgs",c))(Jn||{}),Gn=(l=>(l.Err_1000="CLOSE_NORMAL",l.Err_1001="CLOSE_GOING_AWAY",l.Err_1002="CLOSE_PROTOCOL_ERROR",l.Err_1003="CLOSE_UNSUPPORTED",l.Err_1006="CLOSE_ABNORMAL",l.Err_1007="Unsupported Data",l.Err_1008="Policy Violation",l.Err_1009="CLOSE_TOO_LARGE",l.Err_unknown="unknown",l))(Gn||{});function kt(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 vt(i,e={}){let t=new URL(i,"http://localhost"),n=new URLSearchParams(t.search);return Object.entries(e).forEach(([r,s])=>{n.append(r,String(s));}),i.split("?")[0]+"?"+n.toString()}var Ct=(()=>{let i=typeof process<"u"&&process.versions?.node!=null;return typeof window<"u"&&"Deno"in window||i||typeof window>"u"})();var ue=Ct?"":navigator.userAgent,Et=/android/i.test(ue),It=/iPhone|iPad\s+OS/i.test(ue),Tt=/MicroMessenger/i.test(ue)&&/miniProgram/i.test(ue),Rt=/realsee/i.test(ue);function ve(i){return Object.prototype.toString.call(i)==="[object Object]"}function Ce(i,e){return i===e?!0:i==null||e==null||typeof i!=typeof e?!1:Number.isNaN(i)&&Number.isNaN(e)}function qn(i,e){if(i===e)return !0;if(i==null||e==null)return !1;let t=Object.keys(i),n=Object.keys(e);return t.length!==n.length?!1:t.every(r=>Ce(i[r],e[r]))}function Hn(i,e){return i===e?!0:i==null||e==null||i.length!==e.length?!1:i.every((t,n)=>Ce(t,e[n]))}function zn(i,e){return Ce(i,e)?!0:ve(i)&&ve(e)?qn(i,e):Array.isArray(i)&&Array.isArray(e)?Hn(i,e):!1}function Je(i,e){return Ce(i,e)?!0:ve(i)&&ve(e)?Xn(i,e):Array.isArray(i)&&Array.isArray(e)?Yn(i,e):!1}function Yn(i,e){if(i.length!==e.length)return !1;for(let t=0,n=i.length;t<n;t++)if(!Je(i[t],e[t]))return !1;return !0}function Xn(i,e){if(i===e)return !0;if(i==null||e==null)return !1;let t=Object.keys(i),n=Object.keys(e);return t.length!==n.length?!1:t.every(r=>Je(i[r],e[r]))}function Dt(i,e,t={deep:!1}){return t.deep?Je(i,e):zn(i,e)}var Ee=class extends P{_realWebSocket;_url;_protocols;_readyState=-1;_options={timeout:1e4,shouldReconnect:(e,t)=>{if(!(e.code===1008||e.code===1011))return [0,1e3,2e3][t.attempts%3]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1};_connectTimeout;_attempts=0;_reconnects=-1;_reconnectWhenOnlineAgain=!1;_explicitlyClosed=!1;_pendingReconnect;_connectivityEventsAttached=!1;_heathCheckTimer;get attempts(){return this._attempts}constructor(e){super(),e&&this.setOptions(e),this._startHealthCheck();}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;let t=Object.assign(this._options,e.robustOptions||{});if(typeof t?.timeout!="number")throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if(typeof t?.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=t,this._options.automaticOpen&&this._createWebSocket();}_healthCheck=async()=>{if(this._realWebSocket){let e=this._realWebSocket.readyState;e!==this._readyState&&(this._readyState=e,this._readyState===2&&this.emit("closing"));}await new Promise(e=>setTimeout(e,2e3)),this._heathCheckTimer=requestAnimationFrame(this._healthCheck);};_clearConnectTimeoutIfNeed=()=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);};_clearHeathCheckIfNeed=()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0);};_startHealthCheck=()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck);};_stopHealthCheck=()=>{this._clearHeathCheckIfNeed();};_clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0);};_online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e));};_offline=()=>{this._reconnectWhenOnlineAgain=!0,this._realWebSocket?.close(1e3,"offline");};_detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(globalThis?.removeEventListener("online",this._online),globalThis?.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1);};_attachConnectivityEvents=()=>{this._connectivityEventsAttached||(globalThis?.addEventListener("online",this._online),globalThis?.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0);};send=e=>{this._realWebSocket?.readyState===this._realWebSocket?.OPEN&&this._realWebSocket?.send(e);};close=(e,t)=>(typeof e!="number"&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),this._realWebSocket?.close(e,t));open=e=>{e&&(this._url=e),this._realWebSocket?.readyState!==WebSocket.OPEN&&this._realWebSocket?.readyState!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket());};_createWebSocket=()=>{let e=typeof this._url=="string"?this._url:this._url?.(this);if(!e)return;this._clearConnectTimeoutIfNeed(),this._clearPendingReconnectIfNeeded(),this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(e,this._protocols||void 0),this._attempts++,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));let t=()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("timeout",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));};this._connectTimeout=setTimeout(t,this._options.timeout),this._dispatchWebSocketEvent(),this._options.ignoreConnectivityEvents||this._attachConnectivityEvents();};_removeWebSocketEvent=()=>{this._realWebSocket?.removeEventListener("open",this._webSocketOpenHandler),this._realWebSocket?.removeEventListener("close",this._webSocketCloseHandler),this._realWebSocket?.removeEventListener("error",this._webSocketErrorHandler),this._realWebSocket?.removeEventListener("message",this._webSocketMessageHandler);};_dispatchWebSocketEvent=()=>{this._realWebSocket?.addEventListener("open",this._webSocketOpenHandler),this._realWebSocket?.addEventListener("close",this._webSocketCloseHandler),this._realWebSocket?.addEventListener("error",this._webSocketErrorHandler),this._realWebSocket?.addEventListener("message",this._webSocketMessageHandler);};_webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);let t=++this._reconnects,n=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:n}}))};_webSocketCloseHandler=e=>(this._reconnect(e),this._stopHealthCheck(),this.emit("close",e));_webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}}));_webSocketMessageHandler=e=>this.emit("message",e);_reconnect(e){if(!this._options.should1000Reconnect&&e.code===1e3||this._explicitlyClosed){this._attempts=0;return}if(this._connectivityEventsAttached&&globalThis?.navigator?.onLine===!1){this._reconnectWhenOnlineAgain=!0;return}let r=this._options.shouldReconnect?.(e,this);typeof r=="number"?(console.log(`Reconnecting in ${r}ms...`),this._pendingReconnect=setTimeout(this._createWebSocket,r)):console.log("No reconnection will be attempted.");}};var Ie=class extends P{_ws=new Ee({url:"",robustOptions:{should1000Reconnect:!0,ignoreConnectivityEvents:!0}});_state=-1;set state(e){let t=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,t);}get state(){return this._state}constructor(){super(),this._addWebSocketEventListeners();}_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);};_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);};_handleCloseEvent=e=>{m.info(`live room closed bacause of ${e.code}-${e.reason||kt(e.code)}`),this.state=3;};_handleClosingEvent=()=>{m.info("live room is closing, onLine:",globalThis?.navigator?.onLine),this.state=3;};_handleConnectingEvent=e=>{m.info("live room is connecting"),this.state=0,e.detail.reconnects>0&&this.emit("reconnecting",e.detail);};_handleErrorEvent=e=>{m.error("live room error",e),this.state=3;};_handleMessageEvent=e=>{let t=(()=>{try{return JSON.parse(e.data)}catch{return e.data}})();this.emit("message",t);};_handleOpenEvent=e=>{m.info("live room open",e.detail),this.state=1,e.detail.reconnects>0&&this.emit("reconnected",e.detail);};_handleTimeoutEvent=e=>{m.error("live room connect timeout!",e.detail),this.state=3;};dispose=async()=>(this._removeWebSocketEventListeners(),await this.close("live room close by controller disposed!"));open=e=>this._ws.open(e);close=(e,t)=>new Promise(n=>{this._ws.once("close",()=>n(!0)),this._ws.close(e,t);});sendMessage(e=""){if(e==null)throw new Error("live message is empty!");if(this.state!==1)throw new Error("live has not yet been initialized!");return this._ws.send(JSON.stringify(e))}readyClose(){this._ws&&(this._ws._explicitlyClosed=!0);}};var ze=class{constructor(e,t){this.clock=e,this.len=t;}},Ue=class{constructor(){this.clients=new Map;}},jt=(i,e,t)=>e.clients.forEach((n,r)=>{let s=i.doc.store.clients.get(r);for(let o=0;o<n.length;o++){let c=n[o];Ht(i,s,c.clock,c.len,t);}}),ii=(i,e)=>{let t=0,n=i.length-1;for(;t<=n;){let r=A.floor((t+n)/2),s=i[r],o=s.clock;if(o<=e){if(e<o+s.len)return r;t=r+1;}else n=r-1;}return null},Wt=(i,e)=>{let t=i.clients.get(e.client);return t!==void 0&&ii(t,e.clock)!==null},$t=i=>{i.clients.forEach(e=>{e.sort((r,s)=>r.clock-s.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],s=e[t];r.clock+r.len>=s.clock?r.len=A.max(r.len,s.clock+s.len-r.clock):(n<t&&(e[n]=s),n++);}e.length=n;});};var Ft=(i,e,t,n)=>{x.setIfUndefined(i.clients,e,()=>[]).push(new ze(t,n));};var si=(i,e)=>{u.writeVarUint(i.restEncoder,e.clients.size),K.from(e.clients.entries()).sort((t,n)=>n[0]-t[0]).forEach(([t,n])=>{i.resetDsCurVal(),u.writeVarUint(i.restEncoder,t);let r=n.length;u.writeVarUint(i.restEncoder,r);for(let s=0;s<r;s++){let o=n[s];i.writeDsClock(o.clock),i.writeDsLen(o.len);}});};var Jt=Ne.uint32,ee=class i extends ObservableV2{constructor({guid:e=Ne.uuidv4(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:c=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Jt(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new it,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=c,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=He.create(l=>{this.on("load",()=>{this.isLoaded=!0,l(this);});});let a=()=>He.create(l=>{let d=f=>{(f===void 0||f===!0)&&(this.off("sync",d),l());};this.on("sync",d);});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=a()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this]);}),this.whenSynced=a();}load(){let e=this._item;e!==null&&!this.shouldLoad&&b(e.parent.doc,t=>{t.subdocsLoaded.add(this);},null,!0),this.shouldLoad=!0;}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(K.from(this.subdocs).map(e=>e.guid))}transact(e,t=null){return b(this,e,t)}get(e,t=I){let n=x.setIfUndefined(this.share,e,()=>{let s=new t;return s._integrate(this,null),s}),r=n.constructor;if(t!==I&&r!==t)if(r===I){let s=new t;s._map=n._map,n._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s;}),s._start=n._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=n._length,this.share.set(e,s),s._integrate(this,null),s}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,at)}getText(e=""){return this.get(e,ut)}getMap(e=""){return this.get(e,dt)}getXmlElement(e=""){return this.get(e,Ae)}getXmlFragment(e=""){return this.get(e,we)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON();}),e}destroy(){this.isDestroyed=!0,K.from(this.subdocs).forEach(t=>t.destroy());let e=this._item;if(e!==null){this._item=null;let t=e.content;t.doc=new i({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,b(e.parent.doc,n=>{let r=t.doc;e.deleted||n.subdocsAdded.add(r),n.subdocsRemoved.add(this);},null,!0);}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy();}};var Ye=class{constructor(){this.restEncoder=u.createEncoder();}toUint8Array(){return u.toUint8Array(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){u.writeVarUint(this.restEncoder,e);}writeDsLen(e){u.writeVarUint(this.restEncoder,e);}},Xe=class extends Ye{writeLeftID(e){u.writeVarUint(this.restEncoder,e.client),u.writeVarUint(this.restEncoder,e.clock);}writeRightID(e){u.writeVarUint(this.restEncoder,e.client),u.writeVarUint(this.restEncoder,e.clock);}writeClient(e){u.writeVarUint(this.restEncoder,e);}writeInfo(e){u.writeUint8(this.restEncoder,e);}writeString(e){u.writeVarString(this.restEncoder,e);}writeParentInfo(e){u.writeVarUint(this.restEncoder,e?1:0);}writeTypeRef(e){u.writeVarUint(this.restEncoder,e);}writeLen(e){u.writeVarUint(this.restEncoder,e);}writeAny(e){u.writeAny(this.restEncoder,e);}writeBuf(e){u.writeVarUint8Array(this.restEncoder,e);}writeJSON(e){u.writeVarString(this.restEncoder,JSON.stringify(e));}writeKey(e){u.writeVarString(this.restEncoder,e);}},Ze=class{constructor(){this.restEncoder=u.createEncoder(),this.dsCurrVal=0;}toUint8Array(){return u.toUint8Array(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0;}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,u.writeVarUint(this.restEncoder,t);}writeDsLen(e){e===0&&S.unexpectedCase(),u.writeVarUint(this.restEncoder,e-1),this.dsCurrVal+=e;}},Qe=class extends Ze{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new u.IntDiffOptRleEncoder,this.clientEncoder=new u.UintOptRleEncoder,this.leftClockEncoder=new u.IntDiffOptRleEncoder,this.rightClockEncoder=new u.IntDiffOptRleEncoder,this.infoEncoder=new u.RleEncoder(u.writeUint8),this.stringEncoder=new u.StringEncoder,this.parentInfoEncoder=new u.RleEncoder(u.writeUint8),this.typeRefEncoder=new u.UintOptRleEncoder,this.lenEncoder=new u.UintOptRleEncoder;}toUint8Array(){let e=u.createEncoder();return u.writeVarUint(e,0),u.writeVarUint8Array(e,this.keyClockEncoder.toUint8Array()),u.writeVarUint8Array(e,this.clientEncoder.toUint8Array()),u.writeVarUint8Array(e,this.leftClockEncoder.toUint8Array()),u.writeVarUint8Array(e,this.rightClockEncoder.toUint8Array()),u.writeVarUint8Array(e,u.toUint8Array(this.infoEncoder)),u.writeVarUint8Array(e,this.stringEncoder.toUint8Array()),u.writeVarUint8Array(e,u.toUint8Array(this.parentInfoEncoder)),u.writeVarUint8Array(e,this.typeRefEncoder.toUint8Array()),u.writeVarUint8Array(e,this.lenEncoder.toUint8Array()),u.writeUint8Array(e,u.toUint8Array(this.restEncoder)),u.toUint8Array(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){u.writeAny(this.restEncoder,e);}writeBuf(e){u.writeVarUint8Array(this.restEncoder,e);}writeJSON(e){u.writeAny(this.restEncoder,e);}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t);}},oi=(i,e,t,n)=>{n=A.max(n,e[0].id.clock);let r=G(e,n);u.writeVarUint(i.restEncoder,e.length-r),i.writeClient(t),u.writeVarUint(i.restEncoder,n);let s=e[r];s.write(i,n-s.id.clock);for(let o=r+1;o<e.length;o++)e[o].write(i,0);},ci=(i,e,t)=>{let n=new Map;t.forEach((r,s)=>{M(e,s)>r&&n.set(s,r);}),mt(e).forEach((r,s)=>{t.has(s)||n.set(s,0);}),u.writeVarUint(i.restEncoder,n.size),K.from(n.entries()).sort((r,s)=>s[0]-r[0]).forEach(([r,s])=>{oi(i,e.clients.get(r),r,s);});};var ai=(i,e)=>ci(i,e.doc.store,e.beforeState);var et=class{constructor(){this.l=[];}},Ot=()=>new et,Ut=(i,e)=>i.l.push(e),Lt=(i,e)=>{let t=i.l,n=t.length;i.l=t.filter(r=>e!==r),n===i.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.");},Gt=(i,e,t)=>pt.callAll(i.l,[e,t]),re=class{constructor(e,t){this.client=e,this.clock=t;}},Te=(i,e)=>i===e||i!==null&&e!==null&&i.client===e.client&&i.clock===e.clock,k=(i,e)=>new re(i,e);var li=i=>{for(let[e,t]of i.doc.share.entries())if(t===i)return e;throw S.unexpectedCase()};var ne=(i,e)=>e===void 0?!i.deleted:e.sv.has(i.id.client)&&(e.sv.get(i.id.client)||0)>i.id.clock&&!Wt(e.ds,i.id),nt=(i,e)=>{let t=x.setIfUndefined(i.meta,nt,ge.create),n=i.doc.store;t.has(e)||(e.sv.forEach((r,s)=>{r<M(n,s)&&X(i,k(s,r));}),jt(i,e.ds,r=>{}),t.add(e));};var it=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null;}},mt=i=>{let e=new Map;return i.clients.forEach((t,n)=>{let r=t[t.length-1];e.set(n,r.id.clock+r.length);}),e},M=(i,e)=>{let t=i.clients.get(e);if(t===void 0)return 0;let n=t[t.length-1];return n.id.clock+n.length},qt=(i,e)=>{let t=i.clients.get(e.id.client);if(t===void 0)t=[],i.clients.set(e.id.client,t);else {let n=t[t.length-1];if(n.id.clock+n.length!==e.id.clock)throw S.unexpectedCase()}t.push(e);},G=(i,e)=>{let t=0,n=i.length-1,r=i[n],s=r.id.clock;if(s===e)return n;let o=A.floor(e/(s+r.length-1)*n);for(;t<=n;){if(r=i[o],s=r.id.clock,s<=e){if(e<s+r.length)return o;t=o+1;}else n=o-1;o=A.floor((t+n)/2);}throw S.unexpectedCase()},hi=(i,e)=>{let t=i.clients.get(e.client);return t[G(t,e.clock)]},Ge=hi,rt=(i,e,t)=>{let n=G(e,t),r=e[n];return r.id.clock<t&&r instanceof V?(e.splice(n+1,0,un(i,r,t-r.id.clock)),n+1):n},X=(i,e)=>{let t=i.doc.store.clients.get(e.client);return t[rt(i,t,e.clock)]},Vt=(i,e,t)=>{let n=e.clients.get(t.client),r=G(n,t.clock),s=n[r];return t.clock!==s.id.clock+s.length-1&&s.constructor!==W&&n.splice(r+1,0,un(i,s,t.clock-s.id.clock+1)),s},ui=(i,e,t)=>{let n=i.clients.get(e.id.client);n[G(n,e.id.clock)]=t;},Ht=(i,e,t,n,r)=>{if(n===0)return;let s=t+n,o=rt(i,e,t),c;do c=e[o++],s<c.id.clock+c.length&&rt(i,e,s),r(c);while(o<e.length&&e[o].id.clock<s)},st=class{constructor(e,t,n){this.doc=e,this.deleteSet=new Ue,this.beforeState=mt(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;}},At=(i,e)=>e.deleteSet.clients.size===0&&!x.any(e.afterState,(t,n)=>e.beforeState.get(n)!==t)?!1:($t(e.deleteSet),ai(i,e),si(i,e.deleteSet),!0),xt=(i,e,t)=>{let n=e._item;(n===null||n.id.clock<(i.beforeState.get(n.id.client)||0)&&!n.deleted)&&x.setIfUndefined(i.changed,e,ge.create).add(t);},Oe=(i,e)=>{let t=i[e],n=i[e-1],r=e;for(;r>0;t=n,n=i[--r-1]){if(n.deleted===t.deleted&&n.constructor===t.constructor&&n.mergeWith(t)){t instanceof V&&t.parentSub!==null&&t.parent._map.get(t.parentSub)===t&&t.parent._map.set(t.parentSub,n);continue}break}let s=e-r;return s&&i.splice(e+1-s,s),s},fi=(i,e,t)=>{for(let[n,r]of i.clients.entries()){let s=e.clients.get(n);for(let o=r.length-1;o>=0;o--){let c=r[o],a=c.clock+c.len;for(let l=G(s,c.clock),d=s[l];l<s.length&&d.id.clock<a;d=s[++l]){let f=s[l];if(c.clock+c.len<=f.id.clock)break;f instanceof V&&f.deleted&&!f.keep&&t(f)&&f.gc(e,!1);}}}},gi=(i,e)=>{i.clients.forEach((t,n)=>{let r=e.clients.get(n);for(let s=t.length-1;s>=0;s--){let o=t[s],c=A.min(r.length-1,1+G(r,o.clock+o.len-1));for(let a=c,l=r[a];a>0&&l.id.clock>=o.clock;l=r[a])a-=1+Oe(r,a);}});};var zt=(i,e)=>{if(e<i.length){let t=i[e],n=t.doc,r=n.store,s=t.deleteSet,o=t._mergeStructs;try{$t(s),t.afterState=mt(t.doc.store),n.emit("beforeObserverCalls",[t,n]);let c=[];t.changed.forEach((a,l)=>c.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(t,a);})),c.push(()=>{t.changedParentTypes.forEach((a,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(a=a.filter(d=>d.target._item===null||!d.target._item.deleted),a.forEach(d=>{d.currentTarget=l,d._path=null;}),a.sort((d,f)=>d.path.length-f.path.length),Gt(l._dEH,a,t));});}),c.push(()=>n.emit("afterTransaction",[t,n])),callAll(c,[]),t._needFormattingCleanup&&vi(t);}finally{n.gc&&fi(s,r,n.gcFilter),gi(s,r),t.afterState.forEach((d,f)=>{let p=t.beforeState.get(f)||0;if(p!==d){let g=r.clients.get(f),w=A.max(G(g,p),1);for(let T=g.length-1;T>=w;)T-=1+Oe(g,T);}});for(let d=o.length-1;d>=0;d--){let{client:f,clock:p}=o[d].id,g=r.clients.get(f),w=G(g,p);w+1<g.length&&Oe(g,w+1)>1||w>0&&Oe(g,w);}if(!t.local&&t.afterState.get(n.clientID)!==t.beforeState.get(n.clientID)&&(B.print(B.ORANGE,B.BOLD,"[yjs] ",B.UNBOLD,B.RED,"Changed the client-id because another client seems to be using it."),n.clientID=Jt()),n.emit("afterTransactionCleanup",[t,n]),n._observers.has("update")){let d=new Xe;At(d,t)&&n.emit("update",[d.toUint8Array(),t.origin,n,t]);}if(n._observers.has("updateV2")){let d=new Qe;At(d,t)&&n.emit("updateV2",[d.toUint8Array(),t.origin,n,t]);}let{subdocsAdded:c,subdocsLoaded:a,subdocsRemoved:l}=t;(c.size>0||l.size>0||a.size>0)&&(c.forEach(d=>{d.clientID=n.clientID,d.collectionid==null&&(d.collectionid=n.collectionid),n.subdocs.add(d);}),l.forEach(d=>n.subdocs.delete(d)),n.emit("subdocs",[{loaded:a,added:c,removed:l},n,t]),l.forEach(d=>d.destroy())),i.length<=e+1?(n._transactionCleanups=[],n.emit("afterAllTransactions",[n,i])):zt(i,e+1);}}},b=(i,e,t=null,n=!0)=>{let r=i._transactionCleanups,s=!1,o=null;i._transaction===null&&(s=!0,i._transaction=new st(i,t,n),r.push(i._transaction),r.length===1&&i.emit("beforeAllTransactions",[i]),i.emit("beforeTransaction",[i._transaction,i]));try{o=e(i._transaction);}finally{if(s){let c=i._transaction===r[0];i._transaction=null,c&&zt(r,0);}}return o};var Mt="You must not compute changes after the event-handler fired.",se=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null;}get path(){return this._path||(this._path=pi(this.currentTarget,this.target))}deletes(e){return Wt(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw S.create(Mt);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(r=>{if(r!==null){let s=t._map.get(r),o,c;if(this.adds(s)){let a=s.left;for(;a!==null&&this.adds(a);)a=a.left;if(this.deletes(s))if(a!==null&&this.deletes(a))o="delete",c=K.last(a.content.getContent());else return;else a!==null&&this.deletes(a)?(o="update",c=K.last(a.content.getContent())):(o="add",c=void 0);}else if(this.deletes(s))o="delete",c=K.last(s.content.getContent());else return;e.set(r,{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 S.create(Mt);let t=this.target,n=ge.create(),r=ge.create(),s=[];if(e={added:n,deleted:r,delta:s,keys:this.keys},this.transaction.changed.get(t).has(null)){let c=null,a=()=>{c&&s.push(c);};for(let l=t._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((c===null||c.delete===void 0)&&(a(),c={delete:0}),c.delete+=l.length,r.add(l)):this.adds(l)?((c===null||c.insert===void 0)&&(a(),c={insert:[]}),c.insert=c.insert.concat(l.content.getContent()),n.add(l)):((c===null||c.retain===void 0)&&(a(),c={retain:0}),c.retain+=l.length);c!==null&&c.retain===void 0&&a();}this._changes=e;}return e}},pi=(i,e)=>{let t=[];for(;e._item!==null&&e!==i;){if(e._item.parentSub!==null)t.unshift(e._item.parentSub);else {let n=0,r=e._item.parent._start;for(;r!==e._item&&r!==null;)!r.deleted&&r.countable&&(n+=r.length),r=r.right;t.unshift(n);}e=e._item.parent;}return t},L=()=>{B.warn("Invalid access: Add Yjs type to a document before reading data.");},Yt=80,yt=0,ot=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=yt++;}},mi=i=>{i.timestamp=yt++;},Xt=(i,e,t)=>{i.p.marker=!1,i.p=e,e.marker=!0,i.index=t,i.timestamp=yt++;},yi=(i,e,t)=>{if(i.length>=Yt){let n=i.reduce((r,s)=>r.timestamp<s.timestamp?r:s);return Xt(n,e,t),n}else {let n=new ot(e,t);return i.push(n),n}},Be=(i,e)=>{if(i._start===null||e===0||i._searchMarker===null)return null;let t=i._searchMarker.length===0?null:i._searchMarker.reduce((s,o)=>A.abs(e-s.index)<A.abs(e-o.index)?s:o),n=i._start,r=0;for(t!==null&&(n=t.p,r=t.index,mi(t));n.right!==null&&r<e;){if(!n.deleted&&n.countable){if(e<r+n.length)break;r+=n.length;}n=n.right;}for(;n.left!==null&&r>e;)n=n.left,!n.deleted&&n.countable&&(r-=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&&(r-=n.length);return t!==null&&A.abs(t.index-r)<n.parent.length/Yt?(Xt(t,n,r),t):yi(i._searchMarker,n,r)},pe=(i,e,t)=>{for(let n=i.length-1;n>=0;n--){let r=i[n];if(t>0){let s=r.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(r.index-=s.length);if(s===null||s.marker===!0){i.splice(n,1);continue}r.p=s,s.marker=!0;}(e<r.index||t>0&&e===r.index)&&(r.index=A.max(e,r.index+t));}};var Pe=(i,e,t)=>{let n=i,r=e.changedParentTypes;for(;x.setIfUndefined(r,i,()=>[]).push(t),i._item!==null;)i=i._item.parent;Gt(n._eH,t,e);},I=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Ot(),this._dEH=Ot(),this._searchMarker=null;}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t;}_copy(){throw S.methodUnimplemented()}clone(){throw S.methodUnimplemented()}_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){Ut(this._eH,e);}observeDeep(e){Ut(this._dEH,e);}unobserve(e){Lt(this._eH,e);}unobserveDeep(e){Lt(this._dEH,e);}toJSON(){}},Zt=(i,e,t)=>{i.doc??L(),e<0&&(e=i._length+e),t<0&&(t=i._length+t);let n=t-e,r=[],s=i._start;for(;s!==null&&n>0;){if(s.countable&&!s.deleted){let o=s.content.getContent();if(o.length<=e)e-=o.length;else {for(let c=e;c<o.length&&n>0;c++)r.push(o[c]),n--;e=0;}}s=s.right;}return r},Qt=i=>{i.doc??L();let e=[],t=i._start;for(;t!==null;){if(t.countable&&!t.deleted){let n=t.content.getContent();for(let r=0;r<n.length;r++)e.push(n[r]);}t=t.right;}return e};var me=(i,e)=>{let t=0,n=i._start;for(i.doc??L();n!==null;){if(n.countable&&!n.deleted){let r=n.content.getContent();for(let s=0;s<r.length;s++)e(r[s],t++,i);}n=n.right;}},en=(i,e)=>{let t=[];return me(i,(n,r)=>{t.push(e(n,r,i));}),t},wi=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;}let r=t[n++];return t.length<=n&&(t=null),{done:!1,value:r}}}},tn=(i,e)=>{i.doc??L();let t=Be(i,e),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;}},Le=(i,e,t,n)=>{let r=t,s=i.doc,o=s.clientID,c=s.store,a=t===null?e._start:t.right,l=[],d=()=>{l.length>0&&(r=new V(k(o,M(c,o)),r,r&&r.lastId,a,a&&a.id,e,null,new _e(l)),r.integrate(i,0),l=[]);};n.forEach(f=>{if(f===null)l.push(f);else switch(f.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(f);break;default:switch(d(),f.constructor){case Uint8Array:case ArrayBuffer:r=new V(k(o,M(c,o)),r,r&&r.lastId,a,a&&a.id,e,null,new Me(new Uint8Array(f))),r.integrate(i,0);break;case ee:r=new V(k(o,M(c,o)),r,r&&r.lastId,a,a&&a.id,e,null,new Ke(f)),r.integrate(i,0);break;default:if(f instanceof I)r=new V(k(o,M(c,o)),r,r&&r.lastId,a,a&&a.id,e,null,new Q(f)),r.integrate(i,0);else throw new Error("Unexpected content type in insert operation")}}}),d();},nn=()=>S.create("Length exceeded!"),rn=(i,e,t,n)=>{if(t>e._length)throw nn();if(t===0)return e._searchMarker&&pe(e._searchMarker,t,n.length),Le(i,e,null,n);let r=t,s=Be(e,t),o=e._start;for(s!==null&&(o=s.p,t-=s.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&&X(i,k(o.id.client,o.id.clock+t));break}t-=o.length;}return e._searchMarker&&pe(e._searchMarker,r,n.length),Le(i,e,o,n)},_i=(i,e,t)=>{let r=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(r)for(;r.right;)r=r.right;return Le(i,e,r,t)},sn=(i,e,t,n)=>{if(n===0)return;let r=t,s=n,o=Be(e,t),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&&X(i,k(c.id.client,c.id.clock+t)),t-=c.length);for(;n>0&&c!==null;)c.deleted||(n<c.length&&X(i,k(c.id.client,c.id.clock+n)),c.delete(i),n-=c.length),c=c.right;if(n>0)throw nn();e._searchMarker&&pe(e._searchMarker,r,-s+n);},Ve=(i,e,t)=>{let n=e._map.get(t);n!==void 0&&n.delete(i);},wt=(i,e,t,n)=>{let r=e._map.get(t)||null,s=i.doc,o=s.clientID,c;if(n==null)c=new _e([n]);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:c=new _e([n]);break;case Uint8Array:c=new Me(n);break;case ee:c=new Ke(n);break;default:if(n instanceof I)c=new Q(n);else throw new Error("Unexpected content type")}new V(k(o,M(s.store,o)),r,r&&r.lastId,null,null,e,t,c).integrate(i,0);},_t=(i,e)=>{i.doc??L();let t=i._map.get(e);return t!==void 0&&!t.deleted?t.content.getContent()[t.length-1]:void 0},on=i=>{let e={};return i.doc??L(),i._map.forEach((t,n)=>{t.deleted||(e[n]=t.content.getContent()[t.length-1]);}),e},cn=(i,e)=>{i.doc??L();let t=i._map.get(e);return t!==void 0&&!t.deleted};var bi=(i,e)=>{let t={};return i._map.forEach((n,r)=>{let s=n;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&ne(s,e)&&(t[r]=s.content.getContent()[s.length-1]);}),t},Re=i=>(i.doc??L(),ie.iteratorFilter(i._map.entries(),e=>!e[1].deleted)),ct=class extends se{},at=class i extends I{constructor(){super(),this._prelimContent=[],this._searchMarker=[];}static from(e){let t=new i;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null;}_copy(){return new i}clone(){let e=new i;return e.insert(0,this.toArray().map(t=>t instanceof I?t.clone():t)),e}get length(){return this.doc??L(),this._length}_callObserver(e,t){super._callObserver(e,t),Pe(this,e,new ct(this,e));}insert(e,t){this.doc!==null?b(this.doc,n=>{rn(n,this,e,t);}):this._prelimContent.splice(e,0,...t);}push(e){this.doc!==null?b(this.doc,t=>{_i(t,this,e);}):this._prelimContent.push(...e);}unshift(e){this.insert(0,e);}delete(e,t=1){this.doc!==null?b(this.doc,n=>{sn(n,this,e,t);}):this._prelimContent.splice(e,t);}get(e){return tn(this,e)}toArray(){return Qt(this)}slice(e=0,t=this.length){return Zt(this,e,t)}toJSON(){return this.map(e=>e instanceof I?e.toJSON():e)}map(e){return en(this,e)}forEach(e){me(this,e);}[Symbol.iterator](){return wi(this)}_write(e){e.writeTypeRef(Ti);}};var lt=class extends se{constructor(e,t,n){super(e,t),this.keysChanged=n;}},dt=class i extends I{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,r)=>{this.set(r,n);}),this._prelimContent=null;}_copy(){return new i}clone(){let e=new i;return this.forEach((t,n)=>{e.set(n,t instanceof I?t.clone():t);}),e}_callObserver(e,t){Pe(this,e,new lt(this,e,t));}toJSON(){this.doc??L();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof I?r.toJSON():r;}}),e}get size(){return [...Re(this)].length}keys(){return ie.iteratorMap(Re(this),e=>e[0])}values(){return ie.iteratorMap(Re(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return ie.iteratorMap(Re(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??L(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this);});}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?b(this.doc,t=>{Ve(t,this,e);}):this._prelimContent.delete(e);}set(e,t){return this.doc!==null?b(this.doc,n=>{wt(n,this,e,t);}):this._prelimContent.set(e,t),t}get(e){return _t(this,e)}has(e){return cn(this,e)}clear(){this.doc!==null?b(this.doc,e=>{this.forEach(function(t,n,r){Ve(e,r,n);});}):this._prelimContent.clear();}_write(e){e.writeTypeRef(Ri);}};var Y=(i,e)=>i===e||typeof i=="object"&&typeof e=="object"&&i&&e&&$.equalFlat(i,e),ye=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r;}forward(){switch(this.right===null&&S.unexpectedCase(),this.right.content.constructor){case D:this.right.deleted||ce(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;}},Kt=(i,e,t)=>{for(;e.right!==null&&t>0;){switch(e.right.content.constructor){case D:e.right.deleted||ce(e.currentAttributes,e.right.content);break;default:e.right.deleted||(t<e.right.length&&X(i,k(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},De=(i,e,t,n)=>{let r=new Map,s=n?Be(e,t):null;if(s){let o=new ye(s.p.left,s.p,s.index,r);return Kt(i,o,t-s.index)}else {let o=new ye(null,e._start,0,r);return Kt(i,o,t)}},an=(i,e,t,n)=>{for(;t.right!==null&&(t.right.deleted===!0||t.right.content.constructor===D&&Y(n.get(t.right.content.key),t.right.content.value));)t.right.deleted||n.delete(t.right.content.key),t.forward();let r=i.doc,s=r.clientID;n.forEach((o,c)=>{let a=t.left,l=t.right,d=new V(k(s,M(r.store,s)),a,a&&a.lastId,l,l&&l.id,e,null,new D(c,o));d.integrate(i,0),t.right=d,t.forward();});},ce=(i,e)=>{let{key:t,value:n}=e;n===null?i.delete(t):i.set(t,n);},ln=(i,e)=>{for(;i.right!==null;){if(!(i.right.deleted||i.right.content.constructor===D&&Y(e[i.right.content.key]??null,i.right.content.value)))break;i.forward();}},dn=(i,e,t,n)=>{let r=i.doc,s=r.clientID,o=new Map;for(let c in n){let a=n[c],l=t.currentAttributes.get(c)??null;if(!Y(l,a)){o.set(c,l);let{left:d,right:f}=t;t.right=new V(k(s,M(r.store,s)),d,d&&d.lastId,f,f&&f.id,e,null,new D(c,a)),t.right.integrate(i,0),t.forward();}}return o},qe=(i,e,t,n,r)=>{t.currentAttributes.forEach((p,g)=>{r[g]===void 0&&(r[g]=null);});let s=i.doc,o=s.clientID;ln(t,r);let c=dn(i,e,t,r),a=n.constructor===String?new Z(n):n instanceof I?new Q(n):new oe(n),{left:l,right:d,index:f}=t;e._searchMarker&&pe(e._searchMarker,t.index,a.getLength()),d=new V(k(o,M(s.store,o)),l,l&&l.lastId,d,d&&d.id,e,null,a),d.integrate(i,0),t.right=d,t.index=f,t.forward(),an(i,e,t,c);},Nt=(i,e,t,n,r)=>{let s=i.doc,o=s.clientID;ln(t,r);let c=dn(i,e,t,r);e:for(;t.right!==null&&(n>0||c.size>0&&(t.right.deleted||t.right.content.constructor===D));){if(!t.right.deleted)switch(t.right.content.constructor){case D:{let{key:a,value:l}=t.right.content,d=r[a];if(d!==void 0){if(Y(d,l))c.delete(a);else {if(n===0)break e;c.set(a,l);}t.right.delete(i);}else t.currentAttributes.set(a,l);break}default:n<t.right.length&&X(i,k(t.right.id.client,t.right.id.clock+n)),n-=t.right.length;break}t.forward();}if(n>0){let a="";for(;n>0;n--)a+=`
|
|
27
|
-
`;t.right=new
|
|
28
|
-
`?o.insert.slice(0,-1):o.insert;(typeof c!="string"||c.length>0)&&qe(n,this,r,c,o.attributes||{});}else o.retain!==void 0?Nt(n,this,r,o.retain,o.attributes||{}):o.delete!==void 0&&Bt(n,r,o.delete);}}):this._pending.push(()=>this.applyDelta(e));}toDelta(e,t,n){this.doc??L();let r=[],s=new Map,o=this.doc,c="",a=this._start;function l(){if(c.length>0){let f={},p=!1;s.forEach((w,T)=>{p=!0,f[T]=w;});let g={insert:c};p&&(g.attributes=f),r.push(g),c="";}}let d=()=>{for(;a!==null;){if(ne(a,e)||t!==void 0&&ne(a,t))switch(a.content.constructor){case Z:{let f=s.get("ychange");e!==void 0&&!ne(a,e)?(f===void 0||f.user!==a.id.client||f.type!=="removed")&&(l(),s.set("ychange",n?n("removed",a.id):{type:"removed"})):t!==void 0&&!ne(a,t)?(f===void 0||f.user!==a.id.client||f.type!=="added")&&(l(),s.set("ychange",n?n("added",a.id):{type:"added"})):f!==void 0&&(l(),s.delete("ychange")),c+=a.content.str;break}case Q:case oe:{l();let f={insert:a.content.getContent()[0]};if(s.size>0){let p={};f.attributes=p,s.forEach((g,w)=>{p[w]=g;});}r.push(f);break}case D:ne(a,e)&&(l(),ce(s,a.content));break}a=a.right;}l();};return e||t?b(o,f=>{e&&nt(f,e),t&&nt(f,t),d();},"cleanup"):d(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r!==null?b(r,s=>{let o=De(s,this,e,!n);n||(n={},o.currentAttributes.forEach((c,a)=>{n[a]=c;})),qe(s,this,o,t,n);}):this._pending.push(()=>this.insert(e,t,n));}insertEmbed(e,t,n){let r=this.doc;r!==null?b(r,s=>{let o=De(s,this,e,!n);qe(s,this,o,t,n||{});}):this._pending.push(()=>this.insertEmbed(e,t,n||{}));}delete(e,t){if(t===0)return;let n=this.doc;n!==null?b(n,r=>{Bt(r,De(r,this,e,!0),t);}):this._pending.push(()=>this.delete(e,t));}format(e,t,n){if(t===0)return;let r=this.doc;r!==null?b(r,s=>{let o=De(s,this,e,!1);o.right!==null&&Nt(s,this,o,t,n);}):this._pending.push(()=>this.format(e,t,n));}removeAttribute(e){this.doc!==null?b(this.doc,t=>{Ve(t,this,e);}):this._pending.push(()=>this.removeAttribute(e));}setAttribute(e,t){this.doc!==null?b(this.doc,n=>{wt(n,this,e,t);}):this._pending.push(()=>this.setAttribute(e,t));}getAttribute(e){return _t(this,e)}getAttributes(){return on(this)}_write(e){e.writeTypeRef(Di);}};var fe=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??L();}[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===Ae||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})}},we=class i extends I{constructor(){super(),this._prelimContent=[];}get firstChild(){let 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 i}clone(){let e=new i;return e.insert(0,this.toArray().map(t=>t instanceof I?t.clone():t)),e}get length(){return this.doc??L(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new fe(this,e)}querySelector(e){e=e.toUpperCase();let n=new fe(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return n.done?null:n.value}querySelectorAll(e){return e=e.toUpperCase(),K.from(new fe(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Pe(this,e,new ft(this,t,e));}toString(){return en(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),me(this,s=>{r.insertBefore(s.toDOM(e,t,n),null);}),r}insert(e,t){this.doc!==null?b(this.doc,n=>{rn(n,this,e,t);}):this._prelimContent.splice(e,0,...t);}insertAfter(e,t){if(this.doc!==null)b(this.doc,n=>{let r=e&&e instanceof I?e._item:e;Le(n,this,r,t);});else {let n=this._prelimContent,r=e===null?0:n.findIndex(s=>s===e)+1;if(r===0&&e!==null)throw S.create("Reference item not found");n.splice(r,0,...t);}}delete(e,t=1){this.doc!==null?b(this.doc,n=>{sn(n,this,e,t);}):this._prelimContent.splice(e,t);}toArray(){return Qt(this)}push(e){this.insert(this.length,e);}unshift(e){this.insert(0,e);}get(e){return tn(this,e)}slice(e=0,t=this.length){return Zt(this,e,t)}forEach(e){me(this,e);}_write(e){e.writeTypeRef(Ui);}};var Ae=class i extends we{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map;}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((n,r)=>{this.setAttribute(r,n);}),this._prelimAttrs=null;}_copy(){return new i(this.nodeName)}clone(){let e=new i(this.nodeName),t=this.getAttributes();return $.forEach(t,(n,r)=>{typeof n=="string"&&e.setAttribute(r,n);}),e.insert(0,this.toArray().map(n=>n instanceof I?n.clone():n)),e}toString(){let e=this.getAttributes(),t=[],n=[];for(let c in e)n.push(c);n.sort();let r=n.length;for(let c=0;c<r;c++){let a=n[c];t.push(a+'="'+e[a]+'"');}let s=this.nodeName.toLocaleLowerCase(),o=t.length>0?" "+t.join(" "):"";return `<${s}${o}>${super.toString()}</${s}>`}removeAttribute(e){this.doc!==null?b(this.doc,t=>{Ve(t,this,e);}):this._prelimAttrs.delete(e);}setAttribute(e,t){this.doc!==null?b(this.doc,n=>{wt(n,this,e,t);}):this._prelimAttrs.set(e,t);}getAttribute(e){return _t(this,e)}hasAttribute(e){return cn(this,e)}getAttributes(e){return e?bi(this,e):on(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),s=this.getAttributes();for(let o in s){let c=s[o];typeof c=="string"&&r.setAttribute(o,c);}return me(this,o=>{r.appendChild(o.toDOM(e,t,n));}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Oi),e.writeKey(this.nodeName);}};var ft=class extends se{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r);});}};var xe=class{constructor(e,t){this.id=e,this.length=t;}get deleted(){throw S.methodUnimplemented()}mergeWith(e){return !1}write(e,t,n){throw S.methodUnimplemented()}integrate(e,t){throw S.methodUnimplemented()}},Ci=0,W=class extends xe{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),qt(e.doc.store,this);}write(e,t){e.writeInfo(Ci),e.writeLen(this.length-t);}getMissing(e,t){return null}},Me=class i{constructor(e){this.content=e;}getLength(){return 1}getContent(){return [this.content]}isCountable(){return !0}copy(){return new i(this.content)}splice(e){throw S.methodUnimplemented()}mergeWith(e){return !1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content);}getRef(){return 3}};var gt=class i{constructor(e){this.len=e;}getLength(){return this.len}getContent(){return []}isCountable(){return !1}copy(){return new i(this.len)}splice(e){let t=new i(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Ft(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}};var Ei=(i,e)=>new ee({guid:i,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1}),Ke=class i{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;let 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 i(Ei(this.doc.guid,this.opts))}splice(e){throw S.methodUnimplemented()}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}};var oe=class i{constructor(e){this.embed=e;}getLength(){return 1}getContent(){return [this.embed]}isCountable(){return !0}copy(){return new i(this.embed)}splice(e){throw S.methodUnimplemented()}mergeWith(e){return !1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed);}getRef(){return 5}};var D=class i{constructor(e,t){this.key=e,this.value=t;}getLength(){return 1}getContent(){return []}isCountable(){return !1}copy(){return new i(this.key,this.value)}splice(e){throw S.methodUnimplemented()}mergeWith(e){return !1}integrate(e,t){let 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}};var Ii=Pt.getVariable("node_env")==="development",_e=class i{constructor(e){this.arr=e,Ii&&$.deepFreeze(e);}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return !0}copy(){return new i(this.arr)}splice(e){let t=new i(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){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let s=this.arr[r];e.writeAny(s);}}getRef(){return 8}};var Z=class i{constructor(e){this.str=e;}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return !0}copy(){return new i(this.str)}splice(e){let t=new i(this.str.slice(e));this.str=this.str.slice(0,e);let n=this.str.charCodeAt(e-1);return n>=55296&&n<=56319&&(this.str=this.str.slice(0,e-1)+"\uFFFD",t.str="\uFFFD"+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}};var Ti=0,Ri=1,Di=2,Oi=3,Ui=4;var Q=class i{constructor(e){this.type=e;}getLength(){return 1}getContent(){return [this.type]}isCountable(){return !0}copy(){return new i(this.type._copy())}splice(e){throw S.methodUnimplemented()}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}};var un=(i,e,t)=>{let{client:n,clock:r}=e.id,s=new V(k(n,r+t),e,k(n,r+t-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=k(e.redone.client,e.redone.clock+t)),e.right=s,s.right!==null&&(s.right.left=s),i._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=t,s};var V=class i extends xe{constructor(e,t,n,r,s,o,c,a){super(e,a.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=s,this.parent=o,this.parentSub=c,this.redone=null,this.content=a,this.info=this.content.isCountable()?v.BIT2:0;}set marker(e){(this.info&v.BIT4)>0!==e&&(this.info^=v.BIT4);}get marker(){return (this.info&v.BIT4)>0}get keep(){return (this.info&v.BIT1)>0}set keep(e){this.keep!==e&&(this.info^=v.BIT1);}get countable(){return (this.info&v.BIT2)>0}get deleted(){return (this.info&v.BIT3)>0}set deleted(e){this.deleted!==e&&(this.info^=v.BIT3);}markDeleted(){this.info|=v.BIT3;}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=M(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=M(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===re&&this.id.client!==this.parent.client&&this.parent.clock>=M(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Vt(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=X(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===W||this.right&&this.right.constructor===W)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===i&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===i&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===re){let n=Ge(t,this.parent);n.constructor===W?this.parent=null:this.parent=n.content.type;}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Vt(e,e.doc.store,k(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,r;if(n!==null)r=n.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;let s=new Set,o=new Set;for(;r!==null&&r!==this.right;){if(o.add(r),s.add(r),Te(this.origin,r.origin)){if(r.id.client<this.id.client)n=r,s.clear();else if(Te(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&o.has(Ge(e.doc.store,r.origin)))s.has(Ge(e.doc.store,r.origin))||(n=r,s.clear());else break;r=r.right;}this.left=n;}if(this.left!==null){let 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),qt(e.doc.store,this),this.content.integrate(e,this),xt(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e);}else new W(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:k(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Te(e.origin,this.lastId)&&this.right===e&&Te(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)){let 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){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),Ft(e.deleteSet,this.id.client,this.id.clock,this.length),xt(e,t,this.parentSub),this.content.delete(e);}}gc(e,t){if(!this.deleted)throw S.unexpectedCase();this.content.gc(e),t?ui(e,this,new W(this.id,this.length)):this.content=new gt(this.length);}write(e,t){let n=t>0?k(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&v.BITS5|(n===null?0:v.BIT8)|(r===null?0:v.BIT7)|(s===null?0:v.BIT6);if(e.writeInfo(o),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let c=this.parent;if(c._item!==void 0){let a=c._item;if(a===null){let l=li(c);e.writeParentInfo(!0),e.writeString(l);}else e.writeParentInfo(!1),e.writeLeftID(a.id);}else c.constructor===String?(e.writeParentInfo(!0),e.writeString(c)):c.constructor===re?(e.writeParentInfo(!1),e.writeLeftID(c)):S.unexpectedCase();s!==null&&e.writeString(s);}this.content.write(e,t);}};var fn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},gn="__ $YJS$ __";fn[gn]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");fn[gn]=!0;var be=i=>Promise.reject("unimplemented method GetVoiceSign"),bt=(i,e={},t=[])=>({command:i,front_request_id:z(),data:{...e,to_user_ids:Array.isArray(t)?t:[t]}}),pn=()=>{window?.__Realsee_Live__&&(window?.__Realsee_Live__?.dispose?.(),window.__Realsee_Live__=null);},je=class extends P{_options={};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}keyframes=new P;_yDoc;_buildInData;constructor(e){super(),m.info("Initializing Live instance with options:",e),this._addLiveControllerEventListeners(),this._yDoc=new ee({guid:z()}),this._buildInData={keyframes:this._yDoc.getMap("keyframes")},this._initializeKeyframesObservers(),this._initializeOptions(e),this._autoConnect(),this._debugSetup();}get _buildInKeyframes(){return this._buildInData.keyframes}get snapshot(){return this._buildInData.keyframes.toJSON()}_initializeKeyframesObservers=()=>{this._buildInKeyframes.observe(this._handleKeyframesChange);};_handleKeyframesChange=e=>{let{transaction:t,target:n,changes:r}=e;if(n===this._buildInKeyframes)if(t.origin.triggerUserId===this.selfInfo?.id){let s=bt("KEYFRAME_SYNC",this.snapshot,void 0);try{this._controller.sendMessage(s);}catch(o){m.error("Failed to send keyframe sync message:",o);}}else r.keys.forEach((s,o)=>{let c=s.oldValue,a=this.getFramesByKey(o),l=t.origin.frontRequestId;this.keyframes.emit(o,a,c,l);}),r.keys.size!==0&&this.emit("keyframes",this.snapshot,t.origin.frontRequestId);};getFramesByKey=e=>this.snapshot[e];sendKeyframe=(e,t)=>this.state!==1?(m.warn("Attempted to send keyframe while connection is not open"),!1):(this._yDoc.transact(()=>{this._buildInKeyframes.set(e,t);},{triggerUserId:this.selfInfo?.id,frontRequestId:""}),!0);get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}_controller=new Ie;_initializeOptions(e){this._options=Object.assign({initialMicroStatus:"OPEN"},e),this._options.jsBridge=this._initializeJsBridge(e),this._options.getVoiceSign=e.getVoiceSign??be,this._options.autoPlayConfirm=e.autoPlayConfirm,this._options.rtc=this._initializeRTC(e);}_initializeJsBridge(e){if(e.jsBridge)return e.jsBridge;if(e.useBuiltInJsBridge)return new Vi}_initializeRTC(e){if(e.rtc)return e.rtc;if(e.rtcType)return this._createBuiltInRTC(e);if(e.useBuiltInRTC)return this._createDefaultRTC(e)}_createBuiltInRTC(e){if(!e.getVoiceSign){m.error("GetVoiceSign method must be passed when using built-in RTC instances");return}switch(e.rtcType){case"RealseeVRWebViewRTC":return this._createVRWebViewRTC();case"RealseeBrowserChimeRTC":return new te({getVoiceSign:this._options.getVoiceSign??be,logLevel:e.__debug__?0:1});case"RealseeBrowserRTC":return this._createBrowserRTC();default:m.error("unknown built-in RTC type");return}}_createVRWebViewRTC(){if(this._options.jsBridge)return new he({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign??be});m.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");}_createBrowserRTC(){if(!this._options.autoPlayConfirm){m.error("autoPlayConfirm method must be passed when using built-in RealseeBrowserRTC instances");return}return new de({getVoiceSign:this._options.getVoiceSign??be,autoPlayConfirm:this._options.autoPlayConfirm})}_createDefaultRTC(e){if(!e.getVoiceSign){m.error("GetVoiceSign method must be passed when using built-in RTC instances");return}if(this._options.jsBridge){if(Rt&&(Et||It)||Tt)return this._createVRWebViewRTC();{let t=this._options.getVoiceSign??be;return e.builtInRTCType==="chime"?new te({getVoiceSign:t}):this._createBrowserRTC()}}else {m.error("jsBridge instance must be passed when using built-in RTC instances");return}}_autoConnect(){this._options.url&&this._options.getTicket&&this.connect();}_debugSetup(){this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this});}_addLiveControllerEventListeners=()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage);};_removeLiveControllerEventListeners=()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage);};_handleStateChange=(e,t)=>{m.info(`State changed from ${t} to ${e}`),this.emit("stateChange",e,t);};_handleMessage=async e=>{if(m.debug("Received message:",e),typeof e=="object"){let{command:t,data:n={},frontRequestId:r,code:s,message:o,triggerUserId:c}=e;if(s==="SUCCESS")switch(t){case"SELF_USER_INFO":{let a=n;Dt(this.selfInfo,a,{deep:!0})||(this._buildInData.selfInfo=a,this.emit("selfInfoUpdate",this._buildInData.selfInfo,r));break}case"ROOM_INFO":{let a=n;this._buildInData.roomInfo=Object.assign({},a);let l=a.last_frame||{};this._yDoc.transact(()=>{for(let d in l)this._buildInKeyframes.set(d,l[d]);},{triggerUserId:"readyKeyframeSync",frontRequestId:r}),this.emit("readyKeyframeSync",a.last_frame||{});break}case"RTC_INFO":{m.info("RTC info updated:",n);let{voice_id:a,type:l}=n;if(this._buildInData.rtcInfo={voiceId:a,type:l},this.$RTC?.joined)m.warn("\u5DF2\u52A0\u5165\u8BED\u97F3\u623F\u95F4\uFF0C\u65E0\u9700\u91CD\u590D\u52A0\u5165\uFF01");else if(await this.$RTC?.join({voiceId:a,userId:this.selfInfo?.id||"",roomId:this.roomInfo?.info.room_code,type:l})){let f=this._options.initialMicroStatus??"OPEN";await this.toggleMicro(f==="OPEN");}else m.error("\u52A0\u5165\u8BED\u97F3\u623F\u95F4\u5931\u8D25");break}case"USER_LIST":{let a=n;this._buildInData.userList=a,this.emit("userListUpdate",this.userList,r);break}case"CUSTOM_EVENT":{let a=n;this.emit("broadcast",a,r);break}case"KEYFRAME_SYNC":{let a=n;if(c===this.selfInfo?.id)return;this._yDoc.transact(()=>{for(let l in a)this._buildInKeyframes.set(l,a[l]);},{triggerUserId:c,frontRequestId:r});break}case"BUILTIN_MSG":{let a=n;this.emit("builtinEvent",a),a.event_type==="user_change"&&this.emit("userChange",a),a.event_type==="room_change"&&this.emit("roomChange",a),a.event_type==="user_change"&&a.action==="change_micro_status"&&await this.toggleMicro(a.data.status==="OPEN"),a.event_type==="room_change"&&a.action==="close"&&await this._exit();break}case"USER_KICK_OUT":{this.emit("kickOut");break}default:m.warn("Unknown command received:",t);}else m.error("Error in message:",o),this.emit("error",e);}};_clearLiveData=()=>{this._buildInKeyframes.clear(),this._buildInData={keyframes:this._yDoc.getMap("keyframes")};};connect=async(e={})=>{if(m.info("Attempting to connect with options:",e),this._options.url=e.url??this._options.url??"",this._options.getTicket=e.getTicket??this._options.getTicket,this._options.initialMicroStatus=e.rtcMicStatus??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");let t=this.state;if(t===0||t===1)if(e.force)await this._controller.close("force close by connect").catch(console.warn);else return new Error("\u5DF2\u6709Live\u5B9E\u4F8B\u6B63\u5728\u8FDE\u63A5\u4E2D\uFF0C\u8BF7\u52FF\u91CD\u590D\u8FDE\u63A5\uFF01");this._clearLiveData();try{let n=await this._options.getTicket(),r=vt(this._options.url,{ticket:n,force:+!!e.force});return this._controller.open(r),m.info("Connection established successfully"),!0}catch(n){return m.error("Failed to connect:",n),new Error("Failed to connect")}};_exit=async()=>{this._clearLiveData();try{await this.$RTC?.quit();}catch(e){m.warn(e);}return this.state!==1?!0:await this._controller.close()};exit=async()=>this.close();close=async()=>{await this._controller.readyClose();try{await this.$RTC?.quit();}catch(e){m.warn(e);}await this.updateStatus("room_change","close",{});};dispose=async()=>(this._removeLiveControllerEventListeners(),this._clearLiveData(),await this._controller.dispose());async updateStatus(e,t,n,r){if(this.state!==1)return !1;let s=Object.assign({event_type:e,action:t},{data:n}),o=bt("BUILTIN_MSG",s,r);try{return this._controller.sendMessage(o),!0}catch(c){return m.error(c),!1}}setSelfInfo=async e=>await this.updateStatus("user_change","change_info",e);broadcast(e,t,n){return this.state!==1?!1:new Promise((r,s)=>{let o=bt("CUSTOM_EVENT",e,t),c=o.front_request_id,a=n?setTimeout(()=>{s(new Error("RESPONSE TIMEOUT")),this.off("broadcast",l);},n):void 0,l=(d,f)=>{f===c&&(a&&clearTimeout(a),this.off("broadcast",l),r(d));};this.on("broadcast",l);try{this._controller.sendMessage(o);}catch(d){s(d);}})}toggleMicro=async e=>{if(!this.selfInfo?.permission?.control_own_micro)return !1;let t=await this.$RTC?.toggleMicro(e);return t&&await this.updateStatus("user_change","change_micro_status",{status:e?"OPEN":"CLOSE"},[]),t};forbidMicro=async(e,t)=>typeof this._options.canForbidUserMicro=="function"&&!this._options.canForbidUserMicro(t)||!this.selfInfo?.permission?.control_other_micro?!1:await this.updateStatus("user_change","change_micro_status",{status:e},t);forbidSync=async(e,t)=>typeof this._options.canForbidUserSync=="function"&&!this._options.canForbidUserSync(t)||!this.selfInfo?.permission?.control_other_sync?!1:await this.updateStatus("user_change","change_permission",{sync_frame:e},t);kick=async e=>typeof this._options.canForbidUserKick=="function"&&!this._options.canForbidUserKick(e)||!this.selfInfo?.permission?.change_other_status?!1:await this.updateStatus("user_change","change_status",{status:"KICK_OUT"},e);getSnapshotForKey(e){return this.snapshot[e]}};var mn=i=>(pn(),new je(i));function Yr(i){let e=createContext(null),t=mn(i),n=t.jsBridge,r=h=>U.createElement(e.Provider,{value:t},h.children),s=()=>{let h=U.useContext(e);if(!h)throw new Error("LiveProvider never found.");return h},o=()=>t,c=()=>t.$RTC,a=()=>c(),l=()=>async h=>await t.connect(h);function d(h,_,R=[]){let y=s(),C=[y,name,...R],O=()=>y.keyframes.off(h,_);return U.useEffect(()=>(y.keyframes.on(h,_),O),C),O}function f(){let h=s(),_=useCallback(async E=>{await h.connect(E);},[h]),R=useCallback(E=>{h.toggleMicro(E);},[h]),y=useCallback(async(E,F,$e=0)=>{await h.broadcast(E,F,$e);},[h]),C=useCallback(async()=>{await h.exit();},[h]),O=useCallback(async E=>{await h.kick(E);},[h]),q=useCallback(async(E,F=[])=>{await h.forbidMicro(E,F);},[h]),Se=useCallback((E,F=[])=>{h.forbidSync(E,F);},[h]),We=useCallback(E=>h.getFramesByKey(E),[h]),Sn=useCallback((E,F)=>{h.sendKeyframe(E,F);},[h]),kn=useCallback(E=>{h.setSelfInfo(E);},[h]),vn=useCallback((E,F,$e,Cn)=>{h.updateStatus(E,F,$e,Cn);},[h]);return {connect:_,broadcast:y,exit:C,kick:O,toggleMicro:R,forbidMicro:q,forbidSync:Se,sendKeyframe:Sn,getFramesByKey:We,setSelfInfo:kn,updateStatus:vn}}function p(h){let _=s(),[R,y]=U.useState(_.getFramesByKey(h));U.useEffect(()=>{let O=We=>y(We),q=h,Se=O;return _.keyframes.on(q,Se),()=>_.keyframes.off(q,Se)},[_]);let C=U.useCallback(O=>_.sendKeyframe(h,O),[_]);return [R,C]}function g(h,_,R=[]){let y=s(),C=()=>y.off(h,_),O=[y,h,...R];return U.useEffect(()=>(y.on(h,_),C),O),C}function w(){let h=s(),[_,R]=U.useState(h.state);return U.useEffect(()=>{let y=C=>R(C);return h.on("stateChange",y),()=>h.off("stateChange",y)},[h]),_}function T(){let h=s();return {join:q=>h.$RTC.join(q),quit:()=>h.$RTC.quit(),shock:()=>h.$RTC.shock?.(),toggleMicro:q=>h.$RTC.toggleMicro(q),detectMicro:()=>h.$RTC.detectMicro()}}function yn(h,_,R=[]){let y=s(),C=()=>y.$RTC.off(h,_),O=[y,h,...R];return U.useEffect(()=>(y.$RTC.on(h,_),C),O),C}function wn(){let h=s(),[_,R]=U.useState(h.selfInfo||{}),y=O=>R(O);U.useEffect(()=>(h.on("selfInfoUpdate",y),()=>h.off("selfInfoUpdate",y)),[h]);let C=U.useCallback(async O=>await h.setSelfInfo(O),[h]);return [_,C]}function _n(){let h=s(),[_,R]=U.useState(h.snapshot);return U.useEffect(()=>{let y=C=>R(C);return h.on("keyframes",y),()=>h.off("keyframes",y)},[h]),_}function bn(){let h=s(),[_,R]=U.useState(h.userList),y=C=>R(C);return U.useEffect(()=>(h.on("userListUpdate",y),()=>h.off("userListUpdate",y)),[h]),_}return {live:t,jsBridge:n,LiveProvider:r,unsafe__useLiveInstance:o,unsafe__useRTCInstance:a,useConnect:l,useKeyframe:p,useKeyframeUpdateCallback:d,useLiveAction:f,useLiveEventCallback:g,useLiveState:w,useRTCAction:T,useRTCEventCallback:yn,useSelfInfo:wn,useKeyframesSnapshot:_n,useUserList:bn}}console.log(`%c${process.env.__REALSEE_LIVE_VERSION__}`,"background: #237804; color: white; padding: 2px 4px; border-radius: 4px;");
|
|
6
|
+
var Ee=Symbol("$$REALSEE_LIVE_EVENT$$");function $e(n){return n[Ee]||(n[Ee]={}),n[Ee]}function ti(n){n[Ee]?.length||delete n[Ee];}var M=class{hasListener(e){let t=$e(this);return t&&t[e]&&t[e].length>0}on(e,t,r){let i=$e(this);return i[e]||(i[e]=[]),i[e].push([t,r||!1]),()=>this.off(e,t)}once(e,t){return this.on(e,t,!0)}off(e,t){let r=$e(this);if(!e){ti(this);return}if(r[e]||(r[e]=[]),t===void 0){r[e].length=0;return}let i=r[e].findIndex(s=>s[0]===t);i!==-1&&r[e].splice(i,1);}emit(e,...t){let r=!1,s=$e(this)[e]||[];for(let o of s.slice()){let[c,a=!1]=o,l=c(...t);a&&this.off(e,c),l===!1&&(r=!0);}return r}};var q=class extends M{};var ni=(r=>(r.RealseeBrowserRTC="RealseeBrowserRTC",r.RealseeVRWebViewRTC="RealseeVRWebViewRTC",r.RealseeBrowserChimeRTC="RealseeBrowserChimeRTC",r))(ni||{}),ri=(t=>(t.RealseeXTRTC="trtc",t.RealseeXChimeRTC="chime",t))(ri||{});var ii=()=>{let n=new Date,e=n.getFullYear(),t=(n.getMonth()+1).toString().padStart(2,"0"),r=n.getDate().toString().padStart(2,"0"),i=n.getHours().toString().padStart(2,"0"),s=n.getMinutes().toString().padStart(2,"0"),o=n.getSeconds().toString().padStart(2,"0"),c=n.getMilliseconds().toString().padStart(3,"0");return `[${e}-${t}-${r} ${i}:${s}:${o}.${c}]`};var ke=(n,e=[])=>{let t=`Realsee Live ${ii()} <${n}> `;switch(n){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);}},si={log:(...n)=>ke("LOG",n),info:(...n)=>ke("INFO",n),error:(...n)=>ke("ERROR",n),warn:(...n)=>ke("WARN",n),debug:(...n)=>ke("DEBUG",n)},p=si;function Y(){return ((1+Math.random())*65536|0).toString(16).substring(1)}function X(){return [Y(),Y(),"4"+Y().substring(0,3),Y(),Y(),Y()+Y()+Y()].join("-").toLowerCase()}var Ce=class extends q{type="RealseeBrowserRTC";joined=!1;micro=!1;voiceId="";_getVoiceSign=()=>{throw new Error("\u65B9\u6CD5 getVoiceSign \u672A\u5B9E\u73B0")};_autoPlayConfirm;checkRequirement=()=>vt.checkSystemRequirements();$dom=document.createElement("div");_trtc={client:null,stream:null};constructor(e){super(),this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initParentDom();}_initParentDom(){this.$dom.id=`rs-rtc-${X()}`,this.$dom.style.display="none",document.body.appendChild(this.$dom);}join=async e=>{this.emit("joinWillStart");let t=await this._getVoiceSign({voiceId:e.voiceId,roomId:e.roomId,userId:e.userId});this._trtc.client=vt.createClient({mode:"rtc",...t,enableAutoPlayDialog:typeof this._autoPlayConfirm!="function"}),this._trtc.client?.enableAudioVolumeEvaluation(),this._registerRtcEvent();let r=await new Promise(i=>{this._trtc.client?.join({roomId:Number(e.voiceId)}).then(()=>i(!0)).catch(()=>i(!1));});return this.joined=r,r?(this._trtc.stream=vt.createStream({userId:t.userId,audio:!0,video:!1}),r=await new Promise(i=>{this._trtc.stream?.initialize().then(()=>i(!0)).catch(()=>i(!1));}),r=await new Promise(i=>{this._trtc.client?.publish(this._trtc.stream).then(()=>i(!0)).catch(()=>i(!1));}),this.joined=r,this.joined&&this.emit("joined"),r):!1};quit(){return new Promise(async e=>{this.joined=!1,this._trtc.stream&&(await this._trtc.client?.unpublish(this._trtc.stream),this._trtc.stream.stop(),this._trtc.stream.close(),this._trtc.stream=null),this._trtc.client?.leave().then(()=>this._trtc.client=null).then(()=>e(!0)).catch(()=>e(!1)),e(!0);})}detectMicro(){return new Promise(e=>{let t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then(()=>e(!0)).catch(r=>{p.error(r.message),e(!1);});}catch(r){console.error(r),e(!1);}})}toggleMicro(e){return Promise.resolve((e?this._trtc?.stream?.unmuteAudio():this._trtc?.stream?.muteAudio())||!1)}shock(){throw new Error("Method not implemented.")}_registerRtcEvent(){this._trtc.client?.on("stream-added",this._handleStreamAdded),this._trtc.client?.on("stream-subscribed",this._handleStreamSubscribed),this._trtc.client?.on("audio-volume",e=>this.emit("userVolumes",e.result.map(({userId:t,audioVolume:r})=>({userId:t,audioVolume:r})))),this._trtc.client?.on("error",e=>this.emit("error",e));}_handleStreamAdded=e=>{let t=e.stream;console.log("\u8FDC\u7AEF\u6D41\u589E\u52A0: "+t.getId()),this._trtc.client?.subscribe(t);};_handleStreamSubscribed=e=>{let t=e.stream;console.log("\u8FDC\u7AEF\u6D41\u8BA2\u9605\u6210\u529F\uFF1A"+t.getId());let i=`rs-rtc-remote_stream-${t.getId()}`,s=document.createElement("div");s.id=i,this.$dom.appendChild(s),typeof this._autoPlayConfirm=="function"?(t.play(i).catch(o=>{}),t.on("error",o=>{if(o.getCode()===16451){let a=()=>t.resume();this._autoPlayConfirm({onConfirm:a});}})):t.play(i);}};var ue=class extends q{type="RealseeBrowserChimeRTC";joined=!1;micro=!1;voiceId="";userId="";logger;deviceController;meetingSession;audioInput;audioOutput;deviceChangeObserver={};audioVideoObserver={};audioMixObserver;_getVoiceSign=()=>{throw new Error("\u65B9\u6CD5 getVoiceSign \u672A\u5B9E\u73B0")};_autoPlayConfirm;$dom=document.createElement("div");$audio=document.createElement("audio");constructor(e){super(),this._getVoiceSign=e.getVoiceSign,this._autoPlayConfirm=e.autoPlayConfirm,this._initDom(),this.logger=new ConsoleLogger("WebRTCLogger",e.logLevel||LogLevel.INFO),this.deviceController=new DefaultDeviceController(this.logger),this.initObservers();}_initDom=()=>{this.$audio.id=`rs-rtc-${X()}`,this.$dom.id=`rs-rtc-${X()}`,this.$dom.appendChild(this.$audio),document.body.appendChild(this.$dom);};initObservers=()=>{this.deviceChangeObserver={audioInputsChanged:e=>{this.logger.info(`audioInputsChanged ${typeof e}`),e?.forEach(t=>{this.logger.info(`Device ID: ${t.deviceId} Microphone: ${t.label}`);});},audioOutputsChanged:e=>{this.logger.info(`audioOutputsChanged ${typeof e}`),e?.forEach(t=>{this.logger.info(`Device ID: ${t.deviceId} Speaker: ${t.label}`);});},audioInputMuteStateChanged:(e,t)=>{this.logger.info(`Device ${e.toString()} ${t?"is muted in hardware":"is not muted"}`);}},this.audioVideoObserver={audioVideoDidStart:()=>{this.logger.info("Started");},audioVideoDidStop:e=>{this.logger.info(`Stopped with a session status code: ${e.statusCode()}`);},audioVideoDidStartConnecting:e=>{e&&this.logger.info("Attempting to reconnect");}},this.audioMixObserver={meetingAudioStreamBecameActive:e=>{if(this.$audio.paused){let t=()=>this.$audio.play().then(()=>{}).catch(r=>{if(p.error("\u64AD\u653E\u8FDC\u7AEF\u6D41\u5931\u8D25\uFF01",r),typeof this._autoPlayConfirm=="function"){let i=()=>t();this._autoPlayConfirm({onConfirm:i});}});t();}},meetingAudioStreamBecameInactive:e=>{}};};async join(e){return new Promise(async(t,r)=>{this.emit("joinWillStart");try{let{sdkAppId:i,userId:s,roomId:o,userSig:c}=await this._getVoiceSign({...e,roomId:e.roomId||0});this.userId=s;let{attendence:a,vendor_wrapper:l}=JSON.parse(decodeURIComponent(c)),d=new MeetingSessionConfiguration({Meeting:l},{Attendee:{ExternalUserId:a.external_user_id,AttendeeId:a.attendee_id,JoinToken:a.join_token}});this.meetingSession=new DefaultMeetingSession(d,this.logger,this.deviceController),this._registerRtcEvent(),this.meetingSession.audioVideo.addDeviceChangeObserver(this.deviceChangeObserver),this.meetingSession.audioVideo.addObserver(this.audioVideoObserver),this.meetingSession.audioVideo.bindAudioElement(this.$audio);let u={audioVideoDidStart:()=>{this.meetingSession?.audioVideo.realtimeMuteLocalAudio(),this.joined=!0,this.emit("joined"),t(!0);},audioVideoDidStop:()=>{this.joined=!1,t(!1);}};this.meetingSession.audioVideo.addObserver(u),this.audioMixObserver&&this.meetingSession.audioVideo.addAudioMixObserver(this.audioMixObserver),this.meetingSession.audioVideo.setDeviceLabelTrigger(async()=>await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}));try{let g=await this.meetingSession.audioVideo.listAudioInputDevices();p.info("audioInputDevices ===>",g);let f=g[0]?.deviceId||"default";await this.meetingSession.audioVideo.startAudioInput(f);}catch(g){p.error(`\u8BBE\u7F6E\u8BED\u97F3\u8F93\u5165\u8BBE\u5907\u5931\u8D25:${g.message}`);}try{let g=await this.meetingSession.audioVideo.listAudioOutputDevices();p.info("audioOutputDevices ===>",g);let f=g[0]?.deviceId||"default";await this.meetingSession.audioVideo.chooseAudioOutput(f);}catch(g){p.error(`\u8BBE\u7F6E\u8BED\u97F3\u8F93\u51FA\u8BBE\u5907\u5931\u8D25:${g.message}`);}this.meetingSession.audioVideo.start();}catch(i){this.emit("error",i),this.logger.error(i.message),t(!1);}})}_registerRtcEvent=()=>{let e=this.meetingSession?.configuration?.credentials?.attendeeId||"";if(e){let t=new Map,r=()=>{let i=[];return t.forEach((s,o)=>{i.push({userId:s.userId,volume:s.muted||s.signalStrength===0||!s.volume?0:s.volume});}),i};this.meetingSession?.audioVideo.realtimeSubscribeToAttendeeIdPresence((i,s,o)=>{if(!s){t.delete(i),this.emit("userVolumes",r());return}this.meetingSession?.audioVideo.realtimeSubscribeToVolumeIndicator(i,(c,a,l,d)=>{new DefaultModality(c).base()===c&&(t.set(c,{userId:o||c,volume:a,muted:l,signalStrength:d}),this.emit("userVolumes",r()));});}),this.meetingSession?.audioVideo.realtimeSubscribeToVolumeIndicator(e,(i,s,o,c)=>{new DefaultModality(i).base()===i&&c!==null&&c!==1&&this.emit("weakNetwork");}),this.meetingSession?.audioVideo.realtimeSubscribeToFatalError(i=>this.emit("error",i));}};quit(){return this.joined?new Promise((e,t)=>{this.joined=!1;let r={audioVideoDidStop:async i=>{let s=i.statusCode();this.meetingSession?.deviceController.destroy(),s===MeetingSessionStatusCode.Left?(this.logger.info("You left the session"),e(!0)):(this.logger.info(`Stopped with a session status code: ${s}`),e(!0));}};this.meetingSession?.audioVideo.addObserver(r),this.meetingSession?.audioVideo.stop();}):Promise.resolve(!0)}async detectMicro(){return new Promise(e=>{let t={audio:!0,video:!1};try{navigator.mediaDevices.getUserMedia(t).then(()=>e(!0)).catch(()=>e(!1));}catch(r){this.logger.error(r.message),e(!1);}})}async toggleMicro(e){e?this.meetingSession?.audioVideo.realtimeUnmuteLocalAudio():this.meetingSession?.audioVideo.realtimeMuteLocalAudio();let t=this.meetingSession?.audioVideo.realtimeIsLocalAudioMuted();return t!==void 0?e!==t:!1}shock(){throw new Error("Method not implemented.")}};var ui=(s=>(s[s.Success=0]="Success",s[s.Failure=1]="Failure",s[s.ReJoin=2]="ReJoin",s[s.NoMicroPermission=3]="NoMicroPermission",s[s.Unknown=500]="Unknown",s))(ui||{});var xe=class extends q{type="RealseeVRWebViewRTC";joined=!1;micro=!1;voiceId="";_joinOptions=null;options;get jsBridge(){return this.options.jsBridge}constructor({jsBridge:e,getVoiceSign:t}){super(),this.options={jsBridge:e,getVoiceSign:t},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);}handleUserVolumes=e=>{this.emit("userVolumes",e);};handleWeakNetwork=e=>{e&&this.emit("weakNetwork");};join=async e=>{this._joinOptions=e,this.emit("joinWillStart");let{sdkAppId:t,userId:r,userSig:i}=await this.getVoiceSignOrEmitError(e);return !t||!r||!i?!1:(this.type=e.type,this.jsBridge.webViewType==="WxMiniProgramWebView"?this.handleWxMiniProgramWebViewJoin({sdkAppId:t,userId:r,userSig:i,voiceId:e.voiceId}):this.handleAppWebViewJoin({sdkAppId:t,userId:r,userSig:i,voiceId:e.voiceId}))};reJoin=async()=>this._joinOptions?this.join({voiceId:this._joinOptions.voiceId,userId:this._joinOptions.userId,roomId:this._joinOptions.roomId,type:this._joinOptions.type}):(this.emitErrorAndSetJoinedFalse("\u91CD\u8FDE\u5931\u8D25\uFF1A\u672A\u627E\u5230\u52A0\u5165\u623F\u95F4\u53C2\u6570\u3002"),!1);getVoiceSignOrEmitError=async e=>{try{return await this.options.getVoiceSign(e)}catch{return this.emitErrorAndSetJoinedFalse("\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1Artc \u7B7E\u540D\u8BF7\u6C42\u5F02\u5E38"),{}}};handleWxMiniProgramWebViewJoin=async e=>{let[t,r]=await this.joinRoomOrEmitError(e);return r?!1:this.handleJoinResult(t)};handleAppWebViewJoin=e=>new Promise(t=>{this.off("inner.rtc.success");let r=i=>{this.off("inner.rtc.fail",r),this.off("inner.rtc.success",r),t(this.handleJoinResult(i));};this.once("inner.rtc.fail",r),this.once("inner.rtc.success",r);try{let{sdkAppId:i,userId:s,userSig:o,voiceId:c}=e;this.jsBridge.callAndListen(`live/join?sdkAppID=${i}&userID=${s}&roomID=${c}&userSig=${o}`,a=>{a===!0?this.emit("inner.rtc.success",a):typeof a=="object"?a.code===0||a.code===2?this.emit("inner.rtc.success",a):this.emit("inner.rtc.fail",a):this.emit("inner.rtc.fail",a);});}catch(i){t(this.handleJoinResult({message:i.message,code:500}));}});joinRoomOrEmitError=async({sdkAppId:e,userId:t,voiceId:r,userSig:i})=>{try{return await this.jsBridge.callAndBackfeed(`live/join?sdkAppID=${e}&userID=${t}&roomID=${Number(r)}&userSig=${i}`)}catch(s){return this.emitErrorAndSetJoinedFalse("\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1A"+s.message),[null,s]}};handleJoinResult=e=>{switch(!0){case e===!0:case(typeof e=="object"&&e.code===0):case(typeof e=="object"&&e.code===2):{this.emit("joined"),this.joined=!0;break}default:{this.joined=!1;let t=typeof e=="object"?e.message:"\u52A0\u5165\u623F\u95F4\u5931\u8D25\uFF1A\u672A\u77E5\u5F02\u5E38\u3002";this.emit("error",new Error(t,{cause:e}));}}return this.joined};emitErrorAndSetJoinedFalse=e=>{this.emit("error",new Error(e)),this.joined=!1;};quit=async()=>{let[e,t]=await this.jsBridge.callAndBackfeed("live/quit");return e===null&&this.emit("error",t||new Error("\u9000\u51FA\u623F\u95F4\u5931\u8D25\uFF1A\u672A\u77E5\u5F02\u5E38\u3002")),this.joined=!1,!!e};detectMicro=async()=>{let[e,t]=await this.jsBridge.detectMicro();return e===null?(this.emit("error",t||new Error("\u9EA6\u514B\u98CE\u76D1\u6D4B\u5F02\u5E38\uFF01")),!1):e};toggleMicro=async e=>{let[t,r]=await this.jsBridge.callAndBackfeed(`live/toggleMicro?flag=${e?1:0}`);return t===null?(this.emit("error",r||new Error("\u9EA6\u514B\u98CE\u76D1\u6D4B\u5F02\u5E38\uFF01")),!1):(this.micro=t,t)};shock=()=>{this.jsBridge.shock(1);}};var fi=(a=>(a.SelfUserInfo="SELF_USER_INFO",a.RoomInfo="ROOM_INFO",a.RTCInfo="RTC_INFO",a.UserList="USER_LIST",a.BuiltinMsg="BUILTIN_MSG",a.CustomEvent="CUSTOM_EVENT",a.KeyframeSync="KEYFRAME_SYNC",a.UserKickOut="USER_KICK_OUT",a))(fi||{}),gi=(t=>(t.UserChange="user_change",t.RoomChange="room_change",t))(gi||{}),pi=(o=>(o.UserMicroStatus="change_micro_status",o.UserMicroStatusSync="sync_micro_status",o.UserPermission="change_permission",o.UserStatus="change_status",o.UserInfo="change_info",o.RoomClose="close",o))(pi||{}),mi=(t=>(t.OPEN="OPEN",t.CLOSE="CLOSE",t))(mi||{});function Ro(n){try{let e=JSON.parse(n),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||{}},r=Object.keys(t).filter(i=>t[i]===void 0);return r.length>0&&console.warn(`\u63A8\u9001\u6570\u636E\u683C\u5F0F\u5F02\u5E38\uFF1A${r.join(" ")} \u503C\u4E0D\u5B58\u5728\uFF01`),t}catch{return !1}}var yi=(i=>(i[i.NOTINITIALIZED=-1]="NOTINITIALIZED",i[i.CONNECTING=0]="CONNECTING",i[i.OPEN=1]="OPEN",i[i.CLOSED=3]="CLOSED",i))(yi||{});var wi=(r=>(r[r.Normal=0]="Normal",r[r.Removed=1]="Removed",r[r.Replaced=2]="Replaced",r))(wi||{}),_i=(o=>(o.WAIT_ENTER="WAIT_ENTER",o.ONLINE="ONLINE",o.LEAVE="LEAVE",o.KICK_OUT="KICK_OUT",o.BE_REPLACE="BE_REPLACE",o.EXCEPTION="EXCEPTION",o))(_i||{});var bi=(s=>(s[s.NOTINITIALIZED=-1]="NOTINITIALIZED",s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(bi||{}),Si=(c=>(c.Error="Error",c.Close="Close",c.MicroAuth="MicroAuth",c.DuplicateConnect="DuplicateConnect",c.IllegalURL="IllegalURL",c.Unknown="Unknown",c.IllegalArgs="IllegalArgs",c))(Si||{}),vi=(l=>(l.Err_1000="CLOSE_NORMAL",l.Err_1001="CLOSE_GOING_AWAY",l.Err_1002="CLOSE_PROTOCOL_ERROR",l.Err_1003="CLOSE_UNSUPPORTED",l.Err_1006="CLOSE_ABNORMAL",l.Err_1007="Unsupported Data",l.Err_1008="Policy Violation",l.Err_1009="CLOSE_TOO_LARGE",l.Err_unknown="unknown",l))(vi||{});function bn(n){switch(n){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 Sn(n,e={}){let t=new URL(n,"http://localhost"),r=new URLSearchParams(t.search);return Object.entries(e).forEach(([i,s])=>{r.append(i,String(s));}),n.split("?")[0]+"?"+r.toString()}var vn=(()=>{let n=typeof process<"u"&&process.versions?.node!=null;return typeof window<"u"&&"Deno"in window||n||typeof window>"u"})();var Ie=vn?"":navigator.userAgent,En=/android/i.test(Ie),kn=/iPhone|iPad\s+OS/i.test(Ie),Cn=/MicroMessenger/i.test(Ie)&&/miniProgram/i.test(Ie),xn=/realsee/i.test(Ie);function Ge(n){return Object.prototype.toString.call(n)==="[object Object]"}function qe(n,e){return n===e?!0:n==null||e==null||typeof n!=typeof e?!1:Number.isNaN(n)&&Number.isNaN(e)}function Ei(n,e){if(n===e)return !0;if(n==null||e==null)return !1;let t=Object.keys(n),r=Object.keys(e);return t.length!==r.length?!1:t.every(i=>qe(n[i],e[i]))}function ki(n,e){return n===e?!0:n==null||e==null||n.length!==e.length?!1:n.every((t,r)=>qe(t,e[r]))}function Ci(n,e){return qe(n,e)?!0:Ge(n)&&Ge(e)?Ei(n,e):Array.isArray(n)&&Array.isArray(e)?ki(n,e):!1}function Et(n,e){return qe(n,e)?!0:Ge(n)&&Ge(e)?Ii(n,e):Array.isArray(n)&&Array.isArray(e)?xi(n,e):!1}function xi(n,e){if(n.length!==e.length)return !1;for(let t=0,r=n.length;t<r;t++)if(!Et(n[t],e[t]))return !1;return !0}function Ii(n,e){if(n===e)return !0;if(n==null||e==null)return !1;let t=Object.keys(n),r=Object.keys(e);return t.length!==r.length?!1:t.every(i=>Et(n[i],e[i]))}function In(n,e,t={deep:!1}){return t.deep?Et(n,e):Ci(n,e)}var Je=class extends M{_realWebSocket;_url;_protocols;_readyState=-1;_options={timeout:1e4,shouldReconnect:(e,t)=>{if(!(e.code===1008||e.code===1011))return [0,1e3,2e3][t.attempts%3]},should1000Reconnect:!1,ignoreConnectivityEvents:!1,automaticOpen:!1};_connectTimeout;_attempts=0;_reconnects=-1;_reconnectWhenOnlineAgain=!1;_explicitlyClosed=!1;_pendingReconnect;_connectivityEventsAttached=!1;_heathCheckTimer;get attempts(){return this._attempts}constructor(e){super(),e&&this.setOptions(e),this._startHealthCheck();}setOptions(e){if(!e)return;this._url=e.url,this._protocols=e.protocols;let t=Object.assign(this._options,e.robustOptions||{});if(typeof t?.timeout!="number")throw new Error("timeout must be the number of milliseconds to timeout a connection attempt");if(typeof t?.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=t,this._options.automaticOpen&&this._createWebSocket();}_healthCheck=async()=>{if(this._realWebSocket){let e=this._realWebSocket.readyState;e!==this._readyState&&(this._readyState=e,this._readyState===2&&this.emit("closing"));}await new Promise(e=>setTimeout(e,2e3)),this._heathCheckTimer=requestAnimationFrame(this._healthCheck);};_clearConnectTimeoutIfNeed=()=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);};_clearHeathCheckIfNeed=()=>{this._heathCheckTimer&&(cancelAnimationFrame(this._heathCheckTimer),this._heathCheckTimer=void 0);};_startHealthCheck=()=>{this._clearHeathCheckIfNeed(),this._heathCheckTimer=requestAnimationFrame(this._healthCheck);};_stopHealthCheck=()=>{this._clearHeathCheckIfNeed();};_clearPendingReconnectIfNeeded=()=>{this._pendingReconnect&&(clearTimeout(this._pendingReconnect),this._pendingReconnect=void 0);};_online=e=>{this._reconnectWhenOnlineAgain&&(this._clearPendingReconnectIfNeeded(),this._reconnect(e));};_offline=()=>{this._reconnectWhenOnlineAgain=!0,this._realWebSocket?.close(1e3,"offline");};_detachConnectivityEvents=()=>{this._connectivityEventsAttached&&(globalThis?.removeEventListener("online",this._online),globalThis?.removeEventListener("offline",this._offline),this._connectivityEventsAttached=!1);};_attachConnectivityEvents=()=>{this._connectivityEventsAttached||(globalThis?.addEventListener("online",this._online),globalThis?.addEventListener("offline",this._offline),this._connectivityEventsAttached=!0);};send=e=>{this._realWebSocket?.readyState===this._realWebSocket?.OPEN&&this._realWebSocket?.send(e);};close=(e,t)=>(typeof e!="number"&&(t=e,e=1e3),this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!0,this._detachConnectivityEvents(),this._realWebSocket?.close(e,t));open=e=>{e&&(this._url=e),this._realWebSocket?.readyState!==WebSocket.OPEN&&this._realWebSocket?.readyState!==WebSocket.CONNECTING&&(this._clearPendingReconnectIfNeeded(),this._reconnectWhenOnlineAgain=!1,this._explicitlyClosed=!1,this._createWebSocket());};_createWebSocket=()=>{let e=typeof this._url=="string"?this._url:this._url?.(this);if(!e)return;this._clearConnectTimeoutIfNeed(),this._clearPendingReconnectIfNeeded(),this._removeWebSocketEvent(),this._realWebSocket=new WebSocket(e,this._protocols||void 0),this._attempts++,this.emit("connecting",new CustomEvent("connecting",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));let t=()=>{this._connectTimeout=void 0,this._detachConnectivityEvents(),this.emit("timeout",new CustomEvent("timeout",{detail:{attempts:this._attempts,reconnects:this._reconnects}}));};this._connectTimeout=setTimeout(t,this._options.timeout),this._dispatchWebSocketEvent(),this._options.ignoreConnectivityEvents||this._attachConnectivityEvents();};_removeWebSocketEvent=()=>{this._realWebSocket?.removeEventListener("open",this._webSocketOpenHandler),this._realWebSocket?.removeEventListener("close",this._webSocketCloseHandler),this._realWebSocket?.removeEventListener("error",this._webSocketErrorHandler),this._realWebSocket?.removeEventListener("message",this._webSocketMessageHandler);};_dispatchWebSocketEvent=()=>{this._realWebSocket?.addEventListener("open",this._webSocketOpenHandler),this._realWebSocket?.addEventListener("close",this._webSocketCloseHandler),this._realWebSocket?.addEventListener("error",this._webSocketErrorHandler),this._realWebSocket?.addEventListener("message",this._webSocketMessageHandler);};_webSocketOpenHandler=e=>{this._connectTimeout&&(clearTimeout(this._connectTimeout),this._connectTimeout=void 0);let t=++this._reconnects,r=this._attempts;return this._attempts=0,this._reconnectWhenOnlineAgain=!1,this._startHealthCheck(),this.emit("open",Object.assign(e,{detail:{reconnects:t,attempts:r}}))};_webSocketCloseHandler=e=>(this._reconnect(e),this._stopHealthCheck(),this.emit("close",e));_webSocketErrorHandler=e=>this.emit("error",new CustomEvent("error",{detail:{error:e}}));_webSocketMessageHandler=e=>this.emit("message",e);_reconnect(e){if(!this._options.should1000Reconnect&&e.code===1e3||this._explicitlyClosed){this._attempts=0;return}if(this._connectivityEventsAttached&&globalThis?.navigator?.onLine===!1){this._reconnectWhenOnlineAgain=!0;return}let i=this._options.shouldReconnect?.(e,this);typeof i=="number"?(console.log(`Reconnecting in ${i}ms...`),this._pendingReconnect=setTimeout(this._createWebSocket,i)):console.log("No reconnection will be attempted.");}};var He=class extends M{_ws=new Je({url:"",robustOptions:{should1000Reconnect:!0,ignoreConnectivityEvents:!0}});_state=-1;set state(e){let t=JSON.parse(JSON.stringify(this._state));this._state=e,this.emit("stateChange",this.state,t);}get state(){return this._state}constructor(){super(),this._addWebSocketEventListeners();}_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);};_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);};_handleCloseEvent=e=>{p.info(`live room closed bacause of ${e.code}-${e.reason||bn(e.code)}`),this.state=3;};_handleClosingEvent=()=>{p.info("live room is closing, onLine:",globalThis?.navigator?.onLine),this.state=3;};_handleConnectingEvent=e=>{p.info("live room is connecting"),this.state=0,e.detail.reconnects>0&&this.emit("reconnecting",e.detail);};_handleErrorEvent=e=>{p.error("live room error",e),this.state=3;};_handleMessageEvent=e=>{let t=(()=>{try{return JSON.parse(e.data)}catch{return e.data}})();this.emit("message",t);};_handleOpenEvent=e=>{p.info("live room open",e.detail),this.state=1,e.detail.reconnects>0&&this.emit("reconnected",e.detail);};_handleTimeoutEvent=e=>{p.error("live room connect timeout!",e.detail),this.state=3;};dispose=async()=>(this._removeWebSocketEventListeners(),await this.close("live room close by controller disposed!"));open=e=>this._ws.open(e);close=(e,t)=>new Promise(r=>{this._ws.once("close",()=>r(!0)),this._ws.close(e,t);});sendMessage(e=""){if(e==null)throw new Error("live message is empty!");if(this.state!==1)throw new Error("live has not yet been initialized!");return this._ws.send(JSON.stringify(e))}readyClose(){this._ws&&(this._ws._explicitlyClosed=!0);}};var A=()=>new Map,ze=n=>{let e=A();return n.forEach((t,r)=>{e.set(r,t);}),e},Z=(n,e,t)=>{let r=n.get(e);return r===void 0&&n.set(e,r=t()),r},Tn=(n,e)=>{let t=[];for(let[r,i]of n)t.push(e(i,r));return t},Rn=(n,e)=>{for(let[t,r]of n)if(e(r,t))return !0;return !1};var J=()=>new Set;var Ye=n=>n[n.length-1];var Q=Array.from;var Ct=Array.isArray;var Xe=class{constructor(){this._observers=A();}on(e,t){return Z(this._observers,e,J).add(t),t}once(e,t){let r=(...i)=>{this.off(e,r),t(...i);};this.on(e,r);}off(e,t){let r=this._observers.get(e);r!==void 0&&(r.delete(t),r.size===0&&this._observers.delete(e));}emit(e,t){return Q((this._observers.get(e)||A()).values()).forEach(r=>r(...t))}destroy(){this._observers=A();}};var K=Math.floor;var fe=Math.abs;var Ze=(n,e)=>n<e?n:e,ee=(n,e)=>n>e?n:e;var Dn=n=>n!==0?n<0:1/n<0;var Un=Number.isInteger||(n=>typeof n=="number"&&isFinite(n)&&K(n)===n);var Di=n=>n.toLowerCase(),Ui=/^\s*/g,Oi=n=>n.replace(Ui,""),Ai=/([A-Z])/g,Rt=(n,e)=>Oi(n.replace(Ai,t=>`${e}${Di(t)}`));var Li=n=>{let e=unescape(encodeURIComponent(n)),t=e.length,r=new Uint8Array(t);for(let i=0;i<t;i++)r[i]=e.codePointAt(i);return r},ge=typeof TextEncoder<"u"?new TextEncoder:null,Vi=n=>ge.encode(n),On=ge?Vi:Li;var Tt=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Tt&&Tt.decode(new Uint8Array).length===1&&(Tt=null);var oe=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[];}},tt=()=>new oe;var Bi=n=>{let e=n.cpos;for(let t=0;t<n.bufs.length;t++)e+=n.bufs[t].length;return e};var P=n=>{let e=new Uint8Array(Bi(n)),t=0;for(let r=0;r<n.bufs.length;r++){let i=n.bufs[r];e.set(i,t),t+=i.length;}return e.set(new Uint8Array(n.cbuf.buffer,0,n.cpos),t),e},Ki=(n,e)=>{let t=n.cbuf.length;t-n.cpos<e&&(n.bufs.push(new Uint8Array(n.cbuf.buffer,0,n.cpos)),n.cbuf=new Uint8Array(ee(t,e)*2),n.cpos=0);},I=(n,e)=>{let t=n.cbuf.length;n.cpos===t&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(t*2),n.cpos=0),n.cbuf[n.cpos++]=e;};var nt=I;var y=(n,e)=>{for(;e>127;)I(n,128|127&e),e=K(e/128);I(n,127&e);},rt=(n,e)=>{let t=Dn(e);for(t&&(e=-e),I(n,(e>63?128:0)|(t?64:0)|63&e),e=K(e/64);e>0;)I(n,(e>127?128:0)|127&e),e=K(e/128);},Ut=new Uint8Array(3e4),Pi=Ut.length/3,ji=(n,e)=>{if(e.length<Pi){let t=ge.encodeInto(e,Ut).written||0;y(n,t);for(let r=0;r<t;r++)I(n,Ut[r]);}else L(n,On(e));},Fi=(n,e)=>{let t=unescape(encodeURIComponent(e)),r=t.length;y(n,r);for(let i=0;i<r;i++)I(n,t.codePointAt(i));},ce=ge&&ge.encodeInto?ji:Fi;var it=(n,e)=>{let t=n.cbuf.length,r=n.cpos,i=Ze(t-r,e.length),s=e.length-i;n.cbuf.set(e.subarray(0,i),r),n.cpos+=i,s>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(ee(t*2,s)),n.cbuf.set(e.subarray(i)),n.cpos=s);},L=(n,e)=>{y(n,e.byteLength),it(n,e);},Ot=(n,e)=>{Ki(n,e);let t=new DataView(n.cbuf.buffer,n.cpos,e);return n.cpos+=e,t},Wi=(n,e)=>Ot(n,4).setFloat32(0,e,!1),$i=(n,e)=>Ot(n,8).setFloat64(0,e,!1),Gi=(n,e)=>Ot(n,8).setBigInt64(0,e,!1);var Ln=new DataView(new ArrayBuffer(4)),qi=n=>(Ln.setFloat32(0,n),Ln.getFloat32(0)===n),pe=(n,e)=>{switch(typeof e){case"string":I(n,119),ce(n,e);break;case"number":Un(e)&&fe(e)<=2147483647?(I(n,125),rt(n,e)):qi(e)?(I(n,124),Wi(n,e)):(I(n,123),$i(n,e));break;case"bigint":I(n,122),Gi(n,e);break;case"object":if(e===null)I(n,126);else if(Ct(e)){I(n,117),y(n,e.length);for(let t=0;t<e.length;t++)pe(n,e[t]);}else if(e instanceof Uint8Array)I(n,116),L(n,e);else {I(n,118);let t=Object.keys(e);y(n,t.length);for(let r=0;r<t.length;r++){let i=t[r];ce(n,i),pe(n,e[i]);}}break;case"boolean":I(n,e?120:121);break;default:I(n,127);}},Re=class extends oe{constructor(e){super(),this.w=e,this.s=null,this.count=0;}write(e){this.s===e?this.count++:(this.count>0&&y(this,this.count-1),this.count=1,this.w(this,e),this.s=e);}};var Vn=n=>{n.count>0&&(rt(n.encoder,n.count===1?n.s:-n.s),n.count>1&&y(n.encoder,n.count-2));},ae=class{constructor(){this.encoder=new oe,this.s=0,this.count=0;}write(e){this.s===e?this.count++:(Vn(this),this.count=1,this.s=e);}toUint8Array(){return Vn(this),P(this.encoder)}};var Mn=n=>{if(n.count>0){let e=n.diff*2+(n.count===1?0:1);rt(n.encoder,e),n.count>1&&y(n.encoder,n.count-2);}},me=class{constructor(){this.encoder=new oe,this.s=0,this.count=0,this.diff=0;}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Mn(this),this.count=1,this.diff=e-this.s,this.s=e);}toUint8Array(){return Mn(this),P(this.encoder)}},et=class{constructor(){this.sarr=[],this.s="",this.lensE=new ae;}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length);}toUint8Array(){let e=new oe;return this.sarr.push(this.s),this.s="",ce(e,this.sarr.join("")),it(e,this.lensE.toUint8Array()),P(e)}};var le=n=>new Error(n),N=()=>{throw le("Method unimplemented")},te=()=>{throw le("Unexpected case")};var Nn=crypto.getRandomValues.bind(crypto);var At=()=>Nn(new Uint32Array(1))[0];var zi="10000000-1000-4000-8000"+-1e11,Bn=()=>zi.replace(/[018]/g,n=>(n^At()&15>>n/4).toString(16));var Lt=n=>new Promise(n);Promise.all.bind(Promise);var Vt=n=>n===void 0?null:n;var Mt=class{constructor(){this.map=new Map;}setItem(e,t){this.map.set(e,t);}getItem(e){return this.map.get(e)}},Pn=new Mt,es=!0;try{typeof localStorage<"u"&&localStorage&&(Pn=localStorage,es=!1);}catch{}var jn=Pn;var Wn=Object.assign,ns=Object.keys,$n=(n,e)=>{for(let t in n)e(n[t],t);};var Fn=n=>ns(n).length;var Gn=n=>{for(let e in n)return !1;return !0},rs=(n,e)=>{for(let t in n)if(!e(n[t],t))return !1;return !0},is=(n,e)=>Object.prototype.hasOwnProperty.call(n,e),qn=(n,e)=>n===e||Fn(n)===Fn(e)&&rs(n,(t,r)=>(t!==void 0||is(e,r))&&e[r]===t),ss=Object.freeze,Nt=n=>{for(let e in n){let t=n[e];(typeof t=="object"||typeof t=="function")&&Nt(n[e]);}return ss(n)};var De=(n,e,t=0)=>{try{for(;t<n.length;t++)n[t](...e);}finally{t<n.length&&De(n,e,t+1);}};var Jn=(n,e)=>e.includes(n);var Ue=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]";var j,cs=[],as=()=>{if(j===void 0)if(Ue){j=A();let n=process.argv,e=null;for(let t=0;t<n.length;t++){let r=n[t];r[0]==="-"?(e!==null&&j.set(e,""),e=r):e!==null?(j.set(e,r),e=null):cs.push(r);}e!==null&&j.set(e,"");}else typeof location=="object"?(j=A(),(location.search||"?").slice(1).split("&").forEach(n=>{if(n.length!==0){let[e,t]=n.split("=");j.set(`--${Rt(e,"-")}`,t),j.set(`-${Rt(e,"-")}`,t);}})):j=A();return j},Bt=n=>as().has(n);var Oe=n=>Ue?Vt(process.env[n.toUpperCase().replaceAll("-","_")]):Vt(jn.getItem(n));var zn=n=>Bt("--"+n)||Oe(n)!==null;zn("production");var ls=Ue&&Jn(process.env.FORCE_COLOR,["true","1","2"]),Yn=ls||!Bt("--no-colors")&&!zn("no-color")&&(!Ue||process.stdout.isTTY)&&(!Ue||Bt("--color")||Oe("COLORTERM")!==null||(Oe("TERM")||"").includes("color"));var Kt=class{constructor(e,t){this.left=e,this.right=t;}},F=(n,e)=>new Kt(n,e);typeof DOMParser<"u"?new DOMParser:null;var Zn=n=>Tn(n,(e,t)=>`${t}:${e};`).join("");var W=Symbol;var Ae=W(),Le=W(),Pt=W(),jt=W(),Ft=W(),Ve=W(),Wt=W(),ye=W(),$t=W(),Qn=n=>{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());let e=[],t=[],r=0;for(;r<n.length;r++){let i=n[r];if(i===void 0)break;if(i.constructor===String||i.constructor===Number)e.push(i);else if(i.constructor===Object)break}for(r>0&&t.push(e.join(""));r<n.length;r++){let i=n[r];i instanceof Symbol||t.push(i);}return t};var gs={[Ae]:F("font-weight","bold"),[Le]:F("font-weight","normal"),[Pt]:F("color","blue"),[Ft]:F("color","green"),[jt]:F("color","grey"),[Ve]:F("color","red"),[Wt]:F("color","purple"),[ye]:F("color","orange"),[$t]:F("color","black")},ps=n=>{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());let e=[],t=[],r=A(),i=[],s=0;for(;s<n.length;s++){let o=n[s],c=gs[o];if(c!==void 0)r.set(c.left,c.right);else {if(o===void 0)break;if(o.constructor===String||o.constructor===Number){let a=Zn(r);s>0||a.length>0?(e.push("%c"+o),t.push(a)):e.push(o);}else break}}for(s>0&&(i=t,i.unshift(e.join("")));s<n.length;s++){let o=n[s];o instanceof Symbol||i.push(o);}return i},er=Yn?ps:Qn,tr=(...n)=>{console.log(...er(n)),rr.forEach(e=>e.print(n));},nr=(...n)=>{console.warn(...er(n)),n.unshift(ye),rr.forEach(e=>e.print(n));};var rr=J();var ir=n=>({[Symbol.iterator](){return this},next:n}),sr=(n,e)=>ir(()=>{let t;do t=n.next();while(!t.done&&!e(t.value));return t}),st=(n,e)=>ir(()=>{let{done:t,value:r}=n.next();return {done:t,value:t?void 0:e(r)}});var Jt=class{constructor(e,t){this.clock=e,this.len=t;}},dt=class{constructor(){this.clients=new Map;}},wr=(n,e,t)=>e.clients.forEach((r,i)=>{let s=n.doc.store.clients.get(i);for(let o=0;o<r.length;o++){let c=r[o];Cr(n,s,c.clock,c.len,t);}}),bs=(n,e)=>{let t=0,r=n.length-1;for(;t<=r;){let i=K((t+r)/2),s=n[i],o=s.clock;if(o<=e){if(e<o+s.len)return i;t=i+1;}else r=i-1;}return null},_r=(n,e)=>{let t=n.clients.get(e.client);return t!==void 0&&bs(t,e.clock)!==null},br=n=>{n.clients.forEach(e=>{e.sort((i,s)=>i.clock-s.clock);let t,r;for(t=1,r=1;t<e.length;t++){let i=e[r-1],s=e[t];i.clock+i.len>=s.clock?i.len=ee(i.len,s.clock+s.len-i.clock):(r<t&&(e[r]=s),r++);}e.length=r;});};var Sr=(n,e,t,r)=>{Z(n.clients,e,()=>[]).push(new Jt(t,r));};var vs=(n,e)=>{y(n.restEncoder,e.clients.size),Q(e.clients.entries()).sort((t,r)=>r[0]-t[0]).forEach(([t,r])=>{n.resetDsCurVal(),y(n.restEncoder,t);let i=r.length;y(n.restEncoder,i);for(let s=0;s<i;s++){let o=r[s];n.writeDsClock(o.clock),n.writeDsLen(o.len);}});};var vr=At,he=class n extends Xe{constructor({guid:e=Bn(),collectionid:t=null,gc:r=!0,gcFilter:i=()=>!0,meta:s=null,autoLoad:o=!1,shouldLoad:c=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=vr(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new tn,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=c,this.autoLoad=o,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Lt(l=>{this.on("load",()=>{this.isLoaded=!0,l(this);});});let a=()=>Lt(l=>{let d=u=>{(u===void 0||u===!0)&&(this.off("sync",d),l());};this.on("sync",d);});this.on("sync",l=>{l===!1&&this.isSynced&&(this.whenSynced=a()),this.isSynced=l===void 0||l===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this]);}),this.whenSynced=a();}load(){let e=this._item;e!==null&&!this.shouldLoad&&b(e.parent.doc,t=>{t.subdocsLoaded.add(this);},null,!0),this.shouldLoad=!0;}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Q(this.subdocs).map(e=>e.guid))}transact(e,t=null){return b(this,e,t)}get(e,t=k){let r=Z(this.share,e,()=>{let s=new t;return s._integrate(this,null),s}),i=r.constructor;if(t!==k&&i!==t)if(i===k){let s=new t;s._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=s;}),s._start=r._start;for(let o=s._start;o!==null;o=o.right)o.parent=s;return s._length=r._length,this.share.set(e,s),s._integrate(this,null),s}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,cn)}getText(e=""){return this.get(e,hn)}getMap(e=""){return this.get(e,ln)}getXmlElement(e=""){return this.get(e,ft)}getXmlFragment(e=""){return this.get(e,Pe)}toJSON(){let e={};return this.share.forEach((t,r)=>{e[r]=t.toJSON();}),e}destroy(){this.isDestroyed=!0,Q(this.subdocs).forEach(t=>t.destroy());let e=this._item;if(e!==null){this._item=null;let t=e.content;t.doc=new n({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,b(e.parent.doc,r=>{let i=t.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this);},null,!0);}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy();}};var Ht=class{constructor(){this.restEncoder=tt();}toUint8Array(){return P(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){y(this.restEncoder,e);}writeDsLen(e){y(this.restEncoder,e);}},zt=class extends Ht{writeLeftID(e){y(this.restEncoder,e.client),y(this.restEncoder,e.clock);}writeRightID(e){y(this.restEncoder,e.client),y(this.restEncoder,e.clock);}writeClient(e){y(this.restEncoder,e);}writeInfo(e){nt(this.restEncoder,e);}writeString(e){ce(this.restEncoder,e);}writeParentInfo(e){y(this.restEncoder,e?1:0);}writeTypeRef(e){y(this.restEncoder,e);}writeLen(e){y(this.restEncoder,e);}writeAny(e){pe(this.restEncoder,e);}writeBuf(e){L(this.restEncoder,e);}writeJSON(e){ce(this.restEncoder,JSON.stringify(e));}writeKey(e){ce(this.restEncoder,e);}},Yt=class{constructor(){this.restEncoder=tt(),this.dsCurrVal=0;}toUint8Array(){return P(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0;}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,y(this.restEncoder,t);}writeDsLen(e){e===0&&te(),y(this.restEncoder,e-1),this.dsCurrVal+=e;}},Xt=class extends Yt{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new me,this.clientEncoder=new ae,this.leftClockEncoder=new me,this.rightClockEncoder=new me,this.infoEncoder=new Re(nt),this.stringEncoder=new et,this.parentInfoEncoder=new Re(nt),this.typeRefEncoder=new ae,this.lenEncoder=new ae;}toUint8Array(){let e=tt();return y(e,0),L(e,this.keyClockEncoder.toUint8Array()),L(e,this.clientEncoder.toUint8Array()),L(e,this.leftClockEncoder.toUint8Array()),L(e,this.rightClockEncoder.toUint8Array()),L(e,P(this.infoEncoder)),L(e,this.stringEncoder.toUint8Array()),L(e,P(this.parentInfoEncoder)),L(e,this.typeRefEncoder.toUint8Array()),L(e,this.lenEncoder.toUint8Array()),it(e,P(this.restEncoder)),P(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){pe(this.restEncoder,e);}writeBuf(e){L(this.restEncoder,e);}writeJSON(e){pe(this.restEncoder,e);}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t);}},Es=(n,e,t,r)=>{r=ee(r,e[0].id.clock);let i=H(e,r);y(n.restEncoder,e.length-i),n.writeClient(t),y(n.restEncoder,r);let s=e[i];s.write(n,r-s.id.clock);for(let o=i+1;o<e.length;o++)e[o].write(n,0);},ks=(n,e,t)=>{let r=new Map;t.forEach((i,s)=>{V(e,s)>i&&r.set(s,i);}),gn(e).forEach((i,s)=>{t.has(s)||r.set(s,0);}),y(n.restEncoder,r.size),Q(r.entries()).sort((i,s)=>s[0]-i[0]).forEach(([i,s])=>{Es(n,e.clients.get(i),i,s);});};var Cs=(n,e)=>ks(n,e.doc.store,e.beforeState);var Zt=class{constructor(){this.l=[];}},ar=()=>new Zt,lr=(n,e)=>n.l.push(e),dr=(n,e)=>{let t=n.l,r=t.length;n.l=t.filter(i=>e!==i),r===n.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.");},Er=(n,e,t)=>De(n.l,[e,t]),_e=class{constructor(e,t){this.client=e,this.clock=t;}},ot=(n,e)=>n===e||n!==null&&e!==null&&n.client===e.client&&n.clock===e.clock,S=(n,e)=>new _e(n,e);var xs=n=>{for(let[e,t]of n.doc.share.entries())if(t===n)return e;throw te()};var we=(n,e)=>e===void 0?!n.deleted:e.sv.has(n.id.client)&&(e.sv.get(n.id.client)||0)>n.id.clock&&!_r(e.ds,n.id),en=(n,e)=>{let t=Z(n.meta,en,J),r=n.doc.store;t.has(e)||(e.sv.forEach((i,s)=>{i<V(r,s)&&re(n,S(s,i));}),wr(n,e.ds,i=>{}),t.add(e));};var tn=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null;}},gn=n=>{let e=new Map;return n.clients.forEach((t,r)=>{let i=t[t.length-1];e.set(r,i.id.clock+i.length);}),e},V=(n,e)=>{let t=n.clients.get(e);if(t===void 0)return 0;let r=t[t.length-1];return r.id.clock+r.length},kr=(n,e)=>{let t=n.clients.get(e.id.client);if(t===void 0)t=[],n.clients.set(e.id.client,t);else {let r=t[t.length-1];if(r.id.clock+r.length!==e.id.clock)throw te()}t.push(e);},H=(n,e)=>{let t=0,r=n.length-1,i=n[r],s=i.id.clock;if(s===e)return r;let o=K(e/(s+i.length-1)*r);for(;t<=r;){if(i=n[o],s=i.id.clock,s<=e){if(e<s+i.length)return o;t=o+1;}else r=o-1;o=K((t+r)/2);}throw te()},Ts=(n,e)=>{let t=n.clients.get(e.client);return t[H(t,e.clock)]},Gt=Ts,nn=(n,e,t)=>{let r=H(e,t),i=e[r];return i.id.clock<t&&i instanceof O?(e.splice(r+1,0,Fr(n,i,t-i.id.clock)),r+1):r},re=(n,e)=>{let t=n.doc.store.clients.get(e.client);return t[nn(n,t,e.clock)]},hr=(n,e,t)=>{let r=e.clients.get(t.client),i=H(r,t.clock),s=r[i];return t.clock!==s.id.clock+s.length-1&&s.constructor!==$&&r.splice(i+1,0,Fr(n,s,t.clock-s.id.clock+1)),s},Rs=(n,e,t)=>{let r=n.clients.get(e.id.client);r[H(r,e.id.clock)]=t;},Cr=(n,e,t,r,i)=>{if(r===0)return;let s=t+r,o=nn(n,e,t),c;do c=e[o++],s<c.id.clock+c.length&&nn(n,e,s),i(c);while(o<e.length&&e[o].id.clock<s)},rn=class{constructor(e,t,r){this.doc=e,this.deleteSet=new dt,this.beforeState=gn(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=r,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1;}},ur=(n,e)=>e.deleteSet.clients.size===0&&!Rn(e.afterState,(t,r)=>e.beforeState.get(r)!==t)?!1:(br(e.deleteSet),Cs(n,e),vs(n,e.deleteSet),!0),fr=(n,e,t)=>{let r=e._item;(r===null||r.id.clock<(n.beforeState.get(r.id.client)||0)&&!r.deleted)&&Z(n.changed,e,J).add(t);},lt=(n,e)=>{let t=n[e],r=n[e-1],i=e;for(;i>0;t=r,r=n[--i-1]){if(r.deleted===t.deleted&&r.constructor===t.constructor&&r.mergeWith(t)){t instanceof O&&t.parentSub!==null&&t.parent._map.get(t.parentSub)===t&&t.parent._map.set(t.parentSub,r);continue}break}let s=e-i;return s&&n.splice(e+1-s,s),s},Ds=(n,e,t)=>{for(let[r,i]of n.clients.entries()){let s=e.clients.get(r);for(let o=i.length-1;o>=0;o--){let c=i[o],a=c.clock+c.len;for(let l=H(s,c.clock),d=s[l];l<s.length&&d.id.clock<a;d=s[++l]){let u=s[l];if(c.clock+c.len<=u.id.clock)break;u instanceof O&&u.deleted&&!u.keep&&t(u)&&u.gc(e,!1);}}}},Us=(n,e)=>{n.clients.forEach((t,r)=>{let i=e.clients.get(r);for(let s=t.length-1;s>=0;s--){let o=t[s],c=Ze(i.length-1,1+H(i,o.clock+o.len-1));for(let a=c,l=i[a];a>0&&l.id.clock>=o.clock;l=i[a])a-=1+lt(i,a);}});};var xr=(n,e)=>{if(e<n.length){let t=n[e],r=t.doc,i=r.store,s=t.deleteSet,o=t._mergeStructs;try{br(s),t.afterState=gn(t.doc.store),r.emit("beforeObserverCalls",[t,r]);let c=[];t.changed.forEach((a,l)=>c.push(()=>{(l._item===null||!l._item.deleted)&&l._callObserver(t,a);})),c.push(()=>{t.changedParentTypes.forEach((a,l)=>{l._dEH.l.length>0&&(l._item===null||!l._item.deleted)&&(a=a.filter(d=>d.target._item===null||!d.target._item.deleted),a.forEach(d=>{d.currentTarget=l,d._path=null;}),a.sort((d,u)=>d.path.length-u.path.length),Er(l._dEH,a,t));});}),c.push(()=>r.emit("afterTransaction",[t,r])),De(c,[]),t._needFormattingCleanup&&Ps(t);}finally{r.gc&&Ds(s,i,r.gcFilter),Us(s,i),t.afterState.forEach((d,u)=>{let g=t.beforeState.get(u)||0;if(g!==d){let f=i.clients.get(u),w=ee(H(f,g),1);for(let C=f.length-1;C>=w;)C-=1+lt(f,C);}});for(let d=o.length-1;d>=0;d--){let{client:u,clock:g}=o[d].id,f=i.clients.get(u),w=H(f,g);w+1<f.length&<(f,w+1)>1||w>0&<(f,w);}if(!t.local&&t.afterState.get(r.clientID)!==t.beforeState.get(r.clientID)&&(tr(ye,Ae,"[yjs] ",Le,Ve,"Changed the client-id because another client seems to be using it."),r.clientID=vr()),r.emit("afterTransactionCleanup",[t,r]),r._observers.has("update")){let d=new zt;ur(d,t)&&r.emit("update",[d.toUint8Array(),t.origin,r,t]);}if(r._observers.has("updateV2")){let d=new Xt;ur(d,t)&&r.emit("updateV2",[d.toUint8Array(),t.origin,r,t]);}let{subdocsAdded:c,subdocsLoaded:a,subdocsRemoved:l}=t;(c.size>0||l.size>0||a.size>0)&&(c.forEach(d=>{d.clientID=r.clientID,d.collectionid==null&&(d.collectionid=r.collectionid),r.subdocs.add(d);}),l.forEach(d=>r.subdocs.delete(d)),r.emit("subdocs",[{loaded:a,added:c,removed:l},r,t]),l.forEach(d=>d.destroy())),n.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,n])):xr(n,e+1);}}},b=(n,e,t=null,r=!0)=>{let i=n._transactionCleanups,s=!1,o=null;n._transaction===null&&(s=!0,n._transaction=new rn(n,t,r),i.push(n._transaction),i.length===1&&n.emit("beforeAllTransactions",[n]),n.emit("beforeTransaction",[n._transaction,n]));try{o=e(n._transaction);}finally{if(s){let c=n._transaction===i[0];n._transaction=null,c&&xr(i,0);}}return o};var gr="You must not compute changes after the event-handler fired.",be=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null;}get path(){return this._path||(this._path=Os(this.currentTarget,this.target))}deletes(e){return _r(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw le(gr);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(i=>{if(i!==null){let s=t._map.get(i),o,c;if(this.adds(s)){let a=s.left;for(;a!==null&&this.adds(a);)a=a.left;if(this.deletes(s))if(a!==null&&this.deletes(a))o="delete",c=Ye(a.content.getContent());else return;else a!==null&&this.deletes(a)?(o="update",c=Ye(a.content.getContent())):(o="add",c=void 0);}else if(this.deletes(s))o="delete",c=Ye(s.content.getContent());else return;e.set(i,{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 le(gr);let t=this.target,r=J(),i=J(),s=[];if(e={added:r,deleted:i,delta:s,keys:this.keys},this.transaction.changed.get(t).has(null)){let c=null,a=()=>{c&&s.push(c);};for(let l=t._start;l!==null;l=l.right)l.deleted?this.deletes(l)&&!this.adds(l)&&((c===null||c.delete===void 0)&&(a(),c={delete:0}),c.delete+=l.length,i.add(l)):this.adds(l)?((c===null||c.insert===void 0)&&(a(),c={insert:[]}),c.insert=c.insert.concat(l.content.getContent()),r.add(l)):((c===null||c.retain===void 0)&&(a(),c={retain:0}),c.retain+=l.length);c!==null&&c.retain===void 0&&a();}this._changes=e;}return e}},Os=(n,e)=>{let t=[];for(;e._item!==null&&e!==n;){if(e._item.parentSub!==null)t.unshift(e._item.parentSub);else {let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;t.unshift(r);}e=e._item.parent;}return t},U=()=>{nr("Invalid access: Add Yjs type to a document before reading data.");},Ir=80,pn=0,sn=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=pn++;}},As=n=>{n.timestamp=pn++;},Tr=(n,e,t)=>{n.p.marker=!1,n.p=e,e.marker=!0,n.index=t,n.timestamp=pn++;},Ls=(n,e,t)=>{if(n.length>=Ir){let r=n.reduce((i,s)=>i.timestamp<s.timestamp?i:s);return Tr(r,e,t),r}else {let r=new sn(e,t);return n.push(r),r}},yt=(n,e)=>{if(n._start===null||e===0||n._searchMarker===null)return null;let t=n._searchMarker.length===0?null:n._searchMarker.reduce((s,o)=>fe(e-s.index)<fe(e-o.index)?s:o),r=n._start,i=0;for(t!==null&&(r=t.p,i=t.index,As(t));r.right!==null&&i<e;){if(!r.deleted&&r.countable){if(e<i+r.length)break;i+=r.length;}r=r.right;}for(;r.left!==null&&i>e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return t!==null&&fe(t.index-i)<r.parent.length/Ir?(Tr(t,r,i),t):Ls(n._searchMarker,r,i)},Ne=(n,e,t)=>{for(let r=n.length-1;r>=0;r--){let i=n[r];if(t>0){let s=i.p;for(s.marker=!1;s&&(s.deleted||!s.countable);)s=s.left,s&&!s.deleted&&s.countable&&(i.index-=s.length);if(s===null||s.marker===!0){n.splice(r,1);continue}i.p=s,s.marker=!0;}(e<i.index||t>0&&e===i.index)&&(i.index=ee(e,i.index+t));}};var wt=(n,e,t)=>{let r=n,i=e.changedParentTypes;for(;Z(i,n,()=>[]).push(t),n._item!==null;)n=n._item.parent;Er(r._eH,t,e);},k=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=ar(),this._dEH=ar(),this._searchMarker=null;}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t;}_copy(){throw N()}clone(){throw N()}_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){lr(this._eH,e);}observeDeep(e){lr(this._dEH,e);}unobserve(e){dr(this._eH,e);}unobserveDeep(e){dr(this._dEH,e);}toJSON(){}},Rr=(n,e,t)=>{n.doc??U(),e<0&&(e=n._length+e),t<0&&(t=n._length+t);let r=t-e,i=[],s=n._start;for(;s!==null&&r>0;){if(s.countable&&!s.deleted){let o=s.content.getContent();if(o.length<=e)e-=o.length;else {for(let c=e;c<o.length&&r>0;c++)i.push(o[c]),r--;e=0;}}s=s.right;}return i},Dr=n=>{n.doc??U();let e=[],t=n._start;for(;t!==null;){if(t.countable&&!t.deleted){let r=t.content.getContent();for(let i=0;i<r.length;i++)e.push(r[i]);}t=t.right;}return e};var Be=(n,e)=>{let t=0,r=n._start;for(n.doc??U();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let s=0;s<i.length;s++)e(i[s],t++,n);}r=r.right;}},Ur=(n,e)=>{let t=[];return Be(n,(r,i)=>{t.push(e(r,i,n));}),t},Vs=n=>{let e=n._start,t=null,r=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(),r=0,e=e.right;}let i=t[r++];return t.length<=r&&(t=null),{done:!1,value:i}}}},Or=(n,e)=>{n.doc??U();let t=yt(n,e),r=n._start;for(t!==null&&(r=t.p,e-=t.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e<r.length)return r.content.getContent()[e];e-=r.length;}},ht=(n,e,t,r)=>{let i=t,s=n.doc,o=s.clientID,c=s.store,a=t===null?e._start:t.right,l=[],d=()=>{l.length>0&&(i=new O(S(o,V(c,o)),i,i&&i.lastId,a,a&&a.id,e,null,new je(l)),i.integrate(n,0),l=[]);};r.forEach(u=>{if(u===null)l.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(u);break;default:switch(d(),u.constructor){case Uint8Array:case ArrayBuffer:i=new O(S(o,V(c,o)),i,i&&i.lastId,a,a&&a.id,e,null,new pt(new Uint8Array(u))),i.integrate(n,0);break;case he:i=new O(S(o,V(c,o)),i,i&&i.lastId,a,a&&a.id,e,null,new mt(u)),i.integrate(n,0);break;default:if(u instanceof k)i=new O(S(o,V(c,o)),i,i&&i.lastId,a,a&&a.id,e,null,new se(u)),i.integrate(n,0);else throw new Error("Unexpected content type in insert operation")}}}),d();},Ar=()=>le("Length exceeded!"),Lr=(n,e,t,r)=>{if(t>e._length)throw Ar();if(t===0)return e._searchMarker&&Ne(e._searchMarker,t,r.length),ht(n,e,null,r);let i=t,s=yt(e,t),o=e._start;for(s!==null&&(o=s.p,t-=s.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(n,S(o.id.client,o.id.clock+t));break}t-=o.length;}return e._searchMarker&&Ne(e._searchMarker,i,r.length),ht(n,e,o,r)},Ms=(n,e,t)=>{let i=(e._searchMarker||[]).reduce((s,o)=>o.index>s.index?o:s,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return ht(n,e,i,t)},Vr=(n,e,t,r)=>{if(r===0)return;let i=t,s=r,o=yt(e,t),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(n,S(c.id.client,c.id.clock+t)),t-=c.length);for(;r>0&&c!==null;)c.deleted||(r<c.length&&re(n,S(c.id.client,c.id.clock+r)),c.delete(n),r-=c.length),c=c.right;if(r>0)throw Ar();e._searchMarker&&Ne(e._searchMarker,i,-s+r);},ut=(n,e,t)=>{let r=e._map.get(t);r!==void 0&&r.delete(n);},mn=(n,e,t,r)=>{let i=e._map.get(t)||null,s=n.doc,o=s.clientID,c;if(r==null)c=new je([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:c=new je([r]);break;case Uint8Array:c=new pt(r);break;case he:c=new mt(r);break;default:if(r instanceof k)c=new se(r);else throw new Error("Unexpected content type")}new O(S(o,V(s.store,o)),i,i&&i.lastId,null,null,e,t,c).integrate(n,0);},yn=(n,e)=>{n.doc??U();let t=n._map.get(e);return t!==void 0&&!t.deleted?t.content.getContent()[t.length-1]:void 0},Mr=n=>{let e={};return n.doc??U(),n._map.forEach((t,r)=>{t.deleted||(e[r]=t.content.getContent()[t.length-1]);}),e},Nr=(n,e)=>{n.doc??U();let t=n._map.get(e);return t!==void 0&&!t.deleted};var Ns=(n,e)=>{let t={};return n._map.forEach((r,i)=>{let s=r;for(;s!==null&&(!e.sv.has(s.id.client)||s.id.clock>=(e.sv.get(s.id.client)||0));)s=s.left;s!==null&&we(s,e)&&(t[i]=s.content.getContent()[s.length-1]);}),t},ct=n=>(n.doc??U(),sr(n._map.entries(),e=>!e[1].deleted)),on=class extends be{},cn=class n extends k{constructor(){super(),this._prelimContent=[],this._searchMarker=[];}static from(e){let t=new n;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null;}_copy(){return new n}clone(){let e=new n;return e.insert(0,this.toArray().map(t=>t instanceof k?t.clone():t)),e}get length(){return this.doc??U(),this._length}_callObserver(e,t){super._callObserver(e,t),wt(this,e,new on(this,e));}insert(e,t){this.doc!==null?b(this.doc,r=>{Lr(r,this,e,t);}):this._prelimContent.splice(e,0,...t);}push(e){this.doc!==null?b(this.doc,t=>{Ms(t,this,e);}):this._prelimContent.push(...e);}unshift(e){this.insert(0,e);}delete(e,t=1){this.doc!==null?b(this.doc,r=>{Vr(r,this,e,t);}):this._prelimContent.splice(e,t);}get(e){return Or(this,e)}toArray(){return Dr(this)}slice(e=0,t=this.length){return Rr(this,e,t)}toJSON(){return this.map(e=>e instanceof k?e.toJSON():e)}map(e){return Ur(this,e)}forEach(e){Be(this,e);}[Symbol.iterator](){return Vs(this)}_write(e){e.writeTypeRef($s);}};var an=class extends be{constructor(e,t,r){super(e,t),this.keysChanged=r;}},ln=class n extends k{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((r,i)=>{this.set(i,r);}),this._prelimContent=null;}_copy(){return new n}clone(){let e=new n;return this.forEach((t,r)=>{e.set(r,t instanceof k?t.clone():t);}),e}_callObserver(e,t){wt(this,e,new an(this,e,t));}toJSON(){this.doc??U();let e={};return this._map.forEach((t,r)=>{if(!t.deleted){let i=t.content.getContent()[t.length-1];e[r]=i instanceof k?i.toJSON():i;}}),e}get size(){return [...ct(this)].length}keys(){return st(ct(this),e=>e[0])}values(){return st(ct(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return st(ct(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??U(),this._map.forEach((t,r)=>{t.deleted||e(t.content.getContent()[t.length-1],r,this);});}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?b(this.doc,t=>{ut(t,this,e);}):this._prelimContent.delete(e);}set(e,t){return this.doc!==null?b(this.doc,r=>{mn(r,this,e,t);}):this._prelimContent.set(e,t),t}get(e){return yn(this,e)}has(e){return Nr(this,e)}clear(){this.doc!==null?b(this.doc,e=>{this.forEach(function(t,r,i){ut(e,i,r);});}):this._prelimContent.clear();}_write(e){e.writeTypeRef(Gs);}};var ne=(n,e)=>n===e||typeof n=="object"&&typeof e=="object"&&n&&e&&qn(n,e),Ke=class{constructor(e,t,r,i){this.left=e,this.right=t,this.index=r,this.currentAttributes=i;}forward(){switch(this.right===null&&te(),this.right.content.constructor){case T:this.right.deleted||ve(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;}},pr=(n,e,t)=>{for(;e.right!==null&&t>0;){switch(e.right.content.constructor){case T:e.right.deleted||ve(e.currentAttributes,e.right.content);break;default:e.right.deleted||(t<e.right.length&&re(n,S(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},at=(n,e,t,r)=>{let i=new Map,s=r?yt(e,t):null;if(s){let o=new Ke(s.p.left,s.p,s.index,i);return pr(n,o,t-s.index)}else {let o=new Ke(null,e._start,0,i);return pr(n,o,t)}},Br=(n,e,t,r)=>{for(;t.right!==null&&(t.right.deleted===!0||t.right.content.constructor===T&&ne(r.get(t.right.content.key),t.right.content.value));)t.right.deleted||r.delete(t.right.content.key),t.forward();let i=n.doc,s=i.clientID;r.forEach((o,c)=>{let a=t.left,l=t.right,d=new O(S(s,V(i.store,s)),a,a&&a.lastId,l,l&&l.id,e,null,new T(c,o));d.integrate(n,0),t.right=d,t.forward();});},ve=(n,e)=>{let{key:t,value:r}=e;r===null?n.delete(t):n.set(t,r);},Kr=(n,e)=>{for(;n.right!==null;){if(!(n.right.deleted||n.right.content.constructor===T&&ne(e[n.right.content.key]??null,n.right.content.value)))break;n.forward();}},Pr=(n,e,t,r)=>{let i=n.doc,s=i.clientID,o=new Map;for(let c in r){let a=r[c],l=t.currentAttributes.get(c)??null;if(!ne(l,a)){o.set(c,l);let{left:d,right:u}=t;t.right=new O(S(s,V(i.store,s)),d,d&&d.lastId,u,u&&u.id,e,null,new T(c,a)),t.right.integrate(n,0),t.forward();}}return o},qt=(n,e,t,r,i)=>{t.currentAttributes.forEach((g,f)=>{i[f]===void 0&&(i[f]=null);});let s=n.doc,o=s.clientID;Kr(t,i);let c=Pr(n,e,t,i),a=r.constructor===String?new ie(r):r instanceof k?new se(r):new Se(r),{left:l,right:d,index:u}=t;e._searchMarker&&Ne(e._searchMarker,t.index,a.getLength()),d=new O(S(o,V(s.store,o)),l,l&&l.lastId,d,d&&d.id,e,null,a),d.integrate(n,0),t.right=d,t.index=u,t.forward(),Br(n,e,t,c);},mr=(n,e,t,r,i)=>{let s=n.doc,o=s.clientID;Kr(t,i);let c=Pr(n,e,t,i);e:for(;t.right!==null&&(r>0||c.size>0&&(t.right.deleted||t.right.content.constructor===T));){if(!t.right.deleted)switch(t.right.content.constructor){case T:{let{key:a,value:l}=t.right.content,d=i[a];if(d!==void 0){if(ne(d,l))c.delete(a);else {if(r===0)break e;c.set(a,l);}t.right.delete(n);}else t.currentAttributes.set(a,l);break}default:r<t.right.length&&re(n,S(t.right.id.client,t.right.id.clock+r)),r-=t.right.length;break}t.forward();}if(r>0){let a="";for(;r>0;r--)a+=`
|
|
7
|
+
`;t.right=new O(S(o,V(s.store,o)),t.left,t.left&&t.left.lastId,t.right,t.right&&t.right.id,e,null,new ie(a)),t.right.integrate(n,0),t.forward();}Br(n,e,t,c);},jr=(n,e,t,r,i)=>{let s=e,o=A();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===T){let l=s.content;o.set(l.key,l);}s=s.right;}let c=0,a=!1;for(;e!==s;){if(t===e&&(a=!0),!e.deleted){let l=e.content;switch(l.constructor){case T:{let{key:d,value:u}=l,g=r.get(d)??null;(o.get(d)!==l||g===u)&&(e.delete(n),c++,!a&&(i.get(d)??null)===u&&g!==u&&(g===null?i.delete(d):i.set(d,g))),!a&&!e.deleted&&ve(i,l);break}}}e=e.right;}return c},Bs=(n,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;let t=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===T){let r=e.content.key;t.has(r)?e.delete(n):t.add(r);}e=e.left;}},Ks=n=>{let e=0;return b(n.doc,t=>{let r=n._start,i=n._start,s=A(),o=ze(s);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case T:ve(o,i.content);break;default:e+=jr(t,r,i,s,o),s=ze(o),r=i;break}i=i.right;}}),e},Ps=n=>{let e=new Set,t=n.doc;for(let[r,i]of n.afterState.entries()){let s=n.beforeState.get(r)||0;i!==s&&Cr(n,t.store.clients.get(r),s,i,o=>{!o.deleted&&o.content.constructor===T&&o.constructor!==$&&e.add(o.parent);});}b(t,r=>{wr(n,n.deleteSet,i=>{if(i instanceof $||!i.parent._hasFormatting||e.has(i.parent))return;let s=i.parent;i.content.constructor===T?e.add(s):Bs(r,i);});for(let i of e)Ks(i);});},yr=(n,e,t)=>{let r=t,i=ze(e.currentAttributes),s=e.right;for(;t>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case se:case Se:case ie:t<e.right.length&&re(n,S(e.right.id.client,e.right.id.clock+t)),t-=e.right.length,e.right.delete(n);break}e.forward();}s&&jr(n,s,e.right,i,e.currentAttributes);let o=(e.left||e.right).parent;return o._searchMarker&&Ne(o._searchMarker,e.index,-r+t),e},dn=class extends be{constructor(e,t,r){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,r.forEach(i=>{i===null?this.childListChanged=!0:this.keysChanged.add(i);});}get changes(){if(this._changes===null){let 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){let e=this.target.doc,t=[];b(e,r=>{let i=new Map,s=new Map,o=this.target._start,c=null,a={},l="",d=0,u=0,g=()=>{if(c!==null){let f=null;switch(c){case"delete":u>0&&(f={delete:u}),u=0;break;case"insert":(typeof l=="object"||l.length>0)&&(f={insert:l},i.size>0&&(f.attributes={},i.forEach((w,C)=>{w!==null&&(f.attributes[C]=w);}))),l="";break;case"retain":d>0&&(f={retain:d},Gn(a)||(f.attributes=Wn({},a))),d=0;break}f&&t.push(f),c=null;}};for(;o!==null;){switch(o.content.constructor){case se:case Se:this.adds(o)?this.deletes(o)||(g(),c="insert",l=o.content.getContent()[0],g()):this.deletes(o)?(c!=="delete"&&(g(),c="delete"),u+=1):o.deleted||(c!=="retain"&&(g(),c="retain"),d+=1);break;case ie:this.adds(o)?this.deletes(o)||(c!=="insert"&&(g(),c="insert"),l+=o.content.str):this.deletes(o)?(c!=="delete"&&(g(),c="delete"),u+=o.length):o.deleted||(c!=="retain"&&(g(),c="retain"),d+=o.length);break;case T:{let{key:f,value:w}=o.content;if(this.adds(o)){if(!this.deletes(o)){let C=i.get(f)??null;ne(C,w)?w!==null&&o.delete(r):(c==="retain"&&g(),ne(w,s.get(f)??null)?delete a[f]:a[f]=w);}}else if(this.deletes(o)){s.set(f,w);let C=i.get(f)??null;ne(C,w)||(c==="retain"&&g(),a[f]=C);}else if(!o.deleted){s.set(f,w);let C=a[f];C!==void 0&&(ne(C,w)?C!==null&&o.delete(r):(c==="retain"&&g(),w===null?delete a[f]:a[f]=w));}o.deleted||(c==="insert"&&g(),ve(i,o.content));break}}o=o.right;}for(g();t.length>0;){let f=t[t.length-1];if(f.retain!==void 0&&f.attributes===void 0)t.pop();else break}}),this._delta=t;}return this._delta}},hn=class n extends k{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1;}get length(){return this.doc??U(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(r=>r());}catch(r){console.error(r);}this._pending=null;}_copy(){return new n}clone(){let e=new n;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);let r=new dn(this,e,t);wt(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0);}toString(){this.doc??U();let e="",t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===ie&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc!==null?b(this.doc,r=>{let i=new Ke(null,this._start,0,new Map);for(let s=0;s<e.length;s++){let o=e[s];if(o.insert!==void 0){let c=!t&&typeof o.insert=="string"&&s===e.length-1&&i.right===null&&o.insert.slice(-1)===`
|
|
8
|
+
`?o.insert.slice(0,-1):o.insert;(typeof c!="string"||c.length>0)&&qt(r,this,i,c,o.attributes||{});}else o.retain!==void 0?mr(r,this,i,o.retain,o.attributes||{}):o.delete!==void 0&&yr(r,i,o.delete);}}):this._pending.push(()=>this.applyDelta(e));}toDelta(e,t,r){this.doc??U();let i=[],s=new Map,o=this.doc,c="",a=this._start;function l(){if(c.length>0){let u={},g=!1;s.forEach((w,C)=>{g=!0,u[C]=w;});let f={insert:c};g&&(f.attributes=u),i.push(f),c="";}}let d=()=>{for(;a!==null;){if(we(a,e)||t!==void 0&&we(a,t))switch(a.content.constructor){case ie:{let u=s.get("ychange");e!==void 0&&!we(a,e)?(u===void 0||u.user!==a.id.client||u.type!=="removed")&&(l(),s.set("ychange",r?r("removed",a.id):{type:"removed"})):t!==void 0&&!we(a,t)?(u===void 0||u.user!==a.id.client||u.type!=="added")&&(l(),s.set("ychange",r?r("added",a.id):{type:"added"})):u!==void 0&&(l(),s.delete("ychange")),c+=a.content.str;break}case se:case Se:{l();let u={insert:a.content.getContent()[0]};if(s.size>0){let g={};u.attributes=g,s.forEach((f,w)=>{g[w]=f;});}i.push(u);break}case T:we(a,e)&&(l(),ve(s,a.content));break}a=a.right;}l();};return e||t?b(o,u=>{e&&en(u,e),t&&en(u,t),d();},"cleanup"):d(),i}insert(e,t,r){if(t.length<=0)return;let i=this.doc;i!==null?b(i,s=>{let o=at(s,this,e,!r);r||(r={},o.currentAttributes.forEach((c,a)=>{r[a]=c;})),qt(s,this,o,t,r);}):this._pending.push(()=>this.insert(e,t,r));}insertEmbed(e,t,r){let i=this.doc;i!==null?b(i,s=>{let o=at(s,this,e,!r);qt(s,this,o,t,r||{});}):this._pending.push(()=>this.insertEmbed(e,t,r||{}));}delete(e,t){if(t===0)return;let r=this.doc;r!==null?b(r,i=>{yr(i,at(i,this,e,!0),t);}):this._pending.push(()=>this.delete(e,t));}format(e,t,r){if(t===0)return;let i=this.doc;i!==null?b(i,s=>{let o=at(s,this,e,!1);o.right!==null&&mr(s,this,o,t,r);}):this._pending.push(()=>this.format(e,t,r));}removeAttribute(e){this.doc!==null?b(this.doc,t=>{ut(t,this,e);}):this._pending.push(()=>this.removeAttribute(e));}setAttribute(e,t){this.doc!==null?b(this.doc,r=>{mn(r,this,e,t);}):this._pending.push(()=>this.setAttribute(e,t));}getAttribute(e){return yn(this,e)}getAttributes(){return Mr(this)}_write(e){e.writeTypeRef(qs);}};var Me=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??U();}[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===ft||t.constructor===Pe)&&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})}},Pe=class n extends k{constructor(){super(),this._prelimContent=[];}get firstChild(){let 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 n}clone(){let e=new n;return e.insert(0,this.toArray().map(t=>t instanceof k?t.clone():t)),e}get length(){return this.doc??U(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Me(this,e)}querySelector(e){e=e.toUpperCase();let r=new Me(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),Q(new Me(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){wt(this,e,new un(this,t,e));}toString(){return Ur(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},r){let i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),Be(this,s=>{i.insertBefore(s.toDOM(e,t,r),null);}),i}insert(e,t){this.doc!==null?b(this.doc,r=>{Lr(r,this,e,t);}):this._prelimContent.splice(e,0,...t);}insertAfter(e,t){if(this.doc!==null)b(this.doc,r=>{let i=e&&e instanceof k?e._item:e;ht(r,this,i,t);});else {let r=this._prelimContent,i=e===null?0:r.findIndex(s=>s===e)+1;if(i===0&&e!==null)throw le("Reference item not found");r.splice(i,0,...t);}}delete(e,t=1){this.doc!==null?b(this.doc,r=>{Vr(r,this,e,t);}):this._prelimContent.splice(e,t);}toArray(){return Dr(this)}push(e){this.insert(this.length,e);}unshift(e){this.insert(0,e);}get(e){return Or(this,e)}slice(e=0,t=this.length){return Rr(this,e,t)}forEach(e){Be(this,e);}_write(e){e.writeTypeRef(Hs);}};var ft=class n extends Pe{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map;}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r);}),this._prelimAttrs=null;}_copy(){return new n(this.nodeName)}clone(){let e=new n(this.nodeName),t=this.getAttributes();return $n(t,(r,i)=>{typeof r=="string"&&e.setAttribute(i,r);}),e.insert(0,this.toArray().map(r=>r instanceof k?r.clone():r)),e}toString(){let e=this.getAttributes(),t=[],r=[];for(let c in e)r.push(c);r.sort();let i=r.length;for(let c=0;c<i;c++){let a=r[c];t.push(a+'="'+e[a]+'"');}let s=this.nodeName.toLocaleLowerCase(),o=t.length>0?" "+t.join(" "):"";return `<${s}${o}>${super.toString()}</${s}>`}removeAttribute(e){this.doc!==null?b(this.doc,t=>{ut(t,this,e);}):this._prelimAttrs.delete(e);}setAttribute(e,t){this.doc!==null?b(this.doc,r=>{mn(r,this,e,t);}):this._prelimAttrs.set(e,t);}getAttribute(e){return yn(this,e)}hasAttribute(e){return Nr(this,e)}getAttributes(e){return e?Ns(this,e):Mr(this)}toDOM(e=document,t={},r){let i=e.createElement(this.nodeName),s=this.getAttributes();for(let o in s){let c=s[o];typeof c=="string"&&i.setAttribute(o,c);}return Be(this,o=>{i.appendChild(o.toDOM(e,t,r));}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(Js),e.writeKey(this.nodeName);}};var un=class extends be{constructor(e,t,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i);});}};var gt=class{constructor(e,t){this.id=e,this.length=t;}get deleted(){throw N()}mergeWith(e){return !1}write(e,t,r){throw N()}integrate(e,t){throw N()}},js=0,$=class extends gt{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),kr(e.doc.store,this);}write(e,t){e.writeInfo(js),e.writeLen(this.length-t);}getMissing(e,t){return null}},pt=class n{constructor(e){this.content=e;}getLength(){return 1}getContent(){return [this.content]}isCountable(){return !0}copy(){return new n(this.content)}splice(e){throw N()}mergeWith(e){return !1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content);}getRef(){return 3}};var fn=class n{constructor(e){this.len=e;}getLength(){return this.len}getContent(){return []}isCountable(){return !1}copy(){return new n(this.len)}splice(e){let t=new n(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Sr(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}};var Fs=(n,e)=>new he({guid:n,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1}),mt=class n{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;let 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 n(Fs(this.doc.guid,this.opts))}splice(e){throw N()}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}};var Se=class n{constructor(e){this.embed=e;}getLength(){return 1}getContent(){return [this.embed]}isCountable(){return !0}copy(){return new n(this.embed)}splice(e){throw N()}mergeWith(e){return !1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed);}getRef(){return 5}};var T=class n{constructor(e,t){this.key=e,this.value=t;}getLength(){return 1}getContent(){return []}isCountable(){return !1}copy(){return new n(this.key,this.value)}splice(e){throw N()}mergeWith(e){return !1}integrate(e,t){let r=t.parent;r._searchMarker=null,r._hasFormatting=!0;}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value);}getRef(){return 6}};var Ws=Oe("node_env")==="development",je=class n{constructor(e){this.arr=e,Ws&&Nt(e);}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return !0}copy(){return new n(this.arr)}splice(e){let t=new n(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){let r=this.arr.length;e.writeLen(r-t);for(let i=t;i<r;i++){let s=this.arr[i];e.writeAny(s);}}getRef(){return 8}};var ie=class n{constructor(e){this.str=e;}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return !0}copy(){return new n(this.str)}splice(e){let t=new n(this.str.slice(e));this.str=this.str.slice(0,e);let r=this.str.charCodeAt(e-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"\uFFFD",t.str="\uFFFD"+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}};var $s=0,Gs=1,qs=2,Js=3,Hs=4;var se=class n{constructor(e){this.type=e;}getLength(){return 1}getContent(){return [this.type]}isCountable(){return !0}copy(){return new n(this.type._copy())}splice(e){throw N()}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(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.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(r=>{for(;r!==null;)r.gc(e,!0),r=r.left;}),this.type._map=new Map;}write(e,t){this.type._write(e);}getRef(){return 7}};var Fr=(n,e,t)=>{let{client:r,clock:i}=e.id,s=new O(S(r,i+t),e,S(r,i+t-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(t));return e.deleted&&s.markDeleted(),e.keep&&(s.keep=!0),e.redone!==null&&(s.redone=S(e.redone.client,e.redone.clock+t)),e.right=s,s.right!==null&&(s.right.left=s),n._mergeStructs.push(s),s.parentSub!==null&&s.right===null&&s.parent._map.set(s.parentSub,s),e.length=t,s};var O=class n extends gt{constructor(e,t,r,i,s,o,c,a){super(e,a.getLength()),this.origin=r,this.left=t,this.right=i,this.rightOrigin=s,this.parent=o,this.parentSub=c,this.redone=null,this.content=a,this.info=this.content.isCountable()?2:0;}set marker(e){(this.info&8)>0!==e&&(this.info^=8);}get marker(){return (this.info&8)>0}get keep(){return (this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1);}get countable(){return (this.info&2)>0}get deleted(){return (this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4);}markDeleted(){this.info|=4;}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=V(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=V(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===_e&&this.id.client!==this.parent.client&&this.parent.clock>=V(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=hr(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===$||this.right&&this.right.constructor===$)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===n&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===n&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===_e){let r=Gt(t,this.parent);r.constructor===$?this.parent=null:this.parent=r.content.type;}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=hr(e,e.doc.store,S(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 r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;let s=new Set,o=new Set;for(;i!==null&&i!==this.right;){if(o.add(i),s.add(i),ot(this.origin,i.origin)){if(i.id.client<this.id.client)r=i,s.clear();else if(ot(this.rightOrigin,i.rightOrigin))break}else if(i.origin!==null&&o.has(Gt(e.doc.store,i.origin)))s.has(Gt(e.doc.store,i.origin))||(r=i,s.clear());else break;i=i.right;}this.left=r;}if(this.left!==null){let r=this.left.right;this.right=r,this.left.right=this;}else {let r;if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start,this.parent._start=this;this.right=r;}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),kr(e.doc.store,this),this.content.integrate(e,this),fr(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e);}else new $(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:S(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&ot(e.origin,this.lastId)&&this.right===e&&ot(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)){let t=this.parent._searchMarker;return t&&t.forEach(r=>{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.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){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),Sr(e.deleteSet,this.id.client,this.id.clock,this.length),fr(e,t,this.parentSub),this.content.delete(e);}}gc(e,t){if(!this.deleted)throw te();this.content.gc(e),t?Rs(e,this,new $(this.id,this.length)):this.content=new fn(this.length);}write(e,t){let r=t>0?S(this.id.client,this.id.clock+t-1):this.origin,i=this.rightOrigin,s=this.parentSub,o=this.content.getRef()&31|(r===null?0:128)|(i===null?0:64)|(s===null?0:32);if(e.writeInfo(o),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){let c=this.parent;if(c._item!==void 0){let a=c._item;if(a===null){let l=xs(c);e.writeParentInfo(!0),e.writeString(l);}else e.writeParentInfo(!1),e.writeLeftID(a.id);}else c.constructor===String?(e.writeParentInfo(!0),e.writeString(c)):c.constructor===_e?(e.writeParentInfo(!1),e.writeLeftID(c)):te();s!==null&&e.writeString(s);}this.content.write(e,t);}};var Wr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},$r="__ $YJS$ __";Wr[$r]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Wr[$r]=!0;var Fe=n=>Promise.reject("unimplemented method GetVoiceSign"),wn=(n,e={},t=[])=>({command:n,front_request_id:X(),data:{...e,to_user_ids:Array.isArray(t)?t:[t]}}),Gr=()=>{window?.__Realsee_Live__&&(window?.__Realsee_Live__?.dispose?.(),window.__Realsee_Live__=null);},_t=class extends M{_options={};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}keyframes=new M;_yDoc;_buildInData;constructor(e){super(),p.info("Initializing Live instance with options:",e),this._addLiveControllerEventListeners(),this._yDoc=new he({guid:X()}),this._buildInData={keyframes:this._yDoc.getMap("keyframes")},this._initializeKeyframesObservers(),this._initializeOptions(e),this._autoConnect(),this._debugSetup();}get _buildInKeyframes(){return this._buildInData.keyframes}get snapshot(){return this._buildInData.keyframes.toJSON()}_initializeKeyframesObservers=()=>{this._buildInKeyframes.observe(this._handleKeyframesChange);};_handleKeyframesChange=e=>{let{transaction:t,target:r,changes:i}=e;if(r===this._buildInKeyframes)if(t.origin.triggerUserId===this.selfInfo?.id){let s=wn("KEYFRAME_SYNC",this.snapshot,void 0);try{this._controller.sendMessage(s);}catch(o){p.error("Failed to send keyframe sync message:",o);}}else i.keys.forEach((s,o)=>{let c=s.oldValue,a=this.getFramesByKey(o),l=t.origin.frontRequestId;this.keyframes.emit(o,a,c,l);}),i.keys.size!==0&&this.emit("keyframes",this.snapshot,t.origin.frontRequestId);};getFramesByKey=e=>this.snapshot[e];sendKeyframe=(e,t)=>this.state!==1?(p.warn("Attempted to send keyframe while connection is not open"),!1):(this._yDoc.transact(()=>{this._buildInKeyframes.set(e,t);},{triggerUserId:this.selfInfo?.id,frontRequestId:""}),!0);get selfInfo(){return this._buildInData.selfInfo}get userList(){return this._buildInData.userList||[]}get roomInfo(){return this._buildInData.roomInfo}_controller=new He;_initializeOptions(e){this._options=Object.assign({initialMicroStatus:"OPEN"},e),this._options.jsBridge=this._initializeJsBridge(e),this._options.getVoiceSign=e.getVoiceSign??Fe,this._options.autoPlayConfirm=e.autoPlayConfirm,this._options.rtc=this._initializeRTC(e);}_initializeJsBridge(e){if(e.jsBridge)return e.jsBridge;if(e.useBuiltInJsBridge)return new Ys}_initializeRTC(e){if(e.rtc)return e.rtc;if(e.rtcType)return this._createBuiltInRTC(e);if(e.useBuiltInRTC)return this._createDefaultRTC(e)}_createBuiltInRTC(e){if(!e.getVoiceSign){p.error("GetVoiceSign method must be passed when using built-in RTC instances");return}switch(e.rtcType){case"RealseeVRWebViewRTC":return this._createVRWebViewRTC();case"RealseeBrowserChimeRTC":return new ue({getVoiceSign:this._options.getVoiceSign??Fe,logLevel:e.__debug__?0:1});case"RealseeBrowserRTC":return this._createBrowserRTC();default:p.error("unknown built-in RTC type");return}}_createVRWebViewRTC(){if(this._options.jsBridge)return new xe({jsBridge:this._options.jsBridge,getVoiceSign:this._options.getVoiceSign??Fe});p.error("JsBridge instance must be passed when using built-in VRWebViewRTC instances");}_createBrowserRTC(){if(!this._options.autoPlayConfirm){p.error("autoPlayConfirm method must be passed when using built-in RealseeBrowserRTC instances");return}return new Ce({getVoiceSign:this._options.getVoiceSign??Fe,autoPlayConfirm:this._options.autoPlayConfirm})}_createDefaultRTC(e){if(!e.getVoiceSign){p.error("GetVoiceSign method must be passed when using built-in RTC instances");return}if(this._options.jsBridge){if(xn&&(En||kn)||Cn)return this._createVRWebViewRTC();{let t=this._options.getVoiceSign??Fe;return e.builtInRTCType==="chime"?new ue({getVoiceSign:t}):this._createBrowserRTC()}}else {p.error("jsBridge instance must be passed when using built-in RTC instances");return}}_autoConnect(){this._options.url&&this._options.getTicket&&this.connect();}_debugSetup(){this._options.__debug__&&Object.assign(window,{$liveController:this._controller,$live:this});}_addLiveControllerEventListeners=()=>{this._controller.on("stateChange",this._handleStateChange),this._controller.on("message",this._handleMessage);};_removeLiveControllerEventListeners=()=>{this._controller.off("stateChange",this._handleStateChange),this._controller.off("message",this._handleMessage);};_handleStateChange=(e,t)=>{p.info(`State changed from ${t} to ${e}`),this.emit("stateChange",e,t);};_handleMessage=async e=>{if(p.debug("Received message:",e),typeof e=="object"){let{command:t,data:r={},frontRequestId:i,code:s,message:o,triggerUserId:c}=e;if(s==="SUCCESS")switch(t){case"SELF_USER_INFO":{let a=r;In(this.selfInfo,a,{deep:!0})||(this._buildInData.selfInfo=a,this.emit("selfInfoUpdate",this._buildInData.selfInfo,i));break}case"ROOM_INFO":{let a=r;this._buildInData.roomInfo=Object.assign({},a);let l=a.last_frame||{};this._yDoc.transact(()=>{for(let d in l)this._buildInKeyframes.set(d,l[d]);},{triggerUserId:"readyKeyframeSync",frontRequestId:i}),this.emit("readyKeyframeSync",a.last_frame||{});break}case"RTC_INFO":{p.info("RTC info updated:",r);let{voice_id:a,type:l}=r;if(this._buildInData.rtcInfo={voiceId:a,type:l},this.$RTC?.joined)p.warn("\u5DF2\u52A0\u5165\u8BED\u97F3\u623F\u95F4\uFF0C\u65E0\u9700\u91CD\u590D\u52A0\u5165\uFF01");else if(await this.$RTC?.join({voiceId:a,userId:this.selfInfo?.id||"",roomId:this.roomInfo?.info.room_code,type:l})){let u=this._options.initialMicroStatus??"OPEN";await this.toggleMicro(u==="OPEN");}else p.error("\u52A0\u5165\u8BED\u97F3\u623F\u95F4\u5931\u8D25");break}case"USER_LIST":{let a=r;this._buildInData.userList=a,this.emit("userListUpdate",this.userList,i);break}case"CUSTOM_EVENT":{let a=r;this.emit("broadcast",a,i);break}case"KEYFRAME_SYNC":{let a=r;if(c===this.selfInfo?.id)return;this._yDoc.transact(()=>{for(let l in a)this._buildInKeyframes.set(l,a[l]);},{triggerUserId:c,frontRequestId:i});break}case"BUILTIN_MSG":{let a=r;this.emit("builtinEvent",a),a.event_type==="user_change"&&this.emit("userChange",a),a.event_type==="room_change"&&this.emit("roomChange",a),a.event_type==="user_change"&&a.action==="change_micro_status"&&await this.toggleMicro(a.data.status==="OPEN"),a.event_type==="room_change"&&a.action==="close"&&await this._exit();break}case"USER_KICK_OUT":{this.emit("kickOut");break}default:p.warn("Unknown command received:",t);}else p.error("Error in message:",o),this.emit("error",e);}};_clearLiveData=()=>{this._buildInKeyframes.clear(),this._buildInData={keyframes:this._yDoc.getMap("keyframes")};};connect=async(e={})=>{if(p.info("Attempting to connect with options:",e),this._options.url=e.url??this._options.url??"",this._options.getTicket=e.getTicket??this._options.getTicket,this._options.initialMicroStatus=e.rtcMicStatus??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");let t=this.state;if(t===0||t===1)if(e.force)await this._controller.close("force close by connect").catch(console.warn);else return new Error("\u5DF2\u6709Live\u5B9E\u4F8B\u6B63\u5728\u8FDE\u63A5\u4E2D\uFF0C\u8BF7\u52FF\u91CD\u590D\u8FDE\u63A5\uFF01");this._clearLiveData();try{let r=await this._options.getTicket(),i=Sn(this._options.url,{ticket:r,force:+!!e.force});return this._controller.open(i),p.info("Connection established successfully"),!0}catch(r){return p.error("Failed to connect:",r),new Error("Failed to connect")}};_exit=async()=>{this._clearLiveData();try{await this.$RTC?.quit();}catch(e){p.warn(e);}return this.state!==1?!0:await this._controller.close()};exit=async()=>this.close();close=async()=>{await this._controller.readyClose();try{await this.$RTC?.quit();}catch(e){p.warn(e);}await this.updateStatus("room_change","close",{});};dispose=async()=>(this._removeLiveControllerEventListeners(),this._clearLiveData(),await this._controller.dispose());async updateStatus(e,t,r,i){if(this.state!==1)return !1;let s=Object.assign({event_type:e,action:t},{data:r}),o=wn("BUILTIN_MSG",s,i);try{return this._controller.sendMessage(o),!0}catch(c){return p.error(c),!1}}setSelfInfo=async e=>await this.updateStatus("user_change","change_info",e);broadcast(e,t,r){return this.state!==1?!1:new Promise((i,s)=>{let o=wn("CUSTOM_EVENT",e,t),c=o.front_request_id,a=r?setTimeout(()=>{s(new Error("RESPONSE TIMEOUT")),this.off("broadcast",l);},r):void 0,l=(d,u)=>{u===c&&(a&&clearTimeout(a),this.off("broadcast",l),i(d));};this.on("broadcast",l);try{this._controller.sendMessage(o);}catch(d){s(d);}})}toggleMicro=async e=>{if(!this.selfInfo?.permission?.control_own_micro)return !1;let t=await this.$RTC?.toggleMicro(e);return t&&await this.updateStatus("user_change","change_micro_status",{status:e?"OPEN":"CLOSE"},[]),t};forbidMicro=async(e,t)=>typeof this._options.canForbidUserMicro=="function"&&!this._options.canForbidUserMicro(t)||!this.selfInfo?.permission?.control_other_micro?!1:await this.updateStatus("user_change","change_micro_status",{status:e},t);forbidSync=async(e,t)=>typeof this._options.canForbidUserSync=="function"&&!this._options.canForbidUserSync(t)||!this.selfInfo?.permission?.control_other_sync?!1:await this.updateStatus("user_change","change_permission",{sync_frame:e},t);kick=async e=>typeof this._options.canForbidUserKick=="function"&&!this._options.canForbidUserKick(e)||!this.selfInfo?.permission?.change_other_status?!1:await this.updateStatus("user_change","change_status",{status:"KICK_OUT"},e);getSnapshotForKey(e){return this.snapshot[e]}};var qr=n=>(Gr(),new _t(n));function Zc(n){let e=createContext(null),t=qr(n),r=t.jsBridge,i=h=>D.createElement(e.Provider,{value:t},h.children),s=()=>{let h=D.useContext(e);if(!h)throw new Error("LiveProvider never found.");return h},o=()=>t,c=()=>t.$RTC,a=()=>c(),l=()=>async h=>await t.connect(h);function d(h,_,x=[]){let m=s(),v=[m,name,...x],R=()=>m.keyframes.off(h,_);return D.useEffect(()=>(m.keyframes.on(h,_),R),v),R}function u(){let h=s(),_=useCallback(async E=>{await h.connect(E);},[h]),x=useCallback(E=>{h.toggleMicro(E);},[h]),m=useCallback(async(E,G,St=0)=>{await h.broadcast(E,G,St);},[h]),v=useCallback(async()=>{await h.exit();},[h]),R=useCallback(async E=>{await h.kick(E);},[h]),z=useCallback(async(E,G=[])=>{await h.forbidMicro(E,G);},[h]),We=useCallback((E,G=[])=>{h.forbidSync(E,G);},[h]),bt=useCallback(E=>h.getFramesByKey(E),[h]),Xr=useCallback((E,G)=>{h.sendKeyframe(E,G);},[h]),Zr=useCallback(E=>{h.setSelfInfo(E);},[h]),Qr=useCallback((E,G,St,ei)=>{h.updateStatus(E,G,St,ei);},[h]);return {connect:_,broadcast:m,exit:v,kick:R,toggleMicro:x,forbidMicro:z,forbidSync:We,sendKeyframe:Xr,getFramesByKey:bt,setSelfInfo:Zr,updateStatus:Qr}}function g(h){let _=s(),[x,m]=D.useState(_.getFramesByKey(h));D.useEffect(()=>{let R=bt=>m(bt),z=h,We=R;return _.keyframes.on(z,We),()=>_.keyframes.off(z,We)},[_]);let v=D.useCallback(R=>_.sendKeyframe(h,R),[_]);return [x,v]}function f(h,_,x=[]){let m=s(),v=()=>m.off(h,_),R=[m,h,...x];return D.useEffect(()=>(m.on(h,_),v),R),v}function w(){let h=s(),[_,x]=D.useState(h.state);return D.useEffect(()=>{let m=v=>x(v);return h.on("stateChange",m),()=>h.off("stateChange",m)},[h]),_}function C(){let h=s();return {join:z=>h.$RTC.join(z),quit:()=>h.$RTC.quit(),shock:()=>h.$RTC.shock?.(),toggleMicro:z=>h.$RTC.toggleMicro(z),detectMicro:()=>h.$RTC.detectMicro()}}function Jr(h,_,x=[]){let m=s(),v=()=>m.$RTC.off(h,_),R=[m,h,...x];return D.useEffect(()=>(m.$RTC.on(h,_),v),R),v}function Hr(){let h=s(),[_,x]=D.useState(h.selfInfo||{}),m=R=>x(R);D.useEffect(()=>(h.on("selfInfoUpdate",m),()=>h.off("selfInfoUpdate",m)),[h]);let v=D.useCallback(async R=>await h.setSelfInfo(R),[h]);return [_,v]}function zr(){let h=s(),[_,x]=D.useState(h.snapshot);return D.useEffect(()=>{let m=v=>x(v);return h.on("keyframes",m),()=>h.off("keyframes",m)},[h]),_}function Yr(){let h=s(),[_,x]=D.useState(h.userList),m=v=>x(v);return D.useEffect(()=>(h.on("userListUpdate",m),()=>h.off("userListUpdate",m)),[h]),_}return {live:t,jsBridge:r,LiveProvider:i,unsafe__useLiveInstance:o,unsafe__useRTCInstance:a,useConnect:l,useKeyframe:g,useKeyframeUpdateCallback:d,useLiveAction:u,useLiveEventCallback:f,useLiveState:w,useRTCAction:C,useRTCEventCallback:Jr,useSelfInfo:Hr,useKeyframesSnapshot:zr,useUserList:Yr}}console.log(`%c${process.env.__REALSEE_LIVE_VERSION__}`,"background: #237804; color: white; padding: 2px 4px; border-radius: 4px;");
|
|
29
9
|
|
|
30
|
-
export {
|
|
10
|
+
export { Ce as BrowserRTC, ue as BrowserRTC4Chime, ri as BuiltInRTCType, pi as BuiltinActionType, gi as BuiltinEventType, fi as Command, q as CoreRTC, _t as Live, yi as LiveState, _i as MemUserStatus, mi as MicroStatus, ui as RTCJoinedInfoCodeEnum, ni as RTCType, M as Subscribe, wi as UserStatus, xe as VRWebViewRTC, vi as WebSocketCloseError, Si as WebSocketErrorType, bi as WebSocketState, Gr as _clearLiveInstanceIfNeed, qr as createLive, Zc as createLiveReact, Ro as parseLiveMsg, bn as parseWSClsErr };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@realsee/live",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "如视 Live SDK:基于如视 WebSocket 长链双工通信能力的前端封装,借助此 SDK 您可以快捷地实现具备同屏连线、实时语音的 VR 带看业务能力。",
|
|
5
5
|
"author": "BEIKE REALSEE TECHNOLOGY (HK) LIMITED",
|
|
6
6
|
"license": "SEE LICENSE IN TERMS.txt",
|
|
@@ -52,8 +52,5 @@
|
|
|
52
52
|
"amazon-chime-sdk-js": ">=3.0.0",
|
|
53
53
|
"react": "^18",
|
|
54
54
|
"trtc-js-sdk": ">=4.15.3"
|
|
55
|
-
},
|
|
56
|
-
"dependencies": {
|
|
57
|
-
"lib0": "0.2.98"
|
|
58
55
|
}
|
|
59
56
|
}
|