/*
 * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ "./src/main.js"
/*!*********************!*\
  !*** ./src/main.js ***!
  \*********************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var sfs3_api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sfs3-api */ \"./node_modules/sfs3-api/dist/sfs3-api.js\");\n\n\n// As an alternative, import specific classes:\n//import { SmartFox, SFSEvent, ... } from \"sfs3-api\";\n\nlet sfs;\n\nwindow.onload = () => {\n    connect();\n};\n\nfunction trace(str)\n{\n\tconsole.log('%c' + str, 'color: #6FBFF9');\n    \n    let p = document.createElement(\"p\");\n    p.innerHTML = str;\n    document.getElementById(\"out\").append(p);\n}\n\nfunction connect()\n{\n    // Create instance\n\tsfs = new sfs3_api__WEBPACK_IMPORTED_MODULE_0__.SmartFox();\n\t\n    // Configure\n\tsfs.config.zone = \"Playground\";\n\tsfs.config.netDebugLevel = sfs3_api__WEBPACK_IMPORTED_MODULE_0__.NetDebugLevel.PROTOCOL;\n\tsfs.logger.level = sfs3_api__WEBPACK_IMPORTED_MODULE_0__.LogLevel.DEBUG;\n\n\tsfs.addEventListener(sfs3_api__WEBPACK_IMPORTED_MODULE_0__.SFSEvent.CONNECTION, onConnection, this);\n\tsfs.addEventListener(sfs3_api__WEBPACK_IMPORTED_MODULE_0__.SFSEvent.CONNECTION_LOST, onConnectionLost, this);\n\tsfs.addEventListener(sfs3_api__WEBPACK_IMPORTED_MODULE_0__.SFSEvent.LOGIN, onLogin, this);\n\tsfs.addEventListener(sfs3_api__WEBPACK_IMPORTED_MODULE_0__.SFSEvent.LOGIN_ERROR, onLoginError, this);\n\tsfs.addEventListener(sfs3_api__WEBPACK_IMPORTED_MODULE_0__.SFSEvent.ROOM_JOIN, onRoomJoin, this);\n\tsfs.addEventListener(sfs3_api__WEBPACK_IMPORTED_MODULE_0__.SFSEvent.ROOM_JOIN_ERROR, onRoomJoinError, this);\n\n    trace(\"API version: \" + sfs.version);\n\n\tsfs.connect();\n}\n\n//----------------------------------------------------------------------------//\n\nfunction onConnection(evt)\n{\n    const success = evt[sfs3_api__WEBPACK_IMPORTED_MODULE_0__.EventParam.Success];\n\n    if (success)\n    {\n        trace(\"Connection successful\");\n\n        // Login\n        sfs.send(new sfs3_api__WEBPACK_IMPORTED_MODULE_0__.LoginRequest()); \n    }\n    else\n        trace(\"Connection failed\");\n}\n\nfunction onConnectionLost(evt)\n{\n    trace(\"Connection lost; reason is \" + evt[sfs3_api__WEBPACK_IMPORTED_MODULE_0__.EventParam.DisconnectionReason]);\n}\n\nfunction onLogin(evt)\n{\n    trace(`Logged in zone ${evt[sfs3_api__WEBPACK_IMPORTED_MODULE_0__.EventParam.ZoneName]} as ${evt[sfs3_api__WEBPACK_IMPORTED_MODULE_0__.EventParam.User]}`);\n\n    // Join room\n    sfs.send(new sfs3_api__WEBPACK_IMPORTED_MODULE_0__.JoinRoomRequest(\"Lobby\"));\n}\n\nfunction onLoginError(evt)\n{\n    trace(`Login error: ${evt[sfs3_api__WEBPACK_IMPORTED_MODULE_0__.EventParam.ErrorMessage]} (code: ${evt[sfs3_api__WEBPACK_IMPORTED_MODULE_0__.EventParam.ErrorCode]})`);\n}\n\nfunction onRoomJoin(evt)\n{\n    trace(`Room joined succesfully: ${evt[sfs3_api__WEBPACK_IMPORTED_MODULE_0__.EventParam.Room]}`);\n}\n\nfunction onRoomJoinError(evt)\n{\n    trace(`Room join error: ${evt[sfs3_api__WEBPACK_IMPORTED_MODULE_0__.EventParam.ErrorMessage]} (code: ${evt[sfs3_api__WEBPACK_IMPORTED_MODULE_0__.EventParam.ErrorCode]})`);\n}\n\n//# sourceURL=webpack:///./src/main.js?\n}");

/***/ },

/***/ "./node_modules/sfs3-api/dist/sfs3-api.js"
/*!************************************************!*\
  !*** ./node_modules/sfs3-api/dist/sfs3-api.js ***!
  \************************************************/
(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {

eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   AddBuddyRequest: () => (/* binding */ AddBuddyRequest),\n/* harmony export */   AdminMessageRequest: () => (/* binding */ AdminMessageRequest),\n/* harmony export */   BanMode: () => (/* binding */ zs),\n/* harmony export */   BanUserRequest: () => (/* binding */ BanUserRequest),\n/* harmony export */   BanUsersFromRoomRequest: () => (/* binding */ BanUsersFromRoomRequest),\n/* harmony export */   BlockBuddyRequest: () => (/* binding */ BlockBuddyRequest),\n/* harmony export */   BoolMatch: () => (/* binding */ BoolMatch),\n/* harmony export */   BuddyMessageRequest: () => (/* binding */ BuddyMessageRequest),\n/* harmony export */   ChangeRoomCapacityRequest: () => (/* binding */ ChangeRoomCapacityRequest),\n/* harmony export */   ChangeRoomNameRequest: () => (/* binding */ ChangeRoomNameRequest),\n/* harmony export */   ChangeRoomPasswordStateRequest: () => (/* binding */ ChangeRoomPasswordStateRequest),\n/* harmony export */   ClientDisconnectionReason: () => (/* binding */ Ms),\n/* harmony export */   ClusterEvent: () => (/* binding */ r),\n/* harmony export */   ClusterRoomSettings: () => (/* binding */ ClusterRoomSettings),\n/* harmony export */   ClusterTarget: () => (/* binding */ ClusterTarget),\n/* harmony export */   ConfigData: () => (/* binding */ ConfigData),\n/* harmony export */   CreateRoomRequest: () => (/* binding */ CreateRoomRequest),\n/* harmony export */   CreateSFSGameRequest: () => (/* binding */ CreateSFSGameRequest),\n/* harmony export */   EventParam: () => (/* binding */ e),\n/* harmony export */   ExtensionAsyncRequest: () => (/* binding */ ExtensionAsyncRequest),\n/* harmony export */   ExtensionRequest: () => (/* binding */ ExtensionRequest),\n/* harmony export */   FindRoomsRequest: () => (/* binding */ FindRoomsRequest),\n/* harmony export */   FindUsersRequest: () => (/* binding */ FindUsersRequest),\n/* harmony export */   GoOnlineRequest: () => (/* binding */ GoOnlineRequest),\n/* harmony export */   InitAudioRequest: () => (/* binding */ InitAudioRequest),\n/* harmony export */   InitBuddyListRequest: () => (/* binding */ InitBuddyListRequest),\n/* harmony export */   InvitationReply: () => (/* binding */ qs),\n/* harmony export */   InvitationReplyRequest: () => (/* binding */ InvitationReplyRequest),\n/* harmony export */   InviteUsersRequest: () => (/* binding */ InviteUsersRequest),\n/* harmony export */   JoinRoomInvitationRequest: () => (/* binding */ JoinRoomInvitationRequest),\n/* harmony export */   JoinRoomRequest: () => (/* binding */ JoinRoomRequest),\n/* harmony export */   KickUserRequest: () => (/* binding */ KickUserRequest),\n/* harmony export */   LeaveRoomRequest: () => (/* binding */ LeaveRoomRequest),\n/* harmony export */   LevelMode: () => (/* binding */ Ks),\n/* harmony export */   LogLevel: () => (/* binding */ vs),\n/* harmony export */   LogicOperator: () => (/* binding */ LogicOperator),\n/* harmony export */   LoginRequest: () => (/* binding */ LoginRequest),\n/* harmony export */   LogoutRequest: () => (/* binding */ LogoutRequest),\n/* harmony export */   MMOItemVariable: () => (/* binding */ MMOItemVariable),\n/* harmony export */   MMORoomSettings: () => (/* binding */ MMORoomSettings),\n/* harmony export */   MapLimits: () => (/* binding */ MapLimits),\n/* harmony export */   MatchExpression: () => (/* binding */ MatchExpression),\n/* harmony export */   MessageRecipientMode: () => (/* binding */ MessageRecipientMode),\n/* harmony export */   ModeratorMessageRequest: () => (/* binding */ ModeratorMessageRequest),\n/* harmony export */   NetDebugLevel: () => (/* binding */ Ns),\n/* harmony export */   NumberMatch: () => (/* binding */ NumberMatch),\n/* harmony export */   ObjectMessageRequest: () => (/* binding */ ObjectMessageRequest),\n/* harmony export */   PasswordUtil: () => (/* binding */ PasswordUtil),\n/* harmony export */   PlayerToSpectatorRequest: () => (/* binding */ PlayerToSpectatorRequest),\n/* harmony export */   PrivateMessageRequest: () => (/* binding */ PrivateMessageRequest),\n/* harmony export */   PublicMessageRequest: () => (/* binding */ PublicMessageRequest),\n/* harmony export */   QuickJoinGameRequest: () => (/* binding */ QuickJoinGameRequest),\n/* harmony export */   QuickJoinOrCreateRoomRequest: () => (/* binding */ QuickJoinOrCreateRoomRequest),\n/* harmony export */   RemoveBuddyRequest: () => (/* binding */ RemoveBuddyRequest),\n/* harmony export */   ReservedBuddyVariables: () => (/* binding */ ks),\n/* harmony export */   ReservedRoomVariables: () => (/* binding */ Ys),\n/* harmony export */   RoomEvents: () => (/* binding */ RoomEvents),\n/* harmony export */   RoomExtension: () => (/* binding */ RoomExtension),\n/* harmony export */   RoomPermissions: () => (/* binding */ RoomPermissions),\n/* harmony export */   RoomProperties: () => (/* binding */ Ws),\n/* harmony export */   RoomSettings: () => (/* binding */ RoomSettings),\n/* harmony export */   SFSArray: () => (/* binding */ SFSArray),\n/* harmony export */   SFSAudioEvent: () => (/* binding */ i),\n/* harmony export */   SFSBuddyEvent: () => (/* binding */ s),\n/* harmony export */   SFSBuddyVariable: () => (/* binding */ SFSBuddyVariable),\n/* harmony export */   SFSDataType: () => (/* binding */ Us),\n/* harmony export */   SFSErrorCodes: () => (/* binding */ SFSErrorCodes),\n/* harmony export */   SFSEvent: () => (/* binding */ t),\n/* harmony export */   SFSGameSettings: () => (/* binding */ SFSGameSettings),\n/* harmony export */   SFSObject: () => (/* binding */ SFSObject),\n/* harmony export */   SFSRoom: () => (/* binding */ SFSRoom),\n/* harmony export */   SFSRoomVariable: () => (/* binding */ SFSRoomVariable),\n/* harmony export */   SFSUserVariable: () => (/* binding */ SFSUserVariable),\n/* harmony export */   SFSVector2: () => (/* binding */ SFSVector2),\n/* harmony export */   SFSVector3: () => (/* binding */ SFSVector3),\n/* harmony export */   SampleRate: () => (/* binding */ Vs),\n/* harmony export */   SetBuddyVariablesRequest: () => (/* binding */ SetBuddyVariablesRequest),\n/* harmony export */   SetRoomVariablesRequest: () => (/* binding */ SetRoomVariablesRequest),\n/* harmony export */   SetUserPositionRequest: () => (/* binding */ SetUserPositionRequest),\n/* harmony export */   SetUserVariablesRequest: () => (/* binding */ SetUserVariablesRequest),\n/* harmony export */   SmartFox: () => (/* binding */ SmartFox),\n/* harmony export */   SpectatorToPlayerRequest: () => (/* binding */ SpectatorToPlayerRequest),\n/* harmony export */   StartAudioStreamRequest: () => (/* binding */ StartAudioStreamRequest),\n/* harmony export */   StopAudioStreamRequest: () => (/* binding */ StopAudioStreamRequest),\n/* harmony export */   StringMatch: () => (/* binding */ StringMatch),\n/* harmony export */   SubscribeRoomGroupRequest: () => (/* binding */ SubscribeRoomGroupRequest),\n/* harmony export */   TimeUnit: () => (/* binding */ Hs),\n/* harmony export */   ToggleMuteAudioStreamRequest: () => (/* binding */ ToggleMuteAudioStreamRequest),\n/* harmony export */   UnbanUsersFromRoomRequest: () => (/* binding */ UnbanUsersFromRoomRequest),\n/* harmony export */   UnsubscribeRoomGroupRequest: () => (/* binding */ UnsubscribeRoomGroupRequest),\n/* harmony export */   UserPrivileges: () => (/* binding */ xs),\n/* harmony export */   UserProperties: () => (/* binding */ Qs),\n/* harmony export */   VariableType: () => (/* binding */ Bs),\n/* harmony export */   Vec3D: () => (/* binding */ Vec3D)\n/* harmony export */ });\n/*! For license information please see sfs3-api.js.LICENSE.txt */\nclass EventDispatcher{constructor(){this._listenersByEvent={},Object.seal(this)}addEventListener(e,t,s){this._listenersByEvent[e]||(this._listenersByEvent[e]=[]),this._listenersByEvent[e].push({callback:t,scope:s})}removeEventListener(e,t){const s=this._listenersByEvent[e];if(s)for(let e=0;e<s.length;e++)if(s[e].callback===t){s.splice(e,1);break}}dispatchEvent(e,t){const s=this._listenersByEvent[e];if(s)for(let e of s)e.callback.call(e.scope,t)}removeAllEventListeners(){this._listenersByEvent={}}}const e=Object.freeze({Success:\"success\",ExtParams:\"extParams\",Cmd:\"cmd\",Data:\"data\",ErrorMessage:\"errorMessage\",ErrorCode:\"errorCode\",DisconnectionReason:\"disconnectionReason\",Room:\"room\",User:\"user\",UserList:\"userList\",Buddy:\"buddy\",IsItMe:\"isItMe\",PlayerId:\"playerId\",GroupId:\"groupId\",UserCount:\"userCount\",SpecCount:\"specCount\",LagValue:\"lagValue\",NewRooms:\"newRooms\",ChangedVars:\"changedVars\",ZoneName:\"zoneName\",RoomList:\"roomList\",OldName:\"oldName\",Sender:\"sender\",Message:\"message\",Invitation:\"invitation\",Invitee:\"invitee\",Reply:\"reply\",BuddyList:\"buddyList\",MyBuddyVars:\"myBuddyVars\",AddedItems:\"addedItems\",RemovedItems:\"removedItems\",RemovedUsers:\"removedUsers\",AddedUsers:\"addedUsers\",MMOItem:\"mmoItem\",ClusterConfigData:\"clusterConfigData\",ClusterUserName:\"clusterUserName\",ClusterPassword:\"clusterPassword\",MyAudioStream:\"myAudioStream\",AudioStream:\"audioStream\",AudioStreams:\"audioStreams\"}),t=Object.freeze({CONNECTION:\"connection\",CONNECTION_LOST:\"connectionLost\",CONNECTION_RETRY:\"connectionRetry\",CONNECTION_RESUME:\"connectionResume\",LOGIN:\"login\",LOGIN_ERROR:\"loginError\",LOGOUT:\"logout\",ROOM_ADD:\"roomAdd\",ROOM_CREATION_ERROR:\"roomCreationError\",ROOM_REMOVE:\"roomRemove\",ROOM_JOIN:\"roomJoin\",ROOM_JOIN_ERROR:\"roomJoinError\",USER_ENTER_ROOM:\"userEnterRoom\",USER_EXIT_ROOM:\"userExitRoom\",USER_COUNT_CHANGE:\"userCountChange\",PROXIMITY_LIST_UPDATE:\"proximityListUpdate\",PLAYER_TO_SPECTATOR:\"playerToSpectator\",PLAYER_TO_SPECTATOR_ERROR:\"playerToSpectatorError\",SPECTATOR_TO_PLAYER:\"spectatorToPlayer\",SPECTATOR_TO_PLAYER_ERROR:\"spectatorToPlayerError\",ROOM_NAME_CHANGE:\"roomNameChange\",ROOM_NAME_CHANGE_ERROR:\"roomNameChangeError\",ROOM_PASSWORD_STATE_CHANGE:\"roomPasswordStateChange\",ROOM_PASSWORD_STATE_CHANGE_ERROR:\"roomPasswordStateChangeError\",ROOM_CAPACITY_CHANGE:\"roomCapacityChange\",ROOM_CAPACITY_CHANGE_ERROR:\"roomCapacityChangeError\",PUBLIC_MESSAGE:\"publicMessage\",PRIVATE_MESSAGE:\"privateMessage\",OBJECT_MESSAGE:\"objectMessage\",MODERATOR_MESSAGE:\"moderatorMessage\",ADMIN_MESSAGE:\"adminMessage\",EXTENSION_RESPONSE:\"extensionResponse\",ROOM_VARIABLES_UPDATE:\"roomVariablesUpdate\",USER_VARIABLES_UPDATE:\"userVariablesUpdate\",MMOITEM_VARIABLES_UPDATE:\"mmoItemVariablesUpdate\",ROOM_GROUP_SUBSCRIBE:\"roomGroupSubscribe\",ROOM_GROUP_SUBSCRIBE_ERROR:\"roomGroupSubscribeError\",ROOM_GROUP_UNSUBSCRIBE:\"roomGroupUnsubscribe\",ROOM_GROUP_UNSUBSCRIBE_ERROR:\"roomGroupUnsubscribeError\",ROOM_FIND_RESULT:\"roomFindResult\",USER_FIND_RESULT:\"userFindResult\",INVITATION:\"invitation\",INVITATION_REPLY:\"invitationReply\",INVITATION_REPLY_ERROR:\"invitationReplyError\",PING_PONG:\"pingPong\"}),s=Object.freeze({BUDDY_LIST_INIT:\"buddyListInit\",BUDDY_ADD:\"buddyAdd\",BUDDY_REMOVE:\"buddyRemove\",BUDDY_BLOCK:\"buddyBlock\",BUDDY_ERROR:\"buddyError\",BUDDY_ONLINE_STATE_CHANGE:\"buddyOnlineStateChange\",BUDDY_VARIABLES_UPDATE:\"buddyVariablesUpdate\",BUDDY_MESSAGE:\"buddyMessage\"}),i=Object.freeze({INIT:\"init\",STREAM_START:\"streamStart\",STREAM_STOP:\"streamStop\",STREAM_ADD:\"streamAdd\",STREAM_REMOVE:\"streamRemove\",TOGGLE_MUTE:\"toggleMute\",ERROR:\"audioError\"}),r=Object.freeze({CONNECTION_REQUIRED:\"connectionRequired\",LOAD_BALANCER_ERROR:\"loadBalancerError\"});class Exceptions_SFSError extends Error{constructor(e,t=void 0){super(e,{cause:t}),this.name=\"SFSError\"}}class SFSValidationError extends Exceptions_SFSError{constructor(e,t=[]){super(e),this.name=\"SFSValidationError\",this.errors=t,Object.setPrototypeOf(this,SFSValidationError.prototype)}}class SFSTypeError extends Exceptions_SFSError{constructor(e){super(e),this.name=\"SFSTypeError\"}}var n=function(e,t,s){this._byteOffset=t||0,e instanceof ArrayBuffer?this.buffer=e:\"object\"==typeof e?(this.dataView=e,t&&(this._byteOffset+=t)):this.buffer=new ArrayBuffer(e||1),this.position=0,this.endianness=s??n.LITTLE_ENDIAN};n.prototype={},void 0===Uint8Array.prototype.BYTES_PER_ELEMENT&&(Uint8Array.prototype.BYTES_PER_ELEMENT=Uint8Array.BYTES_PER_ELEMENT,Int8Array.prototype.BYTES_PER_ELEMENT=Int8Array.BYTES_PER_ELEMENT,Uint8ClampedArray.prototype.BYTES_PER_ELEMENT=Uint8ClampedArray.BYTES_PER_ELEMENT,Uint16Array.prototype.BYTES_PER_ELEMENT=Uint16Array.BYTES_PER_ELEMENT,Int16Array.prototype.BYTES_PER_ELEMENT=Int16Array.BYTES_PER_ELEMENT,Uint32Array.prototype.BYTES_PER_ELEMENT=Uint32Array.BYTES_PER_ELEMENT,Int32Array.prototype.BYTES_PER_ELEMENT=Int32Array.BYTES_PER_ELEMENT,Float64Array.prototype.BYTES_PER_ELEMENT=Float64Array.BYTES_PER_ELEMENT),n.prototype.save=function(e){var t=new Blob(this.buffer),s=window.webkitURL||window.URL;if(!s||!s.createObjectURL)throw\"DataStream.save: Can't create object URL.\";var i=s.createObjectURL(t),r=document.createElement(\"a\");r.setAttribute(\"href\",i),r.setAttribute(\"download\",e),r.click(),s.revokeObjectURL(i)},n.BIG_ENDIAN=!1,n.LITTLE_ENDIAN=!0,n.prototype._dynamicSize=!0,Object.defineProperty(n.prototype,\"dynamicSize\",{get:function(){return this._dynamicSize},set:function(e){e||this._trimAlloc(),this._dynamicSize=e}}),n.prototype._byteLength=0,Object.defineProperty(n.prototype,\"byteLength\",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(n.prototype,\"buffer\",{get:function(){return this._trimAlloc(),this._buffer},set:function(e){this._buffer=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(n.prototype,\"byteOffset\",{get:function(){return this._byteOffset},set:function(e){this._byteOffset=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(n.prototype,\"dataView\",{get:function(){return this._dataView},set:function(e){this._byteOffset=e.byteOffset,this._buffer=e.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+e.byteLength}}),n.prototype._realloc=function(e){if(this._dynamicSize){var t=this._byteOffset+this.position+e,s=this._buffer.byteLength;if(t<=s)t>this._byteLength&&(this._byteLength=t);else{for(s<1&&(s=1);t>s;)s*=2;var i=new ArrayBuffer(s),r=new Uint8Array(this._buffer);new Uint8Array(i,0,r.length).set(r),this.buffer=i,this._byteLength=t}}},n.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var e=new ArrayBuffer(this._byteLength),t=new Uint8Array(e),s=new Uint8Array(this._buffer,0,t.length);t.set(s),this.buffer=e}},n.prototype.seek=function(e){var t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t},n.prototype.isEof=function(){return this.position>=this.byteLength},n.prototype.mapInt32Array=function(e,t){this._realloc(4*e);var s=new Int32Array(this._buffer,this.byteOffset+this.position,e);return n.arrayToNative(s,t??this.endianness),this.position+=4*e,s},n.prototype.mapInt16Array=function(e,t){this._realloc(2*e);var s=new Int16Array(this._buffer,this.byteOffset+this.position,e);return n.arrayToNative(s,t??this.endianness),this.position+=2*e,s},n.prototype.mapInt8Array=function(e){this._realloc(1*e);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=1*e,t},n.prototype.mapUint32Array=function(e,t){this._realloc(4*e);var s=new Uint32Array(this._buffer,this.byteOffset+this.position,e);return n.arrayToNative(s,t??this.endianness),this.position+=4*e,s},n.prototype.mapUint16Array=function(e,t){this._realloc(2*e);var s=new Uint16Array(this._buffer,this.byteOffset+this.position,e);return n.arrayToNative(s,t??this.endianness),this.position+=2*e,s},n.prototype.mapUint8Array=function(e){this._realloc(1*e);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=1*e,t},n.prototype.mapFloat64Array=function(e,t){this._realloc(8*e);var s=new Float64Array(this._buffer,this.byteOffset+this.position,e);return n.arrayToNative(s,t??this.endianness),this.position+=8*e,s},n.prototype.mapFloat32Array=function(e,t){this._realloc(4*e);var s=new Float32Array(this._buffer,this.byteOffset+this.position,e);return n.arrayToNative(s,t??this.endianness),this.position+=4*e,s},n.prototype.readInt32Array=function(e,t){e=e??this.byteLength-this.position/4;var s=new Int32Array(e);return n.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,e*s.BYTES_PER_ELEMENT),n.arrayToNative(s,t??this.endianness),this.position+=s.byteLength,s},n.prototype.readInt16Array=function(e,t){e=e??this.byteLength-this.position/2;var s=new Int16Array(e);return n.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,e*s.BYTES_PER_ELEMENT),n.arrayToNative(s,t??this.endianness),this.position+=s.byteLength,s},n.prototype.readInt8Array=function(e){e=e??this.byteLength-this.position;var t=new Int8Array(e);return n.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t},n.prototype.readUint32Array=function(e,t){e=e??this.byteLength-this.position/4;var s=new Uint32Array(e);return n.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,e*s.BYTES_PER_ELEMENT),n.arrayToNative(s,t??this.endianness),this.position+=s.byteLength,s},n.prototype.readUint16Array=function(e,t){e=e??this.byteLength-this.position/2;var s=new Uint16Array(e);return n.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,e*s.BYTES_PER_ELEMENT),n.arrayToNative(s,t??this.endianness),this.position+=s.byteLength,s},n.prototype.readUint8Array=function(e){e=e??this.byteLength-this.position;var t=new Uint8Array(e);return n.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t},n.prototype.readFloat64Array=function(e,t){e=e??this.byteLength-this.position/8;var s=new Float64Array(e);return n.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,e*s.BYTES_PER_ELEMENT),n.arrayToNative(s,t??this.endianness),this.position+=s.byteLength,s},n.prototype.readFloat32Array=function(e,t){e=e??this.byteLength-this.position/4;var s=new Float32Array(e);return n.memcpy(s.buffer,0,this.buffer,this.byteOffset+this.position,e*s.BYTES_PER_ELEMENT),n.arrayToNative(s,t??this.endianness),this.position+=s.byteLength,s},n.prototype.writeInt32Array=function(e,t){if(this._realloc(4*e.length),e instanceof Int32Array&&(this.byteOffset+this.position)%e.BYTES_PER_ELEMENT==0)n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,e.byteOffset,e.byteLength),this.mapInt32Array(e.length,t);else for(var s=0;s<e.length;s++)this.writeInt32(e[s],t)},n.prototype.writeInt16Array=function(e,t){if(this._realloc(2*e.length),e instanceof Int16Array&&(this.byteOffset+this.position)%e.BYTES_PER_ELEMENT==0)n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,e.byteOffset,e.byteLength),this.mapInt16Array(e.length,t);else for(var s=0;s<e.length;s++)this.writeInt16(e[s],t)},n.prototype.writeInt8Array=function(e){if(this._realloc(1*e.length),e instanceof Int8Array&&(this.byteOffset+this.position)%e.BYTES_PER_ELEMENT==0)n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,e.byteOffset,e.byteLength),this.mapInt8Array(e.length);else for(var t=0;t<e.length;t++)this.writeInt8(e[t])},n.prototype.writeUint32Array=function(e,t){if(this._realloc(4*e.length),e instanceof Uint32Array&&(this.byteOffset+this.position)%e.BYTES_PER_ELEMENT==0)n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,e.byteOffset,e.byteLength),this.mapUint32Array(e.length,t);else for(var s=0;s<e.length;s++)this.writeUint32(e[s],t)},n.prototype.writeUint16Array=function(e,t){if(this._realloc(2*e.length),e instanceof Uint16Array&&(this.byteOffset+this.position)%e.BYTES_PER_ELEMENT==0)n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,e.byteOffset,e.byteLength),this.mapUint16Array(e.length,t);else for(var s=0;s<e.length;s++)this.writeUint16(e[s],t)},n.prototype.writeUint8Array=function(e){if(this._realloc(1*e.length),e instanceof Uint8Array&&(this.byteOffset+this.position)%e.BYTES_PER_ELEMENT==0)n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,e.byteOffset,e.byteLength),this.mapUint8Array(e.length);else for(var t=0;t<e.length;t++)this.writeUint8(e[t])},n.prototype.writeFloat64Array=function(e,t){if(this._realloc(8*e.length),e instanceof Float64Array&&(this.byteOffset+this.position)%e.BYTES_PER_ELEMENT==0)n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,e.byteOffset,e.byteLength),this.mapFloat64Array(e.length,t);else for(var s=0;s<e.length;s++)this.writeFloat64(e[s],t)},n.prototype.writeFloat32Array=function(e,t){if(this._realloc(4*e.length),e instanceof Float32Array&&(this.byteOffset+this.position)%e.BYTES_PER_ELEMENT==0)n.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,e.byteOffset,e.byteLength),this.mapFloat32Array(e.length,t);else for(var s=0;s<e.length;s++)this.writeFloat32(e[s],t)},n.prototype.readInt32=function(e){var t=this._dataView.getInt32(this.position,e??this.endianness);return this.position+=4,t},n.prototype.readInt16=function(e){var t=this._dataView.getInt16(this.position,e??this.endianness);return this.position+=2,t},n.prototype.readInt8=function(){var e=this._dataView.getInt8(this.position);return this.position+=1,e},n.prototype.readUint32=function(e){var t=this._dataView.getUint32(this.position,e??this.endianness);return this.position+=4,t},n.prototype.readUint16=function(e){var t=this._dataView.getUint16(this.position,e??this.endianness);return this.position+=2,t},n.prototype.readUint8=function(){var e=this._dataView.getUint8(this.position);return this.position+=1,e},n.prototype.readFloat32=function(e){var t=this._dataView.getFloat32(this.position,e??this.endianness);return this.position+=4,t},n.prototype.readFloat64=function(e){var t=this._dataView.getFloat64(this.position,e??this.endianness);return this.position+=8,t},n.prototype.writeInt32=function(e,t){this._realloc(4),this._dataView.setInt32(this.position,e,t??this.endianness),this.position+=4},n.prototype.writeInt16=function(e,t){this._realloc(2),this._dataView.setInt16(this.position,e,t??this.endianness),this.position+=2},n.prototype.writeInt8=function(e){this._realloc(1),this._dataView.setInt8(this.position,e),this.position+=1},n.prototype.writeUint32=function(e,t){this._realloc(4),this._dataView.setUint32(this.position,e,t??this.endianness),this.position+=4},n.prototype.writeUint16=function(e,t){this._realloc(2),this._dataView.setUint16(this.position,e,t??this.endianness),this.position+=2},n.prototype.writeUint8=function(e){this._realloc(1),this._dataView.setUint8(this.position,e),this.position+=1},n.prototype.writeFloat32=function(e,t){this._realloc(4),this._dataView.setFloat32(this.position,e,t??this.endianness),this.position+=4},n.prototype.writeFloat64=function(e,t){this._realloc(8),this._dataView.setFloat64(this.position,e,t??this.endianness),this.position+=8},n.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,n.memcpy=function(e,t,s,i,r){var n=new Uint8Array(e,t,r),a=new Uint8Array(s,i,r);n.set(a)},n.arrayToNative=function(e,t){return t==this.endianness?e:this.flipArrayEndianness(e)},n.nativeToEndian=function(e,t){return this.endianness==t?e:this.flipArrayEndianness(e)},n.flipArrayEndianness=function(e){for(var t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=0;s<e.byteLength;s+=e.BYTES_PER_ELEMENT)for(var i=s+e.BYTES_PER_ELEMENT-1,r=s;i>r;i--,r++){var n=t[r];t[r]=t[i],t[i]=n}return e},n.createStringFromArray=function(e){for(var t=[],s=0;s<e.length;s+=32768)t.push(String.fromCharCode.apply(null,e.subarray(s,s+32768)));return t.join(\"\")},n.prototype.failurePosition=0,n.prototype.readStruct=function(e){for(var t,s,i={},r=this.position,n=0;n<e.length;n+=2){if(t=e[n+1],null==(s=this.readType(t,i)))return 0==this.failurePosition&&(this.failurePosition=this.position),this.position=r,null;i[e[n]]=s}return i},n.prototype.readUCS2String=function(e,t){return n.createStringFromArray(this.readUint16Array(e,t))},n.prototype.writeUCS2String=function(e,t,s){null==s&&(s=e.length);for(var i=0;i<e.length&&i<s;i++)this.writeUint16(e.charCodeAt(i),t);for(;i<s;i++)this.writeUint16(0)},n.prototype.readString=function(e,t){return null==t||\"ASCII\"==t?n.createStringFromArray(this.mapUint8Array(e??this.byteLength-this.position)):new TextDecoder(t).decode(this.mapUint8Array(e))},n.prototype.writeString=function(e,t,s){if(null==t||\"ASCII\"==t)if(null!=s){var i=0,r=Math.min(e.length,s);for(i=0;i<r;i++)this.writeUint8(e.charCodeAt(i));for(;i<s;i++)this.writeUint8(0)}else for(i=0;i<e.length;i++)this.writeUint8(e.charCodeAt(i));else this.writeUint8Array(new TextEncoder(t).encode(e.substring(0,s)))},n.prototype.readCString=function(e){var t=this.byteLength-this.position,s=new Uint8Array(this._buffer,this._byteOffset+this.position),i=t;null!=e&&(i=Math.min(e,t));for(var r=0;r<i&&0!=s[r];r++);var a=n.createStringFromArray(this.mapUint8Array(r));return null!=e?this.position+=i-r:r!=t&&(this.position+=1),a},n.prototype.writeCString=function(e,t){if(null!=t){var s=0,i=Math.min(e.length,t);for(s=0;s<i;s++)this.writeUint8(e.charCodeAt(s));for(;s<t;s++)this.writeUint8(0)}else{for(s=0;s<e.length;s++)this.writeUint8(e.charCodeAt(s));this.writeUint8(0)}},n.prototype.readType=function(e,t){if(\"function\"==typeof e)return e(this,t);if(!(\"object\"!=typeof e||e instanceof Array))return e.get(this,t);if(e instanceof Array&&3!=e.length)return this.readStruct(e,t);var s=null,i=null,r=\"ASCII\",a=this.position;if(\"string\"==typeof e&&/:/.test(e)){var o=e.split(\":\");e=o[0],i=null!=t[h=o[1]]?parseInt(t[h]):parseInt(o[1])}if(\"string\"==typeof e&&/,/.test(e)){o=e.split(\",\");e=o[0],r=parseInt(o[1])}switch(e){case\"uint8\":s=this.readUint8();break;case\"int8\":s=this.readInt8();break;case\"uint16\":s=this.readUint16(this.endianness);break;case\"int16\":s=this.readInt16(this.endianness);break;case\"uint32\":s=this.readUint32(this.endianness);break;case\"int32\":s=this.readInt32(this.endianness);break;case\"float32\":s=this.readFloat32(this.endianness);break;case\"float64\":s=this.readFloat64(this.endianness);break;case\"uint16be\":s=this.readUint16(n.BIG_ENDIAN);break;case\"int16be\":s=this.readInt16(n.BIG_ENDIAN);break;case\"uint32be\":s=this.readUint32(n.BIG_ENDIAN);break;case\"int32be\":s=this.readInt32(n.BIG_ENDIAN);break;case\"float32be\":s=this.readFloat32(n.BIG_ENDIAN);break;case\"float64be\":s=this.readFloat64(n.BIG_ENDIAN);break;case\"uint16le\":s=this.readUint16(n.LITTLE_ENDIAN);break;case\"int16le\":s=this.readInt16(n.LITTLE_ENDIAN);break;case\"uint32le\":s=this.readUint32(n.LITTLE_ENDIAN);break;case\"int32le\":s=this.readInt32(n.LITTLE_ENDIAN);break;case\"float32le\":s=this.readFloat32(n.LITTLE_ENDIAN);break;case\"float64le\":s=this.readFloat64(n.LITTLE_ENDIAN);break;case\"cstring\":s=this.readCString(i);break;case\"string\":s=this.readString(i,r);break;case\"u16string\":s=this.readUCS2String(i,this.endianness);break;case\"u16stringle\":s=this.readUCS2String(i,n.LITTLE_ENDIAN);break;case\"u16stringbe\":s=this.readUCS2String(i,n.BIG_ENDIAN);break;default:if(3==e.length){var h,l=e[1],u=0;if(u=\"function\"==typeof(h=e[2])?h(t,this,e):\"string\"==typeof h&&null!=t[h]?parseInt(t[h]):parseInt(h),\"string\"==typeof l){var _=l.replace(/(le|be)$/,\"\"),c=null;switch(/le$/.test(l)?c=n.LITTLE_ENDIAN:/be$/.test(l)&&(c=n.BIG_ENDIAN),\"*\"==h&&(u=null),_){case\"uint8\":s=this.readUint8Array(u);break;case\"uint16\":s=this.readUint16Array(u,c);break;case\"uint32\":s=this.readUint32Array(u,c);break;case\"int8\":s=this.readInt8Array(u);break;case\"int16\":s=this.readInt16Array(u,c);break;case\"int32\":s=this.readInt32Array(u,c);break;case\"float32\":s=this.readFloat32Array(u,c);break;case\"float64\":s=this.readFloat64Array(u,c);break;case\"cstring\":case\"utf16string\":case\"string\":if(null==u)for(s=[];!this.isEof();){if(null==(S=this.readType(l,t)))break;s.push(S)}else{s=new Array(u);for(var d=0;d<u;d++)s[d]=this.readType(l,t)}}}else if(\"*\"==h)for(s=[],this.buffer;;){var m=this.position;try{var g=this.readType(l,t);if(null==g){this.position=m;break}s.push(g)}catch(e){this.position=m;break}}else{s=new Array(u);for(d=0;d<u;d++){var S;if(null==(S=this.readType(l,t)))return null;s[d]=S}}break}}return null!=i&&(this.position=a+i),s},n.prototype.writeStruct=function(e,t){for(var s=0;s<e.length;s+=2){var i=e[s+1];this.writeType(i,t[e[s]],t)}},n.prototype.writeType=function(e,t,s){if(\"function\"==typeof e)return e(this,t);if(\"object\"==typeof e&&!(e instanceof Array))return e.set(this,t,s);var i=null,r=\"ASCII\",a=this.position;if(\"string\"==typeof e&&/:/.test(e)){var o=e.split(\":\");e=o[0],i=parseInt(o[1])}if(\"string\"==typeof e&&/,/.test(e)){o=e.split(\",\");e=o[0],r=parseInt(o[1])}switch(e){case\"uint8\":this.writeUint8(t);break;case\"int8\":this.writeInt8(t);break;case\"uint16\":this.writeUint16(t,this.endianness);break;case\"int16\":this.writeInt16(t,this.endianness);break;case\"uint32\":this.writeUint32(t,this.endianness);break;case\"int32\":this.writeInt32(t,this.endianness);break;case\"float32\":this.writeFloat32(t,this.endianness);break;case\"float64\":this.writeFloat64(t,this.endianness);break;case\"uint16be\":this.writeUint16(t,n.BIG_ENDIAN);break;case\"int16be\":this.writeInt16(t,n.BIG_ENDIAN);break;case\"uint32be\":this.writeUint32(t,n.BIG_ENDIAN);break;case\"int32be\":this.writeInt32(t,n.BIG_ENDIAN);break;case\"float32be\":this.writeFloat32(t,n.BIG_ENDIAN);break;case\"float64be\":this.writeFloat64(t,n.BIG_ENDIAN);break;case\"uint16le\":this.writeUint16(t,n.LITTLE_ENDIAN);break;case\"int16le\":this.writeInt16(t,n.LITTLE_ENDIAN);break;case\"uint32le\":this.writeUint32(t,n.LITTLE_ENDIAN);break;case\"int32le\":this.writeInt32(t,n.LITTLE_ENDIAN);break;case\"float32le\":this.writeFloat32(t,n.LITTLE_ENDIAN);break;case\"float64le\":this.writeFloat64(t,n.LITTLE_ENDIAN);break;case\"cstring\":this.writeCString(t,i);break;case\"string\":this.writeString(t,r,i);break;case\"u16string\":this.writeUCS2String(t,this.endianness,i);break;case\"u16stringle\":this.writeUCS2String(t,n.LITTLE_ENDIAN,i);break;case\"u16stringbe\":this.writeUCS2String(t,n.BIG_ENDIAN,i);break;default:if(3==e.length){for(var h=e[1],l=0;l<t.length;l++)this.writeType(h,t[l]);break}this.writeStruct(e,t)}null!=i&&(this.position=a,this._realloc(i),this.position=a+i)},\"function\"==typeof define&&define.amd&&define(\"DataStream\",[],function(){return n}),\"object\"==typeof module&&module&&module.exports&&(module.exports=n);function a(e){let t=e.length;for(;--t>=0;)e[t]=0}const o=256,h=286,l=30,u=15,_=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),c=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),d=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),m=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),g=new Array(576);a(g);const S=new Array(60);a(S);const p=new Array(512);a(p);const f=new Array(256);a(f);const R=new Array(29);a(R);const E=new Array(l);function y(e,t,s,i,r){this.static_tree=e,this.extra_bits=t,this.extra_base=s,this.elems=i,this.max_length=r,this.has_stree=e&&e.length}let b,A,O;function I(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}a(E);const w=e=>e<256?p[e]:p[256+(e>>>7)],T=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},M=(e,t,s)=>{e.bi_valid>16-s?(e.bi_buf|=t<<e.bi_valid&65535,T(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=s-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=s)},v=(e,t,s)=>{M(e,s[2*t],s[2*t+1])},N=(e,t)=>{let s=0;do{s|=1&e,e>>>=1,s<<=1}while(--t>0);return s>>>1},U=(e,t,s)=>{const i=new Array(16);let r,n,a=0;for(r=1;r<=u;r++)a=a+s[r-1]<<1,i[r]=a;for(n=0;n<=t;n++){let t=e[2*n+1];0!==t&&(e[2*n]=N(i[t]++,t))}},F=e=>{let t;for(t=0;t<h;t++)e.dyn_ltree[2*t]=0;for(t=0;t<l;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},L=e=>{e.bi_valid>8?T(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},C=(e,t,s,i)=>{const r=2*t,n=2*s;return e[r]<e[n]||e[r]===e[n]&&i[t]<=i[s]},D=(e,t,s)=>{const i=e.heap[s];let r=s<<1;for(;r<=e.heap_len&&(r<e.heap_len&&C(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!C(t,i,e.heap[r],e.depth));)e.heap[s]=e.heap[r],s=r,r<<=1;e.heap[s]=i},B=(e,t,s)=>{let i,r,n,a,h=0;if(0!==e.sym_next)do{i=255&e.pending_buf[e.sym_buf+h++],i+=(255&e.pending_buf[e.sym_buf+h++])<<8,r=e.pending_buf[e.sym_buf+h++],0===i?v(e,r,t):(n=f[r],v(e,n+o+1,t),a=_[n],0!==a&&(r-=R[n],M(e,r,a)),i--,n=w(i),v(e,n,s),a=c[n],0!==a&&(i-=E[n],M(e,i,a)))}while(h<e.sym_next);v(e,256,t)},Y=(e,t)=>{const s=t.dyn_tree,i=t.stat_desc.static_tree,r=t.stat_desc.has_stree,n=t.stat_desc.elems;let a,o,h,l=-1;for(e.heap_len=0,e.heap_max=573,a=0;a<n;a++)0!==s[2*a]?(e.heap[++e.heap_len]=l=a,e.depth[a]=0):s[2*a+1]=0;for(;e.heap_len<2;)h=e.heap[++e.heap_len]=l<2?++l:0,s[2*h]=1,e.depth[h]=0,e.opt_len--,r&&(e.static_len-=i[2*h+1]);for(t.max_code=l,a=e.heap_len>>1;a>=1;a--)D(e,s,a);h=n;do{a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],D(e,s,1),o=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=o,s[2*h]=s[2*a]+s[2*o],e.depth[h]=(e.depth[a]>=e.depth[o]?e.depth[a]:e.depth[o])+1,s[2*a+1]=s[2*o+1]=h,e.heap[1]=h++,D(e,s,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const s=t.dyn_tree,i=t.max_code,r=t.stat_desc.static_tree,n=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,h=t.stat_desc.max_length;let l,_,c,d,m,g,S=0;for(d=0;d<=u;d++)e.bl_count[d]=0;for(s[2*e.heap[e.heap_max]+1]=0,l=e.heap_max+1;l<573;l++)_=e.heap[l],d=s[2*s[2*_+1]+1]+1,d>h&&(d=h,S++),s[2*_+1]=d,_>i||(e.bl_count[d]++,m=0,_>=o&&(m=a[_-o]),g=s[2*_],e.opt_len+=g*(d+m),n&&(e.static_len+=g*(r[2*_+1]+m)));if(0!==S){do{for(d=h-1;0===e.bl_count[d];)d--;e.bl_count[d]--,e.bl_count[d+1]+=2,e.bl_count[h]--,S-=2}while(S>0);for(d=h;0!==d;d--)for(_=e.bl_count[d];0!==_;)c=e.heap[--l],c>i||(s[2*c+1]!==d&&(e.opt_len+=(d-s[2*c+1])*s[2*c],s[2*c+1]=d),_--)}})(e,t),U(s,l,e.bl_count)},x=(e,t,s)=>{let i,r,n=-1,a=t[1],o=0,h=7,l=4;for(0===a&&(h=138,l=3),t[2*(s+1)+1]=65535,i=0;i<=s;i++)r=a,a=t[2*(i+1)+1],++o<h&&r===a||(o<l?e.bl_tree[2*r]+=o:0!==r?(r!==n&&e.bl_tree[2*r]++,e.bl_tree[32]++):o<=10?e.bl_tree[34]++:e.bl_tree[36]++,o=0,n=r,0===a?(h=138,l=3):r===a?(h=6,l=3):(h=7,l=4))},k=(e,t,s)=>{let i,r,n=-1,a=t[1],o=0,h=7,l=4;for(0===a&&(h=138,l=3),i=0;i<=s;i++)if(r=a,a=t[2*(i+1)+1],!(++o<h&&r===a)){if(o<l)do{v(e,r,e.bl_tree)}while(0!==--o);else 0!==r?(r!==n&&(v(e,r,e.bl_tree),o--),v(e,16,e.bl_tree),M(e,o-3,2)):o<=10?(v(e,17,e.bl_tree),M(e,o-3,3)):(v(e,18,e.bl_tree),M(e,o-11,7));o=0,n=r,0===a?(h=138,l=3):r===a?(h=6,l=3):(h=7,l=4)}};let P=!1;const q=(e,t,s,i)=>{M(e,0+(i?1:0),3),L(e),T(e,s),T(e,~s),s&&e.pending_buf.set(e.window.subarray(t,t+s),e.pending),e.pending+=s};var V=(e,t,s,i)=>{let r,n,a=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,s=4093624447;for(t=0;t<=31;t++,s>>>=1)if(1&s&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<o;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),Y(e,e.l_desc),Y(e,e.d_desc),a=(e=>{let t;for(x(e,e.dyn_ltree,e.l_desc.max_code),x(e,e.dyn_dtree,e.d_desc.max_code),Y(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*m[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,n=e.static_len+3+7>>>3,n<=r&&(r=n)):r=n=s+5,s+4<=r&&-1!==t?q(e,t,s,i):4===e.strategy||n===r?(M(e,2+(i?1:0),3),B(e,g,S)):(M(e,4+(i?1:0),3),((e,t,s,i)=>{let r;for(M(e,t-257,5),M(e,s-1,5),M(e,i-4,4),r=0;r<i;r++)M(e,e.bl_tree[2*m[r]+1],3);k(e,e.dyn_ltree,t-1),k(e,e.dyn_dtree,s-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),B(e,e.dyn_ltree,e.dyn_dtree)),F(e),i&&L(e)},K={_tr_init:e=>{P||((()=>{let e,t,s,i,r;const n=new Array(16);for(s=0,i=0;i<28;i++)for(R[i]=s,e=0;e<1<<_[i];e++)f[s++]=i;for(f[s-1]=i,r=0,i=0;i<16;i++)for(E[i]=r,e=0;e<1<<c[i];e++)p[r++]=i;for(r>>=7;i<l;i++)for(E[i]=r<<7,e=0;e<1<<c[i]-7;e++)p[256+r++]=i;for(t=0;t<=u;t++)n[t]=0;for(e=0;e<=143;)g[2*e+1]=8,e++,n[8]++;for(;e<=255;)g[2*e+1]=9,e++,n[9]++;for(;e<=279;)g[2*e+1]=7,e++,n[7]++;for(;e<=287;)g[2*e+1]=8,e++,n[8]++;for(U(g,287,n),e=0;e<l;e++)S[2*e+1]=5,S[2*e]=N(e,5);b=new y(g,_,257,h,u),A=new y(S,c,0,l,u),O=new y(new Array(0),d,0,19,7)})(),P=!0),e.l_desc=new I(e.dyn_ltree,b),e.d_desc=new I(e.dyn_dtree,A),e.bl_desc=new I(e.bl_tree,O),e.bi_buf=0,e.bi_valid=0,F(e)},_tr_stored_block:q,_tr_flush_block:V,_tr_tally:(e,t,s)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=s,0===t?e.dyn_ltree[2*s]++:(e.matches++,t--,e.dyn_ltree[2*(f[s]+o+1)]++,e.dyn_dtree[2*w(t)]++),e.sym_next===e.sym_end),_tr_align:e=>{M(e,2,3),v(e,256,g),(e=>{16===e.bi_valid?(T(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)}};var G=(e,t,s,i)=>{let r=65535&e,n=e>>>16&65535,a=0;for(;0!==s;){a=s>2e3?2e3:s,s-=a;do{r=r+t[i++]|0,n=n+r|0}while(--a);r%=65521,n%=65521}return r|n<<16};const j=new Uint32Array((()=>{let e,t=[];for(var s=0;s<256;s++){e=s;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t})());var z=(e,t,s,i)=>{const r=j,n=i+s;e^=-1;for(let s=i;s<n;s++)e=e>>>8^r[255&(e^t[s])];return-1^e},H={2:\"need dictionary\",1:\"stream end\",0:\"\",\"-1\":\"file error\",\"-2\":\"stream error\",\"-3\":\"data error\",\"-4\":\"insufficient memory\",\"-5\":\"buffer error\",\"-6\":\"incompatible version\"},J={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:$,_tr_stored_block:X,_tr_flush_block:Z,_tr_tally:W,_tr_align:Q}=K,{Z_NO_FLUSH:ee,Z_PARTIAL_FLUSH:te,Z_FULL_FLUSH:se,Z_FINISH:ie,Z_BLOCK:re,Z_OK:ne,Z_STREAM_END:ae,Z_STREAM_ERROR:oe,Z_DATA_ERROR:he,Z_BUF_ERROR:le,Z_DEFAULT_COMPRESSION:ue,Z_FILTERED:_e,Z_HUFFMAN_ONLY:ce,Z_RLE:de,Z_FIXED:me,Z_DEFAULT_STRATEGY:ge,Z_UNKNOWN:Se,Z_DEFLATED:pe}=J,fe=258,Re=262,Ee=42,ye=113,be=666,Ae=(e,t)=>(e.msg=H[t],t),Oe=e=>2*e-(e>4?9:0),Ie=e=>{let t=e.length;for(;--t>=0;)e[t]=0},we=e=>{let t,s,i,r=e.w_size;t=e.hash_size,i=t;do{s=e.head[--i],e.head[i]=s>=r?s-r:0}while(--t);t=r,i=t;do{s=e.prev[--i],e.prev[i]=s>=r?s-r:0}while(--t)};let Te=(e,t,s)=>(t<<e.hash_shift^s)&e.hash_mask;const Me=e=>{const t=e.state;let s=t.pending;s>e.avail_out&&(s=e.avail_out),0!==s&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+s),e.next_out),e.next_out+=s,t.pending_out+=s,e.total_out+=s,e.avail_out-=s,t.pending-=s,0===t.pending&&(t.pending_out=0))},ve=(e,t)=>{Z(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Me(e.strm)},Ne=(e,t)=>{e.pending_buf[e.pending++]=t},Ue=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},Fe=(e,t,s,i)=>{let r=e.avail_in;return r>i&&(r=i),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),s),1===e.state.wrap?e.adler=G(e.adler,t,r,s):2===e.state.wrap&&(e.adler=z(e.adler,t,r,s)),e.next_in+=r,e.total_in+=r,r)},Le=(e,t)=>{let s,i,r=e.max_chain_length,n=e.strstart,a=e.prev_length,o=e.nice_match;const h=e.strstart>e.w_size-Re?e.strstart-(e.w_size-Re):0,l=e.window,u=e.w_mask,_=e.prev,c=e.strstart+fe;let d=l[n+a-1],m=l[n+a];e.prev_length>=e.good_match&&(r>>=2),o>e.lookahead&&(o=e.lookahead);do{if(s=t,l[s+a]===m&&l[s+a-1]===d&&l[s]===l[n]&&l[++s]===l[n+1]){n+=2,s++;do{}while(l[++n]===l[++s]&&l[++n]===l[++s]&&l[++n]===l[++s]&&l[++n]===l[++s]&&l[++n]===l[++s]&&l[++n]===l[++s]&&l[++n]===l[++s]&&l[++n]===l[++s]&&n<c);if(i=fe-(c-n),n=c-fe,i>a){if(e.match_start=t,a=i,i>=o)break;d=l[n+a-1],m=l[n+a]}}}while((t=_[t&u])>h&&0!==--r);return a<=e.lookahead?a:e.lookahead},Ce=e=>{const t=e.w_size;let s,i,r;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Re)&&(e.window.set(e.window.subarray(t,t+t-i),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),we(e),i+=t),0===e.strm.avail_in)break;if(s=Fe(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=s,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=Te(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=Te(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<Re&&0!==e.strm.avail_in)},De=(e,t)=>{let s,i,r,n=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,a=0,o=e.strm.avail_in;do{if(s=65535,r=e.bi_valid+42>>3,e.strm.avail_out<r)break;if(r=e.strm.avail_out-r,i=e.strstart-e.block_start,s>i+e.strm.avail_in&&(s=i+e.strm.avail_in),s>r&&(s=r),s<n&&(0===s&&t!==ie||t===ee||s!==i+e.strm.avail_in))break;a=t===ie&&s===i+e.strm.avail_in?1:0,X(e,0,0,a),e.pending_buf[e.pending-4]=s,e.pending_buf[e.pending-3]=s>>8,e.pending_buf[e.pending-2]=~s,e.pending_buf[e.pending-1]=~s>>8,Me(e.strm),i&&(i>s&&(i=s),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+i),e.strm.next_out),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i,e.block_start+=i,s-=i),s&&(Fe(e.strm,e.strm.output,e.strm.next_out,s),e.strm.next_out+=s,e.strm.avail_out-=s,e.strm.total_out+=s)}while(0===a);return o-=e.strm.avail_in,o&&(o>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=o&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-o,e.strm.next_in),e.strstart),e.strstart+=o,e.insert+=o>e.w_size-e.insert?e.w_size-e.insert:o),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),a?4:t!==ee&&t!==ie&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(r=e.window_size-e.strstart,e.strm.avail_in>r&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(Fe(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water<e.strstart&&(e.high_water=e.strstart),r=e.bi_valid+42>>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,n=r>e.w_size?e.w_size:r,i=e.strstart-e.block_start,(i>=n||(i||t===ie)&&t!==ee&&0===e.strm.avail_in&&i<=r)&&(s=i>r?r:i,a=t===ie&&0===e.strm.avail_in&&s===i?1:0,X(e,e.block_start,s,a),e.block_start+=s,Me(e.strm)),a?3:1)},Be=(e,t)=>{let s,i;for(;;){if(e.lookahead<Re){if(Ce(e),e.lookahead<Re&&t===ee)return 1;if(0===e.lookahead)break}if(s=0,e.lookahead>=3&&(e.ins_h=Te(e,e.ins_h,e.window[e.strstart+3-1]),s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==s&&e.strstart-s<=e.w_size-Re&&(e.match_length=Le(e,s)),e.match_length>=3)if(i=W(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Te(e,e.ins_h,e.window[e.strstart+3-1]),s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Te(e,e.ins_h,e.window[e.strstart+1]);else i=W(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===ie?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2},Ye=(e,t)=>{let s,i,r;for(;;){if(e.lookahead<Re){if(Ce(e),e.lookahead<Re&&t===ee)return 1;if(0===e.lookahead)break}if(s=0,e.lookahead>=3&&(e.ins_h=Te(e,e.ins_h,e.window[e.strstart+3-1]),s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==s&&e.prev_length<e.max_lazy_match&&e.strstart-s<=e.w_size-Re&&(e.match_length=Le(e,s),e.match_length<=5&&(e.strategy===_e||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,i=W(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=Te(e,e.ins_h,e.window[e.strstart+3-1]),s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,i&&(ve(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(i=W(e,0,e.window[e.strstart-1]),i&&ve(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=W(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===ie?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2};function xe(e,t,s,i,r){this.good_length=e,this.max_lazy=t,this.nice_length=s,this.max_chain=i,this.func=r}const ke=[new xe(0,0,0,0,De),new xe(4,4,8,4,Be),new xe(4,5,16,8,Be),new xe(4,6,32,32,Be),new xe(4,4,16,16,Ye),new xe(8,16,32,32,Ye),new xe(8,16,128,128,Ye),new xe(8,32,128,256,Ye),new xe(32,128,258,1024,Ye),new xe(32,258,258,4096,Ye)];function Pe(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=pe,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Ie(this.dyn_ltree),Ie(this.dyn_dtree),Ie(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Ie(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Ie(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const qe=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==Ee&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==ye&&t.status!==be?1:0},Ve=e=>{if(qe(e))return Ae(e,oe);e.total_in=e.total_out=0,e.data_type=Se;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?Ee:ye,e.adler=2===t.wrap?0:1,t.last_flush=-2,$(t),ne},Ke=e=>{const t=Ve(e);var s;return t===ne&&((s=e.state).window_size=2*s.w_size,Ie(s.head),s.max_lazy_match=ke[s.level].max_lazy,s.good_match=ke[s.level].good_length,s.nice_match=ke[s.level].nice_length,s.max_chain_length=ke[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=2,s.match_available=0,s.ins_h=0),t},Ge=(e,t,s,i,r,n)=>{if(!e)return oe;let a=1;if(t===ue&&(t=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),r<1||r>9||s!==pe||i<8||i>15||t<0||t>9||n<0||n>me||8===i&&1!==a)return Ae(e,oe);8===i&&(i=9);const o=new Pe;return e.state=o,o.strm=e,o.status=Ee,o.wrap=a,o.gzhead=null,o.w_bits=i,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=r+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<r+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=t,o.strategy=n,o.method=s,Ke(e)};var je={deflateInit:(e,t)=>Ge(e,t,pe,15,8,ge),deflateInit2:Ge,deflateReset:Ke,deflateResetKeep:Ve,deflateSetHeader:(e,t)=>qe(e)||2!==e.state.wrap?oe:(e.state.gzhead=t,ne),deflate:(e,t)=>{if(qe(e)||t>re||t<0)return e?Ae(e,oe):oe;const s=e.state;if(!e.output||0!==e.avail_in&&!e.input||s.status===be&&t!==ie)return Ae(e,0===e.avail_out?le:oe);const i=s.last_flush;if(s.last_flush=t,0!==s.pending){if(Me(e),0===e.avail_out)return s.last_flush=-1,ne}else if(0===e.avail_in&&Oe(t)<=Oe(i)&&t!==ie)return Ae(e,le);if(s.status===be&&0!==e.avail_in)return Ae(e,le);if(s.status===Ee&&0===s.wrap&&(s.status=ye),s.status===Ee){let t=pe+(s.w_bits-8<<4)<<8,i=-1;if(i=s.strategy>=ce||s.level<2?0:s.level<6?1:6===s.level?2:3,t|=i<<6,0!==s.strstart&&(t|=32),t+=31-t%31,Ue(s,t),0!==s.strstart&&(Ue(s,e.adler>>>16),Ue(s,65535&e.adler)),e.adler=1,s.status=ye,Me(e),0!==s.pending)return s.last_flush=-1,ne}if(57===s.status)if(e.adler=0,Ne(s,31),Ne(s,139),Ne(s,8),s.gzhead)Ne(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),Ne(s,255&s.gzhead.time),Ne(s,s.gzhead.time>>8&255),Ne(s,s.gzhead.time>>16&255),Ne(s,s.gzhead.time>>24&255),Ne(s,9===s.level?2:s.strategy>=ce||s.level<2?4:0),Ne(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(Ne(s,255&s.gzhead.extra.length),Ne(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(e.adler=z(e.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69;else if(Ne(s,0),Ne(s,0),Ne(s,0),Ne(s,0),Ne(s,0),Ne(s,9===s.level?2:s.strategy>=ce||s.level<2?4:0),Ne(s,3),s.status=ye,Me(e),0!==s.pending)return s.last_flush=-1,ne;if(69===s.status){if(s.gzhead.extra){let t=s.pending,i=(65535&s.gzhead.extra.length)-s.gzindex;for(;s.pending+i>s.pending_buf_size;){let r=s.pending_buf_size-s.pending;if(s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex,s.gzindex+r),s.pending),s.pending=s.pending_buf_size,s.gzhead.hcrc&&s.pending>t&&(e.adler=z(e.adler,s.pending_buf,s.pending-t,t)),s.gzindex+=r,Me(e),0!==s.pending)return s.last_flush=-1,ne;t=0,i-=r}let r=new Uint8Array(s.gzhead.extra);s.pending_buf.set(r.subarray(s.gzindex,s.gzindex+i),s.pending),s.pending+=i,s.gzhead.hcrc&&s.pending>t&&(e.adler=z(e.adler,s.pending_buf,s.pending-t,t)),s.gzindex=0}s.status=73}if(73===s.status){if(s.gzhead.name){let t,i=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>i&&(e.adler=z(e.adler,s.pending_buf,s.pending-i,i)),Me(e),0!==s.pending)return s.last_flush=-1,ne;i=0}t=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,Ne(s,t)}while(0!==t);s.gzhead.hcrc&&s.pending>i&&(e.adler=z(e.adler,s.pending_buf,s.pending-i,i)),s.gzindex=0}s.status=91}if(91===s.status){if(s.gzhead.comment){let t,i=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>i&&(e.adler=z(e.adler,s.pending_buf,s.pending-i,i)),Me(e),0!==s.pending)return s.last_flush=-1,ne;i=0}t=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,Ne(s,t)}while(0!==t);s.gzhead.hcrc&&s.pending>i&&(e.adler=z(e.adler,s.pending_buf,s.pending-i,i))}s.status=103}if(103===s.status){if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size&&(Me(e),0!==s.pending))return s.last_flush=-1,ne;Ne(s,255&e.adler),Ne(s,e.adler>>8&255),e.adler=0}if(s.status=ye,Me(e),0!==s.pending)return s.last_flush=-1,ne}if(0!==e.avail_in||0!==s.lookahead||t!==ee&&s.status!==be){let i=0===s.level?De(s,t):s.strategy===ce?((e,t)=>{let s;for(;;){if(0===e.lookahead&&(Ce(e),0===e.lookahead)){if(t===ee)return 1;break}if(e.match_length=0,s=W(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,s&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ie?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2})(s,t):s.strategy===de?((e,t)=>{let s,i,r,n;const a=e.window;for(;;){if(e.lookahead<=fe){if(Ce(e),e.lookahead<=fe&&t===ee)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,i=a[r],i===a[++r]&&i===a[++r]&&i===a[++r])){n=e.strstart+fe;do{}while(i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&r<n);e.match_length=fe-(n-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(s=W(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(s=W(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),s&&(ve(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ie?(ve(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(ve(e,!1),0===e.strm.avail_out)?1:2})(s,t):ke[s.level].func(s,t);if(3!==i&&4!==i||(s.status=be),1===i||3===i)return 0===e.avail_out&&(s.last_flush=-1),ne;if(2===i&&(t===te?Q(s):t!==re&&(X(s,0,0,!1),t===se&&(Ie(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),Me(e),0===e.avail_out))return s.last_flush=-1,ne}return t!==ie?ne:s.wrap<=0?ae:(2===s.wrap?(Ne(s,255&e.adler),Ne(s,e.adler>>8&255),Ne(s,e.adler>>16&255),Ne(s,e.adler>>24&255),Ne(s,255&e.total_in),Ne(s,e.total_in>>8&255),Ne(s,e.total_in>>16&255),Ne(s,e.total_in>>24&255)):(Ue(s,e.adler>>>16),Ue(s,65535&e.adler)),Me(e),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?ne:ae)},deflateEnd:e=>{if(qe(e))return oe;const t=e.state.status;return e.state=null,t===ye?Ae(e,he):ne},deflateSetDictionary:(e,t)=>{let s=t.length;if(qe(e))return oe;const i=e.state,r=i.wrap;if(2===r||1===r&&i.status!==Ee||i.lookahead)return oe;if(1===r&&(e.adler=G(e.adler,t,s,0)),i.wrap=0,s>=i.w_size){0===r&&(Ie(i.head),i.strstart=0,i.block_start=0,i.insert=0);let e=new Uint8Array(i.w_size);e.set(t.subarray(s-i.w_size,s),0),t=e,s=i.w_size}const n=e.avail_in,a=e.next_in,o=e.input;for(e.avail_in=s,e.next_in=0,e.input=t,Ce(i);i.lookahead>=3;){let e=i.strstart,t=i.lookahead-2;do{i.ins_h=Te(i,i.ins_h,i.window[e+3-1]),i.prev[e&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=e,e++}while(--t);i.strstart=e,i.lookahead=2,Ce(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,e.next_in=a,e.input=o,e.avail_in=n,i.wrap=r,ne},deflateInfo:\"pako deflate (from Nodeca project)\"};const ze=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var He=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const s=t.shift();if(s){if(\"object\"!=typeof s)throw new TypeError(s+\"must be non-object\");for(const t in s)ze(s,t)&&(e[t]=s[t])}}return e},Je=e=>{let t=0;for(let s=0,i=e.length;s<i;s++)t+=e[s].length;const s=new Uint8Array(t);for(let t=0,i=0,r=e.length;t<r;t++){let r=e[t];s.set(r,i),i+=r.length}return s};let $e=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){$e=!1}const Xe=new Uint8Array(256);for(let e=0;e<256;e++)Xe[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;Xe[254]=Xe[254]=1;var Ze=e=>{if(\"function\"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,s,i,r,n,a=e.length,o=0;for(r=0;r<a;r++)s=e.charCodeAt(r),55296==(64512&s)&&r+1<a&&(i=e.charCodeAt(r+1),56320==(64512&i)&&(s=65536+(s-55296<<10)+(i-56320),r++)),o+=s<128?1:s<2048?2:s<65536?3:4;for(t=new Uint8Array(o),n=0,r=0;n<o;r++)s=e.charCodeAt(r),55296==(64512&s)&&r+1<a&&(i=e.charCodeAt(r+1),56320==(64512&i)&&(s=65536+(s-55296<<10)+(i-56320),r++)),s<128?t[n++]=s:s<2048?(t[n++]=192|s>>>6,t[n++]=128|63&s):s<65536?(t[n++]=224|s>>>12,t[n++]=128|s>>>6&63,t[n++]=128|63&s):(t[n++]=240|s>>>18,t[n++]=128|s>>>12&63,t[n++]=128|s>>>6&63,t[n++]=128|63&s);return t},We=(e,t)=>{const s=t||e.length;if(\"function\"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let i,r;const n=new Array(2*s);for(r=0,i=0;i<s;){let t=e[i++];if(t<128){n[r++]=t;continue}let a=Xe[t];if(a>4)n[r++]=65533,i+=a-1;else{for(t&=2===a?31:3===a?15:7;a>1&&i<s;)t=t<<6|63&e[i++],a--;a>1?n[r++]=65533:t<65536?n[r++]=t:(t-=65536,n[r++]=55296|t>>10&1023,n[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&$e)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let s=\"\";for(let i=0;i<t;i++)s+=String.fromCharCode(e[i]);return s})(n,r)},Qe=(e,t)=>{(t=t||e.length)>e.length&&(t=e.length);let s=t-1;for(;s>=0&&128==(192&e[s]);)s--;return s<0||0===s?t:s+Xe[e[s]]>t?s:t};var et=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\"\",this.state=null,this.data_type=2,this.adler=0};const tt=Object.prototype.toString,{Z_NO_FLUSH:st,Z_SYNC_FLUSH:it,Z_FULL_FLUSH:rt,Z_FINISH:nt,Z_OK:at,Z_STREAM_END:ot,Z_DEFAULT_COMPRESSION:ht,Z_DEFAULT_STRATEGY:lt,Z_DEFLATED:ut}=J;function _t(e){this.options=He({level:ht,method:ut,chunkSize:16384,windowBits:15,memLevel:8,strategy:lt},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new et,this.strm.avail_out=0;let s=je.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(s!==at)throw new Error(H[s]);if(t.header&&je.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e=\"string\"==typeof t.dictionary?Ze(t.dictionary):\"[object ArrayBuffer]\"===tt.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,s=je.deflateSetDictionary(this.strm,e),s!==at)throw new Error(H[s]);this._dict_set=!0}}function ct(e,t){const s=new _t(t);if(s.push(e,!0),s.err)throw s.msg||H[s.err];return s.result}_t.prototype.push=function(e,t){const s=this.strm,i=this.options.chunkSize;let r,n;if(this.ended)return!1;for(n=t===~~t?t:!0===t?nt:st,\"string\"==typeof e?s.input=Ze(e):\"[object ArrayBuffer]\"===tt.call(e)?s.input=new Uint8Array(e):s.input=e,s.next_in=0,s.avail_in=s.input.length;;)if(0===s.avail_out&&(s.output=new Uint8Array(i),s.next_out=0,s.avail_out=i),(n===it||n===rt)&&s.avail_out<=6)this.onData(s.output.subarray(0,s.next_out)),s.avail_out=0;else{if(r=je.deflate(s,n),r===ot)return s.next_out>0&&this.onData(s.output.subarray(0,s.next_out)),r=je.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===at;if(0!==s.avail_out){if(n>0&&s.next_out>0)this.onData(s.output.subarray(0,s.next_out)),s.avail_out=0;else if(0===s.avail_in)break}else this.onData(s.output)}return!0},_t.prototype.onData=function(e){this.chunks.push(e)},_t.prototype.onEnd=function(e){e===at&&(this.result=Je(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var dt={Deflate:_t,deflate:ct,deflateRaw:function(e,t){return(t=t||{}).raw=!0,ct(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,ct(e,t)},constants:J};const mt=16209;var gt=function(e,t){let s,i,r,n,a,o,h,l,u,_,c,d,m,g,S,p,f,R,E,y,b,A,O,I;const w=e.state;s=e.next_in,O=e.input,i=s+(e.avail_in-5),r=e.next_out,I=e.output,n=r-(t-e.avail_out),a=r+(e.avail_out-257),o=w.dmax,h=w.wsize,l=w.whave,u=w.wnext,_=w.window,c=w.hold,d=w.bits,m=w.lencode,g=w.distcode,S=(1<<w.lenbits)-1,p=(1<<w.distbits)-1;e:do{d<15&&(c+=O[s++]<<d,d+=8,c+=O[s++]<<d,d+=8),f=m[c&S];t:for(;;){if(R=f>>>24,c>>>=R,d-=R,R=f>>>16&255,0===R)I[r++]=65535&f;else{if(!(16&R)){if(64&R){if(32&R){w.mode=16191;break e}e.msg=\"invalid literal/length code\",w.mode=mt;break e}f=m[(65535&f)+(c&(1<<R)-1)];continue t}for(E=65535&f,R&=15,R&&(d<R&&(c+=O[s++]<<d,d+=8),E+=c&(1<<R)-1,c>>>=R,d-=R),d<15&&(c+=O[s++]<<d,d+=8,c+=O[s++]<<d,d+=8),f=g[c&p];;){if(R=f>>>24,c>>>=R,d-=R,R=f>>>16&255,16&R){if(y=65535&f,R&=15,d<R&&(c+=O[s++]<<d,d+=8,d<R&&(c+=O[s++]<<d,d+=8)),y+=c&(1<<R)-1,y>o){e.msg=\"invalid distance too far back\",w.mode=mt;break e}if(c>>>=R,d-=R,R=r-n,y>R){if(R=y-R,R>l&&w.sane){e.msg=\"invalid distance too far back\",w.mode=mt;break e}if(b=0,A=_,0===u){if(b+=h-R,R<E){E-=R;do{I[r++]=_[b++]}while(--R);b=r-y,A=I}}else if(u<R){if(b+=h+u-R,R-=u,R<E){E-=R;do{I[r++]=_[b++]}while(--R);if(b=0,u<E){R=u,E-=R;do{I[r++]=_[b++]}while(--R);b=r-y,A=I}}}else if(b+=u-R,R<E){E-=R;do{I[r++]=_[b++]}while(--R);b=r-y,A=I}for(;E>2;)I[r++]=A[b++],I[r++]=A[b++],I[r++]=A[b++],E-=3;E&&(I[r++]=A[b++],E>1&&(I[r++]=A[b++]))}else{b=r-y;do{I[r++]=I[b++],I[r++]=I[b++],I[r++]=I[b++],E-=3}while(E>2);E&&(I[r++]=I[b++],E>1&&(I[r++]=I[b++]))}break}if(64&R){e.msg=\"invalid distance code\",w.mode=mt;break e}f=g[(65535&f)+(c&(1<<R)-1)]}}break}}while(s<i&&r<a);E=d>>3,s-=E,d-=E<<3,c&=(1<<d)-1,e.next_in=s,e.next_out=r,e.avail_in=s<i?i-s+5:5-(s-i),e.avail_out=r<a?a-r+257:257-(r-a),w.hold=c,w.bits=d};const St=15,pt=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),ft=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),Rt=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),Et=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var yt=(e,t,s,i,r,n,a,o)=>{const h=o.bits;let l,u,_,c,d,m,g=0,S=0,p=0,f=0,R=0,E=0,y=0,b=0,A=0,O=0,I=null;const w=new Uint16Array(16),T=new Uint16Array(16);let M,v,N,U=null;for(g=0;g<=St;g++)w[g]=0;for(S=0;S<i;S++)w[t[s+S]]++;for(R=h,f=St;f>=1&&0===w[f];f--);if(R>f&&(R=f),0===f)return r[n++]=20971520,r[n++]=20971520,o.bits=1,0;for(p=1;p<f&&0===w[p];p++);for(R<p&&(R=p),b=1,g=1;g<=St;g++)if(b<<=1,b-=w[g],b<0)return-1;if(b>0&&(0===e||1!==f))return-1;for(T[1]=0,g=1;g<St;g++)T[g+1]=T[g]+w[g];for(S=0;S<i;S++)0!==t[s+S]&&(a[T[t[s+S]]++]=S);if(0===e?(I=U=a,m=20):1===e?(I=pt,U=ft,m=257):(I=Rt,U=Et,m=0),O=0,S=0,g=p,d=n,E=R,y=0,_=-1,A=1<<R,c=A-1,1===e&&A>852||2===e&&A>592)return 1;for(;;){M=g-y,a[S]+1<m?(v=0,N=a[S]):a[S]>=m?(v=U[a[S]-m],N=I[a[S]-m]):(v=96,N=0),l=1<<g-y,u=1<<E,p=u;do{u-=l,r[d+(O>>y)+u]=M<<24|v<<16|N}while(0!==u);for(l=1<<g-1;O&l;)l>>=1;if(0!==l?(O&=l-1,O+=l):O=0,S++,0===--w[g]){if(g===f)break;g=t[s+a[S]]}if(g>R&&(O&c)!==_){for(0===y&&(y=R),d+=p,E=g-y,b=1<<E;E+y<f&&(b-=w[E+y],!(b<=0));)E++,b<<=1;if(A+=1<<E,1===e&&A>852||2===e&&A>592)return 1;_=O&c,r[_]=R<<24|E<<16|d-n}}return 0!==O&&(r[d+O]=g-y<<24|64<<16),o.bits=R,0};const{Z_FINISH:bt,Z_BLOCK:At,Z_TREES:Ot,Z_OK:It,Z_STREAM_END:wt,Z_NEED_DICT:Tt,Z_STREAM_ERROR:Mt,Z_DATA_ERROR:vt,Z_MEM_ERROR:Nt,Z_BUF_ERROR:Ut,Z_DEFLATED:Ft}=J,Lt=16180,Ct=16190,Dt=16191,Bt=16192,Yt=16194,xt=16199,kt=16200,Pt=16206,qt=16209,Vt=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function Kt(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Gt=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<Lt||t.mode>16211?1:0},jt=e=>{if(Gt(e))return Mt;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg=\"\",t.wrap&&(e.adler=1&t.wrap),t.mode=Lt,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,It},zt=e=>{if(Gt(e))return Mt;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,jt(e)},Ht=(e,t)=>{let s;if(Gt(e))return Mt;const i=e.state;return t<0?(s=0,t=-t):(s=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Mt:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=s,i.wbits=t,zt(e))},Jt=(e,t)=>{if(!e)return Mt;const s=new Kt;e.state=s,s.strm=e,s.window=null,s.mode=Lt;const i=Ht(e,t);return i!==It&&(e.state=null),i};let $t,Xt,Zt=!0;const Wt=e=>{if(Zt){$t=new Int32Array(512),Xt=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(yt(1,e.lens,0,288,$t,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;yt(2,e.lens,0,32,Xt,0,e.work,{bits:5}),Zt=!1}e.lencode=$t,e.lenbits=9,e.distcode=Xt,e.distbits=5},Qt=(e,t,s,i)=>{let r;const n=e.state;return null===n.window&&(n.wsize=1<<n.wbits,n.wnext=0,n.whave=0,n.window=new Uint8Array(n.wsize)),i>=n.wsize?(n.window.set(t.subarray(s-n.wsize,s),0),n.wnext=0,n.whave=n.wsize):(r=n.wsize-n.wnext,r>i&&(r=i),n.window.set(t.subarray(s-i,s-i+r),n.wnext),(i-=r)?(n.window.set(t.subarray(s-i,s),0),n.wnext=i,n.whave=n.wsize):(n.wnext+=r,n.wnext===n.wsize&&(n.wnext=0),n.whave<n.wsize&&(n.whave+=r))),0};var es={inflateReset:zt,inflateReset2:Ht,inflateResetKeep:jt,inflateInit:e=>Jt(e,15),inflateInit2:Jt,inflate:(e,t)=>{let s,i,r,n,a,o,h,l,u,_,c,d,m,g,S,p,f,R,E,y,b,A,O=0;const I=new Uint8Array(4);let w,T;const M=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Gt(e)||!e.output||!e.input&&0!==e.avail_in)return Mt;s=e.state,s.mode===Dt&&(s.mode=Bt),a=e.next_out,r=e.output,h=e.avail_out,n=e.next_in,i=e.input,o=e.avail_in,l=s.hold,u=s.bits,_=o,c=h,A=It;e:for(;;)switch(s.mode){case Lt:if(0===s.wrap){s.mode=Bt;break}for(;u<16;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}if(2&s.wrap&&35615===l){0===s.wbits&&(s.wbits=15),s.check=0,I[0]=255&l,I[1]=l>>>8&255,s.check=z(s.check,I,2,0),l=0,u=0,s.mode=16181;break}if(s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&l)<<8)+(l>>8))%31){e.msg=\"incorrect header check\",s.mode=qt;break}if((15&l)!==Ft){e.msg=\"unknown compression method\",s.mode=qt;break}if(l>>>=4,u-=4,b=8+(15&l),0===s.wbits&&(s.wbits=b),b>15||b>s.wbits){e.msg=\"invalid window size\",s.mode=qt;break}s.dmax=1<<s.wbits,s.flags=0,e.adler=s.check=1,s.mode=512&l?16189:Dt,l=0,u=0;break;case 16181:for(;u<16;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}if(s.flags=l,(255&s.flags)!==Ft){e.msg=\"unknown compression method\",s.mode=qt;break}if(57344&s.flags){e.msg=\"unknown header flags set\",s.mode=qt;break}s.head&&(s.head.text=l>>8&1),512&s.flags&&4&s.wrap&&(I[0]=255&l,I[1]=l>>>8&255,s.check=z(s.check,I,2,0)),l=0,u=0,s.mode=16182;case 16182:for(;u<32;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}s.head&&(s.head.time=l),512&s.flags&&4&s.wrap&&(I[0]=255&l,I[1]=l>>>8&255,I[2]=l>>>16&255,I[3]=l>>>24&255,s.check=z(s.check,I,4,0)),l=0,u=0,s.mode=16183;case 16183:for(;u<16;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}s.head&&(s.head.xflags=255&l,s.head.os=l>>8),512&s.flags&&4&s.wrap&&(I[0]=255&l,I[1]=l>>>8&255,s.check=z(s.check,I,2,0)),l=0,u=0,s.mode=16184;case 16184:if(1024&s.flags){for(;u<16;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}s.length=l,s.head&&(s.head.extra_len=l),512&s.flags&&4&s.wrap&&(I[0]=255&l,I[1]=l>>>8&255,s.check=z(s.check,I,2,0)),l=0,u=0}else s.head&&(s.head.extra=null);s.mode=16185;case 16185:if(1024&s.flags&&(d=s.length,d>o&&(d=o),d&&(s.head&&(b=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Uint8Array(s.head.extra_len)),s.head.extra.set(i.subarray(n,n+d),b)),512&s.flags&&4&s.wrap&&(s.check=z(s.check,i,d,n)),o-=d,n+=d,s.length-=d),s.length))break e;s.length=0,s.mode=16186;case 16186:if(2048&s.flags){if(0===o)break e;d=0;do{b=i[n+d++],s.head&&b&&s.length<65536&&(s.head.name+=String.fromCharCode(b))}while(b&&d<o);if(512&s.flags&&4&s.wrap&&(s.check=z(s.check,i,d,n)),o-=d,n+=d,b)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=16187;case 16187:if(4096&s.flags){if(0===o)break e;d=0;do{b=i[n+d++],s.head&&b&&s.length<65536&&(s.head.comment+=String.fromCharCode(b))}while(b&&d<o);if(512&s.flags&&4&s.wrap&&(s.check=z(s.check,i,d,n)),o-=d,n+=d,b)break e}else s.head&&(s.head.comment=null);s.mode=16188;case 16188:if(512&s.flags){for(;u<16;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}if(4&s.wrap&&l!==(65535&s.check)){e.msg=\"header crc mismatch\",s.mode=qt;break}l=0,u=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=Dt;break;case 16189:for(;u<32;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}e.adler=s.check=Vt(l),l=0,u=0,s.mode=Ct;case Ct:if(0===s.havedict)return e.next_out=a,e.avail_out=h,e.next_in=n,e.avail_in=o,s.hold=l,s.bits=u,Tt;e.adler=s.check=1,s.mode=Dt;case Dt:if(t===At||t===Ot)break e;case Bt:if(s.last){l>>>=7&u,u-=7&u,s.mode=Pt;break}for(;u<3;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}switch(s.last=1&l,l>>>=1,u-=1,3&l){case 0:s.mode=16193;break;case 1:if(Wt(s),s.mode=xt,t===Ot){l>>>=2,u-=2;break e}break;case 2:s.mode=16196;break;case 3:e.msg=\"invalid block type\",s.mode=qt}l>>>=2,u-=2;break;case 16193:for(l>>>=7&u,u-=7&u;u<32;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}if((65535&l)!=(l>>>16^65535)){e.msg=\"invalid stored block lengths\",s.mode=qt;break}if(s.length=65535&l,l=0,u=0,s.mode=Yt,t===Ot)break e;case Yt:s.mode=16195;case 16195:if(d=s.length,d){if(d>o&&(d=o),d>h&&(d=h),0===d)break e;r.set(i.subarray(n,n+d),a),o-=d,n+=d,h-=d,a+=d,s.length-=d;break}s.mode=Dt;break;case 16196:for(;u<14;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}if(s.nlen=257+(31&l),l>>>=5,u-=5,s.ndist=1+(31&l),l>>>=5,u-=5,s.ncode=4+(15&l),l>>>=4,u-=4,s.nlen>286||s.ndist>30){e.msg=\"too many length or distance symbols\",s.mode=qt;break}s.have=0,s.mode=16197;case 16197:for(;s.have<s.ncode;){for(;u<3;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}s.lens[M[s.have++]]=7&l,l>>>=3,u-=3}for(;s.have<19;)s.lens[M[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,w={bits:s.lenbits},A=yt(0,s.lens,0,19,s.lencode,0,s.work,w),s.lenbits=w.bits,A){e.msg=\"invalid code lengths set\",s.mode=qt;break}s.have=0,s.mode=16198;case 16198:for(;s.have<s.nlen+s.ndist;){for(;O=s.lencode[l&(1<<s.lenbits)-1],S=O>>>24,p=O>>>16&255,f=65535&O,!(S<=u);){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}if(f<16)l>>>=S,u-=S,s.lens[s.have++]=f;else{if(16===f){for(T=S+2;u<T;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}if(l>>>=S,u-=S,0===s.have){e.msg=\"invalid bit length repeat\",s.mode=qt;break}b=s.lens[s.have-1],d=3+(3&l),l>>>=2,u-=2}else if(17===f){for(T=S+3;u<T;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}l>>>=S,u-=S,b=0,d=3+(7&l),l>>>=3,u-=3}else{for(T=S+7;u<T;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}l>>>=S,u-=S,b=0,d=11+(127&l),l>>>=7,u-=7}if(s.have+d>s.nlen+s.ndist){e.msg=\"invalid bit length repeat\",s.mode=qt;break}for(;d--;)s.lens[s.have++]=b}}if(s.mode===qt)break;if(0===s.lens[256]){e.msg=\"invalid code -- missing end-of-block\",s.mode=qt;break}if(s.lenbits=9,w={bits:s.lenbits},A=yt(1,s.lens,0,s.nlen,s.lencode,0,s.work,w),s.lenbits=w.bits,A){e.msg=\"invalid literal/lengths set\",s.mode=qt;break}if(s.distbits=6,s.distcode=s.distdyn,w={bits:s.distbits},A=yt(2,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,w),s.distbits=w.bits,A){e.msg=\"invalid distances set\",s.mode=qt;break}if(s.mode=xt,t===Ot)break e;case xt:s.mode=kt;case kt:if(o>=6&&h>=258){e.next_out=a,e.avail_out=h,e.next_in=n,e.avail_in=o,s.hold=l,s.bits=u,gt(e,c),a=e.next_out,r=e.output,h=e.avail_out,n=e.next_in,i=e.input,o=e.avail_in,l=s.hold,u=s.bits,s.mode===Dt&&(s.back=-1);break}for(s.back=0;O=s.lencode[l&(1<<s.lenbits)-1],S=O>>>24,p=O>>>16&255,f=65535&O,!(S<=u);){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}if(p&&!(240&p)){for(R=S,E=p,y=f;O=s.lencode[y+((l&(1<<R+E)-1)>>R)],S=O>>>24,p=O>>>16&255,f=65535&O,!(R+S<=u);){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}l>>>=R,u-=R,s.back+=R}if(l>>>=S,u-=S,s.back+=S,s.length=f,0===p){s.mode=16205;break}if(32&p){s.back=-1,s.mode=Dt;break}if(64&p){e.msg=\"invalid literal/length code\",s.mode=qt;break}s.extra=15&p,s.mode=16201;case 16201:if(s.extra){for(T=s.extra;u<T;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}s.length+=l&(1<<s.extra)-1,l>>>=s.extra,u-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=16202;case 16202:for(;O=s.distcode[l&(1<<s.distbits)-1],S=O>>>24,p=O>>>16&255,f=65535&O,!(S<=u);){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}if(!(240&p)){for(R=S,E=p,y=f;O=s.distcode[y+((l&(1<<R+E)-1)>>R)],S=O>>>24,p=O>>>16&255,f=65535&O,!(R+S<=u);){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}l>>>=R,u-=R,s.back+=R}if(l>>>=S,u-=S,s.back+=S,64&p){e.msg=\"invalid distance code\",s.mode=qt;break}s.offset=f,s.extra=15&p,s.mode=16203;case 16203:if(s.extra){for(T=s.extra;u<T;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}s.offset+=l&(1<<s.extra)-1,l>>>=s.extra,u-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg=\"invalid distance too far back\",s.mode=qt;break}s.mode=16204;case 16204:if(0===h)break e;if(d=c-h,s.offset>d){if(d=s.offset-d,d>s.whave&&s.sane){e.msg=\"invalid distance too far back\",s.mode=qt;break}d>s.wnext?(d-=s.wnext,m=s.wsize-d):m=s.wnext-d,d>s.length&&(d=s.length),g=s.window}else g=r,m=a-s.offset,d=s.length;d>h&&(d=h),h-=d,s.length-=d;do{r[a++]=g[m++]}while(--d);0===s.length&&(s.mode=kt);break;case 16205:if(0===h)break e;r[a++]=s.length,h--,s.mode=kt;break;case Pt:if(s.wrap){for(;u<32;){if(0===o)break e;o--,l|=i[n++]<<u,u+=8}if(c-=h,e.total_out+=c,s.total+=c,4&s.wrap&&c&&(e.adler=s.check=s.flags?z(s.check,r,c,a-c):G(s.check,r,c,a-c)),c=h,4&s.wrap&&(s.flags?l:Vt(l))!==s.check){e.msg=\"incorrect data check\",s.mode=qt;break}l=0,u=0}s.mode=16207;case 16207:if(s.wrap&&s.flags){for(;u<32;){if(0===o)break e;o--,l+=i[n++]<<u,u+=8}if(4&s.wrap&&l!==(4294967295&s.total)){e.msg=\"incorrect length check\",s.mode=qt;break}l=0,u=0}s.mode=16208;case 16208:A=wt;break e;case qt:A=vt;break e;case 16210:return Nt;default:return Mt}return e.next_out=a,e.avail_out=h,e.next_in=n,e.avail_in=o,s.hold=l,s.bits=u,(s.wsize||c!==e.avail_out&&s.mode<qt&&(s.mode<Pt||t!==bt))&&Qt(e,e.output,e.next_out,c-e.avail_out),_-=e.avail_in,c-=e.avail_out,e.total_in+=_,e.total_out+=c,s.total+=c,4&s.wrap&&c&&(e.adler=s.check=s.flags?z(s.check,r,c,e.next_out-c):G(s.check,r,c,e.next_out-c)),e.data_type=s.bits+(s.last?64:0)+(s.mode===Dt?128:0)+(s.mode===xt||s.mode===Yt?256:0),(0===_&&0===c||t===bt)&&A===It&&(A=Ut),A},inflateEnd:e=>{if(Gt(e))return Mt;let t=e.state;return t.window&&(t.window=null),e.state=null,It},inflateGetHeader:(e,t)=>{if(Gt(e))return Mt;const s=e.state;return 2&s.wrap?(s.head=t,t.done=!1,It):Mt},inflateSetDictionary:(e,t)=>{const s=t.length;let i,r,n;return Gt(e)?Mt:(i=e.state,0!==i.wrap&&i.mode!==Ct?Mt:i.mode===Ct&&(r=1,r=G(r,t,s,0),r!==i.check)?vt:(n=Qt(e,t,s,s),n?(i.mode=16210,Nt):(i.havedict=1,It)))},inflateInfo:\"pako inflate (from Nodeca project)\"};var ts=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=\"\",this.comment=\"\",this.hcrc=0,this.done=!1};const ss=Object.prototype.toString,{Z_NO_FLUSH:is,Z_FINISH:rs,Z_OK:ns,Z_STREAM_END:as,Z_NEED_DICT:os,Z_STREAM_ERROR:hs,Z_DATA_ERROR:ls,Z_MEM_ERROR:us}=J;function _s(e){this.options=He({chunkSize:65536,windowBits:15,to:\"\"},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new et,this.strm.avail_out=0;let s=es.inflateInit2(this.strm,t.windowBits);if(s!==ns)throw new Error(H[s]);if(this.header=new ts,es.inflateGetHeader(this.strm,this.header),t.dictionary&&(\"string\"==typeof t.dictionary?t.dictionary=Ze(t.dictionary):\"[object ArrayBuffer]\"===ss.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(s=es.inflateSetDictionary(this.strm,t.dictionary),s!==ns)))throw new Error(H[s])}function cs(e,t){const s=new _s(t);if(s.push(e),s.err)throw s.msg||H[s.err];return s.result}_s.prototype.push=function(e,t){const s=this.strm,i=this.options.chunkSize,r=this.options.dictionary;let n,a,o;if(this.ended)return!1;for(a=t===~~t?t:!0===t?rs:is,\"[object ArrayBuffer]\"===ss.call(e)?s.input=new Uint8Array(e):s.input=e,s.next_in=0,s.avail_in=s.input.length;;){for(0===s.avail_out&&(s.output=new Uint8Array(i),s.next_out=0,s.avail_out=i),n=es.inflate(s,a),n===os&&r&&(n=es.inflateSetDictionary(s,r),n===ns?n=es.inflate(s,a):n===ls&&(n=os));s.avail_in>0&&n===as&&s.state.wrap>0&&0!==e[s.next_in];)es.inflateReset(s),n=es.inflate(s,a);switch(n){case hs:case ls:case os:case us:return this.onEnd(n),this.ended=!0,!1}if(o=s.avail_out,s.next_out&&(0===s.avail_out||n===as))if(\"string\"===this.options.to){let e=Qe(s.output,s.next_out),t=s.next_out-e,r=We(s.output,e);s.next_out=t,s.avail_out=i-t,t&&s.output.set(s.output.subarray(e,e+t),0),this.onData(r)}else this.onData(s.output.length===s.next_out?s.output:s.output.subarray(0,s.next_out));if(n!==ns||0!==o){if(n===as)return n=es.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,!0;if(0===s.avail_in)break}}return!0},_s.prototype.onData=function(e){this.chunks.push(e)},_s.prototype.onEnd=function(e){e===ns&&(\"string\"===this.options.to?this.result=this.chunks.join(\"\"):this.result=Je(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ds={Inflate:_s,inflate:cs,inflateRaw:function(e,t){return(t=t||{}).raw=!0,cs(e,t)},ungzip:cs,constants:J};const{Deflate:ms,deflate:gs,deflateRaw:Ss,gzip:ps}=dt,{Inflate:fs,inflate:Rs,inflateRaw:Es,ungzip:ys}=ds;var bs={Deflate:ms,deflate:gs,deflateRaw:Ss,gzip:ps,Inflate:fs,inflate:Rs,inflateRaw:Es,ungzip:ys,constants:J};const As=Symbol(),Os=Symbol(),Is=2147483647,ws=32767,Ts=255;class SFSDataSerializer{constructor(e){if(e!==Os)throw\"SFSDataSerializer is a singleton class; you cannot instantiate it\"}static get instance(){return this[As]||(this[As]=new SFSDataSerializer(Os)),Object.seal(this[As])}object2binary(e){const t=new n(new ArrayBuffer(0),0,n.BIG_ENDIAN);return t.writeInt8(Us.SFS_OBJECT),t.writeInt16(e.size()),this.obj2bin(e,t),new Uint8Array(t.buffer)}obj2bin(e,t){for(let s of e.keys()){const i=e.getWrappedItem(s);this.encodeSFSObjectKey(t,s),this.encodeObject(t,i)}}array2binary(e){const t=new n(new ArrayBuffer(0),0,n.BIG_ENDIAN);return t.writeInt8(Us.SFS_ARRAY),t.writeInt16(e.size()),this.arr2bin(e,t),new Uint8Array(t.buffer)}arr2bin(e,t){for(let s=0;s<e.size();s++){const i=e.getWrappedItem(s);this.encodeObject(t,i)}}encodeSFSObjectKey(e,t){const s=new TextEncoder(\"utf-8\").encode(t),i=s.length;if(i>255)throw new SFSError(\"Object key size: \"+i+\" bytes; expected max 255 bytes\");e.writeUint8(i),e.writeUint8Array(s)}encodeObject(e,t){const s=t.type;if(s===Us.NULL)this.binEncode_NULL(e,t);else if(s===Us.BOOL)this.binEncode_BOOL(e,t);else if(s===Us.BOOL_ARRAY)this.binEncode_BOOL_ARRAY(e,t);else if(s===Us.BYTE)this.binEncode_BYTE(e,t);else if(s===Us.BYTE_ARRAY)this.binEncode_BYTE_ARRAY(e,t);else if(s===Us.SHORT)this.binEncode_SHORT(e,t);else if(s===Us.SHORT_ARRAY)this.binEncode_SHORT_ARRAY(e,t);else if(s===Us.INT)this.binEncode_INT(e,t);else if(s===Us.INT_ARRAY)this.binEncode_INT_ARRAY(e,t);else if(s===Us.LONG)this.binEncode_LONG(e,t);else if(s===Us.LONG_ARRAY)this.binEncode_LONG_ARRAY(e,t);else if(s===Us.FLOAT)this.binEncode_FLOAT(e,t);else if(s===Us.FLOAT_ARRAY)this.binEncode_FLOAT_ARRAY(e,t);else if(s===Us.DOUBLE)this.binEncode_DOUBLE(e,t);else if(s===Us.DOUBLE_ARRAY)this.binEncode_DOUBLE_ARRAY(e,t);else if(s===Us.SHORT_STRING)this.binEncode_SHORT_STRING(e,t);else if(s===Us.STRING)this.binEncode_STRING(e,t);else if(s===Us.TEXT)this.binEncode_TEXT(e,t);else if(s===Us.VECTOR2)this.binEncode_VECTOR2(e,t);else if(s===Us.VECTOR3)this.binEncode_VECTOR3(e,t);else if(s===Us.STRING_ARRAY)this.binEncode_STRING_ARRAY(e,t);else if(s===Us.SHORT_STRING_ARRAY)this.binEncode_SHORT_STRING_ARRAY(e,t);else if(s===Us.VECTOR2_ARRAY)this.binEncode_VECTOR2_ARRAY(e,t);else if(s===Us.VECTOR3_ARRAY)this.binEncode_VECTOR3_ARRAY(e,t);else if(s===Us.SFS_ARRAY)e.writeUint8Array(this.array2binary(t.value));else{if(s!==Us.SFS_OBJECT)throw\"Unknow SFSDataType ID: \"+s;e.writeUint8Array(this.object2binary(t.value))}return e}binEncode_NULL(e,t){e.writeUint8(t.type)}binEncode_BOOL(e,t){e.writeUint8(t.type),e.writeUint8(t.value?1:0)}binEncode_BOOL_ARRAY(e,t){const s=t.value;this.checkCollectionSize(s),e.writeUint8(t.type),e.writeUint16(s.length);for(let t=0;t<s.length;t++)e.writeUint8(s[t]?1:0)}binEncode_BYTE(e,t){e.writeUint8(t.type),e.writeUint8(t.value)}binEncode_BYTE_ARRAY(e,t){const s=t.value;if(s.length>Is)throw new Error(\"Byte array limit is \"+Is+\" elements. Found: \"+s.length);e.writeUint8(t.type),e.writeUint32(s.length),e.writeUint8Array(s)}binEncode_SHORT(e,t){e.writeUint8(t.type),e.writeUint16(t.value)}binEncode_SHORT_ARRAY(e,t){const s=t.value;this.checkCollectionSize(s),e.writeUint8(t.type),e.writeUint16(s.length);for(let t=0;t<s.length;t++)e.writeUint16(s[t])}binEncode_INT(e,t){e.writeUint8(t.type),e.writeUint32(t.value)}binEncode_INT_ARRAY(e,t){const s=t.value;this.checkCollectionSize(s),e.writeUint8(t.type),e.writeUint16(s.length);for(var i=0;i<s.length;i++)e.writeUint32(s[i])}binEncode_LONG(e,t){const s=t.value;let i=s<0?(1n<<64n)+s:s;const r=new Uint8Array(8);for(let e=7;e>=0;e--)r[e]=Number(0xFFn&i),i>>=8n;e.writeUint8(t.type),e.writeUint8Array(r)}binEncode_LONG_ARRAY(e,t){const s=t.value;this.checkCollectionSize(s),e.writeUint8(t.type),e.writeUint16(s.length);for(let t=0;t<s.length;t++){const i=s[t];let r=i<0?(1n<<64n)+i:i;const n=new Uint8Array(8);for(let e=7;e>=0;e--)n[e]=Number(0xFFn&r),r>>=8n;e.writeUint8Array(n)}}binEncode_FLOAT(e,t){e.writeUint8(t.type),e.writeFloat32(t.value)}binEncode_FLOAT_ARRAY(e,t){const s=t.value;this.checkCollectionSize(s),e.writeUint8(t.type),e.writeUint16(s.length);for(let t=0;t<s.length;t++)e.writeFloat32(s[t])}binEncode_DOUBLE(e,t){e.writeUint8(t.type),e.writeFloat64(t.value)}binEncode_DOUBLE_ARRAY(e,t){const s=t.value;this.checkCollectionSize(s),e.writeUint8(t.type),e.writeUint16(s.length);for(let t=0;t<s.length;t++)e.writeFloat64(s[t])}binEncode_SHORT_STRING(e,t){const s=new TextEncoder(\"utf-8\").encode(t.value);if(s.length>Ts)throw new Error(\"Short string element exceeds max size: \"+s.length+\"; limit is: \"+Ts);e.writeUint8(t.type),e.writeUint8(s.length),e.writeUint8Array(s)}binEncode_STRING(e,t){const s=new TextEncoder(\"utf-8\").encode(t.value);if(s.length>ws)throw new Error(\"String element exceeds max size: \"+s.length+\"; limit is: \"+ws);e.writeUint8(t.type),e.writeUint16(s.length),e.writeUint8Array(s)}binEncode_TEXT(e,t){const s=new TextEncoder(\"utf-8\").encode(t.value);if(s.length>Is)throw new Error(\"Text element exceeds max size: \"+s.length+\"; limit is: \"+Is);e.writeUint8(t.type),e.writeUint32(s.length),e.writeUint8Array(s)}binEncode_VECTOR2(e,t){e.writeUint8(t.type),e.writeFloat32(t.value.x),e.writeFloat32(t.value.y)}binEncode_VECTOR3(e,t){e.writeUint8(t.type),e.writeFloat32(t.value.x),e.writeFloat32(t.value.y),e.writeFloat32(t.value.z)}binEncode_SHORT_STRING_ARRAY(e,t){const s=t.value;this.checkCollectionSize(s),e.writeUint8(t.type),e.writeUint16(s.length);for(let t=0;t<s.length;t++){const i=new TextEncoder(\"utf-8\").encode(s[t]);if(i.length>Ts)throw new Error(\"Short string element exceeds max size: \"+i.length+\"; limit is: \"+Ts);e.writeUint8(i.length),e.writeUint8Array(i)}}binEncode_STRING_ARRAY(e,t){const s=t.value;this.checkCollectionSize(s),e.writeUint8(t.type),e.writeUint16(s.length);for(let t=0;t<s.length;t++){const i=new TextEncoder(\"utf-8\").encode(s[t]);if(i.length>ws)throw new Error(\"String element exceeds max size: \"+i.length+\"; limit is: \"+ws);e.writeUint16(i.length),e.writeUint8Array(i)}}binEncode_VECTOR2_ARRAY(e,t){const s=t.value;this.checkCollectionSize(s),e.writeUint8(t.type),e.writeUint16(s.length);for(let t=0;t<s.length;t++)e.writeFloat32(s[t].x),e.writeFloat32(s[t].y)}binEncode_VECTOR3_ARRAY(e,t){const s=t.value;this.checkCollectionSize(s),e.writeUint8(t.type),e.writeUint16(s.length);for(let t=0;t<s.length;t++)e.writeFloat32(s[t].x),e.writeFloat32(s[t].y),e.writeFloat32(s[t].z)}checkCollectionSize(e){if(e.length>ws)throw new Error(\"Array limit is 32767 elements. Found: \"+e.length)}binary2object(e){if(e.byteLength<3)throw\"Cannot decode an SFSObject. Byte data is insufficient. Size: \"+e.byteLength+\" bytes\";return this.decodeSFSObject(new n(e,0,n.BIG_ENDIAN))}binary2array(e){if(e.byteLength<3)throw\"Cannot decode an SFSArray. Byte data is insufficient. Size: \"+e.byteLength+\" bytes\";return this.decodeSFSArray(new n(e,0,n.BIG_ENDIAN))}decodeSFSObject(e){const t=new SFSObject,s=e.readUint8();if(s!==Us.SFS_OBJECT)throw\"Invalid SFSDataType. Expected: \"+Us.SFS_OBJECT+\", found: \"+s;const i=e.readUint16();if(i<0)throw\"Cannot decode SFSObject. Size is negative: \"+i;try{for(let s=0;s<i;s++){const s=e.readUint8();if(s<0||s>255)throw\"Invalid SFSObject key length. Found: \"+s;const i=e.readUint8Array(s),r=new TextDecoder(\"utf-8\").decode(i),n=this.decodeObject(e);if(null==n)throw\"Could not decode value for key: \"+r;t.put(r,n.value,n.type,!0)}}catch(e){throw e}return t}decodeSFSArray(e){const t=new SFSArray,s=e.readUint8();if(s!==Us.SFS_ARRAY)throw\"Invalid SFSDataType. Expected: \"+Us.SFS_ARRAY+\", found: \"+s;const i=e.readInt16();if(i<0)throw\"Cannot decode SFSArray. Size is negative: \"+i;try{for(let s=0;s<i;s++){const i=this.decodeObject(e);if(null==i)throw\"Could not decode value for index: \"+s;t.add(i.value,i.type,!0)}}catch(e){throw e}return t}decodeObject(e){let t=null;const s=e.readUint8();if(s===Us.NULL)t=this.binDecode_NULL(e);else if(s===Us.BOOL)t=this.binDecode_BOOL(e);else if(s===Us.BOOL_ARRAY)t=this.binDecode_BOOL_ARRAY(e);else if(s===Us.BYTE)t=this.binDecode_BYTE(e);else if(s===Us.BYTE_ARRAY)t=this.binDecode_BYTE_ARRAY(e);else if(s===Us.SHORT)t=this.binDecode_SHORT(e);else if(s===Us.SHORT_ARRAY)t=this.binDecode_SHORT_ARRAY(e);else if(s===Us.INT)t=this.binDecode_INT(e);else if(s===Us.INT_ARRAY)t=this.binDecode_INT_ARRAY(e);else if(s===Us.LONG)t=this.binDecode_LONG(e);else if(s===Us.LONG_ARRAY)t=this.binDecode_LONG_ARRAY(e);else if(s===Us.FLOAT)t=this.binDecode_FLOAT(e);else if(s===Us.FLOAT_ARRAY)t=this.binDecode_FLOAT_ARRAY(e);else if(s===Us.DOUBLE)t=this.binDecode_DOUBLE(e);else if(s===Us.DOUBLE_ARRAY)t=this.binDecode_DOUBLE_ARRAY(e);else if(s===Us.SHORT_STRING)t=this.binDecode_SHORT_STRING(e);else if(s===Us.SHORT_STRING_ARRAY)t=this.binDecode_SHORT_STRING_ARRAY(e);else if(s===Us.STRING)t=this.binDecode_STRING(e);else if(s===Us.STRING_ARRAY)t=this.binDecode_STRING_ARRAY(e);else if(s===Us.TEXT)t=this.binDecode_TEXT(e);else if(s===Us.VECTOR2)t=this.binDecode_VECTOR2(e);else if(s===Us.VECTOR3)t=this.binDecode_VECTOR3(e);else if(s===Us.VECTOR2_ARRAY)t=this.binDecode_VECTOR2_ARRAY(e);else if(s===Us.VECTOR3_ARRAY)t=this.binDecode_VECTOR3_ARRAY(e);else if(s===Us.SFS_ARRAY){e.seek(e.position-1);const i=this.decodeSFSArray(e);t=new SFSDataWrapper(s,i)}else{if(s!==Us.SFS_OBJECT)throw\"Unknow SFSDataType ID: \"+s;{e.seek(e.position-1);const i=this.decodeSFSObject(e);t=new SFSDataWrapper(s,i)}}return t}binDecode_NULL(e){return new SFSDataWrapper(Us.NULL,null)}binDecode_BOOL(e){const t=e.readUint8();let s=null;if(0===t)s=!1;else{if(1!==t)throw\"Error decoding Bool type. Illegal value: \"+t;s=!0}return new SFSDataWrapper(Us.BOOL,s)}binDecode_BOOL_ARRAY(e){const t=this.getTypedArraySize(e),s=[];for(let i=0;i<t;i++){const t=e.readUint8();let i=null;if(0===t)i=!1;else{if(1!==t)throw\"Error decoding Bool type. Illegal value: \"+t;i=!0}s.push(i)}return new SFSDataWrapper(Us.BOOL_ARRAY,s)}binDecode_BYTE(e){const t=e.readUint8();return new SFSDataWrapper(Us.BYTE,t)}binDecode_BYTE_ARRAY(e){const t=e.readInt32();if(t<0)throw\"Error decoding typed array size. Negative size: \"+t;const s=new Uint8Array(t);for(let i=0;i<t;i++)s[i]=e.readUint8();return new SFSDataWrapper(Us.BYTE_ARRAY,s)}binDecode_SHORT(e){const t=e.readInt16();return new SFSDataWrapper(Us.SHORT,t)}binDecode_SHORT_ARRAY(e){const t=this.getTypedArraySize(e),s=[];for(let i=0;i<t;i++)s.push(e.readInt16());return new SFSDataWrapper(Us.SHORT_ARRAY,s)}binDecode_INT(e){const t=e.readInt32();return new SFSDataWrapper(Us.INT,t)}binDecode_INT_ARRAY(e){const t=this.getTypedArraySize(e),s=[];for(let i=0;i<t;i++)s.push(e.readInt32());return new SFSDataWrapper(Us.INT_ARRAY,s)}binDecode_LONG(e){const t=e.readUint8Array(8);let s,i=0n;for(let e=0;e<8;e++)i=i<<8n|BigInt(t[e]);return s=i&1n<<63n?i-(1n<<64n):i,new SFSDataWrapper(Us.LONG,s)}binDecode_LONG_ARRAY(e){const t=this.getTypedArraySize(e),s=[];for(let i=0;i<t;i++){const t=e.readUint8Array(8);let i=0n;for(let e=0;e<8;e++)i=i<<8n|BigInt(t[e]);i&1n<<63n?s.push(i-(1n<<64n)):s.push(i)}return new SFSDataWrapper(Us.LONG_ARRAY,s)}binDecode_FLOAT(e){const t=e.readFloat32();return new SFSDataWrapper(Us.FLOAT,t)}binDecode_FLOAT_ARRAY(e){const t=this.getTypedArraySize(e),s=[];for(let i=0;i<t;i++)s.push(e.readFloat32());return new SFSDataWrapper(Us.FLOAT_ARRAY,s)}binDecode_DOUBLE(e){const t=e.readFloat64();return new SFSDataWrapper(Us.DOUBLE,t)}binDecode_DOUBLE_ARRAY(e){const t=this.getTypedArraySize(e),s=[];for(let i=0;i<t;i++)s.push(e.readFloat64());return new SFSDataWrapper(Us.DOUBLE_ARRAY,s)}binDecode_SHORT_STRING(e){const t=e.readUint8();if(t<0)throw\"Error decoding SHORT_STRING. Negative size: \"+t;const s=e.readUint8Array(t),i=new TextDecoder(\"utf-8\").decode(s);return new SFSDataWrapper(Us.SHORT_STRING,i)}binDecode_SHORT_STRING_ARRAY(e){const t=this.getTypedArraySize(e),s=[];for(let i=0;i<t;i++){const t=e.readUint8();if(t<0)throw\"Error decoding STRING. Negative size: \"+t;const i=e.readUint8Array(t),r=new TextDecoder(\"utf-8\").decode(i);s.push(r)}return new SFSDataWrapper(Us.SHORT_STRING_ARRAY,s)}binDecode_STRING(e){const t=e.readInt16();if(t<0)throw\"Error decoding STRING. Negative size: \"+t;const s=e.readUint8Array(t),i=new TextDecoder(\"utf-8\").decode(s);return new SFSDataWrapper(Us.STRING,i)}binDecode_STRING_ARRAY(e){const t=this.getTypedArraySize(e),s=[];for(let i=0;i<t;i++){const t=e.readInt16();if(t<0)throw\"Error decoding STRING. Negative size: \"+t;const i=e.readUint8Array(t),r=new TextDecoder(\"utf-8\").decode(i);s.push(r)}return new SFSDataWrapper(Us.STRING_ARRAY,s)}binDecode_TEXT(e){const t=e.readInt32();if(t<0)throw\"Error decoding TEXT. Negative size: \"+t;const s=e.readUint8Array(t),i=new TextDecoder(\"utf-8\").decode(s);return new SFSDataWrapper(Us.TEXT,i)}binDecode_VECTOR2(e){let t=new SFSVector2(e.readFloat32(),e.readFloat32());return new SFSDataWrapper(Us.VECTOR2,t)}binDecode_VECTOR3(e){let t=new SFSVector3(e.readFloat32(),e.readFloat32(),e.readFloat32());return new SFSDataWrapper(Us.VECTOR3,t)}binDecode_VECTOR2_ARRAY(e){const t=this.getTypedArraySize(e),s=[];for(let i=0;i<t;i++)s.push(new SFSVector2(e.readFloat32(),e.readFloat32()));return new SFSDataWrapper(Us.VECTOR2_ARRAY,s)}binDecode_VECTOR3_ARRAY(e){const t=this.getTypedArraySize(e),s=[];for(let i=0;i<t;i++)s.push(new SFSVector3(e.readFloat32(),e.readFloat32(),e.readFloat32()));return new SFSDataWrapper(Us.VECTOR3_ARRAY,s)}getTypedArraySize(e){const t=e.readUint16();if(t<0)throw\"Error decoding typed array size. Negative size: \"+t;return t}}const Ms=Object.freeze({IDLE:\"Idle\",KICKED:\"Kicked\",BANNED:\"Banned\",MANUAL:\"Manual\",RECONNECTION_FAILURE:\"Reconnection failure\",UNKNOWN:\"Unknown\",getReason(e){switch(e){case 0:return this.IDLE;case 1:return this.KICKED;case 2:return this.BANNED;case 3:return this.MANUAL;case 4:return this.UNKNOWN}}});class DumpFormatter{static MAX_ARRAY_DUMP_SIZE=10;static MAX_STRING_DUMP_SIZE=50;static TOKEN_INDENT_OPEN=String.fromCharCode(17);static TOKEN_INDENT_CLOSE=String.fromCharCode(18);static TOKEN_DIVIDER=String.fromCharCode(19);static NEW_LINE=\"\\n\";static TAB=\"\\t\";static DOT=\".\";static HEX_BYTES_PER_LINE=16;static prettyPrintByteArray(e){return null==e?\"Null\":\"Byte[\"+e.length+\"]\"}static prettyPrintCollection(e,t){if(null==e)return\"Null\";if(e.length>this.MAX_ARRAY_DUMP_SIZE)return`${Us.fromId(t)}[${e.length}]`;return`[${e.map(e=>null!=e?e.toString():\"null\").join(\", \")}]`}static prettyPrintString(e){if(null==e)return\"null\";const t=e.length;return t<=this.MAX_STRING_DUMP_SIZE?e:`${e.slice(0,this.MAX_STRING_DUMP_SIZE)} [..+${t-this.MAX_STRING_DUMP_SIZE}]`}static formattedValue(e){const t=e.type;var s=e.value;switch(t){case Us.SFS_OBJECT:case Us.SFS_ARRAY:return s.getDump(!1);case Us.BYTE_ARRAY:return this.prettyPrintByteArray(s);case Us.BOOL_ARRAY:case Us.SHORT_ARRAY:case Us.INT_ARRAY:case Us.LONG_ARRAY:case Us.FLOAT_ARRAY:case Us.DOUBLE_ARRAY:case Us.SHORT_STRING_ARRAY:case Us.STRING_ARRAY:case Us.VECTOR2_ARRAY:case Us.VECTOR3_ARRAY:return this.prettyPrintCollection(s,t);case Us.STRING:case Us.SHORT_STRING:case Us.TEXT:return this.prettyPrintString(s);default:return null!=s?s.toString():\"null\"}}static prettyPrintDump(e){let t=\"\",s=0;for(let i=0;i<e.length;i++){const r=e.charAt(i);if(r==this.TOKEN_INDENT_OPEN)s++,t+=this.NEW_LINE+this.getFormatTabs(s);else if(r==this.TOKEN_INDENT_CLOSE){if(s--,s<0)throw\"Unbalanced dump tokens: indentPos is negative\"}else r==this.TOKEN_DIVIDER?t+=this.NEW_LINE+this.getFormatTabs(s):t+=r}if(0!=s)throw\"Unbalanced dump tokens: indentPos should be zero\";return t}static getFormatTabs(e){return this.strFill(this.TAB,e)}static strFill(e,t){let s=\"\";for(let i=0;i<t;i++)s+=e;return s}static hexDump(e,t=-1){-1===t&&(t=this.HEX_BYTES_PER_LINE);let s=\"Binary size: \"+e.byteLength+this.NEW_LINE,i=\"\",r=\"\",n=0,a=0,o=null,h=null;do{h=e[n];let l=h.toString(16).toUpperCase();1===l.length&&(l=\"0\"+l),i+=l+\" \",o=h>=33&&h<=126?String.fromCharCode(h):this.DOT,r+=o,++a===t&&(a=0,s+=i+this.TAB+r+this.NEW_LINE,i=\"\",r=\"\")}while(++n<e.length);if(0!==a){for(let e=t-a;e>0;--e)i+=\"   \",r+=\" \";s+=i+this.TAB+r+this.NEW_LINE}return s}}const vs=Object.freeze({DEBUG:0,INFO:1,WARN:2,ERROR:3,toString(e){return e===this.DEBUG?\"DEBUG\":e===this.INFO?\"INFO\":e===this.WARN?\"WARN\":e===this.ERROR?\"ERROR\":void 0}});class Logger{static level=1;static showTime=!0;static showOrigin=!0;static getInstance(e){return Object.seal(new Logger(e))}constructor(e){this.className=e}set level(e){this._isValidLevel(e)&&(Logger.level=e)}get level(){return Logger.level}set showTime(e){Logger.showTime=e}get showTime(){return Logger.showTime}set showOrigin(e){Logger.showOrigin=e}get showOrigin(){return Logger.showOrigin}debug(...e){this.log(vs.DEBUG,e)}info(...e){this.log(vs.INFO,e)}warn(...e){this.log(vs.WARN,e)}error(...e){this.log(vs.ERROR,e)}log(e,...t){if(this._isValidLevel(e)&&e>=Logger.level){let i=\"\";if(Logger.showTime){var s=new Date;let e=\"\";e=(\"0\"+s.getHours()).slice(-2)+\":\"+(\"0\"+s.getMinutes()).slice(-2)+\":\"+(\"0\"+s.getSeconds()).slice(-2)+\".\"+(\"00\"+s.getMilliseconds()).slice(-3),i+=e+\" \"}i+=`[SFS ${vs.toString(e)}] `,Logger.showOrigin&&null!=this.className&&\"\"!=this.className&&(i+=`${this.className} -- `),i+=t.join(\" \"),console[vs.toString(e).toLowerCase()](i)}}get isDebugEnabled(){return Logger.level<=vs.DEBUG}_isValidLevel(e){if(!Number.isInteger(e)||e<vs.DEBUG||e>vs.ERROR)throw\"Logging level must be set to a valid value (see LogLevel class)\";return!0}}const Ns=Object.freeze({OFF:0,PACKET:1,PROTOCOL:2}),Us=Object.freeze({NULL:0,BOOL:1,BYTE:2,SHORT:3,INT:4,LONG:5,FLOAT:6,DOUBLE:7,STRING:8,BOOL_ARRAY:9,BYTE_ARRAY:10,SHORT_ARRAY:11,INT_ARRAY:12,LONG_ARRAY:13,FLOAT_ARRAY:14,DOUBLE_ARRAY:15,STRING_ARRAY:16,SFS_ARRAY:17,SFS_OBJECT:18,SHORT_STRING:19,TEXT:20,SHORT_STRING_ARRAY:21,VECTOR2:22,VECTOR3:23,VECTOR2_ARRAY:24,VECTOR3_ARRAY:25,fromId(e){if(\"number\"!=typeof e)return null;for(let t in this)if(this.hasOwnProperty(t)&&this[t]===e)return t},validate(e,t){if(null==this.fromId(e))throw new SFSTypeError(\"Invalid type passed; use one of the SFSDataType constants\");let s=null;if(e===this.NULL&&null!=t&&(s=\"a null value\"),e!==this.NULL&&null==t&&(s=\"a non-null value\"),e!==this.BOOL||this.isBoolType(t)||(s=\"a boolean value\"),e!==this.BYTE||this.isByteType(t)||(s=\"an integer number in this range: 0 <= value < 256\"),e!==this.SHORT||this.isShortType(t)||(s=\"an integer number in this range: -32.768 <= value < +32.768\"),e!==this.INT||this.isIntType(t)||(s=\"an integer number in this range: -2^31 <= value < +2^31\"),e!==this.LONG||this.isLongType(t)||(s=\"an integer number in this range: -(2^63) <= value <= +(2^63 - 1)\"),e!==this.FLOAT||this.isFloatType(t)||(s=\"a number in this range: -3.4028234663852886e+38 <= value <= 3.4028234663852886e+38\"),e!==this.DOUBLE||this.isDoubleType(t)||(s=\"a finite number\"),e!==this.SHORT_STRING&&e!==this.STRING&&e!==this.TEXT||this.isStringType(t)||(s=\"a string value\"),e!==this.BOOL_ARRAY||this.isArrayType(t,this.isBoolType)||(s=\"an array of boolean values\"),e!==this.BYTE_ARRAY||t instanceof Uint8Array||(s=\"a Uint8Array\"),e!==this.SHORT_ARRAY||this.isArrayType(t,this.isShortType)||(s=\"an array of integer numbers in this range: -32.768 <= value < +32.768\"),e!==this.INT_ARRAY||this.isArrayType(t,this.isIntType)||(s=\"an array of integer numbers in this range: -2^31 <= value < +2^31\"),e!==this.LONG_ARRAY||this.isArrayType(t,this.isLongType)||(s=\"an array of integer numbers in this range: -(2^63) <= value <= +(2^63 - 1)\"),e!==this.FLOAT_ARRAY||this.isArrayType(t,this.isFloatType)||(s=\"an array of numbers in this range: -3.4028234663852886e+38 <= value <= 3.4028234663852886e+38\"),e!==this.DOUBLE_ARRAY||this.isArrayType(t,this.isDoubleType)||(s=\"an array of finite numbers\"),e!==this.SHORT_STRING_ARRAY&&e!==this.STRING_ARRAY||this.isArrayType(t,this.isStringType)||(s=\"an array of string values\"),e!==this.SFS_OBJECT||t instanceof SFSObject||(s=\"a SFSObject instance\"),e!==this.SFS_ARRAY||t instanceof SFSArray||(s=\"a SFSArray instance\"),e!==this.VECTOR2||t instanceof SFSVector2||(s=\"a SFSVector2 instance\"),e!==this.VECTOR3||t instanceof SFSVector3||(s=\"a SFSVector3 instance\"),null!=s)throw new SFSTypeError(\"Invalid value passed; type SFSDataType.\"+this.fromId(e)+\" requires \"+s)},isBoolType:e=>\"boolean\"==typeof e,isByteType:e=>\"number\"==typeof e&&Math.floor(e)===e&&e>=0&&e<256,isShortType:e=>\"number\"==typeof e&&Math.floor(e)===e&&e>=-32768&&e<32768,isIntType:e=>\"number\"==typeof e&&Math.floor(e)===e&&e>=-2147483648&&e<2147483648,isLongType:e=>\"bigint\"==typeof e&&e>=-9223372036854775808n&&e<=9223372036854775807n,isFloatType:e=>\"number\"==typeof e&&e>=-34028234663852886e22&&e<=34028234663852886e22,isDoubleType:e=>\"number\"==typeof e&&isFinite(e),isStringType:e=>\"string\"==typeof e,isArrayType:(e,t)=>e instanceof Array&&(!(e.length>0)||t(e[0]))});class SFSDataWrapper{constructor(e,t){this.type=e,this.value=t,Object.freeze(this)}}class SFSObject{constructor(){this._dataHolder=new Map,this._serializer=SFSDataSerializer.instance,Object.freeze(this)}keys(){return this._dataHolder.keys()}getWrappedItem(e){return this._dataHolder.get(e)}static newFromBinaryData(e){return SFSDataSerializer.instance.binary2object(e)}toBinary(){return this._serializer.object2binary(this)}getKeys(){return Array.from(this.keys())}size(){return this._dataHolder.size}containsKey(e){return null!=this.getWrappedItem(e)}get(e,t=null){const s=this.getWrappedItem(e);if(null!=s&&null!=t)if(Array.isArray(t)){if(!t.includes(s.type))throw new SFSTypeError(\"Requested value is not of type among the following ones: \"+t.map(e=>Us.fromId(e)).join(\", \"))}else if(s.type!=t)throw new SFSTypeError(\"Requested value is not of type \"+Us.fromId(t));return null!=s?s.value:null}removeElement(e){this._dataHolder.delete(e)}isNull(e){const t=this.getWrappedItem(e);return null==t||t.type==Us.NULL}getBool(e){return this.get(e,Us.BOOL)}getNumber(e){const t=this.get(e,[Us.BYTE,Us.SHORT,Us.INT,Us.LONG,Us.FLOAT,Us.DOUBLE]);return null!=t&&\"bigint\"==typeof t?Number(t):t}getBigInt(e){return this.get(e,[Us.LONG])}getString(e){return this.get(e,[Us.SHORT_STRING,Us.STRING,Us.TEXT])}getBoolArray(e){return this.get(e,Us.BOOL_ARRAY)}getNumberArray(e){const t=this.get(e,[Us.BYTE_ARRAY,Us.SHORT_ARRAY,Us.INT_ARRAY,Us.LONG_ARRAY,Us.FLOAT_ARRAY,Us.DOUBLE_ARRAY]);return null!=t&&t.length>0&&\"bigint\"==typeof t[0]?t.map(Number):t}getBigIntArray(e){return this.get(e,[Us.LONG_ARRAY])}getStringArray(e){return this.get(e,[Us.SHORT_STRING_ARRAY,Us.STRING_ARRAY])}getSFSObject(e){return this.get(e,Us.SFS_OBJECT)}getSFSArray(e){return this.get(e,Us.SFS_ARRAY)}getVector2(e){return this.get(e,Us.VECTOR2)}getVector3(e){return this.get(e,Us.VECTOR3)}getVector2Array(e){return this.get(e,Us.VECTOR2_ARRAY)}getVector3Array(e){return this.get(e,Us.VECTOR3_ARRAY)}put(e,t,s,i=!1){if(!i){if(\"string\"!=typeof e)throw\"Invalid key passed; must be of type string\";Us.validate(s,t)}this._dataHolder.set(e,new SFSDataWrapper(s,t))}putNull(e){this.put(e,null,Us.NULL)}putBool(e,t){this.put(e,t,Us.BOOL)}putByte(e,t){this.put(e,t,Us.BYTE)}putShort(e,t){this.put(e,t,Us.SHORT)}putInt(e,t){this.put(e,t,Us.INT)}putLong(e,t){\"bigint\"!=typeof t&&(t=BigInt(t)),this.put(e,t,Us.LONG)}putFloat(e,t){this.put(e,t,Us.FLOAT)}putDouble(e,t){this.put(e,t,Us.DOUBLE)}putShortString(e,t){this.put(e,t,Us.SHORT_STRING)}putString(e,t){this.put(e,t,Us.STRING)}putText(e,t){this.put(e,t,Us.TEXT)}putBoolArray(e,t){this.put(e,t,Us.BOOL_ARRAY)}putByteArray(e,t){this.put(e,t,Us.BYTE_ARRAY)}putShortArray(e,t){this.put(e,t,Us.SHORT_ARRAY)}putIntArray(e,t){this.put(e,t,Us.INT_ARRAY)}putLongArray(e,t){null!=t&&(t=t.map(BigInt)),this.put(e,t,Us.LONG_ARRAY)}putFloatArray(e,t){this.put(e,t,Us.FLOAT_ARRAY)}putDoubleArray(e,t){this.put(e,t,Us.DOUBLE_ARRAY)}putShortStringArray(e,t){this.put(e,t,Us.SHORT_STRING_ARRAY)}putStringArray(e,t){this.put(e,t,Us.STRING_ARRAY)}putSFSArray(e,t){this.put(e,t,Us.SFS_ARRAY)}putSFSObject(e,t){this.put(e,t,Us.SFS_OBJECT)}putVector2(e,t){this.put(e,t,Us.VECTOR2)}putVector3(e,t){this.put(e,t,Us.VECTOR3)}putVector2Array(e,t){this.put(e,t,Us.VECTOR2_ARRAY)}putVector3Array(e,t){this.put(e,t,Us.VECTOR3_ARRAY)}getDump(e=!0){return 0===this.size()?\"[ Empty SFSObject ]\":e?DumpFormatter.prettyPrintDump(this._dump()):this._dump()}getHexDump(){return DumpFormatter.hexDump(this.toBinary())}_dump(){let e=DumpFormatter.TOKEN_INDENT_OPEN;for(let t of this.keys()){const s=this.getWrappedItem(t);e+=`(${Us.fromId(s.type).toLowerCase()}) ${t}: `,e+=DumpFormatter.formattedValue(s),e+=DumpFormatter.TOKEN_DIVIDER}return this.size()>0&&(e=e.substring(0,e.length-1)),e+=DumpFormatter.TOKEN_INDENT_CLOSE,e}}class SFSArray{constructor(){this._dataHolder=[],this._serializer=SFSDataSerializer.instance,Object.freeze(this)}getWrappedItem(e){return\"number\"!=typeof e||e>=this._dataHolder.length?null:this._dataHolder[e]}static newFromBinaryData(e){return SFSDataSerializer.instance.binary2array(e)}toBinary(){return this._serializer.array2binary(this)}size(){return this._dataHolder.length}contains(e){if(e instanceof SFSArray||e instanceof SFSObject)throw new Exceptions_SFSError(\"SFSArray and SFSObject types are not supported by the SFSArray.contains method\");for(let t=0;t<this.size();t++){const s=this.getWrappedItem(t);if(null!=s)if(\"function\"==typeof s.value.equals){if(s.value.equals(e))return!0}else if(s.value==e)return!0}return!1}get(e,t=null){if(\"number\"!=typeof e||e>=this._dataHolder.length)return null;const s=this.getWrappedItem(e);if(null!=s&&null!=t)if(Array.isArray(t)){if(!t.includes(s.type))throw new SFSTypeError(\"Requested value is not of type among the following ones: \"+t.map(e=>Us.fromId(e)).join(\", \"))}else if(s.type!=t)throw new SFSTypeError(\"Requested value is not of type \"+Us.fromId(t));return null!=s?s.value:null}getElementAt(e){return this.get(e)}removeElementAt(e){const t=this._dataHolder.splice(e,1);return t.length>0?t[0].value:null}isNull(e){const t=this.getWrappedItem(e);return null==t||t.type==Us.NULL}getBool(e){return this.get(e,Us.BOOL)}getNumber(e){const t=this.get(e,[Us.BYTE,Us.SHORT,Us.INT,Us.LONG,Us.FLOAT,Us.DOUBLE]);return null!=t&&\"bigint\"==typeof t?Number(t):t}getBigInt(e){return this.get(e,[Us.LONG])}getString(e){return this.get(e,[Us.SHORT_STRING,Us.STRING,Us.TEXT])}getBoolArray(e){return this.get(e,Us.BOOL_ARRAY)}getNumberArray(e){const t=this.get(e,[Us.BYTE_ARRAY,Us.SHORT_ARRAY,Us.INT_ARRAY,Us.LONG_ARRAY,Us.FLOAT_ARRAY,Us.DOUBLE_ARRAY]);return null!=t&&t.length>0&&\"bigint\"==typeof t[0]?t.map(Number):t}getBigIntArray(e){return this.get(e,[Us.LONG_ARRAY])}getStringArray(e){return this.get(e,[Us.SHORT_STRING_ARRAY,Us.STRING_ARRAY])}getSFSObject(e){return this.get(e,Us.SFS_OBJECT)}getSFSArray(e){return this.get(e,Us.SFS_ARRAY)}getVector2(e){return this.get(e,Us.VECTOR2)}getVector3(e){return this.get(e,Us.VECTOR3)}getVector2Array(e){return this.get(e,Us.VECTOR2_ARRAY)}getVector3Array(e){return this.get(e,Us.VECTOR3_ARRAY)}add(e,t,s=!1){s||Us.validate(t,e),this._dataHolder.push(new SFSDataWrapper(t,e))}addNull(){this.add(null,Us.NULL)}addBool(e){this.add(e,Us.BOOL)}addByte(e){this.add(e,Us.BYTE)}addShort(e){this.add(e,Us.SHORT)}addInt(e){this.add(e,Us.INT)}addLong(e){\"bigint\"!=typeof e&&(e=BigInt(e)),this.add(e,Us.LONG)}addFloat(e){this.add(e,Us.FLOAT)}addDouble(e){this.add(e,Us.DOUBLE)}addShortString(e){this.add(e,Us.SHORT_STRING)}addString(e){this.add(e,Us.STRING)}addText(e){this.add(e,Us.TEXT)}addBoolArray(e){this.add(e,Us.BOOL_ARRAY)}addByteArray(e){this.add(e,Us.BYTE_ARRAY)}addShortArray(e){this.add(e,Us.SHORT_ARRAY)}addIntArray(e){this.add(e,Us.INT_ARRAY)}addLongArray(e){null!=e&&(e=e.map(BigInt)),this.add(e,Us.LONG_ARRAY)}addFloatArray(e){this.add(e,Us.FLOAT_ARRAY)}addDoubleArray(e){this.add(e,Us.DOUBLE_ARRAY)}addShortStringArray(e){this.add(e,Us.SHORT_STRING_ARRAY)}addStringArray(e){this.add(e,Us.STRING_ARRAY)}addVector2Array(e){this.add(e,Us.VECTOR2_ARRAY)}addVector3Array(e){this.add(e,Us.VECTOR3_ARRAY)}addSFSArray(e){this.add(e,Us.SFS_ARRAY)}addSFSObject(e){this.add(e,Us.SFS_OBJECT)}addVector2(e){this.add(e,Us.VECTOR2)}addVector3(e){this.add(e,Us.VECTOR3)}getDump(e=!0){return 0===this.size()?\"[ Empty SFSArray ]\":e?DumpFormatter.prettyPrintDump(this._dump()):this._dump()}getHexDump(){return DumpFormatter.hexDump(this.toBinary())}_dump(){let e=DumpFormatter.TOKEN_INDENT_OPEN;for(let t=0;t<this.size();t++){const s=this.getWrappedItem(t);e+=`(${Us.fromId(s.type).toLowerCase()}) ${t}: `,e+=DumpFormatter.formattedValue(s),e+=DumpFormatter.TOKEN_DIVIDER}return this.size()>0&&(e=e.substring(0,e.length-1)),e+=DumpFormatter.TOKEN_INDENT_CLOSE,e}}class Vec3D{constructor(e,t,s=0,i=!1){this.px=e,this.py=t,this.pz=s,this._useFloatCoordinates=i}get isFloat(){return this._useFloatCoordinates}toString(){return`(${this.px},${this.py},${this.pz})`}toArray(){return[this.px,this.py,this.pz]}static fromArray(e){return new Vec3D(e[0],e[1],e[2])}}class SFSVector2{static EPSILON=1e-5;constructor(e,t){this.x=e,this.y=t}get lengthSquared(){return this.x*this.x+this.y*this.y}get length(){return Math.sqrt(this.lengthSquared)}get isNormalized(){return Math.abs(this.lengthSquared-1)<SFSVector2.EPSILON}get angle(){return Math.atan2(this.y,this.x)}get aspect(){return this.x/this.y}sum(e){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");return new SFSVector2(this.x+e.x,this.y+e.y)}sub(e){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");return new SFSVector2(this.x-e.x,this.y-e.y)}mult(e){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");return new SFSVector2(this.x*e.x,this.y*e.y)}div(e){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");if(0==e.x||0==e.y)throw new Error(\"Division by zero detected\");return new SFSVector2(this.x/e.x,this.y/e.y)}normalize(){const e=this.length;return e<SFSVector2.EPSILON?new SFSVector2(0,0):new SFSVector2(this.x/e,this.y/e)}dot(e){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");return this.x*e.x+this.y*e.y}distanceTo(e){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");const t=this.x-e.x,s=this.y-e.y;return Math.sqrt(t*t+s*s)}distanceSquaredTo(e){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}abs(){return new SFSVector2(Math.abs(this.x),Math.abs(this.y))}min(e){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");return new SFSVector2(Math.min(this.x,e.x),Math.min(this.y,e.y))}max(e){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");return new SFSVector2(Math.max(this.x,e.x),Math.max(this.y,e.y))}floor(){return new SFSVector2(Math.floor(this.x),Math.floor(this.y))}ceil(){return new SFSVector2(Math.ceil(this.x),Math.ceil(this.y))}round(){return new SFSVector2(Math.round(this.x),Math.round(this.y))}lerp(e,t){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");return new SFSVector2(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)}cross(e){if(!(e instanceof SFSVector2))throw new TypeError(\"Argument must be an instance of SFSVector2\");return this.x*e.y-this.y*e.x}rotate(e){const t=Math.cos(e),s=Math.sin(e);return new SFSVector2(this.x*t-this.y*s,this.x*s+this.y*t)}toString(){return`(${this.x}, ${this.y})`}equals(e){return e instanceof SFSVector2&&(e.x==this.x&&e.y==this.y)}}class SFSVector3{static EPSILON=1e-5;constructor(e,t,s){this.x=e,this.y=t,this.z=s}get lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z}get length(){return Math.sqrt(this.lengthSquared)}get isNormalized(){return Math.abs(this.lengthSquared-1)<SFSVector3.EPSILON}sum(e){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");return new SFSVector3(this.x+e.x,this.y+e.y,this.z+e.z)}sub(e){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");return new SFSVector3(this.x-e.x,this.y-e.y,this.z-e.z)}mult(e){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");return new SFSVector3(this.x*e.x,this.y*e.y,this.z*e.z)}div(e){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");if(0==e.x||0==e.y||0==e.z)throw new Error(\"Division by zero detected\");return new SFSVector3(this.x/e.x,this.y/e.y,this.z/e.z)}normalize(){const e=this.length;return e<SFSVector3.EPSILON?new SFSVector3(0,0,0):new SFSVector3(this.x/e,this.y/e,this.z/e)}dot(e){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");return this.x*e.x+this.y*e.y+this.z*e.z}distanceTo(e){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return Math.sqrt(t*t+s*s+i*i)}distanceSquaredTo(e){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}abs(){return new SFSVector3(Math.abs(this.x),Math.abs(this.y),Math.abs(this.z))}min(e){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");return new SFSVector3(Math.min(this.x,e.x),Math.min(this.y,e.y),Math.min(this.z,e.z))}max(e){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");return new SFSVector3(Math.max(this.x,e.x),Math.max(this.y,e.y),Math.max(this.z,e.z))}floor(){return new SFSVector3(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}ceil(){return new SFSVector3(Math.ceil(this.x),Math.ceil(this.y),Math.ceil(this.z))}round(){return new SFSVector3(Math.round(this.x),Math.round(this.y),Math.round(this.z))}lerp(e,t){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");return new SFSVector3(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t,this.z+(e.z-this.z)*t)}cross(e){if(!(e instanceof SFSVector3))throw new TypeError(\"Argument must be an instance of SFSVector3\");return new SFSVector3(this.y*e.z-this.z*e.y,this.z*e.x-this.x*e.z,this.x*e.y-this.y*e.x)}rotate(e,t){if(!(e instanceof SFSVector3))throw new TypeError(\"Axis argument must be an instance of SFSVector3\");if(!e.isNormalized)throw new Error(\"Axis argument must be a normalized vector\");const s=Math.cos(t),i=Math.sin(t),r=1-s,n=e.dot(this),a=e.cross(this);return new SFSVector3(this.x*s+a.x*i+e.x*n*r,this.y*s+a.y*i+e.y*n*r,this.z*s+a.z*i+e.z*n*r)}toString(){return`(${this.x}, ${this.y}, ${this.z})`}equals(e){return e instanceof SFSVector3&&(e.x==this.x&&e.y==this.y&&e.z==this.z)}}const Fs=Object.freeze({SYSTEM:0,EXTENSION:1,AUDIO:3});class BaseRequest{static KEY_ERROR_CODE=\"ec\";static KEY_ERROR_PARAMS=\"ep\";constructor(e){this._reqObj=new SFSObject,this._id=e,this._targetController=0,this._logger=Logger.getInstance(this.name)}get id(){return this._id}get targetController(){return this._targetController}get message(){return new Message(this._id,this._targetController,this._reqObj,!1)}validate(){this._logger.error(\"BaseRequest.validate = no child-class implementation found!\")}execute(){this._logger.error(\"BaseRequest.execute = no child-class implementation found!\")}}class Message{constructor(e,t,s,i){this._id=e,this._targetController=t,this._content=s,this._isRaw=i,Object.freeze(this)}get id(){return this._id}get targetController(){return this._targetController}get content(){return this._content}get isRaw(){return this._isRaw}dump(){return(Ls.getNameFromId(this._targetController,this.id)+\" (\"+this.id+\")\").trim()+\"\\n\"+(this._isRaw?DumpFormatter.hexDump(this.content):this.content.getDump())}}const Ls=Object.freeze({System:Object.freeze({Handshake:0,Login:1,Logout:2,JoinRoom:4,CreateRoom:6,GenericMessage:7,ChangeRoomName:8,ChangeRoomPassword:9,SetRoomVariables:11,SetUserVariables:12,LeaveRoom:14,SubscribeRoomGroup:15,UnsubscribeRoomGroup:16,SpectatorToPlayer:17,PlayerToSpectator:18,ChangeRoomCapacity:19,KickUser:24,BanUser:25,FindRooms:27,FindUsers:28,PingPong:29,SetUserPosition:30,QuickJoinOrCreateRoom:31,BanUsersFromRoom:33,UnbanUsersFromRoom:34,InitBuddyList:200,AddBuddy:201,BlockBuddy:202,RemoveBuddy:203,SetBuddyVariables:204,GoOnline:205,InviteUsers:300,InvitationReply:301,CreateSFSGame:302,QuickJoinGame:303,JoinRoomInvite:304,ClusterJoinOrCreateRequest:500,ClusterInviteUsers:502,GameServerConnectionRequired:600}),Extension:Object.freeze({CallExtension:13}),Audio:Object.freeze({InitAudio:0,StartAudioStream:1,StopAudioStream:2,AudioStreamData:3,ToggleAudioStreamMute:4}),getNameFromId(e,t){const s=Cs.get(e);if(null!=s)for(let e in s)if(s[e]===t)return e;return\"\"}}),Cs=new Map([[Fs.SYSTEM,Ls.System],[Fs.EXTENSION,Ls.Extension],[Fs.AUDIO,Ls.Audio]]);class SFSErrorCodes{constructor(){throw\"Class SFSErrorCodes cannot be instantiated. Please check the documentation for more details on its usage\"}static get _errorsByCode(){return Ds}static setErrorMessage(e,t){this._errorsByCode[e]=t}static getErrorMessage(e,t){return this.stringFormat(this._errorsByCode[e],t)}static stringFormat(e,t){if(null==e)return\"\";if(null!=t)for(let s=0;s<t.length;s++){let i=\"{\"+s+\"}\";e=e.replace(i,t[s])}return e}}const Ds=[\"Client API version is obsolete: {0}; required version: {1}\",\"Requested Zone {0} does not exist\",\"User name not recognized or length is out of bounds: {0}\",\"Wrong password for user {0}\",\"User {0} is banned\",\"Zone {0} is full\",\"User {0} is already logged in Zone {1}\",\"The server is full\",\"Zone {0} is currently inactive\",\"User name {0} contains bad words; filtered: {1}\",\"Guest users not allowed in Zone {0}\",\"IP address {0} is banned\",\"A Room with the same name already exists: {0}\",\"Requested Group is not available - Room: {0}; Group: {1}\",\"Bad Room name length -  Min: {0}; max: {1}; passed name length: {2}\",\"Room name contains bad words: {0}\",\"Zone is full; cannot add Rooms anymore\",\"You have exceeded the number of Rooms that you can create per session: {0}\",\"Room creation failed, wrong parameter: {0}\",\"User {0} already joined in Room\",\"Room {0} is full\",\"Wrong password for Room {0}\",\"Requested Room does not exist\",\"Room {0} is locked\",\"Group {0} is already subscribed\",\"Group {0} does not exist\",\"Group {0} is not subscribed\",\"Group {0} does not exist\",\"{0}\",\"Room permission error; Room {0} cannot be renamed\",\"Room permission error; Room {0} cannot change password state\",\"Room permission error; Room {0} cannot change capacity\",\"Switch user error; no player slots available in Room {0}\",\"Switch user error; no spectator slots available in Room {0}\",\"Switch user error; Room {0} is not a Game Room\",\"Switch user error; you are not joined in Room {0}\",\"Buddy Manager initialization error, could not load buddy list: {0}\",\"Buddy Manager error, your buddy list is full; size is {0}\",\"Buddy Manager error, was not able to block buddy {0} because offline\",\"Buddy Manager error, you are attempting to set too many Buddy Variables; limit is {0}\",\"Game {0} access denied, user does not match access criteria\",\"QuickJoinGame action failed: no matching Rooms were found\",\"Your previous invitation reply was invalid or arrived too late\",\"User {0} is banned from Room {1}\"],Bs=Object.freeze({NULL:0,BOOLEAN:1,BYTE:2,SHORT:3,INT:4,LONG:5,FLOAT:6,DOUBLE:7,STRING:8,SFSOBJECT:9,SFSARRAY:10,VECTOR2:11,VECTOR3:12,getTypeName:e=>[\"null\",\"boolean\",\"byte\",\"short\",\"int\",\"long\",\"float\",\"double\",\"string\",\"SFSObject\",\"SFSArray\",\"SFSVector2\",\"SFSVector3\"][e]});class BaseVariable{constructor(e,t,s){if(this._name=e,this._value=t,this._type=s,null==s)throw new SFSValidationError(\"Variable type cannot be null; choose one of the types listed in VariableType class\")}get name(){return this._name}get value(){return this._value}get type(){return Bs.getTypeName(this._type)}get isNull(){return this._type===Bs.NULL}toSFSArray(){const e=new SFSArray;return e.addShortString(this.name),e.addByte(this._type),this._populateArrayWithValue(e),e}_populateArrayWithValue(e){switch(this._type){case Bs.NULL:e.addNull();break;case Bs.BOOLEAN:e.addBool(this.value);break;case Bs.BYTE:e.addByte(this.value);break;case Bs.SHORT:e.addShort(this.value);break;case Bs.INT:e.addInt(this.value);break;case Bs.LONG:e.addLong(this.value);break;case Bs.FLOAT:e.addFloat(this.value);break;case Bs.DOUBLE:e.addDouble(this.value);break;case Bs.STRING:e.addString(this.value);break;case Bs.SFSOBJECT:e.addSFSObject(this.value);break;case Bs.SFSARRAY:e.addSFSArray(this.value);break;case Bs.VECTOR2:e.addVector2(this.value);break;case Bs.VECTOR3:e.addVector3(this.value)}}}const Ys=Object.freeze({RV_GAME_STARTED:\"$GS\"});class SFSRoomVariable extends BaseVariable{constructor(e,t,s){super(e,t,s),this.isPrivate=!1,this.isPersistent=!1,Object.seal(this)}toString(){return`[RVar] (${this.type}) ${this.name}: ${this.value} ${this.isPrivate?\" - private\":\"\"}`}toSFSArray(){const e=super.toSFSArray();return e.addBool(this.isPrivate),e.addBool(this.isPersistent),e}static fromSFSArray(e){const t=new SFSRoomVariable(e.get(0),e.get(2),e.get(1));return t.isPrivate=e.get(3),t.isPersistent=e.get(4),t}}class SFSUserVariable extends BaseVariable{constructor(e,t,s){super(e,t,s),this.isPrivate=!1,Object.seal(this)}toString(){return`[UVar] (${this.type}) ${this.name}: ${this.value} ${this.isPrivate?\" - private\":\"\"}`}toSFSArray(){const e=super.toSFSArray();return e.addBool(this.isPrivate),e}static fromSFSArray(e){var t=new SFSUserVariable(e.get(0),e.get(2),e.get(1));return e.size()>3&&(t.isPrivate=e.get(3)),t}}class SFSUser{constructor(e,t,s=!1){this._id=e,this._name=t,this._isItMe=s,this._privilegeId=0,this._aoiEntryPoint=null,this._variables=new Map,this._playerIdByRoomId=new Map,this._userManager=null,Object.seal(this)}static fromSFSArray(e,t=null){const s=new SFSUser(e.getNumber(0),e.getString(1));s._privilegeId=e.getNumber(2),null!=t&&s._setPlayerId(e.getNumber(3),t);const i=e.getSFSArray(4);if(null!=i)for(let e=0;e<i.size();e++){const t=SFSUserVariable.fromSFSArray(i.getSFSArray(e));s._setVariable(t)}return s}get id(){return this._id}get name(){return this._name}get privilegeId(){return this._privilegeId}get isItMe(){return this._isItMe}get isPlayer(){return this.isPlayerInRoom(this._userManager._sfs.lastJoinedRoom)}get isSpectator(){return this.isSpectatorInRoom(this._userManager._sfs.lastJoinedRoom)}get isGuest(){return this._privilegeId===xs.GUEST}get isStandardUser(){return this._privilegeId===xs.STANDARD}get isModerator(){return this._privilegeId===xs.MODERATOR}get isAdmin(){return this.privilegeId===xs.ADMINISTRATOR}get aoiEntryPoint(){return this._aoiEntryPoint}get userManager(){return this._userManager}get playerId(){return this.getPlayerId(this.userManager._sfs.lastJoinedRoom)}getPlayerId(e){const t=this._playerIdByRoomId.get(e.id);return null!=t?t:0}isPlayerInRoom(e){return!!e.isGame&&this.getPlayerId(e)>0}isSpectatorInRoom(e){return!!e.isGame&&this.getPlayerId(e)<0}isJoinedInRoom(e){return e.containsUser(this)}containsVariable(e){return this._variables.has(e)}getVariable(e){return this.containsVariable(e)?this._variables.get(e):null}getVariables(){return Array.from(this._variables.values())}toString(){return`[User: ${this.name}, Id: ${this.id}, Is me: ${this.isItMe}]`}_setUserManager(e){if(null!=this._userManager)throw new Exceptions_SFSError(\"User Manager already assigned to user \"+this.toString());this._userManager=e}_setPlayerId(e,t){this._playerIdByRoomId.set(t.id,e)}_removePlayerId(e){this._playerIdByRoomId.delete(e.id)}_setVariable(e){e.isNull?this._variables.delete(e.name):this._variables.set(e.name,e)}_setVariables(e){for(let t of e)this._setVariable(t)}_replaceVariables(e){this._variables.clear(),this._setVariables(e)}}const xs=Object.freeze({GUEST:0,STANDARD:1,MODERATOR:2,ADMINISTRATOR:3});class SFSUserManager{constructor(e){this._sfs=e,this._usersById=new Map,this._usersByName=new Map}containsUserName(e){return this._usersByName.has(e)}containsUserId(e){return this._usersById.has(e)}containsUser(e){return this._usersById.has(e.id)}getUserByName(e){return this._usersByName.get(e)}getUserById(e){return this._usersById.get(e)}get userList(){return Array.from(this._usersById.values())}get userCount(){return this._usersById.size}_addUser(e){this._usersByName.set(e.name,e),this._usersById.set(e.id,e)}_removeUser(e){this._usersById.delete(e.id),this._usersByName.delete(e.name)}_removeUserById(e){let t=this.getUserById(e);null!=t&&this._removeUser(t)}}class SFSGlobalUserManager extends SFSUserManager{constructor(e){super(e),Object.freeze(this)}containsUser(e){let t=!1,s=this._sfs.getJoinedRooms();if(null!=s)for(let i of s)if(i.containsUser(e)){t=!0;break}return t}containsUserName(e){let t=!1,s=this._sfs.getJoinedRooms();if(null!=s)for(let i of s)if(i.getUserByName(e)){t=!0;break}return t}containsUserId(e){let t=!1,s=this._sfs.getJoinedRooms();if(null!=s)for(let i of s)if(i.getUserById(e)){t=!0;break}return t}getUserById(e){if(this._sfs.mySelf.id==e)return this._sfs.mySelf;let t=null;var s=this._sfs.getJoinedRooms();if(null!=s)for(let i of s)if(t=i.getUserById(e),null!=t)break;return t}getUserByName(e){if(this._sfs.mySelf.name==e)return this._sfs.mySelf;let t=null;var s=this._sfs.getJoinedRooms();if(null!=s)for(let i of s)if(t=i.getUserByName(e),null!=t)break;return t}get userList(){let e=this._sfs.getJoinedRooms();if(null==e||0==e.length){let e=[];return null!=this._sfs.mySelf&&e.push(this._sfs.mySelf),e}{let t=new Set;for(let s of e){let e=new Set(s.userList);t=t.union(e)}return Array.from(t)}}get userCount(){return this.userList.length}getOrCreateUser(e,t){const s=e.getNumber(0);let i=this.getUserById(s);if(null==i)i=SFSUser.fromSFSArray(e,t),i._setUserManager(this);else if(null!=t){i._setPlayerId(e.getNumber(3),t);const s=e.getSFSArray(4);let r=[];if(null!=s)for(let e=0;e<s.size();e++)r.push(SFSUserVariable.fromSFSArray(s.getSFSArray(e)));i._replaceVariables(r)}return i}_addUser(e){}_removeUser(e){}_removeUserById(e){}}class SFSRoom{static DEFAUL_GROUP_ID=\"default\";constructor(e,t,s=SFSRoom.DEFAUL_GROUP_ID,i=!0){this._id=e,this._name=t,this._groupId=s,this._isJoined=!1,this._isGame=!1,this._isHidden=!1,this._isManaged=!0,this._isPasswordProtected=!1,this._maxUsers=0,this._maxSpectators=0,this._userCount=0,this._specCount=0,this._variables=new Map,this._userManager=new SFSUserManager,this._roomManager=null,this._isAudioStreamingAllowed=!1,i&&Object.seal(this)}static fromSFSArray(e){const t=e.size()>12;let s;s=t?new MMORoom(e.getNumber(0),e.getString(1),e.getString(2)):new SFSRoom(e.getNumber(0),e.getString(1),e.getString(2)),s._isGame=e.getBool(3),s._isHidden=e.getBool(4),s._isPasswordProtected=e.getBool(5),s._userCount=e.getNumber(6),s._maxUsers=e.getNumber(7);const i=e.get(8);if(null!=i)for(let e=0;e<i.size();e++){const t=SFSRoomVariable.fromSFSArray(i.getSFSArray(e));s._setVariable(t)}return s._isAudioStreamingAllowed=e.getBool(9),s._isGame&&(s._specCount=e.getNumber(10),s._maxSpectators=e.getNumber(11)),t&&(s._defaultAOI=Vec3D.fromArray(e.get(12)),e.isNull(13)||(s._lowerMapLimit=Vec3D.fromArray(e.get(13)),s._higherMapLimit=Vec3D.fromArray(e.get(14)))),s}get id(){return this._id}get name(){return this._name}get groupId(){return this._groupId}get isJoined(){return this._isJoined}get isGame(){return this._isGame}get isHidden(){return this._isHidden}get isPasswordProtected(){return this._isPasswordProtected}get userCount(){return this.isJoined?this.isGame?this.playerList.length:this._userManager.userCount:this._userCount}get spectatorCount(){return this.isGame?this.isJoined?this.spectatorList.length:this._specCount:0}get maxUsers(){return this._maxUsers}get maxSpectators(){return this._maxSpectators}get capacity(){return this.maxUsers+this.maxSpectators}get isAudioStreamingAllowed(){return this._isAudioStreamingAllowed}get roomManager(){return this._roomManager}get userList(){return this._userManager.userList}get playerList(){return this._userManager.userList.filter(e=>e.isPlayerInRoom(this))}get spectatorList(){return this._userManager.userList.filter(e=>e.isSpectatorInRoom(this))}containsUser(e){return this._userManager.containsUser(e)}getUserByName(e){return this._userManager.getUserByName(e)}getUserById(e){return this._userManager.getUserById(e)}containsVariable(e){return this._variables.has(e)}getVariable(e){return this.containsVariable(e)?this._variables.get(e):null}getVariables(){return Array.from(this._variables.values())}toString(){return`[Room: ${this.name}, Id: ${this.id}, Group Id: ${this.groupId}]`}_setRoomManager(e){if(null!=this._roomManager)throw new Exceptions_SFSError(\"Room Manager already assigne; Room: \"+this.toString());this._roomManager=e}_addUser(e){this._userManager._addUser(e)}_removeUser(e){this._userManager._removeUser(e)}_setVariable(e){e.isNull?this._variables.delete(e.name):this._variables.set(e.name,e)}_setVariables(e){for(let t of e)this._setVariable(t)}}class MMORoom extends SFSRoom{constructor(e,t,s=SFSRoom.DEFAUL_GROUP_ID){super(e,t,s,!1),this._defaultAOI=null,this._lowerMapLimit=null,this._higherMapLimit=null,this._itemsById=new Map,Object.seal(this)}get defaultAOI(){return this._defaultAOI}get lowerMapLimit(){return this._lowerMapLimit}get higherMapLimit(){return this._higherMapLimit}getMMOItem(e){return this._itemsById.get(e)}getMMOItems(){return Array.from(this._itemsById.values())}_addMMOItem(e){this._itemsById.set(e.id,e)}_removeMMOItem(e){this._itemsById.delete(e)}}class MMOItemVariable extends BaseVariable{constructor(e,t,s){super(e,t,s),Object.freeze(this)}toString(){return`[MMOVar] (this.type) ${this.name}: ${this.value}`}static fromSFSArray(e){return new MMOItemVariable(e.get(0),e.get(2),e.get(1))}}class MMOItem{constructor(e){this._id=e,this._variables=new Map,this._aoiEntryPoint=null,Object.seal(this)}static fromSFSArray(e){const t=new MMOItem(e.getNumber(0)),s=e.getSFSArray(1);if(null!=s)for(let e=0;e<s.size();e++){const i=MMOItemVariable.fromSFSArray(s.getSFSArray(e));t._setVariable(i)}return t}get id(){return this._id}get aoiEntryPoint(){return this._aoiEntryPoint}containsVariable(e){return this._variables.has(e)}getVariable(e){return this.containsVariable(e)?this._variables.get(e):null}getVariables(){return Array.from(this._variables.values())}toString(){return`[Item: ${this.id}]`}_setVariable(e){this._variables.set(e.name,e)}_setVariables(e){for(let t of e)this._setVariable(t)}_removeVariable(e){this._variables.delete(e)}}const ks=Object.freeze({BV_ONLINE:\"$__BV_ONLINE__\",BV_STATE:\"$__BV_STATE__\",BV_NICKNAME:\"$__BV_NICKNAME__\"});class SFSBuddyVariable extends BaseVariable{static OFFLINE_PREFIX=\"$\";constructor(e,t,s){super(e,t,s),Object.freeze(this)}get isOffline(){return this._name.charAt(0)===SFSBuddyVariable.OFFLINE_PREFIX}toString(){return`[BVar] (${this.type}) ${this.type}: ${this.value}`}static fromSFSArray(e){return new SFSBuddyVariable(e.get(0),e.get(2),e.get(1))}}class SFSBuddy{constructor(e,t,s=!1,i=!1){this._id=e,this._name=t,this._variables=new Map,this._isBlocked=s,this._isTemp=i,Object.seal(this)}static fromSFSArray(e){const t=new SFSBuddy(e.getNumber(0),e.getString(1),e.getBool(2),e.size()>4&&e.getBool(4)),s=e.getSFSArray(3);if(null!=s)for(let e=0;e<s.size();e++){const i=SFSBuddyVariable.fromSFSArray(s.getSFSArray(e));t._setVariable(i)}return t}get id(){return this._id}get name(){return this._name}get isBlocked(){return this._isBlocked}get isOnline(){const e=this.getVariable(ks.BV_ONLINE);return(null==e||e.value)&&this._id>-1}get isTemp(){return this._isTemp}get state(){const e=this.getVariable(ks.BV_STATE);return null!=e?e.value:null}get nickname(){const e=this.getVariable(ks.BV_NICKNAME);return null!=e?e.value:null}get displayName(){return null!=this.nickname&&\"\"!=this.nickname?this.nickname:this.name}containsVariable(e){return this._variables.has(e)}getVariable(e){return this.containsVariable(e)?this._variables.get(e):null}getVariables(){return Array.from(this._variables.values())}getOfflineVariables(){return this.getVariables().filter(e=>e.name.charAt(0)===SFSBuddyVariable.OFFLINE_PREFIX)}getOnlineVariables(){return this.getVariables().filter(e=>e.name.charAt(0)!==SFSBuddyVariable.OFFLINE_PREFIX)}toString(){return`[Buddy: ${this.name}, Id: ${this.id}]`}_setVariable(e){this._variables.set(e.name,e)}_setVariables(e){for(let t of e)this._setVariable(t)}_removeVariable(e){this._variables.delete(e)}_clearVolatileVariables(){for(let e of this.getOnlineVariables())this._removeVariable(e.name)}}const Ps=Object.freeze({ONLINE:0,OFFLINE:1,LEFT_THE_SERVER:2});class SFSInvitation{constructor(e,t,s=15,i=null){this._id=-1,this._inviter=e,this._invitee=t,this._secondsForAnswer=s,this._params=i,Object.seal(this)}get id(){return this._id}get inviter(){return this._inviter}get invitee(){return this._invitee}get secondsForAnswer(){return this._secondsForAnswer}get params(){return this._params}}const qs=Object.freeze({ACCEPT:0,REFUSE:1,EXPIRED:2}),Vs=Object.freeze({kHz16:16e3,kHz24:24e3,kHz48:48e3}),Ks=Object.freeze({PEAK:0,RMS:1});class AudioSettings{#e=1;chunkSizeMillis;chunksPerTransmission;opusEncoderComplexity;opusApplicationType;opusSignalType;bitrate;delaySettings;static fromSFSObject(e){const t=new AudioSettings;return t.chunkSizeMillis=e.getNumber(\"csm\"),t.chunksPerTransmission=e.getNumber(\"cpt\"),t.opusEncoderComplexity=e.getNumber(\"oec\"),t.opusApplicationType=e.getString(\"oat\"),t.opusSignalType=e.getString(\"ost\"),t.bitrate=e.getNumber(\"br\"),t.delaySettings={delayUpperThreshold:e.getNumber(\"dut\"),delayLowerThreshold:e.getNumber(\"dlt\"),pitchShiftingValue:e.getNumber(\"ps\")},t}get numChannels(){return this.#e}}function Gs(e,t){const s=e.length;if(0===s)return Number.NEGATIVE_INFINITY;let i=0,r=0;for(let t=0;t<s;t++){const s=e[t];i+=s*s;const n=s<0?-s:s;n>r&&(r=n)}const n=t?r:Math.sqrt(i/s);return 20*Math.log10(Math.min(n,1))}class ConfigData{#t=Logger.getInstance(ConfigData.name);constructor(){this._host=\"127.0.0.1\",this._port=8088,this._useSSL=!1,this._netDebugLevel=Ns.OFF,this._zone=null,this._audio=new ConfigData.AudioCfg,Object.seal(this)}set host(e){this._host=e}get host(){return this._host}set port(e){this._port=e}get port(){return this._port}set useSSL(e){this._useSSL=e}get useSSL(){return this._useSSL}set zone(e){this._zone=e}get zone(){return this._zone}set netDebugLevel(e){Object.values(Ns).includes(e)||this.#t.warn(`Invalid network debug level set in ConfigData (${e})`),this._netDebugLevel=e}get netDebugLevel(){return this._netDebugLevel}get audio(){return this._audio}async load(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to load config file '${e}': ${t.status} ${t.statusText}`);const s=(await t.text()).split(/\\r?\\n/);for(let e of s){if(e=e.trim(),\"\"===e||e.startsWith(\"#\"))continue;const t=e.indexOf(\"=\");if(-1===t)continue;const s=e.substring(0,t).trim(),i=e.substring(t+1).trim();\"\"!==s&&this._applyProperty(s,i)}}_applyProperty(e,t){const s=e.split(\".\");let i=this;for(let e=0;e<s.length-1;e++){const t=s[e];if(null===i||\"object\"!=typeof i||!(t in i))return;i=i[t]}const r=s[s.length-1];null!==i&&\"object\"==typeof i&&r in i&&(i[r]=this._coerceValue(i[r],t))}_coerceValue(e,t){switch(typeof e){case\"number\":const s=Number(t);return Number.isNaN(s)?e:s;case\"boolean\":return\"true\"===t.toLowerCase();case\"string\":return t;default:return\"null\"===t?null:\"true\"===t||\"false\"===t?\"true\"===t:\"\"===t||Number.isNaN(Number(t))?t:Number(t)}}}class AudioCfg{#t=Logger.getInstance(AudioCfg.name);constructor(){this._sampleRate=Vs.kHz16,this._monitorInLevel=!1,this._monitorOutLevel=!1,this._monitoringMode=Ks.PEAK,this._enableAEC=!0,this._enableNS=!0,this._enableAGC=!0,Object.seal(this)}set sampleRate(e){Object.values(Vs).includes(e)||this.#t.warn(`Invalid sample rate set in ConfigData.AudioCfg (${e})`),this._sampleRate=e}get sampleRate(){return this._sampleRate}set monitorInLevel(e){this._monitorInLevel=e}get monitorInLevel(){return this._monitorInLevel}set monitorOutLevel(e){this._monitorOutLevel=e}get monitorOutLevel(){return this._monitorOutLevel}set monitoringMode(e){Object.values(Ks).includes(e)||this.#t.warn(`Invalid audio level monitoring mode set in ConfigData.AudioCfg (${e})`),this._monitoringMode=e}get monitoringMode(){return this._monitoringMode}set enableAEC(e){this._enableAEC=e}get enableAEC(){return this._enableAEC}set enableNS(e){this._enableNS=e}get enableNS(){return this._enableNS}set enableAGC(e){this._enableAGC=e}get enableAGC(){return this._enableAGC}}function js(e){let t=1779033703,s=3144134277,i=1013904242,r=2773480762,n=1359893119,a=2600822924,o=528734635,h=1541459225,l=0,u=0;const _=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],c=(e,t)=>e>>>t|e<<32-t,d=new Uint32Array(64),m=new Uint8Array(64),g=()=>{for(let e=0,t=0;e<16;e++,t+=4)d[e]=m[t]<<24|m[t+1]<<16|m[t+2]<<8|m[t+3];for(let e=16;e<64;e++){let t=c(d[e-15],7)^c(d[e-15],18)^d[e-15]>>>3,s=c(d[e-2],17)^c(d[e-2],19)^d[e-2]>>>10;d[e]=d[e-16]+t+d[e-7]+s|0}let e=t,l=s,g=i,S=r,p=n,f=a,R=o,E=h;for(let t=0;t<64;t++){let s=E+(c(p,6)^c(p,11)^c(p,25))+(p&f^~p&R)+_[t]+d[t]|0,i=e&l^e&g^l&g;E=R,R=f,f=p,p=S+s|0,S=g,g=l,l=e,e=s+((c(e,2)^c(e,13)^c(e,22))+i|0)|0}t=t+e|0,s=s+l|0,i=i+g|0,r=r+S|0,n=n+p|0,a=a+f|0,o=o+R|0,h=h+E|0,u=0},S=e=>{\"string\"==typeof e&&(e=\"undefined\"==typeof TextEncoder?Buffer.from(e):(new TextEncoder).encode(e));for(let t=0;t<e.length;t++)m[u++]=e[t],64===u&&g();l+=e.length},p=()=>{if(m[u++]=128,64==u&&g(),u+8>64){for(;u<64;)m[u++]=0;g()}for(;u<58;)m[u++]=0;let e=8*l;m[u++]=e/1099511627776&255,m[u++]=e/4294967296&255,m[u++]=e>>>24,m[u++]=e>>>16&255,m[u++]=e>>>8&255,m[u++]=255&e,g();let _=new Uint8Array(32);return _[0]=t>>>24,_[1]=t>>>16&255,_[2]=t>>>8&255,_[3]=255&t,_[4]=s>>>24,_[5]=s>>>16&255,_[6]=s>>>8&255,_[7]=255&s,_[8]=i>>>24,_[9]=i>>>16&255,_[10]=i>>>8&255,_[11]=255&i,_[12]=r>>>24,_[13]=r>>>16&255,_[14]=r>>>8&255,_[15]=255&r,_[16]=n>>>24,_[17]=n>>>16&255,_[18]=n>>>8&255,_[19]=255&n,_[20]=a>>>24,_[21]=a>>>16&255,_[22]=a>>>8&255,_[23]=255&a,_[24]=o>>>24,_[25]=o>>>16&255,_[26]=o>>>8&255,_[27]=255&o,_[28]=h>>>24,_[29]=h>>>16&255,_[30]=h>>>8&255,_[31]=255&h,_.hex=()=>{let e=\"\";return _.forEach(t=>e+=(\"0\"+t.toString(16)).slice(-2)),e},_};return void 0===e?{add:S,digest:p}:(S(e),p())}ConfigData.AudioCfg=AudioCfg;class PasswordUtil{static sha256Password(e){return Array.from(js(e)).map(e=>e.toString(16).padStart(2,\"0\")).join(\"\").toUpperCase()}}class LoginRequest extends BaseRequest{static KEY_ZONE_NAME=\"zn\";static KEY_USER_NAME=\"un\";static KEY_PASSWORD=\"pw\";static KEY_PARAMS=\"p\";static KEY_PRIVILEGE_ID=\"pi\";static KEY_ID=\"id\";static KEY_ROOMLIST=\"rl\";static KEY_RECONNECTION_SECONDS=\"rs\";static KEY_CLUSTER_SID=\"_sid\";constructor(e=\"\",t=\"\",s=null,i=null){super(Ls.System.Login),this._userName=e,this._password=t,this._zoneName=s,this._params=i,Object.seal(this)}validate(e){if(null!=e.mySelf)throw new SFSValidationError(\"Login request error\",[\"You are already logged in; logout first\"]);const t=[];if(null!=this._zoneName&&0!==this._zoneName.length||null==e.config||(this._zoneName=e.config.zone),null!=this._zoneName&&0!==this._zoneName.length||t.push(\"Missing Zone name\"),null==this._params||this._params instanceof SFSObject||t.push(\"Custom parameters must be passed in a SFSObject\"),t.length>0)throw new SFSValidationError(\"Login request error\",t)}execute(e){this._reqObj.putString(LoginRequest.KEY_ZONE_NAME,this._zoneName),this._reqObj.putString(LoginRequest.KEY_USER_NAME,this._userName),!e.config.useSSL&&this._password.length>0&&(this._password=PasswordUtil.sha256Password(e.sessionToken+this._password)),this._reqObj.putString(LoginRequest.KEY_PASSWORD,this._password),null!=this._params&&this._reqObj.putSFSObject(LoginRequest.KEY_PARAMS,this._params)}}class JoinRoomRequest extends BaseRequest{static KEY_ROOM=\"r\";static KEY_USER_LIST=\"ul\";static KEY_ROOM_NAME=\"n\";static KEY_ROOM_ID=\"i\";static KEY_PASS=\"p\";static KEY_ROOM_TO_LEAVE=\"rl\";static KEY_AS_SPECTATOR=\"sp\";constructor(e,t=null,s=null,i=!1){super(Ls.System.JoinRoom),\"string\"==typeof e?this._rName=e:\"number\"==typeof e?this._rId=e:e instanceof SFSRoom&&(this._rId=e.id,this._rName=e.name),this._password=t,this._roomIdToLeave=s,this._asSpectator=i,Object.seal(this)}validate(e){const t=[];if(null==this._rId&&null==this._rName&&t.push(\"Missing target Room id or name: you should provide at least one, or pass an existing SFSRoom object\"),t.length>0)throw new SFSValidationError(\"JoinRoom request error\",t)}execute(e){this._rId>=0?this._reqObj.putInt(JoinRoomRequest.KEY_ROOM_ID,this._rId):null!=this._rName&&this._reqObj.putString(JoinRoomRequest.KEY_ROOM_NAME,this._rName),null!=this._password&&this._reqObj.putString(JoinRoomRequest.KEY_PASS,this._password),null!=this._roomIdToLeave&&this._reqObj.putInt(JoinRoomRequest.KEY_ROOM_TO_LEAVE,this._roomIdToLeave),this._asSpectator&&this._reqObj.putBool(JoinRoomRequest.KEY_AS_SPECTATOR,this._asSpectator)}}class RoomSettings{constructor(e){this.name=e,this.password=\"\",this.groupId=\"default\",this.isGame=!1,this.maxUsers=10,this.maxSpectators=0,this.maxVariables=5,this.variables=[],this.permissions=null,this.events=null,this.extension=null,this.allowOwnerOnlyInvitation=!0,this.allowAudioStreaming=!1}}class SFSGameSettings extends RoomSettings{constructor(e){super(e),this.isPublic=!0,this.minPlayersToStartGame=2,this.invitedPlayers=null,this.searchableRooms=null,this.invitationExpiryTime=15,this.leaveLastJoinedRoom=!0,this.notifyGameStarted=!1,this.playerMatchExpression=null,this.spectatorMatchExpression=null,this.invitationParams=null,Object.seal(this)}}class MMORoomSettings extends RoomSettings{constructor(e,t){super(e),this.defaultAOI=t,this.mapLimits=null,this.userMaxLimboSeconds=50,this.proximityListUpdateMillis=250,this.sendAOIEntryPoint=!0,Object.seal(this)}}class ClusterRoomSettings extends RoomSettings{constructor(e){super(e),this.isPublic=!0,this.minPlayersToStartGame=2,this.invitedPlayers=null,this.invitationExpiryTime=30,this.notifyGameStarted=!1,this.invitationParams=null,Object.seal(this)}}class RoomPermissions{constructor(){this.allowNameChange=!1,this.allowPasswordStateChange=!1,this.allowPublicMessages=!0,this.allowResizing=!1,Object.seal(this)}}class RoomEvents{constructor(){this.allowUserCountChange=!1,this.allowUserEnter=!1,this.allowUserExit=!1,this.allowUserVariablesUpdate=!1,Object.seal(this)}}class RoomExtension{constructor(e,t){this.id=e,this.className=t,this.propertiesFile=\"\",Object.seal(this)}}class MapLimits{constructor(e,t){if(null==e||null==t)throw new Exceptions_SFSError(\"Map limits arguments must be both non null!\");this.lowerLimit=e,this.higherLimit=t,Object.seal(this)}}const zs=Object.freeze({BY_ADDRESS:0,BY_NAME:1});class MessageRecipientMode{static TO_USER=0;static TO_ROOM=1;static TO_GROUP=2;static TO_ZONE=3;constructor(e,t){if(e<MessageRecipientMode.TO_USER||e>MessageRecipientMode.TO_ZONE)throw new Exceptions_SFSError(\"Illegal recipient mode: \"+e);this._mode=e,this._target=t,Object.freeze(this)}get mode(){return this._mode}get target(){return this._target}}const Hs=Object.freeze({MINUTES:0,HOURS:1});class ClusterTarget{constructor(e,t){this._serverId=e,this._roomId=t,Object.freeze(this)}get serverId(){return this._serverId}get roomId(){return this._roomId}}class CreateRoomRequest extends BaseRequest{static KEY_ROOM=\"r\";static KEY_NAME=\"n\";static KEY_PASSWORD=\"p\";static KEY_GROUP_ID=\"g\";static KEY_ISGAME=\"ig\";static KEY_MAXUSERS=\"mu\";static KEY_MAXSPECTATORS=\"ms\";static KEY_MAXVARS=\"mv\";static KEY_ROOMVARS=\"rv\";static KEY_PERMISSIONS=\"pm\";static KEY_EVENTS=\"ev\";static KEY_EXTID=\"xn\";static KEY_EXTCLASS=\"xc\";static KEY_EXTPROP=\"xp\";static KEY_AUTOJOIN=\"aj\";static KEY_ROOM_TO_LEAVE=\"rl\";static KEY_ALLOW_JOIN_INVITATION_BY_OWNER=\"aji\";static KEY_ALLOW_AUDIO_STREAMING=\"aas\";static KEY_MMO_DEFAULT_AOI=\"maoi\";static KEY_MMO_MAP_LOW_LIMIT=\"mllm\";static KEY_MMO_MAP_HIGH_LIMIT=\"mlhm\";static KEY_MMO_USER_MAX_LIMBO_SECONDS=\"muls\";static KEY_MMO_PROXIMITY_UPDATE_MILLIS=\"mpum\";static KEY_MMO_SEND_ENTRY_POINT=\"msep\";constructor(e,t=!1,s=null){super(Ls.System.CreateRoom),this._settings=e,this._autoJoin=t,this._roomToLeave=s,Object.seal(this)}validate(e){if(!(this._settings instanceof RoomSettings))throw new SFSValidationError(\"CreateRoom request error\",[\"Room configuration must be an instance of RoomSettings class\"]);const t=[];if(null!=this._settings.name&&0!==this._settings.name.length||t.push(\"Missing Room name\"),this._settings.maxUsers<=0&&t.push(\"Max users value must be > 0\"),this._settings.maxSpectators<0&&t.push(\"Max spectators value must be >= 0\"),this._settings.maxVariables<0&&t.push(\"Max number of Room Variables must be >= 0\"),null!=this._settings.variables&&(this._settings.variables instanceof Array?this._settings.variables.every(e=>e instanceof SFSRoomVariable)||t.push(\"Each Room Variable must be an instance of SFSRoomVariable class\"):t.push(\"Room Variables must be passed in an array\")),null==this._settings.permissions||this._settings.permissions instanceof RoomPermissions||t.push(\"Allowed room permissions must be an instance of RoomPermissions class\"),null==this._settings.events||this._settings.events instanceof RoomEvents||t.push(\"Allowed room events must be an instance of RoomEvents class\"),null!=this._settings.extension&&(this._settings.extension instanceof RoomExtension?(null!=this._settings.extension.className&&0!==this._settings.extension.className.length||t.push(\"Missing Extension class name\"),null!=this._settings.extension.id&&0!==this._settings.extension.id.length||t.push(\"Missing Extension id\")):t.push(\"Room Extension settings must be an instance of RoomExtension class\")),this._settings instanceof MMORoomSettings&&(null==this._settings.defaultAOI&&t.push(\"Missing MMORoom's default AoI (Area of Interest)\"),this._settings.defaultAOI instanceof Vec3D||t.push(\"MMORoom's AoI (Area of Interest) must be an instance of Vec3D class\"),null!=this._settings.mapLimits&&(this._settings.mapLimits instanceof MapLimits?(null!=this._settings.mapLimits.lowerLimit&&null!=this._settings.mapLimits.higherLimit||t.push(\"MMORoom's lower and higher map limits must be both set\"),this._settings.mapLimits.lowerLimit instanceof Vec3D&&this._settings.mapLimits.higherLimit instanceof Vec3D||t.push(\"MMORoom's lower and higher map limits must be both instances of Vec3D class\")):t.push(\"MMORoom's map limits must be an instance of MapLimits class\"))),null==this._roomToLeave||this._roomToLeave instanceof SFSRoom||t.push(\"Room to leave must be an instance of SFSRoom class\"),t.length>0)throw new SFSValidationError(\"CreateRoom request error\",t)}execute(e){if(this._reqObj.putString(CreateRoomRequest.KEY_NAME,this._settings.name),this._reqObj.putString(CreateRoomRequest.KEY_GROUP_ID,this._settings.groupId),this._reqObj.putString(CreateRoomRequest.KEY_PASSWORD,this._settings.password),this._reqObj.putBool(CreateRoomRequest.KEY_ISGAME,this._settings.isGame),this._reqObj.putShort(CreateRoomRequest.KEY_MAXUSERS,this._settings.maxUsers),this._reqObj.putShort(CreateRoomRequest.KEY_MAXSPECTATORS,this._settings.maxSpectators),this._reqObj.putShort(CreateRoomRequest.KEY_MAXVARS,this._settings.maxVariables),this._reqObj.putBool(CreateRoomRequest.KEY_ALLOW_JOIN_INVITATION_BY_OWNER,this._settings.allowOwnerOnlyInvitation),this._reqObj.putBool(CreateRoomRequest.KEY_ALLOW_AUDIO_STREAMING,this._settings.allowAudioStreaming),null!=this._settings.variables&&this._settings.variables.length>0){const e=new SFSArray;for(let t of this._settings.variables)e.addSFSArray(t.toSFSArray());this._reqObj.putSFSArray(CreateRoomRequest.KEY_ROOMVARS,e)}if(null!=this._settings.permissions){const e=[];e.push(this._settings.permissions.allowNameChange),e.push(this._settings.permissions.allowPasswordStateChange),e.push(this._settings.permissions.allowPublicMessages),e.push(this._settings.permissions.allowResizing),this._reqObj.putBoolArray(CreateRoomRequest.KEY_PERMISSIONS,e)}if(null!=this._settings.events){const e=[];e.push(this._settings.events.allowUserEnter),e.push(this._settings.events.allowUserExit),e.push(this._settings.events.allowUserCountChange),e.push(this._settings.events.allowUserVariablesUpdate),this._reqObj.putBoolArray(CreateRoomRequest.KEY_EVENTS,e)}null!=this._settings.extension&&(this._reqObj.putString(CreateRoomRequest.KEY_EXTID,this._settings.extension.id),this._reqObj.putString(CreateRoomRequest.KEY_EXTCLASS,this._settings.extension.className),null!=this._settings.extension.propertiesFile&&this._settings.extension.propertiesFile.length>0&&this._reqObj.putString(CreateRoomRequest.KEY_EXTPROP,this._settings.extension.propertiesFile)),this._settings instanceof MMORoomSettings&&(this._settings.defaultAOI.isFloat?(this._reqObj.putFloatArray(CreateRoomRequest.KEY_MMO_DEFAULT_AOI,this._settings.defaultAOI.toArray()),null!=this._settings.mapLimits&&(this._reqObj.putFloatArray(CreateRoomRequest.KEY_MMO_MAP_LOW_LIMIT,this._settings.mapLimits.lowerLimit.toArray()),this._reqObj.putFloatArray(CreateRoomRequest.KEY_MMO_MAP_HIGH_LIMIT,this._settings.mapLimits.higherLimit.toArray()))):(this._reqObj.putIntArray(CreateRoomRequest.KEY_MMO_DEFAULT_AOI,this._settings.defaultAOI.toArray()),null!=this._settings.mapLimits&&(this._reqObj.putIntArray(CreateRoomRequest.KEY_MMO_MAP_LOW_LIMIT,this._settings.mapLimits.lowerLimit.toArray()),this._reqObj.putIntArray(CreateRoomRequest.KEY_MMO_MAP_HIGH_LIMIT,this._settings.mapLimits.higherLimit.toArray()))),this._reqObj.putShort(CreateRoomRequest.KEY_MMO_USER_MAX_LIMBO_SECONDS,this._settings.userMaxLimboSeconds),this._reqObj.putShort(CreateRoomRequest.KEY_MMO_PROXIMITY_UPDATE_MILLIS,this._settings.proximityListUpdateMillis),this._reqObj.putBool(CreateRoomRequest.KEY_MMO_SEND_ENTRY_POINT,this._settings.sendAOIEntryPoint)),this._reqObj.putBool(CreateRoomRequest.KEY_AUTOJOIN,this._autoJoin),null!=this._roomToLeave&&this._reqObj.putInt(CreateRoomRequest.KEY_ROOM_TO_LEAVE,this._roomToLeave.id)}}class ChangeRoomNameRequest extends BaseRequest{static KEY_ROOM=\"r\";static KEY_NAME=\"n\";constructor(e,t){super(Ls.System.ChangeRoomName),this._room=e,this._newName=t,Object.seal(this)}validate(e){const t=[];if(this._room instanceof SFSRoom||t.push(\"Room must be an instance of SFSRoom class\"),null!=this._newName&&0!==this._newName.length||t.push(\"Invalid new room name; it must be a non-null and non-empty string\"),t.length>0)throw new SFSValidationError(\"ChangeRoomName request error\",t)}execute(e){this._reqObj.putInt(ChangeRoomNameRequest.KEY_ROOM,this._room.id),this._reqObj.putString(ChangeRoomNameRequest.KEY_NAME,this._newName)}}class ChangeRoomPasswordStateRequest extends BaseRequest{static KEY_ROOM=\"r\";static KEY_PASS=\"p\";constructor(e,t){super(Ls.System.ChangeRoomPassword),this._room=e,this._newPass=t,Object.seal(this)}validate(e){const t=[];if(this._room instanceof SFSRoom||t.push(\"Room must be an instance of SFSRoom class\"),null==this._newPass&&t.push(\"Invalid new room password; it must be a non-null string\"),t.length>0)throw new SFSValidationError(\"ChangeRoomPasswordState request error\",t)}execute(e){this._reqObj.putInt(ChangeRoomPasswordStateRequest.KEY_ROOM,this._room.id),this._reqObj.putString(ChangeRoomPasswordStateRequest.KEY_PASS,this._newPass)}}class ChangeRoomCapacityRequest extends BaseRequest{static KEY_ROOM=\"r\";static KEY_USER_SIZE=\"u\";static KEY_SPEC_SIZE=\"s\";constructor(e,t,s){super(Ls.System.ChangeRoomCapacity),this._room=e,this._newMaxUsers=t,this._newMaxSpect=s,Object.seal(this)}validate(e){const t=[];if(this._room instanceof SFSRoom||t.push(\"Room must be an instance of SFSRoom class\"),this._newMaxUsers<1&&t.Add(\"New max users value must be > 0\"),this._newMaxSpect<0&&t.Add(\"New max spectators value must be >= 0\"),t.length>0)throw new SFSValidationError(\"ChangeRoomCapacity request error\",t)}execute(e){this._reqObj.putInt(ChangeRoomCapacityRequest.KEY_ROOM,this._room.id),this._reqObj.putInt(ChangeRoomCapacityRequest.KEY_USER_SIZE,this._newMaxUsers),this._reqObj.putInt(ChangeRoomCapacityRequest.KEY_SPEC_SIZE,this._newMaxSpect)}}const Js=Object.freeze({PUBLIC_MSG:0,PRIVATE_MSG:1,MODERATOR_MSG:2,ADMIN_MSG:3,OBJECT_MSG:4,BUDDY_MSG:5});class GenericMessageRequest extends BaseRequest{static KEY_ROOM_ID=\"r\";static KEY_USER_ID=\"u\";static KEY_MESSAGE=\"m\";static KEY_MESSAGE_TYPE=\"t\";static KEY_RECIPIENT=\"rc\";static KEY_RECIPIENT_MODE=\"rm\";static KEY_XTRA_PARAMS=\"p\";static KEY_SENDER_DATA=\"sd\";constructor(){super(Ls.System.GenericMessage),this._type=-1,this._room=null,this._user=null,this._message=null,this._params=null,this._recipient=null,this._sendMode=-1,Object.seal(this)}validate(e){if(this._type<0)throw new SFSValidationError(\"GenericMessage request error\",[\"Unsupported message type: \"+this._type]);const t=[];switch(this._type){case Js.PUBLIC_MSG:this._validatePublicMessage(e,t);break;case Js.PRIVATE_MSG:this._validatePrivateMessage(e,t);break;case Js.OBJECT_MSG:this._validateObjectMessage(e,t);break;case Js.BUDDY_MSG:this._validateBuddyMessage(e,t);break;case Js.MODERATOR_MSG:case Js.ADMIN_MSG:this._validateSuperUserMessage(e,t);break;default:t.push(\"Invalid message type: \"+this._type)}if(t.length>0)throw new SFSValidationError(\"GenericMessage request error\",t)}execute(e){switch(this._reqObj.putByte(GenericMessageRequest.KEY_MESSAGE_TYPE,this._type),this._type){case Js.PUBLIC_MSG:this._executePublicMessage(e);break;case Js.PRIVATE_MSG:this._executePrivateMessage(e);break;case Js.OBJECT_MSG:this._executeObjectMessage(e);break;case Js.BUDDY_MSG:this._executeBuddyMessage(e);break;case Js.MODERATOR_MSG:case Js.ADMIN_MSG:this._executeSuperUserMessage(e)}}_validatePublicMessage(e,t){if(null!=this._message&&0!==this._message.length||t.push(\"Public message is empty\"),null==this._room||this._room instanceof SFSRoom){if(null==this._room){if(null==e.lastJoinedRoom)return void t.push(\"A valid Room must be provided\");this._room=e.lastJoinedRoom}e.getJoinedRooms().indexOf(this._room)<0&&t.push(\"You are not joined in the target Room: \"+this._room)}else t.push(\"Target Room must be an instance of SFSRoom class\");null==this._params||this._params instanceof SFSObject||t.push(\"Message parameters must be set in a SFSObject class instance\")}_validatePrivateMessage(e,t){null!=this._message&&0!==this._message.length||t.push(\"Private message is empty\"),this._recipient<0&&t.push(\"Invalid recipient id: \"+this._recipient),null==this._params||this._params instanceof SFSObject||t.push(\"Message parameters must be set in a SFSObject class instance\")}_validateObjectMessage(e,t){if(null==this._params?t.push(\"Object message is null\"):this._params instanceof SFSObject||t.push(\"Message object must be an instance of SFSObject class\"),null==this._room||this._room instanceof SFSRoom){if(null==this._room){if(null==e.lastJoinedRoom)return void t.push(\"A valid Room must be provided\");this._room=e.lastJoinedRoom}e.getJoinedRooms().indexOf(this._room)<0&&t.push(\"You are not joined in the target Room: \"+this._room)}else t.push(\"Target Room must be an instance of SFSRoom class\");null!=this._room&&null!=this._recipient&&(this._recipient instanceof Array?this._recipient.every(e=>e instanceof SFSUser)||t.push(\"Each message recipient must be an instance of SFSUser class\"):t.push(\"Message recipients must be passed in an array\"),this._recipient.length>this._room.capacity&&t.push(\"The number of recipients is bigger than the target Room capacity: \"+this._recipient.length))}_validateBuddyMessage(e,t){e.buddyManager.isInited||t.push(\"Buddy List not yet initialized; please send an InitBuddyRequest first\"),!1===e.buddyManager.myOnlineState&&t.push(\"Cannot send buddy messages while off-line\"),null!=this._message&&0!==this._message.length||t.push(\"Buddy message is empty\"),this._recipient<0&&t.push(\"Recipient is not online or not in your buddy list\"),null==this._params||this._params instanceof SFSObject||t.push(\"Message parameters must be set in a SFSObject class instance\")}_validateSuperUserMessage(e,t){if(e.mySelf.isModerator||e.mySelf.isAdmin)switch(null!=this._message&&0!==this._message.length||t.push(\"Moderator message is empty\"),null==this._params||this._params instanceof SFSObject||t.push(\"Message parameters must be set in a SFSObject class instance\"),this._sendMode){case MessageRecipientMode.TO_USER:this._recipient instanceof SFSUser||t.push(\"Recipient must be an instance of SFSUser class\");break;case MessageRecipientMode.TO_ROOM:this._recipient instanceof SFSRoom||t.push(\"Recipient must be an instance of SFSRoom class\");break;case MessageRecipientMode.TO_GROUP:\"string\"!=typeof this._recipient&&t.push(\"Recipient must be a string (the groupId)\")}else t.push(\"Not enough privileges to send a moderator/administrator message\")}_executePublicMessage(e){this._reqObj.putInt(GenericMessageRequest.KEY_ROOM_ID,this._room.id),this._reqObj.putString(GenericMessageRequest.KEY_MESSAGE,this._message),null!=this._params&&this._reqObj.putSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS,this._params)}_executePrivateMessage(e){this._reqObj.putInt(GenericMessageRequest.KEY_RECIPIENT,this._recipient),this._reqObj.putString(GenericMessageRequest.KEY_MESSAGE,this._message),null!=this._params&&this._reqObj.putSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS,this._params)}_executeObjectMessage(e){const t=new Set;if(null!=this._recipient)for(let e of this._recipient)t.add(e.id);this._reqObj.putInt(GenericMessageRequest.KEY_ROOM_ID,this._room.id),this._reqObj.putSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS,this._params),t.size>0&&this._reqObj.putIntArray(GenericMessageRequest.KEY_RECIPIENT,Array.from(t))}_executeBuddyMessage(e){this._reqObj.putInt(GenericMessageRequest.KEY_RECIPIENT,this._recipient),this._reqObj.putString(GenericMessageRequest.KEY_MESSAGE,this._message),null!=this._params&&this._reqObj.putSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS,this._params)}_executeSuperUserMessage(e){switch(this._reqObj.putString(GenericMessageRequest.KEY_MESSAGE,this._message),null!=this._params&&this._reqObj.putSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS,this._params),this._reqObj.putInt(GenericMessageRequest.KEY_RECIPIENT_MODE,this._sendMode),this._sendMode){case MessageRecipientMode.TO_USER:case MessageRecipientMode.TO_ROOM:this._reqObj.putInt(GenericMessageRequest.KEY_RECIPIENT,this._recipient.id);break;case MessageRecipientMode.TO_GROUP:this._reqObj.putString(GenericMessageRequest.KEY_RECIPIENT,this._recipient)}}}class ObjectMessageRequest extends GenericMessageRequest{constructor(e,t=null,s=null){super(),this._type=Js.OBJECT_MSG,this._params=e,this._room=t,this._recipient=s,Object.seal(this)}}class PublicMessageRequest extends GenericMessageRequest{constructor(e,t=null,s=null){super(),this._type=Js.PUBLIC_MSG,this._message=e,this._room=s,this._params=t,Object.seal(this)}}class PrivateMessageRequest extends GenericMessageRequest{constructor(e,t,s=null){super(),this._type=Js.PRIVATE_MSG,this._message=e,this._recipient=t,this._params=s,Object.seal(this)}}class ModeratorMessageRequest extends GenericMessageRequest{constructor(e,t,s=null){if(super(),null==t)throw new Exceptions_SFSError(\"Recipient mode cannot be null\");if(!(t instanceof MessageRecipientMode))throw new Exceptions_SFSError(\"Recipient mode must be an instance of MessageRecipientMode class\");this._type=Js.MODERATOR_MSG,this._message=e,this._params=s,this._recipient=t.target,this._sendMode=t.mode,Object.seal(this)}}class AdminMessageRequest extends GenericMessageRequest{constructor(e,t,s=null){if(super(),null==t)throw new Exceptions_SFSError(\"Recipient mode cannot be null\");if(!(t instanceof MessageRecipientMode))throw new Exceptions_SFSError(\"Recipient mode must an instance of MessageRecipientMode class\");this._type=Js.ADMIN_MSG,this._message=e,this._params=s,this._recipient=t.target,this._sendMode=t.mode,Object.seal(this)}}class SetRoomVariablesRequest extends BaseRequest{static KEY_VAR_ROOM=\"r\";static KEY_VAR_LIST=\"vl\";constructor(e,t=null){super(Ls.System.SetRoomVariables),this._roomVariables=e,this._room=t,Object.seal(this)}validate(e){const t=[];if(null==this._room||this._room instanceof SFSRoom){if(null==this._room){if(null==e.lastJoinedRoom)return void t.push(\"A valid Room must be provided\");this._room=e.lastJoinedRoom}e.getJoinedRooms().indexOf(this._room)<0&&t.push(\"You are not joined in the target Room: \"+this._room)}else t.push(\"Target Room must be an instance of SFSRoom class\");if(null==this._roomVariables?t.push(\"No Room Variables specified\"):this._roomVariables instanceof Array?0===this._roomVariables.length?t.push(\"No Room Variables specified\"):this._roomVariables.every(e=>e instanceof SFSRoomVariable)||t.push(\"Room Variables must be passed as instances of SFSRoomVariable class\"):t.push(\"Room Variables must be passed in an array\"),t.length>0)throw new SFSValidationError(\"SetRoomVariables request error\",t)}execute(e){try{const e=new SFSArray;for(let t of this._roomVariables)e.addSFSArray(t.toSFSArray());this._reqObj.putSFSArray(SetRoomVariablesRequest.KEY_VAR_LIST,e),this._reqObj.putInt(SetRoomVariablesRequest.KEY_VAR_ROOM,this._room.id)}catch(e){throw e instanceof SFSTypeError?new SFSTypeError(\"Invalid Room Variable: \"+e.message):e}}}class SetUserVariablesRequest extends BaseRequest{static KEY_USER=\"u\";static KEY_VAR_LIST=\"vl\";constructor(e){super(Ls.System.SetUserVariables),this._userVariables=e,Object.seal(this)}validate(e){const t=[];if(null==this._userVariables?t.push(\"No User Variables specified\"):this._userVariables instanceof Array?0===this._userVariables.length?t.push(\"No User Variables specified\"):this._userVariables.every(e=>e instanceof SFSUserVariable)||t.push(\"User Variables must be passed as instances of SFSUserVariable class\"):t.push(\"User Variables must be passed in an array\"),t.length>0)throw new SFSValidationError(\"SetUserVariables request error\",t)}execute(e){try{const e=new SFSArray;for(let t of this._userVariables)e.addSFSArray(t.toSFSArray());this._reqObj.putSFSArray(SetUserVariablesRequest.KEY_VAR_LIST,e)}catch(e){throw e instanceof SFSTypeError?new SFSTypeError(\"Invalid User Variable: \"+e.message):e}}}class SubscribeRoomGroupRequest extends BaseRequest{static KEY_GROUP_ID=\"g\";static KEY_ROOM_LIST=\"rl\";constructor(e){super(Ls.System.SubscribeRoomGroup),this._groupId=e,Object.seal(this)}validate(e){const t=[];if(null!=this._groupId&&0!==this._groupId.length||t.push(\"Null or empty string is not a valid group id\"),t.length>0)throw new SFSValidationError(\"SubscribeGroup request error\",t)}execute(e){this._reqObj.putString(SubscribeRoomGroupRequest.KEY_GROUP_ID,this._groupId)}}class UnsubscribeRoomGroupRequest extends BaseRequest{static KEY_GROUP_ID=\"g\";constructor(e){super(Ls.System.UnsubscribeRoomGroup),this._groupId=e,Object.seal(this)}validate(e){const t=[];if(null!=this._groupId&&0!==this._groupId.length||t.push(\"Null or empty string is not a valid group id\"),t.length>0)throw new SFSValidationError(\"UnsubscribeGroup request error\",t)}execute(e){this._reqObj.putString(UnsubscribeRoomGroupRequest.KEY_GROUP_ID,this._groupId)}}class SpectatorToPlayerRequest extends BaseRequest{static KEY_ROOM_ID=\"r\";static KEY_USER_ID=\"u\";static KEY_PLAYER_ID=\"p\";constructor(e=null){super(Ls.System.SpectatorToPlayer),this._room=e,Object.seal(this)}validate(e){const t=[];if(null==this._room||this._room instanceof SFSRoom){if(null==this._room){if(null==e.lastJoinedRoom)return void t.push(\"A valid Room must be provided\");this._room=e.lastJoinedRoom}e.getJoinedRooms().indexOf(this._room)<0&&t.push(\"You are not joined in the target Room: \"+this._room)}else t.push(\"Target Room must be an instance of SFSRoom class\");if(t.length>0)throw new SFSValidationError(\"SpectatorToPlayer request error\",t)}execute(e){this._reqObj.putInt(SpectatorToPlayerRequest.KEY_ROOM_ID,this._room.id)}}class PlayerToSpectatorRequest extends BaseRequest{static KEY_ROOM_ID=\"r\";static KEY_USER_ID=\"u\";constructor(e=null){super(Ls.System.PlayerToSpectator),this._room=e,Object.seal(this)}validate(e){const t=[];if(null==this._room||this._room instanceof SFSRoom){if(null==this._room){if(null==e.lastJoinedRoom)return void t.push(\"A valid Room must be provided\");this._room=e.lastJoinedRoom}e.getJoinedRooms().indexOf(this._room)<0&&t.push(\"You are not joined in the target Room: \"+this._room)}else t.push(\"Target Room must be an instance of SFSRoom class\");if(t.length>0)throw new SFSValidationError(\"PlayerToSpectator request error\",t)}execute(e){this._reqObj.putInt(PlayerToSpectatorRequest.KEY_ROOM_ID,this._room.id)}}class MatchExpression{constructor(e,t,s){this._varName=e,this._condition=t,this._varValue=s,this._logicOp=null,this._next=null,this._parent=null,Object.seal(this)}static chainedMatchExpression(e,t,s,i,r){const n=new MatchExpression(e,t,s);return n._logicOp=i,n._parent=r,n}get varName(){return this._varName}get condition(){return this._condition}get varValue(){return this._varValue}get logicOp(){return this._logicOp}get next(){return this._next}and(e,t,s){return this._next=MatchExpression.chainedMatchExpression(e,t,s,LogicOperator.AND,this),this._next}or(e,t,s){return this._next=MatchExpression.chainedMatchExpression(e,t,s,LogicOperator.OR,this),this._next}hasNext(){return null!=this._next}rewind(){let e=this;for(;null!=e._parent;)e=e._parent;return e}toString(){let e=this.rewind(),t=e.asString();for(;e.hasNext();)e=e.next,t+=e.asString();return t}asString(){let e=\"\";null!=this._logicOp&&(e+=` ${this._logicOp.id} `);const t=\"string\"==typeof this._varValue?`' ${this._varValue} '`:this._varValue;return e+=`(${this._varName} ${this._condition.symbol} ${t})`,e}toSFSArray(){let e=this.rewind();const t=new SFSArray;for(t.addSFSArray(e.expressionAsSFSArray());e.hasNext();)e=e.next,t.addSFSArray(e.expressionAsSFSArray());return t}expressionAsSFSArray(){const e=new SFSArray;return null!=this._logicOp?e.addString(this._logicOp.id):e.addNull(),e.addString(this._varName),e.addByte(this._condition.type),e.addString(this._condition.symbol),0===this._condition.type?e.addBool(this._varValue):1===this._condition.type?e.addDouble(this._varValue):e.addString(this._varValue),e}}class LogicOperator{constructor(e){this._id=e,Object.freeze(this)}get id(){return this._id}static AND=new LogicOperator(\"AND\");static OR=new LogicOperator(\"OR\")}class FindRoomsRequest extends BaseRequest{static KEY_EXPRESSION=\"e\";static KEY_GROUP=\"g\";static KEY_LIMIT=\"l\";static KEY_FILTERED_ROOMS=\"fr\";constructor(e,t=null,s=0){super(Ls.System.FindRooms),this._matchExpr=e,this._groupId=t,this._limit=s,Object.seal(this)}validate(e){const t=[];if(null==this._matchExpr&&t.push(\"Missing match expression\"),null==this._matchExpr||this._matchExpr instanceof MatchExpression||t.push(\"Match expression must be an instance of MatchExpression class\"),this._limit<0&&t.push(\"Limit value must be >= 0\"),t.length>0)throw new SFSValidationError(\"FindRooms request error\",t)}execute(e){this._reqObj.putSFSArray(FindRoomsRequest.KEY_EXPRESSION,this._matchExpr.toSFSArray()),null!=this._groupId&&this._reqObj.putString(FindRoomsRequest.KEY_GROUP,this._groupId),this._limit>0&&this._reqObj.putShort(FindRoomsRequest.KEY_LIMIT,this._limit)}}class FindUsersRequest extends BaseRequest{static KEY_EXPRESSION=\"e\";static KEY_GROUP=\"g\";static KEY_ROOM=\"r\";static KEY_LIMIT=\"l\";static KEY_FILTERED_USERS=\"fu\";constructor(e,t=null,s=0){super(Ls.System.FindUsers),this._matchExpr=e,this._target=t,this._limit=s,Object.seal(this)}validate(e){const t=[];if(null==this._matchExpr&&t.push(\"Missing match expression\"),null==this._matchExpr||this._matchExpr instanceof MatchExpression||t.push(\"Match expression must be an instance of MatchExpression class\"),this._limit<0&&t.push(\"Limit value must be >= 0\"),null!=this._target&&(this._target instanceof SFSRoom||\"string\"==typeof this._target||t.push(\"Unsupport target: \"+this._target)),t.length>0)throw new SFSValidationError(\"FindUsers request error\",t)}execute(e){this._reqObj.putSFSArray(FindUsersRequest.KEY_EXPRESSION,this._matchExpr.toSFSArray()),null!=this._target&&(this._target instanceof SFSRoom?this._reqObj.putInt(FindUsersRequest.KEY_ROOM,this._target.id):\"string\"==typeof this._target&&this._reqObj.putString(FindUsersRequest.KEY_GROUP,this._target)),this._limit>0&&this._reqObj.putShort(FindUsersRequest.KEY_LIMIT,this._limit)}}class InviteUsersRequest extends BaseRequest{static KEY_USER=\"u\";static KEY_USER_ID=\"ui\";static KEY_INVITATION_ID=\"ii\";static KEY_TIME=\"t\";static KEY_PARAMS=\"p\";static KEY_INVITEE_ID=\"ee\";static KEY_INVITED_USERS=\"iu\";static KEY_REPLY_ID=\"ri\";static MAX_INVITATIONS_FROM_CLIENT_SIDE=8;static MIN_EXPIRY_TIME=5;static MAX_EXPIRY_TIME=300;constructor(e,t,s=null){super(Ls.System.InviteUsers),this._invitedUsers=e,this._secondsForReply=t,this._params=s,Object.seal(this)}validate(e){const t=[];if(null==this._invitedUsers?t.push(\"No invitation to send\"):this._invitedUsers instanceof Array?(this._invitedUsers.length<1&&t.push(\"No invitation to send\"),this._invitedUsers.length>InviteUsersRequest.MAX_INVITATIONS_FROM_CLIENT_SIDE&&t.push(\"Too many invitations; max allowed from client side is: \"+InviteUsersRequest.MAX_INVITATIONS_FROM_CLIENT_SIDE),this._invitedUsers.every(e=>e instanceof SFSUser||e instanceof SFSBuddy)||t.push(\"Each invited user must be an instance of SFSUser or SFSBuddy class\")):t.push(\"Invited users must be passed in an array\"),(this._secondsForReply<InviteUsersRequest.MIN_EXPIRY_TIME||this._secondsForReply>InviteUsersRequest.MAX_EXPIRY_TIME)&&t.push(\"Seconds for reply value is out of range is out of range (\"+InviteUsersRequest.MIN_EXPIRY_TIME+\"-\"+InviteUsersRequest.MAX_EXPIRY_TIME+\")\"),null==this._params||this._params instanceof SFSObject||t.push(\"Custom invitation parameters must be set in a SFSObject class instance\"),t.length>0)throw new SFSValidationError(\"InviteUsers request error\",t)}execute(e){const t=[];for(let s of this._invitedUsers)if(s instanceof SFSUser||s instanceof SFSBuddy){if(s===e.mySelf)continue;t.push(s.id)}this._reqObj.putIntArray(InviteUsersRequest.KEY_INVITED_USERS,t),this._reqObj.putShort(InviteUsersRequest.KEY_TIME,this._secondsForReply),null!=this._params&&this._reqObj.putSFSObject(InviteUsersRequest.KEY_PARAMS,this._params)}}class SetMMOItemVariables{static KEY_ROOM_ID=\"r\";static KEY_ITEM_ID=\"i\";static KEY_VAR_LIST=\"v\"}class SetUserPositionRequest extends BaseRequest{static KEY_ROOM=\"r\";static KEY_VEC3D=\"v\";static KEY_PLUS_USER_LIST=\"p\";static KEY_MINUS_USER_LIST=\"m\";static KEY_PLUS_ITEM_LIST=\"q\";static KEY_MINUS_ITEM_LIST=\"n\";constructor(e,t=null){super(Ls.System.SetUserPosition),this._pos=e,this._room=t,Object.seal(this)}validate(e){const t=[];if(null!=this._pos&&this._pos instanceof Vec3D||t.push(\"Position must be an instance of Vec3D class\"),null==this._room){if(!(null!=e.lastJoinedRoom&&e.lastJoinedRoom instanceof MMORoom))return void t.push(\"A valid MMORoom must be provided\");this._room=e.lastJoinedRoom}if(this._room instanceof MMORoom||t.push(\"Target room must be an instance of MMORoom class\"),e.getJoinedRooms().indexOf(this._room)<0&&t.push(\"You are not joined in the target Room: \"+this._room),t.length>0)throw new SFSValidationError(\"SetUserPosition Error\",t)}execute(e){this._reqObj.putInt(SetUserPositionRequest.KEY_ROOM,this._room.id),this._pos.isFloat?this._reqObj.putFloatArray(SetUserPositionRequest.KEY_VEC3D,this._pos.toArray()):this._reqObj.putIntArray(SetUserPositionRequest.KEY_VEC3D,this._pos.toArray())}}class InitBuddyListRequest extends BaseRequest{static KEY_BLIST=\"bl\";static KEY_BUDDY_STATES=\"bs\";static KEY_MY_VARS=\"mv\";constructor(){super(Ls.System.InitBuddyList),Object.seal(this)}validate(e){const t=[];if(e.buddyManager.isInited&&t.push(\"BuddyList system is already initialized\"),t.length>0)throw new SFSValidationError(\"InitBuddyList request error\",t)}execute(e){}}class AddBuddyRequest extends BaseRequest{static KEY_BUDDY_NAME=\"bn\";constructor(e){super(Ls.System.AddBuddy),this._name=e,Object.seal(this)}validate(e){const t=[];e.buddyManager.isInited||t.push(\"BuddyList system is not initialized; please send an InitBuddyRequest first\"),(null==this._name||this._name.length<1)&&t.push(\"Invalid buddy name: \"+this._name),!1===e.buddyManager.myOnlineState&&t.push(\"Cannot add buddy while off-line\");const s=e.buddyManager.getBuddyByName(this._name);if(null==s||s.isTemp||t.push(\"Cannot add buddy, it is already in your list: \"+this._name),t.length>0)throw new SFSValidationError(\"AddBuddy request error\",t)}execute(e){this._reqObj.putString(AddBuddyRequest.KEY_BUDDY_NAME,this._name)}}class RemoveBuddyRequest extends BaseRequest{static KEY_BUDDY_NAME=\"bn\";constructor(e){super(Ls.System.RemoveBuddy),this._name=e,Object.seal(this)}validate(e){const t=[];if(e.buddyManager.isInited||t.push(\"BuddyList system is not initialized; please send an InitBuddyRequest first\"),!1===e.buddyManager.myOnlineState&&t.push(\"Cannot remove buddy while offline\"),null==this._name||this._name.length<1?t.push(\"Invalid buddy name: \"+this._name):e.buddyManager.containsBuddy(this._name)||t.push(\"Cannot remove buddy that is not in your list: \"+this._name),t.length>0)throw new SFSValidationError(\"RemoveBuddy request error\",t)}execute(e){this._reqObj.putString(RemoveBuddyRequest.KEY_BUDDY_NAME,this._name)}}class BlockBuddyRequest extends BaseRequest{static KEY_BUDDY_NAME=\"bn\";static KEY_BUDDY_BLOCK_STATE=\"bs\";static KEY_BUDDY=\"bd\";constructor(e,t){super(Ls.System.BlockBuddy),this._name=e,this._blocked=t,Object.seal(this)}validate(e){const t=[];if(e.buddyManager.isInited||t.push(\"BuddyList system is not initialized; please send an InitBuddyRequest first\"),!1===e.buddyManager.myOnlineState&&t.push(\"Cannot block buddy while offline\"),null==this._name||this._name.length<1)t.push(\"Invalid buddy name: \"+this._name);else{const s=e.buddyManager.getBuddyByName(this._name);null==s?t.push(\"Cannot block buddy that is not in your list: \"+this._name):s.isBlocked==this._blocked&&t.push(\"Block flag is already in the requested state: \"+this._blocked+\" (buddy: \"+this._name+\")\")}if(t.length>0)throw new SFSValidationError(\"BlockBuddy request error\",t)}execute(e){this._reqObj.putString(BlockBuddyRequest.KEY_BUDDY_NAME,this._name),this._reqObj.putBool(BlockBuddyRequest.KEY_BUDDY_BLOCK_STATE,this._blocked)}}class GoOnlineRequest extends BaseRequest{static KEY_ONLINE=\"o\";static KEY_BUDDY_NAME=\"bn\";static KEY_BUDDY_ID=\"bi\";constructor(e){super(Ls.System.GoOnline),this._online=e,Object.seal(this)}validate(e){const t=[];if(e.buddyManager.isInited||t.push(\"BuddyList system is not initialized; please send an InitBuddyRequest first\"),t.length>0)throw new SFSValidationError(\"GoOnline request error\",t)}execute(e){e.buddyManager._setMyOnlineState(this._online),this._reqObj.putBool(GoOnlineRequest.KEY_ONLINE,this._online)}}class SetBuddyVariablesRequest extends BaseRequest{static KEY_BUDDY_NAME=\"bn\";static KEY_BUDDY_VARS=\"bv\";constructor(e){super(Ls.System.SetBuddyVariables),this._buddyVariables=e,Object.seal(this)}validate(e){const t=[];if(e.buddyManager.isInited||t.push(\"BuddyList system is not initialized; please send an InitBuddyRequest first\"),!1===e.buddyManager.myOnlineState&&t.push(\"Cannot set buddy variables while offline\"),null==this._buddyVariables?t.push(\"No variables were specified\"):this._buddyVariables instanceof Array?0===this._buddyVariables.length?t.push(\"No variables were specified\"):this._buddyVariables.every(e=>e instanceof SFSBuddyVariable)||t.push(\"Buddy Variables must be passed as instances of SFSBuddyVariable class\"):t.push(\"Buddy Variables must be passed in an array\"),t.length>0)throw new SFSValidationError(\"SetBuddyVariables request error\",t)}execute(e){try{const e=new SFSArray;for(let t of this._buddyVariables)e.addSFSArray(t.toSFSArray());this._reqObj.putSFSArray(SetBuddyVariablesRequest.KEY_BUDDY_VARS,e)}catch(e){throw e instanceof SFSTypeError?new SFSTypeError(\"Invalid Buddy Variable: \"+e.message):e}}}class PingPongRequest extends BaseRequest{constructor(){super(Ls.System.PingPong),Object.seal(this)}validate(e){}execute(e){}}class LagValue{constructor(e,t,s){this._avg=e,this._min=t,this._max=s,Object.seal(this)}get average(){return this._avg}get minimum(){return this._min}get maximum(){return this._max}toString(){return`[LagValue: avg ${this._round(this._avg)} ms; min ${this._round(this._min)} ms; max ${this._round(this._max)} ms]`}_round(e){return Number(e.toFixed(2))}}class LagMonitor{constructor(e,t=4,s=10){this._sfs=e,this._valueQueue=[],this._interval=t,this._queueSize=s,this._thread=null,this._lastReqTime=-1,this._minValue=Number.MAX_VALUE,this._maxValue=0}get isRunning(){return null!=this._thread}get minValue(){return this._minValue}get maxValue(){return this._maxValue}start(){this.isRunning||null==this._sfs||(this._thread=setInterval(this._threadRunner,1e3*this._interval,this))}stop(){this.isRunning&&(clearInterval(this._thread),this._thread=null,this._valueQueue=[])}destroy(){this.stop(),this._sfs=null}getLastPingTime(){return this._valueQueue.length>0?this._valueQueue[this._valueQueue.length-1]:0}_threadRunner(e){e._lastReqTime=(new Date).getTime(),e._sfs.send(new PingPongRequest)}_onPingPong(){const e=(new Date).getTime()-this._lastReqTime;return this._minValue>e&&(this._minValue=e),this._maxValue<e&&(this._maxValue=e),this._valueQueue.length>=this._queueSize&&this._valueQueue.shift(),this._valueQueue.push(e),this._getAveragePingTime()}_getAveragePingTime(){if(0==this._valueQueue.length)return 0;let e=0;for(let t=0;t<this._valueQueue.length;t++)e+=this._valueQueue[t];return e/this._valueQueue.length}}class SystemController{static CONTROLLER_ID=Fs.SYSTEM;static KEY_ERROR_CODE=\"ec\";static KEY_ERROR_PARAMS=\"ep\";static ROOM_PARAM=\"r\";static USER_PARAM=\"u\";static USER_COUNT_PARAM=\"uc\";static SPECT_COUNT_PARAM=\"sc\";static DISCONNECTION_REASON_PARAM=\"dr\";static HOST_PARAM=\"h\";static ACCESS_TOKEN_PARAM=\"at\";static ZONE_PARAM=\"z\";constructor(e){this._sfs=e,this._logger=Logger.getInstance(SystemController.name),this._responseHandlers=new Map,this._initRequestHandlers(),Object.freeze(this)}get id(){return SystemController.CONTROLLER_ID}handleMessage(e,t){const s=this._responseHandlers.get(t);null!=s?(this._logger.isDebugEnabled&&this._logger.debug(`System Request: ${s.name} (${t})`),s.handler.call(this,e)):this._logger.warn(`Unknown request id: ${t}`)}_initRequestHandlers(){this._setHandler(Ls.System.Handshake,this._resHandshake),this._setHandler(Ls.System.Login,this._resLogin),this._setHandler(Ls.System.Logout,this._resLogout),this._setHandler(Ls.System.JoinRoom,this._resJoinRoom),this._setHandler(Ls.System.CreateRoom,this._resCreateRoom),this._setHandler(Ls.System.ChangeRoomName,this._resChangeRoomName),this._setHandler(Ls.System.ChangeRoomPassword,this._resChangeRoomPassword),this._setHandler(Ls.System.ChangeRoomCapacity,this._resChangeRoomCapacity),this._setHandler(Ls.System.GenericMessage,this._resGenericMessage),this._setHandler(Ls.System.SetRoomVariables,this._resSetRoomVariables),this._setHandler(Ls.System.SetUserVariables,this._resSetUserVariables),this._setHandler(Ls.System.SubscribeRoomGroup,this._resSubscribeRoomGroup),this._setHandler(Ls.System.UnsubscribeRoomGroup,this._resUnsubscribeRoomGroup),this._setHandler(Ls.System.SpectatorToPlayer,this._resSpectatorToPlayer),this._setHandler(Ls.System.PlayerToSpectator,this._resPlayerToSpectator),this._setHandler(Ls.System.FindRooms,this._resFindRooms),this._setHandler(Ls.System.FindUsers,this._resFindUsers),this._setHandler(Ls.System.PingPong,this._resPingPong),this._setHandler(Ls.System.InitBuddyList,this._resInitBuddyList),this._setHandler(Ls.System.AddBuddy,this._resAddBuddy),this._setHandler(Ls.System.RemoveBuddy,this._resRemoveBuddy),this._setHandler(Ls.System.BlockBuddy,this._resBlockBuddy),this._setHandler(Ls.System.GoOnline,this._resGoOnline),this._setHandler(Ls.System.SetBuddyVariables,this._resSetBuddyVariables),this._setHandler(Ls.System.QuickJoinGame,this._resQuickJoinGame),this._setHandler(Ls.System.InviteUsers,this._resInviteUsers),this._setHandler(Ls.System.InvitationReply,this._resInvitationReply),this._setHandler(Ls.System.SetUserPosition,this._resSetUserPosition),this._setHandler(Ls.System.GameServerConnectionRequired,this._resGameServerConnectionRequired),this._setHandler(1e3,this._resUserEnterRoom,\"UserEnterRoom\"),this._setHandler(1001,this._resUserCountChange,\"UserCountChange\"),this._setHandler(1002,this._resUserLost,\"UserLost\"),this._setHandler(1003,this._resRoomLost,\"RoomLost\"),this._setHandler(1004,this._resUserExitRoom,\"UserExitRoom\"),this._setHandler(1005,this._resClientDisconnection,\"ClientDisconnection\"),this._setHandler(1006,this._resReconnectionFailure,\"ReconnectionFailure\"),this._setHandler(1007,this._resSetMMOItemVariables,\"SetMMOItemVariables\"),this._setHandler(1600,this._resLoadBalancerError,\"LoadBalancerError\")}_setHandler(e,t,s){this._responseHandlers.set(e,{name:null!=s?s:Ls.getNameFromId(this.id,e),handler:t})}_resHandshake(e){this._sfs._handleHandShake(e)}_resLogin(s){if(this._isSuccessResponse(s)){this._sfs.roomManager._updateRoomList(s.getSFSArray(LoginRequest.KEY_ROOMLIST)),this._sfs._mySelf=new SFSUser(s.getNumber(LoginRequest.KEY_ID),s.getString(LoginRequest.KEY_USER_NAME),!0),this._sfs.mySelf._setUserManager(this._sfs.userManager),this._sfs.mySelf._privilegeId=s.getNumber(LoginRequest.KEY_PRIVILEGE_ID),this._sfs.userManager._addUser(this._sfs.mySelf),this._sfs._setReconnectionSeconds(s.getNumber(LoginRequest.KEY_RECONNECTION_SECONDS));let i=s.getSFSObject(LoginRequest.KEY_PARAMS);if(null!=i){let e=i.getString(LoginRequest.KEY_CLUSTER_SID);null!=e&&(this._sfs._nodeId=e)}const r={[e.ZoneName]:s.getString(LoginRequest.KEY_ZONE_NAME),[e.User]:this._sfs.mySelf,[e.Data]:s.getSFSObject(LoginRequest.KEY_PARAMS)};this._sfs._dispatchEvent(t.LOGIN,r)}else this._dispatchError(t.LOGIN_ERROR,s)}_resLogout(e){this._sfs._handleLogout(e)}_resJoinRoom(s){if(this._sfs._isJoining=!1,this._isSuccessResponse(s)){const i=this._sfs.roomManager,r=this._sfs.userManager,n=s.getSFSArray(JoinRoomRequest.KEY_ROOM),a=s.getSFSArray(JoinRoomRequest.KEY_USER_LIST);let o=SFSRoom.fromSFSArray(n);o._setRoomManager(i),i._addRoom(o,i.containsGroup(o.groupId));for(let e=0;e<a.size();e++){const t=a.getSFSArray(e),s=r.getOrCreateUser(t,o);o._addUser(s)}o._isJoined=!0,this._sfs._lastJoinedRoom=o;const h={[e.Room]:o};this._sfs._dispatchEvent(t.ROOM_JOIN,h)}else this._dispatchError(t.ROOM_JOIN_ERROR,s)}_resCreateRoom(s){if(this._isSuccessResponse(s)){const i=this._sfs.roomManager,r=SFSRoom.fromSFSArray(s.getSFSArray(CreateRoomRequest.KEY_ROOM));r._setRoomManager(i),i._addRoom(r);const n={[e.Room]:r};this._sfs._dispatchEvent(t.ROOM_ADD,n)}else this._dispatchError(t.ROOM_CREATION_ERROR,s)}_resGenericMessage(e){switch(e.getNumber(GenericMessageRequest.KEY_MESSAGE_TYPE)){case Js.PUBLIC_MSG:this._handlePublicMessage(e);break;case Js.PRIVATE_MSG:this._handlePrivateMessage(e);break;case Js.BUDDY_MSG:this._handleBuddyMessage(e);break;case Js.MODERATOR_MSG:this._handleModMessage(e);break;case Js.ADMIN_MSG:this._handleAdminMessage(e);break;case Js.OBJECT_MSG:this._handleObjectMessage(e)}}_handlePublicMessage(s){const i=s.getNumber(GenericMessageRequest.KEY_ROOM_ID),r=this._sfs.roomManager.getRoomById(i);if(null!=r){const i={[e.Room]:r,[e.Sender]:this._sfs.userManager.getUserById(s.getNumber(GenericMessageRequest.KEY_USER_ID)),[e.Message]:s.getString(GenericMessageRequest.KEY_MESSAGE),[e.Data]:s.getSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS)};this._sfs._dispatchEvent(t.PUBLIC_MESSAGE,i)}else this._logger.warn(\"Unexpected; public message target room doesn't exist. Room id: \"+i)}_handlePrivateMessage(s){const i=s.getNumber(GenericMessageRequest.KEY_USER_ID);let r=this._sfs.userManager.getUserById(i);if(null==r){if(!s.containsKey(GenericMessageRequest.KEY_SENDER_DATA))return void this._logger.warn(\"Unexpected; private message has no sender details\");r=SFSUser.fromSFSArray(s.getSFSArray(GenericMessageRequest.KEY_SENDER_DATA))}const n={[e.Sender]:r,[e.Message]:s.getString(GenericMessageRequest.KEY_MESSAGE),[e.Data]:s.getSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS)};this._sfs._dispatchEvent(t.PRIVATE_MESSAGE,n)}_handleBuddyMessage(t){const i=t.getNumber(GenericMessageRequest.KEY_USER_ID),r=this._sfs.buddyManager.getBuddyById(i),n={[e.IsItMe]:this._sfs.mySelf.id===i,[e.Buddy]:r,[e.Message]:t.getString(GenericMessageRequest.KEY_MESSAGE),[e.Data]:t.getSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS)};this._sfs._dispatchEvent(s.BUDDY_MESSAGE,n)}_handleModMessage(s){const i={[e.Sender]:SFSUser.fromSFSArray(s.getSFSArray(GenericMessageRequest.KEY_SENDER_DATA)),[e.Message]:s.getString(GenericMessageRequest.KEY_MESSAGE),[e.Data]:s.getSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS)};this._sfs._dispatchEvent(t.MODERATOR_MESSAGE,i)}_handleAdminMessage(s){const i={[e.Sender]:SFSUser.fromSFSArray(s.getSFSArray(GenericMessageRequest.KEY_SENDER_DATA)),[e.Message]:s.getString(GenericMessageRequest.KEY_MESSAGE),[e.Data]:s.getSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS)};this._sfs._dispatchEvent(t.ADMIN_MESSAGE,i)}_handleObjectMessage(s){const i=s.getNumber(GenericMessageRequest.KEY_USER_ID),r={[e.Sender]:this._sfs.userManager.getUserById(i),[e.Message]:s.getSFSObject(GenericMessageRequest.KEY_XTRA_PARAMS)};this._sfs._dispatchEvent(t.OBJECT_MESSAGE,r)}_resChangeRoomName(s){if(this._isSuccessResponse(s)){const i=s.getNumber(ChangeRoomNameRequest.KEY_ROOM),r=this._sfs.roomManager.getRoomById(i);if(null!=r){const i=r.name;this._sfs.roomManager._changeRoomName(r,s.getString(ChangeRoomNameRequest.KEY_NAME));const n={[e.OldName]:i,[e.Room]:r};this._sfs._dispatchEvent(t.ROOM_NAME_CHANGE,n)}else this._logger.warn(`Room not found, id: ${i}; Room name change failed`)}else this._dispatchError(t.ROOM_NAME_CHANGE_ERROR,s)}_resChangeRoomPassword(s){if(this._isSuccessResponse(s)){const i=s.getNumber(ChangeRoomPasswordStateRequest.KEY_ROOM),r=this._sfs.roomManager.getRoomById(i);if(null!=r){this._sfs.roomManager._changeRoomPasswordState(r,s.getBool(ChangeRoomPasswordStateRequest.KEY_PASS));const i={[e.Room]:r};this._sfs._dispatchEvent(t.ROOM_PASSWORD_STATE_CHANGE,i)}else this._logger.warn(`Room not found, id: ${i}; Room password change failed`)}else this._dispatchError(t.ROOM_PASSWORD_STATE_CHANGE_ERROR,s)}_resChangeRoomCapacity(s){if(this._isSuccessResponse(s)){const i=s.getNumber(ChangeRoomCapacityRequest.KEY_ROOM),r=this._sfs.roomManager.getRoomById(i);if(null!=r){this._sfs.roomManager._changeRoomCapacity(r,s.getNumber(ChangeRoomCapacityRequest.KEY_USER_SIZE),s.getNumber(ChangeRoomCapacityRequest.KEY_SPEC_SIZE));const i={[e.Room]:r};this._sfs._dispatchEvent(t.ROOM_CAPACITY_CHANGE,i)}else this._logger.warn(`Room not found, id: ${i}; Room capacity change failed`)}else this._dispatchError(t.ROOM_CAPACITY_CHANGE_ERROR,s)}_resSetRoomVariables(s){const i=s.getNumber(SetRoomVariablesRequest.KEY_VAR_ROOM),r=s.getSFSArray(SetRoomVariablesRequest.KEY_VAR_LIST),n=this._sfs.roomManager.getRoomById(i),a=new Set;if(null!=n){for(let e=0;e<r.size();e++){const t=SFSRoomVariable.fromSFSArray(r.getSFSArray(e));n._setVariable(t),a.add(t.name)}const s={[e.ChangedVars]:Array.from(a),[e.Room]:n};this._sfs._dispatchEvent(t.ROOM_VARIABLES_UPDATE,s)}else this._logger.warn(\"RoomVariablesUpdate, unknown Room id: \"+i)}_resSetUserVariables(s){const i=s.getNumber(SetUserVariablesRequest.KEY_USER),r=s.getSFSArray(SetUserVariablesRequest.KEY_VAR_LIST),n=this._sfs.userManager.getUserById(i),a=new Set;if(null!=n){for(let e=0;e<r.size();e++){const t=SFSUserVariable.fromSFSArray(r.getSFSArray(e));n._setVariable(t),a.add(t.name)}const s={[e.ChangedVars]:Array.from(a),[e.User]:n};this._sfs._dispatchEvent(t.USER_VARIABLES_UPDATE,s)}else this._logger.warn(\"UserVariablesUpdate: unknown user id: \"+i)}_resSubscribeRoomGroup(s){if(this._isSuccessResponse(s)){const i=s.getString(SubscribeRoomGroupRequest.KEY_GROUP_ID);this._sfs.roomManager.containsGroup(i)&&this._logger.warn(`SubscribeRoomGroup: Group ${i} already subscribed`),this._sfs.roomManager._addGroup(i);const r=s.getSFSArray(SubscribeRoomGroupRequest.KEY_ROOM_LIST);this._sfs.roomManager._updateRoomList(r);const n={[e.GroupId]:i,[e.NewRooms]:this._sfs.roomManager.getRoomListFromGroup(i)};this._sfs._dispatchEvent(t.ROOM_GROUP_SUBSCRIBE,n)}else this._dispatchError(t.ROOM_GROUP_SUBSCRIBE_ERROR,s)}_resUnsubscribeRoomGroup(s){if(this._isSuccessResponse(s)){const i=s.getString(UnsubscribeRoomGroupRequest.KEY_GROUP_ID);this._sfs.roomManager.containsGroup(i)||this._logger.warn(`UnsubscribeRoomGroup: Group ${i} not subscribed`),this._sfs.roomManager._removeGroup(i);const r={[e.GroupId]:i};this._sfs._dispatchEvent(t.ROOM_GROUP_UNSUBSCRIBE,r)}else this._dispatchError(t.ROOM_GROUP_UNSUBSCRIBE_ERROR,s)}_resSpectatorToPlayer(s){if(this._isSuccessResponse(s)){const i=s.getNumber(SpectatorToPlayerRequest.KEY_ROOM_ID),r=s.getNumber(SpectatorToPlayerRequest.KEY_USER_ID),n=s.getNumber(SpectatorToPlayerRequest.KEY_PLAYER_ID),a=this._sfs.userManager.getUserById(r),o=this._sfs.roomManager.getRoomById(i);if(null!=o)if(null!=a)if(a.isJoinedInRoom(o)){a._setPlayerId(n,o);const s={[e.Room]:o,[e.User]:a,[e.PlayerId]:n};this._sfs._dispatchEvent(t.SPECTATOR_TO_PLAYER,s)}else this._logger.warn(`User: ${a} not joined in Room: ${o}, SpectatorToPlayer failed`);else this._logger.warn(`User not found, id: ${r}, SpectatorToPlayer failed`);else this._logger.warn(`Room not found, id: ${i}, SpectatorToPlayer failed`)}else this._dispatchError(t.SPECTATOR_TO_PLAYER_ERROR,s)}_resPlayerToSpectator(s){if(this._isSuccessResponse(s)){const i=s.getNumber(PlayerToSpectatorRequest.KEY_ROOM_ID),r=s.getNumber(PlayerToSpectatorRequest.KEY_USER_ID),n=this._sfs.userManager.getUserById(r),a=this._sfs.roomManager.getRoomById(i);if(null!=a)if(null!=n)if(n.isJoinedInRoom(a)){n._setPlayerId(-1,a);const s={[e.Room]:a,[e.User]:n};this._sfs._dispatchEvent(t.PLAYER_TO_SPECTATOR,s)}else this._logger.warn(`User: ${n} not joined in Room: ${a}, PlayerToSpectator failed`);else this._logger.warn(`User not found, id: ${r}, PlayerToSpectator failed`);else this._logger.warn(`Room not found, id: ${i}, PlayerToSpectator failed`)}else this._dispatchError(t.PLAYER_TO_SPECTATOR_ERROR,s)}_resFindRooms(s){const i=s.getSFSArray(FindRoomsRequest.KEY_FILTERED_ROOMS),r=[];for(var n=0;n<i.size();n++){const e=SFSRoom.fromSFSArray(i.getSFSArray(n)),t=this._sfs.roomManager.getRoomById(e.id);null!=t&&(e._isJoined=t._isJoined),r.push(e)}const a={[e.RoomList]:r};this._sfs._dispatchEvent(t.ROOM_FIND_RESULT,a)}_resFindUsers(s){const i=s.getSFSArray(FindUsersRequest.KEY_FILTERED_USERS),r=[],n=this._sfs.mySelf;for(var a=0;a<i.size();a++){let e=SFSUser.fromSFSArray(i.getSFSArray(a));e.id===n.id&&(e=n),r.push(e)}const o={[e.UserList]:r};this._sfs._dispatchEvent(t.USER_FIND_RESULT,o)}_resPingPong(s){if(null!=this._sfs._lagMonitor){const s={[e.LagValue]:new LagValue(this._sfs._lagMonitor._onPingPong(),this._sfs._lagMonitor.minValue,this._sfs._lagMonitor.maxValue)};this._sfs._dispatchEvent(t.PING_PONG,s)}}_resInitBuddyList(t){if(this._isSuccessResponse(t)){const r=t.getSFSArray(InitBuddyListRequest.KEY_BLIST),n=t.getSFSArray(InitBuddyListRequest.KEY_MY_VARS),a=t.getStringArray(InitBuddyListRequest.KEY_BUDDY_STATES);this._sfs.buddyManager._clearAll();for(let e=0;e<r.size();e++){const t=SFSBuddy.fromSFSArray(r.getSFSArray(e));this._sfs.buddyManager._addBuddy(t)}null!=a&&this._sfs.buddyManager._setBuddyStates(a);var i=[];for(let e=0;e<n.size();e++){const t=SFSBuddyVariable.fromSFSArray(n.getSFSArray(e));i.push(t)}this._sfs.buddyManager._setMyVariables(i),this._sfs.buddyManager._setInited();const o={[e.BuddyList]:this._sfs.buddyManager.buddyList,[e.MyBuddyVars]:this._sfs.buddyManager.getMyVariables()};this._sfs._dispatchEvent(s.BUDDY_LIST_INIT,o)}else this._dispatchError(s.BUDDY_ERROR,t)}_resAddBuddy(t){if(this._isSuccessResponse(t)){const i=SFSBuddy.fromSFSArray(t.getSFSArray(AddBuddyRequest.KEY_BUDDY_NAME));this._sfs.buddyManager._addBuddy(i);const r={[e.Buddy]:i};this._sfs._dispatchEvent(s.BUDDY_ADD,r)}else this._dispatchError(s.BUDDY_ERROR,t)}_resRemoveBuddy(t){if(this._isSuccessResponse(t)){const i=t.getString(RemoveBuddyRequest.KEY_BUDDY_NAME),r=this._sfs.buddyManager._removeBuddyByName(i);if(null!=r){const t={[e.Buddy]:r};this._sfs._dispatchEvent(s.BUDDY_REMOVE,t)}else this._logger.warn(\"RemoveBuddy failed; buddy not found: \"+i)}else this._dispatchError(s.BUDDY_ERROR,t)}_resBlockBuddy(t){if(this._isSuccessResponse(t)){const i=t.getString(BlockBuddyRequest.KEY_BUDDY_NAME);let r=this._sfs.buddyManager.getBuddyByName(i);t.containsKey(BlockBuddyRequest.KEY_BUDDY)?(r=SFSBuddy.fromSFSArray(t.getSFSArray(BlockBuddyRequest.KEY_BUDDY)),this._sfs.buddyManager._addBuddy(r)):null!=r?r._isBlocked=t.getBool(BlockBuddyRequest.KEY_BUDDY_BLOCK_STATE):this._logger.warn(\"BlockBuddy failed; buddy not found: \"+i);const n={[e.Buddy]:r};this._sfs._dispatchEvent(s.BUDDY_BLOCK,n)}else this._dispatchError(s.BUDDY_ERROR,t)}_resGoOnline(t){if(this._isSuccessResponse(t)){const i=t.getString(GoOnlineRequest.KEY_BUDDY_NAME),r=this._sfs.buddyManager.getBuddyByName(i),n=i===this._sfs.mySelf.name,a=t.getNumber(GoOnlineRequest.KEY_ONLINE),o=a===Ps.ONLINE;let h=!0;if(n)this._sfs.buddyManager.myOnlineState!=o&&(this._logger.warn(\"Unexpected: myOnlineState is not in synch with the server; updating to: \"+o),this._sfs.buddyManager._setMyOnlineState(o));else{if(null==r)return void this._logger.warn(\"GoOnline failed; buddy not found: \"+i);{r._id=t.getNumber(GoOnlineRequest.KEY_BUDDY_ID);const e=new SFSBuddyVariable(ks.BV_ONLINE,o,Bs.BOOLEAN);r._setVariable(e),a===Ps.LEFT_THE_SERVER&&r._clearVolatileVariables(),h=this._sfs.buddyManager.myOnlineState}}if(h){const t={[e.Buddy]:r,[e.IsItMe]:n};this._sfs._dispatchEvent(s.BUDDY_ONLINE_STATE_CHANGE,t)}}else this._dispatchError(s.BUDDY_ERROR,t)}_resSetBuddyVariables(t){if(this._isSuccessResponse(t)){const i=t.getString(SetBuddyVariablesRequest.KEY_BUDDY_NAME),r=t.getSFSArray(SetBuddyVariablesRequest.KEY_BUDDY_VARS),n=this._sfs.buddyManager.getBuddyByName(i),a=i===this._sfs.mySelf.name,o=[],h=[];let l=!0;for(let e=0;e<r.size();e++){const t=SFSBuddyVariable.fromSFSArray(r.getSFSArray(e));h.push(t),o.push(t.name)}if(a)this._sfs.buddyManager._setMyVariables(h);else{if(null==n)return void this._logger.warn(\"Unexpected; target of BuddyVariables update not found: \"+i);n._setVariables(h),l=this._sfs.buddyManager.myOnlineState}if(l){const t={[e.Buddy]:n,[e.IsItMe]:a,[e.ChangedVars]:o};this._sfs._dispatchEvent(s.BUDDY_VARIABLES_UPDATE,t)}}else this._dispatchError(s.BUDDY_ERROR,t)}_resQuickJoinGame(e){this._isSuccessResponse(e)||this._dispatchError(t.ROOM_JOIN_ERROR,e)}_resInviteUsers(s){let i=null;i=s.containsKey(InviteUsersRequest.KEY_USER_ID)?this._sfs.userManager.getUserById(s.getNumber(InviteUsersRequest.KEY_USER_ID)):SFSUser.fromSFSArray(s.getSFSArray(InviteUsersRequest.KEY_USER));const r=s.getNumber(InviteUsersRequest.KEY_TIME),n=s.getNumber(InviteUsersRequest.KEY_INVITATION_ID),a=s.getSFSObject(InviteUsersRequest.KEY_PARAMS),o=new SFSInvitation(i,this._sfs.mySelf,r,a);o._id=n;const h={[e.Invitation]:o};this._sfs._dispatchEvent(t.INVITATION,h)}_resInvitationReply(s){if(this._isSuccessResponse(s)){let i=null;i=s.containsKey(InviteUsersRequest.KEY_USER_ID)?this._sfs.userManager.getUserById(s.getNumber(InviteUsersRequest.KEY_USER_ID)):SFSUser.fromSFSArray(s.getSFSArray(InviteUsersRequest.KEY_USER));const r=s.getNumber(InviteUsersRequest.KEY_REPLY_ID),n=s.getSFSObject(InviteUsersRequest.KEY_PARAMS),a={[e.Invitee]:i,[e.Reply]:r,[e.Data]:n};this._sfs._dispatchEvent(t.INVITATION_REPLY,a)}else this._dispatchError(t.INVITATION_REPLY_ERROR,s)}_resSetUserPosition(s){const i=s.getNumber(SetUserPositionRequest.KEY_ROOM),r=s.getNumberArray(SetUserPositionRequest.KEY_MINUS_USER_LIST),n=s.getSFSArray(SetUserPositionRequest.KEY_PLUS_USER_LIST),a=s.getNumberArray(SetUserPositionRequest.KEY_MINUS_ITEM_LIST),o=s.getSFSArray(SetUserPositionRequest.KEY_PLUS_ITEM_LIST),h=this._sfs.userManager,l=this._sfs.roomManager.getRoomById(i);if(null==l)return void this._logger.warn(\"Target MMORoom is null: \"+i);const u=[],_=[],c=[],d=[];if(null!=r)for(let e of r){const t=l.getUserById(e);null!=t&&(l._removeUser(t),_.push(t))}if(null!=n)for(let e=0;e<n.size();e++){const t=n.getSFSArray(e),s=h.getOrCreateUser(t,l);if(u.push(s),l._addUser(s),t.size()>5){const e=t.get(5);s._aoiEntryPoint=Vec3D.fromArray(e)}}if(null!=a)for(let e of a){const t=l.getMMOItem(e);null!=t&&(l._removeMMOItem(e),d.push(t))}if(null!=o)for(let e=0;e<o.size();e++){const t=o.getSFSArray(e),s=MMOItem.fromSFSArray(t);if(c.push(s),l._addMMOItem(s),t.size()>2){const e=t.get(2);s._aoiEntryPoint=Vec3D.fromArray(e)}}const m={[e.AddedItems]:c,[e.RemovedItems]:d,[e.RemovedUsers]:_,[e.AddedUsers]:u,[e.Room]:l};this._sfs._dispatchEvent(t.PROXIMITY_LIST_UPDATE,m)}_resGameServerConnectionRequired(t){const s=t.getString(SystemController.HOST_PARAM),i=t.getString(SystemController.ACCESS_TOKEN_PARAM),n=t.getString(SystemController.ZONE_PARAM),a=this._sfs.config.port,o=new ConfigData;o.host=s,o.port=a,o.zone=n;const h={[e.ClusterConfigData]:config,[e.ClusterUserName]:this._sfs.mySelf.name,[e.ClusterPassword]:i};this._sfs._dispatchEvent(r.CONNECTION_REQUIRED,h)}_resUserEnterRoom(s){const i=this._sfs.roomManager.getRoomById(s.getNumber(SystemController.ROOM_PARAM));if(null!=i){const r=s.getSFSArray(SystemController.USER_PARAM),n=this._sfs.userManager.getOrCreateUser(r,i);i._addUser(n);const a={[e.User]:n,[e.Room]:i};this._sfs._dispatchEvent(t.USER_ENTER_ROOM,a)}}_resUserCountChange(s){const i=this._sfs.roomManager.getRoomById(s.getNumber(SystemController.ROOM_PARAM));if(null!=i){const r=s.getNumber(SystemController.USER_COUNT_PARAM);let n=0;s.containsKey(SystemController.SPECT_COUNT_PARAM)&&(n=s.getNumber(SystemController.SPECT_COUNT_PARAM)),i._userCount=r,i._specCount=n;const a={[e.Room]:i,[e.UserCount]:r,[e.SpecCount]:n};this._sfs._dispatchEvent(t.USER_COUNT_CHANGE,a)}}_resUserLost(s){const i=s.getNumber(SystemController.USER_PARAM),r=this._sfs.userManager.getUserById(i);if(null!=r){const s=this._sfs.roomManager.getUserRooms(r);this._sfs.roomManager._removeUser(r),this._sfs.userManager._removeUser(r);for(let i of s){const s={[e.User]:r,[e.Room]:i};this._sfs._dispatchEvent(t.USER_EXIT_ROOM,s)}}}_resRoomLost(s){const i=s.getNumber(SystemController.ROOM_PARAM),r=this._sfs.roomManager.getRoomById(i);if(null!=r){this._sfs.roomManager._removeRoom(r);for(let e of r.userList)this._sfs.userManager._removeUser(e);const s={[e.Room]:r};this._sfs._dispatchEvent(t.ROOM_REMOVE,s)}}_resUserExitRoom(s){const i=s.getNumber(SystemController.ROOM_PARAM),r=s.getNumber(SystemController.USER_PARAM),n=this._sfs.roomManager.getRoomById(i),a=this._sfs.userManager.getUserById(r);if(null!=n&&null!=a){n._removeUser(a),this._sfs.userManager._removeUser(a),a.isItMe&&n.isJoined&&(n._isJoined=!1,0===this._sfs.roomManager.getJoinedRooms().length&&(this._sfs._lastJoinedRoom=null),n._isManaged||this._sfs.roomManager._removeRoom(n));const s={[e.User]:a,[e.Room]:n};this._sfs._dispatchEvent(t.USER_EXIT_ROOM,s)}else this._logger.warn(`Failed to handle UserExit event; Room: ${n}, User: ${a}`)}_resClientDisconnection(e){const t=e.getNumber(SystemController.DISCONNECTION_REASON_PARAM);this._sfs._socketEngine.disconnect(Ms.getReason(t))}_resReconnectionFailure(e){this._sfs._socketEngine.completeReconnection(!1)}_resSetMMOItemVariables(s){const i=s.getNumber(SetMMOItemVariables.KEY_ROOM_ID),r=s.getNumber(SetMMOItemVariables.KEY_ITEM_ID),n=s.getSFSArray(SetMMOItemVariables.KEY_VAR_LIST),a=this._sfs.roomManager.getRoomById(i),o=new Set;if(null!=a){const s=a.getMMOItem(r);if(null!=s){for(let e=0;e<n.size();e++){const t=MMOItemVariable.fromSFSArray(n.getSFSArray(e));s._setVariable(t),o.add(t.name)}const i={[e.ChangedVars]:Array.from(o),[e.MMOItem]:s,[e.Room]:a};this._sfs._dispatchEvent(t.MMOITEM_VARIABLES_UPDATE,i)}}}_resLoadBalancerError(e){this._sfs._dispatchEvent(r.LOAD_BALANCER_ERROR,{})}_isSuccessResponse(e){return!e.containsKey(SystemController.KEY_ERROR_CODE)}_dispatchError(t,s){const i=s.getNumber(SystemController.KEY_ERROR_CODE),r=SFSErrorCodes.getErrorMessage(i,s.getStringArray(SystemController.KEY_ERROR_PARAMS)),n={};n[e.ErrorCode]=i,n[e.ErrorMessage]=r,this._sfs._dispatchEvent(t,n)}}class ExtensionRequest extends BaseRequest{static KEY_CMD=\"c\";static KEY_PARAMS=\"p\";static KEY_ROOM=\"r\";constructor(e,t=null,s=null){super(Ls.Extension.CallExtension),this._targetController=Fs.EXTENSION,this._extCmd=e,this._params=t,this._room=s,null==this._params&&(this._params=new SFSObject),Object.seal(this)}validate(e){const t=[];if(null!=this._extCmd&&0!==this._extCmd.length||t.push(\"Missing Extension command\"),null==this._params||this._params instanceof SFSObject||t.push(\"Custom parameters must be set in a SFSObject class instance\"),null==this._room||this._room instanceof SFSRoom||t.push(\"Room must be an instance of SFSRoom class\"),t.length>0)throw new SFSValidationError(\"Extension request error\",t)}execute(e){this._reqObj.putString(ExtensionRequest.KEY_CMD,this._extCmd),null!=this._room&&this._reqObj.putInt(ExtensionRequest.KEY_ROOM,this._room.id),this._reqObj.putSFSObject(ExtensionRequest.KEY_PARAMS,this._params??new SFSObject)}}class ExtensionAsyncRequest extends ExtensionRequest{static KEY_ASYNC=\"a\";constructor(e,t=null,s=null){super(e,t,s),Object.seal(this)}execute(e){super.execute(e),this._reqObj.putNull(ExtensionAsyncRequest.KEY_ASYNC)}}class ExtensionController{static CONTROLLER_ID=Fs.EXTENSION;constructor(e){this._sfs=e,this._logger=Logger.getInstance(ExtensionController.name),Object.freeze(this)}get id(){return ExtensionController.CONTROLLER_ID}handleMessage(s,i){this._logger.isDebugEnabled&&this._logger.debug(\"ExtensionController handler\");const r={};r[e.Cmd]=s.getString(ExtensionRequest.KEY_CMD),r[e.ExtParams]=s.getSFSObject(ExtensionRequest.KEY_PARAMS);const n=s.getNumber(ExtensionRequest.KEY_ROOM);null!=n&&(r[e.Room]=this._sfs.roomManager.getRoomById(n)),this._sfs._dispatchEvent(t.EXTENSION_RESPONSE,r)}}class InitAudioRequest extends BaseRequest{static KEY_AUDIO_SETTINGS=\"as\";constructor(){super(Ls.Audio.InitAudio),this._targetController=AudioController.CONTROLLER_ID,Object.seal(this)}validate(e){const t=[];if(e._isAudioStreamingEnabled||t.push(\"Audio streaming not enabled on the server side\"),e.audioManager&&t.push(\"Audio Streaming System already initialized\"),t.length>0)throw new SFSValidationError(\"InitAudio request error\",t)}execute(e){}}class StartAudioStreamRequest extends BaseRequest{static KEY_ROOM_ID=\"r\";static KEY_SAMPLE_RATE=\"sr\";static KEY_CHANNELS=\"ch\";static KEY_MUTED=\"m\";static KEY_AUDIO_INFO_LIST=\"ail\";static KEY_AUDIO_INFO=\"ai\";constructor(e=null,t=!1){super(Ls.Audio.StartAudioStream),this._targetController=AudioController.CONTROLLER_ID,this._room=e,this._isMuted=t,Object.seal(this)}validate(e){const t=[];if(e._isAudioStreamingEnabled?(null==e.audioManager&&t.push(\"Audio Streaming System is not initialized; please send an InitAudioRequest first\"),null!=e.audioManager&&e.audioManager.isStreaming()&&t.push(\"Audio streaming already in progress; stop previous stream before starting a new one\"),null==e.audioManager||e.audioManager.hasUserPermission||t.push(\"User permission to access the audio capture device not granted; call AudioManager.requestUserPermission before starting an audio stream\"),null==this._room||this._room instanceof SFSRoom?(null==this._room&&(null!=e.lastJoinedRoom?this._room=e.lastJoinedRoom:t.push(\"A valid Room must be provided\")),e.getJoinedRooms().indexOf(this._room)<0&&t.push(\"You are not joined in the target Room: \"+this._room)):t.push(\"Target Room must be an instance of SFSRoom class\"),null==this._room||this._room.isAudioStreamingAllowed||t.push(\"Audio streaming not allowed in the target Room: \"+this._room)):t.push(\"Audio streaming not enabled on the server side\"),t.length>0)throw new SFSValidationError(\"StartAudioStream request error\",t)}execute(e){this._reqObj.putInt(StartAudioStreamRequest.KEY_ROOM_ID,this._room.id),this._reqObj.putInt(StartAudioStreamRequest.KEY_SAMPLE_RATE,e.config.audio.sampleRate),this._reqObj.putInt(StartAudioStreamRequest.KEY_CHANNELS,e.audioManager.getCaptureChannels()),this._reqObj.putBool(StartAudioStreamRequest.KEY_MUTED,this._isMuted)}}class StopAudioStreamRequest extends BaseRequest{static KEY_STREAMER_ID=\"si\";constructor(){super(Ls.Audio.StopAudioStream),this._targetController=AudioController.CONTROLLER_ID,Object.seal(this)}validate(e){const t=[];if(e._isAudioStreamingEnabled?(null==e.audioManager&&t.push(\"Audio Streaming System is not initialized; please send an InitAudioRequest first\"),null==e.audioManager||e.audioManager.isStreaming()||t.push(\"No audio streaming currently in progress\")):t.push(\"Audio streaming not enabled on the server side\"),t.length>0)throw new SFSValidationError(\"StopAudioStream request error\",t)}execute(e){e.audioManager.stopStreamingSession()}}class ToggleMuteAudioStreamRequest extends BaseRequest{static KEY_STREAMER_ID=\"si\";static KEY_MUTED=\"m\";constructor(){super(Ls.Audio.ToggleAudioStreamMute),this._targetController=AudioController.CONTROLLER_ID,Object.seal(this)}validate(e){const t=[];if(e._isAudioStreamingEnabled?(null==e.audioManager&&t.push(\"Audio Streaming System is not initialized; please send an InitAudioRequest first\"),null==e.audioManager||e.audioManager.isStreaming()||t.push(\"No audio streaming currently in progress\")):t.push(\"Audio streaming not enabled on the server side\"),t.length>0)throw new SFSValidationError(\"ToggleMuteAudioStream request error\",t)}execute(e){e.audioManager.toggleCaptureMuted()}}class AudioController{static CONTROLLER_ID=Fs.AUDIO;constructor(e){this._sfs=e,this._logger=Logger.getInstance(AudioController.name),this._responseHandlers=new Map,this._initRequestHandlers(),Object.freeze(this)}get id(){return AudioController.CONTROLLER_ID}handleMessage(e,t){const s=this._responseHandlers.get(t);null!=s?(this._logger.isDebugEnabled&&this._logger.debug(`Audio Request: ${s.name} (${t})`),s.handler.call(this,e)):this._logger.warn(`Unknown request id: ${t}`)}_initRequestHandlers(){this._setHandler(Ls.Audio.InitAudio,this._resInitAudio),this._setHandler(Ls.Audio.StartAudioStream,this._resStartAudioStream),this._setHandler(1e3,this._resAudioStreamAdd,\"AudioStreamAdd\"),this._setHandler(1001,this._resAudioStreamRemove,\"AudioStreamRemove\"),this._setHandler(1002,this._resAudioStreamData,\"AudioStreamData\"),this._setHandler(1003,this._resAudioStreamMuteToggle,\"AudioStreamMuteToggle\")}_setHandler(e,t,s){this._responseHandlers.set(e,{name:null!=s?s:Ls.getNameFromId(this.id,e),handler:t})}_resInitAudio(e){const t=e.getSFSObject(InitAudioRequest.KEY_AUDIO_SETTINGS);this._sfs._setupAudioManager(t),this._sfs._dispatchEvent(i.INIT)}_resStartAudioStream(e){if(null!=this._sfs.audioManager){const t=e.getNumber(StartAudioStreamRequest.KEY_ROOM_ID),s=this._sfs.roomManager.getRoomById(t);if(null==s||this._sfs.getJoinedRooms().indexOf(s)<0)return void this._logger.warn(\"Room where to start streaming audio not joined anymore; aborting stream start\");this._sfs.audioManager.startStreamingSession(t,e.getBool(StartAudioStreamRequest.KEY_MUTED));const i=e.getSFSArray(StartAudioStreamRequest.KEY_AUDIO_INFO_LIST);for(let e=0;e<i.size();e++){const s=i.getSFSArray(e),r=s.getNumber(1),n=s.getNumber(2),a=s.getNumber(3),o=s.getBool(4);this._sfs.audioManager.startPlaybackStream(t,r,n,a,o)}}}_resAudioStreamAdd(e){if(null!=this._sfs.audioManager){const t=e.getSFSArray(StartAudioStreamRequest.KEY_AUDIO_INFO),s=t.getNumber(0),i=t.getNumber(1),r=t.getNumber(2),n=t.getNumber(3),a=t.getBool(4);this._sfs.audioManager.startPlaybackStream(s,i,r,n,a)}}_resAudioStreamRemove(e){if(null!=this._sfs.audioManager){const t=e.getNumber(StopAudioStreamRequest.KEY_STREAMER_ID);this._sfs.audioManager.stopPlaybackStream(t)}}_resAudioStreamData(e){if(null!=this._sfs.audioManager){const t=new DataView(e.buffer,e.byteOffset,e.byteLength).getInt32(0,!1),s=e.subarray(4);this._sfs.audioManager.writePlaybackStreamData(t,s)}}_resAudioStreamMuteToggle(e){if(null!=this._sfs.audioManager){const t=e.getNumber(ToggleMuteAudioStreamRequest.KEY_STREAMER_ID),s=e.getBool(ToggleMuteAudioStreamRequest.KEY_MUTED);this._sfs.audioManager.setPlaybackMuted(t,s)}}}class ReconnectionState{constructor(e,t,s){this._isPending=e,this._firstAttemptTime=t,this._counter=s,Object.seal(this)}get isPending(){return this._isPending}get firstAttemptTime(){return this._firstAttemptTime}get counter(){return this._counter}incCounter(){this._counter++}toString(){return`[ Pending: ${this._isPending}, Counter: ${this._counter} ]`}}const $s=Object.freeze({CONNECT:\"connect\",DISCONNECT:\"disconnect\",CONNECTION_RETRY:\"connectionRetry\",CONNECTION_RESUME:\"connectionResume\"});class SocketEngine{constructor(e){this.HTTP_CONN_TIMEOUT=5,this._sfs=e,this._logger=Logger.getInstance(this.name),this._dispatcher=new EventDispatcher,this._cfg=null,this._isConnected=!1,this._socket=null,this._protocolCodec=new SFSProtocolCodec(e),this._disconnectionReason=Ms.UNKNOWN,this._reconnectionDelayMillis=1e3,this._reconnectionSeconds=0,this._reconState=null,this._connTimeout=null,this._initControllers(),Object.seal(this)}get isConnected(){return this._isConnected}get maxMessageSize(){return this._protocolCodec.maxMessageSize}set maxMessageSize(e){this._protocolCodec.maxMessageSize=e}get compressionThreshold(){return this._protocolCodec.compressionThreshold}set compressionThreshold(e){this._protocolCodec.compressionThreshold=e}get reconnectionDelayMillis(){return this._reconnectionDelayMillis}set reconnectionDelayMillis(e){this._reconnectionDelayMillis=e}get reconnectionSeconds(){return this._reconnectionSeconds}set reconnectionSeconds(e){this._reconnectionSeconds=e}addEventListener(e,t,s){this._dispatcher.addEventListener(e,t,s)}removeEventListener(e,t){this._dispatcher.removeEventListener(e,t)}connect(e){if(null!=this._socket)throw this._isConnected?new Error(\"An active connection already exists\"):new Error(\"The connection cannot be reused. Please create a new instance\");this._cfg=e;let t=\"ws\"+(e.useSSL?\"s\":\"\");this._socket=new WebSocket(t+\"://\"+e.host+\":\"+e.port+\"/WebServices/websocket\"),this._socket.binaryType=\"arraybuffer\",this._socket.addEventListener(\"open\",this._onSocketConnect.bind(this)),this._socket.addEventListener(\"close\",this._onSocketDisconnect.bind(this)),this._socket.addEventListener(\"message\",this._onSocketData.bind(this)),this._socket.addEventListener(\"error\",this._onSocketError.bind(this)),this._connTimeout=setTimeout(()=>{this._socket.readyState===WebSocket.CONNECTING&&(this._logger.isDebugEnabled&&this._logger.debug(\"Socket connection forced timeout\"),this._socket.close())},1e3*this.HTTP_CONN_TIMEOUT)}disconnect(e){if(!this._isConnected)throw new Error(\"Client is already disconnected\");this._disconnectionReason=e,this._socket.close()}send(e){if(null==this._socket||this._socket.readyState!==WebSocket.OPEN)return;this._sfs.config.netDebugLevel==Ns.PROTOCOL&&this._logger.info(\"Outgoing - \"+e.dump());const t=this._protocolCodec.onPacketWrite(e);this._socket.send(t)}killConnection(){this._isConnected&&this._socket.close()}attemptReconnection(){if(this._reconnectionSeconds<0)throw new Error(\"Reconnection is not possible: parameter 'reconnectionSeconds' is zero\");this._socket=null,null==this._reconState&&(this._dispatcher.dispatchEvent($s.CONNECTION_RETRY,{}),this._reconState=new ReconnectionState(!0,Date.now(),1));const e=1e3*this._reconnectionSeconds,t=this._reconState.firstAttemptTime+e-Date.now();t>0?(this._logger.info(`Reconnection attempt: ${this._reconState.counter} - Time left: ${t/1e3} sec`),setTimeout(()=>{this._reconState.incCounter(),this.connect(this._cfg)},this._reconnectionDelayMillis)):(this._reconState,this._dispatcher.dispatchEvent($s.DISCONNECT,{reason:Ms.UNKNOWN,errorMessage:\"All reconnection attempts failed\"}))}completeReconnection(e){this._reconState=null,e?this._dispatcher.dispatchEvent($s.CONNECTION_RESUME,{}):(this._disconnectionReason=Ms.RECONNECTION_FAILURE,this._onSocketDisconnect())}_initControllers(){this._controllers={};let e=new SystemController(this._sfs),t=new ExtensionController(this._sfs),s=new AudioController(this._sfs);this._addController(e.id,e),this._addController(t.id,t),this._addController(s.id,s)}_addController(e,t){if(null==t)throw new Error(\"Controller is null\");if(null!=this._controllers[e])throw new Error(`A controller with id: ${e} already exists`);this._controllers[e]=t}_onSocketConnect(){this._logger.isDebugEnabled&&this._logger.debug(\"Socket connection established\"),clearTimeout(this._connTimeout),this._isConnected=!0;var e=null!=this._reconState&&this._reconState.isPending;this._dispatcher.dispatchEvent($s.CONNECT,{success:!0,isReconnection:e})}_onSocketDisconnect(){this._isConnected&&(this._isConnected=!1,this._disconnectionReason==Ms.UNKNOWN&&this._reconnectionSeconds>0?this.attemptReconnection():(this._logger.isDebugEnabled&&this._logger.debug(\"Socket disconnection occurred\"),this._dispatcher.dispatchEvent($s.DISCONNECT,{reason:this._disconnectionReason}),this._disconnectionReason=Ms.UNKNOWN))}_onSocketData(e){const t=this._protocolCodec.onPacketRead(e.data);this._sfs.config.netDebugLevel==Ns.PROTOCOL&&this._logger.info(\"Incoming - \"+t.dump());const s=t.targetController,i=t.id,r=t.content;null!=s?null!=i?this._controllers[s].handleMessage(r,i):this._logger.error(\"Incoming message rejected: Command ID is missing\"):this._logger.error(\"Incoming message rejected: Controller ID is missing\")}_onSocketError(e){clearTimeout(this._connTimeout),null!=this._reconState&&this._reconState.isPending?this.attemptReconnection():this._dispatcher.dispatchEvent($s.CONNECT,{success:!1})}}class SFSProtocolCodec{constructor(e){this.MAX_PACKET_DEBUG_LEN=1024,this._maxMessageSize=1e4,this._compressionThreshold=1024,this._sfs=e,this._logger=Logger.getInstance(this.name),Object.seal(this)}get maxMessageSize(){return this._maxMessageSize}set maxMessageSize(e){this._maxMessageSize=e}get compressionThreshold(){return this._compressionThreshold}set compressionThreshold(e){this._compressionThreshold=e}onPacketRead(e){if(0===e.byteLength)return void this._logger.error(\"Unexpected empty packet data: no readable bytes available!\");let t=new n(e,0,n.BIG_ENDIAN);const s=t.readUint8(),i=(128&s)>0,r=(16&s)>0,a=(32&s)>0?t.readUint32():t.readUint16();let o=t.readUint8Array(a);i&&(o=this.decompress(o));const h=this._sfs.config.netDebugLevel;h!=Ns.PACKET&&h!=Ns.PROTOCOL||(e.byteLength>this.MAX_PACKET_DEBUG_LEN?this._logger.info(`Incoming, Size: ${e.byteLength}, Dump omitted`):this._logger.info(\"Incoming, \"+DumpFormatter.hexDump(o))),t=new n(o,0,n.BIG_ENDIAN);let l=t.readUint8(),u=t.readInt16(),_=t.readUint8Array(o.length-3);const c=r?_:SFSObject.newFromBinaryData(_);return new Message(u,l,c,r)}onPacketWrite(e){let t=new n(new ArrayBuffer(0),0,n.BIG_ENDIAN),s=e.isRaw?e.content:e.content.toBinary();t.writeUint8(e.targetController),t.writeInt16(e.id),t.writeUint8Array(s);let i=s.length+3;const r=i>this.compressionThreshold,a=s.length;s=new Uint8Array(t.buffer);let o=0;r&&(o+=128,s=this.compress(s),i=s.byteLength);const h=i>65335;h&&(o+=32),e.isRaw&&(o+=16);const l=new n(new ArrayBuffer(0),0,n.BIG_ENDIAN);l.writeUint8(o),h?l.writeUint32(i):l.writeUint16(i),l.writeUint8Array(s);const u=new Uint8Array(l.buffer);if(u.byteLength>this.maxMessageSize)throw new Exceptions_SFSError(\"Message size is too big: \"+u.byteLength+\"; the server limit is: \"+this.maxMessageSize);const _=this._sfs.config.netDebugLevel;return _!=Ns.PROTOCOL&&_!=Ns.PROTOCOL||(r&&this._logger.isDebugEnabled&&this._logger.debug(`(cmp: ${a}b / ${s.length}b)`),s.length<this.MAX_PACKET_DEBUG_LEN?this._logger.info(\"Outgoing, \"+DumpFormatter.hexDump(u)):this._logger.info(`Outgoing, Size: ${u.length}, Dump omitted`)),u}decompress(e){return bs.inflate(e)}compress(e){return bs.deflate(e)}}class SFSRoomManager{constructor(e){this._sfs=e,this._groups=new Set,this._roomsById=new Map,this._roomsByName=new Map,Object.seal(this)}containsGroup(e){return this._groups.has(e)}containsRoom(e){return\"number\"==typeof e?this._roomsById.has(e):this._roomsByName.has(e)}containsRoomInGroup(e,t){const s=this.getRoomListFromGroup(t);return\"number\"==typeof e?s.some(t=>t.id===e):s.some(t=>t.name===e)}getRoomById(e){return this._roomsById.get(e)}getRoomByName(e){return this._roomsByName.get(e)}getRoomGroups(){return Array.from(this._groups)}getRoomList(){return Array.from(this._roomsById.values())}getRoomListFromGroup(e){return this.getRoomList().filter(t=>t.groupId===e)}getJoinedRooms(){return this.getRoomList().filter(e=>e.isJoined)}getUserRooms(e){return this.getRoomList().filter(t=>t.containsUser(e))}get roomCount(){return this._roomsById.size}_addRoom(e,t=!0){this._roomsById.set(e.id,e),this._roomsByName.set(e.name,e),t?this._addGroup(e.groupId):e._isManaged=!1}_removeRoom(e){this._roomsById.delete(e.id),this._roomsByName.delete(e.name)}_removeRoomById(e){const t=this.getRoomById(e);null!=t&&this._removeRoom(t)}_removeRoomByName(e){const t=this.getRoomByName(e);null!=t&&this._removeRoom(t)}_addGroup(e){this.containsGroup(e)||this._groups.add(e)}_removeGroup(e){this._groups.delete(e);const t=this.getRoomListFromGroup(e);for(let e of t)e.isJoined?e._isManaged=!1:this._removeRoom(e)}_updateRoomList(e){for(let t=0;t<e.size();t++){let s=e.getSFSArray(t),i=SFSRoom.fromSFSArray(s);this._addRoom(i,!0)}}_changeRoomName(e,t){const s=e.name;e._name=t,this._roomsByName.set(t,e),this._roomsByName.delete(s)}_changeRoomPasswordState(e,t){e._isPasswordProtected=t}_changeRoomCapacity(e,t,s){e._maxUsers=t,e._maxSpectators=s}_removeUser(e){for(let t of this.getUserRooms(e))t instanceof MMORoom||t._removeUser(e)}}class SFSBuddyManager{constructor(e){this._sfs=e,this._buddiesByName=new Map,this._myVariables=new Map,this._inited=!1,this._buddyStates=new Set,Object.seal(this)}get isInited(){return this._inited}get buddyList(){return Array.from(this._buddiesByName.values())}get offlineBuddies(){return this.buddyList.filter(e=>!e.isOnline)}get onlineBuddies(){return this.buddyList.filter(e=>e.isOnline)}get buddyStates(){return Array.from(this._buddyStates.values())}get myOnlineState(){if(!this._inited)return!1;const e=this.getMyVariable(ks.BV_ONLINE);return null==e||e.value}get myNickname(){const e=this.getMyVariable(ks.BV_NICKNAME);return null!=e?e.value:null}get myDisplayName(){return null!=this.myNickname&&\"\"!=this.myNickname?this.myNickname:this._sfs.mySelf.name}get myState(){const e=this.getMyVariable(ks.BV_STATE);return null!=e?e.value:null}containsBuddy(e){return this._buddiesByName.has(e)}getBuddyById(e){return this.buddyList.find(t=>t.id===e)}getBuddyByName(e){return this._buddiesByName.get(e)}getBuddyByNickname(e){return this.buddyList.find(t=>t.nickname===e)}getMyVariable(e){return this._myVariables.get(e)}getMyVariables(){return Array.from(this._myVariables.values())}_setInited(){this._inited=!0}_setBuddyStates(e){this._buddyStates=new Set(e)}_setMyOnlineState(e){this._setMyVariable(new SFSBuddyVariable(ks.BV_ONLINE,e,Bs.BOOLEAN))}_setMyNickname(e){this._setMyVariable(new SFSBuddyVariable(ks.BV_NICKNAME,e,Bs.STRING))}_setMyState(e){this._setMyVariable(new SFSBuddyVariable(ks.BV_STATE,e,Bs.STRING))}_addBuddy(e){this._buddiesByName.set(e.name,e)}_removeBuddyById(e){const t=this.getBuddyById(e);return null!=t&&this._buddiesByName.delete(t.name),t}_removeBuddyByName(e){const t=this.getBuddyByName(e);return null!=t&&this._buddiesByName.delete(e),t}_setMyVariables(e){for(let t of e)this._setMyVariable(t)}_setMyVariable(e){e.isNull?this._myVariables.delete(e.name):this._myVariables.set(e.name,e)}_clearAll(){this._buddiesByName.clear()}}class AudioDevice{#s;#i;#r;#n;constructor(e,t,s,i){this.#s=e,this.#i=t,this.#r=s,this.#n=i}get id(){return this.#s}get name(){return this.#i}get isSelected(){return this.#n}get isDefault(){return this.#r}toString(){return`${this.#i} ${this.#r?\"(default)\":\"\"} ${this.#n?\"(selected)\":\"\"}`}}class AudioStreamInfo{#a;#o;#h;#l;#u;#_=Number.NEGATIVE_INFINITY;#c=Number.NEGATIVE_INFINITY;#d=0;cycles=0;totalMs=0;lastMs=Date.now();totalBytes=0;constructor(e,t,s,i,r){this.#a=e,this.#o=t,this.#h=s,this.#l=i,this.#u=r}get id(){return this.#o.id}get room(){return this.#a}get user(){return this.#o}get sampleRate(){return this.#h}get channels(){return this.#l}get leftLevel(){return this.#_}get rightLevel(){return this.#c}get isMono(){return 1==this.#l}get delay(){return this.#d}get isMuted(){return this.#u}setMuted(e){this.#u=1==e}setLevels(e,t){this.#_=e,this.#c=t}setDelay(e){this.#d=e}get internalInfoString(){const e=this.cycles>0?this.totalMs/this.cycles:0,t=this.cycles>0?this.totalBytes/this.cycles:0;return`[cyles: ${this.cycles}, duration (ms): ${this.totalMs}, bytes (encoded): ${this.totalBytes}, avg ms per cycle: ${e}, avg bytes per cycle: ${t}]`}}class AudioCapturer{constructor(e,t,s){this._logger=Logger.getInstance(AudioCapturer.name),this._manager=e,this._settings=e._settings,this._config=e._config,this._sampleRate=this._config.sampleRate,this._channels=this._settings.numChannels,this._streamInfo=new AudioStreamInfo(t,e._sfs.mySelf,this._config.sampleRate,this._settings.numChannels,s),this._periodSizeInFrames=this._config.sampleRate*this._settings.chunkSizeMillis/1e3,this._stream=null,this._audioContext=null,this._sourceNode=null,this._workletNode=null,this._workletUrl=null,this._encoder=null,this._pendingChunks=[],this._timestampUs=0,this._stopped=!1,Object.seal(this)}get streamInfo(){return this._streamInfo}start(){this._init().catch(e=>{this._logger.error(`Unable to start audio capture: ${e}`),this._stopped||this._manager._onCaptureStartFailed(this,e)})}async _init(){if(this._stream=await navigator.mediaDevices.getUserMedia(this._buildConstraints()),this._stopped)for(const e of this._stream.getTracks())e.stop();else this._audioContext=new AudioContext({sampleRate:this._sampleRate}),\"suspended\"===this._audioContext.state&&await this._audioContext.resume(),this._workletUrl=URL.createObjectURL(new Blob([\"\\nclass SfsCaptureProcessor extends AudioWorkletProcessor\\n{\\n\\tconstructor(options)\\n\\t{\\n\\t\\tsuper();\\n\\n\\t\\tthis._periodSize = options.processorOptions.periodSizeInFrames;\\n\\t\\tthis._channels = options.processorOptions.channels;\\n\\t\\tthis._filled = 0;\\n\\n\\t\\t// One accumulator per channel (planar)\\n\\t\\tthis._buffers = [];\\n\\t\\tfor (let c = 0; c < this._channels; c++)\\n\\t\\t\\tthis._buffers.push(new Float32Array(this._periodSize));\\n\\t}\\n\\n\\tprocess(inputs)\\n\\t{\\n\\t\\tconst input = inputs[0];\\n\\n\\t\\t// No input connected yet\\n\\t\\tif (!input || input.length === 0)\\n\\t\\t\\treturn true;\\n\\n\\t\\tconst frames = input[0].length;\\n\\t\\tlet offset = 0;\\n\\n\\t\\twhile (offset < frames)\\n\\t\\t{\\n\\t\\t\\tconst toCopy = Math.min(frames - offset, this._periodSize - this._filled);\\n\\n\\t\\t\\tfor (let c = 0; c < this._channels; c++)\\n\\t\\t\\t{\\n\\t\\t\\t\\t// Fall back to channel 0 if the source has fewer channels than expected\\n\\t\\t\\t\\tconst src = input[c] || input[0];\\n\\t\\t\\t\\tthis._buffers[c].set(src.subarray(offset, offset + toCopy), this._filled);\\n\\t\\t\\t}\\n\\n\\t\\t\\tthis._filled += toCopy;\\n\\t\\t\\toffset += toCopy;\\n\\n\\t\\t\\t// A full period is ready: post a planar copy to the main thread\\n\\t\\t\\tif (this._filled === this._periodSize)\\n\\t\\t\\t{\\n\\t\\t\\t\\tconst out = new Float32Array(this._periodSize * this._channels);\\n\\n\\t\\t\\t\\tfor (let c = 0; c < this._channels; c++)\\n\\t\\t\\t\\t\\tout.set(this._buffers[c], c * this._periodSize);\\n\\n\\t\\t\\t\\tthis.port.postMessage(out, [out.buffer]);\\n\\t\\t\\t\\tthis._filled = 0;\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\treturn true;\\n\\t}\\n}\\n\\nregisterProcessor('sfs-capture-processor', SfsCaptureProcessor);\\n\"],{type:\"application/javascript\"})),await this._audioContext.audioWorklet.addModule(this._workletUrl),this._stopped?this._teardownGraph():(this._encoder=new AudioEncoder({output:(e,t)=>this._onEncodedChunk(e,t),error:e=>this._logger.error(`Audio encoder error: ${e}`)}),this._encoder.configure({codec:\"opus\",sampleRate:this._sampleRate,numberOfChannels:this._channels,bitrate:this._settings.bitrate,opus:{application:AudioCapturer._mapOpusApplication(this._settings.opusApplicationType),signal:AudioCapturer._mapOpusSignal(this._settings.opusSignalType),complexity:this._settings.opusEncoderComplexity,frameDuration:1e3*this._settings.chunkSizeMillis}}),this._sourceNode=this._audioContext.createMediaStreamSource(this._stream),this._workletNode=new AudioWorkletNode(this._audioContext,\"sfs-capture-processor\",{processorOptions:{periodSizeInFrames:this._periodSizeInFrames,channels:this._channels}}),this._workletNode.port.onmessage=e=>this._onCapturedPeriod(e.data),this._sourceNode.connect(this._workletNode),this._workletNode.connect(this._audioContext.destination))}_buildConstraints(){const e={audio:{echoCancellation:this._config.enableAEC,noiseSuppression:this._config.enableNS,autoGainControl:this._config.enableAGC}},t=this._manager.captureDevice;return null!=t&&(e.audio.deviceId={exact:t.id}),e}async setCaptureDevice(){if(!this._stopped&&null!=this._audioContext)try{const e=await navigator.mediaDevices.getUserMedia(this._buildConstraints());if(this._stopped){for(const t of e.getTracks())t.stop();return}if(null!=this._sourceNode&&this._sourceNode.disconnect(),null!=this._stream)for(const e of this._stream.getTracks())e.stop();this._stream=e,this._sourceNode=this._audioContext.createMediaStreamSource(this._stream),this._sourceNode.connect(this._workletNode)}catch(e){this._logger.error(`Unable to switch capture device: ${e}`);const t=null!=this._stream&&this._stream.getTracks().some(e=>\"live\"===e.readyState);this._stopped||t||this._manager._onCaptureStartFailed(this,e)}}_onCapturedPeriod(e){if(this._stopped||null==this._encoder)return;const t=this._timestampUs;this._timestampUs+=Math.round(this._periodSizeInFrames/this._sampleRate*1e6),this._streamInfo.cycles++;const s=Date.now();if(this._streamInfo.totalMs+=s-this._streamInfo.lastMs,this._streamInfo.lastMs=s,this._streamInfo.isMuted)return this._pendingChunks.length=0,void this._streamInfo.setLevels(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);this._config.monitorOutLevel&&this._measureLevels(e);const i=new AudioData({format:\"f32-planar\",sampleRate:this._sampleRate,numberOfFrames:this._periodSizeInFrames,numberOfChannels:this._channels,timestamp:t,data:e});this._encoder.encode(i),i.close()}_measureLevels(e){const t=this._config.monitoringMode===Ks.PEAK;if(1===this._channels){const s=Gs(e,t);this._streamInfo.setLevels(s,s)}else{const s=Gs(e.subarray(0,this._periodSizeInFrames),t),i=Gs(e.subarray(this._periodSizeInFrames,2*this._periodSizeInFrames),t);this._streamInfo.setLevels(s,i)}}_onEncodedChunk(e,t){if(this._stopped||this._streamInfo.isMuted)return;const s=new Uint8Array(e.byteLength);e.copyTo(s),this._pendingChunks.push(s),this._pendingChunks.length>=this._settings.chunksPerTransmission&&this._transmit()}_transmit(){const e=this._settings.chunksPerTransmission,t=this._pendingChunks.splice(0,e);let s=0;for(const e of t)s+=2+e.length;const i=new Uint8Array(s),r=new DataView(i.buffer);let n=0;for(const e of t)r.setInt16(n,e.length,!1),n+=2,i.set(e,n),n+=e.length;const a=new Message(Ls.Audio.AudioStreamData,Fs.AUDIO,i,!0);this._manager._sfs._socketEngine.send(a),this._streamInfo.totalBytes+=s}stop(){if(this._stopped)return;this._stopped=!0,this._teardownGraph();const t={};t[e.MyAudioStream]=this._streamInfo,this._manager._sfs._dispatchEvent(i.STREAM_STOP,t)}_teardownGraph(){if(null!=this._workletNode&&(this._workletNode.port.onmessage=null,this._workletNode.disconnect(),this._workletNode=null),null!=this._sourceNode&&(this._sourceNode.disconnect(),this._sourceNode=null),null!=this._encoder){if(\"closed\"!==this._encoder.state)try{this._encoder.close()}catch(e){this._logger.debug(`Error closing audio encoder: ${e}`)}this._encoder=null}if(null!=this._stream){for(const e of this._stream.getTracks())e.stop();this._stream=null}null!=this._audioContext&&(\"closed\"!==this._audioContext.state&&this._audioContext.close().catch(()=>{}),this._audioContext=null),null!=this._workletUrl&&(URL.revokeObjectURL(this._workletUrl),this._workletUrl=null),this._pendingChunks.length=0}static _mapOpusApplication(e){const t=(null!=e?String(e):\"\").toLowerCase();return t.includes(\"lowdelay\")||t.includes(\"low_delay\")||t.includes(\"restricted\")?\"lowdelay\":t.includes(\"audio\")||t.includes(\"music\")?\"audio\":\"voip\"}static _mapOpusSignal(e){const t=(null!=e?String(e):\"\").toLowerCase();return t.includes(\"music\")?\"music\":t.includes(\"voice\")?\"voice\":\"auto\"}}const Xs=\"sfs-playback-processor\",Zs=`\\nclass SfsPlaybackProcessor extends AudioWorkletProcessor\\n{\\n\\tconstructor(options)\\n\\t{\\n\\t\\tsuper();\\n\\n\\t\\tconst opt = options.processorOptions;\\n\\n\\t\\tthis._channels = opt.channels;\\n\\n\\t\\t// Jitter buffer: one contiguous Float32Array per channel, a shared valid length and a\\n\\t\\t// fractional read cursor. A flat buffer (rather than a list of chunks) lets us read at a\\n\\t\\t// variable rate with linear interpolation for the pitch-shift catch-up below.\\n\\t\\tthis._capacity = Math.max(1, Math.round(sampleRate)); // ~1 s; grows on demand\\n\\t\\tthis._buffers = [];\\n\\t\\tfor (let c = 0; c < this._channels; c++)\\n\\t\\t\\tthis._buffers.push(new Float32Array(this._capacity));\\n\\t\\tthis._len = 0;      // valid frames currently buffered (per channel)\\n\\t\\tthis._readPos = 0;  // fractional read cursor in [0, _len)\\n\\n\\t\\t// Pitch-shift latency management: when the buffered delay exceeds the upper threshold, play\\n\\t\\t// faster (rate > 1) to drain quicker; return to 1x once it drops below the lower threshold.\\n\\t\\t// This is the in-worklet equivalent of the native ma_sound_set_pitch() the C# player uses.\\n\\t\\tthis._upperMs = opt.delayUpperThreshold;\\n\\t\\tthis._lowerMs = opt.delayLowerThreshold;\\n\\t\\tthis._pitchRate = 1 + (opt.pitchShiftingValue || 0) / 100; // C#: playbackSpeed = 1 + speed/100\\n\\t\\tthis._pitchEnabled = this._pitchRate > 1 && this._upperMs > 0 && this._lowerMs >= 0 && this._lowerMs < this._upperMs;\\n\\t\\tthis._rate = 1; // current playback rate\\n\\n\\t\\t// Status reporting (delay always, levels only when monitoring) once per window\\n\\t\\tthis._monitor = opt.monitorInLevel === true;\\n\\t\\tthis._usePeak = opt.usePeak === true;\\n\\t\\tthis._window = Math.max(1, Math.round(sampleRate * 0.05)); // ~50 ms; 'sampleRate' is a worklet global\\n\\t\\tthis._accFrames = 0;\\n\\t\\tthis._sum = new Array(this._channels).fill(0);\\n\\t\\tthis._peak = new Array(this._channels).fill(0);\\n\\n\\t\\tthis.port.onmessage = (e) => {\\n\\t\\t\\tconst msg = e.data;\\n\\n\\t\\t\\tif (msg.type === 'data')\\n\\t\\t\\t\\tthis._enqueue(msg.channelData);\\n\\t\\t\\telse if (msg.type === 'clear')\\n\\t\\t\\t{\\n\\t\\t\\t\\tthis._len = 0;\\n\\t\\t\\t\\tthis._readPos = 0;\\n\\t\\t\\t\\tthis._rate = 1;\\n\\t\\t\\t}\\n\\t\\t};\\n\\t}\\n\\n\\t// Append decoded PCM frames to the buffer\\n\\t_enqueue(channelData)\\n\\t{\\n\\t\\tconst n = channelData[0].length;\\n\\n\\t\\tthis._ensureCapacity(this._len + n);\\n\\n\\t\\tfor (let c = 0; c < this._channels; c++)\\n\\t\\t{\\n\\t\\t\\tconst src = channelData[c] || channelData[0];\\n\\t\\t\\tthis._buffers[c].set(src, this._len);\\n\\t\\t}\\n\\n\\t\\tthis._len += n;\\n\\t}\\n\\n\\t_ensureCapacity(needed)\\n\\t{\\n\\t\\tif (needed <= this._capacity)\\n\\t\\t\\treturn;\\n\\n\\t\\tlet cap = this._capacity;\\n\\t\\twhile (cap < needed)\\n\\t\\t\\tcap *= 2;\\n\\n\\t\\tfor (let c = 0; c < this._channels; c++)\\n\\t\\t{\\n\\t\\t\\tconst grown = new Float32Array(cap);\\n\\t\\t\\tgrown.set(this._buffers[c].subarray(0, this._len));\\n\\t\\t\\tthis._buffers[c] = grown;\\n\\t\\t}\\n\\n\\t\\tthis._capacity = cap;\\n\\t}\\n\\n\\tprocess(inputs, outputs)\\n\\t{\\n\\t\\tconst output = outputs[0];\\n\\n\\t\\tif (!output || output.length === 0)\\n\\t\\t\\treturn true;\\n\\n\\t\\tconst frames = output[0].length;\\n\\n\\t\\t// Decide the playback rate from the current buffered delay (hysteresis)\\n\\t\\tconst delayMs = (this._len - this._readPos) / sampleRate * 1000;\\n\\t\\tthis._updateRate(delayMs);\\n\\n\\t\\tconst rate = this._rate;\\n\\t\\tlet written = 0;\\n\\n\\t\\t// Drain the buffer into the output, interpolating between samples at the current rate.\\n\\t\\t// At rate 1.0 with an integer cursor frac is 0, so this is an exact 1:1 sample copy.\\n\\t\\twhile (written < frames)\\n\\t\\t{\\n\\t\\t\\tconst i = Math.floor(this._readPos);\\n\\n\\t\\t\\tif (i >= this._len)\\n\\t\\t\\t\\tbreak; // under-run\\n\\n\\t\\t\\tconst frac = this._readPos - i;\\n\\t\\t\\tconst i1 = (i + 1 < this._len) ? i + 1 : i;\\n\\n\\t\\t\\tfor (let c = 0; c < output.length; c++)\\n\\t\\t\\t{\\n\\t\\t\\t\\tconst buf = this._buffers[c] || this._buffers[0];\\n\\t\\t\\t\\toutput[c][written] = buf[i] * (1 - frac) + buf[i1] * frac;\\n\\t\\t\\t}\\n\\n\\t\\t\\tthis._readPos += rate;\\n\\t\\t\\twritten++;\\n\\t\\t}\\n\\n\\t\\t// Under-run: fill the remainder with silence\\n\\t\\tfor (let c = 0; c < output.length; c++)\\n\\t\\t\\tfor (let j = written; j < frames; j++)\\n\\t\\t\\t\\toutput[c][j] = 0;\\n\\n\\t\\t// Drop the consumed frames to keep the buffer compact\\n\\t\\tconst consumed = Math.min(Math.floor(this._readPos), this._len);\\n\\t\\tif (consumed > 0)\\n\\t\\t{\\n\\t\\t\\tfor (let c = 0; c < this._channels; c++)\\n\\t\\t\\t\\tthis._buffers[c].copyWithin(0, consumed, this._len);\\n\\n\\t\\t\\tthis._len -= consumed;\\n\\t\\t\\tthis._readPos -= consumed;\\n\\t\\t}\\n\\n\\t\\t// Accumulate level stats (only when monitoring) on what was actually played\\n\\t\\tif (this._monitor)\\n\\t\\t{\\n\\t\\t\\tfor (let c = 0; c < output.length; c++)\\n\\t\\t\\t{\\n\\t\\t\\t\\tconst ch = output[c];\\n\\n\\t\\t\\t\\tfor (let i = 0; i < frames; i++)\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tconst s = ch[i];\\n\\t\\t\\t\\t\\tthis._sum[c] += s * s;\\n\\n\\t\\t\\t\\t\\tconst abs = s < 0 ? -s : s;\\n\\t\\t\\t\\t\\tif (abs > this._peak[c])\\n\\t\\t\\t\\t\\t\\tthis._peak[c] = abs;\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tthis._accFrames += frames;\\n\\n\\t\\tif (this._accFrames >= this._window)\\n\\t\\t\\tthis._report();\\n\\n\\t\\treturn true;\\n\\t}\\n\\n\\t// Enable/disable pitch-shift catch-up with hysteresis (upper to activate, lower to deactivate)\\n\\t_updateRate(delayMs)\\n\\t{\\n\\t\\tif (!this._pitchEnabled)\\n\\t\\t\\treturn;\\n\\n\\t\\tif (this._rate === 1 && delayMs > this._upperMs)\\n\\t\\t\\tthis._rate = this._pitchRate;\\n\\t\\telse if (this._rate > 1 && delayMs <= this._lowerMs)\\n\\t\\t{\\n\\t\\t\\tthis._rate = 1;\\n\\t\\t\\tthis._readPos = Math.round(this._readPos); // snap so 1x playback isn't permanently resampled\\n\\t\\t}\\n\\t}\\n\\n\\t// Post the current delay (and levels, when monitoring) to the main thread; reset accumulators\\n\\t_report()\\n\\t{\\n\\t\\tconst delay = Math.round((this._len - this._readPos) / sampleRate * 1000);\\n\\n\\t\\tlet left = null;\\n\\t\\tlet right = null;\\n\\n\\t\\tif (this._monitor)\\n\\t\\t{\\n\\t\\t\\tconst levels = [];\\n\\n\\t\\t\\tfor (let c = 0; c < this._channels; c++)\\n\\t\\t\\t{\\n\\t\\t\\t\\tconst value = this._usePeak ? this._peak[c] : Math.sqrt(this._sum[c] / this._accFrames);\\n\\n\\t\\t\\t\\t// Clamp to full scale so the meter never exceeds 0 dBFS; silence -> -Infinity\\n\\t\\t\\t\\tlevels.push(20 * Math.log10(Math.min(value, 1)));\\n\\n\\t\\t\\t\\tthis._sum[c] = 0;\\n\\t\\t\\t\\tthis._peak[c] = 0;\\n\\t\\t\\t}\\n\\n\\t\\t\\t// Mono -> both channels equal; stereo -> per channel\\n\\t\\t\\tleft = levels[0];\\n\\t\\t\\tright = levels.length > 1 ? levels[1] : left;\\n\\t\\t}\\n\\n\\t\\tthis._accFrames = 0;\\n\\n\\t\\tthis.port.postMessage({ type: 'status', delay: delay, left: left, right: right });\\n\\t}\\n}\\n\\nregisterProcessor('${Xs}', SfsPlaybackProcessor);\\n`;class AudioPlayer{constructor(e,t,s,i,r,n){this._logger=Logger.getInstance(AudioPlayer.name),this._manager=e,this._channels=r,this._streamInfo=new AudioStreamInfo(t,s,i,r,n),this._chunksPerTransmission=e._settings.chunksPerTransmission,this._decoder=null,this._decoderConfig=null,this._workletNode=null,this._frameDurationUs=1e3*e._settings.chunkSizeMillis,this._decodeTimestampUs=0,this._pendingData=[],this._started=!1,this._stopped=!1,Object.seal(this)}get streamInfo(){return this._streamInfo}start(){this._init().catch(e=>{this._logger.error(`Unable to start audio playback: ${e}`)})}async _init(){if(this._stopped)return;const e=await this._manager._ensurePlaybackContext();if(this._stopped)return;const t=this._manager._config,s=this._manager._settings.delaySettings||{};this._workletNode=new AudioWorkletNode(e,Xs,{numberOfInputs:0,outputChannelCount:[this._channels],processorOptions:{channels:this._channels,monitorInLevel:!0===t.monitorInLevel,usePeak:t.monitoringMode===Ks.PEAK,delayUpperThreshold:s.delayUpperThreshold,delayLowerThreshold:s.delayLowerThreshold,pitchShiftingValue:s.pitchShiftingValue}}),this._workletNode.connect(e.destination),this._workletNode.port.onmessage=e=>{const t=e.data;\"status\"===t.type&&(this._streamInfo.setDelay(t.delay),null!=t.left&&this._streamInfo.setLevels(t.left,t.right))},this._decoderConfig={codec:\"opus\",sampleRate:48e3,numberOfChannels:this._channels},this._decoder=new AudioDecoder({output:e=>this._onDecoded(e),error:e=>this._logger.warn(`Audio decoder error: ${e}`)}),this._decoder.configure(this._decoderConfig),this._started=!0;const i=this._pendingData;this._pendingData=[];for(const e of i)this._processChunks(e)}processData(e){this._stopped||(this._started?this._processChunks(e):this._pendingData.push(e))}_processChunks(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let s=0;for(let i=0;i<this._chunksPerTransmission&&!(s+2>e.byteLength);i++){const i=t.getInt16(s,!1);if(s+=2,i<=0||s+i>e.byteLength)break;const r=e.subarray(s,s+i);s+=i,this._streamInfo.cycles++;const n=Date.now();this._streamInfo.totalMs+=n-this._streamInfo.lastMs,this._streamInfo.lastMs=n,this._streamInfo.totalBytes+=i,this._decode(r)}}_decode(e){try{this._decoder.decode(new EncodedAudioChunk({type:\"key\",timestamp:this._decodeTimestampUs,data:e})),this._decodeTimestampUs+=this._frameDurationUs}catch(e){this._logger.warn(`Audio decode error: ${e}`)}}_onDecoded(e){if(this._stopped||null==this._workletNode)return void e.close();const t=e.numberOfFrames,s=[];try{for(let i=0;i<this._channels;i++){const r=new Float32Array(t);e.copyTo(r,{planeIndex:i,format:\"f32-planar\"}),s.push(r)}}catch(t){return this._logger.warn(`Audio copy error: ${t}`),void e.close()}e.close(),this._workletNode.port.postMessage({type:\"data\",channelData:s},s.map(e=>e.buffer))}toggleMute(e){this._streamInfo.setMuted(e),e&&(this._pendingData.length=0,null!=this._workletNode&&this._workletNode.port.postMessage({type:\"clear\"}),null!=this._decoder&&\"closed\"!==this._decoder.state&&(this._decoder.reset(),this._decoder.configure(this._decoderConfig),this._decodeTimestampUs=0))}stop(){if(!this._stopped){if(this._stopped=!0,null!=this._workletNode&&(this._workletNode.port.onmessage=null,this._workletNode.disconnect(),this._workletNode=null),null!=this._decoder){if(\"closed\"!==this._decoder.state)try{this._decoder.close()}catch(e){this._logger.debug(`Error closing audio decoder: ${e}`)}this._decoder=null}this._pendingData.length=0}}}class SFSAudioManager{constructor(e,t){this._logger=Logger.getInstance(SFSAudioManager.name),this._sfs=e,this._settings=AudioSettings.fromSFSObject(t),this._config=e.config.audio,this._capturer=null,this._players=[],this._captureDevice=null,this._playbackDevice=null,this._permissionGranted=!1,this._micPermissionStatus=null,this._onDeviceChange=null,this._deviceChangeTimer=null,this._playbackContext=null,this._playbackContextPromise=null,Object.seal(this)}async requestUserPermission(){this._checkMediaDevicesAvailable(),this._checkAudioCodecsAvailable();try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});for(const t of e.getTracks())t.stop()}catch(e){throw new Exceptions_SFSError(\"User permission to access audio device not granted, or request failed (check error cause for more information)\",e)}this._permissionGranted=!0,this._watchPermission();try{await this.getDevices()}catch(e){this._logger.warn(`Unable to resolve default audio devices: ${e}`)}this._registerDeviceChangeListener()}async getDevices(){this._checkMediaDevicesAvailable(),this._checkAudioCodecsAvailable(),await this._checkUserPermission();const e=await navigator.mediaDevices.enumerateDevices(),t=e.filter(e=>\"audioinput\"===e.kind),s=e.filter(e=>\"audiooutput\"===e.kind),i=null!=this._captureDevice?this._captureDevice.id:null,r=null!=this._playbackDevice?this._playbackDevice.id:null,n=this._mapDevices(t,i);let a=this._mapDevices(s,r);return this._supportsPlaybackRouting()||(a=a.filter(e=>e.isDefault)),null==this._captureDevice&&(this._captureDevice=n.find(e=>e.isDefault)||n[0]||null),null==this._playbackDevice&&(this._playbackDevice=a.find(e=>e.isDefault)||a[0]||null),{captureDevices:n,playbackDevices:a}}set captureDevice(e){if(null!=e&&!(e instanceof AudioDevice))return void this._logger.warn(\"captureDevice must be an AudioDevice instance or null\");(null!=this._captureDevice?this._captureDevice.id:null)!==(null!=e?e.id:null)&&(this._captureDevice=null!=e?new AudioDevice(e.id,e.name,e.isDefault,!0):null,null!=this._capturer&&this._capturer.setCaptureDevice())}get captureDevice(){return this._captureDevice}set playbackDevice(e){if(null!=e&&!(e instanceof AudioDevice))return void this._logger.warn(\"playbackDevice must be an AudioDevice instance or null\");if(!this._supportsPlaybackRouting())return void this._logger.warn(\"Selecting a playback device is not supported on this browser; playback uses the system default output\");(null!=this._playbackDevice?this._playbackDevice.id:null)!==(null!=e?e.id:null)&&(this._playbackDevice=null!=e?new AudioDevice(e.id,e.name,e.isDefault,!0):null,this._applyPlaybackSinkId())}get playbackDevice(){return this._playbackDevice}get isMuted(){return null!=this._capturer&&this._capturer.streamInfo.isMuted}get hasUserPermission(){return this._permissionGranted}getAudioStreamInfo(e){if(e==this._sfs.mySelf.id){if(null!=this._capturer)return this._capturer.streamInfo;if(null!=this._players[e])return this._players[e].streamInfo}return null}isStreaming(){return null!=this._capturer}isStreamingInRoom(e){return null!=this._capturer&&this._capturer.streamInfo.room.id==e.id}destroy(){null!=this._onDeviceChange&&(navigator.mediaDevices.removeEventListener(\"devicechange\",this._onDeviceChange),this._onDeviceChange=null),null!=this._deviceChangeTimer&&(clearTimeout(this._deviceChangeTimer),this._deviceChangeTimer=null),null!=this._micPermissionStatus&&(this._micPermissionStatus.onchange=null,this._micPermissionStatus=null),this.isStreaming()&&this.stopStreamingSession(),null!=this._playbackContext&&(this._playbackContext.close().catch(()=>{}),this._playbackContext=null),this._playbackContextPromise=null}startStreamingSession(t,s){const r=this._sfs.roomManager.getRoomById(t);this._capturer=new AudioCapturer(this,r,s),this._capturer.start(),this._logger.isDebugEnabled&&this._logger.debug(\"Outgoing audio stream started\");const n={};n[e.MyAudioStream]=this._capturer.streamInfo,this._sfs._dispatchEvent(i.STREAM_START,n)}stopStreamingSession(){const e=this._capturer.streamInfo;this._capturer.stop(),this._capturer=null,this._logger.isDebugEnabled&&this._logger.debug(`Outgoing audio stream stopped: ${e.internalInfoString}`),Object.keys(this._players).forEach(e=>{this.stopPlaybackStream(e)})}_onCaptureStartFailed(e,t){this._capturer===e&&this._stopStreamingOnError(SFSAudioManager._describeCaptureError(t))}_stopStreamingOnError(e){this._sfs.isConnected?this._sfs.send(new StopAudioStreamRequest):this.stopStreamingSession(),this._dispatchAudioError(e)}_dispatchAudioError(t){const s={};s[e.ErrorMessage]=t,this._sfs._dispatchEvent(i.ERROR,s)}static _describeCaptureError(e){switch(null!=e?e.name:null){case\"NotAllowedError\":return\"Permission to access the capture device was denied or revoked\";case\"NotFoundError\":return\"No capture device was found\";case\"NotReadableError\":return\"The capture device is busy or unavailable\";case\"OverconstrainedError\":return\"The selected capture device is no longer available\";case\"SecurityError\":return\"Access to the capture device is blocked by the browser or system policy\";default:return\"Audio capture failed\"+(null!=e&&e.message?\": \"+e.message:\"\")}}toggleCaptureMuted(){null!=this._capturer&&this._capturer.streamInfo.setMuted(!this._capturer.streamInfo.isMuted)}setPlaybackMuted(t,s){const r=this._players[t];if(null!=r){r.toggleMute(s);const t={};t[e.AudioStream]=r.streamInfo,this._sfs._dispatchEvent(i.TOGGLE_MUTE,t)}}startPlaybackStream(t,s,r,n,a){const o=this._sfs.roomManager.getRoomById(t);if(null==o)return void this._logger.error(\"Unable to initialize incoming audio stream due to missing expected Room; id: \"+t);const h=o.getUserById(s);if(null==h)return void this._logger.error(\"Unable to initialize incoming audio stream due to missing expected User; id: \"+s);const l=new AudioPlayer(this,o,h,r,n,a);this._players[s]=l,l.start(),this._logger.isDebugEnabled&&this._logger.debug(`Incoming audio stream initialized: ${l.streamInfo.user}`);const u={};u[e.AudioStream]=l.streamInfo,this._sfs._dispatchEvent(i.STREAM_ADD,u)}writePlaybackStreamData(e,t){const s=this._players[e];null!=s&&s.processData(t)}stopPlaybackStream(t){const s=this._players[t];if(null!=s){s.stop(),this._logger.isDebugEnabled&&this._logger.debug(`Incoming audio stream stopped: ${s.streamInfo.internalInfoString}`);const t={};t[e.AudioStream]=s.streamInfo,this._sfs._dispatchEvent(i.STREAM_REMOVE,t)}}getCaptureChannels(){return this._settings.numChannels}_ensurePlaybackContext(){return null==this._playbackContextPromise&&(this._playbackContextPromise=this._createPlaybackContext()),this._playbackContextPromise}async _createPlaybackContext(){const e=new AudioContext({sampleRate:48e3});this._playbackContext=e;const t=URL.createObjectURL(new Blob([Zs],{type:\"application/javascript\"}));try{await e.audioWorklet.addModule(t)}finally{URL.revokeObjectURL(t)}return\"suspended\"===e.state&&await e.resume().catch(()=>{}),await this._applyPlaybackSinkId(),e}_supportsPlaybackRouting(){return\"undefined\"!=typeof AudioContext&&\"function\"==typeof AudioContext.prototype.setSinkId}async _applyPlaybackSinkId(){const e=this._playbackContext;if(null==e||\"function\"!=typeof e.setSinkId)return;const t=null==this._playbackDevice||this._playbackDevice.isDefault?\"\":this._playbackDevice.id;try{await e.setSinkId(t)}catch(e){this._logger.warn(`Unable to route audio playback to the selected device: ${e}`)}}_registerDeviceChangeListener(){null==this._onDeviceChange&&\"undefined\"!=typeof navigator&&null!=navigator.mediaDevices&&(this._onDeviceChange=()=>{null!=this._deviceChangeTimer&&clearTimeout(this._deviceChangeTimer),this._deviceChangeTimer=setTimeout(()=>{this._deviceChangeTimer=null,this._handleDeviceChange()},300)},navigator.mediaDevices.addEventListener(\"devicechange\",this._onDeviceChange))}async _handleDeviceChange(){let e;try{e=await navigator.mediaDevices.enumerateDevices()}catch(e){return void this._logger.warn(`Unable to handle audio device change: ${e}`)}const t=e.filter(e=>\"audioinput\"===e.kind),s=e.filter(e=>\"audiooutput\"===e.kind),i=this._captureDevice,r=this._reconcileActiveDevice(i,t);null!=r&&(this._captureDevice=r),null!=this._capturer&&null==r?this._stopStreamingOnError(\"No capture device is available; audio streaming was stopped\"):null!=this._capturer&&this._shouldRestartCapture(i,r)&&(this._logger.isDebugEnabled&&this._logger.debug(`Capture device changed; switching to: ${r}`),this._capturer.setCaptureDevice());const n=this._playbackDevice,a=this._reconcileActiveDevice(n,s);null!=a&&(this._playbackDevice=a,null!=n&&n.id===a.id||this._applyPlaybackSinkId())}_reconcileActiveDevice(e,t){const s=this._mapDevices(t,null!=e?e.id:null);if(0===s.length)return null;let i;return i=null==e||e.isDefault?s.find(e=>e.isDefault)||s[0]:s.find(t=>t.id===e.id)||s.find(e=>e.isDefault)||s[0],new AudioDevice(i.id,i.name,i.isDefault,!0)}_shouldRestartCapture(e,t){return null!=t&&null!=e&&(e.id!==t.id||t.isDefault&&\"default\"===t.id)}_mapDevices(e,t){const s=e.some(e=>\"default\"===e.deviceId);return e.map((e,i)=>{const r=s?\"default\"===e.deviceId:0===i,n=null!=t?e.deviceId===t:r;return new AudioDevice(e.deviceId,e.label,r,n)})}_checkMediaDevicesAvailable(){if(\"undefined\"==typeof navigator||null==navigator.mediaDevices||\"function\"!=typeof navigator.mediaDevices.getUserMedia)throw new Exceptions_SFSError(\"Audio device access is unavailable: it requires a secure context (HTTPS, or http://localhost); the page is not being served over a secure context\")}_checkAudioCodecsAvailable(){if(\"undefined\"==typeof AudioEncoder||\"undefined\"==typeof AudioDecoder)throw new Exceptions_SFSError(\"Audio streaming is not supported on this browser: it requires the WebCodecs Opus encoder/decoder (AudioEncoder/AudioDecoder), which are not available here\")}async _checkUserPermission(){try{if(\"granted\"===(await navigator.permissions.query({name:\"microphone\"})).state)return}catch{}throw new Exceptions_SFSError(\"User permission to access audio device not yet granted; call method AudioManager.requestUserPermission before\")}async _watchPermission(){try{const e=await navigator.permissions.query({name:\"microphone\"});this._micPermissionStatus=e,e.onchange=()=>{this._permissionGranted=\"granted\"===e.state,!this._permissionGranted&&this.isStreaming()&&this._stopStreamingOnError(\"Permission to access the capture device was revoked\")}}catch{}}}class HandshakeRequest extends BaseRequest{static KEY_SESSION_TOKEN=\"tk\";static KEY_API=\"api\";static KEY_COMPRESSION_THRESHOLD=\"ct\";static KEY_RECONNECTION_TOKEN=\"rt\";static KEY_CLIENT_TYPE=\"cl\";static KEY_MAX_MESSAGE_SIZE=\"ms\";static KEY_AUDIO_STREAMING_ENABLED=\"ase\";static KEY_ADMIN_PWD_HASHED=\"aph\";constructor(e,t,s){super(Ls.System.Handshake),this._reqObj.putString(HandshakeRequest.KEY_API,e),this._reqObj.putString(HandshakeRequest.KEY_CLIENT_TYPE,s),null!=t&&this._reqObj.putString(HandshakeRequest.KEY_RECONNECTION_TOKEN,t),Object.seal(this)}validate(e){}execute(e){}}class LogoutRequest extends BaseRequest{static KEY_ZONE_NAME=\"zn\";constructor(){super(Ls.System.Logout),Object.seal(this)}validate(e){const t=[];if(null==e.mySelf&&t.push(\"You are not logged in at the moment\"),t.length>0)throw new SFSValidationError(\"Logout request error\",t)}execute(e){}}class ApiVersion{constructor(e,t,s,i=null){this.maj=e,this.min=t,this.sub=s,this.status=i}get canonical(){return`${this.maj}.${this.min}.${this.sub}`}toString(){return this.canonical+(null!=this.status?\"_\"+this.status:\"\")}}class SmartFox{constructor(){this.MIN_PORT_VALUE=0,this.MAX_PORT_VALUE=65535,this.CLIENT_TYPE_SEPARATOR=\":\",this._version=new ApiVersion(3,0,21,\"beta\"),this._configData=new ConfigData,this._logger=Logger.getInstance(SmartFox.name),this._dispatcher=new EventDispatcher,this._isAdminPwdHashed=!1,this._isAudioStreamingEnabled=!1,this._clientDetails=\"JavaScript\",this._socketEngine=new SocketEngine(this),this._socketEngine.addEventListener($s.CONNECT,this._onSocketConnect,this),this._socketEngine.addEventListener($s.DISCONNECT,this._onSocketDisconnect,this),this._socketEngine.addEventListener($s.CONNECTION_RETRY,this._onSocketConnectionRetry,this),this._socketEngine.addEventListener($s.CONNECTION_RESUME,this._onSocketConnectionResume,this),this._isHandshakeComplete=!1,this._sessionToken=null,this._resetState(),this._nodeId=null,Object.seal(this)}get isAdminPwdHashed(){return this._isAdminPwdHashed}get logger(){return this._logger}get version(){return this._version.toString()}get config(){return this._configData}get sessionToken(){return this._sessionToken}get mySelf(){return this._mySelf}get lastJoinedRoom(){return this._lastJoinedRoom}get roomManager(){return this._roomManager}get userManager(){return this._userManager}get buddyManager(){return this._buddyManager}get audioManager(){return this._audioManager}get httpUploadURI(){return this.isConnected&&null!=this.mySelf?`${this._configData.useSSL?\"https\":\"http\"}://${this._configData.host}:${this._configData.port}/WebServices/SFSFileUpload?sessHashId=${this._sessionToken}`:null}get isConnected(){return this._socketEngine.isConnected&&this._isHandshakeComplete}get nodeId(){return this.isConnected?this._nodeId:null}getJoinedRooms(){return this._roomManager.getJoinedRooms()}setClientDetails(e,t){this.isConnected?this._logger.warn(\"SetClientDetails must be called before the connection is started\"):(e=null!=e?e.replace(this.CLIENT_TYPE_SEPARATOR,\" \"):\"\",t=null!=t?t.replace(this.CLIENT_TYPE_SEPARATOR,\" \"):\"\",this._clientDetails=e+this.CLIENT_TYPE_SEPARATOR+t)}connect(e=null){null!=e?this._validateAndSetConfig(e):this._validateAndSetConfig(this._configData,!1),this._socketEngine.connect(this._configData)}disconnect(){this._socketEngine.disconnect(Ms.MANUAL),this._shutdownApi()}killConnection(){this._socketEngine.killConnection()}send(e){if(e instanceof BaseRequest)if(this.isConnected)try{if(e instanceof JoinRoomRequest){if(this._isJoining)return void this._logger.warn(\"Cannot send a 'JoinRoomRequest' while another JoinRoom transaction is ongoing\");this._isJoining=!0}e.validate(this),e.execute(this),this._socketEngine.send(e.message)}catch(e){if(!(e instanceof SFSValidationError&&null!=e.message))throw e;{let t=e.message;if(null!=e.errors)for(const s of e.errors)t+=\"\\n\\t- \"+s;this._logger.warn(t)}}else this._logger.warn(`You are not connected. Request cannot be sent: ${Ls.getNameFromId(e.targetController,e.id)}`);else this._logger.error(\"An invalid request was passed: \"+e)}enableLagMonitor(e,t=4,s=10){null!=this.mySelf?(null!=this._lagMonitor&&this._lagMonitor.destroy(),e&&(this._lagMonitor=new LagMonitor(this,t,s),this._lagMonitor.start())):this._logger.warn(\"Lag Monitoring requires that you are logged in a Zone first\")}addEventListener(e,t,s){this._dispatcher.addEventListener(e,t,s)}removeEventListener(e,t){this._dispatcher.removeEventListener(e,t)}removeAllEventListeners(){this._dispatcher.removeAllEventListeners()}_resetState(){null!=this._lagMonitor&&this._lagMonitor.destroy(),this._userManager=new SFSGlobalUserManager(this),this._roomManager=new SFSRoomManager(this),this._buddyManager=new SFSBuddyManager(this),null!=this._audioManager&&this._audioManager.destroy(),this._audioManager=null,this._lagMonitor=null,this._isJoining=!1,this._currentZone=null,this._lastJoinedRoom=null,this._mySelf=null}_shutdownApi(){null!=this._lagMonitor&&this._lagMonitor.stop(),null!=this._audioManager&&this._audioManager.isStreaming()&&this._audioManager.stopStreamingSession(),setTimeout(()=>{this._isHandshakeComplete=!1,this._sessionToken=null,this._resetState(),this.removeAllEventListeners()},500)}_validateAndSetConfig(e,t=!0){if(!(e instanceof ConfigData))throw new Error(\"Configuration object must be an instance of ConfigData class\");if(null==e.host||\"string\"!=typeof e.host||0===e.host.length)throw new Error(\"Invalid host name / IP address in configuration\");if(null==e.port||\"number\"!=typeof e.port||e.port<this.MIN_PORT_VALUE||e.port>this.MAX_PORT_VALUE)throw new Error(`Invalid port in configuration. Valid range is ${this.MIN_PORT_VALUE}..${this.MAX_PORT_VALUE}`);if(t&&(null==e.zone||\"string\"!=typeof e.zone||0===e.zone.length))throw new Error(\"Invalid Zone name in configuration\");this._configData=e}_dispatchEvent(e,t){this._dispatcher.dispatchEvent(e,t)}_setReconnectionSeconds(e){this._socketEngine.reconnectionSeconds=e}_setupAudioManager(e){this._isAudioStreamingEnabled&&(this._audioManager=new SFSAudioManager(this,e))}_handleHandShake(s){if(s.containsKey(HandshakeRequest.KEY_RECONNECTION_TOKEN)){const e=s.getBool(HandshakeRequest.KEY_RECONNECTION_TOKEN);return void this._socketEngine.completeReconnection(e)}const i=s.getNumber(BaseRequest.KEY_ERROR_CODE);if(null==i)this._isHandshakeComplete=!0,this._sessionToken=s.getString(HandshakeRequest.KEY_SESSION_TOKEN),this._socketEngine.compressionThreshold=s.getNumber(HandshakeRequest.KEY_COMPRESSION_THRESHOLD),this._socketEngine.maxMessageSize=s.getNumber(HandshakeRequest.KEY_MAX_MESSAGE_SIZE),this._isAudioStreamingEnabled=s.getBool(HandshakeRequest.KEY_AUDIO_STREAMING_ENABLED),this._isAdminPwdHashed=s.getBool(HandshakeRequest.KEY_ADMIN_PWD_HASHED),this._logger.isDebugEnabled&&this._logger.debug(`Handshake response: tk => ${this._sessionToken}, ct => ${this._socketEngine.compressionThreshold}`),this._dispatchEvent(t.CONNECTION,{[e.Success]:!0});else{const r=SFSErrorCodes.getErrorMessage(i,s.getStringArray(BaseRequest.KEY_ERROR_PARAMS)),n={[e.Success]:!1,[e.ErrorMessage]:r,[e.ErrorCode]:i};this._dispatchEvent(t.CONNECTION,n)}}_handleLogout(s){this._resetState();const i={[e.ZoneName]:s.getString(LogoutRequest.KEY_ZONE_NAME)};this._dispatchEvent(t.LOGOUT,i)}_onSocketConnect(s){if(s.success){let e=new HandshakeRequest(this._version.canonical,s.isReconnection?this._sessionToken:null,this._clientDetails);this._socketEngine.send(e.message)}else this._dispatchEvent(t.CONNECTION,{[e.Success]:!1}),this._shutdownApi()}_onSocketDisconnect(s){this._dispatchEvent(t.CONNECTION_LOST,{[e.DisconnectionReason]:s.reason}),this._shutdownApi()}_onSocketConnectionRetry(e){this._dispatchEvent(t.CONNECTION_RETRY,{})}_onSocketConnectionResume(e){this._dispatchEvent(t.CONNECTION_RESUME,{})}}class Matcher{constructor(e,t){this._type=e,this._symbol=t,Object.freeze(this)}get type(){return this._type}get symbol(){return this._symbol}}class BoolMatch extends Matcher{constructor(e){super(0,e),Object.freeze(this)}static EQUALS=new BoolMatch(\"==\");static NOT_EQUALS=new BoolMatch(\"!=\")}class NumberMatch extends Matcher{constructor(e){super(1,e),Object.freeze(this)}static EQUALS=new NumberMatch(\"==\");static NOT_EQUALS=new NumberMatch(\"!=\");static GREATER_THAN=new NumberMatch(\">\");static GREATER_THAN_OR_EQUAL_TO=new NumberMatch(\">=\");static LESS_THAN=new NumberMatch(\"<\");static LESS_THAN_OR_EQUAL_TO=new NumberMatch(\"<=\")}class StringMatch extends Matcher{constructor(e){super(2,e),Object.freeze(this)}static EQUALS=new StringMatch(\"==\");static NOT_EQUALS=new StringMatch(\"!=\");static CONTAINS=new StringMatch(\"contains\");static STARTS_WITH=new StringMatch(\"startsWith\");static ENDS_WITH=new StringMatch(\"endsWith\")}const Ws=Object.freeze({NAME:\"${N}\",GROUP_ID:\"${G}\",MAX_USERS:\"${MXU}\",MAX_SPECTATORS:\"${MXS}\",USER_COUNT:\"${UC}\",SPECTATOR_COUNT:\"${SC}\",IS_GAME:\"${ISG}\",IS_PRIVATE:\"${ISP}\",HAS_FREE_PLAYER_SLOTS:\"${HFP}\",IS_TYPE_SFSGAME:\"${IST}\",IS_TYPE_MMO:\"${ISM}\",IS_TYPE_DEFAULT:\"${ISD}\"}),Qs=Object.freeze({NAME:\"${N}\",IS_PLAYER:\"${ISP}\",IS_SPECTATOR:\"${ISS}\",IS_NPC:\"${ISN}\",PRIVILEGE_ID:\"${PRID}\",IS_IN_ANY_ROOM:\"${IAR}\"});class QuickJoinOrCreateRoomRequest extends BaseRequest{static KEY_MATCH_EXPRESSION=\"me\";static KEY_GROUP_LIST=\"gl\";static KEY_ROOM_SETTINGS=\"rs\";static KEY_ROOM_TO_LEAVE=\"tl\";constructor(e,t,s,i=null){super(Ls.System.QuickJoinOrCreateRoom),this._matchExpression=e,this._groupList=t,this._settings=s,this._roomToLeave=i,this._createRoomRequest=new CreateRoomRequest(s,!1,null),Object.seal(this)}validate(e){let t=[];if(null==this._matchExpression&&t.push(\"Missing match expression\"),null==this._matchExpression||this._matchExpression instanceof MatchExpression||t.push(\"Match expression must be an instance of MatchExpression class\"),(null==this._groupList||this._groupList.length<1)&&t.push(\"List of groups to search is null or empty\"),null==this._roomToLeave||this._roomToLeave instanceof SFSRoom||t.push(\"Room to leave must be an instance of SFSRoom class\"),null==this._settings)t.Add(\"No Room settings provided\");else try{this._createRoomRequest.validate(e)}catch(e){t=t.concat(e.errors)}if(t.length>0)throw new SFSValidationError(\"QuickJoinOrCreateRoom request error\",t)}execute(e){this._createRoomRequest.execute(e);let t=this._createRoomRequest.message.content;this._reqObj.putSFSArray(QuickJoinOrCreateRoomRequest.KEY_MATCH_EXPRESSION,this._matchExpression.toSFSArray()),this._reqObj.putStringArray(QuickJoinOrCreateRoomRequest.KEY_GROUP_LIST,this._groupList),this._reqObj.putSFSObject(QuickJoinOrCreateRoomRequest.KEY_ROOM_SETTINGS,t),null!=this._roomToLeave&&this._reqObj.putInt(QuickJoinOrCreateRoomRequest.KEY_ROOM_TO_LEAVE,this._roomToLeave.id)}}class LeaveRoomRequest extends BaseRequest{static KEY_ROOM_ID=\"r\";constructor(e=null){super(Ls.System.LeaveRoom),this._room=e,Object.seal(this)}validate(e){const t=[];if(e.getJoinedRooms().length<1&&t.push(\"You are not joined in any Room\"),null==this._room||this._room instanceof SFSRoom||t.push(\"Room must be an instance of SFSRoom class\"),t.length>0)throw new SFSValidationError(\"LeaveRoom request error\",t)}execute(e){null!=this._room&&this._reqObj.putInt(LeaveRoomRequest.KEY_ROOM_ID,this._room.id)}}class KickUserRequest extends BaseRequest{static KEY_USER_ID=\"u\";static KEY_MESSAGE=\"m\";static KEY_DELAY=\"d\";constructor(e,t=null,s=5){super(Ls.System.KickUser),s<0&&(s=0),this._userId=e,this._message=t,this._delay=s,Object.seal(this)}validate(e){const t=[];if(t.length>0)throw new SFSValidationError(\"KickUser request error\",t)}execute(e){this._reqObj.putInt(KickUserRequest.KEY_USER_ID,this._userId),this._reqObj.putInt(KickUserRequest.KEY_DELAY,this._delay),null!=this._message&&this._message.length>0&&this._reqObj.putString(KickUserRequest.KEY_MESSAGE,this._message)}}class BanUserRequest extends BaseRequest{static KEY_USER_ID=\"u\";static KEY_MESSAGE=\"m\";static KEY_DELAY=\"d\";static KEY_BAN_MODE=\"b\";static KEY_BAN_DURATION_HOURS=\"dh\";constructor(e,t=null,s=zs.BY_NAME,i=5,r=24){super(Ls.System.BanUser),this._userId=e,this._message=t,this._banMode=s,this._delay=i,this._durationHours=r,Object.seal(this)}validate(e){const t=[];if(this._delay<0&&t.push(\"Ban delay value must be >= 0\"),this._durationHours<1&&t.push(\"Ban duration value must be > 0\"),t.length>0)throw new SFSValidationError(\"BanUser request error\",t)}execute(e){this._reqObj.putInt(BanUserRequest.KEY_USER_ID,this._userId),this._reqObj.putInt(BanUserRequest.KEY_DELAY,this._delay),this._reqObj.putInt(BanUserRequest.KEY_BAN_MODE,this._banMode),this._reqObj.putInt(BanUserRequest.KEY_BAN_DURATION_HOURS,this._durationHours),null!=this._message&&this._message.length>0&&this._reqObj.putString(BanUserRequest.KEY_MESSAGE,this._message)}}class BanUsersFromRoomRequest extends BaseRequest{static KEY_USERS=\"u\";static KEY_ROOM=\"r\";static KEY_INTERVAL=\"i\";static KEY_TIME_UNIT=\"t\";static KEY_MESSAGE=\"m\";static MAX_BAN_PER_REQ=10;constructor(e,t,s=null,i=1,r=Hs.HOURS){super(Ls.System.BanUsersFromRoom),this._users=e,this._room=t,this._timeInterval=i,this._timeUnit=r,this._message=s,Object.seal(this)}validate(e){const t=[];if(null==this._users)t.push(\"No Users provided\");else if(this._users instanceof Array){this._users.length<1&&t.push(\"No Users provided\");for(let e of this._users)if(!(e instanceof SFSUser)){t.push(\"Users must be instances of SFSUser class\");break}this._users.length>BanUsersFromRoomRequest.MAX_BAN_PER_REQ&&t.push(`Max # of banned Users per request execeeded: ${this._users.length}; limit is: ${BanUsersFromRoomRequest.MAX_BAN_PER_REQ}`)}else t.push(\"Users must be passed as an array\");if(null!=this._room&&this._room instanceof SFSRoom||t.push(\"Room must be an instance of SFSRoom class\"),this._timeUnit==Hs.HOURS&&(this._timeInterval<1||this._timeInterval>24)&&t.push(\"Invalid time interval: Users can be banned for 1 to 24 hours\"),this._timeUnit==Hs.MINUTES&&(this._timeInterval<1||this._timeInterval>60)&&t.push(\"Invalid time interval: Users can be banned for 1 to 60 minutes\"),t.length>0)throw new SFSValidationError(\"BanUsersFromRoomRequest request error\",t)}execute(e){const t=this._users.filter(e=>null!=e).map(e=>e.id);this._reqObj.putIntArray(BanUsersFromRoomRequest.KEY_USERS,t),this._reqObj.putInt(BanUsersFromRoomRequest.KEY_ROOM,this._room.id),this._reqObj.putInt(BanUsersFromRoomRequest.KEY_INTERVAL,this._timeInterval),this._reqObj.putByte(BanUsersFromRoomRequest.KEY_TIME_UNIT,this._timeUnit),null!=this._message&&this._message.length>0&&this._reqObj.putString(BanUsersFromRoomRequest.KEY_MESSAGE,this._message)}}class UnbanUsersFromRoomRequest extends BaseRequest{static KEY_USERS=\"u\";static KEY_ROOM=\"r\";static KEY_MESSAGE=\"m\";static MAX_USERS_PER_REQ=10;constructor(e,t,s=null){super(Ls.System.UnbanUsersFromRoom),this._userNames=e,this._room=t,this._message=s,Object.seal(this)}validate(e){const t=[];if(null==this._userNames?t.push(\"No User names provided\"):this._userNames instanceof Array?(this._userNames.length<1&&t.push(\"No User names provided\"),this._userNames.length>UnbanUsersFromRoomRequest.MAX_USERS_PER_REQ&&t.push(`Max # of User names per request execeeded: ${this._userNames.length}; limit is: ${UnbanUsersFromRoomRequest.MAX_USERS_PER_REQ}`)):t.push(\"User names must be passed as an array\"),null!=this._room&&this._room instanceof SFSRoom||t.push(\"Room must be an instance of SFSRoom class\"),t.length>0)throw new SFSValidationError(\"UnbanUsersFromRoomRequest request error\",t)}execute(e){this._reqObj.putStringArray(UnbanUsersFromRoomRequest.KEY_USERS,this._userNames),this._reqObj.putInt(UnbanUsersFromRoomRequest.KEY_ROOM,this._room.id),null!=this._message&&this._message.length>0&&this._reqObj.putString(UnbanUsersFromRoomRequest.KEY_MESSAGE,this._message)}}class CreateSFSGameRequest extends BaseRequest{static KEY_IS_PUBLIC=\"gip\";static KEY_MIN_PLAYERS=\"gmp\";static KEY_INVITED_PLAYERS=\"ginp\";static KEY_SEARCHABLE_ROOMS=\"gsr\";static KEY_PLAYER_MATCH_EXP=\"gpme\";static KEY_SPECTATOR_MATCH_EXP=\"gsme\";static KEY_INVITATION_EXPIRY=\"gie\";static KEY_LEAVE_ROOM=\"glr\";static KEY_NOTIFY_GAME_STARTED=\"gns\";static KEY_INVITATION_PARAMS=\"ip\";constructor(e){super(Ls.System.CreateSFSGame),this._settings=e,this._createRoomRequest=new CreateRoomRequest(e,!1,null),Object.seal(this)}validate(e){if(!(this._settings instanceof SFSGameSettings))throw new SFSValidationError(\"CreateSFSGame request error\",[\"Room configuration must be an instance of SFSGameSettings class\"]);let t=[];try{this._createRoomRequest.validate(e)}catch(e){t=e.getErrors()}if(this._settings.minPlayersToStartGame>this._settings.maxUsers&&t.push(\"Minimum number of players to start the game cannot be greater than the Room's maximum number of users\"),(this._settings.invitationExpiryTime<InviteUsersRequest.MIN_EXPIRY_TIME||this._settings.invitationExpiryTime>InviteUsersRequest.MAX_EXPIRY_TIME)&&t.push(\"Invitation expiration time value is out of range (min: \"+InviteUsersRequest.MIN_EXPIRY_TIME+\"; max: \"+InviteUsersRequest.MAX_EXPIRY_TIME+\")\"),null!=this._settings.invitedPlayers&&(this._settings.invitedPlayers instanceof Array?(this._settings.invitedPlayers.length>InviteUsersRequest.MAX_INVITATIONS_FROM_CLIENT_SIDE&&t.push(\"Cannot invite more than \"+InviteUsersRequest.MAX_INVITATIONS_FROM_CLIENT_SIDE+\" players from client side\"),this._settings.invitedPlayers.every(e=>e instanceof SFSUser||e instanceof SFSBuddy)||t.push(\"Each invited player must be an instance of SFSUser or SFSBuddy classes\")):t.push(\"Invited players must be passed in an array\")),null==this._settings.playerMatchExpression||this._settings.playerMatchExpression instanceof MatchExpression||t.push(\"Player match expression must be an instance of MatchExpression class\"),null==this._settings.spectatorMatchExpression||this._settings.spectatorMatchExpression instanceof MatchExpression||t.push(\"Spectator match expression must be an instance of MatchExpression class\"),null==this._settings.invitationParams||this._settings.invitationParams instanceof SFSObject||t.push(\"Custom invitation parameters must be set in a SFSObject class instance\"),t.length>0)throw new SFSValidationError(\"CreateSFSGame request error\",t)}execute(e){if(this._createRoomRequest.execute(e),this._reqObj=this._createRoomRequest._reqObj,this._reqObj.putBool(CreateSFSGameRequest.KEY_IS_PUBLIC,this._settings.isPublic),this._reqObj.putShort(CreateSFSGameRequest.KEY_MIN_PLAYERS,this._settings.minPlayersToStartGame),this._reqObj.putShort(CreateSFSGameRequest.KEY_INVITATION_EXPIRY,this._settings.invitationExpiryTime),this._reqObj.putBool(CreateSFSGameRequest.KEY_LEAVE_ROOM,this._settings.leaveLastJoinedRoom),this._reqObj.putBool(CreateSFSGameRequest.KEY_NOTIFY_GAME_STARTED,this._settings.notifyGameStarted),null!=this._settings.playerMatchExpression&&this._reqObj.putSFSArray(CreateSFSGameRequest.KEY_PLAYER_MATCH_EXP,this._settings.playerMatchExpression.toSFSArray()),null!=this._settings.spectatorMatchExpression&&this._reqObj.putSFSArray(CreateSFSGameRequest.KEY_SPECTATOR_MATCH_EXP,this._settings.spectatorMatchExpression.toSFSArray()),null!=this._settings.invitedPlayers){const e=[];for(let t of this._settings.invitedPlayers)e.push(t.id);this._reqObj.putIntArray(CreateSFSGameRequest.KEY_INVITED_PLAYERS,e)}null!=this._settings.searchableRooms&&this._reqObj.putStringArray(CreateSFSGameRequest.KEY_SEARCHABLE_ROOMS,this._settings.searchableRooms),null!=this._settings.invitationParams&&this._reqObj.putSFSObject(CreateSFSGameRequest.KEY_INVITATION_PARAMS,this._settings.invitationParams)}}class InvitationReplyRequest extends BaseRequest{static KEY_INVITATION_ID=\"i\";static KEY_INVITATION_REPLY=\"r\";static KEY_INVITATION_PARAMS=\"p\";constructor(e,t,s=null){super(Ls.System.InvitationReply),this._invitation=e,this._reply=t,this._params=s,Object.seal(this)}validate(e){const t=[];if(null==this._invitation?t.push(\"Missing invitation object\"):this._invitation instanceof SFSInvitation||t.push(\"Invitation object must be an instance of Invitation class\"),null==this._params||this._params instanceof SFSObject||t.push(\"Custom invitation parameters must be set in a SFSObject class instance\"),t.length>0)throw new SFSValidationError(\"InvitationReply request error\",t)}execute(e){this._reqObj.putInt(InvitationReplyRequest.KEY_INVITATION_ID,this._invitation.id),this._reqObj.putByte(InvitationReplyRequest.KEY_INVITATION_REPLY,this._reply),null!=this._params&&this._reqObj.putSFSObject(InvitationReplyRequest.KEY_INVITATION_PARAMS,this._params)}}class JoinRoomInvitationRequest extends BaseRequest{static KEY_ROOM_ID=\"r\";static KEY_EXPIRY_SECONDS=\"es\";static KEY_INVITED_NAMES=\"in\";static KEY_AS_SPECT=\"as\";static KEY_OPTIONAL_PARAMS=\"op\";constructor(e,t,s=null,i=30,r=!1){super(Ls.System.JoinRoomInvite),this._targetRoom=e,this._invitedUserNames=t,this._params=s,this._expirySeconds=i,this._asSpectator=r,Object.seal(this)}validate(e){const t=[];if(null==this._targetRoom&&t.push(\"Missing target room\"),null==this._targetRoom||this._targetRoom instanceof SFSRoom||t.push(\"Target room must be an instance of SFSRoom class\"),null==this._invitedUserNames?t.push(\"No invitees provided\"):this._invitedUserNames instanceof Array?this._invitedUserNames.length<1&&t.push(\"No invitees provided\"):t.push(\"Invited user names must be passed in an array\"),null==this._params||this._params instanceof SFSObject||t.push(\"Custom invitation parameters must be set in a SFSObject class instance\"),t.length>0)throw new SFSValidationError(\"JoinRoomInvitation request error\",t)}execute(e){this._reqObj.putInt(JoinRoomInvitationRequest.KEY_ROOM_ID,this._targetRoom.id),this._reqObj.putStringArray(JoinRoomInvitationRequest.KEY_INVITED_NAMES,this._invitedUserNames),this._reqObj.putInt(JoinRoomInvitationRequest.KEY_EXPIRY_SECONDS,this._expirySeconds),this._reqObj.putBool(JoinRoomInvitationRequest.KEY_AS_SPECT,this._asSpectator),null!=this._params&&this._reqObj.putSFSObject(JoinRoomInvitationRequest.KEY_OPTIONAL_PARAMS,this._params)}}class QuickJoinGameRequest extends BaseRequest{static KEY_ROOM_LIST=\"rl\";static KEY_GROUP_LIST=\"gl\";static KEY_ROOM_TO_LEAVE=\"tl\";static KEY_MATCH_EXPRESSION=\"me\";static get MAX_ROOMS(){return 32}constructor(e,t=null,s=null){super(Ls.System.QuickJoinGame),this._whereToSearch=e,this._matchExpression=t,this._roomToLeave=s,Object.seal(this)}validate(e){const t=[];if(null==this._whereToSearch||this._whereToSearch.length<1?t.push(\"Missing list of Rooms or Group names where to search the game to join\"):this._whereToSearch.length>QuickJoinGameRequest.MAX_ROOMS&&t.push(\"Too many Rooms specified in list where to search the game to join; client limit is: \"+QuickJoinGameRequest.MAX_ROOMS),null==this._matchExpression||this._matchExpression instanceof MatchExpression||t.push(\"Match expression must be an instance of MatchExpression class\"),null==this._roomToLeave||this._roomToLeave instanceof SFSRoom||t.push(\"Room to leave must be an instance of SFSRoom class\"),t.length>0)throw new SFSValidationError(\"QuickJoinGame request error\",t)}execute(e){if(\"string\"==typeof this._whereToSearch[0])this._reqObj.putStringArray(QuickJoinGameRequest.KEY_GROUP_LIST,this._whereToSearch);else{if(!(this._whereToSearch[0]instanceof SFSRoom))throw new Exceptions_SFSError(\"Invalid type in whereToSearch parameter\");{const e=[];for(let t of this._whereToSearch)t instanceof SFSRoom&&e.push(t.id);this._reqObj.putIntArray(QuickJoinGameRequest.KEY_ROOM_LIST,e)}}null!=this._roomToLeave&&this._reqObj.putInt(QuickJoinGameRequest.KEY_ROOM_TO_LEAVE,this._roomToLeave.id),null!=this._matchExpression&&this._reqObj.putSFSArray(QuickJoinGameRequest.KEY_MATCH_EXPRESSION,this._matchExpression.toSFSArray())}}class BuddyMessageRequest extends GenericMessageRequest{constructor(e,t,s=null){if(super(),null!=t&&!(t instanceof SFSBuddy))throw new Exceptions_SFSError(\"Target buddy must be an instance of SFSBuddy class\");this._type=Js.BUDDY_MSG,this._message=e,this._recipient=null!=t?t.id:-1,this._params=s,Object.seal(this)}}\n//# sourceMappingURL=sfs3-api.js.map\n\n//# sourceURL=webpack:///./node_modules/sfs3-api/dist/sfs3-api.js?\n}");

/***/ }

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	const __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		const cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		const module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		if (!(moduleId in __webpack_modules__)) {
/******/ 			delete __webpack_module_cache__[moduleId];
/******/ 			const e = new Error("Cannot find module '" + moduleId + "'");
/******/ 			e.code = 'MODULE_NOT_FOUND';
/******/ 			throw e;
/******/ 		}
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter/value functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			if(Array.isArray(definition)) {
/******/ 				var i = 0;
/******/ 				while(i < definition.length) {
/******/ 					var key = definition[i++];
/******/ 					var binding = definition[i++];
/******/ 					if(!__webpack_require__.o(exports, key)) {
/******/ 						if(binding === 0) {
/******/ 							Object.defineProperty(exports, key, { enumerable: true, value: definition[i++] });
/******/ 						} else {
/******/ 							Object.defineProperty(exports, key, { enumerable: true, get: binding });
/******/ 						}
/******/ 					} else if(binding === 0) { i++; }
/******/ 				}
/******/ 			} else {
/******/ 				for(var key in definition) {
/******/ 					if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 						Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 					}
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module can't be inlined because the eval devtool is used.
/******/ 	let __webpack_exports__ = __webpack_require__("./src/main.js");
/******/ 	
/******/ })()
;