rune-sdk
Version:
Build a multiplayer game played by millions! Your game runs inside the Rune app with 10 million installs across [iOS](https://apps.apple.com/app/rune-games-and-voice-chat/id1450358364) and [Android](https://play.google.com/store/apps/details?id=ai.rune.ti
9 lines (8 loc) • 52.6 kB
JavaScript
/*
Copyright (c) 2024 Rune AI Inc.
All rights reserved.
This code is proprietary to Rune AI Inc.
The code may be used solely for accessing the Service provided by Rune AI Inc. following the Rune AI Inc. Terms of Service ("Terms") accessible at rune.ai/eula. You may not use this code for any use or purpose other than as expressly permitted by the Terms.
Restrictions set forth in the Terms include, but is not limited to, that you may not copy, adapt, modify, prepare derivative works based upon, distribute, license, sell, transfer, publicly display, publicly perform, transmit, stream, broadcast, attempt to discover any source code, reverse engineer, decompile, dissemble, or otherwise exploit the code as a whole or any portion of the code.
*/
"use strict";var e=require("rune-msgpack"),t=require("base-64"),r=require("compatto"),n=require("mutative");function o(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var a=o(e),i=o(t);function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function c(e){return function(e){if(Array.isArray(e))return s(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return s(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?s(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(e){return u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u(e)}var l=function(){return l=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},l.apply(this,arguments)};function d(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}function f(e,t,r,n){return new(r||(r=Promise))((function(o,a){function i(e){try{c(n.next(e))}catch(e){a(e)}}function s(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,s)}c((n=n.apply(e,t||[])).next())}))}function m(e,t){var r,n,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&s[0]?n.return:s[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,s[1])).done)return o;switch(n=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,n=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],n=0}finally{r=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function v(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function p(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,a=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=a.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return i}function g(e,t,r){if(r||2===arguments.length)for(var n,o=0,a=t.length;o<a;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}var E=function(e){for(var t=[],r=0,n=e.length;r<n;r++)t.push(String.fromCharCode(e[r]));return t.join("")},y=function(e){return i.encode(e)},_=function(e){return e.charCodeAt(0)},S=function(e){return Uint8Array.from(e,_)},I=function(e){return i.decode(e)};function T(e){var t=a.encode(e,{maxDepth:25});return"RUNE_MSG_V2;"+y(E(t))}var h,A=new(function(){function e(){this.lastDecodedValue="",this.lastDecodedMessage=void 0}return e.prototype.isClientMessage=function(e){if(!this.isRuneMsg(e))return!1;var t=this.decode(e);return t.runeGameEvent||t.runeGameCommand},e.prototype.decodeGameToClient=function(e){if(this.isRuneMsg(e))return this.decode(e).runeGameEvent},e.prototype.decodeClientToGame=function(e){if(this.isRuneMsg(e))return this.decode(e).runeGameCommand},e.prototype.decodeGameToServer=function(e){if(this.isRuneMsg(e))return this.decode(e).gameToServer},e.prototype.decodeServerToGame=function(e){if(this.isRuneMsg(e))return this.decode(e).serverToGame},e.prototype.isRuneMsg=function(e){return"string"==typeof e&&e.startsWith("RUNE_MSG_V2;")},e.prototype.decode=function(e){return e===this.lastDecodedValue||(this.lastDecodedValue=e,this.lastDecodedMessage=function(e){var t=S(I(e.slice("RUNE_MSG_V2;".length)));return a.decode(t)}(e)),this.lastDecodedMessage},e.prototype.encodeClientToGame=function(e){return T({runeGameCommand:e})},e.prototype.encodeGameToClient=function(e){return T({runeGameEvent:e})},e.prototype.encodeGameToServer=function(e){return T({gameToServer:e})},e.prototype.encodeServerToGame=function(e){return T({serverToGame:e})},e}());!function(e){e.GameToServer="G",e.ServerToGame="S"}(h||(h={}));function O(e){var t=p(e.split(";"),2),r=t[0],n=t[1];if(r&&n){var o=p(r.split(","),4),a=o[0],i=o[1],s=o[2],c=o[3];if(!a||!i||!c)throw new Error("Missing fields: "+a+","+i+","+c+" - "+r+" - "+e);var u=Number.parseInt(a),l=Number.parseInt(i);if(Number.isNaN(u))throw new Error("Invalid version number provided in game message: ".concat(u));if(Number.isNaN(l))throw new Error("Invalid game ID provided in game message: ".concat(l));if(!Object.values(h).includes(c))throw new Error("Invalid message type provided in game message: ".concat(c));return{version:u,gameId:l,sessionId:0===s.length?void 0:s,type:c}}}var P=function(){function e(e,t,n,o,a){this.compatto=r.compatto({dictionary:[]}),this.compatto=r.compatto({dictionary:n}),this.gameId=e,this.expectedSessionId=t,this.logger=o,this.sdkProtocolVersion=a}return e.prototype.encodeServerToGame=function(e,t){return void 0===t&&(t=!1),this.encodeHeader(h.ServerToGame)+";"+this.encodeBody(e,t)},e.prototype.encodeGameToServer=function(e,t){return void 0===t&&(t=!1),this.encodeHeader(h.GameToServer)+";"+this.encodeBody(e,t)},e.prototype.encodeBody=function(e,t){var r=a.encode(e,{maxDepth:25});return this.sdkProtocolVersion>=4&&this.compatto&&t?"_"+y(E(this.compatto.compress(E(r)))):y(E(r))},e.prototype.decodeGameToServer=function(e,t){if("string"==typeof e){var r=O(e);if(r&&r.type===h.GameToServer)return this.decodeBody(r,e,t)}},e.prototype.decodeServerToGame=function(e,t){if("string"==typeof e){var r=O(e);if(r&&r.type===h.ServerToGame)return this.decodeBody(r,e,t)}},e.prototype.extractBody=function(e){var t=p(e.split(";"),2);return t[0],t[1]},e.prototype.decodeBody=function(e,t,r){var n,o=this.extractBody(t),i=o.startsWith("_");if(i){if(e.sessionId!==this.expectedSessionId)return void this.logger.onSessionMismatch(null!==(n=e.sessionId)&&void 0!==n?n:null,this.expectedSessionId,r);o=o.substring(1)}var s=S(I(o));return i&&(s=S(this.compatto.decompress(s))),a.decode(s)},e.prototype.encodeHeader=function(e){var t;return this.sdkProtocolVersion+","+this.gameId+","+(null!==(t=this.expectedSessionId)&&void 0!==t?t:"")+","+e},e}();function R(e){var t=e.sdkProtocolVersion,r=e.gameId,n=e.sessionId,o=e.dictionary,a=e.logger;return t>2?new P(r,n,o,a,t):A}function b(e){var t,r,n={};try{for(var o=v(Object.values(e)),a=o.next();!a.done;a=o.next()){var i=a.value;i.playerId&&(n[i.playerId]={playerId:i.playerId,displayName:i.displayName,avatarUrl:i.avatarUrl})}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return n}function M(e,t){return Math.floor(e/t)}function D(e,t){return e*t}function N(){return Math.floor(performance.now())}function C(e,t,r){return r*t-e}function G(e,t,r,n){if(!e)return null;var o=t.getUsers(),a={};return Object.keys(e).forEach((function(t){var i=Object.values(o).find((function(e){return e.playerId===t}));i?a[i.userId]=e[t]:r.error(n,"GAME_END_PERSIST_USER_NOT_FOUND",{playerId:t})})),a}function L(e,t){var r=(JSON.stringify(e)||"").length;return{size:r,underLimit:r<1024*t}}var w="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",x=w.length;var U={logInfo:{devDash:null}},k={devUIUnexpected:!0,logInfo:{devDash:null}};function j(e){return"Encountered <b>".concat(e,"</b>, which should never happen. Please let us know on [Discord](https://discord.gg/rune-devs).")}function V(e){return"[GAMES_SDK][".concat(e,"]")}var F,H,q,Y={ACTION_TRIGGERED_INVALID_ACTION:{devUIMessage:function(e){return'Action "'.concat(e.action,'" threw ').concat("Rune",".invalidAction() in the server. This action will be ignored.")},logInfo:{devDash:null}},GAME_TO_SERVER_MSG_SIZE:U,GAME_TO_SERVER_MSG:U,PLAYER_LEFT_AFTER_GAME_OVER:U,WRONG_TICK_CLIENT_AHEAD:U,WRONG_TICK_SERVER_SLOW:U,WRONG_TICK_MSG_ARRIVED_LATE:U,WRONG_TICK_UNEXPECTED_REASON:U,SERVER_TO_GAME_BROADCAST_MSG:U,SERVER_TO_GAME_MSG_SIZE:U,SERVER_TO_GAME_SEND_MSG:U},K=(F="LOGIC",H={STATE_SYNC_TOO_BIG:{devUIMessage:function(e){return"Your game state is too big (".concat(e.messageSize/1024,"kb). Maximum is ").concat(e.limit/1024," kb. See [game restrictions](https://developers.rune.ai/docs/how-it-works/syncing-game-state#restrictions) for more info.")}},GAME_OVER_INVALID_OPTIONS:{devUIMessage:"Your game called ".concat("Rune",".gameOver() with invalid options. See console for more details and [game over docs](https://developers.rune.ai/docs/api-reference#runegameoveroptions) for examples."),consoleMessage:function(e){return"Game over was called with invalid options:\n".concat(JSON.stringify(e.gameOverOptions,null,2),".")},printExtraDataInDevUI:!0},SERVER_UPDATE_LOOP_FAILED:{devUIMessage:"Your `update` function failed on the server. See the console for more details.",printExtraDataInDevUI:!0},ACTION_FAILED:{devUIMessage:function(e){return'Action "'.concat(e.action,'" failed on the server. See console for more details.')},printExtraDataInDevUI:!0},PLAYER_JOINED_FAILED:{devUIMessage:"Your `playerJoined` function failed on the server. See the console for more details.",printExtraDataInDevUI:!0},AI_PROMPT_RESPONSE_FAILED:{devUIMessage:"Your `ai.promptResponse` function failed on the server. See the console for more details.",printExtraDataInDevUI:!0},PLAYER_LEFT_FAILED:{devUIMessage:"Your `playerLeft` function failed on the server. See the console for more details.",printExtraDataInDevUI:!0},ACTION_PARAMS_SIZE_OVER_LIMIT:{devUIMessage:function(e){return'Action "'.concat(e.action,"' parameter size is ").concat(e.size/1024,"kb which is over allowed limit of ").concat(30,"kb.")}},SETUP_GAME_OVER_NOT_ALLOWED:{devUIMessage:"".concat("Rune",".gameOver() is not allowed in setup function.")},SETUP_FAILED:{devUIMessage:"Setup function failed.",printExtraDataInDevUI:!0},PERSISTED_STATE_USED_WITHOUT_FLAG:{devUIMessage:"To use game.persisted, you must set persistPlayerData: true inside ".concat("Rune",".initLogic().")},SETUP_PERSISTED_KEY_NOT_ALLOWED:{devUIMessage:'Setup function can\'t return "persisted" key. If you wish to modify persisted state, modify game.persisted instead.'},PERSISTED_NOT_AN_OBJECT:{devUIMessage:"game.persisted value must be set to an object."},PERSISTED_KEY_MISSING:{devUIMessage:"Removing game.persisted key is not allowed."},PERSISTED_EXTRA_KEY_DETECTED:{devUIMessage:function(e){return'Extra key "'.concat(e.key,'" in game.persisted detected. Only currently playing player ids as keys are allowed.')}},PERSISTED_PLAYER_MISSING:{devUIMessage:function(e){return"game.persisted is missing player ".concat(e.playerId," state. Make sure to return all players.")}},PERSISTED_PLAYER_NOT_AN_OBJECT:{devUIMessage:function(e){return'game.persisted["'.concat(e.playerId,'"] must be an object.')}},PERSISTED_PLAYER_OVER_LIMIT:{devUIMessage:function(e){return'game.persisted["'.concat(e.playerId,'"] size is ').concat(e.size/1024,"kb which is over allowed limit of ").concat(e.limit,"kb.")}},ACTION_TRIGGERED_IN_LOGIC:{devUIMessage:function(e){return"Action <b>".concat(e.triggeredAction,"</b> was triggered inside game logic. Actions can only be triggered from game client.")}},AI_PROMPT_RESPONSE_NOT_DEFINED:{devUIMessage:"To use ".concat("Rune",".ai.promptRequest() you need to have defined ai.promptResponse in your game logic.")},AI_PROMPT_REQUEST_PARAM_WRONG_FORMAT:{devUIMessage:"".concat("Rune",".ai.promptRequest() expects 1 argument in following format: {messages: {role: string, content: string}[]}")}},q={},Object.keys(H).forEach((function(e){q[e]=l(l({},H[e]),{logInfo:{devDash:{type:F,userType:"UNKNOWN"}}})})),q),W={SERVER_UPDATE_LOOP_FASTER_THAN_GAME_TIME:k,GET_GAME_STATE_FAILED:k,SERVER_RECEIVED_MESSAGE_TOO_BIG:k,SERVER_MESSAGE_TO_CLIENTS_TOO_BIG:k,SERVER_FULL:k,ON_PLAYER_JOINED_CALLBACK_MISSING:k,ROOM_GAME_STATE_MISSING:k,PERSIST_DATA_AFTER_ERROR_NOT_AVAILABLE:k,GET_PERSISTED_STATE_FAILED:k,GAME_END_PERSIST_USER_NOT_FOUND:k,PLAYER_LEFT_NO_USERS_INCORRECT_PERSISTED_PLAYERS:k,PERSISTED_STATE_NOT_ENABLED:k,UPDATE_LOOP_BEHIND_GAME_TIME:{devUIMessage:"Your game was in background for too long and was killed by your browser.",logInfo:{devDash:null}},AI_PROMPT_REQUEST_FAILED:k},B={errorMap:l(l({},K),W),infoMap:Y,warningMap:l({},{GAME_SESSION_ID_MISMATCH:k,CLIENT_MESSAGE_DECODE_FAILED:k,ACTION_PLAYER_ID_AUTHENTICATION_MISMATCH:k,ACTION_NO_SEED_OR_ACTION_COUNT:k,ACTION_WRONG_SEED:U,ACTION_COUNT_MISMATCH:U,ACTION_AFTER_GAME_OVER:U,PLAYER_LEFT_NO_PERSISTED_STATE:k})};function J(e){return function(e,t){function r(t,r,n,o,a){"runtime"!==e?o?t[r](o,n):t[r](n):t[r](l(l({isGameMsg:!0},a),o||{}),n)}function n(t,n,o,a,i){var s=o[a],c=V(a);if("test"===e||"runtime"===e)return r(n,t,c,i,s.logInfo),s;if(!s)return r(n,t,j(a),i),{logInfo:{devDash:null}};if("devUIUnexpected"in s)return r(n,t,j(a)),s;var u="consoleMessage"in s?s.consoleMessage:s.devUIMessage;return u&&(r(n,t,"string"==typeof u?u:u(i)),s.printExtraDataInDevUI&&i&&(i.err?console[t](i.err):console[t](i))),s}return{warn:function(e,r,o){return n("warn",e,t.warningMap,r,o)},error:function(e,r,o){return n("error",e,t.errorMap,r,o)},info:function(e,r,o){return n("info",e,t.infoMap,r,o)},getDevUIErrorMessage:function(e,r){var n=e.replace("[GAMES_SDK][","").replace("]",""),o=t.errorMap[n],a=V(n);return o?"devUIUnexpected"in o?j(n):o.devUIMessage?"string"==typeof o.devUIMessage?o.devUIMessage:o.devUIMessage(r):j(V("UNHANDLED_DEV_UI_SCENARIO")):a},getDevUIErrorTitle:function(e){var r=e.replace("[GAMES_SDK][","").replace("]",""),n=t.errorMap[r];if(n)return"devUIErrorTitle"in n?n.devUIErrorTitle:void 0}}}(e,B)}function z(e){return e.sort((function(e,t){return e>t?1:-1}))}function Q(e,t){if(!e)throw t instanceof Error?t:new Error(null!=t?t:"Assertion failed")}function Z(e){if("object"!=typeof e||null===e)return!1;var t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)}function X(e,t){var r=new Error("[GAMES_SDK][".concat(e,"]"));return t&&(r.extraLoggingData=t),r}function $(e,t,r){var n;return e&&"error"in e?"ROOM_GAME_STATE_MISSING":"string"!=typeof t&&(null===(n=null==t?void 0:t.message)||void 0===n?void 0:n.startsWith("[GAMES_SDK]"))?null==t?void 0:t.message.match(/\[GAMES_SDK]\[(.*)]/)[1]:r}function ee(e,t,r){return void 0===r&&(r=""),function(e){for(var t=0,r=1779033703^e.length;t<e.length;t++)r=(r=Math.imul(r^e.charCodeAt(t),3432918353))<<13|r>>>19;return r=Math.imul(r^r>>>16,2246822507),r=Math.imul(r^r>>>13,3266489909),(r^=r>>>16)>>>0}("".concat(r?r+"-":"").concat(e,"-").concat(t))}var te=["stateHash","orderNumber","serverGameTime","updateCount","logicTick","action","playerId","params","uuid","actionCount","sessionId","randomSeed","measureLatencyStart","expectedLogicTick"],re=function(e){var t;return(null!==(t=null==e?void 0:e.sdkProtocolVersion)&&void 0!==t?t:2)>=3};function ne(e){return 2*e.length<1048576}var oe=function e(t){var r=t,n={}.toString.call(t).slice(8,-1);if("Set"==n)return new Set(c(t).map((function(t){return e(t)})));if("Map"==n)return new Map(c(t).map((function(t){return[e(t[0]),e(t[1])]})));if("Date"==n)return new Date(t.getTime());if("RegExp"==n)return RegExp(t.source,function(e){if("string"==typeof e.source.flags)return e.source.flags;var t=[];return e.global&&t.push("g"),e.ignoreCase&&t.push("i"),e.multiline&&t.push("m"),e.sticky&&t.push("y"),e.unicode&&t.push("u"),t.join("")}(t));if("Array"==n||"Object"==n)for(var o in r=Array.isArray(t)?[]:{},t)r[o]=e(t[o]);return r};var ae="".concat("RUNE","_INVALID_ACTION");var ie=["acos","acosh","asin","asinh","atan","atan2","atanh","cbrt","cos","cosh","exp","expm1","hypot","log","log10","log1p","log2","pow","sin","sinh","sqrt","tan"];var se="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",ce=se.length;function ue(e){for(var t,r,n,o=(t=e,void 0===(r={sortKeys:!0})&&(r={}),a.encode(t,{maxDepth:25,sortKeys:null!==(n=r.sortKeys)&&void 0!==n&&n})),i=0,s=0;s<o.length;s++)i+=o[s];return i}var le={};Object.defineProperty(le,"__esModule",{value:!0});var de=le.default=function e(t){if("object"!==u(t)||null===t)return t;if(Array.isArray(t))return t.map((function(t){return"object"!==u(t)||null===t?t:e(t)}));var r={};for(var n in t){var o=t[n];r[n]="object"!==u(o)||null===o?o:e(o)}return r};function fe(e,t,r){if(!r){var o=de(e);return t(o),o}return n.create(e,t,{mark:function(){return"immutable"}})}var me=new Map;function ve(e){var t=me.get(e);if(!t)throw new Error("[GAMES_SDK][ROOM_GAME_STATE_MISSING]");return t}function pe(e,t){me.set(e,t)}function ge(e){me.delete(e)}function Ee(e){return"object"==typeof e&&!Array.isArray(e)&&null!==e}function ye(e,t){if(!e.persisted)throw X("PERSISTED_KEY_MISSING");if(!Ee(e.persisted))throw X("PERSISTED_NOT_AN_OBJECT");t.forEach((function(t){if(!e.persisted[t])throw X("PERSISTED_PLAYER_MISSING",{playerId:t});if(!Ee(e.persisted[t]))throw X("PERSISTED_PLAYER_NOT_AN_OBJECT",{playerId:t});var r=L(e.persisted[t],100);if(!r.underLimit)throw X("PERSISTED_PLAYER_OVER_LIMIT",{playerId:t,limit:100,size:r.size})})),Object.keys(e.persisted).forEach((function(e){if(!t.includes(e))throw X("PERSISTED_EXTRA_KEY_DETECTED",{key:e})}))}function _e(e){for(var t=Te(this,e),r=0;r<this.length;r++)this[r]=t[r];return this}var Se=function(e,t){if(void 0===e&&void 0===t)return 0;if(void 0===e)return 1;if(void 0===t)return-1;var r=Ie(e),n=Ie(t);return r<n?-1:r>n?1:0},Ie=function(e){if(null===e)return"null";if("boolean"==typeof e||"number"==typeof e)return e.toString();if("string"==typeof e)return e;if("symbol"==typeof e)throw new TypeError;return e.toString()};function Te(e,t){if(void 0===t&&(t=Se),e.length<=1)return e;var r=Math.floor(e.length/2),n=e.slice(0,r),o=e.slice(r);return function(e,t,r){var n=[];for(;e.length&&t.length;)r(e[0],t[0])<=0?n.push(e.shift()):n.push(t.shift());return n.concat(e,t)}(Te(n,t),Te(o,t),t)}function he(e,t){var r,n=globalThis.Math.random;globalThis.Math.random=(r=e,function(){var e=r+=1831565813;return e=Math.imul(e^e>>>15,1|e),(((e^=e+Math.imul(e^e>>>7,61|e))^e>>>14)>>>0)/4294967296});var o=globalThis.Array.prototype.sort;globalThis.Array.prototype.sort=_e;try{return t()}finally{globalThis.Math.random=n,globalThis.Array.prototype.sort=o}}function Ae(e,t,r){return e.state.gameOverContext=null,e.state.aiPromptRequest=null,e.context=t,he(t.randomSeed,r)}function Oe(e,t,r,n,o,a,i,s,c){return Ae(e,n,(function(){try{var n=ve(r),u=fe(n,o,e.gameConfig.reactive);if("runtime"!==t){if(!c&&u.persisted)throw X("PERSISTED_STATE_USED_WITHOUT_FLAG");n.persisted!==u.persisted&&ye(u,a)}return pe(r,u),{data:{gameContext:{gameOver:e.state.gameOverContext},stateHash:i?ue(u):void 0},aiPromptRequest:e.state.aiPromptRequest}}catch(e){if(s&&(function(e){return"object"==typeof e&&null!==e&&"name"in e}(l=e)&&("RUNE_INVALID_ACTION"===l.name||"DUSK_INVALID_ACTION"===l.name)))return{data:!1,aiPromptRequest:null};if("[GAMES_SDK][ROOM_GAME_STATE_MISSING]"===e.message)return{error:e.message};throw ge(r),e}var l}))}exports.canSwitchSpectatorToPlayer=function(e,t){return Object.keys(b(e)).length<t.maxPlayers},exports.createGameServer=function(e){var t,r=e.initialMsgLogger,n=e.params,o=n.gameId,a=n.roomId,i=n.sessionId,s=n.initialServerData,c=n.serverSeed,u=n.persistedUsers,E=n.serverStartedAt,y=e.flags,_=y.sendStateHash,S=void 0===_||_,I=y.logWrongTick,T=void 0!==I&&I,h=y.logNetworkMsg,A=void 0!==h&&h,O=y.logNetworkMsgSize,P=void 0!==O&&O,w=y.sendInitialStateSync,x=void 0!==w&&w,U=y.isPersistFeatureEnabled,k=void 0!==U&&U,j=e.config,V=j.logicTimeoutDuration,F=void 0===V?100:V,H=j.allowedGameTimeDelay,q=void 0===H?5e3:H,Y=j.gameTimeUpdateEveryXTicks,K=void 0===Y?5:Y,W=j.environment,B=void 0===W?"runtime":W,X=j.sdkProtocolVersion,oe=e.network,ae=e.logic;return f(this,void 0,void 0,(function(){function e(e,t,r){return f(this,void 0,void 0,(function(){var o,a,i,s;return m(this,(function(c){switch(c.label){case 0:return pe=!0,"err"!==r?[3,1]:(o=-1,a={},[3,3]);case 1:return[4,_(e,!!oe.onTimelineEntry)];case 2:i=c.sent(),o="error"in i?-1:i.data.stateHash,a="error"in i?{}:i.data.gameState,c.label=3;case 3:return oe.onTimelineEntry&&(s=JSON.stringify(a),n(e,{type:"END",stateHash:o,gameState:s.length>5e3?s.slice(0,5e3):a,logicTick:t,reason:r})),ye?[2,a.persisted]:[2,null]}}))}))}function n(e,t){oe.onTimelineEntry&&(oe.onTimelineEntry(e,l(l({},t),{order:fe})),fe++)}function y(t,r,n,o){var a;return f(this,void 0,void 0,(function(){var i,s,c,u;return m(this,(function(l){switch(l.label){case 0:if(pe)return[2,!0];if("gameEnded"!==(null==n?void 0:n.reason)||void 0===n.options)return[3,5];l.label=1;case 1:return l.trys.push([1,2,,5]),function(e,t){var r,n;if(void 0!==e){if(Q("object"==typeof e&&null!==e&&Z(e),"must be an object"),Q("players"in e||"everyone"in e,"must have players or everyone property"),Q(!("players"in e&&"everyone"in e),"players and everyone option are not allowed at the same time"),"players"in e){Q("object"==typeof e.players&&null!==e.players&&Z(e.players),"players must be an object"),Q(Object.keys(e.players).length>0,"players must not be empty"),Q(Object.keys(e.players).sort().toString()===t.sort().toString(),"all game players must be mentioned in the players object");var o=Object.values(e.players),a=0;try{for(var i=v(o),s=i.next();!s.done;s=i.next()){var c=s.value;Q("number"==typeof c&&!isNaN(c)&&Number.isInteger(c)&&c>=0||["WON","LOST","TIE"].includes(c),"only number >= 0, WON, LOST, TIE are allowed as player results"),"TIE"===c&&a++}}catch(e){r={error:e}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}Q(1!=a,"There must be no TIE or at least 2 TIEs in the game."),Q(o.every((function(e){return["WON","LOST","TIE"].includes(e)}))||o.every((function(e){return"number"==typeof e})),"all players must have either WON, LOST, TIE or all players must have a score")}else Q("number"==typeof e.everyone&&!isNaN(e.everyone)&&Number.isInteger(e.everyone)&&e.everyone>=0||["WON","LOST","TIE"].includes(e.everyone),"only number >= 0, WON, LOST, TIE are allowed as everyone value"),"TIE"===e.everyone&&Q(t.length>1,"There must be at least 2 players in the game to have a TIE");"delayPopup"in e&&Q("boolean"==typeof e.delayPopup,"delayPopup must be a boolean"),"minimizePopUp"in e&&Q("boolean"==typeof e.minimizePopUp,"minimizePopUp must be a boolean")}}(n.options,Object.values(b(oe.getUsers())).map((function(e){return e.playerId}))),[3,5];case 2:return(i=l.sent())instanceof Error?[4,H(t,r,"GAME_OVER_INVALID_OPTIONS",i,{gameOverOptions:n.options})]:[3,4];case 3:return l.sent(),[2,!1];case 4:return[3,5];case 5:return n.players=b(oe.getUsers()),Pe.context.gameOver=n,[4,e(t,r,n.reason)];case 6:return s=l.sent(),c=null,s&&o&&(c=s[o],delete s[o]),u=G(s,oe,he,t),null===(a=oe.onGameOver)||void 0===a||a.call(oe,t,n.reason,u),[2,{onPlayerLeftPersistedState:c}]}}))}))}function _(e,t){var r;return void 0===t&&(t=!1),f(this,void 0,void 0,(function(){var n;return m(this,(function(o){switch(o.label){case 0:return"err"===(null===(r=Pe.context.gameOver)||void 0===r?void 0:r.reason)?[2,{error:"[GAMES_SDK][GAME_OVER_ERR]"}]:[4,ae.getGameState(e,a,t)];case 1:return"error"in(n=o.sent())?[4,H(e,Y(U()),"GET_GAME_STATE_FAILED",void 0,{reason:n.error})]:[3,3];case 2:o.sent(),o.label=3;case 3:return[2,n]}}))}))}function I(e,t){var r;return f(this,void 0,void 0,(function(){var n;return m(this,(function(o){switch(o.label){case 0:return"err"===(null===(r=Pe.context.gameOver)||void 0===r?void 0:r.reason)?[2,{error:"[GAMES_SDK][PERSIST_DATA_AFTER_ERROR_NOT_AVAILABLE]"}]:[4,ae.getPersistedData(e,a,t)];case 1:return"error"in(n=o.sent())?[4,H(e,Y(U()),"GET_PERSISTED_STATE_FAILED",void 0,{reason:n.error})]:[3,3];case 2:return o.sent(),[2,n];case 3:return[2,n.data.persistedPlayers]}}))}))}function h(e,t,r){void 0===r&&(r=!1),Object.values(oe.getUsers()).forEach((function(n){j(e,t,n.userId,r)}))}function O(e,t){var r,n,o=!("event"in t),a=Ne.encodeServerToGame(t,!1),i=Ce.encodeServerToGame(t,o);if(!ne(i))return H(e,Y(U()),"SERVER_MESSAGE_TO_CLIENTS_TOO_BIG",void 0,{messageSize:2*i.length,limit:1048576});if(A&&he.info(e,"SERVER_TO_GAME_BROADCAST_MSG",{serverToGameMsg:t}),P){var s="event"in t?t.event:"serverToGameAction";he.info(e,"SERVER_TO_GAME_MSG_SIZE",{event:s,messageLength:i.length})}me=0;try{for(var c=v(Object.values(oe.getUsers())),u=c.next();!u.done;u=c.next()){var l=u.value;re(l)?oe.sendMsg(e,l.userId,i):oe.sendMsg(e,l.userId,a)}}catch(e){r={error:e}}finally{try{u&&!u.done&&(n=c.return)&&n.call(c)}finally{if(r)throw r.error}}}function w(e){return e in Pe.random||(Pe.random[e]={seed:ue(e),actionCount:0}),Pe.random[e]}function U(){return Ve+N()-Fe}function j(e,t,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=void 0);var a=oe.getUsers(),i=a[r],s=(null==i?void 0:i.playerId)?w(i.playerId):void 0,u=U(),l=Y(u),d={event:"stateSync",params:{game:t,players:b(a),pastPlayerIds:Ie,gameContext:Pe.context,yourPlayerId:null==i?void 0:i.playerId,yourPlayerSeed:null==s?void 0:s.seed,yourPlayerActionCount:null==s?void 0:s.actionCount,serverSeed:c,triggeredByUpdateLoop:n,measureLatencyStart:o},orderNumber:Pe.context.orderNumber,serverGameTime:u,logicTick:l};d.dictionary=be;var f=(re(i)?Ce:Ne).encodeServerToGame(d,!1);if(!ne(f))return H(e,l,"STATE_SYNC_TOO_BIG",void 0,{msgSize:2*f.length,limit:1048576});A&&he.info(e,"SERVER_TO_GAME_SEND_MSG",{serverToGameMsg:d}),he.info(e,"SERVER_TO_GAME_MSG_SIZE",{event:d.event,messageLength:f.length}),oe.sendMsg(e,r,f)}function V(e){return!1===F?e:function(e,t){return new Promise((function(r,n){var o=setTimeout((function(){n(new Error("Timed out after ".concat(t,"ms.")))}),t);e.then(r,n).finally((function(){return clearTimeout(o)}))}))}(e,F)}function H(e,t,r,n,o){return f(this,void 0,void 0,(function(){var a,i;return m(this,(function(s){switch(s.label){case 0:return[4,y(e,t,{reason:"err",err:"runtime"!==B?{message:r,data:o?l({err:n},o):n}:void 0,players:b(oe.getUsers())})];case 1:return s.sent(),a=oe.onError(),he.error(e,r,n||o?"runtime"===B?{gameErr:n,gameInfo:o||void 0,errorContext:a}:l({err:n},o||{}):void 0),i={},Object.values(oe.getUsers()).forEach((function(t){j(e,i,t.userId)})),[2]}}))}))}function Y(e){return Ee.update?Pe.updateCount:M(e,Te)}function W(e,t,r){return f(this,void 0,void 0,(function(){var o,i,s,c,u,f,v,p,g,S,I,T,h;return m(this,(function(m){switch(m.label){case 0:return(o=oe.getUsers()[t])?(i=o.playerId)!==r.playerId?(he.warn(e,"ACTION_PLAYER_ID_AUTHENTICATION_MISMATCH",{gameInfo:{networkPlayerId:i,actionPlayerId:r.playerId}}),[2]):Pe.context.gameOver?(he.warn(e,"ACTION_AFTER_GAME_OVER",{gameInfo:{action:r.action}}),[2]):((s=w(i)).actionCount++,r.actionCount!=s.actionCount&&he.warn(e,"ACTION_COUNT_MISMATCH",{gameInfo:{networkActionCount:r.actionCount,randomStateActionCount:s.actionCount}}),ee(s.seed,r.actionCount)===r.randomSeed?[3,3]:[4,_(e)]):[2];case 1:return"error"in(c=m.sent())?[2]:[4,j(e,c.data.gameState,t)];case 2:return m.sent(),he.warn(e,"ACTION_WRONG_SEED"),[2];case 3:u=U(),f=Y(u),v=void 0,m.label=4;case 4:return m.trys.push([4,6,,7]),[4,V(ae.runAction(e,r.action,{roomId:a,logicContext:{randomSeed:r.randomSeed,msPerTick:Te,logicTick:f,serverStartedAt:E},params:r.params,actionContext:{playerId:i,allPlayerIds:z(Object.keys(b(oe.getUsers())))},calculateStateHash:ge}))];case 5:return v=m.sent(),[3,7];case 6:return g=m.sent(),p=g,[3,7];case 7:return ie(v),S=!(!v||!("data"in v)||!1===v.data)&&v.data,n(e,l({type:"ACTION",action:r.action,params:r.params,playerId:r.playerId,randomSeed:r.randomSeed,logicTick:f},S?{success:!0,stateHash:S.stateHash}:{success:!1})),S?[3,11]:v&&"data"in v?(he.info(e,"ACTION_TRIGGERED_INVALID_ACTION",{gameInfo:{action:r.action}}),[3,10]):[3,8];case 8:return[4,H(e,f,$(v,p,"ACTION_FAILED"),p,l(l({},(null==p?void 0:p.extraLoggingData)||{}),{action:r.action}))];case 9:m.sent(),m.label=10;case 10:return[2];case 11:return"action ".concat(r.action),(I=S.gameContext.gameOver)?[4,y(e,f,S.gameContext.gameOver)]:[3,13];case 12:I=!m.sent(),m.label=13;case 13:return I?[2]:(Pe.context.orderNumber++,r.clientGameTime,T=d(r,["clientGameTime"]),h=l(l({},T),{stateHash:ge&&S?S.stateHash:void 0,orderNumber:Pe.context.orderNumber,serverGameTime:u,logicTick:f}),[4,O(e,h)]);case 14:return m.sent(),[2]}}))}))}function ie(e){e&&"aiPromptRequest"in e&&e.aiPromptRequest&&oe.onAIPromptRequest(e.aiPromptRequest)}function se(e,t,r,n){var o=n.serverPreprocessingDurationInMs;return f(this,void 0,void 0,(function(){var n,a,i,s;return m(this,(function(c){switch(c.label){case 0:return r.sessionId!==Pe.context.sessionId?(he.warn(e,"GAME_SESSION_ID_MISMATCH",{gameInfo:{contextSessionId:Pe.context.sessionId,actionSessionId:r.sessionId}}),[2]):"number"!=typeof r.randomSeed||"number"!=typeof r.actionCount?(he.warn(e,"ACTION_NO_SEED_OR_ACTION_COUNT"),[2]):(u=r.params,n=L(u,30),a=U(),i=Y(a),s=r.expectedLogicTick,n.underLimit?Ee.update?[3,2]:[4,W(e,t,r)]:[2,H(e,i,"ACTION_PARAMS_SIZE_OVER_LIMIT",void 0,{size:n.size,action:r.action})]);case 1:case 3:return c.sent(),[2];case 2:return T&&function(e,t,r){var n=e.expectedLogicTick,o=e.logicTick,a=e.msPerTick,i=e.serverGameTime,s=e.serverPreprocessingDurationInMs,c=i-s,u=a*n;if(n===o);else if(n>o)u-i>100&&t.info(r,"WRONG_TICK_CLIENT_AHEAD",{logicTick:o,expectedLogicTick:n,diff:u-i});else{var l=!1;s>10&&(l=!0,t.info(r,"WRONG_TICK_SERVER_SLOW",{logicTick:o,expectedLogicTick:n,serverReceivedTime:c,serverPreprocessingDurationInMs:s})),c>D(n+1,a)-10&&(l=!0,t.info(r,"WRONG_TICK_MSG_ARRIVED_LATE",{logicTick:o,expectedLogicTick:n,serverReceivedTime:c,serverPreprocessingDurationInMs:s})),l||t.info(r,"WRONG_TICK_UNEXPECTED_REASON",{logicTick:o,expectedLogicTick:n,serverPreprocessingDurationInMs:s})}}({expectedLogicTick:s,logicTick:i,serverPreprocessingDurationInMs:o,msPerTick:Te,serverGameTime:a},he,e),s>i?(ve.push({gameToServerAction:r,userId:t}),[2]):[4,W(e,t,r)]}var u}))}))}function ce(e,t,r,n){return f(this,void 0,void 0,(function(){return m(this,(function(o){return[2,oe.sendMsg(e,t,(re(r)?Ce:Ne).encodeServerToGame({event:"latencyEstimate",measureLatencyStart:n.measureLatencyStart,serverGameTime:U()},!1))]}))}))}var ue,le,de,fe,me,ve,pe,ge,Ee,ye,_e,Se,Ie,Te,he,Ae,Oe,Pe,Re,be,Me,De,Ne,Ce,Ge,Le,we,xe,Ue,ke,je,Ve,Fe,He,qe,Ye,Ke,We=this;return m(this,(function(T){switch(T.label){case 0:if(!i&&!s)throw new Error("Either sessionId or initialServerData has to be provided");if(ue=null!==(t=oe.getSeedForPlayerId)&&void 0!==t?t:function(){return Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)},de=0,fe=0,me=0,ve=[],pe=!1,ge=S||!!oe.onTimelineEntry,Ee=ae.getConfig(),ye=k&&Ee.persistPlayerData,_e=oe.getUsers(),Se=b(_e),Ie=[],D=Ee.updatesPerSecond,Te=Math.round(1e3/D),Object.keys(Se).length<Ee.minPlayers)throw new Error("GameServer cannot start as there is not enough players");if(Object.keys(Se).length>Ee.maxPlayers)throw new Error("GameServer cannot start due to too many players (some should be spectators and not in players object)");if(!c)throw new Error("GameServer cannot start without a serverSeed option");return he=J(B),Ae=function(e){return Ne=R({sdkProtocolVersion:2,gameId:o,sessionId:e,dictionary:be,logger:Re}),Ce=R({sdkProtocolVersion:X,gameId:o,sessionId:e,dictionary:be,logger:Re}),{context:{gameOver:null,orderNumber:1,sessionId:e,gameId:o,serverStartedAt:E},random:{},gameTime:0,updateCount:0}},Re={onSessionMismatch:function(e,t,r){r&&he.warn(r,"GAME_SESSION_ID_MISMATCH",{gameInfo:{stateSessionId:Pe.context.sessionId,decoderSessionId:t,contextSessionId:i,actionSessionId:e}})}},be=g([],p(te),!1),[4,ae.getActionNames(r)];case 1:return Me=T.sent(),be.push.apply(be,g([],p(Me.filter((function(e){return!be.includes(e)}))),!1)),be.sort((function(e,t){return t.length-e.length})),De=null,s?(Oe=s.game,Pe=function(e){return e.game,d(e,["game"])}(s),Ne=R({sdkProtocolVersion:2,gameId:o,sessionId:Pe.context.sessionId,dictionary:be,logger:Re}),Ce=R({sdkProtocolVersion:X,gameId:o,sessionId:Pe.context.sessionId,dictionary:be,logger:Re}),[4,ae.rehydrate(r,a,s.game)]):[3,3];case 2:return T.sent(),[3,6];case 3:return T.trys.push([3,5,,6]),Ge=Ee.persistPlayerData?Object.entries(u).reduce((function(e,t){var r,n=p(t,2),o=n[0],a=n[1],i=_e[Number(o)].playerId;if(!i)throw new Error("PERSISTED_USER_PROVIDED_FOR_NON_PLAYER");return l(l({},e),((r={})[i]=a,r))}),{}):null,[4,V(ae.runSetup(r,{roomId:a,logicContext:{randomSeed:ee(c,0),logicTick:0,msPerTick:Te,serverStartedAt:E},playerIds:z(Object.keys(Se)),calculateStateHash:ge,persistedPlayers:Ge}))];case 4:if(!(Le=T.sent())||"error"in Le)throw new Error("SETUP_FAILED");return we=Le.data,xe=we.gameState,Ue=we.stateHash,De=Le.aiPromptRequest,Oe=xe,Pe=Ae(i),n(r,{type:"START",serverSeed:c,initialPlayers:Se,logicTick:0,stateHash:Ue,persisted:Ge,serverStartedAt:E}),[3,6];case 5:throw(ke=T.sent()).message.startsWith("[GAMES_SDK]")?(je=$(void 0,ke,"SETUP_FAILED"),he.error(r,je,ke.extraLoggingData),"devUI"!==B?ke:new Error("Setup function failed")):(he.error(r,"SETUP_FAILED",{err:ke}),ke);case 6:if(Ve=s&&"gameTime"in s?s.gameTime:0,Fe=N(),Ee.update){if(He=U(),qe=M(He,Te),Math.abs(Pe.updateCount-qe)>1)throw new Error("Update loop is out of sync with gameTime after redeployment. Logic Tick: ".concat(qe,", updateCount: ").concat(Pe.updateCount));Pe.updateCount!==qe?le=setTimeout(oe.queueUpdateLoop,0,{logicTick:qe}):(Ye=C(He,M(He,Te)+1,Te),le=setTimeout(oe.queueUpdateLoop,Ye,{logicTick:qe+1}))}return x&&(h(r,Oe),Oe=void 0),Ke={onMsg:function(e,t,r,n){var a=n.serverPreprocessingDurationInMs;return f(We,void 0,void 0,(function(){var n,i,s,c,u,l,d;return m(this,(function(f){switch(f.label){case 0:if(!ne(r))return[2,H(e,Y(U()),"SERVER_RECEIVED_MESSAGE_TOO_BIG",void 0,{msgSize:2*r.length,limit:1048576})];n=oe.getUsers(),i=n[t];try{s=(re(i)?Ce:Ne).decodeGameToServer(r,e)}catch(t){return he.warn(e,"CLIENT_MESSAGE_DECODE_FAILED",{gameInfo:{contextSessionId:Pe.context.sessionId,msg:r,err:t,compressionDictionary:be}}),[2,Promise.resolve()]}return(c=s)?(P&&(u="type"in c?c.type:"gameToServerAction",he.info(e,"GAME_TO_SERVER_MSG_SIZE",{event:u,messageLength:r.length})),l="type"in c&&"MEASURE_LATENCY"===c.type,A&&!l&&he.info(e,"GAME_TO_SERVER_MSG",{gameToServerMsg:c}),l?[2,ce(e,t,i,c)]:"type"in c&&"REQUEST_STATE_SYNC"===c.type?null!==c.gameId&&c.gameId!==o?[2]:[4,_(e)]:[3,2]):[2,Promise.resolve()];case 1:return d=f.sent(),[2,j(e,"error"in d?{}:d.data.gameState,t,!1,c.measureLatencyStart)];case 2:return"type"in c&&"DEBUG_TIMELINE"===c.type?[2,(c.data,void t.toString())]:(ce(e,t,i,c),[2,se(e,t,c,{serverPreprocessingDurationInMs:a})])}}))}))},onUpdateLoop:function(e,t){return f(We,void 0,void 0,(function(){var r,n,o,i,s,u,l,d,f,g,S,I,T,A,P,R,M,D,N;return m(this,(function(m){switch(m.label){case 0:if(pe||Pe.context.gameOver)return le=void 0,[2];r=ee(c,t.logicTick,"update-"),n=void 0,o=void 0,m.label=1;case 1:return m.trys.push([1,3,,4]),[4,V(ae.runUpdate(e,{roomId:a,logicContext:{randomSeed:r,logicTick:t.logicTick,msPerTick:Te,serverStartedAt:E},updateContext:{allPlayerIds:z(Object.keys(b(oe.getUsers())))}}))];case 2:return n=m.sent(),[3,4];case 3:return i=m.sent(),o=i,[3,4];case 4:return ie(n),!(o||!n||!("data"in n))&&n.data?[3,6]:[4,H(e,t.logicTick,$(n,o,"SERVER_UPDATE_LOOP_FAILED"),o,(null==o?void 0:o.extraLoggingData)||void 0)];case 5:return m.sent(),[2];case 6:return Pe.updateCount++,me++,(s=n&&"data"in n&&n.data.gameContext.gameOver)?[4,y(e,t.logicTick,n.data.gameContext.gameOver)]:[3,8];case 7:s=!m.sent(),m.label=8;case 8:return s?[2]:Pe.context.gameOver?[4,_(e)]:[3,10];case 9:return"error"in(u=m.sent())||(h(e,u.data.gameState,!0),le=void 0),[2];case 10:return l=U(),(d=l-t.logicTick*Te)<-1?[2,H(e,Pe.updateCount,"SERVER_UPDATE_LOOP_FASTER_THAN_GAME_TIME",void 0,{msPassedSinceTheStartOfLogicTick:d,serverGameTime:l,logicTick:t.logicTick,msPerTick:Te})]:me>=K?(f={event:"gameTimeUpdate",orderNumber:Pe.context.orderNumber,serverGameTime:l,params:{gameContext:Pe.context},logicTick:Pe.updateCount},[4,O(e,f)]):[3,12];case 11:m.sent(),m.label=12;case 12:if(g=t.logicTick+1,l-Te*g>q)return[2,H(e,Pe.updateCount,"UPDATE_LOOP_BEHIND_GAME_TIME")];m.label=13;case 13:m.trys.push([13,18,19,20]),S=v(ve.entries()),I=S.next(),m.label=14;case 14:return I.done?[3,17]:(T=p(I.value,2),A=T[0],null===(P=T[1])||P.gameToServerAction.expectedLogicTick!==t.logicTick?[3,16]:[4,W(e,P.userId,P.gameToServerAction)]);case 15:m.sent(),ve[A]=null,m.label=16;case 16:return I=S.next(),[3,14];case 17:return[3,20];case 18:return R=m.sent(),D={error:R},[3,20];case 19:try{I&&!I.done&&(N=S.return)&&N.call(S)}finally{if(D)throw D.error}return[7];case 20:return ve=ve.filter((function(e){return null!==e})),M=C(U(),g,Te),le=setTimeout(oe.queueUpdateLoop,M,{logicTick:g}),[2]}}))}))},onPlayerJoined:function(e,t,r){return f(We,void 0,void 0,(function(){var o,i,s,u,d,f,v,p,g,_;return m(this,(function(m){switch(m.label){case 0:if(Object.keys(b(oe.getUsers())).length>Ee.maxPlayers)return[2,H(e,Y(U()),"SERVER_FULL")];if(!Ee.eventCallbacks.playerJoined)return[2,H(e,Y(U()),"ON_PLAYER_JOINED_CALLBACK_MISSING")];de++,o=ee(c,de),i=b(oe.getUsers()),s=U(),u=Y(s),d=void 0,f=void 0,m.label=1;case 1:return m.trys.push([1,3,,4]),[4,V(ae.runPlayerJoinedEvent(e,{roomId:a,logicContext:{randomSeed:o,msPerTick:Te,logicTick:u,serverStartedAt:E},playerId:t,eventContext:{allPlayerIds:z(Object.keys(i))},persistedPlayerState:Ee.persistPlayerData?r:null,calculateStateHash:ge}))];case 2:return d=m.sent(),[3,4];case 3:return v=m.sent(),f=v,[3,4];case 4:return ie(d),p=!(f||!d||!("data"in d))&&d.data,n(e,l({type:"PLAYER_JOINED",player:i[t],persisted:Ee.persistPlayerData?r:null,logicTick:u},p?{success:!0,stateHash:p.stateHash}:{success:!1})),p?[3,6]:[4,H(e,u,$(d,f,"PLAYER_JOINED_FAILED"),f,(null==f?void 0:f.extraLoggingData)||void 0)];case 5:return m.sent(),[2];case 6:return(g=p.gameContext.gameOver)?[4,y(e,u,p.gameContext.gameOver)]:[3,8];case 7:g=!m.sent(),m.label=8;case 8:return g?[2]:(Pe.context.orderNumber++,_={event:"playerJoined",params:{playerId:t,players:i,gameContext:Pe.context,randomSeed:o,stateHash:ge?p.stateHash:void 0,persistedPlayerState:Ee.persistPlayerData?r:void 0},orderNumber:Pe.context.orderNumber,serverGameTime:s,logicTick:u},[4,O(e,_)]);case 9:return m.sent(),[2]}}))}))},onAIPromptResponse:function(e,t){return f(We,void 0,void 0,(function(){var r,o,i,s,u,d,f,v,p,g;return m(this,(function(m){switch(m.label){case 0:if(pe||Pe.context.gameOver)return[2];if(r=U(),o=Y(r),!t.success)return[2,H(e,o,"AI_PROMPT_REQUEST_FAILED")];de++,i=ee(c,de),s=b(oe.getUsers()),u=void 0,d=void 0,m.label=1;case 1:return m.trys.push([1,3,,4]),[4,V(ae.runAIPromptResponseEvent(e,{roomId:a,logicContext:{randomSeed:i,msPerTick:Te,logicTick:o,serverStartedAt:E},aiPromptResponse:t,eventContext:{allPlayerIds:z(Object.keys(s))},calculateStateHash:ge}))];case 2:return u=m.sent(),[3,4];case 3:return f=m.sent(),d=f,[3,4];case 4:return ie(u),v=!(d||!u||!("data"in u))&&u.data,n(e,l({type:"AI_PROMPT_RESPONSE",aiPromptResponse:t,logicTick:o},v?{success:!0,stateHash:v.stateHash}:{success:!1})),v?[3,6]:[4,H(e,o,$(u,d,"AI_PROMPT_RESPONSE_FAILED"),d,(null==d?void 0:d.extraLoggingData)||void 0)];case 5:return m.sent(),[2];case 6:return(p=v.gameContext.gameOver)?[4,y(e,o,v.gameContext.gameOver)]:[3,8];case 7:p=!m.sent(),m.label=8;case 8:return p?[2]:(Pe.context.orderNumber++,g={event:"aiPromptResponse",params:{aiPromptResponse:t,players:s,gameContext:Pe.context,randomSeed:i,stateHash:ge?v.stateHash:void 0},orderNumber:Pe.context.orderNumber,serverGameTime:r,logicTick:o},[4,O(e,g)]);case 9:return m.sent(),[2]}}))}))},onPlayerLeft:function(t,r){return f(We,void 0,void 0,(function(){var o,i,s,u,d,f,v,p,g,_,S,I,T,h,A;return m(this,(function(m){switch(m.label){case 0:return Pe.context.gameOver?(he.info(t,"PLAYER_LEFT_AFTER_GAME_OVER"),[2,null]):(o=oe.getUsers(),i=U(),s=Y(i),0!==Object.keys(o).length?[3,2]:[4,e(t,s,"minPlayers")]);case 1:return u=m.sent(),ye?u&&1===Object.keys(u).length?[2,u[r]]:(he.error(t,"PLAYER_LEFT_NO_USERS_INCORRECT_PERSISTED_PLAYERS",{players:null===u?"NO PLAYERS":Object.keys(u)}),[2,null]):[2,null];case 2:if(d=b(o),Ie.push(r),de++,f=ee(c,de),v=!1,p=Object.keys(d).length>=Ee.minPlayers,g=Ee.eventCallbacks.playerLeft,!p||!g)return[3,8];_=void 0,S=void 0,m.label=3;case 3:return m.trys.push([3,5,,6]),[4,V(ae.runPlayerLeftEvent(t,{roomId:a,logicContext:{randomSeed:f,msPerTick:Te,logicTick:s,serverStartedAt:E},playerId:r,eventContext:{allPlayerIds:z(Object.keys(d))},calculateStateHash:ge}))];case 4:return _=m.sent(),[3,6];case 5:return I=m.sent(),S=I,[3,6];case 6:return ie(_),v=!(S||!_||!("data"in _))&&_.data,n(t,l({type:"PLAYER_LEFT",playerId:r,logicTick:s},v?{success:!0,stateHash:v.stateHash}:{success:!1})),v?[3,8]:[4,H(t,s,$(_,S,"PLAYER_LEFT_FAILED"),S,(null==S?void 0:S.extraLoggingData)||void 0)];case 7:return m.sent(),[2,null];case 8:return!(T=!!v&&"gameContext"in v&&v.gameContext.gameOver)&&g&&p?[3,10]:[4,y(t,s,T||(g?{reason:"minPlayers",players:d}:{reason:"playerLeft",players:d}),r)];case 9:if(!(h=m.sent()))return[2,null];m.label=10;case 10:return Pe.context.orderNumber++,A={event:"playerLeft",params:{playerId:r,players:d,randomSeed:f,gameContext:Pe.context,stateHash:ge&&v&&v.stateHash?v.stateHash:void 0},orderNumber:Pe.context.orderNumber,serverGameTime:i,logicTick:s},[4,O(t,A)];case 11:return m.sent(),ye?h&&"object"==typeof h&&"onPlayerLeftPersistedState"in h&&h.onPlayerLeftPersistedState?[2,h.onPlayerLeftPersistedState]:v&&"persistedPlayers"in v&&v.persistedPlayers&&r in v.persistedPlayers?[2,v.persistedPlayers[r]]:(he.warn(t,"PLAYER_LEFT_NO_PERSISTED_STATE",{result:v,successfulGameOver:h}),[2,null]):[2,null]}}))}))},getDataForSerialization:function(e){return f(We,void 0,void 0,(function(){var t;return m(this,(function(r){switch(r.label){case 0:return[4,_(e)];case 1:if("error"in(t=r.sent()))throw new Error(t.error);return[2,l(l({},Pe),{gameTime:U(),game:t.data.gameState})]}}))}))},getPersistedUsers:function(e,t){return f(We,void 0,void 0,(function(){var r,n,o;return m(this,(function(a){switch(a.label){case 0:if(!ye)throw new Error("[GAMES_SDK][GAME_DOES_NOT_USE_PERSIST]");return r=oe.getUsers(),n=t?t.map((function(e){return r[e].playerId})):Object.keys(b(r)),[4,I(e,n)];case 1:if("error"in(o=a.sent()))throw new Error(o.error);return[2,Object.keys(o).reduce((function(e,t){return e[Object.values(r).find((function(e){return e.playerId===t})).userId]=o[t],e}),{})]}}))}))},getConfig:function(){return Ee},getSessionId:function(){return Pe.context.sessionId},getGameId:function(){return Pe.context.gameId},cleanup:function(t){return f(We,void 0,void 0,(function(){var r,n;return m(this,(function(o){switch(o.label){case 0:return le&&(clearTimeout(le),le=void 0),r=null,pe?[3,2]:[4,e(t,Y(U()),"stop")];case 1:n=o.sent(),r=G(n,oe,he,t),o.label=2;case 2:return[4,ae.cleanup(t,a)];case 3:return o.sent(),[2,r]}}))}))},isGameOver:function(){return!!Pe.context.gameOver},getCodec:function(){return Ce}},De&&setTimeout((function(){oe.onAIPromptRequest(De)}),0),[2,Ke]}var D}))}))},exports.createSdkForLogicRunner=function(e){globalThis.Math.__SDK_PRECISION_SET__||(ie.forEach((function(e){var t,r;globalThis.Math[e]=(t=globalThis.Math,r=globalThis.Math[e],function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return t.fround(r.apply(t,e))})})),globalThis.Math.__SDK_PRECISION_SET__=!0);var t=void 0,r={initLogic:function(r){if(!r)throw new Error("initParams are required");"runtime"!==e&&function(e){if(e.minPlayers<1)throw new Error("minPlayers cannot be lower than 1");if(e.maxPlayers>6)throw new Error("maxPlayers cannot be greater than ".concat(6));if(e.maxPlayers<e.minPlayers)throw new Error("minPlayers cannot be greater than maxPlayers");if(void 0!==e.updatesPerSecond&&("number"!=typeof e.updatesPerSecond||e.updatesPerSecond<1||e.updatesPerSecond>30||!Number.isInteger(e.updatesPerSecond)))throw new Error("updatesPerSecond must be either not defined or a number between 1 & ".concat(30))}(r),t=function(e,t){var r,n,o,a={state:{gameOverContext:null,aiPromptRequest:null},context:{msPerTick:0,logicTick:0,randomSeed:0,serverStartedAt:0},initParams:e,gameConfig:{minPlayers:e.minPlayers,maxPlayers:e.maxPlayers,eventCallbacks:{playerJoined:!!(null===(r=e.events)||void 0===r?void 0:r.playerJoined),playerLeft:!!(null===(n=e.events)||void 0===n?void 0:n.playerLeft)},update:!!e.update,updatesPerSecond:e.updatesPerSecond||1,landscape:null!==(o=e.landscape)&&void 0!==o&&o,persistPlayerData:e.persistPlayerData||!1,reactive:void 0===e.reactive||e.reactive},getConfig:function(){return a.gameConfig},runSetup:function(r){var n=r.roomId,o=r.logicContext,i=r.playerIds,s=r.calculateStateHash,c=r.persistedPlayers;return Ae(a,o,(function(){var r,o,u,l,d=(null===(r=a.gameConfig)||void 0===r?void 0:r.persistPlayerData)&&null!==c;d?(u={persisted:c},i.forEach((function(e){u.persisted[e]||(u.persisted[e]={})}))):u={};var f=fe(u,(function(t){var r;l=null!==(r=e.setup(i,d?{game:t}:void 0))&&void 0!==r?r:{}}),a.gameConfig.reactive);if("runtime"!==t){if(l.persisted)throw X("SETUP_PERSISTED_KEY_NOT_ALLOWED");(null===(o=a.gameConfig)||void 0===o?void 0:o.persistPlayerData)&&f.persisted!==u.persisted&&ye(f,i)}var m=fe(l||{},(function(e){var t;(null===(t=a.gameConfig)||void 0===t?void 0:t.persistPlayerData)&&(e.persisted=f.persisted)}),a.gameConfig.reactive);if(pe(n,m),a.state.gameOverContext)throw X("SETUP_GAME_OVER_NOT_ALLOWED");return{data:{gameState:m,stateHash:s?ue(m):void 0},aiPromptRequest:a.state.aiPromptRequest}}))},runAction:function(e,r){var n,o=r.roomId,i=r.logicContext,s=r.params,c=r.actionContext,u=r.calculateStateHash;return Oe(a,t,o,i,(function(t){a.initParams.actions[e](s,l(l({},c),{game:t}))}),c.allPlayerIds,u,!0,(null===(n=a.gameConfig)||void 0===n?void 0:n.persistPlayerData)||!1)},runUpdate:function(r){var n,o=r.roomId,i=r.logicContext,s=r.updateContext;return Oe(a,t,o,i,(function(t){var r;null===(r=e.update)||void 0===r||r.call(e,l(l({},s),{game:t}))}),s.allPlayerIds,!1,!1,(null===(n=a.gameConfig)||void 0===n?void 0:n.persistPlayerData)||!1)},runPlayerJoinedEvent:function(r){var n,o,i=r.roomId,s=r.logicContext,c=r.playerId,u=r.persistedPlayerState,d=r.eventContext,f=r.calculateStateHash,m=ve(i);return(null===(n=a.gameConfig)||void 0===n?void 0:n.persistPlayerData)&&null!==u&&pe(i,fe(m,(function(e){e.persisted[c]=u}),a.gameConfig.reactive)),Oe(a,t,i,s,(function(t){var r,n;null===(n=null===(r=e.events)||void 0===r?void 0:r.playerJoined)||void 0===n||n.call(r,c,l(l({},d),{game:t}))}),d.allPlayerIds,f,!1,(null===(o=a.gameConfig)||void 0===o?void 0:o.persistPlayerData)||!1)},runPlayerLeftEvent:function(r){var n,o,i,s,c,u=r.roomId,d=r.logicContext,f=r.playerId,m=r.eventContext,v=r.calculateStateHash,E=Oe(a,t,u,d,(function(t){var r,n;null===(n=null===(r=e.events)||void 0===r?void 0:r.playerLeft)||void 0===n||n.call(r,f,l(l({},m),{game:t}))}),g(g([],p(m.allPlayerIds),!1),[f],!1),!1,!1,(null===(o=a.gameConfig)||void 0===o?void 0:o.persistPlayerData)||!1);if(null===(i=a.gameConfig)||void 0===i?void 0:i.persistPlayerData){var y=ve(u);c=y.persisted[f],pe(u,fe(y,(function(e){delete e.persisted[f]}),a.gameConfig.reactive))}var _=void 0;return v&&(_=ue(ve(u))),"data"in E?{data:l(l({},E.data),{stateHash:_,persistedPlayers:(null===(s=a.gameConfig)||void 0===s?void 0:s.persistPlayerData)&&c?(n={},n[f]=c,n):null}),aiPromptRequest:a.state.aiPromptRequest}:l(l({},E),{aiPromptRequest:a.state.aiPromptRequest})},runAIPromptResponseEvent:function(r){var n,o=r.roomId,i=r.logicContext,s=r.aiPromptResponse,c=r.eventContext,u=r.calculateStateHash,d=Oe(a,t,o,i,(function(t){var r,n;null===(n=null===(r=e.ai)||void 0===r?void 0:r.promptResponse)||void 0===n||n.call(r,s,l(l({},c),{game:t}))}),c.allPlayerIds,u,!1,(null===(n=a.gameConfig)||void 0===n?void 0:n.persistPlayerData)||!1);return"data"in d?{data:d.data,aiPromptRequest:a.state.aiPromptRequest}:l(l({},d),{aiPromptRequest:a.state.aiPromptRequest})},getGameState:function(e,t){try{var r=ve(e);ret