@usions/sdk 2.38.1 → 2.39.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/browser.js +2 -2
- package/src/modules/back-button.js +12 -0
- package/src/modules/core.js +15 -2
- package/src/modules/game-proxy.js +2 -2
- package/src/modules/misc.js +2 -2
- package/src/modules/permissions.js +2 -2
- package/src/modules/screen-capture.js +99 -0
- package/src/modules/screen.js +2 -2
- package/src/modules/wallet.js +2 -2
- package/types/index.d.ts +8 -0
package/package.json
CHANGED
package/src/browser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! @usions/sdk v2.
|
|
2
|
-
var Usion=function(){"use strict";const e={PERMISSION_DENIED:"PERMISSION_DENIED",NOT_CONNECTED:"NOT_CONNECTED",NO_ROOM:"NO_ROOM",ROOM_NOT_FOUND:"ROOM_NOT_FOUND",NOT_PARTICIPANT:"NOT_PARTICIPANT",NOT_IN_ROOM:"NOT_IN_ROOM",NOT_AUTHORITY:"NOT_AUTHORITY",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",JOIN_TIMEOUT:"JOIN_TIMEOUT",CONNECT_TIMEOUT:"CONNECT_TIMEOUT",INIT_TIMEOUT:"INIT_TIMEOUT",MATCH_TIMEOUT:"MATCH_TIMEOUT",STATE_TOO_LARGE:"STATE_TOO_LARGE",INVALID_STATE:"INVALID_STATE",STALE_STATE:"STALE_STATE",INVALID_NEXT_TURN:"INVALID_NEXT_TURN",INVALID_INPUT:"INVALID_INPUT",NOT_FOUND:"NOT_FOUND",QUOTA_EXCEEDED:"QUOTA_EXCEEDED",VALUE_TOO_LARGE:"VALUE_TOO_LARGE",LOBBY_FULL:"LOBBY_FULL",LOBBY_CLOSED:"LOBBY_CLOSED",WORLD_FULL:"WORLD_FULL",CONFLICT:"CONFLICT",RATE_LIMITED:"RATE_LIMITED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",QUEUE_FULL:"QUEUE_FULL",AUTH_CHANGED:"AUTH_CHANGED",CANCELLED:"CANCELLED",SUPERSEDED:"SUPERSEDED",UNSUPPORTED:"UNSUPPORTED",VOICE_UNSUPPORTED:"VOICE_UNSUPPORTED",VOICE_DISABLED:"VOICE_DISABLED",VOICE_UNAVAILABLE:"VOICE_UNAVAILABLE",VOICE_NO_ROOM:"VOICE_NO_ROOM",VOICE_NOT_IN_ROOM:"VOICE_NOT_IN_ROOM",VOICE_BAD_CHANNEL:"VOICE_BAD_CHANNEL",VOICE_FULL:"VOICE_FULL",VOICE_DECLINED:"VOICE_DECLINED",VOICE_MIC_DENIED:"VOICE_MIC_DENIED",VOICE_GUEST:"VOICE_GUEST",VOICE_FAILED:"VOICE_FAILED",UNKNOWN:"UNKNOWN"};class t extends Error{constructor(t,n){super(n||t),this.name="UsionError",this.code=e[t]?t:e.UNKNOWN,this.retryAfter=void 0}}const n=[[/not authenticated/i,e.NOT_AUTHENTICATED],[/room_id required|no room id/i,e.NO_ROOM],[/room not found/i,e.ROOM_NOT_FOUND],[/not in room/i,e.NOT_IN_ROOM],[/not a participant/i,e.NOT_PARTICIPANT],[/room authority/i,e.NOT_AUTHORITY],[/exceeds .*limit/i,e.STATE_TOO_LARGE],[/stale checkpoint|stale state/i,e.STALE_STATE],[/state must be/i,e.INVALID_STATE],[/next_turn must be/i,e.INVALID_NEXT_TURN],[/rate limit|too many/i,e.RATE_LIMITED],[/join timeout/i,e.JOIN_TIMEOUT],[/connection timeout|connect timeout/i,e.CONNECT_TIMEOUT],[/request timeout/i,e.REQUEST_TIMEOUT],[/not connected/i,e.NOT_CONNECTED],[/quota exceeded/i,e.QUOTA_EXCEEDED],[/value too large/i,e.VALUE_TOO_LARGE],[/lobby is full/i,e.LOBBY_FULL],[/lobby is not open/i,e.LOBBY_CLOSED],[/world room is full/i,e.WORLD_FULL],[/not found|unknown service/i,e.NOT_FOUND],[/conflict/i,e.CONFLICT],[/cancelled/i,e.CANCELLED],[/superseded/i,e.SUPERSEDED]];function i(i,r){if(i instanceof t)return i;if(i&&"object"==typeof i){const n="string"==typeof i.code&&e[i.code]?i.code:null,r=i.message||i.error;if(n){const e=new t(n,"string"==typeof r?r:n),o=null!=i.retry_after?i.retry_after:i.retryAfter;return"number"==typeof o&&isFinite(o)&&(e.retryAfter=o),e}i instanceof Error||"string"!=typeof r||(i=r)}const o=i&&i.message?i.message:String(i||"Unknown error");for(let e=0;e<n.length;e++)if(n[e][0].test(o))return new t(n[e][1],o);return new t(r||e.UNKNOWN,o)}const r=/^[a-z0-9][a-z0-9_-]{0,47}$/;function o(e,t){try{e(t)}catch(e){console.error("[Usion] call voice listener error:",e)}}function s(n){let i={on:!1,channel:null,scope:null,status:"idle",micOn:!1,peers:[]};const s=new Set,c=new Set;let a=!1;function u(){const e=n.config&&n.config.hostFeatures;return!(!e||!e.voice)}function l(){a||(a=!0,n.on("CALL_VOICE_CHANGED",function(e){e&&e.state&&d(e.state)}),n.on("CALL_VOICE_SPEAKING",function(e){const t=e&&Array.isArray(e.userIds)?e.userIds.filter(function(e){return"string"==typeof e}):[];c.forEach(function(e){o(e,t)})}))}function d(e){return i=function(e){if(!e||"object"!=typeof e)return{on:!1,channel:null,scope:null,status:"idle",micOn:!1,peers:[]};const t=Array.isArray(e.peers)?e.peers:[];return{on:!!e.on,channel:"string"==typeof e.channel?e.channel:null,scope:"room"===e.scope||"game"===e.scope?e.scope:null,status:["idle","connecting","connected","reconnecting"].indexOf(e.status)>=0?e.status:"idle",micOn:!!e.micOn,peers:t.filter(function(e){return e&&"string"==typeof e.userId}).map(function(e){return{userId:e.userId,name:"string"==typeof e.name?e.name:"",isMe:!!e.isMe,micOn:!!e.micOn,speaking:!!e.speaking}})}}(e),s.forEach(function(e){o(e,i)}),i}function f(r,o,s){return u()?(l(),n._request(r,o,s).then(function(e){return e&&e.state?d(e.state):i})):Promise.reject(new t(e.VOICE_UNSUPPORTED,"Voice needs a newer version of the Usion app"))}return{isAvailable:u,micOn:function(n){const i=n||{},o=null==i.channel?"main":i.channel,s=null==i.scope?"room":i.scope;return"string"==typeof o&&r.test(o)?"room"!==s&&"game"!==s?Promise.reject(new t(e.VOICE_BAD_CHANNEL,"scope must be 'room' or 'game'")):f("CALL_VOICE_ON",{channel:o,scope:s,listen:!!i.listen},6e4):Promise.reject(new t(e.VOICE_BAD_CHANNEL,"Channel names are 1-48 of a-z, 0-9, '-', '_' and start with a letter or digit"))},micOff:function(){return f("CALL_VOICE_OFF",{},5e3).then(function(){})},setMic:function(e){return f("CALL_VOICE_SET_MIC",{on:!!e},5e3)},mutePeer:function(n,i){return"string"==typeof n&&n?f("CALL_VOICE_MUTE_PEER",{userId:n,muted:!1!==i},5e3).then(function(){}):Promise.reject(new t(e.INVALID_INPUT,"userId required"))},state:function(){return u()?f("CALL_VOICE_STATE",{},5e3):Promise.resolve({on:!1,channel:null,scope:null,status:"idle",micOn:!1,peers:[]})},onChange:function(e){if(l(),s.add(e),i.on){const t=i;Promise.resolve().then(function(){s.has(e)&&i===t&&o(e,t)})}return function(){s.delete(e)}},onSpeaking:function(e){return l(),c.add(e),function(){c.delete(e)}}}}const c=/^[a-z0-9][a-z0-9_-]{0,47}$/;function a(n){if(n instanceof t)return n;const i=n&&"string"==typeof n.code?n.code:e.VOICE_FAILED;return new t(i,n&&n.message||"Voice count unavailable")}function u(n){const i=new Map;let r=!1;function o(e,t){e.count=t,e.listeners.forEach(function(e){try{e(t)}catch(e){console.error("[Usion] voice count listener error:",e)}})}function s(s,u,l){let d;try{if(d=function(n){const i=n||{},r=null==i.channel?"main":i.channel,o=null==i.scope?"room":i.scope;if("string"!=typeof r||!c.test(r))throw new t(e.VOICE_BAD_CHANNEL,"Channel names are 1-48 of a-z, 0-9, '-', '_' and start with a letter or digit");if("room"!==o&&"game"!==o)throw new t(e.VOICE_BAD_CHANNEL,"scope must be 'room' or 'game'");return{channel:r,scope:o,key:o+":"+r}}(s),"function"!=typeof u)throw new t(e.INVALID_INPUT,"callback required");if(!function(){const e=n.config&&n.config.hostFeatures;return!(!e||!e.voiceCount)}())throw new t(e.VOICE_UNSUPPORTED,"Voice counts need a newer version of the Usion app")}catch(e){const t=a(e);return"function"==typeof l?Promise.resolve().then(function(){l(t)}):console.warn("[Usion] call.onCount:",t.message),function(){}}r||(r=!0,n.on("CALL_VOICE_COUNT",function(e){if(!e||"number"!=typeof e.count||e.count<0)return;const t=i.get(e.scope+":"+e.channel);t&&t.count!==e.count&&o(t,e.count)}));const f=d.key;let h=i.get(f);const _=!h;h||(h={channel:d.channel,scope:d.scope,count:null,failed:!1,listeners:new Set,errorListeners:new Set},i.set(f,h));const p=h;p.listeners.add(u);const m="function"==typeof l?l:function(e){console.warn("[Usion] call.onCount:",e.message)};if(p.errorListeners.add(m),_)n._request("CALL_VOICE_WATCH",{channel:d.channel,scope:d.scope},15e3).then(function(e){i.get(f)===p&&e&&"number"==typeof e.count&&o(p,e.count)},function(e){i.get(f)===p&&function(e,t){const n=i.get(e);n&&(i.delete(e),n.failed=!0,n.errorListeners.forEach(function(e){try{e(t)}catch(e){console.error("[Usion] voice count error listener:",e)}}))}(f,a(e))});else if(null!==p.count){const e=p.count;Promise.resolve().then(function(){if(p.listeners.has(u)&&p.count===e)try{u(e)}catch(e){console.error("[Usion] voice count listener error:",e)}})}let g=!1;return function(){g||(g=!0,p.listeners.delete(u),p.errorListeners.delete(m),0===p.listeners.size&&i.get(f)===p&&(i.delete(f),n._request("CALL_VOICE_UNWATCH",{channel:p.channel,scope:p.scope},5e3).catch(function(){})))}}return{onCount:s,count:function(n){return new Promise(function(i,r){let o=null,c=!1;function a(e){if(!c&&(c=!0,clearTimeout(u),e(),o)){const e=o;o=null,Promise.resolve().then(e)}}const u=setTimeout(function(){a(function(){r(new t(e.VOICE_FAILED,"Voice count timed out"))})},1e4);if(o=s(n,function(e){a(function(){i(e)})},function(e){a(function(){r(e)})}),c&&o){const e=o;o=null,e()}})}}}let l=0;const d={};function f(){return++l}let h=null;function _(){return"undefined"!=typeof window&&window.parent!==window&&/[?&]usion_compose_id=[0-9a-f-]{36}(?:&|$)/i.test(window.location&&window.location.search||"")}function p(e){return"undefined"==typeof window||(!(!window.ReactNativeWebView||_())||(window.parent===window||(!e||!e.source||e.source===window.parent)&&(null===h&&(h=function(){try{if(window.location.ancestorOrigins&&window.location.ancestorOrigins.length)return window.location.ancestorOrigins[0]}catch(e){}try{if("undefined"!=typeof document&&document.referrer)return new URL(document.referrer).origin}catch(e){}return null}()),!(h&&e&&e.origin&&e.origin!==h))))}const m={version:"2.38.1",config:{},_initialized:!1,_initCallback:null,_messageHandlerRegistered:!1,_results:[],_backButtonCallback:null,init:function(n,r){const o=this;return n&&"object"==typeof n&&(r=n,n=null),r=r||{},o._initialized?(n&&n(o.config),Promise.resolve(o.config)):(n&&(o._initCallback=n),o._initPromise||(o._initPromise=new Promise(function(e,t){o._initResolve=e,o._initReject=t}),o._initPromise.catch(function(){})),r.timeout>0&&!o._initTimer&&(o._initTimer=setTimeout(function(){o._initTimer=null,!o._initialized&&o._initReject&&o._initReject(new t(e.INIT_TIMEOUT,"No INIT from host within "+r.timeout+"ms — host silent or running standalone"))},r.timeout)),o._messageHandlerRegistered||(o._messageHandlerRegistered=!0,window.addEventListener("message",function(e){if(!p(e))return;let t;try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}if("INIT"===t.type&&t.config){if(o._initialized)return o.user&&o.user._applyAuth(t.config,!1),void 0!==t.config.sessionId&&o.session&&(o.config.sessionId=o.session._id=t.config.sessionId||null,o.config.sessionData=o.session._data=t.config.sessionData||{}),Array.isArray(t.config.results)&&(o._results=o.config.results=t.config.results),void 0!==t.config.balance&&o.wallet&&(o.wallet._balance=t.config.balance),!0!==t.config.userIsAdult&&!1!==t.config.userIsAdult||!o.user||(o.config.userIsAdult=t.config.userIsAdult,o.user._isAdult=t.config.userIsAdult),void(t.config.hostFeatures&&"object"==typeof t.config.hostFeatures&&(o.config.hostFeatures=t.config.hostFeatures));o.config=t.config,o._initialized=!0,o._isEmbedded=!0,o.user&&o.user._applyAuth(t.config,!1),t.config.sessionId&&(o.session._id=t.config.sessionId,o.session._data=t.config.sessionData||{}),void 0!==t.config.balance&&(o.wallet._balance=t.config.balance),t.config.results&&(o._results=t.config.results),o._initCallback&&o._initCallback(t.config),o._initTimer&&(clearTimeout(o._initTimer),o._initTimer=null),o._initResolve&&o._initResolve(t.config)}if("AUTH_CHANGED"===t.type&&o.user&&o.user._applyAuth(t,!0),"HOST_TAB_BLOCKED"===t.type&&o.tabs&&o.tabs._dispatchBlocked(t),t._requestId&&d[t._requestId]){const{resolve:e,reject:n}=d[t._requestId];delete d[t._requestId],t.error?n(i(t)):e(t)}if("BALANCE_UPDATE"===t.type&&(o.wallet._balance=t.balance,o.wallet._balanceChangeHandler&&o.wallet._balanceChangeHandler(t.balance)),"BACK_BUTTON_PRESSED"===t.type&&o._backButtonCallback){var n=o._backButtonCallback;o._backButtonCallback=null,n()}if("BOT_MESSAGE"===t.type&&o.bot&&o.bot._messageHandler&&o.bot._messageHandler(t.message),"HOST_NAVIGATE"===t.type&&"string"==typeof t.path&&(o.config&&(o.config.launchPath=t.path),o._hostNavigateCallback&&o._hostNavigateCallback({path:t.path,tab:t.tab||null})),"BACKEND_EVENT"===t.type&&t.event&&o._backendHandlers){const e=o._backendHandlers[t.event];e&&e(t.data)}if("GAME_ROOM_ASSIGNED"===t.type&&t.roomId&&o.game){var r=t.roomId;o.config.roomId=r,o.config.mode="multiplayer",o.game._dispatch("roomAssigned",{roomId:r}),Promise.resolve().then(function(){return o.game.connect()}).then(function(){return o.game.join(r)}).catch(function(){})}}),this._setupInteractionBeacon(),this._post({type:"READY"})),o._initPromise)},_setupInteractionBeacon:function(){const e=this;if(e._interactionBeaconSetup)return;if(e._interactionBeaconSetup=!0,"undefined"==typeof window||!window.addEventListener)return;const t=["pointerdown","mousedown","touchstart","keydown"];function n(i){if(!(i&&!1===i.isTrusted||e._interactionReported)){e._interactionReported=!0;for(let e=0;e<t.length;e++)try{window.removeEventListener(t[e],n,!0)}catch(e){}e._post({type:"USER_INTERACTION"})}}for(let e=0;e<t.length;e++)try{window.addEventListener(t[e],n,{capture:!0,passive:!0})}catch(i){try{window.addEventListener(t[e],n,!0)}catch(e){}}},getTheme:function(){return this.config.theme||"light"},getLanguage:function(){return this.config.language||"en"},getLaunchParams:function(){var e=this.config||{},t="single"===e.mode||"multiplayer"===e.mode?e.mode:e.roomId?"multiplayer":"single";return{path:e.launchPath||null,ref:e.ref||e.launchRef||null,roomId:e.roomId||null,mode:t}},_post:function(e){const t=JSON.stringify(e);_()?window.parent.postMessage(e,"*"):window.ReactNativeWebView?window.ReactNativeWebView.postMessage(t):window.parent!==window&&window.parent.postMessage(e,"*")},_invalidateAuthRequests:function(){Object.keys(d).forEach(function(n){const i=d[n];i.identityBound&&(delete d[n],i.reject(new t(e.AUTH_CHANGED,"Account changed while request was pending")))})},_request:function(n,i,r){const o=this;return r=r||5e3,new Promise(function(s,c){const a=f(),u=setTimeout(function(){delete d[a],c(new t(e.REQUEST_TIMEOUT,"Request timeout"))},r);d[a]={identityBound:-1===["CONFIGURE_HOST_TABS","OPEN_HOST_TAB","REQUEST_LOGIN","CALL_CAPABILITIES"].indexOf(n),resolve:function(e){clearTimeout(u),s(e)},reject:function(e){clearTimeout(u),c(e)}},o._post({type:n,_requestId:a,...i})})}};var g="_d:",y="_migrated_v2";function v(e){return g+e}function I(e,t,n){return e._backendEmit(t,Object.assign({service_id:e.config&&e.config.serviceId,scope:"storage"},n))}function E(e,t){return e._request("STORAGE_GET",{key:t}).then(function(e){return e?e.value:null})}function w(e,t,n){return e._request("STORAGE_SET",{key:t,value:n})}function b(e,t){return e._request("STORAGE_REMOVE",{key:t})}function T(e){return e._request("STORAGE_KEYS",{}).then(function(e){return e&&e.keys||[]})}function S(e){return e.catch(function(){})}const A={setLoading:function(e,t){const n="string"==typeof e?document.querySelector(e):e;n&&(t?(n.classList.add("usion-btn-loading"),n.disabled=!0,n.dataset.originalText=n.textContent):(n.classList.remove("usion-btn-loading"),n.disabled=!1,n.dataset.originalText&&(n.textContent=n.dataset.originalText)))},toggle:function(e,t){const n="string"==typeof e?document.querySelector(e):e;n&&(t?(n.classList.remove("usion-hidden","hidden"),n.classList.add("usion-visible")):(n.classList.add("usion-hidden"),n.classList.remove("usion-visible")))},charCount:function(e,t,n){const i="string"==typeof e?document.querySelector(e):e,r="string"==typeof t?document.querySelector(t):t;function o(){const e=i.value.length;r.textContent=e+" / "+n,r.classList.remove("warning","error"),e>.9*n?r.classList.add("error"):e>.7*n&&r.classList.add("warning")}i&&r&&(i.addEventListener("input",o),o())},selectionGrid:function(e,t,n){const i=document.querySelector(e);if(!i)return;let r=null;return i.querySelectorAll(t).forEach(function(e){e.addEventListener("click",function(){i.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),e.classList.add("selected"),r=e.dataset.value||e.dataset.id,n&&n(r,e)})}),{getSelected:function(){return r},clear:function(){i.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),r=null}}}},O={requestPayment:function(e,t,n){return this.wallet.requestPayment(e,t,n)},diagnostics:function(){const e=this.game||{};return{version:this.version,transport:e.directMode?"direct":e._useProxy?"proxy":e.socket?"socket":"none",connected:!!e.connected,joined:!!e._joined,roomId:e.roomId||null,playerId:e.playerId||null,lastSequence:e._lastSequence||0,lastActionApplied:e._lastActionApplied||0,rejoining:!!e._rejoinPromise}},submit:function(e){this._post({type:"SUBMIT",data:e})},error:function(e){this._post({type:"ERROR",message:e})},exit:function(e){var t={type:"EXIT"};e&&"number"==typeof e.backCount&&e.backCount>1&&(t.backCount=e.backCount),this._post(t)},share:function(e,t){var n=Object.assign({},t,{contentType:e,serviceId:this.config.serviceId,serviceName:this.config.serviceName});this._post({type:"SHARE",contentType:e,data:n})},shareFile:function(e,t){var n={url:e};return(t=t||{}).filename&&(n.filename=t.filename),t.mimeType&&(n.mimeType=t.mimeType),t.title&&(n.title=t.title),t.text&&(n.text=t.text),this._request("SHARE_FILE",n,12e4)},shareToStory:function(e,t){var n={url:e};return(t=t||{}).filename&&(n.filename=t.filename),t.mimeType&&(n.mimeType=t.mimeType),t.stickerUrl&&(n.stickerUrl=t.stickerUrl),t.backgroundTopColor&&(n.backgroundTopColor=t.backgroundTopColor),t.backgroundBottomColor&&(n.backgroundBottomColor=t.backgroundBottomColor),t.title&&(n.title=t.title),t.text&&(n.text=t.text),this._request("SHARE_TO_STORY",n,12e4)},download:function(e,t,n){t&&"object"==typeof t&&(t=(n=t).filename),n=n||{};var i={url:e,filename:t||n.filename||"download.mp4"};return n.mimeType&&(i.mimeType=n.mimeType),n.destination&&(i.destination=n.destination),n.title&&(i.title=n.title),this._request("DOWNLOAD_FILE",i,12e4)},log:function(e){this._post({type:"LOG",msg:e}),console.log("[Usion]",e)},on:function(e,t){function n(n){if(!p(n))return;let i;try{i="string"==typeof n.data?JSON.parse(n.data):n.data}catch(e){return}i.type===e&&t(i)}return window.addEventListener("message",n),function(){window.removeEventListener("message",n)}}};var k=/[\x00-\x1f\x7f\s\\]/;function C(e){return"string"!=typeof e?"path must be a string":e.length>512?"path too long (max 512)":"/"!==e.charAt(0)||"/"===e.charAt(1)?"path must be a relative in-app path starting with a single '/'":-1!==e.indexOf("://")||k.test(e)?"path contains illegal characters":null}function N(e){return Array.from(e).length}var P=5242880,R=/^data:image\/(png|jpeg|webp);base64,/,M=/^[A-Za-z0-9+/]+={0,2}$/;function q(){var e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if(e&&"function"==typeof e.randomUUID)return e.randomUUID();var t=new Array(16);if(e&&"function"==typeof e.getRandomValues){var n=new Uint8Array(16);e.getRandomValues(n);for(var i=0;i<16;i++)t[i]=n[i]}else for(var r=0;r<16;r++)t[r]=Math.floor(256*Math.random());t[6]=15&t[6]|64,t[8]=63&t[8]|128;var o=t.map(function(e){return(e+256).toString(16).slice(1)}).join("");return o.slice(0,8)+"-"+o.slice(8,12)+"-"+o.slice(12,16)+"-"+o.slice(16,20)+"-"+o.slice(20)}const D={canShareToFeed:function(e){var t=this.config&&this.config.hostFeatures;return!(!t||!0!==t.feedShare)&&("image"===e?!0===t.feedShareImage:"video"===e?!0===t.feedShareVideo:"videoUpload"===e?!0===t.feedShareVideoUpload:!e)},uploadFeedVideo:async function(n,i){if(!this.canShareToFeed("videoUpload"))throw new t(e.UNSUPPORTED,"Video uploads require a newer host");if(!n||"number"!=typeof n.size||"function"!=typeof n.slice||n.size<=0||n.size>3221225472||["video/mp4","video/quicktime","video/webm","video/x-matroska"].indexOf(n.type)<0)throw new t(e.INVALID_INPUT,"Choose a supported video of at most 3 GiB");var r=this,o=this.config||{},s=i||{};if(!(r.user&&r.user.getToken()&&o.serviceId&&o.apiUrl))throw new t(e.NOT_AUTHENTICATED,"Sign in to upload");var c=o.apiUrl.replace(/\/$/,"")+"/feed/video-uploads/"+encodeURIComponent(o.serviceId)+"/multipart",a=null;async function u(n,i,o,c){var a={Authorization:"Bearer "+r.user.getToken()};c&&(a["Content-Type"]=c);var u=await fetch(n,{method:i,headers:a,body:o,signal:s.signal});if(!u.ok)throw new t(429===u.status?e.RATE_LIMITED:401===u.status?e.NOT_AUTHENTICATED:403===u.status?e.PERMISSION_DENIED:u.status<500?e.INVALID_INPUT:e.UNKNOWN,"Video upload failed");return u.json()}function l(e){if("function"==typeof s.onProgress)try{s.onProgress({loaded:e,total:n.size})}catch(e){}}try{var d=await u(c,"POST",JSON.stringify({request_id:s.requestId||q(),file_size:n.size,file_type:n.type}),"application/json");if("string"!=typeof(a=d.file_id)||!a)throw new t(e.UNKNOWN,"Invalid upload session");var f=c+"/"+encodeURIComponent(a);if("ready"!==(d=await u(f,"GET")).status&&"completing"!==d.status){var h=d.part_size,_=new Set(d.uploaded_parts||[]),p=0;if(!Number.isInteger(h)||h<1)throw new t(e.UNKNOWN,"Invalid upload part size");for(var m=1,g=0;g<n.size;m++,g+=h){var y=n.slice(g,Math.min(g+h,n.size));if(!_.has(m))for(var v=0;;v++)try{await u(f+"/parts/"+m,"PUT",y,"application/octet-stream");break}catch(n){if(s.signal&&s.signal.aborted)throw n;if(v>=2||n instanceof t&&n.code!==e.UNKNOWN)throw n;await new Promise(function(e){setTimeout(e,500*(v+1))})}l(p+=y.size)}}var I=await u(f+"/complete","POST");if(!I||"string"!=typeof I.receipt)throw new t(e.UNKNOWN,"Invalid upload response");return l(n.size),{receipt:I.receipt}}catch(n){if(s.signal&&s.signal.aborted&&a){try{await fetch(c+"/"+encodeURIComponent(a),{method:"DELETE",headers:{Authorization:"Bearer "+r.user.getToken()}})}catch(e){}throw new t(e.CANCELLED,"Video upload cancelled")}throw n}},shareToFeed:function(n,i){if(i=i||{},"video"===n&&null==i.video&&null==i.videoReceipt)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: video is required"));var r="string"==typeof i.text?i.text.trim():"";if(!r)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: text is required"));var o={contentType:n||"text",text:r,requestId:"string"==typeof i.requestId&&i.requestId?i.requestId:q(),serviceId:this.config&&this.config.serviceId,serviceName:this.config&&this.config.serviceName};if(null!=i.path&&""!==i.path){var s=C(i.path);if(s)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+s));o.path=i.path}if(null!=i.card){var c=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{error:"card must be an object"};var t="string"==typeof e.title?e.title.trim():"";if(!t)return{error:"card.title is required"};if(N(t)>200)return{error:"card.title too long (max 200)"};var n={title:t};if(null!=e.subtitle){if("string"!=typeof e.subtitle)return{error:"card.subtitle must be a string"};var i=e.subtitle.trim();if(N(i)>60)return{error:"card.subtitle too long (max 60)"};i&&(n.subtitle=i)}return{card:n}}(i.card);if("error"in c)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+c.error));o.card=c.card}if(null!=i.image){var a=function(e){var t="string"==typeof e&&R.exec(e);if(!t)return"image must be a data:image/(png|jpeg|webp);base64 URL";var n=e.slice(t[0].length),i="=="===n.slice(-2)?2:"="===n.slice(-1)?1:0;return Math.floor(3*n.length/4)-i>P?"image too large (max 5 MB)":n.length%4==0&&M.test(n)?null:"image is not valid base64"}(i.image);if(a)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+a));o.image=i.image}if(null!=i.video){if(null!=i.image||"string"!=typeof i.video||!/^data:video\/mp4;base64,/.test(i.video))return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: video must be an MP4 data URL without an image"));var u=i.video.slice(22),l="=="===u.slice(-2)?2:"="===u.slice(-1)?1:0;if(!u||u.length%4!=0||3*u.length/4-l>P||!M.test(u))return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: invalid video or video exceeds 5 MB"));if(!this.canShareToFeed("video"))return Promise.reject(new t(e.UNSUPPORTED,"shareToFeed: host does not support video"));o.video=i.video}if(null!=i.videoReceipt){if(null!=i.video||null!=i.image||"string"!=typeof i.videoReceipt||!i.videoReceipt||i.videoReceipt.length>8192)return Promise.reject(new t(e.INVALID_INPUT,"Invalid video receipt"));if(!this.canShareToFeed("videoUpload"))return Promise.reject(new t(e.UNSUPPORTED,"Video uploads require a newer host"));o.videoReceipt=i.videoReceipt}return this._request("SHARE_TO_FEED",o,6e5).then(function(e){return Object.assign({success:!0},e)})},openApp:function(n,i){if("string"!=typeof n||!n.trim())throw new t(e.INVALID_INPUT,"openApp: serviceId is required");var r={type:"OPEN_SERVICE",serviceId:n.trim()};if(null!=i&&""!==i){var o=C(i);if(o)throw new t(e.INVALID_INPUT,"openApp: "+o);r.path=i}this._post(r)}};function U(e,t){var n={liveness:{probeAfterMs:4e3,deadAfterMs:12e3},backpressureBytes:8192,lastInboundAt:0,lastProbeAt:0,lastWatchdogAt:0,livenessGraceUntil:0,lastCloseCode:null,declaredDead:!1,watchdogTimer:null,drainTimer:null,pendingInput:null,visHandler:null,lastVisResyncAt:0,wrappedDisconnect:!1,rtt:null,jitter:0,quality:"dead"};function i(){if(null!=n.rtt)return{rtt:n.rtt,jitter:n.jitter};var t=e._pingMeter;return t&&null!=t.rtt?{rtt:t.rtt,jitter:t.jitter}:{rtt:null,jitter:null}}function r(){var t=function(){var t=e.getConnectionState?e.getConnectionState():e.connected?"connected":"disconnected";if(n.declaredDead||"disconnected"===t)return"dead";if(e.directMode&&(!e.directSocket||1!==e.directSocket.readyState))return"dead";var r=i().rtt||0,o=e.directMode&&n.lastInboundAt?Date.now()-n.lastInboundAt:0;return r<150&&o<2e3?"good":r<400&&o<5e3?"fair":"poor"}();if(t!==n.quality){var r=n.quality;n.quality=t,e._dispatch("networkQuality",{quality:t,prev:r,stats:e.getNetworkStats()})}}function o(){n.watchdogTimer&&(clearInterval(n.watchdogTimer),n.watchdogTimer=null)}function s(){var t=e.directSocket;if(t&&1===t.readyState){var i=Date.now(),r=function(){};r.sentAt=i,r.statsOnly=!0,e._pongWaiters.push(r),n.lastProbeAt=i,e._sendDirect("ping",{t:i})}}function c(){var i=e.directSocket;if(e.directMode&&i&&1===i.readyState){if(n.liveness){var c=Date.now(),a=n.lastWatchdogAt&&c-n.lastWatchdogAt>2e3;if(n.lastWatchdogAt=c,"undefined"!=typeof document&&"hidden"===document.visibilityState)return void(n.livenessGraceUntil=c+n.liveness.deadAfterMs);if(a)return n.livenessGraceUntil=c+n.liveness.deadAfterMs,s(),void r();var u=c-n.lastInboundAt;if(u>=n.liveness.deadAfterMs&&c>=n.livenessGraceUntil){n.declaredDead=!0,o(),t.log("Direct socket liveness timeout - declaring dead"),r(),e._dispatch("disconnect","liveness_timeout");try{i.close()}catch(e){}return}u>=n.liveness.probeAfterMs&&c-n.lastProbeAt>=n.liveness.probeAfterMs&&s()}r()}else o()}function a(){n.drainTimer=null;var t=e.directSocket;if(t&&1===t.readyState){if(null!=n.pendingInput)if(t.bufferedAmount>n.backpressureBytes)n.drainTimer=setTimeout(a,50);else{var i=n.pendingInput;n.pendingInput=null,e._sendDirect("input",i)}}else n.pendingInput=null}function u(){o(),n.drainTimer&&(clearTimeout(n.drainTimer),n.drainTimer=null),n.pendingInput=null,function(){n.visHandler&&"undefined"!=typeof document&&document.removeEventListener&&document.removeEventListener("visibilitychange",n.visHandler);n.visHandler=null}(),e._pongWaiters&&e._pongWaiters.length&&(e._pongWaiters=e._pongWaiters.filter(function(e){return!e.statsOnly}))}e._res=n,e.getNetworkStats=function(){var t=!!e.directMode,r=t?e.directSocket:null,o=i();return{transport:t?"direct":"relay",connectionState:e.getConnectionState?e.getConnectionState():"disconnected",quality:n.quality,rtt:o.rtt,jitter:o.jitter,lastInboundAgeMs:t&&n.lastInboundAt?Math.max(0,Date.now()-n.lastInboundAt):null,bufferedAmount:r?r.bufferedAmount||0:null}},e.onNetworkQuality=function(t){return e._setHandler("networkQuality",t)},e._resConfigure=function(e){if(!1===e.liveness)n.liveness=null;else{var t=e.liveness&&"object"==typeof e.liveness?e.liveness:{},i=isFinite(t.probeAfterMs)?Math.max(1e3,t.probeAfterMs):4e3,r=isFinite(t.deadAfterMs)?t.deadAfterMs:12e3;n.liveness={probeAfterMs:i,deadAfterMs:Math.max(r,i+2e3)}}!1===e.backpressureBytes||0===e.backpressureBytes?n.backpressureBytes=0:"number"==typeof e.backpressureBytes&&e.backpressureBytes>0&&(n.backpressureBytes=e.backpressureBytes)},e._resOnOpen=function(){if(n.declaredDead=!1,n.lastCloseCode=null,n.lastInboundAt=Date.now(),n.lastProbeAt=0,n.lastWatchdogAt=Date.now(),n.livenessGraceUntil=0,o(),n.watchdogTimer=setInterval(c,1e3),function(){if("undefined"==typeof document||!document.addEventListener||n.visHandler)return;n.visHandler=function(){if("visible"===document.visibilityState&&e.directMode&&e._joined){var t=Date.now();if(n.liveness&&(n.livenessGraceUntil=t+n.liveness.deadAfterMs),n.lastWatchdogAt=t,n.lastProbeAt=0,s(),t-n.lastVisResyncAt>=2e3){n.lastVisResyncAt=t;try{e.requestSync(e._lastSequence||0)}catch(e){}}}},document.addEventListener("visibilitychange",n.visHandler)}(),!n.wrappedDisconnect){n.wrappedDisconnect=!0;var t=e.disconnect;e.disconnect=function(){return u(),t.apply(e,arguments)}}r()},e._resOnClose=function(e){n.lastCloseCode=e&&"number"==typeof e.code?e.code:null,u(),r()},e._resOnPong=function(e){e&&"number"==typeof e.sentAt&&function(e){if(e>=0){if(null==n.rtt)return n.rtt=e,void(n.jitter=0);n.jitter+=.3*(Math.abs(e-n.rtt)-n.jitter),n.rtt+=.3*(e-n.rtt)}}(Date.now()-e.sentAt),r()},e._resCanReuseToken=function(){if(4401===n.lastCloseCode)return!1;var t=e.directConfig;if(!t||!t.ws_url||!t.access_token)return!1;var i=function(e){if("number"==typeof e&&isFinite(e))return e>1e12?e:1e3*e;if("string"==typeof e&&e){var t=Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(e)?e:e+"Z");return isNaN(t)?null:t}return null}(t.expires_at);return null!=i&&i-Date.now()>3e4},e._resHoldInput=function(t){if(!n.backpressureBytes)return!1;var i=e.directSocket;return!(!i||!(null!=n.pendingInput||i.bufferedAmount>n.backpressureBytes))&&(n.pendingInput=t,n.drainTimer||(n.drainTimer=setTimeout(a,50)),!0)},e.on("disconnect",r),e.on("connectionState",r)}function L(n,i,r,o,s){return o=o||1e4,s=s||e.REQUEST_TIMEOUT,new Promise(function(c,a){let u=!1;const l=setTimeout(function(){u||(u=!0,a(new t(s,s===e.JOIN_TIMEOUT?"Join timeout":"Game request timeout")))},o);try{n.emit(i,r,function(e){u||(u=!0,clearTimeout(l),c(e||{}))})}catch(e){if(u)return;u=!0,clearTimeout(l),a(e)}})}function j(e,t){return e._joinPromise=t,t.catch(function(){e._joined=!1,e._joinPromise===t&&(e._joinPromise=null)}),t}function x(e,t,n){let i=(t-e)%n;const r=n/2;return i>r&&(i-=n),i<-r&&(i+=n),i}function B(e,t,n,i){return"deg"===i?e+x(e,t,360)*n:"rad"===i?e+x(e,t,2*Math.PI)*n:e+(t-e)*n}class V{constructor(e=120){this._items=[],this._maxSize=e}add(e){this._items.push(e),this._items.length>this._maxSize&&this._items.shift()}get size(){return this._items.length}setMaxSize(e){this._maxSize=Math.max(2,0|e)}latest(){return this._items.length?this._items[this._items.length-1]:null}prevLatest(){return this._items.length>=2?this._items[this._items.length-2]:null}clear(){this._items=[]}straddle(e){const t=this._items;if(0===t.length)return[null,null];if(1===t.length)return[t[0],t[0]];if(e<=t[0].time)return[t[0],t[0]];const n=t[t.length-1];if(e>=n.time)return[n,n];for(let n=t.length-1;n>0;n--)if(t[n-1].time<=e&&e<=t[n].time)return[t[n-1],t[n]];return[n,n]}}function H(e,t){return t?Array.isArray(e[t])?e[t]:[]:Array.isArray(e)?e:[]}class F{constructor(e={}){const t=e.serverFps||20;this._frameMs=1e3/t,this.vault=new V(e.maxSize||120),this._fixedBuffer=null!=e.bufferMs?e.bufferMs:Math.ceil(3*this._frameMs),this._bufferMs=this._fixedBuffer,this._adaptive=!!e.adaptive,this._minBuffer=null!=e.minBufferMs?e.minBufferMs:Math.ceil(2*this._frameMs),this._maxBuffer=null!=e.maxBufferMs?e.maxBufferMs:Math.ceil(8*this._frameMs),this._extrapolationMs=e.extrapolationMs||0,this._useServerTime=!!e.serverTime,this._now=e.now||(()=>Date.now()),this._lastArrival=null,this._avgInterval=this._frameMs,this._jitter=0,this._offset=null}getBufferMs(){return this._bufferMs}setBufferMs(e){this._fixedBuffer=Math.max(0,0|e),this._bufferMs=this._fixedBuffer}getJitter(){return this._jitter}add(e){if(!e)return;const t=this._now(),n=void 0!==e.state?e.state:e,i=e.time;if(null!=this._lastArrival){const e=t-this._lastArrival;if(this._avgInterval+=.1*(e-this._avgInterval),this._jitter+=.1*(Math.abs(e-this._avgInterval)-this._jitter),this._adaptive){const e=this._avgInterval+2*this._jitter;this._bufferMs=Math.max(this._minBuffer,Math.min(this._maxBuffer,e))}}if(this._lastArrival=t,this._useServerTime&&"number"==typeof i){const e=t-i;this._offset=null==this._offset?e:this._offset+.05*(e-this._offset)}const r=this._useServerTime&&"number"==typeof i?i:t;this.vault.add({time:r,state:n})}_renderTime(){return this._useServerTime&&null!=this._offset?this._now()-this._offset-this._bufferMs:this._now()-this._bufferMs}calc(e,t){const n=this._renderTime(),i=this.vault.latest();if(!i)return null;const r=String(e||"").trim().split(/\s+/).filter(Boolean).map(e=>{const t=e.match(/^(.+?)\((deg|rad)\)$/);return t?{key:t[1],type:t[2]}:{key:e,type:"linear"}});if(n>i.time)return this._extrapolationMs>0?this._extrapolate(n,r,t):H(i.state,t).map(e=>Object.assign({},e));const[o,s]=this.vault.straddle(n);if(!o||!s)return null;let c=0;return s.time!==o.time&&(c=(n-o.time)/(s.time-o.time),c=c<0?0:c>1?1:c),this._blend(H(o.state,t),H(s.state,t),c,r)}_blend(e,t,n,i){const r={};for(let t=0;t<e.length;t++)r[e[t].id]=e[t];return t.map(e=>{const t=r[e.id],o=Object.assign({},e);if(t)for(let r=0;r<i.length;r++){const{key:s,type:c}=i[r],a=t[s],u=e[s];"number"==typeof a&&"number"==typeof u&&(o[s]=B(a,u,n,c))}return o})}_extrapolate(e,t,n){const i=this.vault.latest(),r=this.vault.prevLatest(),o=H(i.state,n);if(!r||i.time<=r.time)return o.map(e=>Object.assign({},e));const s=Math.min(e-i.time,this._extrapolationMs),c=i.time-r.time,a={},u=H(r.state,n);for(let e=0;e<u.length;e++)a[u[e].id]=u[e];return o.map(e=>{const n=a[e.id],i=Object.assign({},e);if(n)for(let r=0;r<t.length;r++){const{key:o}=t[r],a=n[o],u=e[o];if("number"==typeof a&&"number"==typeof u){const e=(u-a)/c;i[o]=u+e*s}}return i})}}class G{constructor(e={}){if("function"!=typeof e.apply)throw new Error("Predictor requires an apply(state, input) function");this._apply=e.apply,this._state=void 0!==e.initialState?e.initialState:null,this._seq=0,this._pending=[],this._smoothKeys=function(e){if(!e)return null;let t=null!=e.keys?e.keys:e;return"string"==typeof t&&(t=t.trim().split(/\s+/).filter(Boolean)),Array.isArray(t)&&t.length?t:null}(e.smooth),this._smoothRate=e.smooth&&null!=e.smooth.rate?e.smooth.rate:.2,this._snapTo=e.smooth&&null!=e.smooth.snapTo?e.smooth.snapTo:.001,this._error={}}get state(){return this._state}get pending(){return this._pending.slice()}get lastSeq(){return this._seq}predict(e){this._seq+=1;const t=this._seq;return this._pending.push({seq:t,input:e}),this._state=this._apply(this._state,e),{seq:t,state:this._state}}reconcile(e,t){const n=this._state,i=null==t?-1:t;this._pending=this._pending.filter(e=>e.seq>i);let r=e;for(let e=0;e<this._pending.length;e++)r=this._apply(r,this._pending[e].input);if(this._smoothKeys&&n&&r)for(let e=0;e<this._smoothKeys.length;e++){const t=this._smoothKeys[e];"number"==typeof n[t]&&"number"==typeof r[t]&&(this._error[t]=(this._error[t]||0)+(n[t]-r[t]))}return this._state=r,this._state}view(e){if(!this._smoothKeys||!this._state||"object"!=typeof this._state)return this._state;const t=null!=e?e:this._smoothRate,n=Array.isArray(this._state)?this._state.slice():Object.assign({},this._state);for(let e=0;e<this._smoothKeys.length;e++){const i=this._smoothKeys[e];let r=this._error[i]||0;"number"==typeof n[i]&&0!==r&&(n[i]=n[i]+r),r*=1-t,Math.abs(r)<this._snapTo&&(r=0),this._error[i]=r}return n}reset(e){this._state=void 0!==e?e:null,this._seq=0,this._pending=[],this._error={}}}class W{constructor(e={}){if("function"!=typeof e.onFlush)throw new Error("Coalescer requires an onFlush(entries) callback");this._onFlush=e.onFlush,this._hz=e.hz||20,this._setInterval=e.setInterval||("undefined"!=typeof setInterval?setInterval:null),this._clearInterval=e.clearInterval||("undefined"!=typeof clearInterval?clearInterval:null),this._order=[],this._slots={},this._timer=null,!1!==e.autoStart&&this.start()}get running(){return null!==this._timer}_ensure(e,t){let n=this._slots[e];return n||(n={mode:t,value:void 0,list:[]},this._slots[e]=n,this._order.push(e)),n}queue(e,t){const n=this._ensure(e,"latest");n.mode="latest",n.value=t}append(e,t){const n=this._ensure(e,"list");n.mode="list",n.list.push(t)}drain(){const e=[];for(let t=0;t<this._order.length;t++){const n=this._order[t],i=this._slots[n];if("latest"===i.mode)void 0!==i.value&&e.push({type:n,data:i.value});else for(let t=0;t<i.list.length;t++)e.push({type:n,data:i.list[t]})}return this._order=[],this._slots={},e}flush(){if(0===this._order.length)return;const e=this.drain();e.length&&this._onFlush(e)}start(){!this._timer&&this._setInterval&&(this._timer=this._setInterval(()=>this.flush(),Math.max(1,Math.round(1e3/this._hz))))}stop(){this._timer&&this._clearInterval&&this._clearInterval(this._timer),this._timer=null}}class J{constructor(e={}){this._alpha=null!=e.alpha?e.alpha:.2,this._now=e.now||(()=>Date.now()),this._rtt=null,this._jitter=0,this._last=null,this._id=0,this._outstanding={}}get rtt(){return this._rtt}get latency(){return null==this._rtt?null:this._rtt/2}get jitter(){return this._jitter}get last(){return this._last}begin(){const e=++this._id;return this._outstanding[e]=this._now(),e}end(e){const t=this._outstanding[e];return null==t?null:(delete this._outstanding[e],this.sample(this._now()-t))}sample(e){return e>=0?(null==this._rtt?this._rtt=e:(this._jitter+=this._alpha*(Math.abs(e-this._rtt)-this._jitter),this._rtt+=this._alpha*(e-this._rtt)),this._last=e,e):null}reset(){this._rtt=null,this._jitter=0,this._last=null,this._outstanding={}}}const z=[{urls:"stun:stun.l.google.com:19302"}];function Q(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}class K{constructor(e={}){if("host"!==e.role&&"guest"!==e.role)throw new Error("MeshConnection requires role 'host' or 'guest'");if("function"!=typeof e.sendSignal)throw new Error("MeshConnection requires a sendSignal(payload) function");this.role=e.role,this._sendSignal=e.sendSignal,this._iceServers=e.iceServers||z,this._sequenced=!1!==e.sequenced,this._autoReconnect=!1!==e.autoReconnect,this._maxRestarts=null!=e.maxRestarts?e.maxRestarts:5,this._RTCPeerConnection=e.RTCPeerConnection||("undefined"!=typeof RTCPeerConnection?RTCPeerConnection:null),this._setTimeout=e.setTimeout||("undefined"!=typeof setTimeout?setTimeout:null),this.connected=!1,this._pc=null,this._unreliable=null,this._reliable=null,this._sendSeq=0,this._recvSeq=0,this._restarts=0,this.onOpen=null,this.onMessage=null,this.onClose=null,this.onError=null,this.onStateChange=null}static iceServers(e={}){const t=[{urls:e.stun||"stun:stun.l.google.com:19302"}];if(e.turn){const n={urls:e.turn};e.turnUsername&&(n.username=e.turnUsername),e.turnCredential&&(n.credential=e.turnCredential),t.push(n)}return t}async start(){if(!this._RTCPeerConnection)throw new Error("RTCPeerConnection unavailable");const e=new this._RTCPeerConnection({iceServers:this._iceServers});this._pc=e,e.onicecandidate=e=>{e&&e.candidate&&this._sendSignal({type:"ice",candidate:e.candidate})};const t=()=>this._handleStateChange(e.connectionState||e.iceConnectionState);e.onconnectionstatechange=t,e.oniceconnectionstatechange=t,"host"===this.role?(this._bindChannel(this._unreliable=e.createDataChannel("unreliable",{ordered:!1,maxRetransmits:0}),"unreliable"),this._bindChannel(this._reliable=e.createDataChannel("reliable",{ordered:!0}),"reliable"),await this._makeOffer(!1)):e.ondatachannel=e=>{const t=e.channel;"unreliable"===t.label?this._bindChannel(this._unreliable=t,"unreliable"):"reliable"===t.label&&this._bindChannel(this._reliable=t,"reliable")}}async _makeOffer(e){const t=this._pc,n=await t.createOffer(e?{iceRestart:!0}:void 0);await t.setLocalDescription(n),this._sendSignal({type:"offer",sdp:t.localDescription,restart:!!e})}_handleStateChange(e){if(this.onStateChange&&this.onStateChange(e),"connected"!==e){if(("failed"===e||"disconnected"===e||"closed"===e)&&(this.connected&&(this.connected=!1,this.onClose&&this.onClose()),this._autoReconnect&&"host"===this.role&&"closed"!==e&&this._restarts<this._maxRestarts)){this._restarts+=1;const e=Math.min(1e3*this._restarts,5e3);this._setTimeout&&this._setTimeout(()=>{this._makeOffer(!0).catch(e=>{this.onError&&this.onError(e)})},e)}}else this._restarts=0}async handleSignal(e){const t=this._pc;if(t&&e&&e.type)try{if("offer"===e.type){await t.setRemoteDescription(e.sdp);const n=await t.createAnswer();await t.setLocalDescription(n),this._sendSignal({type:"answer",sdp:t.localDescription})}else"answer"===e.type?await t.setRemoteDescription(e.sdp):"ice"===e.type&&e.candidate&&await t.addIceCandidate(e.candidate)}catch(e){this.onError&&this.onError(e)}}_bindChannel(e,t){e.binaryType="arraybuffer",e.onopen=()=>{"unreliable"!==t||this.connected||(this.connected=!0,this.onOpen&&this.onOpen())},e.onmessage=e=>{if(!this.onMessage)return;let n=e.data;if(Q(n))this.onMessage(n,t);else{try{n="string"==typeof n?JSON.parse(n):n}catch(n){return void this.onMessage(e.data,t)}if("unreliable"===t&&this._sequenced&&n&&"number"==typeof n.__s){if(n.__s<=this._recvSeq)return;return this._recvSeq=n.__s,void this.onMessage(n.m,t)}this.onMessage(n,t)}},e.onclose=()=>{this.connected&&(this.connected=!1,this.onClose&&this.onClose())},e.onerror=e=>{this.onError&&this.onError(e)}}send(e){const t=this._unreliable;return!(!t||"open"!==t.readyState)&&(Q(e)?(t.send(e),!0):(this._sequenced?(this._sendSeq+=1,t.send(JSON.stringify({__s:this._sendSeq,m:e}))):t.send("string"==typeof e?e:JSON.stringify(e)),!0))}sendReliable(e){const t=this._reliable;return!(!t||"open"!==t.readyState)&&(Q(e)?t.send(e):t.send("string"==typeof e?e:JSON.stringify(e)),!0)}close(){try{this._unreliable&&this._unreliable.close()}catch(e){}try{this._reliable&&this._reliable.close()}catch(e){}try{this._pc&&this._pc.close()}catch(e){}this._unreliable=this._reliable=this._pc=null,this.connected=!1}}class Y{constructor(e={}){if(!e.selfId)throw new Error("MeshNetwork requires a selfId");if("function"!=typeof e.sendSignal)throw new Error("MeshNetwork requires sendSignal(toPeerId, payload)");this.selfId=e.selfId,this._sendSignal=e.sendSignal,this._opts=e,this._peers={},this.onPeerOpen=null,this.onPeerClose=null,this.onMessage=null,this.onError=null}get peerIds(){return Object.keys(this._peers)}get connectedCount(){let e=0;for(const t in this._peers)this._peers[t].connected&&(e+=1);return e}peer(e){return this._peers[e]||null}_roleFor(e){return this.selfId<e?"host":"guest"}_ensurePeer(e){if(this._peers[e])return this._peers[e];const t=this,n=new K({role:this._roleFor(e),iceServers:this._opts.iceServers,RTCPeerConnection:this._opts.RTCPeerConnection,setTimeout:this._opts.setTimeout,sequenced:this._opts.sequenced,autoReconnect:this._opts.autoReconnect,sendSignal:n=>t._sendSignal(e,n)});return n.onOpen=()=>{t.onPeerOpen&&t.onPeerOpen(e)},n.onClose=()=>{t.onPeerClose&&t.onPeerClose(e)},n.onMessage=(n,i)=>{t.onMessage&&t.onMessage(e,n,i)},n.onError=n=>{t.onError&&t.onError(e,n)},this._peers[e]=n,n}async addPeer(e){if(e===this.selfId)return null;const t=this._ensurePeer(e);return await t.start(),t}async setRoster(e){const t={};for(let n=0;n<e.length;n++)e[n]!==this.selfId&&(t[e[n]]=!0);for(const e in t)this._peers[e]||await this.addPeer(e);for(const e in this._peers)t[e]||this.removePeer(e)}removePeer(e){const t=this._peers[e];if(t){try{t.close()}catch(e){}delete this._peers[e]}}async handleSignal(e,t){if(!e||e===this.selfId)return;const n=this._ensurePeer(e);n._pc||await n.start(),await n.handleSignal(t)}send(e,t){const n=this._peers[e];return!!n&&n.send(t)}sendReliable(e,t){const n=this._peers[e];return!!n&&n.sendReliable(t)}broadcast(e){for(const t in this._peers)this._peers[t].send(e)}broadcastReliable(e){for(const t in this._peers)this._peers[t].sendReliable(e)}close(){for(const e in this._peers)try{this._peers[e].close()}catch(e){}this._peers={}}}const $="undefined"!=typeof TextEncoder?new TextEncoder:null,X="undefined"!=typeof TextDecoder?new TextDecoder:null;function Z(e){return(t=e)instanceof ArrayBuffer||ArrayBuffer.isView(t)?{type:0,bytes:e instanceof Uint8Array?e:new Uint8Array(e.buffer||e)}:{type:1,bytes:(n=JSON.stringify(e),$?$.encode(n):Uint8Array.from(Buffer.from(n,"utf8")))};var t,n}function ee(e,t){if(1===e)try{return JSON.parse((n=t,X?X.decode(n):Buffer.from(n).toString("utf8")))}catch(e){return null}var n;return t}class te{constructor(){this._buf=new Uint8Array(0)}push(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Uint8Array(this._buf.length+t.length);n.set(this._buf,0),n.set(t,this._buf.length),this._buf=n;const i=[];for(;this._buf.length>=4;){const e=new DataView(this._buf.buffer,this._buf.byteOffset,4).getUint32(0,!1);if(this._buf.length<4+e)break;const t=this._buf[4],n=this._buf.subarray(5,4+e);i.push(ee(t,n.slice())),this._buf=this._buf.subarray(4+e)}return i}}class ne{constructor(e={}){if(!e.url)throw new Error("WebTransportConnection requires a url");this._url=e.url,this._opts=e,this._sequenced=!1!==e.sequenced,this._WT=e.WebTransport||("undefined"!=typeof WebTransport?WebTransport:null),this.connected=!1,this._t=null,this._dgWriter=null,this._streamWriter=null,this._deframer=new te,this._sendSeq=0,this._recvSeq=0,this.onOpen=null,this.onMessage=null,this.onClose=null,this.onError=null}async connect(){if(!this._WT)throw new Error("WebTransport unavailable in this environment");const e={};this._opts.serverCertificateHashes&&(e.serverCertificateHashes=this._opts.serverCertificateHashes);const t=new this._WT(this._url,e);if(this._t=t,t.ready&&"function"==typeof t.ready.then&&await t.ready,t.datagrams&&t.datagrams.writable&&(this._dgWriter=t.datagrams.writable.getWriter()),"function"==typeof t.createBidirectionalStream)try{const e=await t.createBidirectionalStream();this._streamWriter=e.writable.getWriter(),this._pumpReadable(e.readable,"reliable")}catch(e){}t.datagrams&&t.datagrams.readable&&this._pumpDatagrams(t.datagrams.readable),t.closed&&"function"==typeof t.closed.then&&t.closed.then(()=>this._onClosed(),()=>this._onClosed()),this.connected=!0,this.onOpen&&this.onOpen()}async _pumpDatagrams(e){try{const t=e.getReader();for(;;){const{value:e,done:n}=await t.read();if(n)break;e&&this._onDatagramBytes(e)}}catch(e){this.onError&&this.onError(e)}}async _pumpReadable(e,t){try{const n=e.getReader();for(;;){const{value:e,done:i}=await n.read();if(i)break;if(e){const n=this._deframer.push(e);for(let e=0;e<n.length;e++)this.onMessage&&this.onMessage(n[e],t)}}}catch(e){this.onError&&this.onError(e)}}_onDatagramBytes(e){const t=function(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);return t.length<5?null:{seq:new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!1),value:ee(t[4],t.subarray(5))}}(e);if(t){if(this._sequenced){if(t.seq<=this._recvSeq)return;this._recvSeq=t.seq}this.onMessage&&this.onMessage(t.value,"datagram")}}send(e){if(!this._dgWriter)return!1;this._sendSeq+=1;try{return this._dgWriter.write(function(e,t){const{type:n,bytes:i}=Z(t),r=new Uint8Array(5+i.length);return new DataView(r.buffer).setUint32(0,e>>>0,!1),r[4]=n,r.set(i,5),r}(this._sendSeq,e)),!0}catch(e){return!1}}sendReliable(e){if(!this._streamWriter)return!1;try{return this._streamWriter.write(function(e){const{type:t,bytes:n}=Z(e),i=new Uint8Array(5+n.length);return new DataView(i.buffer).setUint32(0,1+n.length,!1),i[4]=t,i.set(n,5),i}(e)),!0}catch(e){return!1}}_onClosed(){this.connected&&(this.connected=!1,this.onClose&&this.onClose())}close(){try{this._dgWriter&&this._dgWriter.releaseLock&&this._dgWriter.releaseLock()}catch(e){}try{this._t&&this._t.close()}catch(e){}this._t=this._dgWriter=this._streamWriter=null,this.connected=!1}}class ie{constructor(e={}){this._set=e.setTimeout||("undefined"!=typeof setTimeout?setTimeout:null),this._clear=e.clearTimeout||("undefined"!=typeof clearTimeout?clearTimeout:null),this._rand=e.random||Math.random,this._timers=new Set,this.set(e)}set(e={}){return null!=e.latencyMs?this.latencyMs=Math.max(0,e.latencyMs):null==this.latencyMs&&(this.latencyMs=0),null!=e.jitterMs?this.jitterMs=Math.max(0,e.jitterMs):null==this.jitterMs&&(this.jitterMs=0),null!=e.lossPct?this.lossPct=Math.max(0,Math.min(100,e.lossPct)):null==this.lossPct&&(this.lossPct=0),null!=e.dupPct?this.dupPct=Math.max(0,Math.min(100,e.dupPct)):null==this.dupPct&&(this.dupPct=0),this}_delay(){const e=this.jitterMs?(2*this._rand()-1)*this.jitterMs:0,t=this.latencyMs+e;return t>0?t:0}_schedule(e,t){if(!this._set)return void e();const n=this._set(()=>{this._timers.delete(n),e()},t);this._timers.add(n)}wrap(e){const t=this;return function(...n){if(!(t.latencyMs||t.jitterMs||t.lossPct||t.dupPct))return e.apply(this,n);if(t.lossPct&&100*t._rand()<t.lossPct)return;const i=this;t._schedule(()=>e.apply(i,n),t._delay()),t.dupPct&&100*t._rand()<t.dupPct&&t._schedule(()=>e.apply(i,n),t._delay())}}flush(){if(this._clear)for(const e of this._timers)this._clear(e);this._timers.clear()}}class re{constructor(e={}){if(!e.playerId)throw new Error("Lockstep requires playerId");if(!Array.isArray(e.players)||0===e.players.length)throw new Error("Lockstep requires players[]");if("function"!=typeof e.step)throw new Error("Lockstep requires a step(frame, inputs) function");this.playerId=e.playerId,this._players=e.players.slice(),this._step=e.step,this._send=e.send||function(){},this._inputDelay=null!=e.inputDelay?e.inputDelay:2,this._idle=null!=e.idleInput?e.idleInput:null,this._inputs={},this._frame=0,this._submitFrame=this._inputDelay,this._replay=[];for(let e=0;e<this._inputDelay;e++){this._inputs[e]={};for(let t=0;t<this._players.length;t++)this._inputs[e][this._players[t]]=this._idle}}get frame(){return this._frame}get players(){return this._players.slice()}submit(e){const t=this._submitFrame++;return this._inputs[t]||(this._inputs[t]={}),this._inputs[t][this.playerId]=e,this._send({frame:t,playerId:this.playerId,input:e}),t}receive(e){e&&null!=e.frame&&e.playerId&&(this._inputs[e.frame]||(this._inputs[e.frame]={}),this._inputs[e.frame][e.playerId]=e.input)}_ready(e){const t=this._inputs[e];if(!t)return!1;for(let e=0;e<this._players.length;e++)if(!(this._players[e]in t))return!1;return!0}tick(){let e=0;for(;this._ready(this._frame);){const t=this._inputs[this._frame];this._step(this._frame,t),this._replay.push({frame:this._frame,inputs:t}),delete this._inputs[this._frame],this._frame+=1,e+=1}return e}isStalled(){return!this._ready(this._frame)}getReplay(){return this._replay.slice()}static replay(e,t){for(let n=0;n<e.length;n++)t(e[n].frame,e[n].inputs)}}function oe(e,t,n){return e+(t-e)*n}class se{constructor(e={}){this._historyMs=e.historyMs||1e3,this._maxSize=e.maxSize||256,this._now=e.now||(()=>Date.now()),this._history=[]}record(e,t){const n=null!=t?t:this._now();this._history.push({time:n,entities:e.map(e=>Object.assign({},e))});const i=n-this._historyMs;for(;this._history.length>this._maxSize||this._history.length>2&&this._history[0].time<i;)this._history.shift()}get size(){return this._history.length}clear(){this._history=[]}rewind(e,t){const n=this._history;if(0===n.length)return{};if(e<=n[0].time)return ce(n[0].entities);if(e>=n[n.length-1].time)return ce(n[n.length-1].entities);let i=n[0],r=n[n.length-1];for(let t=n.length-1;t>0;t--)if(n[t-1].time<=e&&e<=n[t].time){i=n[t-1],r=n[t];break}const o=r.time-i.time,s=o>0?(e-i.time)/o:0,c=ce(i.entities),a={},u=ce(r.entities);for(const e in u){const n=u[e],i=c[e],r=Object.assign({},n);if(i){const e=t||Object.keys(n);for(let t=0;t<e.length;t++){const o=e[t];"number"==typeof i[o]&&"number"==typeof n[o]&&(r[o]=oe(i[o],n[o],s))}}a[e]=r}return a}rewindForClient(e,t,n){const i=null!=(n=n||{}).maxRewindMs?n.maxRewindMs:250;let r=(e||0)/2+(t||0);return r>i&&(r=i),this.rewind(this._now()-r,n.keys)}}function ce(e){const t={};for(let n=0;n<e.length;n++)t[e[n].id]=e[n];return t}const ae="_s",ue="_d",le="_a",de="_n",fe="_ka",he="_add",_e="_del",pe="_ord";function me(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ge(e){if(!Array.isArray(e)||0===e.length)return!1;for(let t=0;t<e.length;t++){const n=e[t];if(!me(n)||"string"!=typeof n.id&&"number"!=typeof n.id)return!1}return!0}function ye(e,t){if(e===t)return;const n=Array.isArray(e),i=Array.isArray(t);return n!==i||me(e)!==me(t)?{[ae]:t}:i?ge(e)&&ge(t)?function(e,t){const n={},i=[];for(let t=0;t<e.length;t++)n[e[t].id]=e[t],i.push(e[t].id);const r=[],o={};let s=!1;for(let e=0;e<t.length;e++){const i=t[e];if(r.push(i.id),Object.prototype.hasOwnProperty.call(n,i.id)){const e=ye(n[i.id],i);void 0!==e&&(o[fe]||(o[fe]={}),o[fe][i.id]=e,s=!0)}else o[he]||(o[he]=[]),o[he].push(i),s=!0}const c={};for(let e=0;e<r.length;e++)c[r[e]]=!0;for(let e=0;e<i.length;e++)c[i[e]]||(o[_e]||(o[_e]=[]),o[_e].push(i[e]),s=!0);(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0})(i,r)||(o[pe]=r,s=!0);return s?o:void 0}(e,t):function(e,t){const n={[le]:{}};let i=!1;for(let r=0;r<t.length;r++){const o=r<e.length?ye(e[r],t[r]):{[ae]:t[r]};void 0!==o&&(n[le][r]=o,i=!0)}t.length!==e.length&&(n[de]=t.length,i=!0);return i?n:void 0}(e,t):me(t)?function(e,t){const n={};let i=!1;for(const r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;const o=ye(e[r],t[r]);void 0!==o&&(n[r]=o,i=!0)}const r=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(Object.prototype.hasOwnProperty.call(t,n)||r.push(n));r.length&&(n[ue]=r,i=!0);return i?n:void 0}(e,t):{[ae]:t}}function ve(e,t){if(null==t)return e;if(Object.prototype.hasOwnProperty.call(t,ae))return t[ae];if(t[fe]||t[he]||t[_e]||t[pe])return function(e,t){const n=Array.isArray(e)?e:[],i={},r=[];for(let e=0;e<n.length;e++){const t=n[e];!t||"string"!=typeof t.id&&"number"!=typeof t.id||(i[t.id]=t,r.push(t.id))}if(t[fe])for(const e in t[fe])Object.prototype.hasOwnProperty.call(t[fe],e)&&void 0!==i[e]&&(i[e]=ve(i[e],t[fe][e]));if(t[he])for(let e=0;e<t[he].length;e++){const n=t[he][e];i[n.id]=n}const o={};if(t[_e])for(let e=0;e<t[_e].length;e++)o[t[_e][e]]=!0;if(t[pe]){const e=[];for(let n=0;n<t[pe].length;n++){const r=t[pe][n];void 0!==i[r]&&e.push(i[r])}return e}const s=[];for(let e=0;e<r.length;e++){const t=r[e];o[t]||s.push(i[t])}return s}(e,t);if(Object.prototype.hasOwnProperty.call(t,le)||Object.prototype.hasOwnProperty.call(t,de)){const n=Array.isArray(e)?e:[],i=Object.prototype.hasOwnProperty.call(t,de)?t[de]:n.length,r=n.slice(0,i),o=t[le]||{};for(const e in o)Object.prototype.hasOwnProperty.call(o,e)&&(r[e]=ve(r[e],o[e]));return r}const n=me(e)?Object.assign({},e):{},i=t[ue];for(const e in t)e!==ue&&Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=ve(n[e],t[e]));if(Array.isArray(i))for(let e=0;e<i.length;e++)delete n[i[e]];return n}function Ie(e,t=2){const n=Math.pow(10,t);return function e(t){if("number"==typeof t)return Number.isFinite(t)?Math.round(t*n)/n:t;if(Array.isArray(t))return t.map(e);if(me(t)){const n={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=e(t[i]));return n}return t}(e)}const Ee="undefined"!=typeof TextEncoder?new TextEncoder:null,we="undefined"!=typeof TextDecoder?new TextDecoder:null;function be(e,t){for(t>>>=0;t>127;)e.push(127&t|128),t>>>=7;e.push(t)}function Te(e,t){if(null==t)return void e.push(192);const n=typeof t;if("boolean"!==n)if("number"!==n){var i;if("string"===n){e.push(198);const n=Ee?Ee.encode(t):Buffer.from(t,"utf8");be(e,n.length);for(let t=0;t<n.length;t++)e.push(n[t]);return}if(Array.isArray(t)){e.push(199),be(e,t.length);for(let n=0;n<t.length;n++)Te(e,t[n])}else{if("object"===n){const n=Object.keys(t);e.push(200),be(e,n.length);for(let i=0;i<n.length;i++){const r=n[i],o=Ee?Ee.encode(r):Buffer.from(r,"utf8");be(e,o.length);for(let t=0;t<o.length;t++)e.push(o[t]);Te(e,t[r])}return}e.push(192)}}else if(Number.isInteger(t)&&t>=-2147483648&&t<=2147483647)e.push(196),be(e,((i=t)<<1^i>>31)>>>0);else{e.push(197);const n=new Uint8Array(8);new DataView(n.buffer).setFloat64(0,t,!0);for(let t=0;t<8;t++)e.push(n[t])}else e.push(t?195:194)}function Se(e){const t=[];return Te(t,e),Uint8Array.from(t)}function Ae(e){return function(e){let t=0;const n=new DataView(e.buffer,e.byteOffset,e.byteLength);function i(){let n,i=0,r=0;do{n=e[t++],r|=(127&n)<<i,i+=7}while(128&n);return r>>>0}function r(){const n=i(),r=e.subarray(t,t+n);return t+=n,we?we.decode(r):Buffer.from(r).toString("utf8")}return function o(){switch(e[t++]){case 192:default:return null;case 195:return!0;case 194:return!1;case 196:return(s=i())>>>1^-(1&s);case 197:{const e=n.getFloat64(t,!0);return t+=8,e}case 198:return r();case 199:{const e=i(),t=new Array(e);for(let n=0;n<e;n++)t[n]=o();return t}case 200:{const e=i(),t={};for(let n=0;n<e;n++)t[r()]=o();return t}}var s}}(e instanceof Uint8Array?e:new Uint8Array(e))()}function Oe(e,t){if(!("string"==typeof e&&e.length>0||"number"==typeof e&&isFinite(e)))throw new Error("interestGrid."+t+": id must be a non-empty string or a finite number");return e}function ke(e,t,n){if("number"!=typeof e||!isFinite(e))throw new Error("interestGrid."+n+": "+t+" must be a finite number");return e}function Ce(e,t){if(ke(e,"radius",t),e<0)throw new Error("interestGrid."+t+": radius must be >= 0");return e}function Ne(e){const t=null!=(e=e||{}).cellSize?e.cellSize:256;if("number"!=typeof t||!isFinite(t)||t<=0)throw new Error("createInterestGrid: cellSize must be a finite number > 0");const n=new Map,i=new Map,r=new Map;function o(e,t){let n=i.get(e);n||(n=new Set,i.set(e,n)),n.add(t)}function s(e,t){const n=i.get(e);n&&(n.delete(t),0===n.size&&i.delete(e))}function c(e,r,o,s){const c=o*o,a=Math.floor((e-o)/t),u=Math.floor((e+o)/t),l=Math.floor((r-o)/t),d=Math.floor((r+o)/t);for(let t=a;t<=u;t++)for(let o=l;o<=d;o++){const a=i.get(t+","+o);if(a)for(const t of a){const i=n.get(t);if(!i)continue;const o=i.x-e,a=i.y-r;o*o+a*a<=c&&s(t)}}}return{upsert:function(e,i,r){Oe(e,"upsert"),ke(i,"x","upsert"),ke(r,"y","upsert");const c=Math.floor(i/t)+","+Math.floor(r/t),a=n.get(e);if(a)return a.x=i,a.y=r,void(a.key!==c&&(s(a.key,e),o(c,e),a.key=c));n.set(e,{x:i,y:r,key:c}),o(c,e)},remove:function(e){Oe(e,"remove");const t=n.get(e);t&&(n.delete(e),s(t.key,e))},query:function(e,t,n){ke(e,"x","query"),ke(t,"y","query"),Ce(n,"query");const i=[];return c(e,t,n,function(e){i.push(e)}),i},observe:function(e,t,n,i){Oe(e,"observe"),ke(t,"x","observe"),ke(n,"y","observe"),Ce(i,"observe");let o=r.get(e);o||(o={prev:new Set,next:new Set},r.set(e,o));const s=o.prev,a=o.next;a.clear();const u=[],l=[],d=[];c(t,n,i,function(e){a.add(e),d.push(e),s.has(e)||u.push(e)});for(const e of s)a.has(e)||l.push(e);return o.prev=a,o.next=s,{entered:u,left:l,visible:d}},dropObserver:function(e){Oe(e,"dropObserver"),r.delete(e)},size:function(){return n.size}}}function Pe(e,t){e.diff=ye,e.patch=ve,e.quantize=Ie,e.encode=Se,e.decode=Ae,e.createInterpolation=function(e){return new F(e||{})},e.createPredictor=function(e){return new G(e||{})},e.createLagCompensator=function(e){return new se(e||{})},e.createLockstep=function(e){return new re(e||{})},e.createInterestGrid=function(e){return Ne(e||{})},e._channels=e._channels||{},e._userRealtime=e._userRealtime||null,e._inboundDispatch=null,e._dispatchRealtime=function(t){const n=t&&t.action_type;n&&e._channels[n]?e._channels[n](t&&(void 0!==t.action_data?t.action_data:t),t):e._userRealtime&&e._userRealtime(t)},e._installRealtimeRouter=function(){e._routerInstalled||(e._eventHandlers.realtime&&e._eventHandlers.realtime!==e._router&&(e._userRealtime=e._eventHandlers.realtime),e._router=function(t){(e._inboundDispatch||e._dispatchRealtime)(t)},e._eventHandlers.realtime=e._router,e._routerInstalled=!0)},e._onChannel=function(t,n){return e._channels[t]=n,e._installRealtimeRouter(),function(){delete e._channels[t]}},e.onRealtime=function(t){e._userRealtime=t,e._installRealtimeRouter()},e.createSender=function(e){const t=this,n=(e=e||{}).send||function(e,n){t.realtime(e,n)};return new W({hz:e.hz||20,autoStart:!1!==e.autoStart,onFlush:function(e){for(let t=0;t<e.length;t++)n(e[t].type,e[t].data)}})},e.createSnapshotSender=function(e){const t=this,n=(e=e||{}).channel||"state",i=!1!==e.delta,r=null!=e.keyframeEvery?e.keyframeEvery:30,o=e.precision,s=!0===e.encode?Se:"function"==typeof e.encode?e.encode:null,c=e.send||function(e,n){t.realtime(e,n)},a="function"==typeof e.source?e.source:null;let u=null,l=0,d=0,f=0;function h(e){if(null==e)return;const t=null!=o?Ie(e,o):e;let a;if(!i||null===u||f>=r)d+=1,u=null==(h=t)?h:JSON.parse(JSON.stringify(h)),l=d,f=0,a={s:d,f:t};else{const e=ye(u,t);if(void 0===e)return;d+=1,f+=1,a={s:d,b:l,d:e}}var h;c(n,s?s(a):a)}const _=e.hz||20;let p;const m=a?null:new W({hz:_,autoStart:!1!==e.autoStart,onFlush:function(e){for(let t=0;t<e.length;t++)"__snap"===e[t].type&&(p=e[t].data);h(p)}});let g=null;function y(){m?m.start():g||"undefined"==typeof setInterval||(g=setInterval(function(){h(a())},Math.max(1,Math.round(1e3/_))))}return a&&!1!==e.autoStart&&y(),{send:function(e){m?m.queue("__snap",e):h(e)},flush:function(){m?m.flush():a&&h(a())},start:y,stop:function(){m&&m.stop(),g&&(clearInterval(g),g=null)},reset:function(){u=null,l=0,d=0,f=0}}},e.createSnapshotReceiver=function(e){const t=!0===(e=e||{}).decode?Ae:"function"==typeof e.decode?e.decode:null;let n=null,i=-1,r=null,o=-1,s=0;return{receive:function(e){return t&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e=t(e)),e?void 0!==e.f?void 0!==e.s&&e.s<=o?(s+=1,r):(n=e.f,i=void 0!==e.s?e.s:0,r=e.f,o=i,r):void 0!==e.d?void 0!==e.b&&e.b!==i||void 0!==e.s&&e.s<=o?(s+=1,r):(r=ve(n,e.d),void 0!==e.s&&(o=e.s),r):r:r},get state(){return r},get stats(){return{appliedSeq:o,baseSeq:i,dropped:s}},reset:function(){n=null,i=-1,r=null,o=-1,s=0}}},e.replicate=function(e,t){t=t||{};let n=null!=e?e:{};const i=this.createSnapshotSender(Object.assign({},t,{source:function(){return n}}));return{get state(){return n},set state(e){n=e},flush:function(){i.flush()},start:function(){i.start()},stop:function(){i.stop()}}},e.replica=function(e){const t=(e=e||{}).channel||"state",n=this.createSnapshotReceiver({decode:e.decode}),i=e.interpolate?this.createInterpolation("object"==typeof e.interpolate?e.interpolate:{}):null,r="string"==typeof e.interpolate?e.interpolate:e.keys||e.interpolate&&e.interpolate.keys,o=e.group||e.interpolate&&e.interpolate.group;let s=null;const c=this._onChannel(t,function(e){const t=n.receive(e);i&&null!=t&&i.add(t),s&&s(t)});return{get state(){return n.state},view:function(){return i?i.calc(r||"x y",o):n.state},onChange:function(e){s=e},stop:function(){c()}}},e.createMesh=function(e){const t=this,n=(e=e||{}).signalChannel||"signal",i=new K(Object.assign({},e,{sendSignal:function(e){t.realtime(n,e)}}));return this._onChannel(n,function(e){e&&e.type&&i.handleSignal(e)}),i},e.createMeshNetwork=function(e){const n=this,i=(e=e||{}).signalChannel||"mesh",r=e.selfId||t.user&&t.user.getId&&t.user.getId(),o=new Y(Object.assign({},e,{selfId:r,sendSignal:function(e,t){n.realtime(i,{to:e,from:r,payload:t})}}));return this._onChannel(i,function(e){e&&e.to===r&&e.from&&o.handleSignal(e.from,e.payload)}),o},e.simulateNetwork=function(e){const t=this;return t._installRealtimeRouter(),t._realtimeRaw||"function"!=typeof t.realtime||(t._realtimeRaw=t.realtime.bind(t)),e?(t._sim?t._sim.set(e):t._sim=new ie(e),t._realtimeRaw&&(t.realtime=t._sim.wrap(t._realtimeRaw)),t._inboundDispatch=t._sim.wrap(t._dispatchRealtime),t._sim):(t._realtimeRaw&&(t.realtime=t._realtimeRaw),t._inboundDispatch=null,t._sim&&t._sim.flush(),void(t._sim=null))},e.createWebTransport=function(e){const n=(e=e||{}).url||t.config&&(t.config.webTransportUrl||t.config.wtUrl);return new ne(Object.assign({},e,{url:n}))},e.ping=function(){const e=this;if(e._pingMeter||(e._pingMeter=new J),e._pingInFlight)return e._pingInFlight;let t;if(e.directMode){if(!e.directSocket||1!==e.directSocket.readyState)return Promise.resolve(null);t=new Promise(function(t){const n=e._pingMeter.begin();let i=!1;const r=function(){i||(i=!0,t(e._pingMeter.end(n)))};r.sentAt=Date.now(),e._pongWaiters.push(r),e._sendDirect("ping",{t:Date.now()}),setTimeout(function(){if(i)return;i=!0;const o=e._pongWaiters.indexOf(r);o>=0&&e._pongWaiters.splice(o,1),delete e._pingMeter._outstanding[n],t(null)},3e3)})}else{if(!e.socket||!e.connected||e._useProxy)return Promise.resolve(null);t=new Promise(function(t){const n=Date.now();let i=!1;try{e.socket.emit("game:ping",{t:n},function(){i||(i=!0,t(e._pingMeter.sample(Date.now()-n)))})}catch(e){return void t(null)}setTimeout(function(){i||(i=!0,t(null))},3e3)})}return e._pingInFlight=t,t.then(function(){e._pingInFlight=null},function(){e._pingInFlight=null}),t},e.getRtt=function(){return this._pingMeter?this._pingMeter.rtt:null}}function Re(e,t){e.syncedState=function(e,n){var i=this,r="function"==typeof(n=n||{}).reduce?n.reduce:function(e,t){return Object.assign({},e,t.data)},o=null!=n.checkpointEvery?n.checkpointEvery:1,s="all"===n.authority?"all":"host",c=n.type||"update",a=void 0===e?{}:e,u=0,l=0,d=-1,f=0,h=new Map,_=[],p=[];function m(e){for(var n=_.slice(),i=0;i<n.length;i++)try{n[i](a,e)}catch(e){t.log("syncedState onChange error: "+e.message)}}function g(){if("all"===s)return!0;var e=i.playerId||t.user&&t.user.getId&&t.user.getId();return!(!e||!i._hostId||e!==i._hostId)}function y(){return i.directMode?Promise.resolve({success:!1,error:"not_supported_in_direct_mode"}):i.setState({__usionSyncedState:1,seq:u,state:a})}function v(e,n,i,o){if(void 0!==o){if(!Number.isSafeInteger(o)||o<=u)return!1;if(f=Math.max(f,o),o!==u+1)return h.size<1e3&&h.set(o,{playerId:e,type:n,data:i,sequence:o}),!1}var s;try{s=r(a,{playerId:e,type:n,data:i,sequence:o})}catch(e){return t.log("syncedState reduce error: "+e.message),!1}return void 0!==s&&(a=s),void 0!==o&&(u=o),!0}function I(){var e=0;for(h.forEach(function(e,t){t<=u&&h.delete(t)});h.has(u+1);){var t=h.get(u+1);if(!v(t.playerId,t.type,t.data,t.sequence))break;h.delete(t.sequence),e+=1}return e}function E(){if(!(f<=u||d===u)){d=u;try{i.requestSync(u)}catch(e){d=-1}}}function w(e){if(e){var t=!1;Number.isSafeInteger(e.sequence)&&(f=Math.max(f,e.sequence));var n=e.game_state;n&&n.__usionSyncedState&&"number"==typeof n.seq&&n.seq>=u&&void 0!==n.state&&(a=n.state,u=n.seq,t=!0);var i=e.actions;if(i&&i.length)for(var r=i.slice().sort(function(e,t){return(e.sequence||0)-(t.sequence||0)}),o=0;o<r.length;o++){var s=r[o];s&&v(s.player_id,s.action_type,s.action_data,s.sequence)&&(t=!0)}I()&&(t=!0),t&&m("recover"),E()}}return p.push(i.on("action",function(e){if(e){var t=v(e.player_id,e.action_type,e.action_data,e.sequence)?1:0;(t+=I())&&(m("action"),function(e){o>0&&g()&&(l+=e)>=o&&(l=0,y())}(t)),E()}})),p.push(i.on("sync",w)),p.push(i.on("joined",w)),{get:function(){return a},commit:function(e,t,n){var r,o,s;return"string"==typeof e?(r=e,o=t,s=n):(r=c,o=e,s=t),i.directMode?(v(i.playerId,r,o,void 0)&&m("action"),i.action(r,o,s)):i.action(r,o,s)},onChange:function(e){return _.push(e),function(){var t=_.indexOf(e);t>=0&&_.splice(t,1)}},isAuthority:g,checkpoint:function(){return y()},getSequence:function(){return u},destroy:function(){for(var e=0;e<p.length;e++)try{p[e]()}catch(e){}p.length=0,_.length=0,h.clear()}}}}const Me="__usion_players_v1",qe=e=>["direct","turn","webrtc"].includes(e),De=()=>globalThis.crypto.randomUUID(),Ue=e=>"string"==typeof e&&e.length>0&&e.length<=128;class Le{constructor(e,t,n={}){this.game=e,this.usion=t,this.options=n,this.selfId=t.user.getId(),this.roomId=null,this.closed=!1,this.online=!1,this.session=De(),this.peers=new Map,this.roster=new Set,this.listeners={message:new Set,status:new Set,log:new Set},this.logs=[],this.sequence=0,this.generation=0,this.lastHello=0,this.RTC=void 0===n.RTCPeerConnection?globalThis.RTCPeerConnection:n.RTCPeerConnection,this.iceServers=n.iceServers||[{urls:"stun:stun.l.google.com:19302"}],this.timeout=n.directTimeoutMs??6e3,this.unsubscribers=[e._onChannel(Me,(e,t)=>this._incoming(e,t)),e.on("joined",e=>this._joined(e)),e.on("playerJoined",e=>this._roster(e)),e.on("playerLeft",e=>this._roster(e,!0)),e.on("sync",e=>this._roster(e)),e.on("roomAssigned",({roomId:e})=>{this._join(e).catch(()=>this._log("join_failed"))}),e.on("disconnect",()=>this._offline()),e.on("reconnect",()=>this._recover()),e.on("reconnected",()=>this._recover())],this.tick=setInterval(()=>this._tick(),1e3)}async start(){const e=this.options.roomId||this.game.roomId||this.usion.config.roomId;return e&&await this._join(e),this}_emit(e,t){for(const n of this.listeners[e])try{n(t)}catch{}}_listen(e,t){return this.listeners[e].add(t),()=>this.listeners[e].delete(t)}onMessage(e){return this._listen("message",e)}onStatusChange(e){return this._listen("status",e)}onLog(e){return this._listen("log",e)}getLogs(){return this.logs.map(e=>({...e}))}_log(e,t=void 0,n=void 0){const i={time:Date.now(),event:e,peerId:t,reason:n};this.logs.push(i),this.logs.length>100&&this.logs.shift(),this._emit("log",{...i})}getStatus(){return{roomId:this.roomId,state:this.closed?"closed":this.roomId?this.online?"connected":"offline":"waiting",peers:[...this.peers.values()].map(e=>({playerId:e.id,transport:this.online?e.mode:"offline",rttMs:e.rtt,sent:e.sent,received:e.received}))}}_status(){this._emit("status",this.getStatus())}_mode(e,t,n){e.mode=t,e.rtt=null,this._log("transport",e.id,n),this._status()}async _join(e){if(this.closed)return;const t=++this.generation;if(this.roomId!==e&&(this._clearPeers(),this.roster.clear(),this.session=De(),this.roomId=e),this.online=!1,await this.game.connect(),this.closed||t!==this.generation)return;const n=await this.game.join(e);this.closed||t!==this.generation||this._joined(n||{})}_joined(e){if(this.closed)return;(e.room_id||this.game.roomId)===this.roomId&&(this.online=!0,this._roster(e),this._hello(),this._status())}_recover(){this.closed||this.online||!this.roomId||this._join(this.roomId).catch(()=>this._log("rejoin_failed"))}_offline(){this.closed||(this.generation++,this.online=!1,this.session=De(),this._clearPeers(),this._log("offline"),this._status())}_roster(e,t=!1){if(!(this.closed||!e||e.room_id&&e.room_id!==this.roomId)){Array.isArray(e.player_ids)?this.roster=new Set(e.player_ids.filter(Ue)):Ue(e.player_id)&&(t?this.roster.delete(e.player_id):this.roster.add(e.player_id));for(const[n,i]of this.peers)(!this.roster.has(n)||t&&n===e.player_id)&&(this._closeRTC(i),this.peers.delete(n),this._log("peer_left",n));this._hello(),this._status()}}_relay(e,t){if(!this.online||this.closed)return!1;try{return this.game.realtime(Me,{...e,v:1,room:this.roomId,session:this.session,to:t}),!0}catch{return this._log("relay_send_failed",t),!1}}_hello(e=void 0){this._relay({kind:"hello"},e)}_peer(e,t){let n=this.peers.get(e);if(n&&n.session!==t&&(this._closeRTC(n),this.peers.delete(e),n=null),!n){if(this.peers.size>=7)return this._log("peer_limit",e),null;n={id:e,session:t,mode:"relay",pc:null,dc:null,attempt:null,candidates:[],queue:Promise.resolve(),lastDirect:0,lastSequence:-1,rtt:null,sent:0,received:0,started:!1,pendingPing:null},this.peers.set(e,n),this._log("peer_joined",e),this._status()}return n}_incoming(e,t){const n=t?.player_id;if(this.closed||!this.online||!e||1!==e.v||e.room!==this.roomId||t.room_id!==this.roomId||!Ue(n)||n===this.selfId||!this.roster.has(n)||!Ue(e.session)||e.to&&e.to!==this.selfId)return;if("hello"===e.kind){const t=this.peers.get(n)?.session===e.session,i=this._peer(n,e.session);if(!i)return;return t||this._hello(n),void(this.selfId<n&&!i.started&&this._attempt(i))}const i=this.peers.get(n);if(i&&i.session===e.session&&e.target===this.session)if("offer"===e.kind&&this.selfId>n&&Ue(e.attempt)){if(i.attempt===e.attempt)return;this._setup(i,e.attempt),i.pc&&this._signal(i,e)}else["answer","ice"].includes(e.kind)&&e.attempt===i.attempt?this._signal(i,e):"fallback"===e.kind&&e.attempt===i.attempt?this._fallback(i,"peer_requested",!1):"retry"===e.kind&&this.selfId<n?this._attempt(i):"data"===e.kind&&this._receive(i,e,"relay")}_control(e,t){return this._relay({...t,target:e.session,attempt:e.attempt},e.id)}_setup(e,t){if(this._closeRTC(e),e.attempt=t,e.started=!0,this.RTC&&!1!==this.options.direct){this._mode(e,"connecting","direct_attempt");try{const t=e.pc=new this.RTC({iceServers:this.iceServers});e.localCandidates=[],e.descriptionSent=!1,t.onicecandidate=n=>{if(e.pc!==t||!n.candidate)return;const i=n.candidate.toJSON();e.descriptionSent?this._control(e,{kind:"ice",candidate:i}):e.localCandidates.length<64&&e.localCandidates.push(i)},t.ondatachannel=n=>{e.pc===t&&this._channel(e,t,n.channel)},t.onconnectionstatechange=()=>{e.pc===t&&["failed","disconnected","closed"].includes(t.connectionState)&&this._fallback(e,t.connectionState)},e.timer=setTimeout(()=>{e.pc===t&&this._fallback(e,"direct_timeout")},this.timeout)}catch{this._fallback(e,"rtc_setup_failed")}}else this._fallback(e,"direct_unavailable")}_attempt(e){this._setup(e,De());const t=e.pc;if(t){try{this._channel(e,t,t.createDataChannel("usion-game",{ordered:!1,maxRetransmits:0}))}catch{return void this._fallback(e,"channel_failed")}e.queue=(async()=>{const n=await t.createOffer();e.pc===t&&(await t.setLocalDescription(n),e.pc===t&&this._description(e,"offer"))})().catch(()=>{e.pc===t&&this._fallback(e,"offer_failed")})}}_signal(e,t){const n=e.pc;n&&(e.queue=e.queue.then(async()=>{if(e.pc===n)if("ice"===t.kind)n.remoteDescription?await n.addIceCandidate(t.candidate):e.candidates.length<64&&e.candidates.push(t.candidate);else{if(await n.setRemoteDescription(t.description),e.pc!==n)return;const i=e.candidates;e.candidates=[];for(const e of i)await n.addIceCandidate(e);"offer"===t.kind&&(await n.setLocalDescription(await n.createAnswer()),e.pc===n&&this._description(e,"answer"))}}).catch(()=>{e.pc===n&&this._fallback(e,"negotiation_failed")}))}_description(e,t){this._control(e,{kind:t,description:e.pc.localDescription.toJSON()}),e.descriptionSent=!0;for(const t of e.localCandidates)this._control(e,{kind:"ice",candidate:t});e.localCandidates=[]}_channel(e,t,n){e.dc=n,n.onopen=()=>{e.pc===t&&(clearTimeout(e.timer),e.lastDirect=Date.now(),this._mode(e,"webrtc","channel_open"),this._inspectRoute(e,t))},n.onmessage=n=>{if(!(e.pc!==t||"string"!=typeof n.data||n.data.length>16384))try{this._receive(e,JSON.parse(n.data),"direct")}catch{}},n.onerror=n.onclose=()=>{e.pc===t&&this._fallback(e,"channel_closed")}}async _inspectRoute(e,t){if(t?.getStats)try{const n=await t.getStats();if(e.pc!==t||!qe(e.mode))return;let i;if(n.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&(i=n.get(e.selectedCandidatePairId))}),i||n.forEach(e=>{"candidate-pair"===e.type&&e.nominated&&"succeeded"===e.state&&(i=e)}),!i)return;const r=n.get(i.localCandidateId),o=n.get(i.remoteCandidateId);if(!r?.candidateType||!o?.candidateType)return;const s="relay"===r.candidateType||"relay"===o.candidateType?"turn":"direct";s!==e.mode&&this._mode(e,s,"ice_route_selected")}catch{}}_closeRTC(e){clearTimeout(e.timer);const t=e.pc,n=e.dc;e.pc=e.dc=null,e.candidates=[],e.queue=Promise.resolve(),n&&(n.onopen=n.onmessage=n.onerror=n.onclose=null,n.close()),t&&(t.onicecandidate=t.ondatachannel=t.onconnectionstatechange=null,t.close())}_fallback(e,t,n=!0){n&&this._control(e,{kind:"fallback"}),this._closeRTC(e),this._mode(e,"relay",t)}_packet(e,t){const n={...t,kind:"data",room:this.roomId,session:this.session,target:e.session};if(qe(e.mode)&&"open"===e.dc?.readyState)try{if(e.dc.bufferedAmount>65536)throw Error("backpressure");return e.dc.send(JSON.stringify(n)),!0}catch{this._fallback(e,"send_failed")}return this._control(e,n)}_receive(e,t,n){t.room===this.roomId&&t.session===e.session&&t.target===this.session&&("direct"===n&&(e.lastDirect=Date.now()),Number.isSafeInteger(t.ping)&&t.ping>0?this._packet(e,{pong:t.ping}):Number.isSafeInteger(t.pong)&&t.pong>0?t.pong===e.pendingPing&&(e.rtt=Date.now()-t.pong,e.pendingPing=null,this._status()):!Number.isSafeInteger(t.seq)||t.seq<=e.lastSequence||(e.lastSequence=t.seq,e.received++,this._emit("message",{data:t.data,playerId:e.id,transport:"direct"===n?qe(e.mode)?e.mode:"webrtc":n})))}send(e,t){if(this.closed||!this.online)return!1;const n=JSON.stringify(e);if(void 0===n||(new TextEncoder).encode(n).length>4096)throw new Error("connectPlayers messages must be JSON, at most 4096 bytes");const i=JSON.parse(n),r=++this.sequence,o=t?[this.peers.get(t)].filter(Boolean):[...this.peers.values()];let s=o.length>0;for(const e of o){const t=this._packet(e,{data:i,seq:r});t&&e.sent++,s=s&&t}return s}forceRelay(e){for(const t of this.peers.values())e&&t.id!==e||this._fallback(t,"forced")}retryDirect(e){if(this.online&&!this.closed)for(const t of this.peers.values())e&&t.id!==e||(this.selfId<t.id?this._attempt(t):this._control(t,{kind:"retry"}))}async invite(){return this.game.invite()}_tick(){if(!this.online||this.closed)return;const e=Date.now();e-this.lastHello>=3e3&&(this.lastHello=e,this._hello());for(const t of this.peers.values())qe(t.mode)&&e-(t.lastStats||0)>1e4&&(t.lastStats=e,this._inspectRoute(t,t.pc)),qe(t.mode)&&e-t.lastDirect>3e3&&this._fallback(t,"direct_unresponsive"),t.pendingPing=e,this._packet(t,{ping:e})}_clearPeers(){for(const e of this.peers.values())this._closeRTC(e);this.peers.clear()}close(){if(!this.closed){this.closed=!0,this.generation++,clearInterval(this.tick),this._clearPeers(),this.unsubscribers.forEach(e=>e()),this._status();for(const e of Object.values(this.listeners))e.clear()}}}const je={joined:"joined",player_joined:"playerJoined",player_left:"playerLeft",player_connection:"playerConnection",state:"stateUpdate",state_update:"stateUpdate",sync:"sync",action:"action",realtime:"realtime",finished:"finished",restarted:"restarted",error:"error",rematch_request:"rematchRequest",disconnect:"disconnect",reconnect:"reconnect",connection_error:"connectionError",room_assigned:"roomAssigned",connection_state:"connectionState",reconnected:"reconnected",network_quality:"networkQuality"};const xe={SnapshotInterpolation:F,Vault:V,Predictor:G,Coalescer:W,PingMeter:J,MeshConnection:K,MeshNetwork:Y,WebTransportConnection:ne,NetworkSim:ie,Lockstep:re,LagCompensator:se,diff:ye,patch:ve,quantize:Ie,encode:Se,decode:Ae,createInterestGrid:Ne},Be=Object.assign({},m);var Ve;return Be.user=function(n){const i=new Set;let r={status:"loading",userId:null};return{_applyAuth:function(e,t){e={...e};const o=r,s=t=>Object.prototype.hasOwnProperty.call(e,t),c=e.authState,a=s("userId")||!!c,u=s("userId")?e.userId:c?c.userId:this.getId(),l="string"==typeof u&&u&&0!==u.indexOf("guest_")?u:null;if(a){const e=c&&"loading"===c.status?"loading":c&&"guest"===c.status?"guest":l?"authenticated":"guest";r={status:e,userId:"authenticated"===e?l:null};(o.status!==r.status||o.userId!==r.userId)&&"loading"!==o.status&&(this._name=this._avatar=this._token=this._isAdult=null,n.config.userName=n.config.userAvatar=n.config.authToken=n.config.userIsAdult=null),this._id="string"==typeof u?u:null,n.config.userId=this._id}if(s("userName")&&(this._name=n.config.userName=e.userName||null),s("userAvatar")&&(this._avatar=n.config.userAvatar=e.userAvatar||null),s("userIsAdult")&&(this._isAdult=n.config.userIsAdult="boolean"==typeof e.userIsAdult?e.userIsAdult:null),t||s("authToken")||a&&"authenticated"!==r.status){const t=s("userId")&&"string"==typeof e.userId&&0===e.userId.indexOf("guest_");this._token=n.config.authToken="authenticated"!==r.status&&!t||"string"!=typeof e.authToken?null:e.authToken}n.config.authState={...r},o.status===r.status&&o.userId===r.userId||("loading"!==o.status&&(n._invalidateAuthRequests&&n._invalidateAuthRequests(),n._results=[],n.config.sessionId=null,n.config.sessionData={},n.config.results=[],n.config.balance=null,n.session&&(n.session._id=null,n.session._data={}),n.wallet&&(n.wallet._balance=null)),i.forEach(function(e){try{e({...r})}catch(e){console.error("[Usion] auth listener error:",e)}}))},getAuthState:function(){return{...r}},onAuthChange:function(e){return"function"!=typeof e?function(){}:(i.add(e),function(){i.delete(e)})},requestLogin:function(i){if(!n.config.hostFeatures?.auth)return Promise.reject(new t(e.UNSUPPORTED,"Login requires a newer Usion host"));const r=i&&i.returnPath;return null!=r&&("string"!=typeof r||!r.startsWith("/")||r.startsWith("//")||/[\\\s\x00-\x1f]/.test(r)||r.length>2048)?Promise.reject(new t(e.INVALID_INPUT,"returnPath must be a safe relative app path")):n._request("REQUEST_LOGIN",null==r?{}:{returnPath:r})},_id:null,_name:null,_avatar:null,_token:null,_isAdult:null,getId:function(){return this._id||n.config.userId||null},getName:function(){return this._name||n.config.userName||null},getAvatar:function(){return this._avatar||n.config.userAvatar||null},isAdult:function(){if(!0===this._isAdult||!1===this._isAdult)return this._isAdult;var e=n.config&&n.config.userIsAdult;return!0===e||!1===e?e:null},getToken:function(){return this._token||n.config.authToken||null},getProfile:function(){return n._request("GET_USER_PROFILE",{}).then(function(e){return e.profile||{id:n.user.getId(),name:n.user.getName(),avatar:n.user.getAvatar(),isAdult:n.user.isAdult()}})},openProfile:function(e){"string"==typeof e&&e&&0!==e.indexOf("guest_")&&n._post({type:"OPEN_USER_PROFILE",userId:e})}}}(Be),Be.storage=function(e){var t=null;function n(){return t||(t=I(e,"kv:get",{key:y}).then(function(t){if(!t||!t.exists||!0!==t.value)return Promise.all([I(e,"kv:keys",{}),T(e)]).then(function(t){var n=new Set(t[0]&&t[0].keys||[]);return Promise.all(t[1].map(function(t){var i=v(t);if(!n.has(i))return E(e,t).then(function(t){if(null!=t)return I(e,"kv:set",{key:i,value:t})})}))}).then(function(){return I(e,"kv:set",{key:y,value:!0})})}).catch(function(e){throw t=null,e}))}return{get:function(t){return n().then(function(){return I(e,"kv:get",{key:v(t)})}).then(function(n){return n&&n.exists?S(w(e,t,n.value)).then(function(){return n.value}):S(b(e,t)).then(function(){return null})}).catch(function(n){return E(e,t).then(function(e){if(null!=e)return e;throw n},function(){throw n})})},set:function(t,i){return n().then(function(){return I(e,"kv:set",{key:v(t),value:i})}).then(function(){return S(w(e,t,i))})},remove:function(t){return n().then(function(){return I(e,"kv:remove",{key:v(t)})}).then(function(){return S(b(e,t))})},clear:function(){return n().then(function(){return I(e,"kv:clear",{prefix:g})}).then(function(){return S(e._request("STORAGE_CLEAR",{}))})},keys:function(){return n().then(function(){return I(e,"kv:keys",{})}).then(function(e){return(e&&e.keys||[]).filter(function(e){return 0===e.indexOf(g)}).map(function(e){return e.slice(3)})}).catch(function(t){return T(e).catch(function(){throw t})})}}}(Be),Be.wallet=function(e){return{_balance:null,_balanceChangeHandler:null,_paymentTimeoutMs:6e4,_recoveryPollMs:2e3,_recoveryMaxPolls:10,_recoveryQueryTimeoutMs:8e3,getBalance:function(t){const n=this;return!(!t||!t.fresh)||null===n._balance?e._request("GET_BALANCE",{}).then(function(e){return n._balance=e.balance,e.balance}):Promise.resolve(n._balance)},hasCredits:function(e){return this.getBalance().then(function(t){return t>=e})},requestPayment:function(t,n,i){const r=this,o=i&&"object"==typeof i?i:null,s=o&&"string"==typeof o.idempotencyKey&&o.idempotencyKey?o.idempotencyKey:null;return new Promise(function(o,c){const a=f(),u=r._paymentTimeoutMs||6e4;let l=!1,d=null;function h(){clearTimeout(y),d&&clearTimeout(d),window.removeEventListener("message",g)}function _(e){l||(l=!0,h(),e&&void 0!==e.newBalance?r._balance=e.newBalance:(null!==r._balance&&(r._balance-=t),r.getBalance({fresh:!0}).catch(function(){})),o(e))}function m(e){l||(l=!0,h(),c(e))}function g(e){if(!p(e))return;let t;try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}t&&t._requestId===a&&("PAYMENT_SUCCESS"===t.type?_(t):"PAYMENT_FAILED"===t.type&&m(new Error(t.reason||"Payment failed")))}window.addEventListener("message",g);const y=setTimeout(function(){const t=r._recoveryPollMs||2e3,n=r._recoveryMaxPolls||10,i=r._recoveryQueryTimeoutMs||8e3;let o=0,c=0;!function r(){l||e._request("PAYMENT_RESULT_QUERY",{paymentRequestId:a,idempotencyKey:s||void 0},i).then(function(e){if(l)return;const n=e&&e.status;if("succeeded"!==n)if("failed"!==n){if("pending"===n)return o=0,c=0,void(d=setTimeout(r,t));c=0,o+=1,o>=2?m(new Error("Payment confirmation timeout")):d=setTimeout(r,t)}else m(new Error(e.reason||"Payment failed"));else _({type:"PAYMENT_SUCCESS",_requestId:a,newBalance:e.newBalance,transactionId:e.transactionId,receiptToken:e.receiptToken})}).catch(function(){l||(c+=1,c>=n?m(new Error("Payment confirmation timeout")):d=setTimeout(r,t))})}()},u);e._post({type:"PAYMENT_REQUEST",_requestId:a,amount:t,reason:n,data:i,idempotencyKey:s||void 0})})},onBalanceChange:function(e){const t=this;return t._balanceChangeHandler=e,function(){t._balanceChangeHandler===e&&(t._balanceChangeHandler=null)}}}}(Be),Be.session=function(e){return{_id:null,_data:{},getId:function(){return this._id||e.config.sessionId||null},getData:function(e){return e?this._data[e]:this._data},setData:function(t,n){"object"==typeof t?Object.assign(this._data,t):this._data[t]=n,e._post({type:"SESSION_DATA_UPDATE",data:this._data})},clear:function(){this._data={},e._post({type:"SESSION_DATA_CLEAR"})}}}(Be),Be.chat=function(e){return{sendMessage:function(t,n){return e._request("SEND_MESSAGE_REQUEST",{recipientId:t,message:n})},createPersonalChat:function(t){return e._request("CREATE_PERSONAL_CHAT",{peerUserId:t})}}}(Be),Be.bot=function(e){return{_messageHandler:null,callAction:function(t,n){return e._request("CALL_BOT",{action:t,data:n||{}},3e4)},sendMessage:function(t){e._post({type:"SEND_USER_MESSAGE",text:t})},updateContext:function(t){e._post({type:"UPDATE_CONTEXT",context:t})},close:function(t){e._post({type:"CLOSE",result:t})},onMessage:function(e){this._messageHandler=e}}}(Be),Be.fileStorage=(Ve=Be,{set:function(e,t,n){return Ve._request("FILE_STORAGE_SET",{key:e,base64Data:t,mimeType:n||"application/octet-stream"},3e4).then(function(){})},get:function(e){return Ve._request("FILE_STORAGE_GET",{key:e},3e4).then(function(e){return e&&e.base64Data?{base64Data:e.base64Data,mimeType:e.mimeType}:null})},remove:function(e){return Ve._request("FILE_STORAGE_REMOVE",{key:e}).then(function(){})}}),Be.game=function(n){const r={socket:null,directSocket:null,roomId:null,playerId:null,connected:!1,directMode:!1,directConfig:null,_directSeq:0,_eventHandlers:{},_lastSequence:0,_connecting:!1,_connectPromise:null,_joined:!1,_joinPromise:null,_useProxy:!1,_proxyListenerSetup:!1,_heartbeatInterval:null,_pingMeter:null,_pongWaiters:[],_lastActionApplied:0,_rejoinPromise:null,connect:function(e,t){const i=this;return"direct"===(n.config&&n.config.connectionMode||"platform")?i.connectDirect():i._useProxy&&i.connected||i.socket&&i.connected?Promise.resolve():i._connecting&&i._connectPromise?i._connectPromise:window.__USION_PROXY__||window.parent!==window||window.ReactNativeWebView||n._isEmbedded?(n.log("Running in iframe – using parent app as socket proxy"),i._connectViaProxy()):(e=e||n.config.socketUrl,t=t||n.user.getToken(),e?t?(i._connecting=!0,i._connectPromise=new Promise(function(n,r){if("undefined"==typeof io){var o=["/socket.io.min.js","https://usions.com/socket.io.min.js","https://cdn.socket.io/4.7.2/socket.io.min.js"];!function s(c){if(c>=o.length)return i._connecting=!1,void r(new Error("Failed to load Socket.IO client"));var a=document.createElement("script");a.src=o[c],a.onload=function(){i._initSocket(e,t,n,r)},a.onerror=function(){s(c+1)},document.head.appendChild(a)}(0)}else i._initSocket(e,t,n,r)}),i._connectPromise):Promise.reject(new Error("No auth token available")):Promise.reject(new Error("No socket URL provided")))},onJoined:function(e){return this._setHandler("joined",e)},onPlayerJoined:function(e){return this._setHandler("playerJoined",e)},onPlayerLeft:function(e){return this._setHandler("playerLeft",e)},onStateUpdate:function(e){return this._setHandler("stateUpdate",e)},onSync:function(e){return this._setHandler("sync",e)},onAction:function(e){return this._setHandler("action",e)},onRealtime:function(e){return this._setHandler("realtime",e)},onGameFinished:function(e){return this._setHandler("finished",e)},onGameRestarted:function(e){return this._setHandler("restarted",e)},onError:function(e){return this._setHandler("error",e)},onRematchRequest:function(e){return this._setHandler("rematchRequest",e)},onDisconnect:function(e){return this._setHandler("disconnect",e)},onReconnect:function(e){return this._setHandler("reconnect",e)},onConnectionError:function(e){return this._setHandler("connectionError",e)},onPlayerConnection:function(e){return this._setHandler("playerConnection",e)},onRoomAssigned:function(e){return this._setHandler("roomAssigned",e)},_setHandler:function(e,t){const n=this;return n._eventHandlers[e]=t,function(){n._eventHandlers[e]===t&&(n._eventHandlers[e]=null)}},_dispatch:function(e){const t=Array.prototype.slice.call(arguments,1),i=this._eventHandlers[e];if(i)try{i.apply(null,t)}catch(t){n.log("game handler error ("+e+"): "+t.message)}const r=this._listeners[e];if(r&&r.length){const i=r.slice();for(let r=0;r<i.length;r++)try{i[r].apply(null,t)}catch(t){n.log("game listener error ("+e+"): "+t.message)}}},on:function(e,t){const n=this,i=function(e){let t=String(e||"");if(0===t.indexOf("game:")&&(t=t.slice(5)),je[t])return je[t];const n=t.replace(/([A-Z])/g,function(e){return"_"+e.toLowerCase()});return je[n]||t}(e);return n._listeners[i]||(n._listeners[i]=[]),n._listeners[i].push(t),function(){const e=n._listeners[i];if(!e)return;const r=e.indexOf(t);r>=0&&e.splice(r,1)}},_listeners:{}};return function(e,t){e.connectDirect=function(e){var n=this;return e=e||{},n.directMode&&n.directSocket&&n.connected?Promise.resolve():(n._connecting&&n._connectPromise||(n._resConfigure&&n._resConfigure(e),n._connecting=!0,n.directMode=!0,n._autoReconnect=void 0!==e.autoReconnect?e.autoReconnect:!(t.config&&!1===t.config.autoReconnect),n._connectPromise=n._fetchDirectAccess(e).then(function(e){return n.directConfig=e,n._initDirectSocket(e)}).then(function(){n.connected=!0,n._connecting=!1,t.log("Direct game socket connected")}).catch(function(e){throw n._connecting=!1,n.connected=!1,n.directMode=!1,n._dispatch("connectionError",e),e})),n._connectPromise)},e._fetchDirectAccess=function(e){var n=e.roomId||this.roomId||t.config.roomId,i=e.serviceId||t.config.serviceId,r=e.apiUrl||t.config.apiUrl||"",o=e.token||t.user.getToken();if(!n)return Promise.reject(new Error("No room ID provided"));if(!i)return Promise.reject(new Error("No service ID provided"));if(this.roomId=n,this.playerId=t.user.getId(),t._isEmbedded)return t._request("GAME_ACCESS_REQUEST",{room_id:n,service_id:i,protocol_version:e.protocolVersion||t.config.protocolVersion||t.config.protocol_version||"2"},1e4);if(!r)return Promise.reject(new Error("No API URL provided"));if(!o)return Promise.reject(new Error("No auth token available"));var s=String(r).replace(/\/$/,"")+"/games/rooms/"+encodeURIComponent(n)+"/access";return fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o},body:JSON.stringify({service_id:i,client_type:"iframe",protocol_version:e.protocolVersion||t.config.protocolVersion||t.config.protocol_version||"2"})}).then(function(e){return e.ok?e.json():e.text().then(function(t){throw new Error(t||"Direct access failed: HTTP "+e.status)})})},e._initDirectSocket=function(e){var t=this;return new Promise(function(n,i){if(e&&e.ws_url&&e.access_token){var r=e.ws_url,o=-1===r.indexOf("?")?"?":"&",s=r+o+"token="+encodeURIComponent(e.access_token),c=new WebSocket(s);t.directSocket=c;var a=!1,u=!1,l=setTimeout(function(){if(!a){try{c.close()}catch(e){}i(new Error("Direct WebSocket connection timeout"))}},1e4);c.onopen=function(){a=!0,clearTimeout(l),u||(u=!0,t._sendDirect("join",{})),t._heartbeatInterval&&clearInterval(t._heartbeatInterval),t._heartbeatInterval=setInterval(function(){t.directSocket&&t.directSocket.readyState===WebSocket.OPEN&&t._sendDirect("heartbeat",{})},25e3),t._resOnOpen&&t._resOnOpen(),n()},c.onerror=function(){a||(clearTimeout(l),i(new Error("Direct WebSocket connection error")))},c.onclose=function(e){t._resOnClose&&t._resOnClose(e),t.connected=!1,t._joined=!1,t._joinPromise=null,t._heartbeatInterval&&(clearInterval(t._heartbeatInterval),t._heartbeatInterval=null),t._dispatch("disconnect",e&&e.reason?e.reason:"direct socket closed"),t.directMode&&!1!==t._autoReconnect&&t._scheduleDirectReconnect()},c.onmessage=function(e){t._res&&(t._res.lastInboundAt=Date.now()),t._handleDirectMessage(e&&e.data)}}else i(new Error("Invalid direct access payload"))})},e._scheduleDirectReconnect=function(){var e=this;if(!e._reconnecting){e._reconnecting=!0;var t=e._reconnectAttempt||0,n=function(){e.directMode?(t+=1,e._reconnectAttempt=t,(e._resCanReuseToken&&e._resCanReuseToken()?Promise.resolve(e.directConfig):e._fetchDirectAccess({})).then(function(t){return e.directConfig=t,e._initDirectSocket(t)}).then(function(){e.connected=!0,e._reconnecting=!1,e._reconnectAttempt=0,e._dispatch("reconnect",t),e.roomId&&e.requestSync(e._lastSequence||0)}).catch(function(){if(e.directMode){var i=Math.min(1e3*Math.pow(2,t-1),15e3);setTimeout(n,i)}else e._reconnecting=!1})):e._reconnecting=!1};setTimeout(n,100)}},e._sendDirect=function(e,t){this.directSocket&&this.directSocket.readyState===WebSocket.OPEN&&("input"===e&&this._resHoldInput&&this._resHoldInput(t)||(this._directSeq=this._directSeq+1,this.directSocket.send(JSON.stringify({type:e,room_id:this.roomId,ts:Date.now(),seq:this._directSeq,session_id:this.directConfig&&this.directConfig.session_id?this.directConfig.session_id:null,protocol_version:this.directConfig&&this.directConfig.protocol_version?this.directConfig.protocol_version:"2",payload:t||{}}))))},e._handleDirectMessage=function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return}if(t&&t.type){var n=t.payload||{};if("joined"===t.type)return this._joined=!0,void this._dispatch("joined",n);if("player_joined"!==t.type)if("player_left"!==t.type){if("state_snapshot"===t.type||"state_delta"===t.type)return this._dispatch("realtime",n),void this._dispatch("stateUpdate",n);if("pong"===t.type){var i=this._pongWaiters&&this._pongWaiters.length?this._pongWaiters.shift():null;return this._resOnPong&&this._resOnPong(i),i&&i(),void this._dispatch("sync",n)}"match_end"!==t.type?"error"===t.type&&this._dispatch("error",n):this._dispatch("finished",n)}else this._dispatch("playerLeft",n);else this._dispatch("playerJoined",n)}}}(r,n),U(r,n),function(e,t){e._initSocket=function(e,n,i,r){const o=this;if(o.socket&&o.socket.connected)return o._connecting=!1,void i();o.socket&&(o.socket.disconnect(),o.socket=null);try{o.socket=io(e,{path:"/socket.io",transports:["websocket","polling"],auth:{token:n},autoConnect:!0,reconnection:!0,reconnectionAttempts:50,reconnectionDelay:1e3,reconnectionDelayMax:1e4}),t._bindBackendSocket&&t._bindBackendSocket(o.socket);var s=!1;o.socket.io&&"function"==typeof o.socket.io.on&&o.socket.io.on("reconnect_attempt",function(e){o._reconnAttempts=e}),o.socket.on("connect",function(){var e=s;if(s=!0,o.connected=!0,o._connecting=!1,t.log("Game socket connected"),o._heartbeatInterval&&clearInterval(o._heartbeatInterval),o._heartbeatInterval=setInterval(function(){o.socket&&o.connected&&o.roomId&&o.socket.emit("game:heartbeat",{room_id:o.roomId})},25e3),o.roomId){var n=o._lastSequence||0;o._joined=!1,o._joinPromise=null,o._rejoinPromise=o.join(o.roomId).then(function(){t.log("Reconnected - joined room "+o.roomId),o.requestSync(n)}).catch(function(e){t.log("Rejoin failed: "+(e&&e.message?e.message:String(e)))}).then(function(){o._rejoinPromise=null,o._flushOfflineQueue&&o._flushOfflineQueue()})}e&&(t.log("Game socket reconnected"),o._dispatch("reconnect",o._reconnAttempts||1),o._reconnAttempts=0),i()}),o.socket.on("connect_error",function(e){o._connecting=!1,t.log("Game socket error: "+e.message),o._dispatch("connectionError",e),r(e)}),o.socket.on("disconnect",function(e){o.connected=!1,o._joined=!1,o._joinPromise=null,o._heartbeatInterval&&(clearInterval(o._heartbeatInterval),o._heartbeatInterval=null),t.log("Game socket disconnected: "+e),o._dispatch("disconnect",e)}),o.socket.on("game:joined",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("joined",e)}),o.socket.on("game:player_joined",function(e){o._dispatch("playerJoined",e)}),o.socket.on("game:player_left",function(e){o._dispatch("playerLeft",e)}),o.socket.on("game:state",function(e){void 0!==e.sequence&&(o._lastSequence=Math.max(o._lastSequence,e.sequence)),o._dispatch("stateUpdate",e)}),o.socket.on("game:sync",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("sync",e),o._dispatch("stateUpdate",e)}),o.socket.on("game:action",function(e){if(void 0!==e.sequence){if(e.sequence<=o._lastActionApplied)return;o._lastActionApplied=e.sequence,o._lastSequence=Math.max(o._lastSequence,e.sequence)}o._dispatch("action",e)}),o.socket.on("game:player_connection",function(e){o._dispatch("playerConnection",e)}),o.socket.on("game:realtime",function(e){o._dispatch("realtime",e)}),o.socket.on("game:finished",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence),o._dispatch("finished",e)}),o.socket.on("game:error",function(e){t.log("Game error: "+(e.message||e.code)),o._dispatch("error",e)}),o.socket.on("game:rematch_request",function(e){o._dispatch("rematchRequest",e)}),o.socket.on("game:restarted",function(e){o._lastSequence=0,o._lastActionApplied=0,o._dispatch("restarted",e)})}catch(e){r(e)}}}(r,n),function(n,r){n._connectViaProxy=function(){var n=this;return n._useProxy&&n.connected?Promise.resolve():(n._useProxy=!0,n._connecting=!0,n._setupProxyListener(),n._connectPromise=new Promise(function(i,o){n._proxyConnectResolve=function(){n.connected=!0,n._connecting=!1,r.log("Game socket connected via parent proxy"),i()},r._post({type:"GAME_CONNECT"}),setTimeout(function(){n.connected||(n._connecting=!1,o(new t(e.CONNECT_TIMEOUT,"Proxy connection timeout")))},1e4)}),n._connectPromise)},n._setupProxyListener=function(){var e=this;e._proxyListenerSetup||(e._proxyListenerSetup=!0,window.addEventListener("message",function(t){if(p(t)){var n;try{n="string"==typeof t.data?JSON.parse(t.data):t.data}catch(e){return}if(n&&"object"==typeof n&&e._useProxy)switch(n.type){case"GAME_CONNECTED":e._proxyConnectResolve&&(e._proxyConnectResolve(),e._proxyConnectResolve=null);break;case"GAME_CONNECT_ERROR":e.connected=!1,e._connecting=!1;break;case"GAME_DISCONNECTED":e.connected=!1,e._dispatch("disconnect",n.reason||"transport");break;case"GAME_RECONNECTED":e.connected=!0,e._dispatch("reconnect",n.attempts||1);break;case"GAME_PLAYER_CONNECTION":e._dispatch("playerConnection",n);break;case"GAME_JOINED":e._joined=!0,void 0!==n.sequence&&(e._lastSequence=n.sequence,e._lastActionApplied=Math.max(e._lastActionApplied,n.sequence)),e._proxyJoinResolve&&(e._proxyJoinResolve(n),e._proxyJoinResolve=null),e._proxyJoinReject=null,e._dispatch("joined",n);break;case"GAME_JOIN_ERROR":e._joined=!1,e._proxyJoinReject&&(e._proxyJoinReject(i(n.message||"Join failed")),e._proxyJoinReject=null),e._proxyJoinResolve=null;break;case"GAME_PLAYER_JOINED":e._dispatch("playerJoined",n);break;case"GAME_PLAYER_LEFT":e._dispatch("playerLeft",n);break;case"GAME_STATE":void 0!==n.sequence&&(e._lastSequence=Math.max(e._lastSequence,n.sequence)),e._dispatch("stateUpdate",n);break;case"GAME_ACTION_DATA":if(void 0!==n.sequence){if(n.sequence<=e._lastActionApplied)break;e._lastActionApplied=n.sequence,e._lastSequence=Math.max(e._lastSequence,n.sequence)}e._dispatch("action",n);break;case"GAME_REALTIME_DATA":e._dispatch("realtime",n);break;case"GAME_FINISHED":void 0!==n.sequence&&(e._lastSequence=n.sequence),e._dispatch("finished",n);break;case"GAME_ERROR":r.log("Game error via proxy: "+(n.message||n.code)),e._dispatch("error",n);break;case"GAME_RESTARTED":e._lastSequence=0,e._lastActionApplied=0,e._dispatch("restarted",n);break;case"GAME_REMATCH_REQUEST":e._dispatch("rematchRequest",n);break;case"GAME_SYNC":void 0!==n.sequence&&(e._lastSequence=n.sequence,e._lastActionApplied=Math.max(e._lastActionApplied,n.sequence)),e._dispatch("sync",n),e._dispatch("stateUpdate",n)}}}))}}(r,n),function(n,r){function o(e){const t=e.roomId||r.config&&r.config.roomId,n=e.playerId||r.user&&"function"==typeof r.user.getId&&r.user.getId()||r.config&&r.config.userId;return t&&n?"_usion_game_state:"+n+":"+t:null}n.join=function(n){const o=this;if(n=n||r.config.roomId,o.roomId===n&&o._joinPromise)return o._joinPromise;if(o.roomId=n,o.playerId=r.user.getId(),o.directMode)return o._joined=!0,o._joinPromise=Promise.resolve({room_id:n,player_id:o.playerId}),o._joinPromise;if(o._useProxy){const i=new Promise(function(i,s){const c=function(e){s(e)};o._proxyJoinResolve=i,o._proxyJoinReject=c,r._post({type:"GAME_JOIN",room_id:n}),setTimeout(function(){o._proxyJoinReject===c&&(o._proxyJoinResolve=null,o._proxyJoinReject=null,s(new t(e.JOIN_TIMEOUT,"Join timeout")))},15e3)});return j(o,i)}let s;return s=o.socket&&o.connected?n?L(o.socket,"game:join",{room_id:n},15e3,e.JOIN_TIMEOUT).then(function(e){if(e.error)throw o._joined=!1,i(e);return o._joined=!0,void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("joined",e),e}):Promise.reject(new t(e.NO_ROOM,"No room ID provided")):Promise.reject(new t(e.NOT_CONNECTED,"Not connected")),j(o,s)},n.joinWorld=function(e){const t=this;return e=e||{},r.matchmaking._joinWorld(e.serviceId).then(function(e){return t.roomId=e.roomId,{roomId:e.roomId,playerIds:e.players||[]}})},n.leave=function(){const e=this;return e._playersConnection&&e._playersConnection.close(),e.directMode?(e.roomId&&e._sendDirect("leave",{}),e.roomId=null,e._lastSequence=0,e._joined=!1,void(e._joinPromise=null)):e._useProxy?(e.roomId&&r._post({type:"GAME_LEAVE",room_id:e.roomId}),e.roomId=null,e._lastSequence=0,e._joined=!1,void(e._joinPromise=null)):void(e.socket&&e.connected&&e.roomId&&(e.socket.emit("game:leave",{room_id:e.roomId}),e.roomId=null,e._lastSequence=0,e._joined=!1,e._joinPromise=null))},n.action=function(n,i,o){const s=this,c=o&&o.nextTurn,a=!(!o||!o.queueOffline);if(s.directMode)return s._sendDirect("action",{action_type:n||"default",action_data:i||{}}),Promise.resolve({success:!0});if(a&&!s.connected)return s._queueOfflineAction(n,i,o);if(s._useProxy){if(!s.connected)return Promise.reject(new t(e.NOT_CONNECTED,"Not connected"));const o={type:"GAME_ACTION",room_id:s.roomId,action_type:n,action_data:i};return c&&(o.next_turn=c),r._post(o),Promise.resolve({success:!0,acknowledged:!1})}return(s._rejoinPromise||Promise.resolve()).then(function(){if(!s.socket||!s.connected){if(a)return s._queueOfflineAction(n,i,o);throw new t(e.NOT_CONNECTED,"Not connected")}const r={room_id:s.roomId,action_type:n,action_data:i};return c&&(r.next_turn=c),s._emitAction(r,!0)})},n._emitAction=function(n,r){const o=this;return o.socket&&o.connected?L(o.socket,"game:action",n).then(function(t){if(t.error){const s=i(t);if(r&&s.code===e.NOT_IN_ROOM)return o._autoRejoin().then(function(){return o._emitAction(n,!1)});throw s}return void 0!==t.sequence&&(o._lastSequence=t.sequence),t}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n._autoRejoin=function(){const e=this;if(e._rejoinPromise)return e._rejoinPromise;if(!e.roomId||!e.socket||!e.connected)return Promise.resolve();r.log("Server reports socket not in room - auto-rejoining "+e.roomId);const t=e._lastSequence||0;return e._joined=!1,e._joinPromise=null,e._rejoinPromise=e.join(e.roomId).then(function(){e.requestSync(t)}).catch(function(e){r.log("Auto-rejoin failed: "+(e&&e.message?e.message:String(e)))}).then(function(){e._rejoinPromise=null,e._flushOfflineQueue&&e._flushOfflineQueue()}),e._rejoinPromise},n._queueOfflineAction=function(n,i,o){const s=this;return s._offlineQueue||(s._offlineQueue=[]),s._offlineQueue.length>=20?Promise.reject(new t(e.QUEUE_FULL,"Offline action queue is full (20)")):(r.log("Queued action while offline: "+n),new Promise(function(e,t){s._offlineQueue.push({actionType:n,actionData:i,opts:Object.assign({},o,{queueOffline:!1}),resolve:e,reject:t}),s._ensureOfflineFlushHook()}))},n._ensureOfflineFlushHook=function(){const e=this;e._offlineFlushHooked||(e._offlineFlushHooked=!0,e.on("reconnect",function(){e._flushOfflineQueue()}))},n._flushOfflineQueue=function(){const t=this,n=t._offlineQueue;if(!n||!n.length)return Promise.resolve();if(t._offlineFlushPromise)return t._offlineFlushPromise;if(!t.connected||!t._useProxy&&!t.directMode&&!t._joined)return Promise.resolve();r.log("Flushing "+n.length+" queued action(s) after reconnect");const o=Promise.resolve().then(function r(){if(!n.length)return Promise.resolve();if(!t.connected||!t._useProxy&&!t.directMode&&!t._joined)return Promise.resolve();const o=n[0];return t.action(o.actionType,o.actionData,o.opts).then(function(e){return n[0]===o&&n.shift(),o.resolve(e),r()},function(t){const s=i(t);if(s.code!==e.NOT_CONNECTED&&s.code!==e.NOT_IN_ROOM)return n[0]===o&&n.shift(),o.reject(t),r()})});function s(){t._offlineFlushPromise===o&&(t._offlineFlushPromise=null)}return t._offlineFlushPromise=o,o.then(s,s),o},n.setState=function(n){const o=this;if(o.directMode)return Promise.resolve({success:!1,error:"not_supported_in_direct_mode",code:e.UNSUPPORTED});const s=o._lastSequence||0,c=n&&1===n.__usionSyncedState&&Number.isSafeInteger(n.seq)&&n.seq>=0&&n.seq<=s?n.seq:s;return o._useProxy?r._request("GAME_SET_STATE",{room_id:o.roomId,state:n||{},sequence:c}).then(function(e){if(e&&e.error){const t=i(e);return{success:!1,error:t.message,code:t.code}}return e||{success:!0}}).catch(function(t){const n=i(t,e.REQUEST_TIMEOUT);return{success:!1,error:n.message,code:n.code}}):o.socket&&o.connected?L(o.socket,"game:set_state",{room_id:o.roomId,state:n||{},sequence:c}).then(function(e){if(e.error){const t=i(e);return{success:!1,error:t.message,code:t.code}}return Object.keys(e).length?e:{success:!0}}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n.realtime=function(t,n){const o=this;o.directMode?o._sendDirect("input",{action_type:t,action_data:n||{}}):o._useProxy?r._post({type:"GAME_REALTIME",room_id:o.roomId,action_type:t,action_data:n}):o.socket&&o.connected&&o.socket.emit("game:realtime",{room_id:o.roomId,action_type:t,action_data:n},function(t){if(!t||!t.error)return;const n=i(t);o._dispatch("error",{code:n.code,message:n.message,source:"realtime"}),n.code===e.NOT_IN_ROOM&&o._autoRejoin()})},n.requestSync=function(e){const t=this;e=void 0!==e?e:t._lastSequence,t.directMode?t._sendDirect("ping",{last_sequence:e||0}):t._useProxy&&t.roomId?r._post({type:"GAME_SYNC_REQUEST",room_id:t.roomId,last_sequence:e||0}):t.socket&&t.connected&&t.roomId&&t.socket.emit("game:sync_request",{room_id:t.roomId,last_sequence:e||0})},n.requestRematch=function(){const e=this;e.directMode?e._sendDirect("rematch",{}):e._useProxy&&e.roomId?r._post({type:"GAME_REMATCH",room_id:e.roomId}):e.socket&&e.connected&&e.roomId&&e.socket.emit("game:rematch",{room_id:e.roomId})},n.forfeit=function(){const n=this;return n.directMode?(n._sendDirect("forfeit",{}),Promise.resolve({success:!0})):n._useProxy?(r._post({type:"GAME_FORFEIT",room_id:n.roomId}),Promise.resolve({success:!0})):n.socket&&n.connected?L(n.socket,"game:forfeit",{room_id:n.roomId}).then(function(e){if(e.error)throw i(e);return e}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n.reportResult=function(n,i){if(i=i||{},!((n=n||{}).draw||"string"==typeof n.winnerId&&n.winnerId))return Promise.reject(new t(e.INVALID_INPUT,"reportResult needs a winnerId (or draw: true)"));const o=n.roomId||this.roomId||r.config&&r.config.roomId||null;if(!o)return Promise.reject(new t(e.NO_ROOM,"reportResult needs a room — join a game first"));let s=null;return Array.isArray(n.standings)&&(s=n.standings.map(function(e){return"string"==typeof e?e:e&&(e.userId||e.user_id)||null}).filter(function(e){return"string"==typeof e&&e}),s.length||(s=null)),r._backendEmit("gc:match_result",{service_id:i.serviceId||r.config&&r.config.serviceId,room_id:o,winner_id:n.draw?null:n.winnerId,draw:!!n.draw,standings:s,scores:n.scores&&"object"==typeof n.scores?n.scores:null,display_score:null!=n.displayScore?String(n.displayScore):null,metric:null!=n.metric?String(n.metric):null,match_id:null!=n.matchId?String(n.matchId):null})},n.invite=function(e){const t=this;e=e||{};const n="undefined"!=typeof window&&(!!window.ReactNativeWebView||!!window.parent&&window.parent!==window),i=t.roomId||r.config&&r.config.roomId||null;if(!n){try{console.warn("[Usion] game.invite needs the Usion app; resolving as not sent.")}catch(e){}return Promise.resolve({success:!1,roomId:i,invited:[]})}const o={roomId:i};return"number"==typeof e.maxPlayers&&e.maxPlayers>0&&(o.maxPlayers=e.maxPlayers),r._request("GAME_INVITE_REQUEST",o,e.timeout||12e4).then(function(e){const n=(e=e||{}).roomId||i||null,r={success:!!e.success,roomId:n,invited:Array.isArray(e.invited)?e.invited:[]};return r.success&&n?Promise.resolve().then(function(){return t.connect()}).then(function(){return t.join(n)}).then(function(){return r}).catch(function(){return r}):r}).catch(function(){return{success:!1,roomId:i,invited:[]}})},n.disconnect=function(){const e=this;if(e._playersConnection&&e._playersConnection.close(),e._heartbeatInterval&&(clearInterval(e._heartbeatInterval),e._heartbeatInterval=null),e.directMode){if(e.directSocket)try{e.directSocket.close()}catch(e){}return e.directSocket=null,e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null,e.directMode=!1,e.directConfig=null,void(e._directSeq=0)}if(e._useProxy)return r._post({type:"GAME_DISCONNECT"}),e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null,void(e._useProxy=!1);e.socket&&(e.socket.disconnect(),e.socket=null,e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null)},n.saveState=function(e){const t=o(this);if(!t)return!1;try{return localStorage.setItem(t,JSON.stringify({state:e,savedAt:Date.now()})),!0}catch(e){return!1}},n.loadState=function(){const e=o(this);if(!e)return null;try{const t=localStorage.getItem(e);if(!t)return null;const n=JSON.parse(t);return n&&void 0!==n.state?n.state:null}catch(e){return null}},n.clearState=function(){const e=o(this);if(e)try{localStorage.removeItem(e)}catch(e){}},n.debug=function(e){try{var t=window.parent&&window.parent!==window,n=!!window.ReactNativeWebView;if(t||n){var i=Object.assign({},e||{});i._diag=r.diagnostics?r.diagnostics():void 0,r._post({type:"GAME_DEBUG",payload:i})}}catch(e){}},n.isMultiplayer=function(){return"multiplayer"===r.getLaunchParams().mode},n.isConnected=function(){return this.directMode?!(!this.connected||!this.directSocket||this.directSocket.readyState!==WebSocket.OPEN):this._useProxy?!!this.connected:!!(this.connected&&this.socket&&this.socket.connected)}}(r,n),Pe(r,n),function(e,t){e.connectPlayers=function(n={}){if(e._playersConnection&&!e._playersConnection.closed)return e._playersPromise;if(e.directMode||"direct"===t.config.connectionMode)return Promise.reject(new Error("connectPlayers requires platform room signaling"));if(!Ue(t.user.getId()))return Promise.reject(new Error("Initialize Usion before connectPlayers"));if(void 0!==n.directTimeoutMs&&(!Number.isFinite(n.directTimeoutMs)||n.directTimeoutMs<1e3||n.directTimeoutMs>3e4))return Promise.reject(new Error("directTimeoutMs must be 1000–30000"));const i=e._playersConnection=new Le(e,t,n);return e._playersPromise=i.start().catch(e=>{throw i.close(),e}),e._playersPromise}}(r,n),function(e,t){e.getParticipants=async function(){const e=this.roomId;if(!e)throw new Error("Join a room before reading participants");for(let n=0;n<5;n++){const i=t.user.getToken();if(!i){if(n<4){await new Promise(e=>setTimeout(e,500));continue}throw new Error("Participant access needs an authenticated Usions session")}const r=String(t.config.apiUrl||"").replace(/\/$/,"");if(!r)throw new Error("No API URL provided");const o=await fetch(r+"/games/rooms/"+encodeURIComponent(e)+"/participants",{headers:{Authorization:"Bearer "+i},cache:"no-store"});if(401===o.status&&n<4){await new Promise(e=>setTimeout(e,500));continue}if(!o.ok)throw new Error("Participant access failed: HTTP "+o.status);const s=await o.json();if(this.roomId!==e)throw new Error("Room changed while loading participants");return s}}}(r,n),function(e,t){function n(t){var n=e[t];"function"==typeof n&&(e[t]=function(){var e=this;return n.apply(e,arguments).then(function(t){return e._awaitResync||e._setConnState("connected"),t})})}function i(t){t&&(t.host_id?e._hostId=t.host_id:t.player_ids&&t.player_ids.length&&(e._hostId=t.player_ids[0]))}e.getLastSequence=function(){return this._lastSequence||0},e.getLastAppliedSequence=function(){return this._lastActionApplied||0},e._connState="disconnected",e._awaitResync=!1,e._setConnState=function(e){this._connState!==e&&(this._connState=e,this._dispatch("connectionState",e))},e.getConnectionState=function(){return this._connState},e.onConnectionState=function(e){return this._setHandler("connectionState",e)},e.onReconnected=function(e){return this._setHandler("reconnected",e)},e.on("disconnect",function(){e._awaitResync=!1,e._setConnState("disconnected")}),e.on("reconnect",function(){e.roomId?(e._awaitResync=!0,e._setConnState("rejoining")):e._setConnState("connected")}),e.on("sync",function(t){e._awaitResync&&(e._awaitResync=!1,e._dispatch("reconnected",{state:t&&t.game_state||null,lastSequence:e._lastSequence||0,viaSync:!0}),e._setConnState("reconnected"),e._setConnState("connected"))}),n("connect"),n("connectDirect"),e._hostId=null,e.on("joined",i),e.on("playerJoined",i),Re(e,t)}(r,n),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("visibilitychange",function(){if("visible"===document.visibilityState&&r.roomId)try{r.requestSync()}catch(e){}}),r}(Be),Be.UsionError=t,Be.ERROR_CODES=e,function(n){n._backendHandlers={},n._boundSockets="undefined"!=typeof WeakSet?new WeakSet:null,n._bindBackendSocket=function(e){if(!e||"function"!=typeof e.onAny)return;if(this._boundSockets){if(this._boundSockets.has(e))return;this._boundSockets.add(e)}const t=this;e.onAny(function(e,n){const i=t._backendHandlers[e];i&&i(n)})},n._backendOn=function(e,t){this._backendHandlers[e]=t;const n=this.game&&this.game.socket;n&&("function"==typeof n.onAny?this._bindBackendSocket(n):"function"==typeof n.on&&n.on(e,t))},n._backendEmit=function(n,r,o){const s=this;function c(s){return new Promise(function(c,a){let u=!1;const l=setTimeout(function(){u||(u=!0,a(new t(e.REQUEST_TIMEOUT,"Backend request timeout")))},o);try{s.emit(n,r||{},function(e){u||(u=!0,clearTimeout(l),e&&e.error?a(i(e)):c(e))})}catch(e){clearTimeout(l),a(i(e))}})}o=o||8e3;const a=s.game&&s.game.socket;if(a&&a.connected)return c(a);if(s._isEmbedded)return s._request("BACKEND_EMIT",{event:n,data:r||{}},o).catch(function(e){throw i(e)});const u=s.config&&s.config.connectionMode||"platform";return!a&&"direct"!==u&&s.game&&"function"==typeof s.game.connect?s.game.connect().then(function(){const n=s.game.socket;if(n&&n.connected)return c(n);throw new t(e.NOT_CONNECTED,"No backend connection")}).catch(function(n){if(n instanceof t)throw n;throw new t(e.NOT_CONNECTED,"Backend connect failed: "+(n&&n.message?n.message:String(n)))}):Promise.reject(new t(e.NOT_CONNECTED,"No backend connection — socket is offline or reconnecting"))}}(Be),Be.lobby=function(e){const t={code:null,host:null,status:null,members:[]},n={};let i=!1;function r(){i||(i=!0,e._backendOn("lobby:update",function(e){t.code=e.code,t.host=e.host,t.status=e.status,t.members=e.members||[],n.update&&n.update(e)}),e._backendOn("lobby:started",function(e){t.status="started",n.started&&n.started(e)}))}function o(t,n){return r(),e._backendEmit(t,n)}return{get state(){return t},onUpdate:function(e){n.update=e,r()},onStarted:function(e){n.started=e,r()},create:async function(e){e=e||{};const n=await o("lobby:create",{max_players:e.maxPlayers||8,public:!!e.public});return n&&n.code&&(t.code=n.code),n},join:async function(e){const n=await o("lobby:join",{code:String(e||"").toUpperCase()});return n&&n.code&&(t.code=n.code),n},leave:function(){return t.code=null,o("lobby:leave",{}).catch(function(){})},setReady:function(e){return o("lobby:ready",{ready:!1!==e})},allReady:function(){return t.members.length>0&&t.members.every(function(e){return e.ready})},isHost:function(){const n=e.user&&e.user.getId&&e.user.getId();return!(!t.host||!n||t.host!==n)},start:function(e){return o("lobby:start",{room_id:e})},queue:async function(t,n){n=n||{};const i=e.config&&e.config.apiUrl||"",r=e.user&&e.user.getToken&&e.user.getToken();if(!i)throw new Error("No apiUrl configured");const o=await fetch(i.replace(/\/$/,"")+"/games/matchmake",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r},body:JSON.stringify({service_id:t,conversation_id:n.conversationId||"standalone_"+t})});if(!o.ok)throw new Error("Matchmake failed: HTTP "+o.status);return o.json()}}}(Be),Be.leaderboard=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}return{submit:function(n,i,r){return e._backendEmit("lb:submit",{service_id:t(r),score:n,metadata:null!=i?i:null})},scores:function(n,i){var r=Array.isArray(n)?n:[n];return e._backendEmit("lb:scores",{service_id:t(i),user_ids:r}).then(function(e){return e&&e.scores||{}})},friends:function(n){return n=n||{},e._backendEmit("lb:friends",{service_id:t(n),limit:n.limit||50}).then(function(e){return e&&e.entries||[]})},top:function(n){return n=n||{},e._backendEmit("lb:top",{service_id:t(n),limit:n.limit||20}).then(function(e){return e&&e.entries||[]})},me:function(n){return e._backendEmit("lb:me",{service_id:t(n)})}}}(Be),Be.cloud=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}function n(n,i,r,o){var s=Object.assign({service_id:t(o),scope:i},r);return e._backendEmit(n,s)}function i(e){return{get:function(t,i){return n("kv:get",e,{key:t},i).then(function(e){return e&&e.exists?e.value:null})},set:function(t,i,r){return n("kv:set",e,{key:t,value:i},r)},remove:function(t,i){return n("kv:remove",e,{key:t},i)},keys:function(t){return n("kv:keys",e,{},t).then(function(e){return e&&e.keys||[]})}}}var r=i("user");return r.shared=i("shared"),r.friends=i("friends"),r.friends.list=function(e,t){return n("kv:get","friends",{key:e,friends:!0},t).then(function(e){return(e&&e.entries||[]).map(function(e){return{userId:e.user_id,name:e.name||null,avatar:e.avatar||null,value:e.value,updatedAt:e.updated_at||null}})})},r.shared.incr=function(e,t,i){return n("kv:incr","shared",{key:e,delta:null==t?1:t},i).then(function(e){return e&&e.value})},r}(Be),Be.matchmaking=function(n){let r=null,o=null,s=!1;function c(e){return{roomId:e&&e.room_id,players:e&&e.player_ids||[],serviceId:e&&e.service_id}}function a(){s||(s=!0,n._backendOn("mm:matched",function(e){const t=c(e);if(o&&o(t),r){const e=r;r=null,e.resolve(t)}}))}function u(o,s,u){if(a(),r){const n=r;r=null,n.reject(new t(e.SUPERSEDED,"Superseded by a newer find()"))}let l=null;const d={},f=new Promise(function(e,t){d.resolve=function(t){l&&clearTimeout(l),e(t)},d.reject=function(e){l&&clearTimeout(l),r===d&&(r=null),t(e)}});return r=d,s>0&&(l=setTimeout(function(){l=null,n._backendEmit("mm:cancel",{}).catch(function(){}),d.reject(new t(e.MATCH_TIMEOUT,u+s+"ms"))},s)),n._backendEmit("mm:join",o).then(function(e){e&&e.matched&&e.room_id&&r===d&&(r=null,d.resolve(c(e)))}).catch(function(e){r===d&&d.reject(i(e))}),f}return{onMatch:function(e){o=e,a()},find:function(e,t){t=t||{};return u({service_id:e||n.config&&n.config.serviceId,size:t.size||2},t.timeout,"No match within ")},_joinWorld:function(e){return u({service_id:e||n.config&&n.config.serviceId,mode:"world"},15e3,"No world placement within ")},cancel:function(){if(r){const n=r;r=null,n.reject(new t(e.CANCELLED,"cancelled"))}return n._backendEmit("mm:cancel",{})}}}(Be),Be.notify=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}return{send:function(n){return n=n||{},e._backendEmit("notify:send",{service_id:t(n),title:n.title,body:n.body,path:n.path})},setMuted:function(n,i){return e._backendEmit("notify:set_pref",{service_id:t(i),muted:!!n})},isMuted:function(n){return e._backendEmit("notify:get_pref",{service_id:t(n)}).then(function(e){return!(!e||!e.muted)})}}}(Be),Be.permissions=function(e){function t(e){return"string"==typeof e?e?[e]:[]:Array.isArray(e)?e.filter(function(e){return"string"==typeof e&&e}):[]}function n(){return"undefined"!=typeof window&&(!!window.ReactNativeWebView||!!window.parent&&window.parent!==window)}function i(e){const t={};return e.forEach(function(e){t[e]=!1}),t}function r(e,t){const n=t||{};return{granted:e.length>0&&e.every(function(e){return!!n[e]}),permissions:n}}const o={_requestTimeoutMs:12e4,request:function(s,c){const a=t(s),u=c&&"string"==typeof c.reason?c.reason:void 0;if(!n()){try{console.warn("[Usion] permissions.request needs the Usion app; resolving as not granted.")}catch(e){}return Promise.resolve(r(a,i(a)))}return new Promise(function(t){const n=f();let s=!1,c=null;function l(e){s||(s=!0,c&&clearTimeout(c),window.removeEventListener("message",d),t(e))}function d(e){if(!p(e))return;let t;try{t="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}t&&t._requestId===n&&"PERMISSION_RESULT"===t.type&&l(r(a,t.permissions))}window.addEventListener("message",d),c=setTimeout(function(){s||o.query(a).then(function(e){l(r(a,e))}).catch(function(){l(r(a,i(a)))})},o._requestTimeoutMs||12e4),e._post({type:"PERMISSION_REQUEST",_requestId:n,permissions:a,reason:u})})},query:function(r){const o=t(r);return n()?e._request("PERMISSION_QUERY",{permissions:o},8e3).then(function(e){return e&&e.permissions||{}}):Promise.resolve(i(o))},has:function(e){return o.query([e]).then(function(t){return!(!t||!t[e])})}};return o}(Be),Be.screen=function(e){var t=[],n=!1;function i(e){if(p(e)){var n;try{n="string"==typeof e.data?JSON.parse(e.data):e.data}catch(e){return}if(n&&"SCREEN_CAPTURE"===n.type)for(var i="string"==typeof n.kind&&n.kind?n.kind:"screenshot",r=t.slice(),o=0;o<r.length;o++)try{r[o]({kind:i})}catch(e){}}}return{protect:function(t){try{e._post({type:"SCREEN_PROTECT",enabled:!!t})}catch(e){}},onCapture:function(e){if("function"!=typeof e)return function(){};t.push(e),n||"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("message",i),n=!0);var r=!1;return function(){if(!r){r=!0;var o=t.indexOf(e);o>=0&&t.splice(o,1),0===t.length&&function(){if(n){try{window.removeEventListener("message",i)}catch(e){}n=!1}}()}}},support:function(){var t=e.config&&e.config.screenCapture||null;return{block:!(!t||!t.block),detect:!(!t||!t.detect)}}}}(Be),Be.profile=function(n){function i(i,r){return"undefined"!=typeof window&&("ReactNativeWebView"in window||window.parent!==window)?n._request(i,r,3e4):Promise.reject(new t(e.UNSUPPORTED,"Profile content requires the Usion host"))}return{getContent:()=>i("PROFILE_CONTENT_GET",{}).then(e=>e.content),setContent:n=>!n||!Array.isArray(n.items)||n.items.length>50?Promise.reject(new t(e.INVALID_INPUT,"Profile content requires at most 50 items")):i("PROFILE_CONTENT_SET",{content:n}).then(e=>e.content),clearContent:()=>i("PROFILE_CONTENT_CLEAR",{}).then(()=>{})}}(Be),Be.call=function(e){return Object.assign(s(e),u(e),{capabilities:function(){return e._request("CALL_CAPABILITIES",{},5e3)},startAnalysis:async function(t){if(!t||!Array.isArray(t.capabilities)||"function"!=typeof t.onSample)throw new Error("capabilities and onSample are required");var n=null,i=!1,r=e.on("CALL_ANALYSIS_EVENT",function(e){i||null===n||e.subscriptionId!==n||t.onSample(e.sample)}),o=e.on("CALL_ANALYSIS_STOPPED",function(e){e.subscriptionId===n&&s()});function s(){i||(i=!0,r(),o(),"function"==typeof t.onStopped&&t.onStopped())}try{var c=await e._request("CALL_ANALYSIS_START",{capabilities:t.capabilities},12e4);if(!c.started||!Number.isInteger(c.subscriptionId))throw new Error("Invalid call analysis response");return n=c.subscriptionId,{stop:async function(){i||(s(),await e._request("CALL_ANALYSIS_STOP",{},5e3))}}}catch(e){throw s(),e}}})}(Be),Be.tabs=function(n){const i=new Set;function r(i,r){return n.config.hostFeatures?.tabControl?n._request(i,r):Promise.reject(new t(e.UNSUPPORTED,"Tab control requires a newer Usion host"))}function o(e){return"string"==typeof e&&e.startsWith("/")&&!e.startsWith("//")&&!/[\\\s\x00-\x1f]/.test(e)&&e.length<=2048}function s(e){return"string"==typeof e&&/^[a-zA-Z0-9_-]{1,64}$/.test(e)}function c(){return Promise.reject(new t(e.INVALID_INPUT,"Invalid tab navigation options"))}return{configure:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return c();const t=["landingTab","landingPath","lockedTabs","fallbackTab","fallbackPath"];return Object.keys(e).some(e=>-1===t.indexOf(e))||["landingTab","fallbackTab"].some(t=>void 0!==e[t]&&!s(e[t]))||["landingPath","fallbackPath"].some(t=>void 0!==e[t]&&!o(e[t]))||void 0!==e.lockedTabs&&(!Array.isArray(e.lockedTabs)||e.lockedTabs.length>32||e.lockedTabs.some(e=>!s(e)))?c():r("CONFIGURE_HOST_TABS",{...e})},open:function(e,t){return t=t||{},!s(e)||Object.keys(t).some(e=>"path"!==e)||void 0!==t.path&&!o(t.path)?c():r("OPEN_HOST_TAB",{tab:e,...void 0===t.path?{}:{path:t.path}})},onBlocked:function(e){return"function"!=typeof e?function(){}:(i.add(e),function(){i.delete(e)})},_dispatchBlocked:function(e){if(!s(e.tab))return;const t={tab:e.tab,...o(e.path)?{path:e.path}:{}};i.forEach(function(e){try{e(t)}catch(e){console.error("[Usion] tab listener error:",e)}})}}}(Be),Be.modal=function(n){function i(i,r,o){return n.config.hostFeatures?.modal?n._request(i,r,o):Promise.reject(new t(e.UNSUPPORTED,"Modals require a newer Usion host"))}return{open:n=>!n||"string"!=typeof n.path||!n.path.startsWith("/")||n.path.startsWith("//")||n.path.length>2048||void 0!==n.tab&&("string"!=typeof n.tab||!/^[a-zA-Z0-9_-]{1,64}$/.test(n.tab))||void 0!==n.title&&("string"!=typeof n.title||n.title.length>100)?Promise.reject(new t(e.INVALID_INPUT,"Invalid modal options")):i("OPEN_HOST_MODAL",{path:n.path,tab:n.tab,title:n.title},18e5),close:e=>i("CLOSE_HOST_MODAL",{result:e})}}(Be),Be.netcode=xe,Object.assign(Be,function(e){return{saveResult:function(t,n){return e._request("SAVE_RESULT",{data:t,metadata:n||{}},15e3)},deleteResult:function(t){return e._request("DELETE_RESULT",{resultId:t})},getResults:function(){return e._results||[]}}}(Be)),Object.assign(Be,function(e){return{claimBackButton:function(t){e._backButtonCallback=t,e._post({type:"CLAIM_BACK_BUTTON"})},releaseBackButton:function(){e._backButtonCallback=null,e._post({type:"RELEASE_BACK_BUTTON"})}}}(Be)),Object.assign(Be,function(e){return{onHostNavigate:function(t){e._hostNavigateCallback=t,e._post({type:"HOST_NAVIGATE_SUBSCRIBED"})},offHostNavigate:function(){e._hostNavigateCallback=null,e._post({type:"HOST_NAVIGATE_UNSUBSCRIBED"})},openChat:function(t){t=t||{},e._post({type:"OPEN_CHAT_TAB",prefill:"string"==typeof t.prefill?t.prefill:void 0})},reportPath:function(t){"string"==typeof t&&t&&e._post({type:"TAB_CHANGED",path:t})}}}(Be)),Object.assign(Be,A),Object.assign(Be,O),Object.assign(Be,D),Be}();"undefined"!=typeof window?window.Usion=Usion:"undefined"!=typeof globalThis&&(globalThis.Usion=Usion);
|
|
1
|
+
/*! @usions/sdk v2.39.1 — minified build; source: packages/sdk/src/modules (github.com/ugshanyu/usionthemobile) */
|
|
2
|
+
var Usion=function(){"use strict";const e={PERMISSION_DENIED:"PERMISSION_DENIED",NOT_CONNECTED:"NOT_CONNECTED",NO_ROOM:"NO_ROOM",ROOM_NOT_FOUND:"ROOM_NOT_FOUND",NOT_PARTICIPANT:"NOT_PARTICIPANT",NOT_IN_ROOM:"NOT_IN_ROOM",NOT_AUTHORITY:"NOT_AUTHORITY",NOT_AUTHENTICATED:"NOT_AUTHENTICATED",JOIN_TIMEOUT:"JOIN_TIMEOUT",CONNECT_TIMEOUT:"CONNECT_TIMEOUT",INIT_TIMEOUT:"INIT_TIMEOUT",MATCH_TIMEOUT:"MATCH_TIMEOUT",STATE_TOO_LARGE:"STATE_TOO_LARGE",INVALID_STATE:"INVALID_STATE",STALE_STATE:"STALE_STATE",INVALID_NEXT_TURN:"INVALID_NEXT_TURN",INVALID_INPUT:"INVALID_INPUT",NOT_FOUND:"NOT_FOUND",QUOTA_EXCEEDED:"QUOTA_EXCEEDED",VALUE_TOO_LARGE:"VALUE_TOO_LARGE",LOBBY_FULL:"LOBBY_FULL",LOBBY_CLOSED:"LOBBY_CLOSED",WORLD_FULL:"WORLD_FULL",CONFLICT:"CONFLICT",RATE_LIMITED:"RATE_LIMITED",REQUEST_TIMEOUT:"REQUEST_TIMEOUT",QUEUE_FULL:"QUEUE_FULL",AUTH_CHANGED:"AUTH_CHANGED",CANCELLED:"CANCELLED",SUPERSEDED:"SUPERSEDED",UNSUPPORTED:"UNSUPPORTED",VOICE_UNSUPPORTED:"VOICE_UNSUPPORTED",VOICE_DISABLED:"VOICE_DISABLED",VOICE_UNAVAILABLE:"VOICE_UNAVAILABLE",VOICE_NO_ROOM:"VOICE_NO_ROOM",VOICE_NOT_IN_ROOM:"VOICE_NOT_IN_ROOM",VOICE_BAD_CHANNEL:"VOICE_BAD_CHANNEL",VOICE_FULL:"VOICE_FULL",VOICE_DECLINED:"VOICE_DECLINED",VOICE_MIC_DENIED:"VOICE_MIC_DENIED",VOICE_GUEST:"VOICE_GUEST",VOICE_FAILED:"VOICE_FAILED",UNKNOWN:"UNKNOWN"};class t extends Error{constructor(t,n){super(n||t),this.name="UsionError",this.code=e[t]?t:e.UNKNOWN,this.retryAfter=void 0}}const n=[[/not authenticated/i,e.NOT_AUTHENTICATED],[/room_id required|no room id/i,e.NO_ROOM],[/room not found/i,e.ROOM_NOT_FOUND],[/not in room/i,e.NOT_IN_ROOM],[/not a participant/i,e.NOT_PARTICIPANT],[/room authority/i,e.NOT_AUTHORITY],[/exceeds .*limit/i,e.STATE_TOO_LARGE],[/stale checkpoint|stale state/i,e.STALE_STATE],[/state must be/i,e.INVALID_STATE],[/next_turn must be/i,e.INVALID_NEXT_TURN],[/rate limit|too many/i,e.RATE_LIMITED],[/join timeout/i,e.JOIN_TIMEOUT],[/connection timeout|connect timeout/i,e.CONNECT_TIMEOUT],[/request timeout/i,e.REQUEST_TIMEOUT],[/not connected/i,e.NOT_CONNECTED],[/quota exceeded/i,e.QUOTA_EXCEEDED],[/value too large/i,e.VALUE_TOO_LARGE],[/lobby is full/i,e.LOBBY_FULL],[/lobby is not open/i,e.LOBBY_CLOSED],[/world room is full/i,e.WORLD_FULL],[/not found|unknown service/i,e.NOT_FOUND],[/conflict/i,e.CONFLICT],[/cancelled/i,e.CANCELLED],[/superseded/i,e.SUPERSEDED]];function i(i,r){if(i instanceof t)return i;if(i&&"object"==typeof i){const n="string"==typeof i.code&&e[i.code]?i.code:null,r=i.message||i.error;if(n){const e=new t(n,"string"==typeof r?r:n),o=null!=i.retry_after?i.retry_after:i.retryAfter;return"number"==typeof o&&isFinite(o)&&(e.retryAfter=o),e}i instanceof Error||"string"!=typeof r||(i=r)}const o=i&&i.message?i.message:String(i||"Unknown error");for(let e=0;e<n.length;e++)if(n[e][0].test(o))return new t(n[e][1],o);return new t(r||e.UNKNOWN,o)}const r=/^[a-z0-9][a-z0-9_-]{0,47}$/;function o(e,t){try{e(t)}catch(e){console.error("[Usion] call voice listener error:",e)}}function s(n){let i={on:!1,channel:null,scope:null,status:"idle",micOn:!1,peers:[]};const s=new Set,c=new Set;let a=!1;function u(){const e=n.config&&n.config.hostFeatures;return!(!e||!e.voice)}function l(){a||(a=!0,n.on("CALL_VOICE_CHANGED",function(e){e&&e.state&&d(e.state)}),n.on("CALL_VOICE_SPEAKING",function(e){const t=e&&Array.isArray(e.userIds)?e.userIds.filter(function(e){return"string"==typeof e}):[];c.forEach(function(e){o(e,t)})}))}function d(e){return i=function(e){if(!e||"object"!=typeof e)return{on:!1,channel:null,scope:null,status:"idle",micOn:!1,peers:[]};const t=Array.isArray(e.peers)?e.peers:[];return{on:!!e.on,channel:"string"==typeof e.channel?e.channel:null,scope:"room"===e.scope||"game"===e.scope?e.scope:null,status:["idle","connecting","connected","reconnecting"].indexOf(e.status)>=0?e.status:"idle",micOn:!!e.micOn,peers:t.filter(function(e){return e&&"string"==typeof e.userId}).map(function(e){return{userId:e.userId,name:"string"==typeof e.name?e.name:"",isMe:!!e.isMe,micOn:!!e.micOn,speaking:!!e.speaking}})}}(e),s.forEach(function(e){o(e,i)}),i}function f(r,o,s){return u()?(l(),n._request(r,o,s).then(function(e){return e&&e.state?d(e.state):i})):Promise.reject(new t(e.VOICE_UNSUPPORTED,"Voice needs a newer version of the Usion app"))}return{isAvailable:u,micOn:function(n){const i=n||{},o=null==i.channel?"main":i.channel,s=null==i.scope?"room":i.scope;return"string"==typeof o&&r.test(o)?"room"!==s&&"game"!==s?Promise.reject(new t(e.VOICE_BAD_CHANNEL,"scope must be 'room' or 'game'")):f("CALL_VOICE_ON",{channel:o,scope:s,listen:!!i.listen},6e4):Promise.reject(new t(e.VOICE_BAD_CHANNEL,"Channel names are 1-48 of a-z, 0-9, '-', '_' and start with a letter or digit"))},micOff:function(){return f("CALL_VOICE_OFF",{},5e3).then(function(){})},setMic:function(e){return f("CALL_VOICE_SET_MIC",{on:!!e},5e3)},mutePeer:function(n,i){return"string"==typeof n&&n?f("CALL_VOICE_MUTE_PEER",{userId:n,muted:!1!==i},5e3).then(function(){}):Promise.reject(new t(e.INVALID_INPUT,"userId required"))},state:function(){return u()?f("CALL_VOICE_STATE",{},5e3):Promise.resolve({on:!1,channel:null,scope:null,status:"idle",micOn:!1,peers:[]})},onChange:function(e){if(l(),s.add(e),i.on){const t=i;Promise.resolve().then(function(){s.has(e)&&i===t&&o(e,t)})}return function(){s.delete(e)}},onSpeaking:function(e){return l(),c.add(e),function(){c.delete(e)}}}}const c=/^[a-z0-9][a-z0-9_-]{0,47}$/;function a(n){if(n instanceof t)return n;const i=n&&"string"==typeof n.code?n.code:e.VOICE_FAILED;return new t(i,n&&n.message||"Voice count unavailable")}function u(n){const i=new Map;let r=!1;function o(e,t){e.count=t,e.listeners.forEach(function(e){try{e(t)}catch(e){console.error("[Usion] voice count listener error:",e)}})}function s(s,u,l){let d;try{if(d=function(n){const i=n||{},r=null==i.channel?"main":i.channel,o=null==i.scope?"room":i.scope;if("string"!=typeof r||!c.test(r))throw new t(e.VOICE_BAD_CHANNEL,"Channel names are 1-48 of a-z, 0-9, '-', '_' and start with a letter or digit");if("room"!==o&&"game"!==o)throw new t(e.VOICE_BAD_CHANNEL,"scope must be 'room' or 'game'");return{channel:r,scope:o,key:o+":"+r}}(s),"function"!=typeof u)throw new t(e.INVALID_INPUT,"callback required");if(!function(){const e=n.config&&n.config.hostFeatures;return!(!e||!e.voiceCount)}())throw new t(e.VOICE_UNSUPPORTED,"Voice counts need a newer version of the Usion app")}catch(e){const t=a(e);return"function"==typeof l?Promise.resolve().then(function(){l(t)}):console.warn("[Usion] call.onCount:",t.message),function(){}}r||(r=!0,n.on("CALL_VOICE_COUNT",function(e){if(!e||"number"!=typeof e.count||e.count<0)return;const t=i.get(e.scope+":"+e.channel);t&&t.count!==e.count&&o(t,e.count)}));const f=d.key;let h=i.get(f);const _=!h;h||(h={channel:d.channel,scope:d.scope,count:null,failed:!1,listeners:new Set,errorListeners:new Set},i.set(f,h));const p=h;p.listeners.add(u);const m="function"==typeof l?l:function(e){console.warn("[Usion] call.onCount:",e.message)};if(p.errorListeners.add(m),_)n._request("CALL_VOICE_WATCH",{channel:d.channel,scope:d.scope},15e3).then(function(e){i.get(f)===p&&e&&"number"==typeof e.count&&o(p,e.count)},function(e){i.get(f)===p&&function(e,t){const n=i.get(e);n&&(i.delete(e),n.failed=!0,n.errorListeners.forEach(function(e){try{e(t)}catch(e){console.error("[Usion] voice count error listener:",e)}}))}(f,a(e))});else if(null!==p.count){const e=p.count;Promise.resolve().then(function(){if(p.listeners.has(u)&&p.count===e)try{u(e)}catch(e){console.error("[Usion] voice count listener error:",e)}})}let g=!1;return function(){g||(g=!0,p.listeners.delete(u),p.errorListeners.delete(m),0===p.listeners.size&&i.get(f)===p&&(i.delete(f),n._request("CALL_VOICE_UNWATCH",{channel:p.channel,scope:p.scope},5e3).catch(function(){})))}}return{onCount:s,count:function(n){return new Promise(function(i,r){let o=null,c=!1;function a(e){if(!c&&(c=!0,clearTimeout(u),e(),o)){const e=o;o=null,Promise.resolve().then(e)}}const u=setTimeout(function(){a(function(){r(new t(e.VOICE_FAILED,"Voice count timed out"))})},1e4);if(o=s(n,function(e){a(function(){i(e)})},function(e){a(function(){r(e)})}),c&&o){const e=o;o=null,e()}})}}}var l=null;function d(e,t){var n=t.requestId;if(!(l||"string"!=typeof n||!n||n.length>64)){l=i,setTimeout(i,250);try{requestAnimationFrame(i)}catch(e){}}function i(){if(l===i){l=null;var t=null;try{t=function(){var e,t=0;for(var n of document.getElementsByTagName("canvas")){var i=n.width&&n.height&&"hidden"!==getComputedStyle(n).visibility?n.offsetWidth*n.offsetHeight:0;i>t&&(e=n,t=i)}if(!e)return null;var r=720/Math.max(720,e.width,e.height),o=document.createElement("canvas"),s=o.width=e.width*r|0,c=o.height=e.height*r|0,a=o.getContext("2d");a.drawImage(e,0,0,s,c);var u,l=a.getImageData(0,0,s,c).data;return l.every((e,t)=>e===l[t%4])||(u=o.toDataURL("image/jpeg",.7)).length>12e5?null:u}()}catch(e){}try{e._post({type:"SCREEN_CAPTURED",requestId:n,dataUrl:t})}catch(e){}}}}let f=0;const h={};function _(){return++f}let p=null;function m(){return"undefined"!=typeof window&&window.parent!==window&&/[?&]usion_compose_id=[0-9a-f-]{36}(?:&|$)/i.test(window.location&&window.location.search||"")}function g(e){return"undefined"==typeof window||(!(!window.ReactNativeWebView||m())||(window.parent===window||(!e||!e.source||e.source===window.parent)&&(null===p&&(p=function(){try{if(window.location.ancestorOrigins&&window.location.ancestorOrigins.length)return window.location.ancestorOrigins[0]}catch(e){}try{if("undefined"!=typeof document&&document.referrer)return new URL(document.referrer).origin}catch(e){}return null}()),!(p&&e&&e.origin&&e.origin!==p))))}function y(e){return"string"==typeof e.data?JSON.parse(e.data):e.data}const v={version:"2.39.1",config:{},_initialized:!1,_initCallback:null,_messageHandlerRegistered:!1,_results:[],_backButtonCallback:null,init:function(n,r){const o=this;return n&&"object"==typeof n&&(r=n,n=null),r=r||{},o._initialized?(n&&n(o.config),Promise.resolve(o.config)):(n&&(o._initCallback=n),o._initPromise||(o._initPromise=new Promise(function(e,t){o._initResolve=e,o._initReject=t}),o._initPromise.catch(function(){})),r.timeout>0&&!o._initTimer&&(o._initTimer=setTimeout(function(){o._initTimer=null,!o._initialized&&o._initReject&&o._initReject(new t(e.INIT_TIMEOUT,"No INIT from host within "+r.timeout+"ms — host silent or running standalone"))},r.timeout)),o._messageHandlerRegistered||(o._messageHandlerRegistered=!0,window.addEventListener("message",function(e){if(!g(e))return;let t;try{t=y(e)}catch(e){return}if("INIT"===t.type&&t.config){if(o._initialized)return o.user&&o.user._applyAuth(t.config,!1),void 0!==t.config.sessionId&&o.session&&(o.config.sessionId=o.session._id=t.config.sessionId||null,o.config.sessionData=o.session._data=t.config.sessionData||{}),Array.isArray(t.config.results)&&(o._results=o.config.results=t.config.results),void 0!==t.config.balance&&o.wallet&&(o.wallet._balance=t.config.balance),!0!==t.config.userIsAdult&&!1!==t.config.userIsAdult||!o.user||(o.config.userIsAdult=t.config.userIsAdult,o.user._isAdult=t.config.userIsAdult),void(t.config.hostFeatures&&"object"==typeof t.config.hostFeatures&&(o.config.hostFeatures=t.config.hostFeatures));o.config=t.config,o._initialized=!0,o._isEmbedded=!0,o.user&&o.user._applyAuth(t.config,!1),t.config.sessionId&&(o.session._id=t.config.sessionId,o.session._data=t.config.sessionData||{}),void 0!==t.config.balance&&(o.wallet._balance=t.config.balance),t.config.results&&(o._results=t.config.results),o._initCallback&&o._initCallback(t.config),o._initTimer&&(clearTimeout(o._initTimer),o._initTimer=null),o._initResolve&&o._initResolve(t.config)}if("AUTH_CHANGED"===t.type&&o.user&&o.user._applyAuth(t,!0),"HOST_TAB_BLOCKED"===t.type&&o.tabs&&o.tabs._dispatchBlocked(t),t._requestId&&h[t._requestId]){const{resolve:e,reject:n}=h[t._requestId];delete h[t._requestId],t.error?n(i(t)):e(t)}if("BALANCE_UPDATE"===t.type&&(o.wallet._balance=t.balance,o.wallet._balanceChangeHandler&&o.wallet._balanceChangeHandler(t.balance)),"BACK_BUTTON_PRESSED"===t.type&&o._backButtonCallback){var n=o._backButtonCallback;o._backButtonCallback=null,n()}if("BOT_MESSAGE"===t.type&&o.bot&&o.bot._messageHandler&&o.bot._messageHandler(t.message),"HOST_NAVIGATE"===t.type&&"string"==typeof t.path&&(o.config&&(o.config.launchPath=t.path),o._hostNavigateCallback&&o._hostNavigateCallback({path:t.path,tab:t.tab||null})),"BACKEND_EVENT"===t.type&&t.event&&o._backendHandlers){const e=o._backendHandlers[t.event];e&&e(t.data)}if("CAPTURE_SCREEN"===t.type&&d(o,t),"GAME_ROOM_ASSIGNED"===t.type&&t.roomId&&o.game){var r=t.roomId;o.config.roomId=r,o.config.mode="multiplayer",o.game._dispatch("roomAssigned",{roomId:r}),Promise.resolve().then(function(){return o.game.connect()}).then(function(){return o.game.join(r)}).catch(function(){})}}),this._setupInteractionBeacon(),this._post({type:"READY"})),o._initPromise)},_setupInteractionBeacon:function(){const e=this;if(e._interactionBeaconSetup)return;if(e._interactionBeaconSetup=!0,"undefined"==typeof window||!window.addEventListener)return;const t=["pointerdown","mousedown","touchstart","keydown"];function n(i){if(!(i&&!1===i.isTrusted||e._interactionReported)){e._interactionReported=!0;for(let e=0;e<t.length;e++)try{window.removeEventListener(t[e],n,!0)}catch(e){}e._post({type:"USER_INTERACTION"})}}for(let e=0;e<t.length;e++)try{window.addEventListener(t[e],n,{capture:!0,passive:!0})}catch(i){try{window.addEventListener(t[e],n,!0)}catch(e){}}},getTheme:function(){return this.config.theme||"light"},getLanguage:function(){return this.config.language||"en"},getLaunchParams:function(){var e=this.config||{},t="single"===e.mode||"multiplayer"===e.mode?e.mode:e.roomId?"multiplayer":"single";return{path:e.launchPath||null,ref:e.ref||e.launchRef||null,roomId:e.roomId||null,mode:t}},_post:function(e){const t=JSON.stringify(e);m()?window.parent.postMessage(e,"*"):window.ReactNativeWebView?window.ReactNativeWebView.postMessage(t):window.parent!==window&&window.parent.postMessage(e,"*")},_invalidateAuthRequests:function(){Object.keys(h).forEach(function(n){const i=h[n];i.identityBound&&(delete h[n],i.reject(new t(e.AUTH_CHANGED,"Account changed while request was pending")))})},_request:function(n,i,r){const o=this;return r=r||5e3,new Promise(function(s,c){const a=_(),u=setTimeout(function(){delete h[a],c(new t(e.REQUEST_TIMEOUT,"Request timeout"))},r);h[a]={identityBound:-1===["CONFIGURE_HOST_TABS","OPEN_HOST_TAB","REQUEST_LOGIN","CALL_CAPABILITIES"].indexOf(n),resolve:function(e){clearTimeout(u),s(e)},reject:function(e){clearTimeout(u),c(e)}},o._post({type:n,_requestId:a,...i})})}};var I="_d:",E="_migrated_v2";function w(e){return I+e}function b(e,t,n){return e._backendEmit(t,Object.assign({service_id:e.config&&e.config.serviceId,scope:"storage"},n))}function T(e,t){return e._request("STORAGE_GET",{key:t}).then(function(e){return e?e.value:null})}function S(e,t,n){return e._request("STORAGE_SET",{key:t,value:n})}function A(e,t){return e._request("STORAGE_REMOVE",{key:t})}function O(e){return e._request("STORAGE_KEYS",{}).then(function(e){return e&&e.keys||[]})}function C(e){return e.catch(function(){})}const k={setLoading:function(e,t){const n="string"==typeof e?document.querySelector(e):e;n&&(t?(n.classList.add("usion-btn-loading"),n.disabled=!0,n.dataset.originalText=n.textContent):(n.classList.remove("usion-btn-loading"),n.disabled=!1,n.dataset.originalText&&(n.textContent=n.dataset.originalText)))},toggle:function(e,t){const n="string"==typeof e?document.querySelector(e):e;n&&(t?(n.classList.remove("usion-hidden","hidden"),n.classList.add("usion-visible")):(n.classList.add("usion-hidden"),n.classList.remove("usion-visible")))},charCount:function(e,t,n){const i="string"==typeof e?document.querySelector(e):e,r="string"==typeof t?document.querySelector(t):t;function o(){const e=i.value.length;r.textContent=e+" / "+n,r.classList.remove("warning","error"),e>.9*n?r.classList.add("error"):e>.7*n&&r.classList.add("warning")}i&&r&&(i.addEventListener("input",o),o())},selectionGrid:function(e,t,n){const i=document.querySelector(e);if(!i)return;let r=null;return i.querySelectorAll(t).forEach(function(e){e.addEventListener("click",function(){i.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),e.classList.add("selected"),r=e.dataset.value||e.dataset.id,n&&n(r,e)})}),{getSelected:function(){return r},clear:function(){i.querySelectorAll(t).forEach(function(e){e.classList.remove("selected")}),r=null}}}},N={requestPayment:function(e,t,n){return this.wallet.requestPayment(e,t,n)},diagnostics:function(){const e=this.game||{};return{version:this.version,transport:e.directMode?"direct":e._useProxy?"proxy":e.socket?"socket":"none",connected:!!e.connected,joined:!!e._joined,roomId:e.roomId||null,playerId:e.playerId||null,lastSequence:e._lastSequence||0,lastActionApplied:e._lastActionApplied||0,rejoining:!!e._rejoinPromise}},submit:function(e){this._post({type:"SUBMIT",data:e})},error:function(e){this._post({type:"ERROR",message:e})},exit:function(e){var t={type:"EXIT"};e&&"number"==typeof e.backCount&&e.backCount>1&&(t.backCount=e.backCount),this._post(t)},share:function(e,t){var n=Object.assign({},t,{contentType:e,serviceId:this.config.serviceId,serviceName:this.config.serviceName});this._post({type:"SHARE",contentType:e,data:n})},shareFile:function(e,t){var n={url:e};return(t=t||{}).filename&&(n.filename=t.filename),t.mimeType&&(n.mimeType=t.mimeType),t.title&&(n.title=t.title),t.text&&(n.text=t.text),this._request("SHARE_FILE",n,12e4)},shareToStory:function(e,t){var n={url:e};return(t=t||{}).filename&&(n.filename=t.filename),t.mimeType&&(n.mimeType=t.mimeType),t.stickerUrl&&(n.stickerUrl=t.stickerUrl),t.backgroundTopColor&&(n.backgroundTopColor=t.backgroundTopColor),t.backgroundBottomColor&&(n.backgroundBottomColor=t.backgroundBottomColor),t.title&&(n.title=t.title),t.text&&(n.text=t.text),this._request("SHARE_TO_STORY",n,12e4)},download:function(e,t,n){t&&"object"==typeof t&&(t=(n=t).filename),n=n||{};var i={url:e,filename:t||n.filename||"download.mp4"};return n.mimeType&&(i.mimeType=n.mimeType),n.destination&&(i.destination=n.destination),n.title&&(i.title=n.title),this._request("DOWNLOAD_FILE",i,12e4)},log:function(e){this._post({type:"LOG",msg:e}),console.log("[Usion]",e)},on:function(e,t){function n(n){if(!g(n))return;let i;try{i=y(n)}catch(e){return}i.type===e&&t(i)}return window.addEventListener("message",n),function(){window.removeEventListener("message",n)}}};var P=/[\x00-\x1f\x7f\s\\]/;function R(e){return"string"!=typeof e?"path must be a string":e.length>512?"path too long (max 512)":"/"!==e.charAt(0)||"/"===e.charAt(1)?"path must be a relative in-app path starting with a single '/'":-1!==e.indexOf("://")||P.test(e)?"path contains illegal characters":null}function M(e){return Array.from(e).length}var q=5242880,D=/^data:image\/(png|jpeg|webp);base64,/,U=/^[A-Za-z0-9+/]+={0,2}$/;function L(){var e="undefined"!=typeof globalThis?globalThis.crypto:void 0;if(e&&"function"==typeof e.randomUUID)return e.randomUUID();var t=new Array(16);if(e&&"function"==typeof e.getRandomValues){var n=new Uint8Array(16);e.getRandomValues(n);for(var i=0;i<16;i++)t[i]=n[i]}else for(var r=0;r<16;r++)t[r]=Math.floor(256*Math.random());t[6]=15&t[6]|64,t[8]=63&t[8]|128;var o=t.map(function(e){return(e+256).toString(16).slice(1)}).join("");return o.slice(0,8)+"-"+o.slice(8,12)+"-"+o.slice(12,16)+"-"+o.slice(16,20)+"-"+o.slice(20)}const j={canShareToFeed:function(e){var t=this.config&&this.config.hostFeatures;return!(!t||!0!==t.feedShare)&&("image"===e?!0===t.feedShareImage:"video"===e?!0===t.feedShareVideo:"videoUpload"===e?!0===t.feedShareVideoUpload:!e)},uploadFeedVideo:async function(n,i){if(!this.canShareToFeed("videoUpload"))throw new t(e.UNSUPPORTED,"Video uploads require a newer host");if(!n||"number"!=typeof n.size||"function"!=typeof n.slice||n.size<=0||n.size>3221225472||["video/mp4","video/quicktime","video/webm","video/x-matroska"].indexOf(n.type)<0)throw new t(e.INVALID_INPUT,"Choose a supported video of at most 3 GiB");var r=this,o=this.config||{},s=i||{};if(!(r.user&&r.user.getToken()&&o.serviceId&&o.apiUrl))throw new t(e.NOT_AUTHENTICATED,"Sign in to upload");var c=o.apiUrl.replace(/\/$/,"")+"/feed/video-uploads/"+encodeURIComponent(o.serviceId)+"/multipart",a=null;async function u(n,i,o,c){var a={Authorization:"Bearer "+r.user.getToken()};c&&(a["Content-Type"]=c);var u=await fetch(n,{method:i,headers:a,body:o,signal:s.signal});if(!u.ok)throw new t(429===u.status?e.RATE_LIMITED:401===u.status?e.NOT_AUTHENTICATED:403===u.status?e.PERMISSION_DENIED:u.status<500?e.INVALID_INPUT:e.UNKNOWN,"Video upload failed");return u.json()}function l(e){if("function"==typeof s.onProgress)try{s.onProgress({loaded:e,total:n.size})}catch(e){}}try{var d=await u(c,"POST",JSON.stringify({request_id:s.requestId||L(),file_size:n.size,file_type:n.type}),"application/json");if("string"!=typeof(a=d.file_id)||!a)throw new t(e.UNKNOWN,"Invalid upload session");var f=c+"/"+encodeURIComponent(a);if("ready"!==(d=await u(f,"GET")).status&&"completing"!==d.status){var h=d.part_size,_=new Set(d.uploaded_parts||[]),p=0;if(!Number.isInteger(h)||h<1)throw new t(e.UNKNOWN,"Invalid upload part size");for(var m=1,g=0;g<n.size;m++,g+=h){var y=n.slice(g,Math.min(g+h,n.size));if(!_.has(m))for(var v=0;;v++)try{await u(f+"/parts/"+m,"PUT",y,"application/octet-stream");break}catch(n){if(s.signal&&s.signal.aborted)throw n;if(v>=2||n instanceof t&&n.code!==e.UNKNOWN)throw n;await new Promise(function(e){setTimeout(e,500*(v+1))})}l(p+=y.size)}}var I=await u(f+"/complete","POST");if(!I||"string"!=typeof I.receipt)throw new t(e.UNKNOWN,"Invalid upload response");return l(n.size),{receipt:I.receipt}}catch(n){if(s.signal&&s.signal.aborted&&a){try{await fetch(c+"/"+encodeURIComponent(a),{method:"DELETE",headers:{Authorization:"Bearer "+r.user.getToken()}})}catch(e){}throw new t(e.CANCELLED,"Video upload cancelled")}throw n}},shareToFeed:function(n,i){if(i=i||{},"video"===n&&null==i.video&&null==i.videoReceipt)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: video is required"));var r="string"==typeof i.text?i.text.trim():"";if(!r)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: text is required"));var o={contentType:n||"text",text:r,requestId:"string"==typeof i.requestId&&i.requestId?i.requestId:L(),serviceId:this.config&&this.config.serviceId,serviceName:this.config&&this.config.serviceName};if(null!=i.path&&""!==i.path){var s=R(i.path);if(s)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+s));o.path=i.path}if(null!=i.card){var c=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{error:"card must be an object"};var t="string"==typeof e.title?e.title.trim():"";if(!t)return{error:"card.title is required"};if(M(t)>200)return{error:"card.title too long (max 200)"};var n={title:t};if(null!=e.subtitle){if("string"!=typeof e.subtitle)return{error:"card.subtitle must be a string"};var i=e.subtitle.trim();if(M(i)>60)return{error:"card.subtitle too long (max 60)"};i&&(n.subtitle=i)}return{card:n}}(i.card);if("error"in c)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+c.error));o.card=c.card}if(null!=i.image){var a=function(e){var t="string"==typeof e&&D.exec(e);if(!t)return"image must be a data:image/(png|jpeg|webp);base64 URL";var n=e.slice(t[0].length),i="=="===n.slice(-2)?2:"="===n.slice(-1)?1:0;return Math.floor(3*n.length/4)-i>q?"image too large (max 5 MB)":n.length%4==0&&U.test(n)?null:"image is not valid base64"}(i.image);if(a)return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: "+a));o.image=i.image}if(null!=i.video){if(null!=i.image||"string"!=typeof i.video||!/^data:video\/mp4;base64,/.test(i.video))return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: video must be an MP4 data URL without an image"));var u=i.video.slice(22),l="=="===u.slice(-2)?2:"="===u.slice(-1)?1:0;if(!u||u.length%4!=0||3*u.length/4-l>q||!U.test(u))return Promise.reject(new t(e.INVALID_INPUT,"shareToFeed: invalid video or video exceeds 5 MB"));if(!this.canShareToFeed("video"))return Promise.reject(new t(e.UNSUPPORTED,"shareToFeed: host does not support video"));o.video=i.video}if(null!=i.videoReceipt){if(null!=i.video||null!=i.image||"string"!=typeof i.videoReceipt||!i.videoReceipt||i.videoReceipt.length>8192)return Promise.reject(new t(e.INVALID_INPUT,"Invalid video receipt"));if(!this.canShareToFeed("videoUpload"))return Promise.reject(new t(e.UNSUPPORTED,"Video uploads require a newer host"));o.videoReceipt=i.videoReceipt}return this._request("SHARE_TO_FEED",o,6e5).then(function(e){return Object.assign({success:!0},e)})},openApp:function(n,i){if("string"!=typeof n||!n.trim())throw new t(e.INVALID_INPUT,"openApp: serviceId is required");var r={type:"OPEN_SERVICE",serviceId:n.trim()};if(null!=i&&""!==i){var o=R(i);if(o)throw new t(e.INVALID_INPUT,"openApp: "+o);r.path=i}this._post(r)}};function x(e,t){var n={liveness:{probeAfterMs:4e3,deadAfterMs:12e3},backpressureBytes:8192,lastInboundAt:0,lastProbeAt:0,lastWatchdogAt:0,livenessGraceUntil:0,lastCloseCode:null,declaredDead:!1,watchdogTimer:null,drainTimer:null,pendingInput:null,visHandler:null,lastVisResyncAt:0,wrappedDisconnect:!1,rtt:null,jitter:0,quality:"dead"};function i(){if(null!=n.rtt)return{rtt:n.rtt,jitter:n.jitter};var t=e._pingMeter;return t&&null!=t.rtt?{rtt:t.rtt,jitter:t.jitter}:{rtt:null,jitter:null}}function r(){var t=function(){var t=e.getConnectionState?e.getConnectionState():e.connected?"connected":"disconnected";if(n.declaredDead||"disconnected"===t)return"dead";if(e.directMode&&(!e.directSocket||1!==e.directSocket.readyState))return"dead";var r=i().rtt||0,o=e.directMode&&n.lastInboundAt?Date.now()-n.lastInboundAt:0;return r<150&&o<2e3?"good":r<400&&o<5e3?"fair":"poor"}();if(t!==n.quality){var r=n.quality;n.quality=t,e._dispatch("networkQuality",{quality:t,prev:r,stats:e.getNetworkStats()})}}function o(){n.watchdogTimer&&(clearInterval(n.watchdogTimer),n.watchdogTimer=null)}function s(){var t=e.directSocket;if(t&&1===t.readyState){var i=Date.now(),r=function(){};r.sentAt=i,r.statsOnly=!0,e._pongWaiters.push(r),n.lastProbeAt=i,e._sendDirect("ping",{t:i})}}function c(){var i=e.directSocket;if(e.directMode&&i&&1===i.readyState){if(n.liveness){var c=Date.now(),a=n.lastWatchdogAt&&c-n.lastWatchdogAt>2e3;if(n.lastWatchdogAt=c,"undefined"!=typeof document&&"hidden"===document.visibilityState)return void(n.livenessGraceUntil=c+n.liveness.deadAfterMs);if(a)return n.livenessGraceUntil=c+n.liveness.deadAfterMs,s(),void r();var u=c-n.lastInboundAt;if(u>=n.liveness.deadAfterMs&&c>=n.livenessGraceUntil){n.declaredDead=!0,o(),t.log("Direct socket liveness timeout - declaring dead"),r(),e._dispatch("disconnect","liveness_timeout");try{i.close()}catch(e){}return}u>=n.liveness.probeAfterMs&&c-n.lastProbeAt>=n.liveness.probeAfterMs&&s()}r()}else o()}function a(){n.drainTimer=null;var t=e.directSocket;if(t&&1===t.readyState){if(null!=n.pendingInput)if(t.bufferedAmount>n.backpressureBytes)n.drainTimer=setTimeout(a,50);else{var i=n.pendingInput;n.pendingInput=null,e._sendDirect("input",i)}}else n.pendingInput=null}function u(){o(),n.drainTimer&&(clearTimeout(n.drainTimer),n.drainTimer=null),n.pendingInput=null,function(){n.visHandler&&"undefined"!=typeof document&&document.removeEventListener&&document.removeEventListener("visibilitychange",n.visHandler);n.visHandler=null}(),e._pongWaiters&&e._pongWaiters.length&&(e._pongWaiters=e._pongWaiters.filter(function(e){return!e.statsOnly}))}e._res=n,e.getNetworkStats=function(){var t=!!e.directMode,r=t?e.directSocket:null,o=i();return{transport:t?"direct":"relay",connectionState:e.getConnectionState?e.getConnectionState():"disconnected",quality:n.quality,rtt:o.rtt,jitter:o.jitter,lastInboundAgeMs:t&&n.lastInboundAt?Math.max(0,Date.now()-n.lastInboundAt):null,bufferedAmount:r?r.bufferedAmount||0:null}},e.onNetworkQuality=function(t){return e._setHandler("networkQuality",t)},e._resConfigure=function(e){if(!1===e.liveness)n.liveness=null;else{var t=e.liveness&&"object"==typeof e.liveness?e.liveness:{},i=isFinite(t.probeAfterMs)?Math.max(1e3,t.probeAfterMs):4e3,r=isFinite(t.deadAfterMs)?t.deadAfterMs:12e3;n.liveness={probeAfterMs:i,deadAfterMs:Math.max(r,i+2e3)}}!1===e.backpressureBytes||0===e.backpressureBytes?n.backpressureBytes=0:"number"==typeof e.backpressureBytes&&e.backpressureBytes>0&&(n.backpressureBytes=e.backpressureBytes)},e._resOnOpen=function(){if(n.declaredDead=!1,n.lastCloseCode=null,n.lastInboundAt=Date.now(),n.lastProbeAt=0,n.lastWatchdogAt=Date.now(),n.livenessGraceUntil=0,o(),n.watchdogTimer=setInterval(c,1e3),function(){if("undefined"==typeof document||!document.addEventListener||n.visHandler)return;n.visHandler=function(){if("visible"===document.visibilityState&&e.directMode&&e._joined){var t=Date.now();if(n.liveness&&(n.livenessGraceUntil=t+n.liveness.deadAfterMs),n.lastWatchdogAt=t,n.lastProbeAt=0,s(),t-n.lastVisResyncAt>=2e3){n.lastVisResyncAt=t;try{e.requestSync(e._lastSequence||0)}catch(e){}}}},document.addEventListener("visibilitychange",n.visHandler)}(),!n.wrappedDisconnect){n.wrappedDisconnect=!0;var t=e.disconnect;e.disconnect=function(){return u(),t.apply(e,arguments)}}r()},e._resOnClose=function(e){n.lastCloseCode=e&&"number"==typeof e.code?e.code:null,u(),r()},e._resOnPong=function(e){e&&"number"==typeof e.sentAt&&function(e){if(e>=0){if(null==n.rtt)return n.rtt=e,void(n.jitter=0);n.jitter+=.3*(Math.abs(e-n.rtt)-n.jitter),n.rtt+=.3*(e-n.rtt)}}(Date.now()-e.sentAt),r()},e._resCanReuseToken=function(){if(4401===n.lastCloseCode)return!1;var t=e.directConfig;if(!t||!t.ws_url||!t.access_token)return!1;var i=function(e){if("number"==typeof e&&isFinite(e))return e>1e12?e:1e3*e;if("string"==typeof e&&e){var t=Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(e)?e:e+"Z");return isNaN(t)?null:t}return null}(t.expires_at);return null!=i&&i-Date.now()>3e4},e._resHoldInput=function(t){if(!n.backpressureBytes)return!1;var i=e.directSocket;return!(!i||!(null!=n.pendingInput||i.bufferedAmount>n.backpressureBytes))&&(n.pendingInput=t,n.drainTimer||(n.drainTimer=setTimeout(a,50)),!0)},e.on("disconnect",r),e.on("connectionState",r)}function B(n,i,r,o,s){return o=o||1e4,s=s||e.REQUEST_TIMEOUT,new Promise(function(c,a){let u=!1;const l=setTimeout(function(){u||(u=!0,a(new t(s,s===e.JOIN_TIMEOUT?"Join timeout":"Game request timeout")))},o);try{n.emit(i,r,function(e){u||(u=!0,clearTimeout(l),c(e||{}))})}catch(e){if(u)return;u=!0,clearTimeout(l),a(e)}})}function H(e,t){return e._joinPromise=t,t.catch(function(){e._joined=!1,e._joinPromise===t&&(e._joinPromise=null)}),t}function V(e,t,n){let i=(t-e)%n;const r=n/2;return i>r&&(i-=n),i<-r&&(i+=n),i}function F(e,t,n,i){return"deg"===i?e+V(e,t,360)*n:"rad"===i?e+V(e,t,2*Math.PI)*n:e+(t-e)*n}class G{constructor(e=120){this._items=[],this._maxSize=e}add(e){this._items.push(e),this._items.length>this._maxSize&&this._items.shift()}get size(){return this._items.length}setMaxSize(e){this._maxSize=Math.max(2,0|e)}latest(){return this._items.length?this._items[this._items.length-1]:null}prevLatest(){return this._items.length>=2?this._items[this._items.length-2]:null}clear(){this._items=[]}straddle(e){const t=this._items;if(0===t.length)return[null,null];if(1===t.length)return[t[0],t[0]];if(e<=t[0].time)return[t[0],t[0]];const n=t[t.length-1];if(e>=n.time)return[n,n];for(let n=t.length-1;n>0;n--)if(t[n-1].time<=e&&e<=t[n].time)return[t[n-1],t[n]];return[n,n]}}function W(e,t){return t?Array.isArray(e[t])?e[t]:[]:Array.isArray(e)?e:[]}class z{constructor(e={}){const t=e.serverFps||20;this._frameMs=1e3/t,this.vault=new G(e.maxSize||120),this._fixedBuffer=null!=e.bufferMs?e.bufferMs:Math.ceil(3*this._frameMs),this._bufferMs=this._fixedBuffer,this._adaptive=!!e.adaptive,this._minBuffer=null!=e.minBufferMs?e.minBufferMs:Math.ceil(2*this._frameMs),this._maxBuffer=null!=e.maxBufferMs?e.maxBufferMs:Math.ceil(8*this._frameMs),this._extrapolationMs=e.extrapolationMs||0,this._useServerTime=!!e.serverTime,this._now=e.now||(()=>Date.now()),this._lastArrival=null,this._avgInterval=this._frameMs,this._jitter=0,this._offset=null}getBufferMs(){return this._bufferMs}setBufferMs(e){this._fixedBuffer=Math.max(0,0|e),this._bufferMs=this._fixedBuffer}getJitter(){return this._jitter}add(e){if(!e)return;const t=this._now(),n=void 0!==e.state?e.state:e,i=e.time;if(null!=this._lastArrival){const e=t-this._lastArrival;if(this._avgInterval+=.1*(e-this._avgInterval),this._jitter+=.1*(Math.abs(e-this._avgInterval)-this._jitter),this._adaptive){const e=this._avgInterval+2*this._jitter;this._bufferMs=Math.max(this._minBuffer,Math.min(this._maxBuffer,e))}}if(this._lastArrival=t,this._useServerTime&&"number"==typeof i){const e=t-i;this._offset=null==this._offset?e:this._offset+.05*(e-this._offset)}const r=this._useServerTime&&"number"==typeof i?i:t;this.vault.add({time:r,state:n})}_renderTime(){return this._useServerTime&&null!=this._offset?this._now()-this._offset-this._bufferMs:this._now()-this._bufferMs}calc(e,t){const n=this._renderTime(),i=this.vault.latest();if(!i)return null;const r=String(e||"").trim().split(/\s+/).filter(Boolean).map(e=>{const t=e.match(/^(.+?)\((deg|rad)\)$/);return t?{key:t[1],type:t[2]}:{key:e,type:"linear"}});if(n>i.time)return this._extrapolationMs>0?this._extrapolate(n,r,t):W(i.state,t).map(e=>Object.assign({},e));const[o,s]=this.vault.straddle(n);if(!o||!s)return null;let c=0;return s.time!==o.time&&(c=(n-o.time)/(s.time-o.time),c=c<0?0:c>1?1:c),this._blend(W(o.state,t),W(s.state,t),c,r)}_blend(e,t,n,i){const r={};for(let t=0;t<e.length;t++)r[e[t].id]=e[t];return t.map(e=>{const t=r[e.id],o=Object.assign({},e);if(t)for(let r=0;r<i.length;r++){const{key:s,type:c}=i[r],a=t[s],u=e[s];"number"==typeof a&&"number"==typeof u&&(o[s]=F(a,u,n,c))}return o})}_extrapolate(e,t,n){const i=this.vault.latest(),r=this.vault.prevLatest(),o=W(i.state,n);if(!r||i.time<=r.time)return o.map(e=>Object.assign({},e));const s=Math.min(e-i.time,this._extrapolationMs),c=i.time-r.time,a={},u=W(r.state,n);for(let e=0;e<u.length;e++)a[u[e].id]=u[e];return o.map(e=>{const n=a[e.id],i=Object.assign({},e);if(n)for(let r=0;r<t.length;r++){const{key:o}=t[r],a=n[o],u=e[o];if("number"==typeof a&&"number"==typeof u){const e=(u-a)/c;i[o]=u+e*s}}return i})}}class J{constructor(e={}){if("function"!=typeof e.apply)throw new Error("Predictor requires an apply(state, input) function");this._apply=e.apply,this._state=void 0!==e.initialState?e.initialState:null,this._seq=0,this._pending=[],this._smoothKeys=function(e){if(!e)return null;let t=null!=e.keys?e.keys:e;return"string"==typeof t&&(t=t.trim().split(/\s+/).filter(Boolean)),Array.isArray(t)&&t.length?t:null}(e.smooth),this._smoothRate=e.smooth&&null!=e.smooth.rate?e.smooth.rate:.2,this._snapTo=e.smooth&&null!=e.smooth.snapTo?e.smooth.snapTo:.001,this._error={}}get state(){return this._state}get pending(){return this._pending.slice()}get lastSeq(){return this._seq}predict(e){this._seq+=1;const t=this._seq;return this._pending.push({seq:t,input:e}),this._state=this._apply(this._state,e),{seq:t,state:this._state}}reconcile(e,t){const n=this._state,i=null==t?-1:t;this._pending=this._pending.filter(e=>e.seq>i);let r=e;for(let e=0;e<this._pending.length;e++)r=this._apply(r,this._pending[e].input);if(this._smoothKeys&&n&&r)for(let e=0;e<this._smoothKeys.length;e++){const t=this._smoothKeys[e];"number"==typeof n[t]&&"number"==typeof r[t]&&(this._error[t]=(this._error[t]||0)+(n[t]-r[t]))}return this._state=r,this._state}view(e){if(!this._smoothKeys||!this._state||"object"!=typeof this._state)return this._state;const t=null!=e?e:this._smoothRate,n=Array.isArray(this._state)?this._state.slice():Object.assign({},this._state);for(let e=0;e<this._smoothKeys.length;e++){const i=this._smoothKeys[e];let r=this._error[i]||0;"number"==typeof n[i]&&0!==r&&(n[i]=n[i]+r),r*=1-t,Math.abs(r)<this._snapTo&&(r=0),this._error[i]=r}return n}reset(e){this._state=void 0!==e?e:null,this._seq=0,this._pending=[],this._error={}}}class Q{constructor(e={}){if("function"!=typeof e.onFlush)throw new Error("Coalescer requires an onFlush(entries) callback");this._onFlush=e.onFlush,this._hz=e.hz||20,this._setInterval=e.setInterval||("undefined"!=typeof setInterval?setInterval:null),this._clearInterval=e.clearInterval||("undefined"!=typeof clearInterval?clearInterval:null),this._order=[],this._slots={},this._timer=null,!1!==e.autoStart&&this.start()}get running(){return null!==this._timer}_ensure(e,t){let n=this._slots[e];return n||(n={mode:t,value:void 0,list:[]},this._slots[e]=n,this._order.push(e)),n}queue(e,t){const n=this._ensure(e,"latest");n.mode="latest",n.value=t}append(e,t){const n=this._ensure(e,"list");n.mode="list",n.list.push(t)}drain(){const e=[];for(let t=0;t<this._order.length;t++){const n=this._order[t],i=this._slots[n];if("latest"===i.mode)void 0!==i.value&&e.push({type:n,data:i.value});else for(let t=0;t<i.list.length;t++)e.push({type:n,data:i.list[t]})}return this._order=[],this._slots={},e}flush(){if(0===this._order.length)return;const e=this.drain();e.length&&this._onFlush(e)}start(){!this._timer&&this._setInterval&&(this._timer=this._setInterval(()=>this.flush(),Math.max(1,Math.round(1e3/this._hz))))}stop(){this._timer&&this._clearInterval&&this._clearInterval(this._timer),this._timer=null}}class K{constructor(e={}){this._alpha=null!=e.alpha?e.alpha:.2,this._now=e.now||(()=>Date.now()),this._rtt=null,this._jitter=0,this._last=null,this._id=0,this._outstanding={}}get rtt(){return this._rtt}get latency(){return null==this._rtt?null:this._rtt/2}get jitter(){return this._jitter}get last(){return this._last}begin(){const e=++this._id;return this._outstanding[e]=this._now(),e}end(e){const t=this._outstanding[e];return null==t?null:(delete this._outstanding[e],this.sample(this._now()-t))}sample(e){return e>=0?(null==this._rtt?this._rtt=e:(this._jitter+=this._alpha*(Math.abs(e-this._rtt)-this._jitter),this._rtt+=this._alpha*(e-this._rtt)),this._last=e,e):null}reset(){this._rtt=null,this._jitter=0,this._last=null,this._outstanding={}}}const Y=[{urls:"stun:stun.l.google.com:19302"}];function $(e){return e instanceof ArrayBuffer||ArrayBuffer.isView(e)}class X{constructor(e={}){if("host"!==e.role&&"guest"!==e.role)throw new Error("MeshConnection requires role 'host' or 'guest'");if("function"!=typeof e.sendSignal)throw new Error("MeshConnection requires a sendSignal(payload) function");this.role=e.role,this._sendSignal=e.sendSignal,this._iceServers=e.iceServers||Y,this._sequenced=!1!==e.sequenced,this._autoReconnect=!1!==e.autoReconnect,this._maxRestarts=null!=e.maxRestarts?e.maxRestarts:5,this._RTCPeerConnection=e.RTCPeerConnection||("undefined"!=typeof RTCPeerConnection?RTCPeerConnection:null),this._setTimeout=e.setTimeout||("undefined"!=typeof setTimeout?setTimeout:null),this.connected=!1,this._pc=null,this._unreliable=null,this._reliable=null,this._sendSeq=0,this._recvSeq=0,this._restarts=0,this.onOpen=null,this.onMessage=null,this.onClose=null,this.onError=null,this.onStateChange=null}static iceServers(e={}){const t=[{urls:e.stun||"stun:stun.l.google.com:19302"}];if(e.turn){const n={urls:e.turn};e.turnUsername&&(n.username=e.turnUsername),e.turnCredential&&(n.credential=e.turnCredential),t.push(n)}return t}async start(){if(!this._RTCPeerConnection)throw new Error("RTCPeerConnection unavailable");const e=new this._RTCPeerConnection({iceServers:this._iceServers});this._pc=e,e.onicecandidate=e=>{e&&e.candidate&&this._sendSignal({type:"ice",candidate:e.candidate})};const t=()=>this._handleStateChange(e.connectionState||e.iceConnectionState);e.onconnectionstatechange=t,e.oniceconnectionstatechange=t,"host"===this.role?(this._bindChannel(this._unreliable=e.createDataChannel("unreliable",{ordered:!1,maxRetransmits:0}),"unreliable"),this._bindChannel(this._reliable=e.createDataChannel("reliable",{ordered:!0}),"reliable"),await this._makeOffer(!1)):e.ondatachannel=e=>{const t=e.channel;"unreliable"===t.label?this._bindChannel(this._unreliable=t,"unreliable"):"reliable"===t.label&&this._bindChannel(this._reliable=t,"reliable")}}async _makeOffer(e){const t=this._pc,n=await t.createOffer(e?{iceRestart:!0}:void 0);await t.setLocalDescription(n),this._sendSignal({type:"offer",sdp:t.localDescription,restart:!!e})}_handleStateChange(e){if(this.onStateChange&&this.onStateChange(e),"connected"!==e){if(("failed"===e||"disconnected"===e||"closed"===e)&&(this.connected&&(this.connected=!1,this.onClose&&this.onClose()),this._autoReconnect&&"host"===this.role&&"closed"!==e&&this._restarts<this._maxRestarts)){this._restarts+=1;const e=Math.min(1e3*this._restarts,5e3);this._setTimeout&&this._setTimeout(()=>{this._makeOffer(!0).catch(e=>{this.onError&&this.onError(e)})},e)}}else this._restarts=0}async handleSignal(e){const t=this._pc;if(t&&e&&e.type)try{if("offer"===e.type){await t.setRemoteDescription(e.sdp);const n=await t.createAnswer();await t.setLocalDescription(n),this._sendSignal({type:"answer",sdp:t.localDescription})}else"answer"===e.type?await t.setRemoteDescription(e.sdp):"ice"===e.type&&e.candidate&&await t.addIceCandidate(e.candidate)}catch(e){this.onError&&this.onError(e)}}_bindChannel(e,t){e.binaryType="arraybuffer",e.onopen=()=>{"unreliable"!==t||this.connected||(this.connected=!0,this.onOpen&&this.onOpen())},e.onmessage=e=>{if(!this.onMessage)return;let n=e.data;if($(n))this.onMessage(n,t);else{try{n="string"==typeof n?JSON.parse(n):n}catch(n){return void this.onMessage(e.data,t)}if("unreliable"===t&&this._sequenced&&n&&"number"==typeof n.__s){if(n.__s<=this._recvSeq)return;return this._recvSeq=n.__s,void this.onMessage(n.m,t)}this.onMessage(n,t)}},e.onclose=()=>{this.connected&&(this.connected=!1,this.onClose&&this.onClose())},e.onerror=e=>{this.onError&&this.onError(e)}}send(e){const t=this._unreliable;return!(!t||"open"!==t.readyState)&&($(e)?(t.send(e),!0):(this._sequenced?(this._sendSeq+=1,t.send(JSON.stringify({__s:this._sendSeq,m:e}))):t.send("string"==typeof e?e:JSON.stringify(e)),!0))}sendReliable(e){const t=this._reliable;return!(!t||"open"!==t.readyState)&&($(e)?t.send(e):t.send("string"==typeof e?e:JSON.stringify(e)),!0)}close(){try{this._unreliable&&this._unreliable.close()}catch(e){}try{this._reliable&&this._reliable.close()}catch(e){}try{this._pc&&this._pc.close()}catch(e){}this._unreliable=this._reliable=this._pc=null,this.connected=!1}}class Z{constructor(e={}){if(!e.selfId)throw new Error("MeshNetwork requires a selfId");if("function"!=typeof e.sendSignal)throw new Error("MeshNetwork requires sendSignal(toPeerId, payload)");this.selfId=e.selfId,this._sendSignal=e.sendSignal,this._opts=e,this._peers={},this.onPeerOpen=null,this.onPeerClose=null,this.onMessage=null,this.onError=null}get peerIds(){return Object.keys(this._peers)}get connectedCount(){let e=0;for(const t in this._peers)this._peers[t].connected&&(e+=1);return e}peer(e){return this._peers[e]||null}_roleFor(e){return this.selfId<e?"host":"guest"}_ensurePeer(e){if(this._peers[e])return this._peers[e];const t=this,n=new X({role:this._roleFor(e),iceServers:this._opts.iceServers,RTCPeerConnection:this._opts.RTCPeerConnection,setTimeout:this._opts.setTimeout,sequenced:this._opts.sequenced,autoReconnect:this._opts.autoReconnect,sendSignal:n=>t._sendSignal(e,n)});return n.onOpen=()=>{t.onPeerOpen&&t.onPeerOpen(e)},n.onClose=()=>{t.onPeerClose&&t.onPeerClose(e)},n.onMessage=(n,i)=>{t.onMessage&&t.onMessage(e,n,i)},n.onError=n=>{t.onError&&t.onError(e,n)},this._peers[e]=n,n}async addPeer(e){if(e===this.selfId)return null;const t=this._ensurePeer(e);return await t.start(),t}async setRoster(e){const t={};for(let n=0;n<e.length;n++)e[n]!==this.selfId&&(t[e[n]]=!0);for(const e in t)this._peers[e]||await this.addPeer(e);for(const e in this._peers)t[e]||this.removePeer(e)}removePeer(e){const t=this._peers[e];if(t){try{t.close()}catch(e){}delete this._peers[e]}}async handleSignal(e,t){if(!e||e===this.selfId)return;const n=this._ensurePeer(e);n._pc||await n.start(),await n.handleSignal(t)}send(e,t){const n=this._peers[e];return!!n&&n.send(t)}sendReliable(e,t){const n=this._peers[e];return!!n&&n.sendReliable(t)}broadcast(e){for(const t in this._peers)this._peers[t].send(e)}broadcastReliable(e){for(const t in this._peers)this._peers[t].sendReliable(e)}close(){for(const e in this._peers)try{this._peers[e].close()}catch(e){}this._peers={}}}const ee="undefined"!=typeof TextEncoder?new TextEncoder:null,te="undefined"!=typeof TextDecoder?new TextDecoder:null;function ne(e){return(t=e)instanceof ArrayBuffer||ArrayBuffer.isView(t)?{type:0,bytes:e instanceof Uint8Array?e:new Uint8Array(e.buffer||e)}:{type:1,bytes:(n=JSON.stringify(e),ee?ee.encode(n):Uint8Array.from(Buffer.from(n,"utf8")))};var t,n}function ie(e,t){if(1===e)try{return JSON.parse((n=t,te?te.decode(n):Buffer.from(n).toString("utf8")))}catch(e){return null}var n;return t}class re{constructor(){this._buf=new Uint8Array(0)}push(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),n=new Uint8Array(this._buf.length+t.length);n.set(this._buf,0),n.set(t,this._buf.length),this._buf=n;const i=[];for(;this._buf.length>=4;){const e=new DataView(this._buf.buffer,this._buf.byteOffset,4).getUint32(0,!1);if(this._buf.length<4+e)break;const t=this._buf[4],n=this._buf.subarray(5,4+e);i.push(ie(t,n.slice())),this._buf=this._buf.subarray(4+e)}return i}}class oe{constructor(e={}){if(!e.url)throw new Error("WebTransportConnection requires a url");this._url=e.url,this._opts=e,this._sequenced=!1!==e.sequenced,this._WT=e.WebTransport||("undefined"!=typeof WebTransport?WebTransport:null),this.connected=!1,this._t=null,this._dgWriter=null,this._streamWriter=null,this._deframer=new re,this._sendSeq=0,this._recvSeq=0,this.onOpen=null,this.onMessage=null,this.onClose=null,this.onError=null}async connect(){if(!this._WT)throw new Error("WebTransport unavailable in this environment");const e={};this._opts.serverCertificateHashes&&(e.serverCertificateHashes=this._opts.serverCertificateHashes);const t=new this._WT(this._url,e);if(this._t=t,t.ready&&"function"==typeof t.ready.then&&await t.ready,t.datagrams&&t.datagrams.writable&&(this._dgWriter=t.datagrams.writable.getWriter()),"function"==typeof t.createBidirectionalStream)try{const e=await t.createBidirectionalStream();this._streamWriter=e.writable.getWriter(),this._pumpReadable(e.readable,"reliable")}catch(e){}t.datagrams&&t.datagrams.readable&&this._pumpDatagrams(t.datagrams.readable),t.closed&&"function"==typeof t.closed.then&&t.closed.then(()=>this._onClosed(),()=>this._onClosed()),this.connected=!0,this.onOpen&&this.onOpen()}async _pumpDatagrams(e){try{const t=e.getReader();for(;;){const{value:e,done:n}=await t.read();if(n)break;e&&this._onDatagramBytes(e)}}catch(e){this.onError&&this.onError(e)}}async _pumpReadable(e,t){try{const n=e.getReader();for(;;){const{value:e,done:i}=await n.read();if(i)break;if(e){const n=this._deframer.push(e);for(let e=0;e<n.length;e++)this.onMessage&&this.onMessage(n[e],t)}}}catch(e){this.onError&&this.onError(e)}}_onDatagramBytes(e){const t=function(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);return t.length<5?null:{seq:new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(0,!1),value:ie(t[4],t.subarray(5))}}(e);if(t){if(this._sequenced){if(t.seq<=this._recvSeq)return;this._recvSeq=t.seq}this.onMessage&&this.onMessage(t.value,"datagram")}}send(e){if(!this._dgWriter)return!1;this._sendSeq+=1;try{return this._dgWriter.write(function(e,t){const{type:n,bytes:i}=ne(t),r=new Uint8Array(5+i.length);return new DataView(r.buffer).setUint32(0,e>>>0,!1),r[4]=n,r.set(i,5),r}(this._sendSeq,e)),!0}catch(e){return!1}}sendReliable(e){if(!this._streamWriter)return!1;try{return this._streamWriter.write(function(e){const{type:t,bytes:n}=ne(e),i=new Uint8Array(5+n.length);return new DataView(i.buffer).setUint32(0,1+n.length,!1),i[4]=t,i.set(n,5),i}(e)),!0}catch(e){return!1}}_onClosed(){this.connected&&(this.connected=!1,this.onClose&&this.onClose())}close(){try{this._dgWriter&&this._dgWriter.releaseLock&&this._dgWriter.releaseLock()}catch(e){}try{this._t&&this._t.close()}catch(e){}this._t=this._dgWriter=this._streamWriter=null,this.connected=!1}}class se{constructor(e={}){this._set=e.setTimeout||("undefined"!=typeof setTimeout?setTimeout:null),this._clear=e.clearTimeout||("undefined"!=typeof clearTimeout?clearTimeout:null),this._rand=e.random||Math.random,this._timers=new Set,this.set(e)}set(e={}){return null!=e.latencyMs?this.latencyMs=Math.max(0,e.latencyMs):null==this.latencyMs&&(this.latencyMs=0),null!=e.jitterMs?this.jitterMs=Math.max(0,e.jitterMs):null==this.jitterMs&&(this.jitterMs=0),null!=e.lossPct?this.lossPct=Math.max(0,Math.min(100,e.lossPct)):null==this.lossPct&&(this.lossPct=0),null!=e.dupPct?this.dupPct=Math.max(0,Math.min(100,e.dupPct)):null==this.dupPct&&(this.dupPct=0),this}_delay(){const e=this.jitterMs?(2*this._rand()-1)*this.jitterMs:0,t=this.latencyMs+e;return t>0?t:0}_schedule(e,t){if(!this._set)return void e();const n=this._set(()=>{this._timers.delete(n),e()},t);this._timers.add(n)}wrap(e){const t=this;return function(...n){if(!(t.latencyMs||t.jitterMs||t.lossPct||t.dupPct))return e.apply(this,n);if(t.lossPct&&100*t._rand()<t.lossPct)return;const i=this;t._schedule(()=>e.apply(i,n),t._delay()),t.dupPct&&100*t._rand()<t.dupPct&&t._schedule(()=>e.apply(i,n),t._delay())}}flush(){if(this._clear)for(const e of this._timers)this._clear(e);this._timers.clear()}}class ce{constructor(e={}){if(!e.playerId)throw new Error("Lockstep requires playerId");if(!Array.isArray(e.players)||0===e.players.length)throw new Error("Lockstep requires players[]");if("function"!=typeof e.step)throw new Error("Lockstep requires a step(frame, inputs) function");this.playerId=e.playerId,this._players=e.players.slice(),this._step=e.step,this._send=e.send||function(){},this._inputDelay=null!=e.inputDelay?e.inputDelay:2,this._idle=null!=e.idleInput?e.idleInput:null,this._inputs={},this._frame=0,this._submitFrame=this._inputDelay,this._replay=[];for(let e=0;e<this._inputDelay;e++){this._inputs[e]={};for(let t=0;t<this._players.length;t++)this._inputs[e][this._players[t]]=this._idle}}get frame(){return this._frame}get players(){return this._players.slice()}submit(e){const t=this._submitFrame++;return this._inputs[t]||(this._inputs[t]={}),this._inputs[t][this.playerId]=e,this._send({frame:t,playerId:this.playerId,input:e}),t}receive(e){e&&null!=e.frame&&e.playerId&&(this._inputs[e.frame]||(this._inputs[e.frame]={}),this._inputs[e.frame][e.playerId]=e.input)}_ready(e){const t=this._inputs[e];if(!t)return!1;for(let e=0;e<this._players.length;e++)if(!(this._players[e]in t))return!1;return!0}tick(){let e=0;for(;this._ready(this._frame);){const t=this._inputs[this._frame];this._step(this._frame,t),this._replay.push({frame:this._frame,inputs:t}),delete this._inputs[this._frame],this._frame+=1,e+=1}return e}isStalled(){return!this._ready(this._frame)}getReplay(){return this._replay.slice()}static replay(e,t){for(let n=0;n<e.length;n++)t(e[n].frame,e[n].inputs)}}function ae(e,t,n){return e+(t-e)*n}class ue{constructor(e={}){this._historyMs=e.historyMs||1e3,this._maxSize=e.maxSize||256,this._now=e.now||(()=>Date.now()),this._history=[]}record(e,t){const n=null!=t?t:this._now();this._history.push({time:n,entities:e.map(e=>Object.assign({},e))});const i=n-this._historyMs;for(;this._history.length>this._maxSize||this._history.length>2&&this._history[0].time<i;)this._history.shift()}get size(){return this._history.length}clear(){this._history=[]}rewind(e,t){const n=this._history;if(0===n.length)return{};if(e<=n[0].time)return le(n[0].entities);if(e>=n[n.length-1].time)return le(n[n.length-1].entities);let i=n[0],r=n[n.length-1];for(let t=n.length-1;t>0;t--)if(n[t-1].time<=e&&e<=n[t].time){i=n[t-1],r=n[t];break}const o=r.time-i.time,s=o>0?(e-i.time)/o:0,c=le(i.entities),a={},u=le(r.entities);for(const e in u){const n=u[e],i=c[e],r=Object.assign({},n);if(i){const e=t||Object.keys(n);for(let t=0;t<e.length;t++){const o=e[t];"number"==typeof i[o]&&"number"==typeof n[o]&&(r[o]=ae(i[o],n[o],s))}}a[e]=r}return a}rewindForClient(e,t,n){const i=null!=(n=n||{}).maxRewindMs?n.maxRewindMs:250;let r=(e||0)/2+(t||0);return r>i&&(r=i),this.rewind(this._now()-r,n.keys)}}function le(e){const t={};for(let n=0;n<e.length;n++)t[e[n].id]=e[n];return t}const de="_s",fe="_d",he="_a",_e="_n",pe="_ka",me="_add",ge="_del",ye="_ord";function ve(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ie(e){if(!Array.isArray(e)||0===e.length)return!1;for(let t=0;t<e.length;t++){const n=e[t];if(!ve(n)||"string"!=typeof n.id&&"number"!=typeof n.id)return!1}return!0}function Ee(e,t){if(e===t)return;const n=Array.isArray(e),i=Array.isArray(t);return n!==i||ve(e)!==ve(t)?{[de]:t}:i?Ie(e)&&Ie(t)?function(e,t){const n={},i=[];for(let t=0;t<e.length;t++)n[e[t].id]=e[t],i.push(e[t].id);const r=[],o={};let s=!1;for(let e=0;e<t.length;e++){const i=t[e];if(r.push(i.id),Object.prototype.hasOwnProperty.call(n,i.id)){const e=Ee(n[i.id],i);void 0!==e&&(o[pe]||(o[pe]={}),o[pe][i.id]=e,s=!0)}else o[me]||(o[me]=[]),o[me].push(i),s=!0}const c={};for(let e=0;e<r.length;e++)c[r[e]]=!0;for(let e=0;e<i.length;e++)c[i[e]]||(o[ge]||(o[ge]=[]),o[ge].push(i[e]),s=!0);(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0})(i,r)||(o[ye]=r,s=!0);return s?o:void 0}(e,t):function(e,t){const n={[he]:{}};let i=!1;for(let r=0;r<t.length;r++){const o=r<e.length?Ee(e[r],t[r]):{[de]:t[r]};void 0!==o&&(n[he][r]=o,i=!0)}t.length!==e.length&&(n[_e]=t.length,i=!0);return i?n:void 0}(e,t):ve(t)?function(e,t){const n={};let i=!1;for(const r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;const o=Ee(e[r],t[r]);void 0!==o&&(n[r]=o,i=!0)}const r=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(Object.prototype.hasOwnProperty.call(t,n)||r.push(n));r.length&&(n[fe]=r,i=!0);return i?n:void 0}(e,t):{[de]:t}}function we(e,t){if(null==t)return e;if(Object.prototype.hasOwnProperty.call(t,de))return t[de];if(t[pe]||t[me]||t[ge]||t[ye])return function(e,t){const n=Array.isArray(e)?e:[],i={},r=[];for(let e=0;e<n.length;e++){const t=n[e];!t||"string"!=typeof t.id&&"number"!=typeof t.id||(i[t.id]=t,r.push(t.id))}if(t[pe])for(const e in t[pe])Object.prototype.hasOwnProperty.call(t[pe],e)&&void 0!==i[e]&&(i[e]=we(i[e],t[pe][e]));if(t[me])for(let e=0;e<t[me].length;e++){const n=t[me][e];i[n.id]=n}const o={};if(t[ge])for(let e=0;e<t[ge].length;e++)o[t[ge][e]]=!0;if(t[ye]){const e=[];for(let n=0;n<t[ye].length;n++){const r=t[ye][n];void 0!==i[r]&&e.push(i[r])}return e}const s=[];for(let e=0;e<r.length;e++){const t=r[e];o[t]||s.push(i[t])}return s}(e,t);if(Object.prototype.hasOwnProperty.call(t,he)||Object.prototype.hasOwnProperty.call(t,_e)){const n=Array.isArray(e)?e:[],i=Object.prototype.hasOwnProperty.call(t,_e)?t[_e]:n.length,r=n.slice(0,i),o=t[he]||{};for(const e in o)Object.prototype.hasOwnProperty.call(o,e)&&(r[e]=we(r[e],o[e]));return r}const n=ve(e)?Object.assign({},e):{},i=t[fe];for(const e in t)e!==fe&&Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=we(n[e],t[e]));if(Array.isArray(i))for(let e=0;e<i.length;e++)delete n[i[e]];return n}function be(e,t=2){const n=Math.pow(10,t);return function e(t){if("number"==typeof t)return Number.isFinite(t)?Math.round(t*n)/n:t;if(Array.isArray(t))return t.map(e);if(ve(t)){const n={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=e(t[i]));return n}return t}(e)}const Te="undefined"!=typeof TextEncoder?new TextEncoder:null,Se="undefined"!=typeof TextDecoder?new TextDecoder:null;function Ae(e,t){for(t>>>=0;t>127;)e.push(127&t|128),t>>>=7;e.push(t)}function Oe(e,t){if(null==t)return void e.push(192);const n=typeof t;if("boolean"!==n)if("number"!==n){var i;if("string"===n){e.push(198);const n=Te?Te.encode(t):Buffer.from(t,"utf8");Ae(e,n.length);for(let t=0;t<n.length;t++)e.push(n[t]);return}if(Array.isArray(t)){e.push(199),Ae(e,t.length);for(let n=0;n<t.length;n++)Oe(e,t[n])}else{if("object"===n){const n=Object.keys(t);e.push(200),Ae(e,n.length);for(let i=0;i<n.length;i++){const r=n[i],o=Te?Te.encode(r):Buffer.from(r,"utf8");Ae(e,o.length);for(let t=0;t<o.length;t++)e.push(o[t]);Oe(e,t[r])}return}e.push(192)}}else if(Number.isInteger(t)&&t>=-2147483648&&t<=2147483647)e.push(196),Ae(e,((i=t)<<1^i>>31)>>>0);else{e.push(197);const n=new Uint8Array(8);new DataView(n.buffer).setFloat64(0,t,!0);for(let t=0;t<8;t++)e.push(n[t])}else e.push(t?195:194)}function Ce(e){const t=[];return Oe(t,e),Uint8Array.from(t)}function ke(e){return function(e){let t=0;const n=new DataView(e.buffer,e.byteOffset,e.byteLength);function i(){let n,i=0,r=0;do{n=e[t++],r|=(127&n)<<i,i+=7}while(128&n);return r>>>0}function r(){const n=i(),r=e.subarray(t,t+n);return t+=n,Se?Se.decode(r):Buffer.from(r).toString("utf8")}return function o(){switch(e[t++]){case 192:default:return null;case 195:return!0;case 194:return!1;case 196:return(s=i())>>>1^-(1&s);case 197:{const e=n.getFloat64(t,!0);return t+=8,e}case 198:return r();case 199:{const e=i(),t=new Array(e);for(let n=0;n<e;n++)t[n]=o();return t}case 200:{const e=i(),t={};for(let n=0;n<e;n++)t[r()]=o();return t}}var s}}(e instanceof Uint8Array?e:new Uint8Array(e))()}function Ne(e,t){if(!("string"==typeof e&&e.length>0||"number"==typeof e&&isFinite(e)))throw new Error("interestGrid."+t+": id must be a non-empty string or a finite number");return e}function Pe(e,t,n){if("number"!=typeof e||!isFinite(e))throw new Error("interestGrid."+n+": "+t+" must be a finite number");return e}function Re(e,t){if(Pe(e,"radius",t),e<0)throw new Error("interestGrid."+t+": radius must be >= 0");return e}function Me(e){const t=null!=(e=e||{}).cellSize?e.cellSize:256;if("number"!=typeof t||!isFinite(t)||t<=0)throw new Error("createInterestGrid: cellSize must be a finite number > 0");const n=new Map,i=new Map,r=new Map;function o(e,t){let n=i.get(e);n||(n=new Set,i.set(e,n)),n.add(t)}function s(e,t){const n=i.get(e);n&&(n.delete(t),0===n.size&&i.delete(e))}function c(e,r,o,s){const c=o*o,a=Math.floor((e-o)/t),u=Math.floor((e+o)/t),l=Math.floor((r-o)/t),d=Math.floor((r+o)/t);for(let t=a;t<=u;t++)for(let o=l;o<=d;o++){const a=i.get(t+","+o);if(a)for(const t of a){const i=n.get(t);if(!i)continue;const o=i.x-e,a=i.y-r;o*o+a*a<=c&&s(t)}}}return{upsert:function(e,i,r){Ne(e,"upsert"),Pe(i,"x","upsert"),Pe(r,"y","upsert");const c=Math.floor(i/t)+","+Math.floor(r/t),a=n.get(e);if(a)return a.x=i,a.y=r,void(a.key!==c&&(s(a.key,e),o(c,e),a.key=c));n.set(e,{x:i,y:r,key:c}),o(c,e)},remove:function(e){Ne(e,"remove");const t=n.get(e);t&&(n.delete(e),s(t.key,e))},query:function(e,t,n){Pe(e,"x","query"),Pe(t,"y","query"),Re(n,"query");const i=[];return c(e,t,n,function(e){i.push(e)}),i},observe:function(e,t,n,i){Ne(e,"observe"),Pe(t,"x","observe"),Pe(n,"y","observe"),Re(i,"observe");let o=r.get(e);o||(o={prev:new Set,next:new Set},r.set(e,o));const s=o.prev,a=o.next;a.clear();const u=[],l=[],d=[];c(t,n,i,function(e){a.add(e),d.push(e),s.has(e)||u.push(e)});for(const e of s)a.has(e)||l.push(e);return o.prev=a,o.next=s,{entered:u,left:l,visible:d}},dropObserver:function(e){Ne(e,"dropObserver"),r.delete(e)},size:function(){return n.size}}}function qe(e,t){e.diff=Ee,e.patch=we,e.quantize=be,e.encode=Ce,e.decode=ke,e.createInterpolation=function(e){return new z(e||{})},e.createPredictor=function(e){return new J(e||{})},e.createLagCompensator=function(e){return new ue(e||{})},e.createLockstep=function(e){return new ce(e||{})},e.createInterestGrid=function(e){return Me(e||{})},e._channels=e._channels||{},e._userRealtime=e._userRealtime||null,e._inboundDispatch=null,e._dispatchRealtime=function(t){const n=t&&t.action_type;n&&e._channels[n]?e._channels[n](t&&(void 0!==t.action_data?t.action_data:t),t):e._userRealtime&&e._userRealtime(t)},e._installRealtimeRouter=function(){e._routerInstalled||(e._eventHandlers.realtime&&e._eventHandlers.realtime!==e._router&&(e._userRealtime=e._eventHandlers.realtime),e._router=function(t){(e._inboundDispatch||e._dispatchRealtime)(t)},e._eventHandlers.realtime=e._router,e._routerInstalled=!0)},e._onChannel=function(t,n){return e._channels[t]=n,e._installRealtimeRouter(),function(){delete e._channels[t]}},e.onRealtime=function(t){e._userRealtime=t,e._installRealtimeRouter()},e.createSender=function(e){const t=this,n=(e=e||{}).send||function(e,n){t.realtime(e,n)};return new Q({hz:e.hz||20,autoStart:!1!==e.autoStart,onFlush:function(e){for(let t=0;t<e.length;t++)n(e[t].type,e[t].data)}})},e.createSnapshotSender=function(e){const t=this,n=(e=e||{}).channel||"state",i=!1!==e.delta,r=null!=e.keyframeEvery?e.keyframeEvery:30,o=e.precision,s=!0===e.encode?Ce:"function"==typeof e.encode?e.encode:null,c=e.send||function(e,n){t.realtime(e,n)},a="function"==typeof e.source?e.source:null;let u=null,l=0,d=0,f=0;function h(e){if(null==e)return;const t=null!=o?be(e,o):e;let a;if(!i||null===u||f>=r)d+=1,u=null==(h=t)?h:JSON.parse(JSON.stringify(h)),l=d,f=0,a={s:d,f:t};else{const e=Ee(u,t);if(void 0===e)return;d+=1,f+=1,a={s:d,b:l,d:e}}var h;c(n,s?s(a):a)}const _=e.hz||20;let p;const m=a?null:new Q({hz:_,autoStart:!1!==e.autoStart,onFlush:function(e){for(let t=0;t<e.length;t++)"__snap"===e[t].type&&(p=e[t].data);h(p)}});let g=null;function y(){m?m.start():g||"undefined"==typeof setInterval||(g=setInterval(function(){h(a())},Math.max(1,Math.round(1e3/_))))}return a&&!1!==e.autoStart&&y(),{send:function(e){m?m.queue("__snap",e):h(e)},flush:function(){m?m.flush():a&&h(a())},start:y,stop:function(){m&&m.stop(),g&&(clearInterval(g),g=null)},reset:function(){u=null,l=0,d=0,f=0}}},e.createSnapshotReceiver=function(e){const t=!0===(e=e||{}).decode?ke:"function"==typeof e.decode?e.decode:null;let n=null,i=-1,r=null,o=-1,s=0;return{receive:function(e){return t&&(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e=t(e)),e?void 0!==e.f?void 0!==e.s&&e.s<=o?(s+=1,r):(n=e.f,i=void 0!==e.s?e.s:0,r=e.f,o=i,r):void 0!==e.d?void 0!==e.b&&e.b!==i||void 0!==e.s&&e.s<=o?(s+=1,r):(r=we(n,e.d),void 0!==e.s&&(o=e.s),r):r:r},get state(){return r},get stats(){return{appliedSeq:o,baseSeq:i,dropped:s}},reset:function(){n=null,i=-1,r=null,o=-1,s=0}}},e.replicate=function(e,t){t=t||{};let n=null!=e?e:{};const i=this.createSnapshotSender(Object.assign({},t,{source:function(){return n}}));return{get state(){return n},set state(e){n=e},flush:function(){i.flush()},start:function(){i.start()},stop:function(){i.stop()}}},e.replica=function(e){const t=(e=e||{}).channel||"state",n=this.createSnapshotReceiver({decode:e.decode}),i=e.interpolate?this.createInterpolation("object"==typeof e.interpolate?e.interpolate:{}):null,r="string"==typeof e.interpolate?e.interpolate:e.keys||e.interpolate&&e.interpolate.keys,o=e.group||e.interpolate&&e.interpolate.group;let s=null;const c=this._onChannel(t,function(e){const t=n.receive(e);i&&null!=t&&i.add(t),s&&s(t)});return{get state(){return n.state},view:function(){return i?i.calc(r||"x y",o):n.state},onChange:function(e){s=e},stop:function(){c()}}},e.createMesh=function(e){const t=this,n=(e=e||{}).signalChannel||"signal",i=new X(Object.assign({},e,{sendSignal:function(e){t.realtime(n,e)}}));return this._onChannel(n,function(e){e&&e.type&&i.handleSignal(e)}),i},e.createMeshNetwork=function(e){const n=this,i=(e=e||{}).signalChannel||"mesh",r=e.selfId||t.user&&t.user.getId&&t.user.getId(),o=new Z(Object.assign({},e,{selfId:r,sendSignal:function(e,t){n.realtime(i,{to:e,from:r,payload:t})}}));return this._onChannel(i,function(e){e&&e.to===r&&e.from&&o.handleSignal(e.from,e.payload)}),o},e.simulateNetwork=function(e){const t=this;return t._installRealtimeRouter(),t._realtimeRaw||"function"!=typeof t.realtime||(t._realtimeRaw=t.realtime.bind(t)),e?(t._sim?t._sim.set(e):t._sim=new se(e),t._realtimeRaw&&(t.realtime=t._sim.wrap(t._realtimeRaw)),t._inboundDispatch=t._sim.wrap(t._dispatchRealtime),t._sim):(t._realtimeRaw&&(t.realtime=t._realtimeRaw),t._inboundDispatch=null,t._sim&&t._sim.flush(),void(t._sim=null))},e.createWebTransport=function(e){const n=(e=e||{}).url||t.config&&(t.config.webTransportUrl||t.config.wtUrl);return new oe(Object.assign({},e,{url:n}))},e.ping=function(){const e=this;if(e._pingMeter||(e._pingMeter=new K),e._pingInFlight)return e._pingInFlight;let t;if(e.directMode){if(!e.directSocket||1!==e.directSocket.readyState)return Promise.resolve(null);t=new Promise(function(t){const n=e._pingMeter.begin();let i=!1;const r=function(){i||(i=!0,t(e._pingMeter.end(n)))};r.sentAt=Date.now(),e._pongWaiters.push(r),e._sendDirect("ping",{t:Date.now()}),setTimeout(function(){if(i)return;i=!0;const o=e._pongWaiters.indexOf(r);o>=0&&e._pongWaiters.splice(o,1),delete e._pingMeter._outstanding[n],t(null)},3e3)})}else{if(!e.socket||!e.connected||e._useProxy)return Promise.resolve(null);t=new Promise(function(t){const n=Date.now();let i=!1;try{e.socket.emit("game:ping",{t:n},function(){i||(i=!0,t(e._pingMeter.sample(Date.now()-n)))})}catch(e){return void t(null)}setTimeout(function(){i||(i=!0,t(null))},3e3)})}return e._pingInFlight=t,t.then(function(){e._pingInFlight=null},function(){e._pingInFlight=null}),t},e.getRtt=function(){return this._pingMeter?this._pingMeter.rtt:null}}function De(e,t){e.syncedState=function(e,n){var i=this,r="function"==typeof(n=n||{}).reduce?n.reduce:function(e,t){return Object.assign({},e,t.data)},o=null!=n.checkpointEvery?n.checkpointEvery:1,s="all"===n.authority?"all":"host",c=n.type||"update",a=void 0===e?{}:e,u=0,l=0,d=-1,f=0,h=new Map,_=[],p=[];function m(e){for(var n=_.slice(),i=0;i<n.length;i++)try{n[i](a,e)}catch(e){t.log("syncedState onChange error: "+e.message)}}function g(){if("all"===s)return!0;var e=i.playerId||t.user&&t.user.getId&&t.user.getId();return!(!e||!i._hostId||e!==i._hostId)}function y(){return i.directMode?Promise.resolve({success:!1,error:"not_supported_in_direct_mode"}):i.setState({__usionSyncedState:1,seq:u,state:a})}function v(e,n,i,o){if(void 0!==o){if(!Number.isSafeInteger(o)||o<=u)return!1;if(f=Math.max(f,o),o!==u+1)return h.size<1e3&&h.set(o,{playerId:e,type:n,data:i,sequence:o}),!1}var s;try{s=r(a,{playerId:e,type:n,data:i,sequence:o})}catch(e){return t.log("syncedState reduce error: "+e.message),!1}return void 0!==s&&(a=s),void 0!==o&&(u=o),!0}function I(){var e=0;for(h.forEach(function(e,t){t<=u&&h.delete(t)});h.has(u+1);){var t=h.get(u+1);if(!v(t.playerId,t.type,t.data,t.sequence))break;h.delete(t.sequence),e+=1}return e}function E(){if(!(f<=u||d===u)){d=u;try{i.requestSync(u)}catch(e){d=-1}}}function w(e){if(e){var t=!1;Number.isSafeInteger(e.sequence)&&(f=Math.max(f,e.sequence));var n=e.game_state;n&&n.__usionSyncedState&&"number"==typeof n.seq&&n.seq>=u&&void 0!==n.state&&(a=n.state,u=n.seq,t=!0);var i=e.actions;if(i&&i.length)for(var r=i.slice().sort(function(e,t){return(e.sequence||0)-(t.sequence||0)}),o=0;o<r.length;o++){var s=r[o];s&&v(s.player_id,s.action_type,s.action_data,s.sequence)&&(t=!0)}I()&&(t=!0),t&&m("recover"),E()}}return p.push(i.on("action",function(e){if(e){var t=v(e.player_id,e.action_type,e.action_data,e.sequence)?1:0;(t+=I())&&(m("action"),function(e){o>0&&g()&&(l+=e)>=o&&(l=0,y())}(t)),E()}})),p.push(i.on("sync",w)),p.push(i.on("joined",w)),{get:function(){return a},commit:function(e,t,n){var r,o,s;return"string"==typeof e?(r=e,o=t,s=n):(r=c,o=e,s=t),i.directMode?(v(i.playerId,r,o,void 0)&&m("action"),i.action(r,o,s)):i.action(r,o,s)},onChange:function(e){return _.push(e),function(){var t=_.indexOf(e);t>=0&&_.splice(t,1)}},isAuthority:g,checkpoint:function(){return y()},getSequence:function(){return u},destroy:function(){for(var e=0;e<p.length;e++)try{p[e]()}catch(e){}p.length=0,_.length=0,h.clear()}}}}const Ue="__usion_players_v1",Le=e=>["direct","turn","webrtc"].includes(e),je=()=>globalThis.crypto.randomUUID(),xe=e=>"string"==typeof e&&e.length>0&&e.length<=128;class Be{constructor(e,t,n={}){this.game=e,this.usion=t,this.options=n,this.selfId=t.user.getId(),this.roomId=null,this.closed=!1,this.online=!1,this.session=je(),this.peers=new Map,this.roster=new Set,this.listeners={message:new Set,status:new Set,log:new Set},this.logs=[],this.sequence=0,this.generation=0,this.lastHello=0,this.RTC=void 0===n.RTCPeerConnection?globalThis.RTCPeerConnection:n.RTCPeerConnection,this.iceServers=n.iceServers||[{urls:"stun:stun.l.google.com:19302"}],this.timeout=n.directTimeoutMs??6e3,this.unsubscribers=[e._onChannel(Ue,(e,t)=>this._incoming(e,t)),e.on("joined",e=>this._joined(e)),e.on("playerJoined",e=>this._roster(e)),e.on("playerLeft",e=>this._roster(e,!0)),e.on("sync",e=>this._roster(e)),e.on("roomAssigned",({roomId:e})=>{this._join(e).catch(()=>this._log("join_failed"))}),e.on("disconnect",()=>this._offline()),e.on("reconnect",()=>this._recover()),e.on("reconnected",()=>this._recover())],this.tick=setInterval(()=>this._tick(),1e3)}async start(){const e=this.options.roomId||this.game.roomId||this.usion.config.roomId;return e&&await this._join(e),this}_emit(e,t){for(const n of this.listeners[e])try{n(t)}catch{}}_listen(e,t){return this.listeners[e].add(t),()=>this.listeners[e].delete(t)}onMessage(e){return this._listen("message",e)}onStatusChange(e){return this._listen("status",e)}onLog(e){return this._listen("log",e)}getLogs(){return this.logs.map(e=>({...e}))}_log(e,t=void 0,n=void 0){const i={time:Date.now(),event:e,peerId:t,reason:n};this.logs.push(i),this.logs.length>100&&this.logs.shift(),this._emit("log",{...i})}getStatus(){return{roomId:this.roomId,state:this.closed?"closed":this.roomId?this.online?"connected":"offline":"waiting",peers:[...this.peers.values()].map(e=>({playerId:e.id,transport:this.online?e.mode:"offline",rttMs:e.rtt,sent:e.sent,received:e.received}))}}_status(){this._emit("status",this.getStatus())}_mode(e,t,n){e.mode=t,e.rtt=null,this._log("transport",e.id,n),this._status()}async _join(e){if(this.closed)return;const t=++this.generation;if(this.roomId!==e&&(this._clearPeers(),this.roster.clear(),this.session=je(),this.roomId=e),this.online=!1,await this.game.connect(),this.closed||t!==this.generation)return;const n=await this.game.join(e);this.closed||t!==this.generation||this._joined(n||{})}_joined(e){if(this.closed)return;(e.room_id||this.game.roomId)===this.roomId&&(this.online=!0,this._roster(e),this._hello(),this._status())}_recover(){this.closed||this.online||!this.roomId||this._join(this.roomId).catch(()=>this._log("rejoin_failed"))}_offline(){this.closed||(this.generation++,this.online=!1,this.session=je(),this._clearPeers(),this._log("offline"),this._status())}_roster(e,t=!1){if(!(this.closed||!e||e.room_id&&e.room_id!==this.roomId)){Array.isArray(e.player_ids)?this.roster=new Set(e.player_ids.filter(xe)):xe(e.player_id)&&(t?this.roster.delete(e.player_id):this.roster.add(e.player_id));for(const[n,i]of this.peers)(!this.roster.has(n)||t&&n===e.player_id)&&(this._closeRTC(i),this.peers.delete(n),this._log("peer_left",n));this._hello(),this._status()}}_relay(e,t){if(!this.online||this.closed)return!1;try{return this.game.realtime(Ue,{...e,v:1,room:this.roomId,session:this.session,to:t}),!0}catch{return this._log("relay_send_failed",t),!1}}_hello(e=void 0){this._relay({kind:"hello"},e)}_peer(e,t){let n=this.peers.get(e);if(n&&n.session!==t&&(this._closeRTC(n),this.peers.delete(e),n=null),!n){if(this.peers.size>=7)return this._log("peer_limit",e),null;n={id:e,session:t,mode:"relay",pc:null,dc:null,attempt:null,candidates:[],queue:Promise.resolve(),lastDirect:0,lastSequence:-1,rtt:null,sent:0,received:0,started:!1,pendingPing:null},this.peers.set(e,n),this._log("peer_joined",e),this._status()}return n}_incoming(e,t){const n=t?.player_id;if(this.closed||!this.online||!e||1!==e.v||e.room!==this.roomId||t.room_id!==this.roomId||!xe(n)||n===this.selfId||!this.roster.has(n)||!xe(e.session)||e.to&&e.to!==this.selfId)return;if("hello"===e.kind){const t=this.peers.get(n)?.session===e.session,i=this._peer(n,e.session);if(!i)return;return t||this._hello(n),void(this.selfId<n&&!i.started&&this._attempt(i))}const i=this.peers.get(n);if(i&&i.session===e.session&&e.target===this.session)if("offer"===e.kind&&this.selfId>n&&xe(e.attempt)){if(i.attempt===e.attempt)return;this._setup(i,e.attempt),i.pc&&this._signal(i,e)}else["answer","ice"].includes(e.kind)&&e.attempt===i.attempt?this._signal(i,e):"fallback"===e.kind&&e.attempt===i.attempt?this._fallback(i,"peer_requested",!1):"retry"===e.kind&&this.selfId<n?this._attempt(i):"data"===e.kind&&this._receive(i,e,"relay")}_control(e,t){return this._relay({...t,target:e.session,attempt:e.attempt},e.id)}_setup(e,t){if(this._closeRTC(e),e.attempt=t,e.started=!0,this.RTC&&!1!==this.options.direct){this._mode(e,"connecting","direct_attempt");try{const t=e.pc=new this.RTC({iceServers:this.iceServers});e.localCandidates=[],e.descriptionSent=!1,t.onicecandidate=n=>{if(e.pc!==t||!n.candidate)return;const i=n.candidate.toJSON();e.descriptionSent?this._control(e,{kind:"ice",candidate:i}):e.localCandidates.length<64&&e.localCandidates.push(i)},t.ondatachannel=n=>{e.pc===t&&this._channel(e,t,n.channel)},t.onconnectionstatechange=()=>{e.pc===t&&["failed","disconnected","closed"].includes(t.connectionState)&&this._fallback(e,t.connectionState)},e.timer=setTimeout(()=>{e.pc===t&&this._fallback(e,"direct_timeout")},this.timeout)}catch{this._fallback(e,"rtc_setup_failed")}}else this._fallback(e,"direct_unavailable")}_attempt(e){this._setup(e,je());const t=e.pc;if(t){try{this._channel(e,t,t.createDataChannel("usion-game",{ordered:!1,maxRetransmits:0}))}catch{return void this._fallback(e,"channel_failed")}e.queue=(async()=>{const n=await t.createOffer();e.pc===t&&(await t.setLocalDescription(n),e.pc===t&&this._description(e,"offer"))})().catch(()=>{e.pc===t&&this._fallback(e,"offer_failed")})}}_signal(e,t){const n=e.pc;n&&(e.queue=e.queue.then(async()=>{if(e.pc===n)if("ice"===t.kind)n.remoteDescription?await n.addIceCandidate(t.candidate):e.candidates.length<64&&e.candidates.push(t.candidate);else{if(await n.setRemoteDescription(t.description),e.pc!==n)return;const i=e.candidates;e.candidates=[];for(const e of i)await n.addIceCandidate(e);"offer"===t.kind&&(await n.setLocalDescription(await n.createAnswer()),e.pc===n&&this._description(e,"answer"))}}).catch(()=>{e.pc===n&&this._fallback(e,"negotiation_failed")}))}_description(e,t){this._control(e,{kind:t,description:e.pc.localDescription.toJSON()}),e.descriptionSent=!0;for(const t of e.localCandidates)this._control(e,{kind:"ice",candidate:t});e.localCandidates=[]}_channel(e,t,n){e.dc=n,n.onopen=()=>{e.pc===t&&(clearTimeout(e.timer),e.lastDirect=Date.now(),this._mode(e,"webrtc","channel_open"),this._inspectRoute(e,t))},n.onmessage=n=>{if(!(e.pc!==t||"string"!=typeof n.data||n.data.length>16384))try{this._receive(e,JSON.parse(n.data),"direct")}catch{}},n.onerror=n.onclose=()=>{e.pc===t&&this._fallback(e,"channel_closed")}}async _inspectRoute(e,t){if(t?.getStats)try{const n=await t.getStats();if(e.pc!==t||!Le(e.mode))return;let i;if(n.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&(i=n.get(e.selectedCandidatePairId))}),i||n.forEach(e=>{"candidate-pair"===e.type&&e.nominated&&"succeeded"===e.state&&(i=e)}),!i)return;const r=n.get(i.localCandidateId),o=n.get(i.remoteCandidateId);if(!r?.candidateType||!o?.candidateType)return;const s="relay"===r.candidateType||"relay"===o.candidateType?"turn":"direct";s!==e.mode&&this._mode(e,s,"ice_route_selected")}catch{}}_closeRTC(e){clearTimeout(e.timer);const t=e.pc,n=e.dc;e.pc=e.dc=null,e.candidates=[],e.queue=Promise.resolve(),n&&(n.onopen=n.onmessage=n.onerror=n.onclose=null,n.close()),t&&(t.onicecandidate=t.ondatachannel=t.onconnectionstatechange=null,t.close())}_fallback(e,t,n=!0){n&&this._control(e,{kind:"fallback"}),this._closeRTC(e),this._mode(e,"relay",t)}_packet(e,t){const n={...t,kind:"data",room:this.roomId,session:this.session,target:e.session};if(Le(e.mode)&&"open"===e.dc?.readyState)try{if(e.dc.bufferedAmount>65536)throw Error("backpressure");return e.dc.send(JSON.stringify(n)),!0}catch{this._fallback(e,"send_failed")}return this._control(e,n)}_receive(e,t,n){t.room===this.roomId&&t.session===e.session&&t.target===this.session&&("direct"===n&&(e.lastDirect=Date.now()),Number.isSafeInteger(t.ping)&&t.ping>0?this._packet(e,{pong:t.ping}):Number.isSafeInteger(t.pong)&&t.pong>0?t.pong===e.pendingPing&&(e.rtt=Date.now()-t.pong,e.pendingPing=null,this._status()):!Number.isSafeInteger(t.seq)||t.seq<=e.lastSequence||(e.lastSequence=t.seq,e.received++,this._emit("message",{data:t.data,playerId:e.id,transport:"direct"===n?Le(e.mode)?e.mode:"webrtc":n})))}send(e,t){if(this.closed||!this.online)return!1;const n=JSON.stringify(e);if(void 0===n||(new TextEncoder).encode(n).length>4096)throw new Error("connectPlayers messages must be JSON, at most 4096 bytes");const i=JSON.parse(n),r=++this.sequence,o=t?[this.peers.get(t)].filter(Boolean):[...this.peers.values()];let s=o.length>0;for(const e of o){const t=this._packet(e,{data:i,seq:r});t&&e.sent++,s=s&&t}return s}forceRelay(e){for(const t of this.peers.values())e&&t.id!==e||this._fallback(t,"forced")}retryDirect(e){if(this.online&&!this.closed)for(const t of this.peers.values())e&&t.id!==e||(this.selfId<t.id?this._attempt(t):this._control(t,{kind:"retry"}))}async invite(){return this.game.invite()}_tick(){if(!this.online||this.closed)return;const e=Date.now();e-this.lastHello>=3e3&&(this.lastHello=e,this._hello());for(const t of this.peers.values())Le(t.mode)&&e-(t.lastStats||0)>1e4&&(t.lastStats=e,this._inspectRoute(t,t.pc)),Le(t.mode)&&e-t.lastDirect>3e3&&this._fallback(t,"direct_unresponsive"),t.pendingPing=e,this._packet(t,{ping:e})}_clearPeers(){for(const e of this.peers.values())this._closeRTC(e);this.peers.clear()}close(){if(!this.closed){this.closed=!0,this.generation++,clearInterval(this.tick),this._clearPeers(),this.unsubscribers.forEach(e=>e()),this._status();for(const e of Object.values(this.listeners))e.clear()}}}const He={joined:"joined",player_joined:"playerJoined",player_left:"playerLeft",player_connection:"playerConnection",state:"stateUpdate",state_update:"stateUpdate",sync:"sync",action:"action",realtime:"realtime",finished:"finished",restarted:"restarted",error:"error",rematch_request:"rematchRequest",disconnect:"disconnect",reconnect:"reconnect",connection_error:"connectionError",room_assigned:"roomAssigned",connection_state:"connectionState",reconnected:"reconnected",network_quality:"networkQuality"};const Ve={SnapshotInterpolation:z,Vault:G,Predictor:J,Coalescer:Q,PingMeter:K,MeshConnection:X,MeshNetwork:Z,WebTransportConnection:oe,NetworkSim:se,Lockstep:ce,LagCompensator:ue,diff:Ee,patch:we,quantize:be,encode:Ce,decode:ke,createInterestGrid:Me},Fe=Object.assign({},v);var Ge;return Fe.user=function(n){const i=new Set;let r={status:"loading",userId:null};return{_applyAuth:function(e,t){e={...e};const o=r,s=t=>Object.prototype.hasOwnProperty.call(e,t),c=e.authState,a=s("userId")||!!c,u=s("userId")?e.userId:c?c.userId:this.getId(),l="string"==typeof u&&u&&0!==u.indexOf("guest_")?u:null;if(a){const e=c&&"loading"===c.status?"loading":c&&"guest"===c.status?"guest":l?"authenticated":"guest";r={status:e,userId:"authenticated"===e?l:null};(o.status!==r.status||o.userId!==r.userId)&&"loading"!==o.status&&(this._name=this._avatar=this._token=this._isAdult=null,n.config.userName=n.config.userAvatar=n.config.authToken=n.config.userIsAdult=null),this._id="string"==typeof u?u:null,n.config.userId=this._id}if(s("userName")&&(this._name=n.config.userName=e.userName||null),s("userAvatar")&&(this._avatar=n.config.userAvatar=e.userAvatar||null),s("userIsAdult")&&(this._isAdult=n.config.userIsAdult="boolean"==typeof e.userIsAdult?e.userIsAdult:null),t||s("authToken")||a&&"authenticated"!==r.status){const t=s("userId")&&"string"==typeof e.userId&&0===e.userId.indexOf("guest_");this._token=n.config.authToken="authenticated"!==r.status&&!t||"string"!=typeof e.authToken?null:e.authToken}n.config.authState={...r},o.status===r.status&&o.userId===r.userId||("loading"!==o.status&&(n._invalidateAuthRequests&&n._invalidateAuthRequests(),n._results=[],n.config.sessionId=null,n.config.sessionData={},n.config.results=[],n.config.balance=null,n.session&&(n.session._id=null,n.session._data={}),n.wallet&&(n.wallet._balance=null)),i.forEach(function(e){try{e({...r})}catch(e){console.error("[Usion] auth listener error:",e)}}))},getAuthState:function(){return{...r}},onAuthChange:function(e){return"function"!=typeof e?function(){}:(i.add(e),function(){i.delete(e)})},requestLogin:function(i){if(!n.config.hostFeatures?.auth)return Promise.reject(new t(e.UNSUPPORTED,"Login requires a newer Usion host"));const r=i&&i.returnPath;return null!=r&&("string"!=typeof r||!r.startsWith("/")||r.startsWith("//")||/[\\\s\x00-\x1f]/.test(r)||r.length>2048)?Promise.reject(new t(e.INVALID_INPUT,"returnPath must be a safe relative app path")):n._request("REQUEST_LOGIN",null==r?{}:{returnPath:r})},_id:null,_name:null,_avatar:null,_token:null,_isAdult:null,getId:function(){return this._id||n.config.userId||null},getName:function(){return this._name||n.config.userName||null},getAvatar:function(){return this._avatar||n.config.userAvatar||null},isAdult:function(){if(!0===this._isAdult||!1===this._isAdult)return this._isAdult;var e=n.config&&n.config.userIsAdult;return!0===e||!1===e?e:null},getToken:function(){return this._token||n.config.authToken||null},getProfile:function(){return n._request("GET_USER_PROFILE",{}).then(function(e){return e.profile||{id:n.user.getId(),name:n.user.getName(),avatar:n.user.getAvatar(),isAdult:n.user.isAdult()}})},openProfile:function(e){"string"==typeof e&&e&&0!==e.indexOf("guest_")&&n._post({type:"OPEN_USER_PROFILE",userId:e})}}}(Fe),Fe.storage=function(e){var t=null;function n(){return t||(t=b(e,"kv:get",{key:E}).then(function(t){if(!t||!t.exists||!0!==t.value)return Promise.all([b(e,"kv:keys",{}),O(e)]).then(function(t){var n=new Set(t[0]&&t[0].keys||[]);return Promise.all(t[1].map(function(t){var i=w(t);if(!n.has(i))return T(e,t).then(function(t){if(null!=t)return b(e,"kv:set",{key:i,value:t})})}))}).then(function(){return b(e,"kv:set",{key:E,value:!0})})}).catch(function(e){throw t=null,e}))}return{get:function(t){return n().then(function(){return b(e,"kv:get",{key:w(t)})}).then(function(n){return n&&n.exists?C(S(e,t,n.value)).then(function(){return n.value}):C(A(e,t)).then(function(){return null})}).catch(function(n){return T(e,t).then(function(e){if(null!=e)return e;throw n},function(){throw n})})},set:function(t,i){return n().then(function(){return b(e,"kv:set",{key:w(t),value:i})}).then(function(){return C(S(e,t,i))})},remove:function(t){return n().then(function(){return b(e,"kv:remove",{key:w(t)})}).then(function(){return C(A(e,t))})},clear:function(){return n().then(function(){return b(e,"kv:clear",{prefix:I})}).then(function(){return C(e._request("STORAGE_CLEAR",{}))})},keys:function(){return n().then(function(){return b(e,"kv:keys",{})}).then(function(e){return(e&&e.keys||[]).filter(function(e){return 0===e.indexOf(I)}).map(function(e){return e.slice(3)})}).catch(function(t){return O(e).catch(function(){throw t})})}}}(Fe),Fe.wallet=function(e){return{_balance:null,_balanceChangeHandler:null,_paymentTimeoutMs:6e4,_recoveryPollMs:2e3,_recoveryMaxPolls:10,_recoveryQueryTimeoutMs:8e3,getBalance:function(t){const n=this;return!(!t||!t.fresh)||null===n._balance?e._request("GET_BALANCE",{}).then(function(e){return n._balance=e.balance,e.balance}):Promise.resolve(n._balance)},hasCredits:function(e){return this.getBalance().then(function(t){return t>=e})},requestPayment:function(t,n,i){const r=this,o=i&&"object"==typeof i?i:null,s=o&&"string"==typeof o.idempotencyKey&&o.idempotencyKey?o.idempotencyKey:null;return new Promise(function(o,c){const a=_(),u=r._paymentTimeoutMs||6e4;let l=!1,d=null;function f(){clearTimeout(v),d&&clearTimeout(d),window.removeEventListener("message",m)}function h(e){l||(l=!0,f(),e&&void 0!==e.newBalance?r._balance=e.newBalance:(null!==r._balance&&(r._balance-=t),r.getBalance({fresh:!0}).catch(function(){})),o(e))}function p(e){l||(l=!0,f(),c(e))}function m(e){if(!g(e))return;let t;try{t=y(e)}catch(e){return}t&&t._requestId===a&&("PAYMENT_SUCCESS"===t.type?h(t):"PAYMENT_FAILED"===t.type&&p(new Error(t.reason||"Payment failed")))}window.addEventListener("message",m);const v=setTimeout(function(){const t=r._recoveryPollMs||2e3,n=r._recoveryMaxPolls||10,i=r._recoveryQueryTimeoutMs||8e3;let o=0,c=0;!function r(){l||e._request("PAYMENT_RESULT_QUERY",{paymentRequestId:a,idempotencyKey:s||void 0},i).then(function(e){if(l)return;const n=e&&e.status;if("succeeded"!==n)if("failed"!==n){if("pending"===n)return o=0,c=0,void(d=setTimeout(r,t));c=0,o+=1,o>=2?p(new Error("Payment confirmation timeout")):d=setTimeout(r,t)}else p(new Error(e.reason||"Payment failed"));else h({type:"PAYMENT_SUCCESS",_requestId:a,newBalance:e.newBalance,transactionId:e.transactionId,receiptToken:e.receiptToken})}).catch(function(){l||(c+=1,c>=n?p(new Error("Payment confirmation timeout")):d=setTimeout(r,t))})}()},u);e._post({type:"PAYMENT_REQUEST",_requestId:a,amount:t,reason:n,data:i,idempotencyKey:s||void 0})})},onBalanceChange:function(e){const t=this;return t._balanceChangeHandler=e,function(){t._balanceChangeHandler===e&&(t._balanceChangeHandler=null)}}}}(Fe),Fe.session=function(e){return{_id:null,_data:{},getId:function(){return this._id||e.config.sessionId||null},getData:function(e){return e?this._data[e]:this._data},setData:function(t,n){"object"==typeof t?Object.assign(this._data,t):this._data[t]=n,e._post({type:"SESSION_DATA_UPDATE",data:this._data})},clear:function(){this._data={},e._post({type:"SESSION_DATA_CLEAR"})}}}(Fe),Fe.chat=function(e){return{sendMessage:function(t,n){return e._request("SEND_MESSAGE_REQUEST",{recipientId:t,message:n})},createPersonalChat:function(t){return e._request("CREATE_PERSONAL_CHAT",{peerUserId:t})}}}(Fe),Fe.bot=function(e){return{_messageHandler:null,callAction:function(t,n){return e._request("CALL_BOT",{action:t,data:n||{}},3e4)},sendMessage:function(t){e._post({type:"SEND_USER_MESSAGE",text:t})},updateContext:function(t){e._post({type:"UPDATE_CONTEXT",context:t})},close:function(t){e._post({type:"CLOSE",result:t})},onMessage:function(e){this._messageHandler=e}}}(Fe),Fe.fileStorage=(Ge=Fe,{set:function(e,t,n){return Ge._request("FILE_STORAGE_SET",{key:e,base64Data:t,mimeType:n||"application/octet-stream"},3e4).then(function(){})},get:function(e){return Ge._request("FILE_STORAGE_GET",{key:e},3e4).then(function(e){return e&&e.base64Data?{base64Data:e.base64Data,mimeType:e.mimeType}:null})},remove:function(e){return Ge._request("FILE_STORAGE_REMOVE",{key:e}).then(function(){})}}),Fe.game=function(n){const r={socket:null,directSocket:null,roomId:null,playerId:null,connected:!1,directMode:!1,directConfig:null,_directSeq:0,_eventHandlers:{},_lastSequence:0,_connecting:!1,_connectPromise:null,_joined:!1,_joinPromise:null,_useProxy:!1,_proxyListenerSetup:!1,_heartbeatInterval:null,_pingMeter:null,_pongWaiters:[],_lastActionApplied:0,_rejoinPromise:null,connect:function(e,t){const i=this;return"direct"===(n.config&&n.config.connectionMode||"platform")?i.connectDirect():i._useProxy&&i.connected||i.socket&&i.connected?Promise.resolve():i._connecting&&i._connectPromise?i._connectPromise:window.__USION_PROXY__||window.parent!==window||window.ReactNativeWebView||n._isEmbedded?(n.log("Running in iframe – using parent app as socket proxy"),i._connectViaProxy()):(e=e||n.config.socketUrl,t=t||n.user.getToken(),e?t?(i._connecting=!0,i._connectPromise=new Promise(function(n,r){if("undefined"==typeof io){var o=["/socket.io.min.js","https://usions.com/socket.io.min.js","https://cdn.socket.io/4.7.2/socket.io.min.js"];!function s(c){if(c>=o.length)return i._connecting=!1,void r(new Error("Failed to load Socket.IO client"));var a=document.createElement("script");a.src=o[c],a.onload=function(){i._initSocket(e,t,n,r)},a.onerror=function(){s(c+1)},document.head.appendChild(a)}(0)}else i._initSocket(e,t,n,r)}),i._connectPromise):Promise.reject(new Error("No auth token available")):Promise.reject(new Error("No socket URL provided")))},onJoined:function(e){return this._setHandler("joined",e)},onPlayerJoined:function(e){return this._setHandler("playerJoined",e)},onPlayerLeft:function(e){return this._setHandler("playerLeft",e)},onStateUpdate:function(e){return this._setHandler("stateUpdate",e)},onSync:function(e){return this._setHandler("sync",e)},onAction:function(e){return this._setHandler("action",e)},onRealtime:function(e){return this._setHandler("realtime",e)},onGameFinished:function(e){return this._setHandler("finished",e)},onGameRestarted:function(e){return this._setHandler("restarted",e)},onError:function(e){return this._setHandler("error",e)},onRematchRequest:function(e){return this._setHandler("rematchRequest",e)},onDisconnect:function(e){return this._setHandler("disconnect",e)},onReconnect:function(e){return this._setHandler("reconnect",e)},onConnectionError:function(e){return this._setHandler("connectionError",e)},onPlayerConnection:function(e){return this._setHandler("playerConnection",e)},onRoomAssigned:function(e){return this._setHandler("roomAssigned",e)},_setHandler:function(e,t){const n=this;return n._eventHandlers[e]=t,function(){n._eventHandlers[e]===t&&(n._eventHandlers[e]=null)}},_dispatch:function(e){const t=Array.prototype.slice.call(arguments,1),i=this._eventHandlers[e];if(i)try{i.apply(null,t)}catch(t){n.log("game handler error ("+e+"): "+t.message)}const r=this._listeners[e];if(r&&r.length){const i=r.slice();for(let r=0;r<i.length;r++)try{i[r].apply(null,t)}catch(t){n.log("game listener error ("+e+"): "+t.message)}}},on:function(e,t){const n=this,i=function(e){let t=String(e||"");if(0===t.indexOf("game:")&&(t=t.slice(5)),He[t])return He[t];const n=t.replace(/([A-Z])/g,function(e){return"_"+e.toLowerCase()});return He[n]||t}(e);return n._listeners[i]||(n._listeners[i]=[]),n._listeners[i].push(t),function(){const e=n._listeners[i];if(!e)return;const r=e.indexOf(t);r>=0&&e.splice(r,1)}},_listeners:{}};return function(e,t){e.connectDirect=function(e){var n=this;return e=e||{},n.directMode&&n.directSocket&&n.connected?Promise.resolve():(n._connecting&&n._connectPromise||(n._resConfigure&&n._resConfigure(e),n._connecting=!0,n.directMode=!0,n._autoReconnect=void 0!==e.autoReconnect?e.autoReconnect:!(t.config&&!1===t.config.autoReconnect),n._connectPromise=n._fetchDirectAccess(e).then(function(e){return n.directConfig=e,n._initDirectSocket(e)}).then(function(){n.connected=!0,n._connecting=!1,t.log("Direct game socket connected")}).catch(function(e){throw n._connecting=!1,n.connected=!1,n.directMode=!1,n._dispatch("connectionError",e),e})),n._connectPromise)},e._fetchDirectAccess=function(e){var n=e.roomId||this.roomId||t.config.roomId,i=e.serviceId||t.config.serviceId,r=e.apiUrl||t.config.apiUrl||"",o=e.token||t.user.getToken();if(!n)return Promise.reject(new Error("No room ID provided"));if(!i)return Promise.reject(new Error("No service ID provided"));if(this.roomId=n,this.playerId=t.user.getId(),t._isEmbedded)return t._request("GAME_ACCESS_REQUEST",{room_id:n,service_id:i,protocol_version:e.protocolVersion||t.config.protocolVersion||t.config.protocol_version||"2"},1e4);if(!r)return Promise.reject(new Error("No API URL provided"));if(!o)return Promise.reject(new Error("No auth token available"));var s=String(r).replace(/\/$/,"")+"/games/rooms/"+encodeURIComponent(n)+"/access";return fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o},body:JSON.stringify({service_id:i,client_type:"iframe",protocol_version:e.protocolVersion||t.config.protocolVersion||t.config.protocol_version||"2"})}).then(function(e){return e.ok?e.json():e.text().then(function(t){throw new Error(t||"Direct access failed: HTTP "+e.status)})})},e._initDirectSocket=function(e){var t=this;return new Promise(function(n,i){if(e&&e.ws_url&&e.access_token){var r=e.ws_url,o=-1===r.indexOf("?")?"?":"&",s=r+o+"token="+encodeURIComponent(e.access_token),c=new WebSocket(s);t.directSocket=c;var a=!1,u=!1,l=setTimeout(function(){if(!a){try{c.close()}catch(e){}i(new Error("Direct WebSocket connection timeout"))}},1e4);c.onopen=function(){a=!0,clearTimeout(l),u||(u=!0,t._sendDirect("join",{})),t._heartbeatInterval&&clearInterval(t._heartbeatInterval),t._heartbeatInterval=setInterval(function(){t.directSocket&&t.directSocket.readyState===WebSocket.OPEN&&t._sendDirect("heartbeat",{})},25e3),t._resOnOpen&&t._resOnOpen(),n()},c.onerror=function(){a||(clearTimeout(l),i(new Error("Direct WebSocket connection error")))},c.onclose=function(e){t._resOnClose&&t._resOnClose(e),t.connected=!1,t._joined=!1,t._joinPromise=null,t._heartbeatInterval&&(clearInterval(t._heartbeatInterval),t._heartbeatInterval=null),t._dispatch("disconnect",e&&e.reason?e.reason:"direct socket closed"),t.directMode&&!1!==t._autoReconnect&&t._scheduleDirectReconnect()},c.onmessage=function(e){t._res&&(t._res.lastInboundAt=Date.now()),t._handleDirectMessage(e&&e.data)}}else i(new Error("Invalid direct access payload"))})},e._scheduleDirectReconnect=function(){var e=this;if(!e._reconnecting){e._reconnecting=!0;var t=e._reconnectAttempt||0,n=function(){e.directMode?(t+=1,e._reconnectAttempt=t,(e._resCanReuseToken&&e._resCanReuseToken()?Promise.resolve(e.directConfig):e._fetchDirectAccess({})).then(function(t){return e.directConfig=t,e._initDirectSocket(t)}).then(function(){e.connected=!0,e._reconnecting=!1,e._reconnectAttempt=0,e._dispatch("reconnect",t),e.roomId&&e.requestSync(e._lastSequence||0)}).catch(function(){if(e.directMode){var i=Math.min(1e3*Math.pow(2,t-1),15e3);setTimeout(n,i)}else e._reconnecting=!1})):e._reconnecting=!1};setTimeout(n,100)}},e._sendDirect=function(e,t){this.directSocket&&this.directSocket.readyState===WebSocket.OPEN&&("input"===e&&this._resHoldInput&&this._resHoldInput(t)||(this._directSeq=this._directSeq+1,this.directSocket.send(JSON.stringify({type:e,room_id:this.roomId,ts:Date.now(),seq:this._directSeq,session_id:this.directConfig&&this.directConfig.session_id?this.directConfig.session_id:null,protocol_version:this.directConfig&&this.directConfig.protocol_version?this.directConfig.protocol_version:"2",payload:t||{}}))))},e._handleDirectMessage=function(e){var t;try{t="string"==typeof e?JSON.parse(e):e}catch(e){return}if(t&&t.type){var n=t.payload||{};if("joined"===t.type)return this._joined=!0,void this._dispatch("joined",n);if("player_joined"!==t.type)if("player_left"!==t.type){if("state_snapshot"===t.type||"state_delta"===t.type)return this._dispatch("realtime",n),void this._dispatch("stateUpdate",n);if("pong"===t.type){var i=this._pongWaiters&&this._pongWaiters.length?this._pongWaiters.shift():null;return this._resOnPong&&this._resOnPong(i),i&&i(),void this._dispatch("sync",n)}"match_end"!==t.type?"error"===t.type&&this._dispatch("error",n):this._dispatch("finished",n)}else this._dispatch("playerLeft",n);else this._dispatch("playerJoined",n)}}}(r,n),x(r,n),function(e,t){e._initSocket=function(e,n,i,r){const o=this;if(o.socket&&o.socket.connected)return o._connecting=!1,void i();o.socket&&(o.socket.disconnect(),o.socket=null);try{o.socket=io(e,{path:"/socket.io",transports:["websocket","polling"],auth:{token:n},autoConnect:!0,reconnection:!0,reconnectionAttempts:50,reconnectionDelay:1e3,reconnectionDelayMax:1e4}),t._bindBackendSocket&&t._bindBackendSocket(o.socket);var s=!1;o.socket.io&&"function"==typeof o.socket.io.on&&o.socket.io.on("reconnect_attempt",function(e){o._reconnAttempts=e}),o.socket.on("connect",function(){var e=s;if(s=!0,o.connected=!0,o._connecting=!1,t.log("Game socket connected"),o._heartbeatInterval&&clearInterval(o._heartbeatInterval),o._heartbeatInterval=setInterval(function(){o.socket&&o.connected&&o.roomId&&o.socket.emit("game:heartbeat",{room_id:o.roomId})},25e3),o.roomId){var n=o._lastSequence||0;o._joined=!1,o._joinPromise=null,o._rejoinPromise=o.join(o.roomId).then(function(){t.log("Reconnected - joined room "+o.roomId),o.requestSync(n)}).catch(function(e){t.log("Rejoin failed: "+(e&&e.message?e.message:String(e)))}).then(function(){o._rejoinPromise=null,o._flushOfflineQueue&&o._flushOfflineQueue()})}e&&(t.log("Game socket reconnected"),o._dispatch("reconnect",o._reconnAttempts||1),o._reconnAttempts=0),i()}),o.socket.on("connect_error",function(e){o._connecting=!1,t.log("Game socket error: "+e.message),o._dispatch("connectionError",e),r(e)}),o.socket.on("disconnect",function(e){o.connected=!1,o._joined=!1,o._joinPromise=null,o._heartbeatInterval&&(clearInterval(o._heartbeatInterval),o._heartbeatInterval=null),t.log("Game socket disconnected: "+e),o._dispatch("disconnect",e)}),o.socket.on("game:joined",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("joined",e)}),o.socket.on("game:player_joined",function(e){o._dispatch("playerJoined",e)}),o.socket.on("game:player_left",function(e){o._dispatch("playerLeft",e)}),o.socket.on("game:state",function(e){void 0!==e.sequence&&(o._lastSequence=Math.max(o._lastSequence,e.sequence)),o._dispatch("stateUpdate",e)}),o.socket.on("game:sync",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("sync",e),o._dispatch("stateUpdate",e)}),o.socket.on("game:action",function(e){if(void 0!==e.sequence){if(e.sequence<=o._lastActionApplied)return;o._lastActionApplied=e.sequence,o._lastSequence=Math.max(o._lastSequence,e.sequence)}o._dispatch("action",e)}),o.socket.on("game:player_connection",function(e){o._dispatch("playerConnection",e)}),o.socket.on("game:realtime",function(e){o._dispatch("realtime",e)}),o.socket.on("game:finished",function(e){void 0!==e.sequence&&(o._lastSequence=e.sequence),o._dispatch("finished",e)}),o.socket.on("game:error",function(e){t.log("Game error: "+(e.message||e.code)),o._dispatch("error",e)}),o.socket.on("game:rematch_request",function(e){o._dispatch("rematchRequest",e)}),o.socket.on("game:restarted",function(e){o._lastSequence=0,o._lastActionApplied=0,o._dispatch("restarted",e)})}catch(e){r(e)}}}(r,n),function(n,r){n._connectViaProxy=function(){var n=this;return n._useProxy&&n.connected?Promise.resolve():(n._useProxy=!0,n._connecting=!0,n._setupProxyListener(),n._connectPromise=new Promise(function(i,o){n._proxyConnectResolve=function(){n.connected=!0,n._connecting=!1,r.log("Game socket connected via parent proxy"),i()},r._post({type:"GAME_CONNECT"}),setTimeout(function(){n.connected||(n._connecting=!1,o(new t(e.CONNECT_TIMEOUT,"Proxy connection timeout")))},1e4)}),n._connectPromise)},n._setupProxyListener=function(){var e=this;e._proxyListenerSetup||(e._proxyListenerSetup=!0,window.addEventListener("message",function(t){if(g(t)){var n;try{n=y(t)}catch(e){return}if(n&&"object"==typeof n&&e._useProxy)switch(n.type){case"GAME_CONNECTED":e._proxyConnectResolve&&(e._proxyConnectResolve(),e._proxyConnectResolve=null);break;case"GAME_CONNECT_ERROR":e.connected=!1,e._connecting=!1;break;case"GAME_DISCONNECTED":e.connected=!1,e._dispatch("disconnect",n.reason||"transport");break;case"GAME_RECONNECTED":e.connected=!0,e._dispatch("reconnect",n.attempts||1);break;case"GAME_PLAYER_CONNECTION":e._dispatch("playerConnection",n);break;case"GAME_JOINED":e._joined=!0,void 0!==n.sequence&&(e._lastSequence=n.sequence,e._lastActionApplied=Math.max(e._lastActionApplied,n.sequence)),e._proxyJoinResolve&&(e._proxyJoinResolve(n),e._proxyJoinResolve=null),e._proxyJoinReject=null,e._dispatch("joined",n);break;case"GAME_JOIN_ERROR":e._joined=!1,e._proxyJoinReject&&(e._proxyJoinReject(i(n.message||"Join failed")),e._proxyJoinReject=null),e._proxyJoinResolve=null;break;case"GAME_PLAYER_JOINED":e._dispatch("playerJoined",n);break;case"GAME_PLAYER_LEFT":e._dispatch("playerLeft",n);break;case"GAME_STATE":void 0!==n.sequence&&(e._lastSequence=Math.max(e._lastSequence,n.sequence)),e._dispatch("stateUpdate",n);break;case"GAME_ACTION_DATA":if(void 0!==n.sequence){if(n.sequence<=e._lastActionApplied)break;e._lastActionApplied=n.sequence,e._lastSequence=Math.max(e._lastSequence,n.sequence)}e._dispatch("action",n);break;case"GAME_REALTIME_DATA":e._dispatch("realtime",n);break;case"GAME_FINISHED":void 0!==n.sequence&&(e._lastSequence=n.sequence),e._dispatch("finished",n);break;case"GAME_ERROR":r.log("Game error via proxy: "+(n.message||n.code)),e._dispatch("error",n);break;case"GAME_RESTARTED":e._lastSequence=0,e._lastActionApplied=0,e._dispatch("restarted",n);break;case"GAME_REMATCH_REQUEST":e._dispatch("rematchRequest",n);break;case"GAME_SYNC":void 0!==n.sequence&&(e._lastSequence=n.sequence,e._lastActionApplied=Math.max(e._lastActionApplied,n.sequence)),e._dispatch("sync",n),e._dispatch("stateUpdate",n)}}}))}}(r,n),function(n,r){function o(e){const t=e.roomId||r.config&&r.config.roomId,n=e.playerId||r.user&&"function"==typeof r.user.getId&&r.user.getId()||r.config&&r.config.userId;return t&&n?"_usion_game_state:"+n+":"+t:null}n.join=function(n){const o=this;if(n=n||r.config.roomId,o.roomId===n&&o._joinPromise)return o._joinPromise;if(o.roomId=n,o.playerId=r.user.getId(),o.directMode)return o._joined=!0,o._joinPromise=Promise.resolve({room_id:n,player_id:o.playerId}),o._joinPromise;if(o._useProxy){const i=new Promise(function(i,s){const c=function(e){s(e)};o._proxyJoinResolve=i,o._proxyJoinReject=c,r._post({type:"GAME_JOIN",room_id:n}),setTimeout(function(){o._proxyJoinReject===c&&(o._proxyJoinResolve=null,o._proxyJoinReject=null,s(new t(e.JOIN_TIMEOUT,"Join timeout")))},15e3)});return H(o,i)}let s;return s=o.socket&&o.connected?n?B(o.socket,"game:join",{room_id:n},15e3,e.JOIN_TIMEOUT).then(function(e){if(e.error)throw o._joined=!1,i(e);return o._joined=!0,void 0!==e.sequence&&(o._lastSequence=e.sequence,o._lastActionApplied=Math.max(o._lastActionApplied,e.sequence)),o._dispatch("joined",e),e}):Promise.reject(new t(e.NO_ROOM,"No room ID provided")):Promise.reject(new t(e.NOT_CONNECTED,"Not connected")),H(o,s)},n.joinWorld=function(e){const t=this;return e=e||{},r.matchmaking._joinWorld(e.serviceId).then(function(e){return t.roomId=e.roomId,{roomId:e.roomId,playerIds:e.players||[]}})},n.leave=function(){const e=this;return e._playersConnection&&e._playersConnection.close(),e.directMode?(e.roomId&&e._sendDirect("leave",{}),e.roomId=null,e._lastSequence=0,e._joined=!1,void(e._joinPromise=null)):e._useProxy?(e.roomId&&r._post({type:"GAME_LEAVE",room_id:e.roomId}),e.roomId=null,e._lastSequence=0,e._joined=!1,void(e._joinPromise=null)):void(e.socket&&e.connected&&e.roomId&&(e.socket.emit("game:leave",{room_id:e.roomId}),e.roomId=null,e._lastSequence=0,e._joined=!1,e._joinPromise=null))},n.action=function(n,i,o){const s=this,c=o&&o.nextTurn,a=!(!o||!o.queueOffline);if(s.directMode)return s._sendDirect("action",{action_type:n||"default",action_data:i||{}}),Promise.resolve({success:!0});if(a&&!s.connected)return s._queueOfflineAction(n,i,o);if(s._useProxy){if(!s.connected)return Promise.reject(new t(e.NOT_CONNECTED,"Not connected"));const o={type:"GAME_ACTION",room_id:s.roomId,action_type:n,action_data:i};return c&&(o.next_turn=c),r._post(o),Promise.resolve({success:!0,acknowledged:!1})}return(s._rejoinPromise||Promise.resolve()).then(function(){if(!s.socket||!s.connected){if(a)return s._queueOfflineAction(n,i,o);throw new t(e.NOT_CONNECTED,"Not connected")}const r={room_id:s.roomId,action_type:n,action_data:i};return c&&(r.next_turn=c),s._emitAction(r,!0)})},n._emitAction=function(n,r){const o=this;return o.socket&&o.connected?B(o.socket,"game:action",n).then(function(t){if(t.error){const s=i(t);if(r&&s.code===e.NOT_IN_ROOM)return o._autoRejoin().then(function(){return o._emitAction(n,!1)});throw s}return void 0!==t.sequence&&(o._lastSequence=t.sequence),t}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n._autoRejoin=function(){const e=this;if(e._rejoinPromise)return e._rejoinPromise;if(!e.roomId||!e.socket||!e.connected)return Promise.resolve();r.log("Server reports socket not in room - auto-rejoining "+e.roomId);const t=e._lastSequence||0;return e._joined=!1,e._joinPromise=null,e._rejoinPromise=e.join(e.roomId).then(function(){e.requestSync(t)}).catch(function(e){r.log("Auto-rejoin failed: "+(e&&e.message?e.message:String(e)))}).then(function(){e._rejoinPromise=null,e._flushOfflineQueue&&e._flushOfflineQueue()}),e._rejoinPromise},n._queueOfflineAction=function(n,i,o){const s=this;return s._offlineQueue||(s._offlineQueue=[]),s._offlineQueue.length>=20?Promise.reject(new t(e.QUEUE_FULL,"Offline action queue is full (20)")):(r.log("Queued action while offline: "+n),new Promise(function(e,t){s._offlineQueue.push({actionType:n,actionData:i,opts:Object.assign({},o,{queueOffline:!1}),resolve:e,reject:t}),s._ensureOfflineFlushHook()}))},n._ensureOfflineFlushHook=function(){const e=this;e._offlineFlushHooked||(e._offlineFlushHooked=!0,e.on("reconnect",function(){e._flushOfflineQueue()}))},n._flushOfflineQueue=function(){const t=this,n=t._offlineQueue;if(!n||!n.length)return Promise.resolve();if(t._offlineFlushPromise)return t._offlineFlushPromise;if(!t.connected||!t._useProxy&&!t.directMode&&!t._joined)return Promise.resolve();r.log("Flushing "+n.length+" queued action(s) after reconnect");const o=Promise.resolve().then(function r(){if(!n.length)return Promise.resolve();if(!t.connected||!t._useProxy&&!t.directMode&&!t._joined)return Promise.resolve();const o=n[0];return t.action(o.actionType,o.actionData,o.opts).then(function(e){return n[0]===o&&n.shift(),o.resolve(e),r()},function(t){const s=i(t);if(s.code!==e.NOT_CONNECTED&&s.code!==e.NOT_IN_ROOM)return n[0]===o&&n.shift(),o.reject(t),r()})});function s(){t._offlineFlushPromise===o&&(t._offlineFlushPromise=null)}return t._offlineFlushPromise=o,o.then(s,s),o},n.setState=function(n){const o=this;if(o.directMode)return Promise.resolve({success:!1,error:"not_supported_in_direct_mode",code:e.UNSUPPORTED});const s=o._lastSequence||0,c=n&&1===n.__usionSyncedState&&Number.isSafeInteger(n.seq)&&n.seq>=0&&n.seq<=s?n.seq:s;return o._useProxy?r._request("GAME_SET_STATE",{room_id:o.roomId,state:n||{},sequence:c}).then(function(e){if(e&&e.error){const t=i(e);return{success:!1,error:t.message,code:t.code}}return e||{success:!0}}).catch(function(t){const n=i(t,e.REQUEST_TIMEOUT);return{success:!1,error:n.message,code:n.code}}):o.socket&&o.connected?B(o.socket,"game:set_state",{room_id:o.roomId,state:n||{},sequence:c}).then(function(e){if(e.error){const t=i(e);return{success:!1,error:t.message,code:t.code}}return Object.keys(e).length?e:{success:!0}}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n.realtime=function(t,n){const o=this;o.directMode?o._sendDirect("input",{action_type:t,action_data:n||{}}):o._useProxy?r._post({type:"GAME_REALTIME",room_id:o.roomId,action_type:t,action_data:n}):o.socket&&o.connected&&o.socket.emit("game:realtime",{room_id:o.roomId,action_type:t,action_data:n},function(t){if(!t||!t.error)return;const n=i(t);o._dispatch("error",{code:n.code,message:n.message,source:"realtime"}),n.code===e.NOT_IN_ROOM&&o._autoRejoin()})},n.requestSync=function(e){const t=this;e=void 0!==e?e:t._lastSequence,t.directMode?t._sendDirect("ping",{last_sequence:e||0}):t._useProxy&&t.roomId?r._post({type:"GAME_SYNC_REQUEST",room_id:t.roomId,last_sequence:e||0}):t.socket&&t.connected&&t.roomId&&t.socket.emit("game:sync_request",{room_id:t.roomId,last_sequence:e||0})},n.requestRematch=function(){const e=this;e.directMode?e._sendDirect("rematch",{}):e._useProxy&&e.roomId?r._post({type:"GAME_REMATCH",room_id:e.roomId}):e.socket&&e.connected&&e.roomId&&e.socket.emit("game:rematch",{room_id:e.roomId})},n.forfeit=function(){const n=this;return n.directMode?(n._sendDirect("forfeit",{}),Promise.resolve({success:!0})):n._useProxy?(r._post({type:"GAME_FORFEIT",room_id:n.roomId}),Promise.resolve({success:!0})):n.socket&&n.connected?B(n.socket,"game:forfeit",{room_id:n.roomId}).then(function(e){if(e.error)throw i(e);return e}):Promise.reject(new t(e.NOT_CONNECTED,"Not connected"))},n.reportResult=function(n,i){if(i=i||{},!((n=n||{}).draw||"string"==typeof n.winnerId&&n.winnerId))return Promise.reject(new t(e.INVALID_INPUT,"reportResult needs a winnerId (or draw: true)"));const o=n.roomId||this.roomId||r.config&&r.config.roomId||null;if(!o)return Promise.reject(new t(e.NO_ROOM,"reportResult needs a room — join a game first"));let s=null;return Array.isArray(n.standings)&&(s=n.standings.map(function(e){return"string"==typeof e?e:e&&(e.userId||e.user_id)||null}).filter(function(e){return"string"==typeof e&&e}),s.length||(s=null)),r._backendEmit("gc:match_result",{service_id:i.serviceId||r.config&&r.config.serviceId,room_id:o,winner_id:n.draw?null:n.winnerId,draw:!!n.draw,standings:s,scores:n.scores&&"object"==typeof n.scores?n.scores:null,display_score:null!=n.displayScore?String(n.displayScore):null,metric:null!=n.metric?String(n.metric):null,match_id:null!=n.matchId?String(n.matchId):null})},n.invite=function(e){const t=this;e=e||{};const n="undefined"!=typeof window&&(!!window.ReactNativeWebView||!!window.parent&&window.parent!==window),i=t.roomId||r.config&&r.config.roomId||null;if(!n){try{console.warn("[Usion] game.invite needs the Usion app; resolving as not sent.")}catch(e){}return Promise.resolve({success:!1,roomId:i,invited:[]})}const o={roomId:i};return"number"==typeof e.maxPlayers&&e.maxPlayers>0&&(o.maxPlayers=e.maxPlayers),r._request("GAME_INVITE_REQUEST",o,e.timeout||12e4).then(function(e){const n=(e=e||{}).roomId||i||null,r={success:!!e.success,roomId:n,invited:Array.isArray(e.invited)?e.invited:[]};return r.success&&n?Promise.resolve().then(function(){return t.connect()}).then(function(){return t.join(n)}).then(function(){return r}).catch(function(){return r}):r}).catch(function(){return{success:!1,roomId:i,invited:[]}})},n.disconnect=function(){const e=this;if(e._playersConnection&&e._playersConnection.close(),e._heartbeatInterval&&(clearInterval(e._heartbeatInterval),e._heartbeatInterval=null),e.directMode){if(e.directSocket)try{e.directSocket.close()}catch(e){}return e.directSocket=null,e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null,e.directMode=!1,e.directConfig=null,void(e._directSeq=0)}if(e._useProxy)return r._post({type:"GAME_DISCONNECT"}),e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null,void(e._useProxy=!1);e.socket&&(e.socket.disconnect(),e.socket=null,e.connected=!1,e.roomId=null,e._lastSequence=0,e._connecting=!1,e._connectPromise=null,e._joined=!1,e._joinPromise=null)},n.saveState=function(e){const t=o(this);if(!t)return!1;try{return localStorage.setItem(t,JSON.stringify({state:e,savedAt:Date.now()})),!0}catch(e){return!1}},n.loadState=function(){const e=o(this);if(!e)return null;try{const t=localStorage.getItem(e);if(!t)return null;const n=JSON.parse(t);return n&&void 0!==n.state?n.state:null}catch(e){return null}},n.clearState=function(){const e=o(this);if(e)try{localStorage.removeItem(e)}catch(e){}},n.debug=function(e){try{var t=window.parent&&window.parent!==window,n=!!window.ReactNativeWebView;if(t||n){var i=Object.assign({},e||{});i._diag=r.diagnostics?r.diagnostics():void 0,r._post({type:"GAME_DEBUG",payload:i})}}catch(e){}},n.isMultiplayer=function(){return"multiplayer"===r.getLaunchParams().mode},n.isConnected=function(){return this.directMode?!(!this.connected||!this.directSocket||this.directSocket.readyState!==WebSocket.OPEN):this._useProxy?!!this.connected:!!(this.connected&&this.socket&&this.socket.connected)}}(r,n),qe(r,n),function(e,t){e.connectPlayers=function(n={}){if(e._playersConnection&&!e._playersConnection.closed)return e._playersPromise;if(e.directMode||"direct"===t.config.connectionMode)return Promise.reject(new Error("connectPlayers requires platform room signaling"));if(!xe(t.user.getId()))return Promise.reject(new Error("Initialize Usion before connectPlayers"));if(void 0!==n.directTimeoutMs&&(!Number.isFinite(n.directTimeoutMs)||n.directTimeoutMs<1e3||n.directTimeoutMs>3e4))return Promise.reject(new Error("directTimeoutMs must be 1000–30000"));const i=e._playersConnection=new Be(e,t,n);return e._playersPromise=i.start().catch(e=>{throw i.close(),e}),e._playersPromise}}(r,n),function(e,t){e.getParticipants=async function(){const e=this.roomId;if(!e)throw new Error("Join a room before reading participants");for(let n=0;n<5;n++){const i=t.user.getToken();if(!i){if(n<4){await new Promise(e=>setTimeout(e,500));continue}throw new Error("Participant access needs an authenticated Usions session")}const r=String(t.config.apiUrl||"").replace(/\/$/,"");if(!r)throw new Error("No API URL provided");const o=await fetch(r+"/games/rooms/"+encodeURIComponent(e)+"/participants",{headers:{Authorization:"Bearer "+i},cache:"no-store"});if(401===o.status&&n<4){await new Promise(e=>setTimeout(e,500));continue}if(!o.ok)throw new Error("Participant access failed: HTTP "+o.status);const s=await o.json();if(this.roomId!==e)throw new Error("Room changed while loading participants");return s}}}(r,n),function(e,t){function n(t){var n=e[t];"function"==typeof n&&(e[t]=function(){var e=this;return n.apply(e,arguments).then(function(t){return e._awaitResync||e._setConnState("connected"),t})})}function i(t){t&&(t.host_id?e._hostId=t.host_id:t.player_ids&&t.player_ids.length&&(e._hostId=t.player_ids[0]))}e.getLastSequence=function(){return this._lastSequence||0},e.getLastAppliedSequence=function(){return this._lastActionApplied||0},e._connState="disconnected",e._awaitResync=!1,e._setConnState=function(e){this._connState!==e&&(this._connState=e,this._dispatch("connectionState",e))},e.getConnectionState=function(){return this._connState},e.onConnectionState=function(e){return this._setHandler("connectionState",e)},e.onReconnected=function(e){return this._setHandler("reconnected",e)},e.on("disconnect",function(){e._awaitResync=!1,e._setConnState("disconnected")}),e.on("reconnect",function(){e.roomId?(e._awaitResync=!0,e._setConnState("rejoining")):e._setConnState("connected")}),e.on("sync",function(t){e._awaitResync&&(e._awaitResync=!1,e._dispatch("reconnected",{state:t&&t.game_state||null,lastSequence:e._lastSequence||0,viaSync:!0}),e._setConnState("reconnected"),e._setConnState("connected"))}),n("connect"),n("connectDirect"),e._hostId=null,e.on("joined",i),e.on("playerJoined",i),De(e,t)}(r,n),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("visibilitychange",function(){if("visible"===document.visibilityState&&r.roomId)try{r.requestSync()}catch(e){}}),r}(Fe),Fe.UsionError=t,Fe.ERROR_CODES=e,function(n){n._backendHandlers={},n._boundSockets="undefined"!=typeof WeakSet?new WeakSet:null,n._bindBackendSocket=function(e){if(!e||"function"!=typeof e.onAny)return;if(this._boundSockets){if(this._boundSockets.has(e))return;this._boundSockets.add(e)}const t=this;e.onAny(function(e,n){const i=t._backendHandlers[e];i&&i(n)})},n._backendOn=function(e,t){this._backendHandlers[e]=t;const n=this.game&&this.game.socket;n&&("function"==typeof n.onAny?this._bindBackendSocket(n):"function"==typeof n.on&&n.on(e,t))},n._backendEmit=function(n,r,o){const s=this;function c(s){return new Promise(function(c,a){let u=!1;const l=setTimeout(function(){u||(u=!0,a(new t(e.REQUEST_TIMEOUT,"Backend request timeout")))},o);try{s.emit(n,r||{},function(e){u||(u=!0,clearTimeout(l),e&&e.error?a(i(e)):c(e))})}catch(e){clearTimeout(l),a(i(e))}})}o=o||8e3;const a=s.game&&s.game.socket;if(a&&a.connected)return c(a);if(s._isEmbedded)return s._request("BACKEND_EMIT",{event:n,data:r||{}},o).catch(function(e){throw i(e)});const u=s.config&&s.config.connectionMode||"platform";return!a&&"direct"!==u&&s.game&&"function"==typeof s.game.connect?s.game.connect().then(function(){const n=s.game.socket;if(n&&n.connected)return c(n);throw new t(e.NOT_CONNECTED,"No backend connection")}).catch(function(n){if(n instanceof t)throw n;throw new t(e.NOT_CONNECTED,"Backend connect failed: "+(n&&n.message?n.message:String(n)))}):Promise.reject(new t(e.NOT_CONNECTED,"No backend connection — socket is offline or reconnecting"))}}(Fe),Fe.lobby=function(e){const t={code:null,host:null,status:null,members:[]},n={};let i=!1;function r(){i||(i=!0,e._backendOn("lobby:update",function(e){t.code=e.code,t.host=e.host,t.status=e.status,t.members=e.members||[],n.update&&n.update(e)}),e._backendOn("lobby:started",function(e){t.status="started",n.started&&n.started(e)}))}function o(t,n){return r(),e._backendEmit(t,n)}return{get state(){return t},onUpdate:function(e){n.update=e,r()},onStarted:function(e){n.started=e,r()},create:async function(e){e=e||{};const n=await o("lobby:create",{max_players:e.maxPlayers||8,public:!!e.public});return n&&n.code&&(t.code=n.code),n},join:async function(e){const n=await o("lobby:join",{code:String(e||"").toUpperCase()});return n&&n.code&&(t.code=n.code),n},leave:function(){return t.code=null,o("lobby:leave",{}).catch(function(){})},setReady:function(e){return o("lobby:ready",{ready:!1!==e})},allReady:function(){return t.members.length>0&&t.members.every(function(e){return e.ready})},isHost:function(){const n=e.user&&e.user.getId&&e.user.getId();return!(!t.host||!n||t.host!==n)},start:function(e){return o("lobby:start",{room_id:e})},queue:async function(t,n){n=n||{};const i=e.config&&e.config.apiUrl||"",r=e.user&&e.user.getToken&&e.user.getToken();if(!i)throw new Error("No apiUrl configured");const o=await fetch(i.replace(/\/$/,"")+"/games/matchmake",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+r},body:JSON.stringify({service_id:t,conversation_id:n.conversationId||"standalone_"+t})});if(!o.ok)throw new Error("Matchmake failed: HTTP "+o.status);return o.json()}}}(Fe),Fe.leaderboard=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}return{submit:function(n,i,r){return e._backendEmit("lb:submit",{service_id:t(r),score:n,metadata:null!=i?i:null})},scores:function(n,i){var r=Array.isArray(n)?n:[n];return e._backendEmit("lb:scores",{service_id:t(i),user_ids:r}).then(function(e){return e&&e.scores||{}})},friends:function(n){return n=n||{},e._backendEmit("lb:friends",{service_id:t(n),limit:n.limit||50}).then(function(e){return e&&e.entries||[]})},top:function(n){return n=n||{},e._backendEmit("lb:top",{service_id:t(n),limit:n.limit||20}).then(function(e){return e&&e.entries||[]})},me:function(n){return e._backendEmit("lb:me",{service_id:t(n)})}}}(Fe),Fe.cloud=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}function n(n,i,r,o){var s=Object.assign({service_id:t(o),scope:i},r);return e._backendEmit(n,s)}function i(e){return{get:function(t,i){return n("kv:get",e,{key:t},i).then(function(e){return e&&e.exists?e.value:null})},set:function(t,i,r){return n("kv:set",e,{key:t,value:i},r)},remove:function(t,i){return n("kv:remove",e,{key:t},i)},keys:function(t){return n("kv:keys",e,{},t).then(function(e){return e&&e.keys||[]})}}}var r=i("user");return r.shared=i("shared"),r.friends=i("friends"),r.friends.list=function(e,t){return n("kv:get","friends",{key:e,friends:!0},t).then(function(e){return(e&&e.entries||[]).map(function(e){return{userId:e.user_id,name:e.name||null,avatar:e.avatar||null,value:e.value,updatedAt:e.updated_at||null}})})},r.shared.incr=function(e,t,i){return n("kv:incr","shared",{key:e,delta:null==t?1:t},i).then(function(e){return e&&e.value})},r}(Fe),Fe.matchmaking=function(n){let r=null,o=null,s=!1;function c(e){return{roomId:e&&e.room_id,players:e&&e.player_ids||[],serviceId:e&&e.service_id}}function a(){s||(s=!0,n._backendOn("mm:matched",function(e){const t=c(e);if(o&&o(t),r){const e=r;r=null,e.resolve(t)}}))}function u(o,s,u){if(a(),r){const n=r;r=null,n.reject(new t(e.SUPERSEDED,"Superseded by a newer find()"))}let l=null;const d={},f=new Promise(function(e,t){d.resolve=function(t){l&&clearTimeout(l),e(t)},d.reject=function(e){l&&clearTimeout(l),r===d&&(r=null),t(e)}});return r=d,s>0&&(l=setTimeout(function(){l=null,n._backendEmit("mm:cancel",{}).catch(function(){}),d.reject(new t(e.MATCH_TIMEOUT,u+s+"ms"))},s)),n._backendEmit("mm:join",o).then(function(e){e&&e.matched&&e.room_id&&r===d&&(r=null,d.resolve(c(e)))}).catch(function(e){r===d&&d.reject(i(e))}),f}return{onMatch:function(e){o=e,a()},find:function(e,t){t=t||{};return u({service_id:e||n.config&&n.config.serviceId,size:t.size||2},t.timeout,"No match within ")},_joinWorld:function(e){return u({service_id:e||n.config&&n.config.serviceId,mode:"world"},15e3,"No world placement within ")},cancel:function(){if(r){const n=r;r=null,n.reject(new t(e.CANCELLED,"cancelled"))}return n._backendEmit("mm:cancel",{})}}}(Fe),Fe.notify=function(e){function t(t){return t&&t.serviceId||e.config&&e.config.serviceId}return{send:function(n){return n=n||{},e._backendEmit("notify:send",{service_id:t(n),title:n.title,body:n.body,path:n.path})},setMuted:function(n,i){return e._backendEmit("notify:set_pref",{service_id:t(i),muted:!!n})},isMuted:function(n){return e._backendEmit("notify:get_pref",{service_id:t(n)}).then(function(e){return!(!e||!e.muted)})}}}(Fe),Fe.permissions=function(e){function t(e){return"string"==typeof e?e?[e]:[]:Array.isArray(e)?e.filter(function(e){return"string"==typeof e&&e}):[]}function n(){return"undefined"!=typeof window&&(!!window.ReactNativeWebView||!!window.parent&&window.parent!==window)}function i(e){const t={};return e.forEach(function(e){t[e]=!1}),t}function r(e,t){const n=t||{};return{granted:e.length>0&&e.every(function(e){return!!n[e]}),permissions:n}}const o={_requestTimeoutMs:12e4,request:function(s,c){const a=t(s),u=c&&"string"==typeof c.reason?c.reason:void 0;if(!n()){try{console.warn("[Usion] permissions.request needs the Usion app; resolving as not granted.")}catch(e){}return Promise.resolve(r(a,i(a)))}return new Promise(function(t){const n=_();let s=!1,c=null;function l(e){s||(s=!0,c&&clearTimeout(c),window.removeEventListener("message",d),t(e))}function d(e){if(!g(e))return;let t;try{t=y(e)}catch(e){return}t&&t._requestId===n&&"PERMISSION_RESULT"===t.type&&l(r(a,t.permissions))}window.addEventListener("message",d),c=setTimeout(function(){s||o.query(a).then(function(e){l(r(a,e))}).catch(function(){l(r(a,i(a)))})},o._requestTimeoutMs||12e4),e._post({type:"PERMISSION_REQUEST",_requestId:n,permissions:a,reason:u})})},query:function(r){const o=t(r);return n()?e._request("PERMISSION_QUERY",{permissions:o},8e3).then(function(e){return e&&e.permissions||{}}):Promise.resolve(i(o))},has:function(e){return o.query([e]).then(function(t){return!(!t||!t[e])})}};return o}(Fe),Fe.screen=function(e){var t=[],n=!1;function i(e){if(g(e)){var n;try{n=y(e)}catch(e){return}if(n&&"SCREEN_CAPTURE"===n.type)for(var i="string"==typeof n.kind&&n.kind?n.kind:"screenshot",r=t.slice(),o=0;o<r.length;o++)try{r[o]({kind:i})}catch(e){}}}return{protect:function(t){try{e._post({type:"SCREEN_PROTECT",enabled:!!t})}catch(e){}},onCapture:function(e){if("function"!=typeof e)return function(){};t.push(e),n||"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("message",i),n=!0);var r=!1;return function(){if(!r){r=!0;var o=t.indexOf(e);o>=0&&t.splice(o,1),0===t.length&&function(){if(n){try{window.removeEventListener("message",i)}catch(e){}n=!1}}()}}},support:function(){var t=e.config&&e.config.screenCapture||null;return{block:!(!t||!t.block),detect:!(!t||!t.detect)}}}}(Fe),Fe.profile=function(n){function i(i,r){return"undefined"!=typeof window&&("ReactNativeWebView"in window||window.parent!==window)?n._request(i,r,3e4):Promise.reject(new t(e.UNSUPPORTED,"Profile content requires the Usion host"))}return{getContent:()=>i("PROFILE_CONTENT_GET",{}).then(e=>e.content),setContent:n=>!n||!Array.isArray(n.items)||n.items.length>50?Promise.reject(new t(e.INVALID_INPUT,"Profile content requires at most 50 items")):i("PROFILE_CONTENT_SET",{content:n}).then(e=>e.content),clearContent:()=>i("PROFILE_CONTENT_CLEAR",{}).then(()=>{})}}(Fe),Fe.call=function(e){return Object.assign(s(e),u(e),{capabilities:function(){return e._request("CALL_CAPABILITIES",{},5e3)},startAnalysis:async function(t){if(!t||!Array.isArray(t.capabilities)||"function"!=typeof t.onSample)throw new Error("capabilities and onSample are required");var n=null,i=!1,r=e.on("CALL_ANALYSIS_EVENT",function(e){i||null===n||e.subscriptionId!==n||t.onSample(e.sample)}),o=e.on("CALL_ANALYSIS_STOPPED",function(e){e.subscriptionId===n&&s()});function s(){i||(i=!0,r(),o(),"function"==typeof t.onStopped&&t.onStopped())}try{var c=await e._request("CALL_ANALYSIS_START",{capabilities:t.capabilities},12e4);if(!c.started||!Number.isInteger(c.subscriptionId))throw new Error("Invalid call analysis response");return n=c.subscriptionId,{stop:async function(){i||(s(),await e._request("CALL_ANALYSIS_STOP",{},5e3))}}}catch(e){throw s(),e}}})}(Fe),Fe.tabs=function(n){const i=new Set;function r(i,r){return n.config.hostFeatures?.tabControl?n._request(i,r):Promise.reject(new t(e.UNSUPPORTED,"Tab control requires a newer Usion host"))}function o(e){return"string"==typeof e&&e.startsWith("/")&&!e.startsWith("//")&&!/[\\\s\x00-\x1f]/.test(e)&&e.length<=2048}function s(e){return"string"==typeof e&&/^[a-zA-Z0-9_-]{1,64}$/.test(e)}function c(){return Promise.reject(new t(e.INVALID_INPUT,"Invalid tab navigation options"))}return{configure:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return c();const t=["landingTab","landingPath","lockedTabs","fallbackTab","fallbackPath"];return Object.keys(e).some(e=>-1===t.indexOf(e))||["landingTab","fallbackTab"].some(t=>void 0!==e[t]&&!s(e[t]))||["landingPath","fallbackPath"].some(t=>void 0!==e[t]&&!o(e[t]))||void 0!==e.lockedTabs&&(!Array.isArray(e.lockedTabs)||e.lockedTabs.length>32||e.lockedTabs.some(e=>!s(e)))?c():r("CONFIGURE_HOST_TABS",{...e})},open:function(e,t){return t=t||{},!s(e)||Object.keys(t).some(e=>"path"!==e)||void 0!==t.path&&!o(t.path)?c():r("OPEN_HOST_TAB",{tab:e,...void 0===t.path?{}:{path:t.path}})},onBlocked:function(e){return"function"!=typeof e?function(){}:(i.add(e),function(){i.delete(e)})},_dispatchBlocked:function(e){if(!s(e.tab))return;const t={tab:e.tab,...o(e.path)?{path:e.path}:{}};i.forEach(function(e){try{e(t)}catch(e){console.error("[Usion] tab listener error:",e)}})}}}(Fe),Fe.modal=function(n){function i(i,r,o){return n.config.hostFeatures?.modal?n._request(i,r,o):Promise.reject(new t(e.UNSUPPORTED,"Modals require a newer Usion host"))}return{open:n=>!n||"string"!=typeof n.path||!n.path.startsWith("/")||n.path.startsWith("//")||n.path.length>2048||void 0!==n.tab&&("string"!=typeof n.tab||!/^[a-zA-Z0-9_-]{1,64}$/.test(n.tab))||void 0!==n.title&&("string"!=typeof n.title||n.title.length>100)?Promise.reject(new t(e.INVALID_INPUT,"Invalid modal options")):i("OPEN_HOST_MODAL",{path:n.path,tab:n.tab,title:n.title},18e5),close:e=>i("CLOSE_HOST_MODAL",{result:e})}}(Fe),Fe.netcode=Ve,Object.assign(Fe,function(e){return{saveResult:function(t,n){return e._request("SAVE_RESULT",{data:t,metadata:n||{}},15e3)},deleteResult:function(t){return e._request("DELETE_RESULT",{resultId:t})},getResults:function(){return e._results||[]}}}(Fe)),Object.assign(Fe,function(e){return{claimBackButton:function(t){e._backButtonCallback=t,e._post({type:"CLAIM_BACK_BUTTON"})},releaseBackButton:function(){e._backButtonCallback=null,e._post({type:"RELEASE_BACK_BUTTON"})},setHeaderTitle:function(t){var n="string"==typeof t?Array.from(t.trim()).slice(0,60).join(""):"";e._post({type:"SET_HEADER_TITLE",title:n})}}}(Fe)),Object.assign(Fe,function(e){return{onHostNavigate:function(t){e._hostNavigateCallback=t,e._post({type:"HOST_NAVIGATE_SUBSCRIBED"})},offHostNavigate:function(){e._hostNavigateCallback=null,e._post({type:"HOST_NAVIGATE_UNSUBSCRIBED"})},openChat:function(t){t=t||{},e._post({type:"OPEN_CHAT_TAB",prefill:"string"==typeof t.prefill?t.prefill:void 0})},reportPath:function(t){"string"==typeof t&&t&&e._post({type:"TAB_CHANGED",path:t})}}}(Fe)),Object.assign(Fe,k),Object.assign(Fe,N),Object.assign(Fe,j),Fe}();"undefined"!=typeof window?window.Usion=Usion:"undefined"!=typeof globalThis&&(globalThis.Usion=Usion);
|
|
@@ -21,6 +21,18 @@ export function createBackButtonMethods(Usion) {
|
|
|
21
21
|
releaseBackButton: function() {
|
|
22
22
|
Usion._backButtonCallback = null;
|
|
23
23
|
Usion._post({ type: 'RELEASE_BACK_BUTTON' });
|
|
24
|
+
},
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Name the current page in the host's header, next to the host's back
|
|
28
|
+
* button. Call it on every page change; '' (or nothing) restores the
|
|
29
|
+
* app's own name. Fire-and-forget: where the host draws no header (a
|
|
30
|
+
* full-screen app, an older host) it does nothing.
|
|
31
|
+
* @param {string} [title] - Trimmed and capped at 60 characters
|
|
32
|
+
*/
|
|
33
|
+
setHeaderTitle: function(title) {
|
|
34
|
+
var text = typeof title === 'string' ? Array.from(title.trim()).slice(0, 60).join('') : '';
|
|
35
|
+
Usion._post({ type: 'SET_HEADER_TITLE', title: text });
|
|
24
36
|
}
|
|
25
37
|
};
|
|
26
38
|
}
|
package/src/modules/core.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { UsionError, toUsionError, ERROR_CODES } from './errors.js';
|
|
6
|
+
import { answerScreenCapture } from './screen-capture.js';
|
|
6
7
|
|
|
7
8
|
// Request ID counter for tracking async responses
|
|
8
9
|
let _requestId = 0;
|
|
@@ -72,11 +73,20 @@ export function isTrustedMessageSource(event) {
|
|
|
72
73
|
return true;
|
|
73
74
|
}
|
|
74
75
|
|
|
76
|
+
/**
|
|
77
|
+
* The payload of a host message: the WebView bridge delivers JSON text, a web
|
|
78
|
+
* parent delivers the object itself. Throws on malformed JSON (callers catch).
|
|
79
|
+
* @param {MessageEvent} event
|
|
80
|
+
*/
|
|
81
|
+
export function messageData(event) {
|
|
82
|
+
return typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
|
|
83
|
+
}
|
|
84
|
+
|
|
75
85
|
/**
|
|
76
86
|
* Core Usion object with init, _post, _request
|
|
77
87
|
*/
|
|
78
88
|
export const core = {
|
|
79
|
-
version: '2.
|
|
89
|
+
version: '2.39.1', // synced from package.json by scripts/sync-version.mjs
|
|
80
90
|
config: {},
|
|
81
91
|
_initialized: false,
|
|
82
92
|
_initCallback: null,
|
|
@@ -149,7 +159,7 @@ export const core = {
|
|
|
149
159
|
|
|
150
160
|
let data;
|
|
151
161
|
try {
|
|
152
|
-
data =
|
|
162
|
+
data = messageData(event);
|
|
153
163
|
} catch (e) {
|
|
154
164
|
return;
|
|
155
165
|
}
|
|
@@ -280,6 +290,9 @@ export const core = {
|
|
|
280
290
|
if (h) h(data.data);
|
|
281
291
|
}
|
|
282
292
|
|
|
293
|
+
// Internal: the host asks for a picture of the game canvas.
|
|
294
|
+
if (data.type === 'CAPTURE_SCREEN') answerScreenCapture(self, data);
|
|
295
|
+
|
|
283
296
|
// Handle a room assigned by the host AFTER launch — the solo→host
|
|
284
297
|
// promotion path. The user opened the game solo from Explore (launch
|
|
285
298
|
// mode 'single'), then shared it; the host created a room and tells us
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Usion SDK Game Proxy — postMessage relay through parent app
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import { isTrustedMessageSource } from './core.js';
|
|
5
|
+
import { isTrustedMessageSource, messageData } from './core.js';
|
|
6
6
|
import { UsionError, toUsionError, ERROR_CODES } from './errors.js';
|
|
7
7
|
|
|
8
8
|
/**
|
|
@@ -65,7 +65,7 @@ export function applyGameProxy(game, Usion) {
|
|
|
65
65
|
|
|
66
66
|
var data;
|
|
67
67
|
try {
|
|
68
|
-
data =
|
|
68
|
+
data = messageData(event);
|
|
69
69
|
} catch (e) {
|
|
70
70
|
return;
|
|
71
71
|
}
|
package/src/modules/misc.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Usion SDK Misc — submit, error, exit, share, log, on, requestPayment (legacy)
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import { isTrustedMessageSource } from './core.js';
|
|
5
|
+
import { isTrustedMessageSource, messageData } from './core.js';
|
|
6
6
|
export const miscMethods = {
|
|
7
7
|
/**
|
|
8
8
|
* Request payment from user (legacy method)
|
|
@@ -201,7 +201,7 @@ export const miscMethods = {
|
|
|
201
201
|
|
|
202
202
|
let data;
|
|
203
203
|
try {
|
|
204
|
-
data =
|
|
204
|
+
data = messageData(event);
|
|
205
205
|
} catch (e) {
|
|
206
206
|
return;
|
|
207
207
|
}
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* is no modal — request()/query() resolve to a benign "not granted" default and
|
|
20
20
|
* the user manages the grant inside the Usion app.
|
|
21
21
|
*/
|
|
22
|
-
import { getNextRequestId, isTrustedMessageSource } from './core.js';
|
|
22
|
+
import { getNextRequestId, isTrustedMessageSource, messageData } from './core.js';
|
|
23
23
|
|
|
24
24
|
export function createPermissionsModule(Usion) {
|
|
25
25
|
function normalizeList(perms) {
|
|
@@ -97,7 +97,7 @@ export function createPermissionsModule(Usion) {
|
|
|
97
97
|
if (!isTrustedMessageSource(event)) return;
|
|
98
98
|
let response;
|
|
99
99
|
try {
|
|
100
|
-
response =
|
|
100
|
+
response = messageData(event);
|
|
101
101
|
} catch (e) { return; }
|
|
102
102
|
if (!response || response._requestId !== requestId) return;
|
|
103
103
|
if (response.type === 'PERMISSION_RESULT') {
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Usion SDK — answer the host's request for a picture of the game (INTERNAL).
|
|
3
|
+
*
|
|
4
|
+
* Not an app-facing API: nothing here is reachable from `window.Usion`. The
|
|
5
|
+
* host shell sends `CAPTURE_SCREEN {requestId}` (through the same trusted
|
|
6
|
+
* listener as every other host message, see core.js) and gets back exactly
|
|
7
|
+
* one `SCREEN_CAPTURED {requestId, dataUrl}`, sent from the next animation
|
|
8
|
+
* frame (or after 250 ms when no frame comes). `dataUrl` is a
|
|
9
|
+
* JPEG data URL of the largest visible <canvas> (by laid-out area), longest
|
|
10
|
+
* side at most 720 px, or `null` when there is nothing worth sending — no
|
|
11
|
+
* canvas, a tainted or blank one, or a result too large. The host then carries
|
|
12
|
+
* on without a picture.
|
|
13
|
+
*
|
|
14
|
+
* Unrelated to `Usion.screen` (screen.js), which is about the USER capturing
|
|
15
|
+
* the screen; this is the host asking the app for its own canvas.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
var MAX_SIDE = 720; // longest side of the picture, px
|
|
19
|
+
var MAX_CHARS = 1200000; // longest data URL we hand back
|
|
20
|
+
var MAX_ID = 64;
|
|
21
|
+
|
|
22
|
+
/** @returns {string|null} JPEG data URL, or null (no canvas / blank / too big). May throw. */
|
|
23
|
+
function capture() {
|
|
24
|
+
/** @type {HTMLCanvasElement|undefined} */
|
|
25
|
+
var best;
|
|
26
|
+
var bestArea = 0;
|
|
27
|
+
for (var c of document.getElementsByTagName('canvas')) {
|
|
28
|
+
// Skip what nobody sees: an empty backing store, visibility:hidden, and
|
|
29
|
+
// display:none (which lays out as 0x0).
|
|
30
|
+
var area = c.width && c.height && getComputedStyle(c).visibility !== 'hidden'
|
|
31
|
+
? c.offsetWidth * c.offsetHeight : 0;
|
|
32
|
+
if (area > bestArea) { best = c; bestArea = area; }
|
|
33
|
+
}
|
|
34
|
+
if (!best) return null;
|
|
35
|
+
|
|
36
|
+
var scale = MAX_SIDE / Math.max(MAX_SIDE, best.width, best.height); // never enlarges
|
|
37
|
+
var copy = document.createElement('canvas');
|
|
38
|
+
var w = copy.width = (best.width * scale) | 0;
|
|
39
|
+
var h = copy.height = (best.height * scale) | 0;
|
|
40
|
+
// No 2D context throws on the next line, which the caller turns into null.
|
|
41
|
+
var ctx = /** @type {CanvasRenderingContext2D} */ (copy.getContext('2d'));
|
|
42
|
+
ctx.drawImage(best, 0, 0, w, h);
|
|
43
|
+
|
|
44
|
+
// One flat colour = nothing to see (also what a WebGL canvas without
|
|
45
|
+
// preserveDrawingBuffer reads as when nothing drew it this frame). Reading
|
|
46
|
+
// the pixels is also where a tainted canvas throws (caught by the caller).
|
|
47
|
+
var px = ctx.getImageData(0, 0, w, h).data;
|
|
48
|
+
var url;
|
|
49
|
+
return px.every((v, j) => v === px[j % 4])
|
|
50
|
+
|| (url = copy.toDataURL('image/jpeg', 0.7)).length > MAX_CHARS ? null : url;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The request being answered (its reply function), or null.
|
|
55
|
+
* @type {(function(): void)|null}
|
|
56
|
+
*/
|
|
57
|
+
var pending = null;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Answer one trusted `CAPTURE_SCREEN`: exactly one reply, never throws.
|
|
61
|
+
*
|
|
62
|
+
* The picture is taken inside the NEXT animation frame. Our callback is queued
|
|
63
|
+
* behind the game's own frame callback, so a WebGL canvas has just been drawn
|
|
64
|
+
* and its buffer is still readable (between frames it reads blank). If no
|
|
65
|
+
* frame comes within 250 ms (hidden page), a timer takes the picture instead.
|
|
66
|
+
* A request that arrives while another is pending is ignored.
|
|
67
|
+
*
|
|
68
|
+
* @param {{_post: function(object): void}} Usion
|
|
69
|
+
* @param {{requestId?: unknown}} data
|
|
70
|
+
*/
|
|
71
|
+
export function answerScreenCapture(Usion, data) {
|
|
72
|
+
var id = data.requestId;
|
|
73
|
+
if (pending || typeof id !== 'string' || !id || id.length > MAX_ID) return;
|
|
74
|
+
|
|
75
|
+
function reply() {
|
|
76
|
+
// Frame and timer both end up here; only the first one answers.
|
|
77
|
+
if (pending !== reply) return;
|
|
78
|
+
pending = null;
|
|
79
|
+
var dataUrl = null;
|
|
80
|
+
try {
|
|
81
|
+
dataUrl = capture();
|
|
82
|
+
} catch (e) {
|
|
83
|
+
// SecurityError (tainted canvas), no DOM, no 2D context — no picture.
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
Usion._post({ type: 'SCREEN_CAPTURED', requestId: id, dataUrl: dataUrl });
|
|
87
|
+
} catch (e) {
|
|
88
|
+
// No host to answer; its own timeout covers this.
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
pending = reply;
|
|
93
|
+
setTimeout(reply, 250);
|
|
94
|
+
try {
|
|
95
|
+
requestAnimationFrame(reply);
|
|
96
|
+
} catch (e) {
|
|
97
|
+
// No animation frames here — the timer answers.
|
|
98
|
+
}
|
|
99
|
+
}
|
package/src/modules/screen.js
CHANGED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
* `onCapture()` simply never fires, and `support()` reports all-false.
|
|
33
33
|
*/
|
|
34
34
|
|
|
35
|
-
import { isTrustedMessageSource } from './core.js';
|
|
35
|
+
import { isTrustedMessageSource, messageData } from './core.js';
|
|
36
36
|
|
|
37
37
|
export function createScreenModule(Usion) {
|
|
38
38
|
/** @type {Array<function>} */
|
|
@@ -46,7 +46,7 @@ export function createScreenModule(Usion) {
|
|
|
46
46
|
|
|
47
47
|
var data;
|
|
48
48
|
try {
|
|
49
|
-
data =
|
|
49
|
+
data = messageData(event);
|
|
50
50
|
} catch (e) {
|
|
51
51
|
return;
|
|
52
52
|
}
|
package/src/modules/wallet.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Usion SDK Wallet Module — wallet and payment operations
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import { getNextRequestId, isTrustedMessageSource } from './core.js';
|
|
5
|
+
import { getNextRequestId, isTrustedMessageSource, messageData } from './core.js';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* @param {object} Usion - Reference to the main Usion object
|
|
@@ -126,7 +126,7 @@ export function createWalletModule(Usion) {
|
|
|
126
126
|
|
|
127
127
|
let response;
|
|
128
128
|
try {
|
|
129
|
-
response =
|
|
129
|
+
response = messageData(event);
|
|
130
130
|
} catch (e) {
|
|
131
131
|
return;
|
|
132
132
|
}
|
package/types/index.d.ts
CHANGED
|
@@ -1377,6 +1377,14 @@ export interface UsionSDK {
|
|
|
1377
1377
|
// Back button
|
|
1378
1378
|
claimBackButton(callback: () => void): void;
|
|
1379
1379
|
releaseBackButton(): void;
|
|
1380
|
+
/**
|
|
1381
|
+
* Name the current page in the host's header, next to the host's back
|
|
1382
|
+
* button — draw no title bar or back arrow of your own. Call it on every
|
|
1383
|
+
* page change; `''` or no argument restores the app's own name. Trimmed and
|
|
1384
|
+
* capped at 60 characters. Fire-and-forget: it does nothing where the host
|
|
1385
|
+
* draws no header (a full-screen app, an older host). (SDK ≥ 2.39)
|
|
1386
|
+
*/
|
|
1387
|
+
setHeaderTitle(title?: string): void;
|
|
1380
1388
|
|
|
1381
1389
|
// Hybrid tabbed services (SDK ≥ 2.25)
|
|
1382
1390
|
/**
|