@idosgames/core 0.26.11 → 0.26.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var zod=require('zod'),gn=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var gn__default=/*#__PURE__*/_interopDefault(gn);var Zn=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.off(e,t);}}once(e,t){let n=this.on(e,s=>{n(),t(s);});return n}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e));}emit(e,t){let n=this.listeners.get(e);if(n)for(let s of [...n])s(t);}removeAllListeners(){this.listeners.clear();}};function Du(r){return {get:e=>r.getString(e),set:(e,t)=>r.setString(e,t),remove:e=>r.remove(e)}}var Iu="https://api.idosgames.com";function Pu(r,e){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??Iu).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??Du(e.storage),locale:r.locale??e.getLanguage(),appVersion:r.appVersion??""}}function V(){return crypto.randomUUID()}var dy="idos-host-files",vs="files";function As(r){return new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function my(r){return r.slice().buffer}var An=class{map=new Map;async read(e){let t=this.map.get(e);return t?t.bytes.slice():null}async write(e,t){return this.map.set(e,{bytes:t.slice(),updatedAt:Date.now()}),true}async remove(e){this.map.delete(e);}async list(e=""){let t=[];for(let[n,s]of this.map)n.startsWith(e)&&t.push({key:n,size:s.bytes.byteLength,updatedAt:s.updatedAt});return t.sort((n,s)=>s.updatedAt-n.updatedAt)}},cn=class{db=null;fallback=new An;open(){return this.db||(this.db=(async()=>{try{if(typeof indexedDB>"u")return null;let e=indexedDB.open(dy,1);return e.onupgradeneeded=()=>{e.result.objectStoreNames.contains(vs)||e.result.createObjectStore(vs,{keyPath:"key"});},await As(e)}catch{return null}})()),this.db}async store(e){let t=await this.open();if(!t)return null;try{return t.transaction(vs,e).objectStore(vs)}catch{return null}}async read(e){let t=await this.store("readonly");if(!t)return this.fallback.read(e);try{let n=await As(t.get(e));return n?new Uint8Array(n.bytes):null}catch{return null}}async write(e,t){let n=await this.store("readwrite");if(!n)return this.fallback.write(e,t);try{let s={key:e,bytes:my(t),size:t.byteLength,updatedAt:Date.now()};return await As(n.put(s)),!0}catch{return false}}async remove(e){let t=await this.store("readwrite");if(!t)return this.fallback.remove(e);try{await As(t.delete(e));}catch{}}async list(e=""){let t=await this.store("readonly");if(!t)return this.fallback.list(e);try{let n=e&&typeof IDBKeyRange<"u"?IDBKeyRange.bound(e,e+"\uFFFF"):void 0,s=[];return await new Promise((i,o)=>{let p=t.openCursor(n);p.onerror=()=>o(p.error),p.onsuccess=()=>{let m=p.result;if(!m)return i();let g=m.value;g.key.startsWith(e)&&s.push({key:g.key,size:g.size,updatedAt:g.updatedAt}),m.continue();};}),s.sort((i,o)=>o.updatedAt-i.updatedAt)}catch{return []}}};function Yn(){return typeof document<"u"&&typeof document.createElement=="function"}function Ts(r={}){return Yn()?new Promise(e=>{let t=false,n=document.createElement("input");n.type="file",r.accept?.length&&(n.accept=r.accept.join(",")),n.multiple=r.multiple===true,n.style.display="none";let s=i=>{t||(t=true,n.remove(),e(i));};n.addEventListener("cancel",()=>s([])),n.addEventListener("change",()=>{let i=[...n.files??[]];Promise.all(i.map(async o=>{try{return {bytes:new Uint8Array(await o.arrayBuffer()),name:o.name,mime:o.type||"application/octet-stream"}}catch{return null}})).then(o=>s(o.filter(p=>p!==null)));}),document.body?.appendChild(n),n.click();}):Promise.resolve([])}var vu="idos_device_id",la="idos:platformSignIn:declined:",nt="UNAVAILABLE",Tn=Object.freeze({autoSignIn:false,signIn:false,rewardedAds:false,titleAds:false,storePurchases:false,creditsPayments:true,creditsConfirm:false,cryptoTopUp:false,tokenTrade:false,sceneCaptureRequests:false,share:false,vibration:false,sharedMemory:false,filePicker:false,pushNotifications:false}),Kt=class{storage;files;visible=true;visibilityListeners=new Set;linkListeners=new Set;constructor(e,t=new An){this.storage=e,this.files=t;}openTrade(e){return Promise.resolve({ok:false,error:nt})}buyProduct(e){return Promise.resolve({ok:false,error:nt})}finishPurchase(e,t){return Promise.resolve(false)}pendingPurchases(){return Promise.resolve([])}pickFiles(e){return Promise.resolve([])}requestPushToken(e){return Promise.resolve({error:nt})}getDeviceID(){let e=this.storage.getString(vu);return e||(e=this.newDeviceID(),this.storage.setString(vu,e)),e}newDeviceID(){return V()}setSignInDeclined(e,t){t?this.storage.setString(la+e,"1"):this.storage.remove(la+e);}isSignInDeclined(e){return this.storage.getString(la+e)==="1"}isVisible(){return this.visible}onVisibilityChange(e){return this.visibilityListeners.add(e),()=>{this.visibilityListeners.delete(e);}}onLinkOpened(e){return this.linkListeners.add(e),()=>{this.linkListeners.delete(e);}}emitLink(e){for(let t of [...this.linkListeners])try{t(e);}catch{}}setVisible(e){if(e!==this.visible){this.visible=e;for(let t of [...this.visibilityListeners])try{t(e);}catch{}}}};function ws(r){return (typeof r=="number"?[r]:[...r]).map(t=>Math.max(0,Math.round(t)))}var pn=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,t){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,t);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},Xn=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,t){this.map.set(e,t);}remove(e){this.map.delete(e);}};var Dt={Virtual:"Virtual",Crypto:"Crypto"},kn=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),ks={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},zn=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),Ne={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},zs=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),fy={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Ms=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),gy={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Challenge:"Challenge",ChallengePoints:"ChallengePoints"},Os=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season","Challenge","ChallengePoints"]).catch("TimedEvent"),yy={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},es=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),Ue={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};var ts=class extends Kt{id="memory";supports;clientPlatform;deviceId;constructor(e={}){let t="getString"in e?{storage:e}:e;super(t.storage??new Xn),this.supports=Object.freeze({...Tn,...t.supports}),this.clientPlatform=t.clientPlatform??Ne.Web,this.deviceId=t.deviceId??"memory-device";}setVisibleForTest(e){this.setVisible(e);}newDeviceID(){return this.deviceId}getPlatform(){return "Web"}getClientPlatform(){return this.clientPlatform}getFullURL(){return ""}getStartParameter(){return null}getReferrer(){return null}getTelegramInitDataRaw(){return null}getDeviceModel(){return "Memory"}getLanguage(){return ""}async signIn(){return {error:nt}}async showRewardedAd(){return {ok:false,error:nt}}async confirmCredits(){return {ok:false,error:nt}}async topUp(){return {ok:false,error:nt}}openInvoice(){}openUrl(){}async share(){return "unavailable"}async shareFile(){return "unavailable"}async copyText(){return false}vibrate(){}createWorker(){return null}};function ns(r){return [r.text,r.url].filter(e=>!!e).join(" ")}function Es(){return globalThis.crossOriginIsolated===true&&typeof SharedArrayBuffer<"u"}function qs(r,e={}){if(typeof Worker>"u")return null;try{let t=typeof location<"u"?location.href:void 0,n=t?new URL(r,t):new URL(r),s={type:"module",name:e.name};if(n.protocol==="blob:"||n.protocol==="data:"||!t||n.origin===new URL(t).origin)return new Worker(n.href,s);let i=URL.createObjectURL(new Blob([`import ${JSON.stringify(n.href)};`],{type:"text/javascript"}));return new Worker(i,s)}catch{return null}}var ua=1,Au="__IDOS_HOST__";function ca(){let r=globalThis[Au];return !r||typeof r!="object"||r.protocol!==1||typeof r.post!="function"?null:r}var Ry={signIn:30*6e4,showRewardedAd:5*6e4,confirmCredits:10*6e4,topUp:15*6e4,openInvoice:3e4,openUrl:3e4,share:10*6e4,shareFile:10*6e4,copyText:3e4,vibrate:3e4,buyProduct:30*6e4,finishPurchase:6e4,pendingPurchases:6e4,requestPushToken:10*6e4};function Cy(r){switch((r??"").toLowerCase()){case "android":return Ne.Android;case "ios":return Ne.Ios;case "web":return Ne.Web;default:return Ne.Unknown}}var ss=class extends Kt{id;supports;shell;pending=new Map;nextId=1;constructor(e,t=new pn){super(t,new cn),this.shell=e,this.id=`native:${e.id??"unknown"}`;let n=e.capabilities??{},s=i=>n[i]??Tn[i];this.supports=Object.freeze({autoSignIn:s("autoSignIn"),signIn:s("signIn")||s("autoSignIn"),rewardedAds:s("rewardedAds")||s("titleAds"),titleAds:s("titleAds"),storePurchases:s("storePurchases"),creditsPayments:s("creditsPayments"),creditsConfirm:s("creditsConfirm"),cryptoTopUp:s("cryptoTopUp"),tokenTrade:false,sceneCaptureRequests:false,share:s("share"),vibration:s("vibration"),sharedMemory:Es(),filePicker:Yn(),pushNotifications:s("pushNotifications")}),e.receive=i=>this.receive(i),e.info?.visible===false&&this.setVisible(false);}receive(e){let t;try{t=JSON.parse(e);}catch{return}if(!(!t||t.v!==1)){if(t.kind==="response"&&typeof t.id=="string"){let n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id),clearTimeout(n.timer),n.resolve(t.ok===true?{ok:true,result:t.result??{}}:{ok:false,error:typeof t.error=="string"?t.error:"FAILED"});return}if(t.kind==="event"&&t.name==="visibility"){let n=t.data;typeof n?.visible=="boolean"&&this.setVisible(n.visible);return}if(t.kind==="event"&&t.name==="link"){let n=t.data;typeof n?.url=="string"&&n.url&&this.emitLink(n.url);}}}request(e,t){let n=`r${this.nextId++}`,s={v:1,kind:"request",id:n,method:e,params:t};return new Promise(i=>{let o=setTimeout(()=>{this.pending.delete(n),i({ok:false,error:"TIMEOUT"});},Ry[e]);this.pending.set(n,{resolve:i,timer:o});try{this.shell.post(JSON.stringify(s));}catch{clearTimeout(o),this.pending.delete(n),i({ok:false,error:"UNAVAILABLE"});}})}notify(e,t){this.request(e,t);}newDeviceID(){return this.shell.info?.deviceId||super.newDeviceID()}getPlatform(){return this.getClientPlatform()===Ne.Ios?"iOS":this.getClientPlatform()}getClientPlatform(){return Cy(this.shell.clientPlatform)}getFullURL(){return this.shell.info?.launchUrl??""}getStartParameter(){return this.shell.info?.startParameter??null}getReferrer(){return null}getTelegramInitDataRaw(){return null}getDeviceModel(){return this.shell.info?.deviceModel||this.id}getLanguage(){return this.shell.info?.language||""}async signIn(e){if(!this.supports.signIn)return {error:"UNAVAILABLE"};let t=await this.request("signIn",{titleID:e});if(!t.ok)return {error:t.error};let{code:n,ticket:s}=t.result;return typeof s=="string"&&s.length>0?{ticket:s}:typeof n=="string"&&n.length>0?{code:n}:{error:"no_code"}}async showRewardedAd(e){if(!this.supports.rewardedAds)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("showRewardedAd",e);return t.ok?{ok:true,via:t.result.via==="unit"?"unit":"ad"}:{ok:false,error:t.error}}async confirmCredits(e){if(!this.supports.creditsConfirm)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("confirmCredits",e);return t.ok?{ok:true}:{ok:false,error:t.error}}async topUp(e){if(!this.supports.cryptoTopUp)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("topUp",e);return t.ok?{ok:true}:{ok:false,error:t.error}}openInvoice(e){this.notify("openInvoice",{url:e});}async buyProduct(e){if(!this.supports.storePurchases)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("buyProduct",e);if(!t.ok)return {ok:false,error:t.error};let n=t.result.receipt;return n&&typeof n.receipt=="string"&&n.receipt?{ok:true,receipt:n}:{ok:false,error:"FAILED"}}async finishPurchase(e,t){return this.supports.storePurchases?(await this.request("finishPurchase",{receipt:e,consumable:t})).ok:false}async pendingPurchases(){if(!this.supports.storePurchases)return [];let e=await this.request("pendingPurchases",{});return !e.ok||!Array.isArray(e.result.receipts)?[]:e.result.receipts.filter(t=>t&&typeof t.receipt=="string"&&t.receipt)}async requestPushToken(e){if(!this.supports.pushNotifications)return {error:"UNAVAILABLE"};let t=await this.request("requestPushToken",{prompt:e.prompt===true});if(!t.ok)return {error:t.error};let{token:n,transport:s}=t.result;return typeof n!="string"||!n?{error:"UNAVAILABLE"}:{token:n,transport:s==="Apns"?"Apns":"Fcm"}}openUrl(e){this.notify("openUrl",{url:e});}async share(e){if(!this.supports.share)return await this.copyText(ns(e))?"copied":"unavailable";let t=await this.request("share",e);return t.ok?t.result.outcome??"shared":t.error==="CANCELLED"?"cancelled":"unavailable"}pickFiles(e){return Ts(e)}async shareFile(e){let t=await this.request("shareFile",{name:e.name,mime:e.mime,data:Sy(e.bytes)});return t.ok?t.result.outcome??"shared":t.error==="CANCELLED"?"cancelled":"unavailable"}async copyText(e){return (await this.request("copyText",{text:e})).ok}vibrate(e){this.supports.vibration&&this.notify("vibrate",{pattern:ws(e)});}createWorker(e,t){return qs(e,t)}};function Sy(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)}function Qt(){return globalThis.Telegram?.WebApp??null}function wu(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return Tu(e);let t=r.cordova?.platformId;return t?Tu(t):r.navigator?.userAgent??""?Ne.Web:Ne.Unknown}function Tu(r){let e=r.toLowerCase();return e==="android"?Ne.Android:e==="ios"?Ne.Ios:e==="web"?Ne.Web:Ne.Unknown}var It=["https://idosgames.com","https://www.idosgames.com"],Us="https://platform.idosgames.com",ku=/^[a-z0-9]{8}-preview\.idos\.games$/;function pa(r){return r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r.endsWith(".localhost")}function is(){if(typeof window>"u")return false;let r=window.location.hostname.toLowerCase();return ku.test(r)?true:pa(r)&&globalThis.__IDOS_PREVIEW__!=null}function hn(r){if(typeof window<"u"&&ku.test(window.location.hostname.toLowerCase()))return r===Us;if(It.includes(r))return true;if(typeof window>"u"||!pa(window.location.hostname))return false;try{return pa(new URL(r).hostname)}catch{return false}}var zu="IDOS_PLATFORM_WALLET_ACK",Ls="PLATFORM_WALLET_UNAVAILABLE",by=5e3,xy=18e4;function Dy(){if(hn(Us))return [Us];let r=[...It],e=window.location.ancestorOrigins?.[0];return e&&!r.includes(e)&&hn(e)&&r.push(e),r}function Iy(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Pt(r,e,t,n={}){let s={ok:false,error:Ls,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(s);let i=window.parent;if(!i)return Promise.resolve(s);let o=Iy(),p=n.answerTimeoutMs??xy;return new Promise(m=>{let g=false,j,pe=fe=>{g||(g=true,window.removeEventListener("message",Ae),clearTimeout(j),m(fe));},Ae=fe=>{if(!hn(fe.origin))return;let xe=fe.data;if(!(!xe||xe.requestId!==o)){if(xe.type===zu){clearTimeout(j),j=setTimeout(()=>pe({ok:false,error:"TIMEOUT",data:{}}),p);return}xe.type===e&&pe({ok:xe.ok===true,error:typeof xe.error=="string"?xe.error:void 0,data:xe});}};j=setTimeout(()=>pe(s),by),window.addEventListener("message",Ae);for(let fe of Dy())try{i.postMessage({type:r,requestId:o,...t},fe);}catch{}})}var ha={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},Py=30*6e4;function Mu(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(is())return false;let r=window.location.ancestorOrigins?.[0];if(r&&!It.includes(r))try{let e=new URL(r).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}function da(){if(typeof window>"u"||!is())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function Ou(r){let e=await Pt(ha.request,ha.response,{titleID:r,supports:["pgs"]},{answerTimeoutMs:Py}),t=e.data.ticket;if(e.ok&&typeof t=="string"&&t.length>0)return {ticket:t};let n=e.data.code;return e.ok&&typeof n=="string"&&n.length>0?{code:n}:{error:e.error??"no_code"}}var ma={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},vy=15*6e4,Ay=/^[a-z0-9]{8}-preview\.idos\.games$/;function Mn(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !Ay.test(window.location.hostname.toLowerCase())}async function Eu(r){let e=await Pt(ma.request,ma.response,{titleID:r.titleID,userID:r.userID,currencyID:r.currencyID,amount:r.amount},{answerTimeoutMs:vy});return e.ok?{ok:true}:{ok:false,error:e.error}}var fa={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},Ty=5*6e4;function qu(){return Mn()}async function Uu(r){let e=await Pt(fa.request,fa.response,{titleID:r.titleID,userID:r.userID,requestID:r.requestID,placementID:r.placementID,adUnitID:r.adUnitID??null},{answerTimeoutMs:Ty});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var ga={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},wy=10*6e4,ky=["DECLINED","NOT_ENOUGH_CREDITS"];function Lu(){let r=globalThis.navigator?.userAgent??"";if(!/\biDosGamesApp\/(?:player|studio)\//.test(r))return true;let e=/\biDosGamesPlatform\/(ios|android)\b/.exec(r);return (e?e[1]:/\bAndroid\b/.test(r)?"android":"ios")!=="ios"}function Bu(){return Mn()}async function Gu(r){let e=await Pt(ga.request,ga.response,{titleID:r.titleID,confirmationID:r.confirmationID},{answerTimeoutMs:wy});return e.ok?{ok:true}:{ok:false,error:e.error}}var ya={request:"IDOS_PLATFORM_TRADE_REQUEST",response:"IDOS_PLATFORM_TRADE_RESPONSE"};function Nu(r){return typeof r=="string"&&/^\d{1,15}(\.\d{1,18})?$/.test(r)&&Number(r)>0}function Ra(r,e,t){let n=`trade=${e}${t?`&amount=${encodeURIComponent(t)}`:""}`;return `${It[0]}/app/${encodeURIComponent(r)}?${n}`}async function _u(r){let e=await Pt(ya.request,ya.response,{titleID:r.titleID,side:r.side,amount:r.amount??null});return e.ok?{ok:true}:{ok:false,error:e.error}}var Fu="IDOS_APP_FRAME_HIDDEN";function dn(){return globalThis.navigator??null}function Bs(){return typeof window<"u"}function Vu(){if(!Bs())return false;try{return window.self!==window.top}catch{return true}}var rs=class extends Kt{id;supports;hiddenBySite=false;documentHidden=false;constructor(e=new pn){if(super(e,new cn),!Bs()){this.id="web",this.supports=Tn;return}let t=dn(),n=Mu();this.supports=Object.freeze({autoSignIn:n,signIn:n||da(),rewardedAds:qu(),titleAds:false,storePurchases:false,creditsPayments:Lu(),creditsConfirm:Bu(),cryptoTopUp:Mn(),tokenTrade:!is(),sceneCaptureRequests:Vu(),share:typeof t?.share=="function",vibration:typeof t?.vibrate=="function",sharedMemory:Es(),filePicker:Yn(),pushNotifications:false}),this.id=Qt()?"telegram":da()?"preview":this.supports.cryptoTopUp?"site":"web",this.watchVisibility(),window.addEventListener("hashchange",()=>this.emitLink(window.location.href));}watchVisibility(){typeof document<"u"&&(this.documentHidden=document.visibilityState==="hidden",document.addEventListener("visibilitychange",()=>{this.documentHidden=document.visibilityState==="hidden",this.update();})),Vu()&&window.addEventListener("message",e=>{let t=e.data;!t||t.type!==Fu||hn(e.origin)&&(this.hiddenBySite=t.hidden===true,this.update());}),this.update();}update(){this.setVisible(!this.documentHidden&&!this.hiddenBySite);}getPlatform(){return Qt()?.platform??"Web"}getClientPlatform(){return wu()}getFullURL(){return Bs()?window.location.href:""}getStartParameter(){let e=Qt()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){return typeof document>"u"?null:document.referrer||null}getTelegramInitDataRaw(){let e=Qt()?.initData;return e&&e.length>0?e:null}getDeviceModel(){return dn()?.userAgent||"Web"}getLanguage(){return dn()?.language||""}async signIn(e){return this.supports.signIn?Ou(e):{error:nt}}async showRewardedAd(e){return this.supports.rewardedAds?Uu(e):{ok:false,error:nt}}async confirmCredits(e){return this.supports.creditsConfirm?Gu(e):{ok:false,error:nt}}async topUp(e){return this.supports.cryptoTopUp?Eu(e):{ok:false,error:nt}}async openTrade(e){if(!this.supports.tokenTrade)return {ok:false,error:nt};let t=e?.side,n=e?.amount;if(!e?.titleID||t!=="buy"&&t!=="sell"||n!=null&&n!==""&&!Nu(n))return {ok:false,error:"BAD_REQUEST"};if(this.supports.cryptoTopUp){let s=await _u({titleID:e.titleID,side:t,amount:n||null});return s.ok?{ok:true}:{ok:false,error:s.error===Ls?nt:s.error}}return this.openUrl(Ra(e.titleID,t,n||null)),{ok:true}}openInvoice(e){let t=Qt();if(t?.openInvoice){t.openInvoice(e);return}this.openUrl(e);}openUrl(e){let t=Qt();if(t?.openTelegramLink&&/^https:\/\/t\.me\//i.test(e)){t.openTelegramLink(e);return}Bs()&&window.open(e,"_blank","noopener");}async share(e){let t=dn();if(t?.share)try{return await t.share({url:e.url||void 0,title:e.title,text:e.text}),"shared"}catch(n){if(n?.name==="AbortError")return "cancelled"}return await this.copyText(ns(e))?"copied":"unavailable"}pickFiles(e){return Ts(e)}async shareFile(e){if(typeof document>"u"||typeof Blob>"u")return "unavailable";let t=new Blob([e.bytes],{type:e.mime}),n=dn();if(typeof File<"u"&&n?.share&&n.canShare){let i=new File([t],e.name,{type:e.mime});if(n.canShare({files:[i]}))try{return await n.share({files:[i],title:e.name}),"shared"}catch(o){if(o?.name==="AbortError")return "cancelled"}}let s=document.createElement("a");return s.href=URL.createObjectURL(t),s.download=e.name,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(s.href),3e4),"saved"}async copyText(e){let t=dn();if(t?.clipboard)try{return await t.clipboard.writeText(e),!0}catch{}return zy(e)}vibrate(e){try{dn()?.vibrate?.(ws(e));}catch{}}createWorker(e,t){return qs(e,t)}};function zy(r){if(typeof document>"u"||!document.body)return false;let e=document.createElement("textarea");e.value=r,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();let t=false;try{t=document.execCommand("copy");}catch{t=false;}return e.remove(),t}function Ca(){let r=ca();return r?new ss(r):typeof window>"u"?new ts:new rs}var Sa="idos_acq",ju=["gclid","fbclid","ttclid","msclkid","yclid"],My=["ref","r"],Oy=["ref_","ref-","ref=","r_","r-"];var fn=class{constructor(e){this.host=e;}host;capture(){let e=this.readFromEnvironment();Ey(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),n=t?{...t.signal}:{},s=Ly(this.host.getDeviceModel());return s&&(n.OsVersion=s),e&&(n.AppVersion=e),Object.keys(n).length>0?n:void 0}clear(){this.host.storage.remove(Sa);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let n=Ku(Hu(t));if(n)return n}return Gs(t)}readFromEnvironment(){let e={},t=Hu(this.host.getFullURL());mn(e,"UtmSource",t.get("utm_source")),mn(e,"UtmMedium",t.get("utm_medium")),mn(e,"UtmCampaign",t.get("utm_campaign")),mn(e,"UtmTerm",t.get("utm_term")),mn(e,"UtmContent",t.get("utm_content")),mn(e,"ClaimToken",t.get("idos_click"));for(let g of ju){let j=t.get(g);if(j){e.ClickID=j;break}}let n=this.host.getStartParameter()??"",s=Uy(n);if(s){for(let g of qy)mn(e,g,s.get(Qu[g])??null);for(let g of ju){let j=s.get(g);if(j){e.ClickID=j;break}}}let i=Gs(s?s.get("ref")??s.get("r")??"":n),o=Ku(t),p=i||o;p&&(e.ReferralCode=p,e.ChannelHint=i?"telegram":"query");let m=this.host.getReferrer();return m&&(e.Referrer=m),e}read(){try{let e=this.host.storage.getString(Sa);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.host.storage.setString(Sa,JSON.stringify(e));}catch{}}};function Ey(r){return !!(r.UtmSource||r.UtmMedium||r.UtmCampaign||r.ClickID||r.Referrer||r.ReferralCode||r.ClaimToken)}function mn(r,e,t){t&&(r[e]=t);}var Wu="a1_",Qu={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},qy=Object.keys(Qu);function Uy(r){let e=(r||"").trim();if(!e.startsWith(Wu))return null;let t=e.slice(Wu.length);if(!t)return null;try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(n+"=".repeat((4-n.length%4)%4)),i=Uint8Array.from(s,m=>m.charCodeAt(0)),o=new TextDecoder().decode(i),p=new URLSearchParams(o);return [...p.keys()].length>0?p:null}catch{return null}}function Hu(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function Ku(r){for(let e of My){let t=r.get(e);if(t)return Gs(t)}return null}function Gs(r){let e=(r||"").trim();if(!e)return null;for(let t of Oy)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Ly(r){let e=r||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let n=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(n)return n[1]}var $u="idos_usage_pending",Ju="idos_usage_session",Zu="idos_usage_closed_session",Yu="idos_usage_new_session",Xu="idos_usage_last_activity",os=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;stopVisibility=null;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=!this.ctx.host.isVisible(),this.timer=setInterval(()=>this.tick(),200*1e3),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=e=>{if(!e){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,n=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,n,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=n,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=n,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber($u),this.currentSessionSeconds=this.readNumber(Ju),this.pendingClosedSessionSeconds=this.readNumber(Zu),this.isNewSessionPending=this.readNumber(Yu)!==0;let e=this.readNumber(Xu);this.currentSessionSeconds>0&&e>0&&(Date.now()-e)/1e3>=1800&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,Math.floor(this.currentSessionSeconds)),this.currentSessionSeconds=0);}persist(){this.writeNumber($u,this.pendingSeconds),this.writeNumber(Ju,this.currentSessionSeconds),this.writeNumber(Zu,this.pendingClosedSessionSeconds),this.writeNumber(Yu,this.isNewSessionPending?1:0),this.writeNumber(Xu,Date.now());}readNumber(e){let t=this.ctx.host.storage.getString(e),n=t?Number(t):0;return Number.isFinite(n)&&n>0?n:0}writeNumber(e,t){try{this.ctx.host.storage.setString(e,String(Math.floor(t)));}catch{}}};function G(r){return {ok:true,data:r}}function h(r,e){return {ok:false,reason:r,error:e}}var l=h("unauthorized","Not logged in.");function By(r){return r.ok}function Gy(r){return !r.ok}var Q=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="string"?Number(r):r;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(r)}`}),zod.z.NEVER)}),se=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="number"?String(r):r.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(r)}`}),zod.z.NEVER):t}),u=zod.z.string();var zt=zod.z.object({Type:zn.nullish(),CurrencyID:zod.z.string().nullish(),Amount:Q.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),Ny=zod.z.object({Type:Os.nullish(),EntityID:zod.z.string()}),_y=zod.z.object({Address:Ny.nullish(),Amount:Q.nullish(),Source:zod.z.string().nullish()}),he=zod.z.object({Entries:zod.z.array(zt).nullish(),EventTokens:zod.z.array(_y).nullish()}),ec=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:he.nullish()}),$=zod.z.object({Standard:he.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(ec).nullish()}),Nt=zod.z.object({Standard:he.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(ec).nullish()}),O=zod.z.object({Grant:$.nullish(),Consume:Nt.nullish()}),_t=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:O.nullish(),ToResult:O.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:he.nullish()});var Vy=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Fy={Completed:"Completed",Started:"Started",StepReached:"StepReached"},jy=zod.z.object({FlowIDs:zod.z.array(zod.z.string()).nullish(),Mode:zod.z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:zod.z.string().nullish(),Negate:zod.z.boolean().nullish(),SkippedCountsAsCompleted:zod.z.boolean().nullish()}).passthrough(),te=zod.z.object({Segments:zod.z.array(zod.z.string()).nullish(),MinPremiumTier:zod.z.number().nullish(),RequiredPremiumIDs:zod.z.array(zod.z.string()).nullish(),MinLevel:zod.z.number().nullish(),MaxLevel:zod.z.number().nullish(),Countries:zod.z.array(zod.z.string()).nullish(),RegisteredWithinDays:zod.z.number().nullish(),ActiveWithinDays:zod.z.number().nullish(),Experiment:Vy.nullish(),Tutorial:jy.nullish(),Platforms:zod.z.array(zs).nullish()}).passthrough();var ve=zod.z.object({TotalCap:zod.z.number().nullish(),DailyCap:zod.z.number().nullish(),DailyWeightCap:zod.z.number().nullish(),PerActivationCap:zod.z.number().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish()}).passthrough();var Wy=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Hy=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Ky=zod.z.object({AnchorUtc:zod.z.string().nullish(),MaxCycles:zod.z.number().nullish(),PauseBetweenPhasesSec:zod.z.number().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish()}).passthrough();zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();var Qy=zod.z.object({Reset:zod.z.string().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:zod.z.string().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();zod.z.object({SourceType:zod.z.string().nullish(),TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var ft=zod.z.object({SourceType:zod.z.string().nullish(),BaseWeight:zod.z.number().nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish(),TileTypeFilter:zod.z.array(zod.z.string()).nullish(),TileIndexFilter:zod.z.array(zod.z.number()).nullish(),ChanceOutcomeFilter:zod.z.array(zod.z.string()).nullish(),OutcomeFilter:zod.z.array(zod.z.string()).nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Limits:ve.nullish()}).passthrough(),Se=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:Hy.nullish(),Chain:Ky.nullish(),Cyclic:Qy.nullish(),ActivationTriggers:zod.z.array(ft).nullish(),Relative:Wy.nullish()}).passthrough();var $y={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},Jy=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Zy={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Yy=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),Xy=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Ze=zod.z.object({Base:zod.z.number().nullish(),Shape:Jy.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(Xy).nullish(),Interpolation:Yy.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var eR=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:$.nullish()}).passthrough(),tR=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),ba=zod.z.object({Bundles:zod.z.array(eR).nullish(),Multipliers:zod.z.array(tR).nullish()}).passthrough();var nR=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Ns=zod.z.object({Source:nR.nullish(),SourceKey:zod.z.string().nullish(),Curve:Ze.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:he.nullish(),ExcludeRewards:he.nullish()}).passthrough(),tc=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),je=zod.z.object({MilestoneID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredProgress:zod.z.number().nullish(),Rewards:$.nullish(),BonusRewards:$.nullish(),SeasonTierRewards:ba.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),On=zod.z.object({Milestones:zod.z.record(zod.z.string(),je).nullish()}).passthrough();var J=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var sR=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Mt=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxBalance:zod.z.number().nullish(),MaxPerGrant:zod.z.number().nullish(),DailyEarnCap:zod.z.number().nullish(),BurnOnEventEnd:zod.z.boolean().nullish(),BurnConversion:sR.nullish()}).passthrough();var iR=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),En=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),EquippedSlot:iR.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),K=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),En).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var Ee=r=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:r.nullish()}),Ot=r=>zod.z.object({ServerTimeUtc:u,Items:zod.z.array(Ee(r)),Resources:O.nullish(),Inventory:K.nullish()});var rR={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},nc=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),oR=zod.z.object({}).passthrough().transform(r=>r),aR=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:u.nullish(),CycleEndUtc:u.nullish(),PointsTotalEarned:Q.nullish(),PointsCurrent:Q.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:je.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),xa=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:Q.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:nc}),sc=zod.z.object({State:oR.nullish(),PointsTracks:zod.z.record(zod.z.string(),aR).nullish()}),Da=zod.z.object({ServerTimeUtc:u,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:nc.nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Ia=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:Q.nullish(),Resources:O.nullish(),Inventory:K.nullish(),NextMilestone:je.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),ic=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),rc=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(xa).nullish()}),oc=zod.z.array(Ee(Da)),ac=zod.z.array(Ee(Ia)),lR={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},uR=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),cR={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},pR=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),lc=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:uR.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(ft).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),Pa=zod.z.object({Milestones:J.nullish(),Linking:J.nullish(),Availability:J.nullish(),Reward:J.nullish(),Objectives:J.nullish()}).passthrough(),hR=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),uc=zod.z.object({CycleIDs:zod.z.array(zod.z.string()).nullish(),GroupID:zod.z.string().nullish(),PhaseIDs:zod.z.array(zod.z.string()).nullish(),RequiredQuestIDs:zod.z.array(zod.z.string()).nullish(),PrerequisiteMode:pR.nullish()}).passthrough(),cc=zod.z.object({Schedule:Se.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:te.nullish(),Limits:ve.nullish()}).passthrough(),pc=zod.z.object({Grant:$.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),dR=zod.z.object({QuestID:zod.z.string().nullish(),Identity:hR.nullish(),Linking:uc.nullish(),Availability:cc.nullish(),Objectives:zod.z.record(zod.z.string(),lc).nullish(),Reward:pc.nullish(),Presets:Pa.nullish()}).passthrough(),mR=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:te.nullish(),Reward:$.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),fR=zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Gate:te.nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),Presets:Pa.nullish(),PointsToken:Mt.nullish()}).passthrough(),gR=zod.z.object({Milestones:zod.z.record(zod.z.string(),On).nullish(),Linking:zod.z.record(zod.z.string(),uc).nullish(),Availability:zod.z.record(zod.z.string(),cc).nullish(),Reward:zod.z.record(zod.z.string(),pc).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),lc)).nullish()}).passthrough(),yR=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Se.nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),Gate:te.nullish(),PointsToken:Mt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),mR).nullish(),Phases:zod.z.record(zod.z.string(),fR).nullish(),Presets:Pa.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Vs=zod.z.object({Cycles:zod.z.record(zod.z.string(),yR).nullish(),Quests:zod.z.record(zod.z.string(),dR).nullish(),Presets:gR.nullish()}).passthrough(),At={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var RR={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},CR=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),SR={Never:"Never",OnRequest:"OnRequest",Always:"Always"},bR=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),xR={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},DR=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),IR={GameLoop:"GameLoop"},PR={Raid:"Raid",Attack:"Attack"},vR=zod.z.object({Title:zod.z.string().nullish(),TitleKey:zod.z.string().nullish(),Body:zod.z.string().nullish(),BodyKey:zod.z.string().nullish(),AnchorID:zod.z.string().nullish(),HighlightTarget:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),UiHint:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),AR=zod.z.object({Mode:CR.nullish(),Triggers:zod.z.array(ft).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),TR=zod.z.object({Grant:$.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),wR=zod.z.object({TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),RandomActionType:zod.z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),kR=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:wR.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),zR=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),va=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:vR.nullish(),Completion:AR.nullish(),Effects:TR.nullish(),Script:kR.nullish(),Policy:zR.nullish()}).passthrough(),MR=zod.z.object({DisplayName:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),Description:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),hc=zod.z.object({Schedule:Se.nullish(),Gate:te.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:ft.nullish()}).passthrough(),dc=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:bR.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),mc=zod.z.object({Grant:$.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),OR=zod.z.object({Availability:J.nullish(),Policy:J.nullish(),Reward:J.nullish(),Steps:J.nullish()}).passthrough(),ER=zod.z.object({FlowID:zod.z.string().nullish(),Identity:MR.nullish(),Availability:hc.nullish(),Policy:dc.nullish(),Steps:zod.z.record(zod.z.string(),va).nullish(),Reward:mc.nullish(),Presets:OR.nullish()}).passthrough(),qR=zod.z.object({BlockingFlowIDs:zod.z.array(zod.z.string()).nullish(),BlockedModules:zod.z.array(zod.z.string()).nullish(),BlockedActions:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),BlockBeforeStart:zod.z.boolean().nullish(),SkipLiftsBlock:zod.z.boolean().nullish()}).passthrough(),UR=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:qR.nullish()}).passthrough(),LR=zod.z.object({Availability:zod.z.record(zod.z.string(),hc).nullish(),Policy:zod.z.record(zod.z.string(),dc).nullish(),Reward:zod.z.record(zod.z.string(),mc).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),va)).nullish()}).passthrough(),fc=zod.z.object({Flows:zod.z.record(zod.z.string(),ER).nullish(),Settings:UR.nullish(),Presets:LR.nullish()}).passthrough(),BR=zod.z.object({}).passthrough().transform(r=>r),gc=zod.z.object({FlowID:zod.z.string(),Status:DR,CurrentStepID:zod.z.string().nullish(),CurrentStep:va.nullish(),TotalSteps:zod.z.number(),CompletedSteps:zod.z.number(),CanSkip:zod.z.boolean(),RewardClaimed:zod.z.boolean(),RewardPending:zod.z.boolean(),VariantID:zod.z.string().nullish()}).passthrough(),Fs=zod.z.object({State:BR.nullish(),Flows:zod.z.array(gc).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Jt=zod.z.object({Flow:gc.nullish()}).passthrough(),yc=zod.z.object({FlowID:zod.z.string().nullish(),Granted:O.nullish()}).passthrough(),Rc=zod.z.array(Ee(Jt)),Cc=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),gt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function js(r){return Array.isArray(r)?r.filter(e=>e!==null).map(js):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,js(t)])):r}var Ws=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),n=this.last.get(e);return n!==void 0&&t-n<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var Hs=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Sc(r){return r===429||r>=500&&r<=599}function Ks(r,e=Math.random){let t=Math.min(500*Math.pow(2,r-1),4e3),n=t*.2*(e()*2-1);return Math.max(50,t+n)}function Zt(r){return new Promise(e=>setTimeout(e,r))}var bc=15e3;async function xc(r){try{let t=JSON.parse(await r.text()),n=Number(t?.RetryAfterMs);if(Number.isFinite(n)&&n>0)return n}catch{}let e=Number(r.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Dc(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function Ic(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var Aa=15,Pc=1e3,Qs=class{constructor(e=Aa,t=()=>Date.now(),n=Zt){this.perSecond=e;this.now=t;this.wait=n;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=Pc;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(Pc-(e-this.starts[0])+5);}}};var GR=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function Un(r){if(!r)return null;let e=GR.exec(r);if(!e)return null;let[,t,n,s]=e;if(!t||n===void 0||s===void 0)return null;let i=new gn__default.default(n),o=new gn__default.default(s),p=o.minus(gn__default.default.max(i,0));return p.lte(0)?null:{currencyID:t,required:o.toNumber(),available:i.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var NR=12e3,_R=new Set(["RelatedEntityID"]);function VR(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[n,s]of Object.entries(e))_R.has(n)||(t[n]=s);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var FR=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(xa).nullish(),TutorialProgress:zod.z.array(Cc).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),$s=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Hs;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new Ws(e.throttleMs),this.pacer=new Qs(e.maxRequestsPerSecond??Aa),this.clientPlatform=e.clientPlatform??Ne.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,n,s={}){let i=s.throttleKey??VR(e,t);if(!this.throttler.tryAcquire(i))return h("throttled","Throttled");if(!this.inflight.add(i))return h("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,p=JSON.stringify(t),m=s.ticket??null,g=s.silent??!1,j=s.timeoutMs??NR,pe=s.autoRetry??!0,Ae=!1,fe=!1,xe=0;for(;;){let Gt;s.keepalive||await this.pacer.take();try{Gt=await this.doFetch(o,p,m,j,s.keepalive??!1);}catch{if(pe&&xe<3){xe++,await Zt(Ks(xe));continue}return this.connectionFailure("Internet Connection Error",g)}let lt=Gt.status;if(lt>=200&&lt<300){let ce=!fe&&this.cryptoTopUpHandler!==null,Oe=await this.parseSuccess(Gt,n,g,e,ce);if(!Oe.ok&&ce){let ye=Un(Oe.error);if(ye){if(fe=!0,await this.runTopUp(ye))continue;g||this.emitter.emit("error:global",Oe.error);}}return Oe}if(lt===401){if(!Ae&&this.sessionRefreshHandler){Ae=!0;let ce=null;try{ce=await this.sessionRefreshHandler();}catch{ce=null;}if(ce){m=ce;continue}}return this.emitter.emit("auth:unauthorized",void 0),h("unauthorized","Unauthorized")}if(Sc(lt)){let ce=lt===429?await xc(Gt):null;if(ce!==null&&ce>bc)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ce/1e3)} s`,g);if(pe&&xe<3){xe++,await Zt(ce!==null?Dc(ce):lt===429?Ic(xe):Ks(xe));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${lt})`,g)}let $n="";try{$n=await Gt.text();}catch{}if(lt===409&&/operation in progress/i.test($n)&&pe&&xe<3){xe++,await Zt(Ks(xe));continue}return this.handleWebError($n,lt,g)}}finally{this.inflight.remove(i),this.lowerBusy();}}async doFetch(e,t,n,s,i=false){let o=new AbortController,p=setTimeout(()=>{o.abort();},s);try{let m={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return n&&(m.Authorization=`Bearer ${n}`),await this.fetchImpl(e,{method:"POST",body:t,headers:m,signal:o.signal,...i?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,n,s,i=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",n)}let p;try{p=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",n)}let m=FR.safeParse(p);if(!m.success)return this.globalError("Malformed response envelope",n);if(!m.data.Success){let fe=m.data.Error??"Server returned Success=false",xe=i&&Un(fe);return !n&&!xe&&this.emitter.emit("error:global",fe),h("server",fe)}let g=m.data.StateVersions;g&&Object.keys(g).length>0&&this.emitter.emit("user:stateVersions",{epoch:m.data.StateEpoch??null,versions:g});let j=m.data.QuestProgress;j&&j.length>0&&this.emitter.emit("quest:systemProgress",j);let pe=m.data.TutorialProgress;pe&&pe.length>0&&this.emitter.emit("tutorial:systemProgress",pe);let Ae=t.safeParse(m.data.Data);if(!Ae.success){let fe=t.safeParse(js(m.data.Data));fe.success&&(Ae=fe);}if(!Ae.success){let fe=`Validation error (${s}): ${Ae.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",fe),n||this.emitter.emit("error:global",fe),h("validation",fe)}return G(Ae.data)}handleWebError(e,t,n){let s=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),h("server","PLAY_ACCESS_REQUIRED");s=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return n||this.emitter.emit("error:global",s),h("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),h("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),h("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function Ln(r){return (typeof r=="string"?r:r.toISOString()).slice(0,10)}function as(r){return `${Ln(r)}T00:00:00.000Z`}function vc(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Ac(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function ka(r,e,t,n){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;r.InventoryV2??={};let i=r.InventoryV2,o=n.toISOString(),p=new Map,m=new Map,g=new Map,j=new Map,pe=new Map,Ae=new Map,fe=new Map,xe=new Map,Gt=e.Grant?.PremiumTiers??[],lt=Gt.length;for(let ce=0;;ce++){let Oe,ye;if(ce===0)Oe=e.Grant?.Standard?.Entries,ye=false;else if(ce-1<lt)Oe=Gt[ce-1]?.Resources?.Entries,ye=false;else if(ce===1+lt)Oe=e.Consume?.Standard?.Entries,ye=true;else break;if(Oe)for(let ge of Oe){if(ge.Type==null)continue;let Ce=Math.max(0,ge.Amount??0);if(!(Ce<=0))switch(ge.Type){case "VirtualCurrency":{if(!ge.CurrencyID)continue;let be=ye?m:p;be.set(ge.CurrencyID,(be.get(ge.CurrencyID)??0)+Ce);break}case "CryptoCurrency":{if(!ge.CurrencyID)continue;let be=ye?j:g;be.set(ge.CurrencyID,(be.get(ge.CurrencyID)??new gn__default.default(0)).plus(Ce));break}case "Item":{if(!ge.ItemID)continue;let be=WR(t,ge.CatalogID,ge.ItemID),we=(be?be.IsStackable??true:true)?ye?Ae:pe:ye?xe:fe;we.set(ge.ItemID,(we.get(ge.ItemID)??0)+Ce);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||m.size>0,s.vcChanged){i.VirtualCurrencies??={};for(let ce of new Set([...p.keys(),...m.keys()])){let Oe=p.get(ce)??0,ye=m.get(ce)??0,ge=Oe-ye,Ce=i.VirtualCurrencies[ce];Ce?(Ce.Amount+=ge,Ce.UpdatedAt=o,Ce.Daily&&Ln(Ce.Daily.PeriodStartUtc)===Ln(n)?(Ce.Daily.Earned+=Oe,Ce.Daily.Spent+=ye):Ce.Daily={PeriodStartUtc:as(n),Earned:Oe,Spent:ye}):i.VirtualCurrencies[ce]={Amount:ge,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:as(n),Earned:Oe,Spent:ye}};}}if(s.ccChanged=g.size>0||j.size>0,s.ccChanged){i.CryptoCurrencies??={};for(let ce of new Set([...g.keys(),...j.keys()])){let Oe=g.get(ce)??new gn__default.default(0),ye=j.get(ce)??new gn__default.default(0),ge=Oe.minus(ye),Ce=i.CryptoCurrencies[ce];Ce?(Ce.Amount=new gn__default.default(Ce.Amount).plus(ge).toString(),Ce.UpdatedAt=o):i.CryptoCurrencies[ce]={Amount:ge.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(s.itemsChanged=pe.size>0||Ae.size>0||fe.size>0||xe.size>0,s.itemsChanged){i.Items??={},i.UnstackableItems??={};let ce=i.UnstackableItems,Oe=new Set([...pe.keys(),...Ae.keys(),...fe.keys(),...xe.keys()]);for(let ye of Oe){let ge=(pe.get(ye)??0)-(Ae.get(ye)??0),Ce=(fe.get(ye)??0)-(xe.get(ye)??0),be=ge+Ce,mt=i.Items[ye];mt?(ge!==0&&(mt.StackableAmount+=ge),Ce!==0&&(mt.UnstackableAmount+=Ce),be!==0&&(mt.TotalAmount+=be)):i.Items[ye]={StackableAmount:Math.max(0,ge),UnstackableAmount:Math.max(0,Ce),TotalAmount:Math.max(0,be)};}for(let[ye,ge]of xe){if(ge<=0)continue;let Ce=Object.values(ce).filter(be=>be.ItemID===ye&&be.EquippedSlot==null&&(be.ExpiresAt==null||new Date(be.ExpiresAt)>n)).sort(jR).slice(0,ge).map(be=>be.ItemInstanceID);for(let be of Ce)delete ce[be];}for(let[ye,ge]of fe){let Ce=HR(t,ye);for(let be=0;be<ge;be++){let mt=V();ce[mt]={ItemInstanceID:mt,ItemID:ye,CatalogID:Ce,RemainingUses:1,AcquiredAt:o};}}}r.EventToken??={};let $n=r.EventToken;for(let ce=0;;ce++){let Oe,ye;if(ce===0)Oe=e.Grant?.Standard?.EventTokens,ye=false;else if(ce-1<lt)Oe=Gt[ce-1]?.Resources?.EventTokens,ye=false;else if(ce===1+lt)Oe=e.Consume?.Standard?.EventTokens,ye=true;else break;if(!(!Oe||Oe.length===0))for(let ge of Oe){let Ce=ge.Address;if(!Ce||Ce.Type==null)continue;let be=ge.Amount??0;if(be<=0)continue;let mt=KR($n,Ce.Type);if(!mt)continue;let we=mt[Ce.EntityID];we||(we={},mt[Ce.EntityID]=we),we.Balance??={Current:0,TotalEarned:0,TotalSpent:0},we.Daily??={Date:as(n),TotalEarned:0},we.Meta??={};let Jn=ge.Source&&ge.Source.length>0?ge.Source:"CustomAction";ye?(we.Balance.Current-=be,we.Balance.TotalSpent+=be):(we.Balance.Current+=be,we.Balance.TotalEarned+=be,Ln(we.Daily.Date)!==Ln(n)&&(we.Daily={Date:as(n),TotalEarned:0}),we.Daily.TotalEarned+=be,we.Daily.EarnedBySource??={},we.Daily.EarnedBySource[Jn]=(we.Daily.EarnedBySource[Jn]??0)+be,we.Daily.TriggersBySource??={},we.Daily.TriggersBySource[Jn]=(we.Daily.TriggersBySource[Jn]??0)+1,we.Daily.LastTriggerBySource??={},we.Daily.LastTriggerBySource[Jn]=o,we.Meta.JoinedAtUtc||(we.Meta.JoinedAtUtc=o),we.Meta.LastEarnedAtUtc=o),s.tokensChanged=true;}}return s}function jR(r,e){return r.AcquiredAt!==e.AcquiredAt?r.AcquiredAt<e.AcquiredAt?-1:1:r.ItemInstanceID===e.ItemInstanceID?0:r.ItemInstanceID<e.ItemInstanceID?-1:1}function WR(r,e,t){let n=r?.Catalogs;if(n){if(e){let s=n[e]?.Items?.[t];if(s)return s}for(let s of Object.values(n)){let i=s.Items?.[t];if(i)return i}}}function HR(r,e){let t=r?.Catalogs;if(t){for(let[n,s]of Object.entries(t))if(s.Items&&e in s.Items)return n}}function KR(r,e){switch(e){case "TimedEvent":return r.TimedEvent??={};case "Quest":return r.Quest??={};case "Leaderboard":return r.Leaderboard??={};case "CoopEvent":return r.CoopEvent??={};case "Season":return r.Season??={};case "Challenge":return r.Challenge??={};case "ChallengePoints":return r.ChallengePoints??={};default:return null}}function Tc(r,e,t){let n={drop:[],restore:{}};if(!t)return n;let s=t.ChangedInstances??{},i=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let m of Object.values(s))m?.ItemID&&o.add(m.ItemID);for(let m of i){let g=r[m]?.ItemID;g&&o.add(g);}if(o.size===0)return n;let p=m=>i.has(m)||m in s;if(e){for(let[m,g]of Object.entries(e))m in r||p(m)||g&&o.has(g.ItemID)&&n.drop.push(m);for(let[m,g]of Object.entries(r))m in e||p(m)||g&&o.has(g.ItemID)&&(n.restore[m]=g);}return n}function za(r,e){return r===e||r.startsWith(`${e}:`)}var Zs=class r{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let n of Object.values(t))n&&(typeof n.Amount=="number"&&(n.Amount=String(n.Amount)),typeof n.Frozen=="number"&&(n.Frozen=String(n.Frozen)));}applyUserState(e){r.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let n of t)this.currentState[n]=e[n];r.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){r.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,n=new Date){if(!this.currentState)return;let s=ka(this.currentState,e,t,n);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,n,s=new Date){if(!this.currentState)return;let i=this.currentState,o={...i.InventoryV2?.UnstackableItems??{}},p=ka(i,e,n,s),m=Tc(o,i.InventoryV2?.UnstackableItems,t),g=Object.entries(t?.ChangedInstances??{}),j=t?.RemovedInstanceIDs??[],pe=m.drop.length>0||Object.keys(m.restore).length>0||g.length>0||j.length>0;if(pe){i.InventoryV2??={},i.InventoryV2.UnstackableItems??={};let Ae=i.InventoryV2.UnstackableItems;for(let fe of m.drop)delete Ae[fe];for(let[fe,xe]of Object.entries(m.restore))Ae[fe]=xe;for(let[fe,xe]of g)Ae[fe]=xe;for(let fe of j)delete Ae[fe];}this.emitResourceChanges(p,pe);}emitResourceChanges(e,t){let n=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),n&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(n||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,n,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let i=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof gn__default.default?t:new gn__default.default(t),p=s===void 0?new gn__default.default(0):s instanceof gn__default.default?s:new gn__default.default(s),m=n??new Date().toISOString(),g=i[e];g?(g.Amount=new gn__default.default(g.Amount).plus(o).toString(),p.isZero()||(g.Frozen=new gn__default.default(g.Frozen??0).plus(p).toString()),g.UpdatedAt=m):i[e]={Amount:o.toString(),Frozen:p.toString(),CreatedAt:m,UpdatedAt:m},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,n){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,i=s[e];i||(i={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=i),i.TotalPurchases+=t,i.LastPurchasedAt=n,n>=i.DailyResetUtc?(i.DailyPurchases=t,i.DailyResetUtc=vc(n)):i.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,n){if(!e||n<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let i=new Date().toISOString();for(let o of t)o.RuleID&&(s.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:i});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchRewardWindowState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Windows??={},this.currentState.Reward.Windows[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,n){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let i=s.Cycles[t];if(!i)return;i.Quests??={};let o=i.Quests[e]??={QuestID:e,Status:n};o.Status=n,n==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let i=s.PermanentQuests[e]??={QuestID:e,Status:n};i.Status=n,n==="Claimed"&&(i.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let n=this.getQuestPointsProgress(e);n&&(n.Milestone??={},this.markMilestoneClaimed(n.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let n of Object.values(e)){if(!n.CycleID)continue;let s=n.InstanceKey?`${n.CycleID}:${n.InstanceKey}`:n.CycleID,i=t[s]??={};i.Balance??={Current:0,TotalEarned:0,TotalSpent:0},i.Balance.Current=n.PointsCurrent??0,i.Balance.TotalEarned=n.PointsTotalEarned??0,i.Milestone??={};for(let o of n.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(i.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let n=this.currentState.Quest.Cycles[e];n&&(n.ClaimedGroupCompletionIDs??=[],n.ClaimedGroupCompletionIDs.includes(t)||n.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let n=t.Flows[e.FlowID]??={FlowID:e.FlowID};n.Status=e.Status,n.CurrentStepID=e.CurrentStepID??null,n.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(n.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let n of e){if(!n.FlowID||!n.StepID)continue;let s=t.Flows[n.FlowID]??={FlowID:n.FlowID,Status:"InProgress"};s.Steps??={};let i=s.Steps[n.StepID]??={StepID:n.StepID};i.Progress=n.Progress,n.Completed&&(i.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===n.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let n of e){if(!n.QuestID)continue;let s;if(!n.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[n.QuestID]??={QuestID:n.QuestID,Status:n.Status};else {t.Cycles??={};let i=t.Cycles[n.CycleID];if(!i)continue;i.Quests??={},s=i.Quests[n.QuestID]??={QuestID:n.QuestID,Status:n.Status};}if(s.Status=n.Status,n.ObjectiveID){s.Objectives??={};let i=s.Objectives[n.ObjectiveID]??={ObjectiveID:n.ObjectiveID,CurrentValue:0,Completed:false};i.CurrentValue=n.NewValue??0,n.ObjectiveCompleted&&(i.Completed=true,i.CompletedAtUtc??=new Date().toISOString());}n.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[n,s]of Object.entries(t))if(za(n,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,n,s){if(!(!t||!n)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[i,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((s?i!==s:!za(i,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),n));this.patchActiveEventMilestoneClaimed(e,t,n,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,n,s){let i=this.activeEventsCache?.ActiveEvents;if(i)for(let o of i)o.Type!==e||o.TimedEventID!==t||s&&o.TokenEntityID&&o.TokenEntityID!==s||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),n));}markMilestoneClaimed(e,t){e.Claims??={};let n=e.Claims[t]??={};n.ClaimedAt??=new Date().toISOString(),n.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let n=this.ensureLeaderboardProgress(e);n.CurrentScore=t.CurrentScore??0,n.LastKnownRank=t.LastKnownRank??0,n.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,n.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,n.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,n,s){if(!e)return;let i=this.ensureLeaderboardProgress(e);(i.ScoreCycleVersion??0)<s&&(i.ScoreEarnedThisCycle=0,i.ClaimedMilestoneIDs=[],i.BracketID=null),i.CurrentScore=t,i.ScoreEarnedThisCycle=(i.ScoreEarnedThisCycle??0)+n,i.ScoreCycleVersion=s,i.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let n=this.ensureLeaderboardProgress(e);n.ClaimedMilestoneIDs??=[],n.ClaimedMilestoneIDs.includes(t)||n.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,n=t[e];return n||(n={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=n),n}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let n=this.ensureSeasonState(e);n.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let n=this.ensureSeasonState(e);n.ClaimedTierRewards??=[],n.ClaimedTierRewards.includes(t)||n.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,n=t[e];return n||(n={SeasonChainID:e},t[e]=n),n}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let n=this.currentState?.Character?.Characters;if(!n)return;let s=false;for(let i of Object.values(n))for(let o of Object.values(i.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySelectedCharacter(e){this.currentState??={},this.currentState.Character??={};let t=e??null;(this.currentState.Character.SelectedCharacterID??null)!==t&&(this.currentState.Character.SelectedCharacterID=t,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let n=this.currentState.Character.Characters,s=n[e];s||(s={CharacterID:e},n[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,n){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},n===null?delete s.Equipment[t]:s.Equipment[t]=n,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,n=false;for(let[s,i]of Object.entries(e.ChangedInstances??{}))t[s]=i,n=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],n=true);n&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,n){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=n,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(n=>n!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(n=>n!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(n=>n!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),n=false;typeof e.FriendsCount=="number"&&(n||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(n||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(n||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),n&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let n=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(n)){let i=n[s];i&&i.BoostID===e.BoostID&&s!==e.InstanceID&&delete n[s];}n[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,n,s,i){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,p={Value:n,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:i??null};if(e==="Private")o.Private??={},o.Private[t]=p;else if(e==="Public")o.Public??={},o.Public[t]=p;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let n=this.currentState.CustomData;if(e==="Private")n.Private&&delete n.Private[t];else if(e==="Public")n.Public&&delete n.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let n=this.ensureBoard();n.BuildingStates??=[];let s=n.BuildingStates.find(i=>i.SlotIndex===e);s||(s={SlotIndex:e},n.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let n=this.ensureBoard().Pending;!n||n.Type.toUpperCase()!=="SPECIAL"||(n.Special??={},e(n.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),n=e.PendingAdded;if(t.size>0||n){let s=this.currentState.Blockchain??={},i=s.PendingWithdrawals??[];t.size>0&&(i=i.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),n&&!i.some(o=>o.TitleTransactionID===n.TitleTransactionID)&&(i=[...i,n]),s.PendingWithdrawals=i;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var Ys=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,n]of Object.entries(e))this.sections.has(t)||this.sections.set(t,n);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let n=this.config?.[e];return n??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var Xs=class{user;config;constructor(e){this.user=new Zs(e),this.config=new Ys;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function QR(r){return r}var $R=0,JR=1500,ZR=3,ti=class{constructor(e,t,n=null,s="",i="auto"){this.emitter=e;this.config=t;this.storage=n;this.titleId=s;this.loginMode=i;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return G(void 0);let n=Date.now(),s=[],i=[];for(let m of new Set(e)){let g=this.rules.get(m);if(g&&(t?.force||g.needsServer(n))){s.push(this.runRule(m,g));continue}(t?.force||!this.state.isStateFresh(m,t?.maxAgeMs))&&i.push(m);}let p=(await Promise.all([...s,i.length>0?this.queueSlice(i):Promise.resolve(G(void 0))])).find(m=>!m.ok);return p&&!p.ok?p:G(void 0)}runRule(e,t){let n=this.ruleInflight.get(e);if(n)return n;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}queueSlice(e){for(let n of e)this.pending.add(n);let t=new Promise(n=>this.waiters.push(n));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},$R),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let n;this.batchRunning=new Promise(s=>n=s);try{let s=this.state?await this.state.readStateSlice(e):G(void 0),i=s.ok?G(void 0):s;for(let o of t)o(i);}finally{this.batchRunning=null,n();}}async read(e,t,n){this.register(e);let s=ei(e,n?.args);if(this.noteUsed(e,n?.args,n?.loginParams),!n?.forceRefresh){let g=this.fresh(s,n?.maxAgeMs);if(g)return G(g.data);let j=this.loginFailures.get(s);if(j)return this.loginFailures.delete(s),j;let pe=this.inflight.get(s);if(pe)return pe}let i=this.generation.get(s)??0,o=Date.now(),m=t().then(g=>{if(!g.ok)return g;let j=Date.now();if((this.generation.get(s)??0)===i)return this.entries.set(s,{data:g.data,storedAt:j,expiresAt:Ma(e,g.data,j)}),g;let pe=this.entries.get(s);if(pe&&pe.storedAt>=o)return g;let Ae=Ma(e,g.data,j);return this.entries.set(s,{data:g.data,storedAt:j,expiresAt:Math.min(Ae??1/0,j+JR)}),g}).finally(()=>{this.inflight.get(s)===m&&this.inflight.delete(s);});return this.inflight.set(s,m),m}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...n})=>n))}acceptLoginViews(e){for(let t of e??[]){let n=this.loginBindings.get(t.Name);if(!n)continue;let s=t.Key?t.Key:void 0,i=ei(n.view,s);if(!t.Success){this.loginFailures.set(i,h("server",t.Error??"View failed."));continue}let o=n.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(i),n.apply(o.data,s),this.put(n.view,o.data,s));}}noteUsed(e,t,n){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let i=wc({Name:s,Key:t});this.used.get(i)?.n!==this.session&&(this.used.set(i,{Name:s,Key:t??"",...n,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>ZR||this.used.set(wc(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),n=t?JSON.parse(t):null;return !n||typeof n.s!="number"||!Array.isArray(n.v)?e:{session:n.s,views:n.v.filter(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(ei(e,t))?.data}put(e,t,n){this.register(e);let s=ei(e,n);this.bump(s);let i=Date.now();this.entries.set(s,{data:t,storedAt:i,expiresAt:Ma(e,t,i)});}invalidate(e,t){let n=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${n}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===n||s.startsWith(`${n}|`))&&this.drop(s);this.drop(n);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,n])=>({key:t,ageMs:e-n.storedAt,expiresInMs:n.expiresAt===null?null:n.expiresAt-e}))}fresh(e,t){let n=this.entries.get(e);if(!n)return;let s=Date.now();if(!(n.expiresAt!==null&&s>=n.expiresAt)&&!(t!==void 0&&s-n.storedAt>t))return n}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let n of this.views.values())n.dependsOn?.some(s=>t.has(s))&&this.invalidate(n);}};function ei(r,e){return e===void 0?r.key:`${r.key}|${e}`}function wc(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function Ma(r,e,t){let n=r.expiresAt?.(e)??null,s=r.ttlMs!==void 0?t+r.ttlMs:null;return n!==null&&s!==null?Math.min(n,s):n??s}var ni=class{constructor(e,t){this.storage=e;this.authTypeKey=`Saved_AuthType_${t}`,this.emailKey=`Saved_Auth_Email_${t}`,this.passwordKey=`Saved_Auth_Password_${t}`,this.refreshTokenKey=`Saved_Auth_RefreshToken_${t}`;}storage;authTypeKey;emailKey;passwordKey;refreshTokenKey;get lastAuthType(){let e=this.storage.getString(this.authTypeKey);return YR(e)?e:Ue.None}saveAuthType(e){this.storage.setString(this.authTypeKey,e);}get savedEmail(){return this.storage.getString(this.emailKey)??""}get savedPassword(){return this.storage.getString(this.passwordKey)??""}saveEmailAndPassword(e,t){this.storage.setString(this.emailKey,e),this.storage.setString(this.passwordKey,t);}get savedRefreshToken(){return this.storage.getString(this.refreshTokenKey)??""}saveRefreshToken(e){e?this.storage.setString(this.refreshTokenKey,e):this.storage.remove(this.refreshTokenKey);}clear(){this.storage.remove(this.authTypeKey),this.storage.remove(this.emailKey),this.storage.remove(this.passwordKey),this.storage.remove(this.refreshTokenKey);}};function YR(r){return r!==null&&Object.values(Ue).includes(r)}var XR=8,eC=100,tC=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,si=["GameLoop"];function nC(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var ii=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=Ue.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,n){let s=this.authContext;if(!s)return l;let i=this.baseRequest();i.UserID=s.userID,i.ClientSessionTicket=s.clientSessionTicket,i.WalletAddress=e,i.NetworkID=t,n&&(i.WalletSignature=n);let o=await this.ctx.api.authentication.linkWallet(i);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return l;let n=this.baseRequest();n.UserID=t.userID,n.ClientSessionTicket=t.clientSessionTicket,n.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(n);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.host.getDeviceID(),e.Device=this.ctx.host.getDeviceModel(),e.Platform=this.ctx.host.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(Ue.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.host.getTelegramInitDataRaw();if(!e)return h("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let n=await this.ctx.api.authentication.loginWithTelegram(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Ue.Telegram)):n}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.Password=t;let s=await this.ctx.api.authentication.loginWithEmail(n);if(!s.ok)return s;this.applyAuthContext(s.data);let i=await this.fetchAndApplyClientState(Ue.Email);return i.ok&&this.keepEmailCredentials(e,t),i}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.Password=t,n.DeviceID=this.ctx.host.getDeviceID(),n.Device=this.ctx.host.getDeviceModel(),n.Platform=this.ctx.host.getPlatform();let s=await this.ctx.api.authentication.registerWithEmail(n);return s.ok?(this.pendingRegistration={email:e,password:t},G({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(n);if(!s.ok)return s;this.applyAuthContext(s.data);let i=await this.fetchAndApplyClientState(Ue.Email);return i.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,i}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let n=await this.ctx.api.authentication.resendVerificationCode(t);return n.ok?G(void 0):n}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let n=await this.ctx.api.authentication.loginWithGoogle(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Ue.Google)):n}async loginWithApple(e,t){if(!e?.trim())return h("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.AppleIDToken=e,t?.nonce&&(n.AuthNonce=t.nonce),t?.name?.trim()&&(n.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(n);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(Ue.Apple)):s}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.WalletAddress=e,n.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(n)}async loginWithWallet(e,t,n){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=n,s.Platform=this.ctx.host.getPlatform(),s.Device=this.ctx.host.getDeviceModel(),s.DeviceID=this.ctx.host.getDeviceID();let i=await this.ctx.api.authentication.loginWithWallet(s);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(Ue.Wallet)):i}async loginWithSsoCode(e){if(!e)return h("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.host.getDeviceID(),t.Device=this.ctx.host.getDeviceModel(),t.Platform=this.ctx.host.getPlatform();let n=await this.ctx.api.authentication.loginWithSsoCode(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Ue.iDosGames)):n}async loginWithPlatformGameTicket(e){if(!e)return h("client","Platform game ticket is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.PlatformGameTicket=e;let n=await this.ctx.userService.prepareLoginClientState(si,si);t.ClientState=n.request;let s=await this.ctx.api.authentication.resolvePlatformGameSession(t);if(!s.ok)return s;this.applyAuthContext(s.data),this.platformGameSession=true;let i=s.data.ClientState;return this.fetchAndApplyClientState(Ue.iDosGames,i?()=>n.finish(i):void 0)}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,n){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=n,this.ctx.api.authentication.resetPassword(s)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==Ue.None?e:Ue.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let n=this.baseRequest();n.RefreshToken=t,e?.appOpened&&(n.AppOpened=true);let s=await this.ctx.api.authentication.refreshSession(n);return s.ok?(this.applyRefresh(s.data),"ok"):(nC(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,n){switch(e){case Ue.Email:return this.loginWithEmail(t,n);case Ue.Device:case Ue.None:return this.loginWithDeviceID();case Ue.Telegram:return this.loginWithTelegram();default:return Promise.resolve(h("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;if(this.platformGameSession){this.refreshing=true;try{let t=await this.ctx.host.signIn(this.ctx.settings.titleID);if(!t.ticket)return null;let n=this.baseRequest();n.PlatformGameTicket=t.ticket;let s=await this.ctx.api.authentication.resolvePlatformGameSession(n);return s.ok?(this.applyAuthContext(s.data),this.platformGameSession=!0,s.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==Ue.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===Ue.None)return null;this.refreshing=true;try{return (await this.replay(e,this.sessionEmail||this.ctx.authStore.savedEmail,this.sessionPassword||this.ctx.authStore.savedPassword)).ok&&this.authContext?this.authContext.clientSessionTicket:null}catch{return null}finally{this.refreshing=false;}}logout(){this.authContext=null,this.playAccessStatus=null,this.forgetSession(),this.ctx.authStore.clear(),this.ctx.data.reset(),this.ctx.emitter.emit("auth:loggedOut",void 0);}static isValidEmail(e){return e.length>0&&tC.test(e)}static isValidPasswordLength(e){return e.length>=XR&&e.length<=eC}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=Ue.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e,t){let n=t?await t():await this.ctx.userService.getClientStateExcept(si,si);return n.ok&&(this.sessionAuthType=e,this.rememberSession?(this.ctx.authStore.saveAuthType(e),this.ctx.authStore.saveRefreshToken(this.sessionRefreshToken)):this.ctx.authStore.clear(),this.ctx.emitter.emit("auth:loggedIn",void 0)),n}};var sC="idos:cfg",Bn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${kc(t)}`:e&&e.length>0?`f:${kc(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.v!="string"||!n.c?null:n}catch{return null}}async write(e,t,n){try{let s={v:t,c:n};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${sC}:${this.titleId}:${e}`}};function kc(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var zc="idos:loc",Gn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.v!="number"||!n.t||typeof n.t!="object"?null:n}catch{return null}}async write(e,t,n){try{let s={v:t,t:n};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let n={};for(let[s,i]of Object.entries(t))typeof i=="number"&&i>0&&(n[s]=i);return n}catch{return {}}}async noteVersion(e,t){let n=await this.readVersions();n[e]!==t&&(n[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(n)));}keyOf(e){return `${zc}:${this.titleId}:${e}`}versionsKey(){return `${zc}:${this.titleId}:versions`}};var iC="idos:sec",ri=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let n=JSON.parse(t);return !n||typeof n!="object"||n.v!==e||!n.s||typeof n.s!="object"?{}:n.s}catch{return {}}}async write(e,t){try{let n={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(n));}catch{}}keyOf(){return `${iC}:${this.titleId}`}};var rC="idos:state",oi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.e!="string"||!n.v||!n.s?null:n}catch{return null}}async write(e,t,n,s){if(!(!e||!t))try{let i={e:t,v:n,s};await this.storage.set(this.keyOf(e),JSON.stringify(i));}catch{}}keyOf(e){return `${rC}:${this.titleId}:${e}`}};function oC(r,e){if(!r)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return r;let n={};for(let[s,i]of Object.entries(r))t.has(s.toLowerCase())||(n[s]=i);return n}function Oa(r,e,t,n){let s={...r??{}};if(!e||!t||!n)return s;for(let[i,o]of Object.entries(t))n[i]===o&&i in e&&(s[i]=e[i]);return s}function aC(r){return {...r??{}}}function Ea(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.StateEpoch:null}var ai=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,n=Date.now()){if(this.versions[e]===void 0)return false;let s=this.confirmedAt[e];return s===void 0?false:t===void 0||n-s<=t}forget(e){let t=[];for(let n of e)this.versions[n]!==void 0&&(delete this.versions[n],delete this.confirmedAt[n],t.push(n));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=oC(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let o=Object.keys(this.versions);this.reset(e),this.notify(o);}return []}let n=Date.now(),s=[],i=[];for(let[o,p]of Object.entries(t)){let m=this.versions[o];m!==p&&(m!==void 0&&p===m+1?(this.versions[o]=p,this.confirmedAt[o]=n):(delete this.versions[o],delete this.confirmedAt[o],m!==void 0&&p>m+1&&i.push(o)),s.push(o),this.dirty=true);}return this.notify(s),i}afterFullRead(e,t){let n=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=aC(t);let s=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=s;this.dirty=true;let i=new Set;for(let o of new Set([...Object.keys(n),...Object.keys(this.versions)]))n[o]!==this.versions[o]&&i.add(o);this.notify([...i]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let n=Date.now(),s=[];for(let[i,o]of Object.entries(t??{}))this.versions[i]!==o&&s.push(i),this.versions[i]=o,this.confirmedAt[i]=n;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Mc=h("server","Title configuration is unavailable (CDN and API both failed)."),li=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:V()}:null}get configCache(){return this.cache??=new Bn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new Gn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new ri(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new ai(new oi(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){if(!this.ctx.auth.context?.userID||!this.stateStore.currentEpoch)return;let s=this.stateStore.noteMutation(e,t);s.length>0&&(this.ctx.cache.ensureState(s),this.ctx.emitter.emit("user:changedElsewhere",{containers:s}));}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return l;let t=Bn.scopeOf(e.TitleFields,null),n=await this.configCache.read(t);n&&(e.KnownTitleConfigVersion=n.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let i=await this.ctx.api.user.getClientState(e);if(!i.ok)return i;let o=await this.resolveTitleConfig(i.data,t,n,{Fields:e.TitleFields});return o==null?Mc:(this.finishStateHandshake(i.data,s),await this.restoreSections(i.data.TitleConfigVersion,o),await this.applyClientState(i.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(i.data.Views),await this.applyLocalization(i.data.Localization),await this.flushState(s),i)}async prepareStateHandshake(e,t){let n=this.ctx.auth.context?.userID;if(!n)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(n),await this.stateStore.flush(n,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let i=this.stateStore.currentEpoch;i&&(e.KnownStateEpoch=i);}return {userId:n,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let n=Oa(e.User,t.cached,t.sent,e.StateVersions);e.User=n;let s=Ea(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,n,s){let i=e.TitleConfigVersion;if(n&&i&&n.v===i)return n.c;if(e.TitleConfigUrl){let p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return i&&await this.configCache.write(t,i,p),p}let o=await this.fetchConfigFromApi(s);return o!=null?(i&&await this.configCache.write(t,i,o),o):n?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let n=await t.json();return n&&typeof n=="object"?n:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let n={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(n):await this.ctx.api.title.getTitlePublicConfiguration(n);return s.ok?s.data:null}async getClientStateExcept(e,t){let n=this.baseRequest();if(!n)return l;let s=await this.prepareClientStateExcept(n,e,t,true),i=await this.ctx.api.user.getClientStateExcept(n);return i.ok?this.finishClientStateExcept(s,i.data):i}async prepareLoginClientState(e,t){let n={BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:V()},s=await this.prepareClientStateExcept(n,e,t,false);return {request:n,finish:async i=>{let o=this.ctx.auth.context?.userID??null;return o&&await this.stateStore.load(o),s.handshake={userId:o,cached:null,sent:void 0},this.finishClientStateExcept(s,i)}}}async prepareClientStateExcept(e,t,n,s){e.ExcludeFields=t,e.ExcludeTitleFields=n;let i=Bn.scopeOf(null,n??[]),o=await this.configCache.read(i);o&&(e.KnownTitleConfigVersion=o.v),await this.prepareLocalization(e);let p=s?await this.prepareStateHandshake(e,t??null):{userId:null,cached:null,sent:void 0};return await this.prepareLoginViews(e),{scope:i,cached:o,handshake:p,excludeFields:t,excludeTitleFields:n}}async finishClientStateExcept(e,t){let n=await this.resolveTitleConfig(t,e.scope,e.cached,{ExcludeFields:e.excludeTitleFields??[]});return n==null?Mc:(this.finishStateHandshake(t,e.handshake),await this.restoreSections(t.TitleConfigVersion,n),await this.applyClientState(t,n,e.excludeFields,e.excludeTitleFields),this.ctx.cache.acceptLoginViews(t.Views),await this.applyLocalization(t.Localization),await this.flushState(e.handshake),G(t))}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let n=t,s={};for(let[i,o]of Object.entries(await this.sectionCache.read(e)))n[i]==null&&(s[i]=o);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((i,o)=>{n[i]!=null||o==null||(s[i]=o,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let n=await this.localizationCache.readVersions();Object.keys(n).length>0&&(e.KnownLocalizationVersions=n);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),n=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:n});}async resolveLocalizationTable(e){let t=e.Locale??null,n=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(n<=0)return s?.t??null;if(s&&s.v===n)return s.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,n,o),o}let i=await this.fetchLocalizationFromApi(t,s?.v??0);return i??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let n=await t.json();return n&&typeof n=="object"?n:null}catch{return null}}async fetchLocalizationFromApi(e,t){let n=this.baseRequest();if(!n)return null;let s=await this.ctx.api.localization.getLocalizationTable({...n,Locale:e,KnownVersion:t});if(!s.ok)return null;let i=s.data;if(i.NotModified)return null;let o=i.Entries??{},p=i.Version??0,m=i.Locale??e;return p>0&&await this.localizationCache.write(m,p,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):l}async getUserState(e){let t=this.baseRequest();if(!t)return l;e&&e.length>0&&(t.Fields=e);let n=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let i=Oa(s.data.User,n.cached,n.sent,s.data.StateVersions);s.data.User=i;let o=n.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([g,j])=>o[g]!==j||this.ctx.data.user.state?.[g]===void 0).map(([g])=>g);this.ctx.data.user.applyUserStateContainers(i,p);let m=Ea(s.data);return m&&(this.stateStore.afterSliceRead(m,s.data.StateVersions),await this.flushState(n)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,n){let s=this.baseRequest();if(!s)return l;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=n;let i=await this.ctx.api.user.addUsageTime(s);return i.ok&&this.ctx.emitter.emit("user:usageTimeAdded",i.data),i}async deleteUserAccount(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return l;t.Username=e;let n=await this.ctx.api.user.changeUsername(t);return n.ok&&this.ctx.emitter.emit("user:usernameChanged",n.data),n}async applyClientState(e,t,n,s){let i=n?.includes("GameLoop")===true,o=s?.includes("GameLoop")===true,p=i?this.ctx.data.user.state?.GameLoop:void 0,m=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let g=this.ctx.data.user.state;i&&g&&g.GameLoop==null&&(g.GameLoop=p);let j=this.ctx.data.config.titlePublicConfiguration;o&&j&&j.GameLoop==null&&(j.GameLoop=m),this.ctx.emitter.emit("user:clientStateReceived",e);}};var ci=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return h("client","SpendID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${V()}`},s=await this.ctx.api.currency.spend(n);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",s.data)),s}async convert(e,t,n,s,i,o){if(!t)return h("client","SourceID is required.");if(!s)return h("client","TargetID is required.");if(i<=0)return h("client","Amount must be positive.");if(e===n&&t===s)return h("client","Source and target must differ.");if(e===Dt.Crypto||n===Dt.Crypto)return h("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return l;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:n,TargetID:s,SourceAmount:String(Math.trunc(i)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${n}_${s}_${V()}`},m=await this.ctx.api.currency.convert(p);if(m.ok){let g=m.data,j={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:g.SourceID,Amount:g.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:g.TargetID,Amount:g.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(j,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",g);}return m}async cryptoConvert(e,t,n,s,i,o){let p=i instanceof gn__default.default?i:new gn__default.default(i);if(!t)return h("client","SourceID is required.");if(!s)return h("client","TargetID is required.");if(p.lte(0))return h("client","SourceAmount must be a positive decimal.");if(e===n&&t===s)return h("client","Source and target must differ.");if(e===Dt.Virtual&&n===Dt.Virtual)return h("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===Dt.Virtual&&!p.isInteger())return h("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return l;let m={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:n,TargetID:s,SourceAmount:p.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${n}_${s}_${V()}`},g=await this.ctx.api.currency.cryptoConvert(m);if(g.ok){let j=g.data,pe=[],Ae=[];if(j.SourceType===Dt.Virtual&&pe.push({Type:"VirtualCurrency",CurrencyID:j.SourceID,Amount:Math.trunc(Number(j.SourceSpent))}),j.TargetType===Dt.Virtual&&Ae.push({Type:"VirtualCurrency",CurrencyID:j.TargetID,Amount:Math.trunc(Number(j.TargetCredited))}),pe.length>0||Ae.length>0){let fe={Consume:pe.length>0?{Standard:{Entries:pe}}:null,Grant:Ae.length>0?{Standard:{Entries:Ae}}:null};this.ctx.data.user.applyResourceOperation(fe,this.ctx.data.config.itemDefinitions);}j.SourceType===Dt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.SourceID,new gn__default.default(j.SourceSpent).negated(),j.ServerTimeUtc),j.TargetType===Dt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.TargetID,new gn__default.default(j.TargetCredited),j.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",j);}return g}};var pi=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,n,s){let i=e.trim();if(!i)return h("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:i,SelectedOptionID:n,CreditsConfirmationID:s,RelatedEntityID:`upgrade_item_${i}_${V()}`};t&&t.length>0&&(o.FodderInstanceIDs=[...t]);let p=await this.ctx.api.item.upgradeLevel(o);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(p.data.ItemInstanceID??i,p.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",p.data)),p}async upgradeLevelsBatch(e){if(!e||e.length===0)return h("client","upgrades is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},n=await this.ctx.api.item.upgradeLevelsBatch(t);if(n.ok){for(let s of n.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",n.data);}return n}};var hi=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:Nt.nullish(),AllowedPlatforms:zod.z.array(zs).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),me=zod.z.record(zod.z.string(),hi),lC=zod.z.object({Store:Ms,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var ls={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},Re=zod.z.object({ConfirmationID:zod.z.string(),Url:zod.z.string(),Status:zod.z.string(),PriceCredits:zod.z.number(),ExpiresAt:u}).passthrough(),Oc=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),uC={LoginRequired:"CREDITS_LOGIN_REQUIRED",NotEnough:"NOT_ENOUGH_CREDITS",SellerUnknown:"CREDITS_SELLER_UNKNOWN",PriceChanged:"CREDITS_PRICE_CHANGED",ConfirmationPending:"CREDITS_CONFIRMATION_PENDING",ConfirmationDeclined:"CREDITS_CONFIRMATION_DECLINED",ConfirmationExpired:"CREDITS_CONFIRMATION_EXPIRED",ConfirmationNotFound:"CREDITS_CONFIRMATION_NOT_FOUND",ConfirmationMismatch:"CREDITS_CONFIRMATION_MISMATCH",BatchForbidden:"CREDITS_BATCH_FORBIDDEN",NotAllowedHere:"CREDITS_NOT_ALLOWED_HERE",MixedWithStorePayment:"CREDITS_MIXED_WITH_STORE_PAYMENT",SellerNotReady:"CREDITS_SELLER_NOT_READY",ConfirmationInUse:"CREDITS_CONFIRMATION_IN_USE"},qa=zod.z.object({ServerTimeUtc:u,OfferID:zod.z.string(),Count:zod.z.number(),Resources:O.nullish(),Inventory:K.nullish(),CreditsConfirmation:Re.nullish()}),Ec=zod.z.array(Ee(qa)),cC=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:u,LastPurchasedAt:u}),pC=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:u}),qc=zod.z.object({Purchases:zod.z.record(zod.z.string(),cC).nullish(),Rotations:zod.z.record(zod.z.string(),pC).nullish()}).passthrough().transform(r=>r),Vt=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),di=zod.z.object({Schedule:Se.nullish(),Gate:te.nullish()}).passthrough(),hC={Fixed:"Fixed",Title:"Title",Player:"Player"},dC=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:te.nullish()}).passthrough(),Uc=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(dC).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),mC=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Rotation:J.nullish()}).passthrough(),fC=zod.z.object({SlotID:zod.z.string().nullish(),Identity:Vt.nullish(),Availability:di.nullish(),Rotation:Uc.nullish(),Presets:mC.nullish()}).passthrough(),gC=zod.z.object({Identity:J.nullish(),Availability:J.nullish()}).passthrough(),yC=zod.z.object({SectionID:zod.z.string().nullish(),Identity:Vt.nullish(),Availability:di.nullish(),Slots:zod.z.record(zod.z.string(),fC).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:gC.nullish()}).passthrough(),Lc=zod.z.object({Sections:zod.z.record(zod.z.string(),yC).nullish()}).passthrough(),RC=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Layout:J.nullish()}).passthrough(),CC=zod.z.object({StoreID:zod.z.string().nullish(),Identity:Vt.nullish(),Availability:di.nullish(),Layout:Lc.nullish(),Presets:RC.nullish()}).passthrough(),Bc=zod.z.object({Options:me.nullish(),CompareAt:zod.z.record(zod.z.string(),Nt).nullish()}).passthrough(),Gc=zod.z.object({Grant:$.nullish()}).passthrough(),Nc=zod.z.object({Schedule:Se.nullish(),Gate:te.nullish(),Limits:ve.nullish()}).passthrough(),SC=zod.z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish(),Availability:J.nullish()}).passthrough(),bC=zod.z.object({OfferID:zod.z.string().nullish(),Identity:Vt.nullish(),Pricing:Bc.nullish(),Reward:Gc.nullish(),Availability:Nc.nullish(),Presets:SC.nullish()}).passthrough(),xC=zod.z.object({Identity:zod.z.record(zod.z.string(),Vt).nullish(),Availability:zod.z.record(zod.z.string(),di).nullish(),Layout:zod.z.record(zod.z.string(),Lc).nullish(),Rotation:zod.z.record(zod.z.string(),Uc).nullish(),Pricing:zod.z.record(zod.z.string(),Bc).nullish(),Reward:zod.z.record(zod.z.string(),Gc).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Nc).nullish()}).passthrough(),mi=zod.z.object({Stores:zod.z.record(zod.z.string(),CC).nullish(),StoreOffers:zod.z.record(zod.z.string(),bC).nullish(),Presets:xC.nullish()}).passthrough(),DC=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:u.nullish()}).passthrough(),IC=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:Nt.nullish(),CompareAtCost:Nt.nullish(),DiscountPercent:zod.z.number().nullish(),IsFree:zod.z.boolean(),IsAdPaid:zod.z.boolean(),IsStorePaid:zod.z.boolean(),IsCreditsPaid:zod.z.boolean().nullish(),CreditsPrice:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),PC=zod.z.object({OfferID:zod.z.string(),Identity:Vt.nullish(),PriceOptions:zod.z.array(IC).nullish(),Rewards:$.nullish(),State:DC.nullish()}).passthrough(),vC=zod.z.object({SlotID:zod.z.string(),Identity:Vt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:u.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:PC.nullish()}).passthrough(),AC=zod.z.object({SectionID:zod.z.string(),Identity:Vt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(vC).nullish()}).passthrough(),TC=zod.z.object({StoreID:zod.z.string(),Identity:Vt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:u.nullish(),Sections:zod.z.array(AC).nullish()}).passthrough(),fi=zod.z.object({ServerTimeUtc:u,Stores:zod.z.array(TC).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Ft={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},wC="OFFER_NOT_IN_ROTATION";var _c="Store",Vc={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=null;for(let t of r.Stores??[])for(let n of t.Sections??[])for(let s of n.Slots??[]){let i=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},gi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Vc,{schema:fi,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,n){if(!e)return h("client","OfferID is required.");if(t<1)return h("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return l;let i={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,StoreID:n?.slot?.storeID,SectionID:n?.slot?.sectionID,SlotID:n?.slot?.slotID,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${s.userID}_${V()}`},o=await this.ctx.api.store.purchase(i);if(o.ok&&!o.data.CreditsConfirmation){let p=o.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return o}async purchaseWithCredits(e,t=1,n={}){return await this.ctx.credits.pay(s=>this.purchase(e,t,{selectedOptionID:n.selectedOptionID,slot:n.slot,creditsConfirmationID:s}),{onConfirmation:n.onConfirmation,signal:n.signal,pollMs:n.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):l}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):l}async purchaseBatch(e){if(!e||e.length===0)return h("client","purchases is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},n=await this.ctx.api.store.purchaseBatch(t);if(n.ok){let s=false;for(let i of n.data)!i.Success||!i.Data||!i.Data.OfferID||(this.ctx.data.user.patchStorePurchase(i.Data.OfferID,i.Data.Count,i.Data.ServerTimeUtc),!s&&i.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",n.data);}return n}async getDefinitions(e){let t=this.ctx.cache.configSection(_c,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.store.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(_c,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(Vc,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let n of t.Sections??[])for(let s of n.Slots??[]){let i=s.RefreshesAtUtc;i&&(e===null||Date.parse(i)<Date.parse(e))&&(e=i);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var yi=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let n=await e(void 0);if(!n.ok||!n.data.CreditsConfirmation)return n;let s=n.data.CreditsConfirmation,i=()=>e(s.ConfirmationID);if(this.ctx.host.supports.creditsConfirm){let m=await this.ctx.host.confirmCredits({titleID:this.ctx.settings.titleID,confirmationID:s.ConfirmationID});if(m.ok)return await i();if(m.error==="DECLINED")return h("server","CREDITS_CONFIRMATION_DECLINED");if(m.error==="NOT_ENOUGH_CREDITS")return h("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(s);let o=Math.max(1e3,t.pollMs??2500),p=Date.parse(s.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return h("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>p)return h("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(j=>setTimeout(j,o));let m=await this.ctx.store.getCreditsConfirmation(s.ConfirmationID);if(!m.ok)continue;let g=m.data.Status;if(g!==ls.Pending)return g===ls.Declined?h("server","CREDITS_CONFIRMATION_DECLINED"):g===ls.Expired?h("server","CREDITS_CONFIRMATION_EXPIRED"):await i()}}};var Ri=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return l;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return l;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?G(t.data.Purchase??{}):t}async validatePurchase(e,t,n){if(!t)return h("client","Receipt is required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:n?.signature,ProductID:n?.productID,TransactionID:n?.transactionID},i=await this.ctx.api.purchase.validatePurchase(s);return i.ok&&this.applyValidation(i.data),i}async buyWithTelegramStars(e,t){if(!e)return h("client","productID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(n);return s.ok&&t?.open!==false&&this.ctx.host.openInvoice(s.data.InvoiceLink),s}async buy(e){if(!e)return h("client","productID is required.");if(!this.ctx.host.supports.storePurchases)return h("client","UNAVAILABLE");if(!this.ctx.auth.context)return l;let t=await this.getDefinitions();if(!t.ok)return t;let n=t.data.Purchase?.Products?.[e],s=this.hostStore(),i=n?.StoreProductIDs?.[s];if(!n||n.Enabled===false||!i)return h("client","NOT_SOLD");let o=this.ctx.buildAuthedBaseRequest(),p=await this.ctx.host.buyProduct({storeProductID:i,type:n.Type??"Consumable",accountID:o.UserID??void 0});return !p.ok||!p.receipt?h("client",p.error??"FAILED"):this.deliver(p.receipt,n)}async restorePending(){if(!this.ctx.host.supports.storePurchases||!this.ctx.auth.context)return 0;let e=await this.ctx.host.pendingPurchases();if(e.length===0)return 0;let t=await this.getDefinitions(),n=t.ok?Object.values(t.data.Purchase?.Products??{}):[],s=0;for(let i of e){let o=n.find(p=>i.storeProductID&&p.StoreProductIDs?.[i.store]===i.storeProductID);(await this.deliver(i,o)).ok&&s++;}return s}async deliver(e,t){let n=await this.validatePurchase(e.store,e.receipt,{signature:e.signature});return n.ok&&await this.ctx.host.finishPurchase(e,(t?.Type??"Consumable")==="Consumable"),n}hostStore(){return this.ctx.host.getClientPlatform()===Ne.Ios?"AppleAppStore":"GooglePlay"}async validatePurchasesBatch(e){if(!e||e.length===0)return h("client","receipts is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},n=await this.ctx.api.purchase.validatePurchasesBatch(t);if(n.ok)for(let s of n.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return n}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Fc=3,kC=700,Ci=class{constructor(e){this.ctx=e;e.host.supports.cryptoTopUp&&this.setTopUpHandler(this.hostTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return Un(e)}hostTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let n=await this.ctx.host.topUp({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return n.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:n.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=Fc;t++){let n=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(n.ok)return;if(n.reason!=="throttled"||t===Fc)break;await Zt(kC);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,n])=>({...n,OptionID:n.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,n)=>(t.OptionID??"").localeCompare(n.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let n of t)if(n?.Type===ks.Purchase&&n.ProductID)return n.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let n of t){if(n?.Type!==ks.CryptoCurrency||!n.CurrencyID)continue;let s=Number(n.Amount??0);if(!(s>0))continue;let i=this.cryptoBalance(n.CurrencyID);return i>=s?null:{currencyID:n.CurrencyID,required:s,available:i,missing:s-i}}return null}cryptoBalance(e){let n=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(n?.Amount??0)}};var jc="Lootbox",Si=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(jc,e);if(t){let i={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),G(i)}let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.lootbox.getDefinitions(n);if(s.ok){let i=s.data.LootboxDefinitions;i&&(this.ctx.data.config.patchSection(jc,i),this.ctx.emitter.emit("lootbox:definitionsLoaded",i));}return s}async open(e,t,n,s,i){if(!e)return h("client","LootboxID is required.");if(t<1)return h("client","Count must be at least 1.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:n,Payment:s,CreditsConfirmationID:i,RelatedEntityID:`lootbox_${e}_${n??"default"}_${V()}`},p=await this.ctx.api.lootbox.open(o);if(p.ok&&!p.data.CreditsConfirmation){let m=p.data;m.TriggeredPity&&m.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,m.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(m.Resources,m.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",m);}return p}};var Ua="Reward";function bi(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var xi=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Reward",{needsServer:()=>!t&&Object.values(e.cache.configSection(Ua)?.Comebacks??{}).some(n=>n?.TrackPresenceOnRead===true),refresh:async()=>{let n=await this.getUserRewardsState();return n.ok&&(t=true),n}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(Ua,e);if(t){let i={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),G(i)}let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.reward.getRewardDefinitions(n);if(s.ok){let i=s.data.RewardDefinitions;i&&(this.ctx.data.config.patchSection(Ua,i),this.ctx.emitter.emit("reward:definitionsLoaded",i));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let n=t.data;this.multiplierEnabled=n.Enabled,this.multiplier=n.Enabled?n.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",n);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${V()}`},s=await this.ctx.api.reward.claimDailyReward(n);if(s.ok){let i=s.data;this.ctx.data.user.patchDailyCalendarState(i.CalendarID,i.DailyState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",i);}return s}async collectIdleAccrual(e){if(!bi(e))return h("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${V()}`},n=await this.ctx.api.reward.collectIdleAccrual(t);if(n.ok){let s=n.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return n}async claimComebackReward(e){if(!bi(e))return h("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${V()}`},n=await this.ctx.api.reward.claimComebackReward(t);if(n.ok){let s=n.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return n}async claimReward(e){if(!bi(e))return h("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${V()}`},n=await this.ctx.api.reward.claimReward(t);if(n.ok){let s=n.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return n}async claimRewardWindow(e,t,n={}){if(!bi(e))return h("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return h("client","Amount must be a positive number.");let s=n.boost??"None";if(s==="Ad"&&!n.adRequestID)return h("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:s,...n.adRequestID?{AdRequestID:n.adRequestID}:{},RelatedEntityID:n.roundID??`reward_window_${e}_${V()}`},o=await this.ctx.api.reward.claimRewardWindow(i);if(o.ok){let p=o.data;this.ctx.data.user.patchRewardWindowState(p.WindowID,p.WindowState),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:windowClaimed",p);}return o}};var Di="Tutorial",Wc={key:"tutorial.state",login:"TutorialState",ttlMs:5*6e4,dependsOn:["Tutorial"],invalidateOn:["tutorial:flowStarted","tutorial:flowSkipped","tutorial:flowReset","tutorial:stepChanged","tutorial:stepsCompletedBatch","tutorial:rewardClaimed","tutorial:systemProgress"]},Ii=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Wc,{schema:Fs,apply:n=>this.applyUserTutorialState(n)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(Di)?.Flows??{}).length>0,refresh:async()=>{let n=await this.getUserTutorialState();return n.ok&&(t=true),n}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(Di,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.tutorial.getTutorialDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Di,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(Wc,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return l;t.AutoStart=e;let n=await this.ctx.api.tutorial.getUserTutorialState(t);return n.ok&&this.applyUserTutorialState(n.data),n}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.reportStepShown(n))}async completeStep(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.completeStep(n),{relatedEntityID:`tutorial_step_${e}_${t}_${V()}`})}async completeStepsBatch(e,t){let n=e?.trim();if(!n)return h("client","FlowID is required.");if(!t||t.length===0)return h("client","stepIDs is required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepIDs:t,RelatedEntityID:`tutorial_batch_${n}_${V()}`},i=await this.ctx.api.tutorial.completeStepsBatch(s);return i.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",i.data)),i}async skipStep(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.skipStep(n))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return h("client","FlowID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${V()}`},s=await this.ctx.api.tutorial.claimFlowReward(n);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,n){let s=e?.trim();if(!s)return h("client","FlowID is required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:s},o=await t(i);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(n.event,o.data)),o}async stepCall(e,t,n,s){let i=e?.trim(),o=t?.trim();if(!i)return h("client","FlowID is required.");if(!o)return h("client","StepID is required.");if(!this.ctx.auth.context)return l;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepID:o};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let m=this.ctx.data.user.state?.Tutorial?.Flows?.[i]?.RewardClaimed===true,g=await n(p);return g.ok&&(this.applyFlowView(g.data),this.mayHavePaid(i,o,m,g.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",g.data)),g}mayHavePaid(e,t,n,s){return !n&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Di)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}};var Pi=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return l;e>0&&(t.Limit=e);let n=await this.ctx.api.communityMarketing.getEarnings(t);return n.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",n.data),n}async claim(e){if(!e)return h("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.CampaignID=e;let n=await this.ctx.api.communityMarketing.claim(t);return n.ok&&this.ctx.emitter.emit("communityMarketing:claimed",n.data),n}async withdrawCryptoReward(e,t,n){if(!e)return h("client","campaignID is required.");if(!t)return h("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return l;s.CampaignID=e,s.WalletAddress=t,n&&(s.Amount=n);let i=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return i.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",i.data),i}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var _e=zod.z.object({Username:zod.z.string().nullish(),Country:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Premium:zod.z.boolean().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BoardRank:zod.z.number().nullish()}).passthrough();var zC={Global:"Global",Announcement:"Announcement",Group:"Group"},Kc=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),MC={None:"None",Language:"Language",Region:"Region"},OC=zod.z.enum(["None","Language","Region"]).catch("None"),EC={Anyone:"Anyone",Friends:"Friends"},qC=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),UC={Reject:"Reject",Mask:"Mask"},LC=zod.z.enum(["Reject","Mask"]).catch("Reject"),BC={Player:"Player",Publisher:"Publisher",System:"System"},GC=zod.z.enum(["Player","Publisher","System"]).catch("Player"),NC={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var _C=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),Qc=zod.z.object({Gate:te.nullish(),Schedule:Se.nullish()}).passthrough(),$c=zod.z.object({Gate:te.nullish(),Limits:ve.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Jc=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),VC=zod.z.object({Availability:J.nullish(),Write:J.nullish(),Retention:J.nullish()}).passthrough(),FC=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:_C.nullish(),Type:Kc.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:OC.nullish(),Capacity:zod.z.number().nullish(),Availability:Qc.nullish(),Write:$c.nullish(),Retention:Jc.nullish(),Presets:VC.nullish()}).passthrough(),jC=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:te.nullish(),WhoCanMessage:qC.nullish(),Limits:ve.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),WC=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:LC.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:ve.nullish()}).passthrough(),HC=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),KC=zod.z.object({Availability:zod.z.record(zod.z.string(),Qc).nullish(),Write:zod.z.record(zod.z.string(),$c).nullish(),Retention:zod.z.record(zod.z.string(),Jc).nullish()}).passthrough(),Zc=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),FC).nullish(),Direct:jC.nullish(),Moderation:WC.nullish(),Polling:HC.nullish(),Presets:KC.nullish()}).passthrough(),QC=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),Hc=zod.z.object({LastAt:zod.z.string().nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:zod.z.string().nullish(),TotalCount:zod.z.number().nullish(),LastTextHash:zod.z.string().nullish()}).passthrough();zod.z.object({MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish(),Ignored:zod.z.array(zod.z.string()).nullish(),Channels:zod.z.record(zod.z.string(),QC).nullish(),Limits:zod.z.record(zod.z.string(),Hc).nullish(),ReportLimits:Hc.nullish()}).passthrough();var La=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),vi=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:_e.nullish(),AuthorType:GC.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),SystemKey:zod.z.string().nullish(),SystemParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$C=zod.z.object({ChannelID:zod.z.string().nullish(),RoomID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Type:Kc.nullish(),CanWrite:zod.z.boolean().nullish(),WriteBlockedReason:zod.z.string().nullish(),SlowModeSeconds:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Ai=zod.z.object({Channels:zod.z.array($C).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),JC=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(vi).nullish(),NextCursor:La.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Yc=zod.z.object({Rooms:zod.z.array(JC).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Xc=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(vi).nullish(),NextBefore:La.nullish()}).passthrough(),ep=zod.z.object({Message:vi.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),tp=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:_e.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),ZC=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:_e.nullish(),LastMessage:vi.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),np=zod.z.object({Conversations:zod.z.array(ZC).nullish()}).passthrough(),Nn=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:La.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),sp=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),st={GetChatDefinitions:"GetChatDefinitions",GetChannels:"GetChannels",Poll:"Poll",GetHistory:"GetHistory",GetConversations:"GetConversations",SendMessage:"SendMessage",OpenDirectChannel:"OpenDirectChannel",MarkRead:"MarkRead",JoinChannel:"JoinChannel",LeaveChannel:"LeaveChannel",ReportMessage:"ReportMessage",IgnoreUser:"IgnoreUser",UnignoreUser:"UnignoreUser"};var ip="Chat",rp={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Ti=class{constructor(e){this.ctx=e;e.cache.bindLoginView(rp,{schema:Ai,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(ip,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.chat.getChatDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(ip,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(rp,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.Locale=e);let n=await this.ctx.api.chat.getChannels(t);return n.ok&&this.ctx.emitter.emit("chat:channelsLoaded",n.data),n}async poll(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let n=await this.ctx.api.chat.poll(t);if(!n.ok)return n;for(let s of n.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return n}async getHistory(e,t,n){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),n&&(s.Limit=n),this.ctx.api.chat.getHistory(s)):l}async sendMessage(e,t,n){let s=this.ctx.authedRequest();if(!s)return l;s.ChannelID=e,s.Text=t,n&&(s.Locale=n);let i=await this.ctx.api.chat.sendMessage(s);return i.ok&&this.ctx.emitter.emit("chat:sent",i.data),i}async sendDirect(e,t){let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.Text=t;let s=await this.ctx.api.chat.sendMessage(n);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):l}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):l}async markRead(e,t){let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(n);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):l}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):l}async reportMessage(e,t,n,s){let i=this.ctx.authedRequest();return i?(i.RoomID=e,i.MessageID=t,i.Reason=n,s&&(i.Comment=s),this.ctx.api.chat.reportMessage(i)):l}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):l}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):l}resetCursors(){this.cursors.clear();}};var YC={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},XC=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),eS={Player:"player",Title:"title",Creator:"creator"},_n={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},op=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),tS=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),Ba=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:XC.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(tS).nullish()}).passthrough(),ap=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(Ba).nullish()}).passthrough(),it={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var nS="IDOS_PLATFORM_PUSH_REQUEST",sS="IDOS_PLATFORM_PUSH_RESPONSE",iS=12e4;function lp(r){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(n=>{let s=false,i=m=>{s||(s=true,window.removeEventListener("message",o),clearTimeout(p),n(m));},o=m=>{let g=m?.data;!g||g.type!==sS||g.requestId!==t||It.includes(m.origin)&&i(g.ok===true);},p=setTimeout(()=>i(false),iS);window.addEventListener("message",o);for(let m of It)try{e.postMessage({type:nS,requestId:t,titleID:r},m);}catch{}})}var rS="idos:push:deviceToken:",wi=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let n=await this.ctx.api.push.getPushConfig(t),s=n.ok?n.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,n.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(this.ctx.host.supports.pushNotifications){if(!e.Configured)return it.Unsupported;let i=await this.ctx.host.requestPushToken({prompt:false});return i.error==="BLOCKED"?it.Blocked:i.token?this.ctx.host.storage.getString(this.deviceTokenKey())===i.token?it.Subscribed:it.Idle:i.error==="NOT_GRANTED"?it.Idle:it.Unsupported}if(!e.Configured||!e.PublicKey)return it.Unsupported;if(this.isEmbedded())return it.Embedded;if(!this.isSupported())return it.Unsupported;let t=Notification.permission;return t==="denied"?it.Blocked:t!=="granted"?it.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?it.Subscribed:it.Idle}async subscribe(e={}){let t=await this.getConfig();if(this.ctx.host.supports.pushNotifications)return this.subscribeDevice(t,e);if(!t.Configured||!t.PublicKey)return h("client","Push notifications are not available for this title.");if(this.isEmbedded())return await lp(this.ctx.settings.titleID)?G({Where:"portal",Subscription:null}):h("client","The portal did not complete the subscription.");if(!this.isSupported())return h("client","This browser has no Push API.");let n=await Notification.requestPermission();if(n!=="granted")return h("client",n==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:oS(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return l;let m=o.toJSON();p.PushEndpoint=m.endpoint,p.PushP256dh=m.keys?.p256dh,p.PushAuth=m.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let g=await this.ctx.api.push.subscribePush(p);return g.ok?(this.ctx.emitter.emit("push:subscribed",g.data),G({Where:"game",Subscription:g.data})):g}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return l;if(this.ctx.host.supports.pushNotifications){let n=this.ctx.host.storage.getString(this.deviceTokenKey());if(!n)return h("client","This device has no push subscription to remove.");e.PushDeviceToken=n;let s=await this.ctx.api.push.unsubscribePush(e);return s.ok&&(this.ctx.host.storage.remove(this.deviceTokenKey()),this.ctx.emitter.emit("push:unsubscribed",void 0)),s}if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return h("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):l}async unsubscribeByHash(e){if(!e)return h("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return l;t.PushEndpointHash=e;let n=await this.ctx.api.push.unsubscribePush(t);return n.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),n}async subscribeDevice(e,t){if(!e.Configured)return h("client","Push notifications are not available for this title.");let n=await this.ctx.host.requestPushToken({prompt:true});if(!n.token)return h("client",n.error==="BLOCKED"?"The player blocked notifications for this app.":"The device gave no push token.");let s=this.ctx.authedRequest();if(!s)return l;s.PushTransport=n.transport??"Fcm",s.PushDeviceToken=n.token,s.PushLocale=t.locale??(this.ctx.host.getLanguage()||void 0),s.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let i=await this.ctx.api.push.subscribePush(s);return i.ok?(this.ctx.host.storage.setString(this.deviceTokenKey(),n.token),this.ctx.emitter.emit("push:subscribed",i.data),G({Where:"game",Subscription:i.data})):i}deviceTokenKey(){return rS+this.ctx.settings.titleID}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function oS(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),n=new ArrayBuffer(t.length),s=new Uint8Array(n);for(let i=0;i<t.length;i++)s[i]=t.charCodeAt(i);return n}var ki=Object.freeze({}),zi=class{constructor(e){this.ctx=e;}ctx;table={...ki};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new Gn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,n])=>({Locale:n?.Locale??t,DisplayName:n?.DisplayName??null,Order:n?.Order??0})).sort((t,n)=>(t.Order??0)-(n.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let n=this.resolveKey(e,t),s=this.lookup(n)??this.lookup(e);return s===void 0?this.onMissing(e):t?aS(s,t):s}applyState(e,t){if(!e){this.reset();return}let n=e.Locale??null;this.table=t.table??{...ki},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return l;let n=await this.loadTableFromApi(e);if(!n.ok)return n;let{locale:s,table:i,fallbackLocale:o}=n.data,p=null;if(o){let m=await this.loadTableFromApi(o);m.ok&&(p=m.data.table);}return this.table=i,this.fallbackTable=p,this.currentFallbackLocale=o,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:o,entryCount:Object.keys(i).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):l}reset(){this.table={...ki},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:V()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return l;t.Locale=e;let n=await this.cache.read(up(e));n&&(t.KnownVersion=n.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let i=s.data,o=i.Locale??up(e),p=i.Version??0;if(i.NotModified){let g=n??await this.cache.read(o);return {ok:true,data:{locale:o,table:g?.t??{...ki},fallbackLocale:i.FallbackLocale??null}}}let m=i.Entries??{};return p>0&&await this.cache.write(o,p,m),{ok:true,data:{locale:o,table:m,fallbackLocale:i.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let n=t?.count;if(typeof n!="number")return e;let s=this.pluralCategory(n),i=`${e}.${s}`;if(this.lookup(i)!==void 0)return i;let o=`${e}.other`;return this.lookup(o)!==void 0?o:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function aS(r,e){return r.replace(/\{(\w+)\}/g,(t,n)=>{let s=e[n];return s===void 0?t:String(s)})}function up(r){return r.trim().replace(/_/g,"-").toLowerCase()}var Ga="Quest",lS={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:r=>{let e=Date.now(),t=null,n=[...Object.values(r.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(r.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of n){let i=Date.parse(s??"");!Number.isNaN(i)&&i>e&&(t===null||i<t)&&(t=i);}return t}},Mi=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:n=>{let s=e.cache.configSection(Ga)?.Cycles;if(!s)return false;let i=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(s)){let p=Date.parse(i[o]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=n&&t<p)return true}return false},refresh:async()=>{let n=await this.getUserQuestState(true,{forceRefresh:true});return n.ok&&(t=Date.now()),n}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(Ga,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.quest.getQuestDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Ga,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(lS,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return l;t.AutoRefreshCycles=e;let n=await this.ctx.api.quest.getUserQuestState(t);if(n.ok){let s=n.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(n.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return n}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let n=e.trim();if(!n)return h("client","QuestID is required.");if(!this.ctx.auth.context)return l;let s=t&&t.trim().length>0?t.trim():void 0,i={...this.ctx.buildAuthedBaseRequest(),QuestID:n,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${n}_${V()}`},o=await this.ctx.api.quest.claimQuestReward(i);if(o.ok){let p=o.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return h("client","quests is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},n=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(n.ok){let s=false;for(let i of n.data)!i.Success||!i.Data||(this.ctx.data.user.patchQuestStatus(i.Data.QuestID,i.Data.CycleID,"Claimed"),!s&&i.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",n.data);}return n}async claimMilestoneReward(e,t){let n=e.trim(),s=t.trim();if(!n||!s)return h("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),CycleID:n,MilestoneID:s,RelatedEntityID:`milestone_claim_${n}_${s}_${V()}`},o=await this.ctx.api.quest.claimMilestoneReward(i);if(o.ok){let p=o.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return h("client","milestones is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(n.ok){let s=false;for(let i of n.data)!i.Success||!i.Data||(this.ctx.data.user.patchMilestoneClaimed(i.Data.CycleID,i.Data.MilestoneID),!s&&i.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",n.data);}return n}async claimGroupCompletionReward(e,t){let n=e.trim(),s=t.trim();if(!n||!s)return h("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),CycleID:n,GroupCompletionID:s,RelatedEntityID:`group_completion_${n}_${s}_${V()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(i);if(o.ok){let p=o.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return o}async addQuestProgress(e,t){let n=e.trim();if(!n)return h("client","MetricID is required.");if(t<0)return h("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:n,ProgressValue:t},i=await this.ctx.api.quest.addQuestProgress(s);return i.ok&&(this.ctx.data.user.patchQuestProgressUpdates(i.data.Updates),this.ctx.emitter.emit("quest:progressAdded",i.data)),i}};var cp=zod.z.object({}).passthrough().transform(r=>r);var uS=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),cS=zod.z.object({Schedule:zod.z.array(uS).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),pS=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:u.nullish(),NextBonusStartUtc:u.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),hS=zod.z.object({Milestones:J.nullish()}).passthrough(),Na=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Category:zod.z.string().nullish(),Token:Mt.nullish(),TokenSources:zod.z.array(ft).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),Presets:hS.nullish(),BonusWindow:cS.nullish()}).passthrough(),dS=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:Na.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),mS=zod.z.object({TimedEventID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:Se.nullish(),Content:Na.nullish(),Events:zod.z.array(dS).nullish(),Gate:te.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),fS=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),gS=zod.z.object({Milestones:zod.z.record(zod.z.string(),On).nullish()}).passthrough(),Oi=zod.z.object({Definitions:zod.z.record(zod.z.string(),mS).nullish(),Settings:fS.nullish(),Presets:gS.nullish()}).passthrough(),yS=zod.z.object({Type:es,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:Na.nullish(),Progress:cp.nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:je.nullish(),BonusWindow:pS.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),Ei=zod.z.object({ActiveEvents:zod.z.array(yS).nullish()}).passthrough(),pp=zod.z.object({Tokens:zod.z.record(zod.z.string(),cp).nullish()}),_a=zod.z.object({Type:es.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),Va=zod.z.object({Type:es.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}),RS=zod.z.object({Type:es.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),Fa=zod.z.array(Ee(Va)),hp=zod.z.array(Ee(_a)),dp=zod.z.array(Ee(RS)),Rt={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var mp="TimedEvent",fp={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:r=>{let e=null;for(let t of r.ActiveEvents??[]){let n=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},qi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fp,{schema:Ei,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(fp,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(mp,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.timedEvent.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(mp,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,n,s,i,o,p=1){if(!t)return h("client","LteID is required.");if(!n)return h("client","SourceType is required.");if(!this.ctx.auth.context)return l;let m={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:n,Outcome:s,AmountOverride:i,SourceParams:o,RollMultiplier:p},g=await this.ctx.api.timedEvent.grantTokens(m);return g.ok&&(this.ctx.data.user.applyResourceOperation(g.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",g.data)),g}async spendTokens(e,t,n){if(!t)return h("client","LteID is required.");if(n<=0)return h("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:n},i=await this.ctx.api.timedEvent.spendTokens(s);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",i.data)),i}async claimMilestone(e,t,n){if(!t||!n)return h("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:n},i=await this.ctx.api.timedEvent.claimMilestone(s);if(i.ok){let o=i.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,n,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return h("client","milestones is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return n.ok&&(this.applyMilestoneClaimBatch(n.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",n.data)),n}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return l;e&&e.length>0&&(t.Events=e);let n=await this.ctx.api.timedEvent.claimAllMilestones(t);return n.ok&&(this.applyMilestoneClaimBatch(n.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",n.data)),n}async spendTokensBatch(e){if(!e||e.length===0)return h("client","spends is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},n=await this.ctx.api.timedEvent.spendTokensBatch(t);if(n.ok){let s=false;for(let i of n.data)!s&&i.Success&&i.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(i.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",n.data);}return n}async grantTokensBatch(e){if(!e||e.length===0)return h("client","grants is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},n=await this.ctx.api.timedEvent.grantTokensBatch(t);if(n.ok){let s=false;for(let i of n.data)!s&&i.Success&&i.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(i.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",n.data);}return n}applyMilestoneClaimBatch(e){let t=false;for(let n of e){if(!n.Success||!n.Data)continue;let s=n.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var CS=zod.z.object({UserID:zod.z.string(),Score:Q.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:u.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:_e.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),us=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:Q.nullish(),CycleEndUtc:u.nullish(),TopUsers:zod.z.array(CS).nullish(),BracketID:zod.z.string().nullish()}),SS=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),MilestoneTokensEarned:Q.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Ui=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:Q.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:Q.nullish(),MilestoneTokensEarned:Q.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:je.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(SS).nullish()}),Li=zod.z.object({LeaderboardID:zod.z.string(),NewScore:Q,CycleVersion:zod.z.number()}),Bi=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Gi=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish()}),gp=zod.z.array(Ee(us)),Ni=zod.z.array(Ee(Ui)),yp=zod.z.array(Ee(Bi)),Rp=zod.z.array(Ee(Gi)),Cp=zod.z.array(Ee(Li)),bS=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:Ee(Bi).nullish(),Milestones:zod.z.array(Ee(Gi)).nullish()}),Sp=zod.z.array(bS),xS=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:Ee(us).nullish(),Progress:Ee(Ui).nullish()}),bp=zod.z.array(xS),DS=zod.z.string(),xp=zod.z.object({Rank:zod.z.string().nullish(),Rewards:$.nullish(),SeasonTierRewards:ba.nullish()}).passthrough(),IS=zod.z.object({RankRewards:zod.z.array(xp).nullish()}).passthrough(),PS=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),vS=zod.z.object({Milestones:J.nullish(),RankRewards:J.nullish()}).passthrough(),AS=zod.z.object({LeaderboardID:zod.z.string(),DisplayName:zod.z.string().nullish(),ScoreDisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsEnabled:zod.z.boolean().nullish(),ScoreAggregation:DS.nullish(),Schedule:Se.nullish(),ChainEvents:zod.z.array(PS).nullish(),Gate:te.nullish(),TopUsersLimit:zod.z.number().nullish(),MinScoreToEnterTop:zod.z.number().nullish(),BracketSize:zod.z.number().nullish(),LinkedSeasonChainID:zod.z.string().nullish(),RankRewards:zod.z.array(xp).nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),Presets:vS.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(ft).nullish()}).passthrough(),TS=zod.z.object({Milestones:zod.z.record(zod.z.string(),On).nullish(),RankRewards:zod.z.record(zod.z.string(),IS).nullish()}).passthrough(),_i=zod.z.object({Definitions:zod.z.record(zod.z.string(),AS).nullish(),Presets:TS.nullish()}).passthrough(),Ye={GetDefinitions:"GetDefinitions",GetLeaderboard:"GetLeaderboard",GetMyProgress:"GetMyProgress",SubmitScore:"SubmitScore",SubmitScoreFromSource:"SubmitScoreFromSource",ClaimCycleReward:"ClaimCycleReward",ClaimMilestone:"ClaimMilestone",GetFriendsLeaderboard:"GetFriendsLeaderboard",GetLeaderboardsBatch:"GetLeaderboardsBatch",GetProgressBatch:"GetProgressBatch",ClaimCycleRewardsBatch:"ClaimCycleRewardsBatch",ClaimMilestonesBatch:"ClaimMilestonesBatch",SubmitScoresBatch:"SubmitScoresBatch",ClaimAllRewardsBatch:"ClaimAllRewardsBatch",GetOverviewBatch:"GetOverviewBatch"};var Dp="Leaderboard",Ip={key:"leaderboard.progress",login:"LeaderboardProgress",ttlMs:5*6e4,dependsOn:["Leaderboard","EventToken"],invalidateOn:["leaderboard:scoreSubmitted","leaderboard:scoresSubmittedBatch","leaderboard:cycleRewardClaimed","leaderboard:cycleRewardsClaimedBatch","leaderboard:milestoneClaimed","leaderboard:milestonesClaimedBatch","leaderboard:allRewardsClaimedBatch"]},Vi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ip,{schema:Ni,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Dp,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.leaderboard.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Dp,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return h("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getLeaderboard(t);return n.ok&&this.ctx.emitter.emit("leaderboard:loaded",n.data),n}async getMyProgress(e){if(!e)return h("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getMyProgress(t);return n.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),n.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",n.data)),n}async submitScore(e,t){if(!e)return h("client","LeaderboardID is required.");if(t<=0)return h("client","Score must be positive.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(n);if(s.ok){let i=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),i.NewScore,t,i.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",i);}return s}async submitScoreFromSource(e,t,n,s,i=1){if(!e)return h("client","LeaderboardID is required.");if(!t)return h("client","SourceType is required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:n,Params:s,RollMultiplier:i},p=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(p.ok){let m=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),m.NewScore,m.NewScore,m.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",m);}return p}async claimCycleReward(e){if(!e)return h("client","LeaderboardID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},n=await this.ctx.api.leaderboard.claimCycleReward(t);if(n.ok){let s=n.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return n}async claimMilestone(e,t,n){if(!e||!t)return h("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...n?{CycleKey:n}:{}},i=await this.ctx.api.leaderboard.claimMilestone(s);if(i.ok){let o=i.data;n||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",o);}return i}async getFriendsLeaderboard(e){if(!e)return h("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return n.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",n.data),n}async getLeaderboardsBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return n.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",n.data),n}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(h("client","leaderboardIDs is required.")):this.ctx.cache.read(Ip,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getProgressBatch(t);return n.ok&&this.applyProgressBatch(n.data),n}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},n=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(n.ok){for(let s of n.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",n.data);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return h("client","milestones is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(n.ok){for(let s of n.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",n.data);}return n}async submitScoresBatch(e){if(!e||e.length===0)return h("client","scores is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},n=await this.ctx.api.leaderboard.submitScoresBatch(t);if(n.ok){for(let s of n.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",n.data);}return n}async claimAllRewardsBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},n=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(n.ok){for(let s of n.data){let i=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(i),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of s.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(i,o.Data.MilestoneID),o.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(o.Data.Resources,o.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",n.data);}return n}async getOverviewBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getOverviewBatch(t);if(n.ok){for(let s of n.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",n.data);}return n}};var ja=zod.z.object({}).passthrough().transform(r=>r),Fi=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>Tp).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:Q.nullish(),UserState:ja.nullish(),NextTier:zod.z.lazy(()=>Ap).nullish()}).passthrough(),Pp=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:Q.nullish(),NewStatusTokens:Q.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),Wa=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:O.nullish(),Inventory:K.nullish()}),vp=Ot(Wa);var Ap=zod.z.object({Tier:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredTokens:Q.nullish(),TierReachedReward:$.nullish()}).passthrough(),Tp=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:Q.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(Ap).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var wS=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Se.nullish(),Seasons:zod.z.array(Tp).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:te.nullish()}).passthrough(),ji=zod.z.object({Chains:zod.z.record(zod.z.string(),wS).nullish()}).passthrough(),Xt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var wp="Season",kp={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=Date.parse(r.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Wi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(kp,{schema:Fi,apply:(t,n)=>this.applyActiveSeason(n??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(wp,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.season.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(wp,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(kp,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(h("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return l;t.SeasonChainID=e;let n=await this.ctx.api.season.getActiveSeason(t);return n.ok&&this.applyActiveSeason(e,n.data),n}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return h("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.SeasonChainID=e;let n=await this.ctx.api.season.getUserState(t);return n.ok&&(this.ctx.data.user.patchSeasonState(e,n.data),this.ctx.emitter.emit("season:userStateLoaded",n.data)),n}async grantStatusTokens(e,t){if(!e)return h("client","SeasonChainID is required.");if(t<=0)return h("client","Amount must be positive.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${V()}`},s=await this.ctx.api.season.grantStatusTokens(n);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return h("client","SeasonChainID is required.");if(t<=0)return h("client","TierNumber must be positive.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${V()}`},s=await this.ctx.api.season.claimTierReward(n);if(s.ok){let i=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",i);}return s}async claimTierRewardsBatch(e,t){if(!e)return h("client","SeasonChainID is required.");let n=(t??[]).filter(o=>o>0);if(n.length===0)return h("client","TierNumbers is required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:n,RelatedEntityID:`season_tier_batch_${e}_${V()}`},i=await this.ctx.api.season.claimTierRewardsBatch(s);if(i.ok){let o=i.data;for(let p of o.Items??[]){let m=p.Data?.TierNumber;p.Success&&typeof m=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,m);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return i}};var zp="Premium",Hi=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(zp,e);if(t){let i={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",i),G(i)}let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.premium.getDefinitions(n);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(zp,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return h("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(n);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,n="Default",s=1,i){if(!e||!t)return h("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:n,Count:s,CreditsConfirmationID:i,RelatedEntityID:`premium_purchase_${e}_${t}`},p=await this.ctx.api.premium.purchaseItemOrCurrency(o);if(p.ok&&!p.data.CreditsConfirmation){let m=p.data;m.Premium&&this.ctx.data.user.applyPremium(m.Premium),this.ctx.data.user.applyResourceOperation(m.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",m);}return p}async purchaseRealMoney(e,t,n,s,i,o,p,m){if(!e||!t)return h("client","PremiumID and TransactionID are required.");if(!s||!i)return h("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return l;let g={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:n,ProductID:s,ReceiptData:i,PurchaseToken:o,PackageName:p,AppStoreEnvironment:m,RelatedEntityID:`premium_iap_${e}_${t}`},j=await this.ctx.api.premium.purchaseRealMoney(g);if(j.ok){let pe=j.data;pe.Premium&&this.ctx.data.user.applyPremium(pe.Premium),this.ctx.data.user.applyResourceOperation(pe.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",pe);}return j}};var Ki=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:u.nullish()}),cs=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:Q.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),Ki).nullish(),UpdatedAt:u.nullish()}).passthrough(),Mp=zod.z.object({Characters:zod.z.record(zod.z.string(),cs).nullish(),SelectedCharacterID:zod.z.string().nullish()}),Ha=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Ka=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Op=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Ki).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Ep=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),kS=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),qp=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),kS).nullish(),Inventory:K.nullish()}),Qa=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Up=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:Ki.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Lp=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Ki.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Bp=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),zS=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:u.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:me.nullish()}),MS=zod.z.object({CharacterID:zod.z.string(),CharacterOpen:zod.z.boolean().nullish(),DefaultSkinID:zod.z.string().nullish(),WornSkinID:zod.z.string().nullish(),Skins:zod.z.array(zS).nullish()}),Gp=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),MS).nullish()}),Np=zod.z.object({ServerTimeUtc:u,SelectedCharacterID:zod.z.string().nullish()}),_p=Ot(Qa),Vp=Ot(Ka),Fp=Ot(Ha),$a=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),jp=zod.z.object({StatID:zod.z.string(),TypeID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish(),Weight:zod.z.number().nullish(),PriceOptions:me.nullish(),CostCurve:Ze.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Ze.nullish(),RankCurve:Ze.nullish(),Requirements:zod.z.array($a).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),OS=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array($a).nullish(),AllowedRarityIDs:zod.z.array(zod.z.string()).nullish(),AllowedItemTags:zod.z.array(zod.z.string()).nullish(),MinItemLevel:zod.z.number().nullish(),MaxItemLevel:zod.z.number().nullish()}).passthrough(),Wp=zod.z.object({Slots:zod.z.record(zod.z.string(),OS).nullish()}).passthrough(),Hp=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Lore:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ES=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),qS=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:me.nullish()}).passthrough(),US=zod.z.object({Stats:J.nullish(),Levels:J.nullish(),Equipment:J.nullish()}).passthrough(),Kp=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:me.nullish(),CostCurve:Ze.nullish()}).passthrough(),Ja="@skin";function LS(r){return !!r&&r.startsWith("@")}var BS=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),GS=zod.z.object({PriceOptions:me.nullish(),Schedule:Se.nullish(),Gate:te.nullish()}).passthrough(),NS=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array($a).nullish()}).passthrough(),_S=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Hp.nullish(),Item:BS.nullish(),Sale:GS.nullish(),Requirements:NS.nullish()}).passthrough(),VS=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),_S).nullish()}).passthrough(),FS=zod.z.object({CharacterID:zod.z.string(),Identity:Hp.nullish(),Classification:ES.nullish(),Unlock:qS.nullish(),Presets:US.nullish(),Equipment:Wp.nullish(),Stats:zod.z.record(zod.z.string(),jp).nullish(),RankLadder:Kp.nullish(),RankStatCurve:Ze.nullish(),StatMaxLevelCurve:Ze.nullish(),Skins:VS.nullish()}).passthrough(),jS=zod.z.object({Stats:zod.z.record(zod.z.string(),jp).nullish()}).passthrough(),WS=zod.z.object({RankLadder:Kp.nullish()}).passthrough(),HS=zod.z.object({Equipment:Wp.nullish()}).passthrough(),KS=zod.z.object({Stats:zod.z.record(zod.z.string(),jS).nullish(),Levels:zod.z.record(zod.z.string(),WS).nullish(),Equipment:zod.z.record(zod.z.string(),HS).nullish()}).passthrough(),Qi=zod.z.object({Definitions:zod.z.record(zod.z.string(),FS).nullish(),Presets:KS.nullish()}).passthrough(),Je={GetCharacterDefinitions:"GetCharacterDefinitions",GetUserCharacters:"GetUserCharacters",UnlockCharacter:"UnlockCharacter",UpgradeStatLevel:"UpgradeStatLevel",UpgradeCharacterLevel:"UpgradeCharacterLevel",EquipItems:"EquipItems",UnequipItems:"UnequipItems",UnequipAllCharacters:"UnequipAllCharacters",UnlockCharactersBatch:"UnlockCharactersBatch",UpgradeCharacterLevelsBatch:"UpgradeCharacterLevelsBatch",UpgradeStatLevelsBatch:"UpgradeStatLevelsBatch",UnlockSkin:"UnlockSkin",EquipSkin:"EquipSkin",UnequipSkin:"UnequipSkin",GetCharacterSkins:"GetCharacterSkins",SelectCharacter:"SelectCharacter"},QS="SKIN_ALREADY_OWNED";var Za="Character",$i=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Za)?.Definitions,n=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,i])=>i?.Unlock?.UnlockedByDefault===true&&!n[i.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(Za,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.character.getCharacterDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Za,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let n=t.data.Characters??{};this.ctx.data.user.applyCharacter(n),this.ctx.data.user.applySelectedCharacter(t.data.SelectedCharacterID),this.ctx.emitter.emit("character:userCharactersLoaded",n);}return t}async unlockCharacter(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${V()}`},s=await this.ctx.api.character.unlockCharacter(n);if(s.ok&&!s.data.CreditsConfirmation){let i=s.data;this.ctx.data.user.patchCharacter(i.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},i.Power!=null&&(o.Power=i.Power),o.UpdatedAt=i.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(i.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",i);}return s}async upgradeStatLevel(e,t,n){if(!e||!t)return h("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${V()}`,SelectedOptionID:n?.selectedOptionID,CreditsConfirmationID:n?.creditsConfirmationID,...n?.levels!=null?{Levels:n.levels}:{},...n?.targetLevel!=null?{TargetLevel:n.targetLevel}:{}},i=await this.ctx.api.character.upgradeStatLevel(s);if(i.ok&&!i.data.CreditsConfirmation){let o=i.data;this.ctx.data.user.patchCharacter(o.CharacterID,p=>{p.StatLevels??={},p.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(p.Power=o.Power),p.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return i}async upgradeCharacterLevel(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${V()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(n);if(s.ok&&!s.data.CreditsConfirmation){let i=s.data;this.ctx.data.user.patchCharacter(i.CharacterID,o=>{o.Level=i.NewLevel,i.Power!=null&&(o.Power=i.Power),o.UpdatedAt=i.ServerTimeUtc,i.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(i.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",i);}return s}async equipItems(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(n);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(n);if(s.ok){let i=s.data;this.applyUnequipChangesLocally(e,i),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:i.ClearedSlotIDs??[],power:i.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,n){if(!e||!t)return h("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,AutoEquip:n?.autoEquip??false,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${V()}`},i=await this.ctx.api.character.unlockSkin(s);if(i.ok&&!i.data.CreditsConfirmation){let o=i.data;this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),o.Equipped&&o.Equipment&&this.applySkinLocally(o.CharacterID,o.Equipment,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",o);}return i}async equipSkin(e,t,n){if(!e||!t)return h("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:n},i=await this.ctx.api.character.equipSkin(s);if(i.ok){let o=i.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return i}async unequipSkin(e){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},n=await this.ctx.api.character.unequipSkin(t);if(n.ok){let s=n.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return n}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):l}async selectCharacter(e){let t=this.ctx.authedRequest();if(!t)return l;let n=e?.trim();if(!n)return h("client","CharacterID is required.");t.CharacterID=n;let s=await this.ctx.api.character.selectCharacter(t);return s.ok&&(this.ctx.data.user.applySelectedCharacter(s.data.SelectedCharacterID),this.ctx.emitter.emit("character:selected",s.data)),s}applySkinLocally(e,t,n,s){let i=this.ctx.data.user;i.patchCharacterEquipment(e,Ja,t??null),i.patchCharacter(e,o=>{n!=null&&(o.Power=n),o.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return h("client","characterIDs is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},n=await this.ctx.api.character.unlockCharactersBatch(t);return n.ok&&(this.applyBatchResults(n.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,i=>{i.Level??=1,i.StatLevels??={},i.Equipment??={},s.Power!=null&&(i.Power=s.Power),i.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",n.data)),n}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return h("client","upgrades is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},n=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return n.ok&&(this.applyBatchResults(n.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,i=>{i.Level=s.NewLevel,s.Power!=null&&(i.Power=s.Power),i.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(i.StatLevels??={},i.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",n.data)),n}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return h("client","upgrades is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},n=await this.ctx.api.character.upgradeStatLevelsBatch(t);return n.ok&&(this.applyBatchResults(n.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,i=>{i.StatLevels??={},i.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(i.Power=s.Power),i.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",n.data)),n}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let n of e.Items??[])!n.Success||!n.Data||t(n.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[s,i]of Object.entries(t.Equipment??{}))n.patchCharacterEquipment(e,s,i);n.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let n=t.ClearedSlotIDs??[];if(n.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let i of n)s.patchCharacterEquipment(e,i,null);s.patchCharacter(e,i=>{t.Power!=null&&(i.Power=t.Power),i.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[n,s]of Object.entries(e.Characters??{})){for(let i of s.ClearedSlotIDs??[])t.patchCharacterEquipment(n,i,null);t.patchCharacter(n,i=>{s.Power!=null&&(i.Power=s.Power),i.UpdatedAt=e.ServerTimeUtc;});}}};var Qp="Match",Ji=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,n,s,i,o){let p=this.ctx.auth.context;if(!p)return l;let m={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:n,BattleStrategy:s,TargetUserID:i,SelectedOptionID:o,RelatedEntityID:`pvp_create_${p.userID}_${V()}`},g=await this.ctx.api.match.createMatch(m);return g.ok&&(this.ctx.data.user.applyResourceOperation(g.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",g.data)),g}async updateMatch(e,t={}){if(!e)return h("client","MatchID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(n);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return h("client","MatchID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},n=await this.ctx.api.match.cancelMatch(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",n.data)),n}async instantBattle(e,t,n,s){let i=this.ctx.auth.context;if(!i)return l;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:n,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${V()}`},p=await this.ctx.api.match.instantBattle(o);if(p.ok){let m=p.data,g=this.ctx.data.config.itemDefinitions;if(m.Resources)this.ctx.data.user.applyResourceOperation(m.Resources,g);else if(m.ResourcesDual){let j=m.ResourcesDual;j.FromUserID===i.userID&&j.FromResult?this.ctx.data.user.applyResourceOperation(j.FromResult,g):j.ToUserID===i.userID&&j.ToResult&&this.ctx.data.user.applyResourceOperation(j.ToResult,g);}this.ctx.emitter.emit("match:instantBattleCompleted",m);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},n=await this.ctx.api.match.saveStrategy(t);return n.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),n}async getMyMatches(e=0,t=20,n){let s=this.ctx.authedRequest();if(!s)return l;s.Page=e,s.PageSize=t,s.Statuses=n;let i=await this.ctx.api.match.getMyMatches(s);return i.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",i.data),i}async getAvailableMatches(e=0,t=20,n=false){let s=this.ctx.authedRequest();if(!s)return l;s.Page=e,s.PageSize=t,s.OnlyPublic=n;let i=await this.ctx.api.match.getAvailableMatches(s);return i.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",i.data),i}async getDefinitions(e){let t=this.ctx.cache.configSection(Qp,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.match.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Qp,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var $S="Challenge",Zi=class{constructor(e){this.ctx=e;}ctx;lastState=null;get definitions(){return this.ctx.cache.configSection($S)??null}get state(){return this.lastState}chainDefinition(e){return this.definitions?.Chains?.[e]??null}phaseDefinition(e,t){return t?this.chainDefinition(e)?.Challenges?.find(n=>n?.ChallengeID===t)??null:null}chainView(e){return this.lastState?.Chains?.find(t=>t.ChainID===e)??null}newAttemptID(){return V().replace(/-/g,"")}async getState(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.ChainID=e);let n=await this.ctx.api.challenge.getState(t);return n.ok&&this.applyState(n.data,e),n}async refreshOpponents(e){if(!e)return h("client","ChainID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.ChainID=e;let n=await this.ctx.api.challenge.refreshOpponents(t);return n.ok&&this.applyState(n.data,e),n}async attempt(e,t,n,s,i){if(!e)return h("client","ChainID is required.");if(!n)return h("client","AttemptID is required.");let o=this.ctx.authedRequest();if(!o)return l;o.ChainID=e,o.AttemptID=n,"tierID"in t?o.TierID=t.tierID:o.RevengeID=t.revengeID,s&&(o.CharacterID=s),i&&(o.BattleStrategy=i);let p=await this.ctx.api.challenge.attempt(o);if(p.ok){let m=p.data;m.IsReplay||this.ctx.data.user.applyResourcesWithDelta(m.Rewards,m.Inventory,this.ctx.data.config.itemDefinitions),this.patchAfterAttempt(e,m,"revengeID"in t?t.revengeID:void 0),this.ctx.emitter.emit("challenge:attemptCompleted",m);}return p}async claimMilestone(e,t,n){if(!e||!t)return h("client","ChainID and MilestoneID are required.");let s=this.ctx.authedRequest();if(!s)return l;s.ChainID=e,s.MilestoneID=t,n&&(s.InstanceKey=n);let i=await this.ctx.api.challenge.claimMilestone(s);if(i.ok){let o=i.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.markClaimed(e,o.InstanceKey??n,t),this.ctx.emitter.emit("challenge:milestoneClaimed",o);}return i}async claimReachedMilestones(e){if(!this.ctx.auth.context)return l;let t=[],n=(this.lastState?.Chains??[]).filter(s=>!e||s.ChainID===e);for(let s of n){if(!s.ChainID)continue;let i=[s.Active,...s.Ended??[]].filter(o=>!!o&&!!o.CanClaim);for(let o of i)for(let p of this.reachedUnclaimed(s.ChainID,o)){let m=await this.claimMilestone(s.ChainID,p,o.InstanceKey??void 0);m.ok&&t.push(m.data);}}return G(t)}reachedUnclaimed(e,t){let n=this.phaseDefinition(e,t.ChallengeID),s=t.PointsEarned??0,i=new Set(t.ClaimedMilestoneIDs??[]);return Object.entries(n?.Milestones??{}).filter(([o,p])=>!i.has(o)&&(p?.RequiredProgress??1/0)<=s).sort((o,p)=>(o[1]?.RequiredProgress??0)-(p[1]?.RequiredProgress??0)).map(([o])=>o)}applyState(e,t){if((e.Rewards||e.Inventory)&&this.ctx.data.user.applyResourcesWithDelta(e.Rewards,e.Inventory,this.ctx.data.config.itemDefinitions),t&&this.lastState){let n=(this.lastState.Chains??[]).filter(s=>s.ChainID!==t);this.lastState={...e,Chains:[...n,...e.Chains??[]]};}else this.lastState=e;this.ctx.emitter.emit("challenge:stateLoaded",e);}patchAfterAttempt(e,t,n){let s=this.chainView(e);if(!s)return;t.Tickets!=null&&(s.Tickets=t.Tickets);let i=s.Active;if(!i||i.InstanceKey!==t.InstanceKey)return;t.PointsEarned!=null&&(i.PointsEarned=t.PointsEarned),t.IsReplay||(i.AttemptsToday=(i.AttemptsToday??0)+1);let o=t.Attempt;if(!(!o?.Win||!i.Arena))if(o.IsRevenge)i.Arena.Revenges=(i.Arena.Revenges??[]).filter(p=>p.RevengeID!==n);else for(let p of i.Arena.Opponents??[])p.TierID===o.TierID&&p.OpponentID===o.OpponentID&&(p.Defeated=true);}markClaimed(e,t,n){let s=this.chainView(e);if(s)for(let i of [s.Active,...s.Ended??[]])i&&(t&&i.InstanceKey!==t||!t&&i!==s.Active||(i.ClaimedMilestoneIDs=[...new Set([...i.ClaimedMilestoneIDs??[],n])]));}};var $p="Craft",Yi=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection($p,e);if(t){let i={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),G(i)}let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.craft.getDefinitions(n);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection($p,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,n=1,s,i,o){if(!e)return h("client","CraftID is required.");let p=this.ctx.auth.context;if(!p)return l;let m={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:n,SelectedOptionID:s,InputInstanceIDs:i,CreditsConfirmationID:o,RelatedEntityID:`craft_${e}_${p.userID}_${V()}`},g=await this.ctx.api.craft.craft(m);return g.ok&&!g.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(g.data.Resources,g.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",g.data)),g}};var en=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(en),zod.z.record(zod.z.string(),en)]));var tn={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Jp=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),yn={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function ps(r){return r!==yn.Pending&&r!==yn.Running}var JS={Disabled:"AI_DISABLED",FeatureNotFound:"AI_FEATURE_NOT_FOUND",FeatureDisabled:"AI_FEATURE_DISABLED",WrongAction:"AI_WRONG_ACTION",NotAvailableForPlayer:"AI_NOT_AVAILABLE_FOR_PLAYER",FeatureClosed:"AI_FEATURE_CLOSED",LimitReached:"AI_LIMIT_REACHED",Cooldown:"AI_COOLDOWN",BadInput:"AI_BAD_INPUT",PromptRejected:"AI_PROMPT_REJECTED",Unavailable:"AI_UNAVAILABLE",GenerationFailed:"AI_GENERATION_FAILED",GenerationNotFound:"AI_GENERATION_NOT_FOUND"};function ZS(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var YS=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),XS=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),Xi=zod.z.object({CreditsConfirmation:Re.nullish(),GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Jp.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),en).nullish(),Assets:zod.z.array(YS).nullish(),Error:XS.nullish(),Charge:O.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:O.nullish(),Context:zod.z.record(zod.z.string(),en).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreditsPrice:zod.z.number().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish()}),Zp=zod.z.object({Data:zod.z.array(Xi).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),eb=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish()}).passthrough(),Tt=zod.z.record(zod.z.string(),zod.z.string()),tb=zod.z.object({Key:zod.z.string().nullish(),Role:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),Label:Tt.nullish()}).passthrough(),nb=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Default:zod.z.string().nullish(),Multiline:zod.z.boolean().nullish(),Label:Tt.nullish(),Placeholder:Tt.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string().nullish(),Label:Tt.nullish()}).passthrough()).nullish()}).passthrough(),Yp=zod.z.object({Key:zod.z.string(),Kind:zod.z.string().nullish(),Name:Tt.nullish(),Hint:Tt.nullish(),Unit:Tt.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string(),Name:Tt.nullish(),Group:zod.z.string().nullish()}).passthrough()).nullish(),Groups:zod.z.array(zod.z.object({Key:zod.z.string(),Name:Tt.nullish()}).passthrough()).nullish(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),Step:zod.z.number().nullish()}).passthrough(),Xp=zod.z.object({PriceOptions:me.nullish()}).passthrough(),sb=zod.z.object({Id:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Action:zod.z.string().nullish(),IsTrend:zod.z.boolean().nullish(),Category:zod.z.string().nullish(),Order:zod.z.number().nullish(),Name:Tt.nullish(),Description:Tt.nullish(),Preview:zod.z.object({Url:zod.z.string().nullish(),PosterUrl:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough().nullish(),Inputs:zod.z.array(tb).nullish(),Variables:zod.z.array(nb).nullish(),Settings:zod.z.array(Yp).nullish()}).passthrough(),ib=zod.z.object({Modality:Jp.nullish(),Async:zod.z.boolean().nullish(),Limits:ve.nullish(),PriceOptions:me.nullish(),Tags:zod.z.array(zod.z.string()).nullish(),HistoryMessages:zod.z.number().nullish(),MaxTokens:zod.z.number().nullish(),AllowImages:zod.z.boolean().nullish(),MaxInputImages:zod.z.number().nullish(),MaxInputImageBytes:zod.z.number().nullish(),AllowedImageTypes:zod.z.array(zod.z.string()).nullish(),MaxImages:zod.z.number().nullish(),AllowEdit:zod.z.boolean().nullish(),AllowReferenceImage:zod.z.boolean().nullish(),MaxPromptChars:zod.z.number().nullish(),LockBehavior:zod.z.boolean().nullish(),ImageSize:zod.z.string().nullish(),VideoSize:zod.z.string().nullish(),VideoSeconds:zod.z.number().nullish(),Voice:zod.z.string().nullish(),AudioFormat:zod.z.string().nullish(),MusicFormat:zod.z.string().nullish(),ThreeDOperation:zod.z.string().nullish(),ThreeDAnimations:zod.z.array(zod.z.string()).nullish(),Reward:$.nullish(),PromptVariables:zod.z.array(eb).nullish(),AllowFreePrompt:zod.z.boolean().nullish(),PlatformTemplateId:zod.z.string().nullish(),PlatformTemplate:sb.nullish(),Settings:zod.z.array(Yp).nullish(),FreePerDay:zod.z.number().nullish(),FreeLeftToday:zod.z.number().nullish()}).passthrough(),eh=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),ib).nullish()}).passthrough(),We={GetDefinitions:"GetDefinitions",GenerateText:"GenerateText",GetText:"GetText",GenerateImage:"GenerateImage",EditImage:"EditImage",GenerateVideo:"GenerateVideo",GetVideo:"GetVideo",GenerateAudio:"GenerateAudio",GenerateMusic:"GenerateMusic",GenerateThreeD:"GenerateThreeD",GetThreeD:"GetThreeD",ListGenerations:"ListGenerations",GetGeneration:"GetGeneration",GetImage:"GetImage",GetAudio:"GetAudio",GetMusic:"GetMusic",GenerateFromTemplate:"GenerateFromTemplate",EstimateTemplatePrice:"EstimateTemplatePrice"};var th="AI",rb=/^[A-Za-z0-9_-]{1,128}$/,ob=2e3,ab=5e3,lb=30*6e4;function ub(r,e){return new Promise(t=>{if(e?.aborted){t();return}let n=()=>{clearTimeout(s),e?.removeEventListener("abort",n),t();},s=setTimeout(n,r);e?.addEventListener("abort",n,{once:true});})}var er=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(th,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.ai.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(th,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,n){return this.generate(e,{Text:t},n,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,n){return this.generate(e,{Image:t},n,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,n){return this.generate(e,{ImageEdit:t},n,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,n){return this.generate(e,{Video:t},n,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,n){return this.generate(e,{Audio:t},n,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,n){return this.generate(e,{Music:t},n,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,n){return this.generate(e,{TemplateInputs:t},n,s=>this.ctx.api.ai.generateFromTemplate(s))}async estimateTemplatePrice(e,t,n){return e?this.ctx.auth.context?this.ctx.api.ai.estimateTemplatePrice({...this.ctx.buildAuthedBaseRequest(),FeatureKey:e,Params:t,Variables:n}):l:h("client","FeatureKey is required.")}generateThreeD(e,t,n){return this.generate(e,{ThreeD:t},n,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):l}async getGeneration(e){if(!e)return h("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):l}isTerminal(e){return ps(e)}async waitForGeneration(e,t={}){let n;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;n=p.data;}else {if(!e?.GenerationID)return h("client","GenerationID is required.");n=e;}let s=Date.now()+(t.timeoutMs??lb),i=Math.max(1,t.intervalMs??ob),o=Math.max(i,t.maxIntervalMs??ab);for(;!ps(n.Status);){if(t.signal?.aborted)return h("client","Stopped waiting: the wait was aborted.");if(Date.now()+i>s)return h("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await ub(i,t.signal),t.signal?.aborted)return h("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(n);if(i=Math.min(o,Math.round(i*1.5)),!p.ok){if(p.reason==="connection")continue;return p}n=p.data,ps(n.Status)||t.onUpdate?.(n);}return G(n)}pollFor(e){switch(e.Modality){case tn.Text:return this.getText(e.GenerationID);case tn.Image:return this.getImage(e.GenerationID);case tn.Audio:return this.getAudio(e.GenerationID);case tn.Music:return this.getMusic(e.GenerationID);case tn.Video:return this.getVideo(e.GenerationID);case tn.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,n,s){if(!e)return h("client","FeatureKey is required.");let i=n?.relatedEntityID;if(i!==void 0&&!rb.test(i))return h("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,Variables:n?.variables,Params:n?.params,Context:n?.context,RelatedEntityID:i??V()},p=await s(o);return p.ok&&!p.data.CreditsConfirmation&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return h("client","GenerationID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.GenerationID=e;let s=await t(n);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===yn.Completed&&!this.rewarded.has(e.GenerationID)&&(this.rewarded.add(e.GenerationID),await this.ctx.userService.getUserInventory()),!(!t||!e.Charge||this.charged.has(e.GenerationID))&&(this.charged.add(e.GenerationID),this.ctx.data.user.applyResourceOperation(e.Charge,this.ctx.data.config.itemDefinitions));}emitView(e){this.ctx.emitter.emit("ai:generationUpdated",e),e.Status===yn.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===yn.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Ya="Collection",tr=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let n=e.cache.configSection(Ya),s=Object.keys(n?.Collections??{});if(s.length===0||t)return false;let i=e.cache.configSection("Season");return Object.values(i?.Chains??{}).some(p=>(p?.Seasons??[]).some(m=>!!m?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let n=await this.getUserState();return n.ok&&(t=true),n}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ya,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.collection.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Ya,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,n=1,s){let i=this.ctx.auth.context;if(!i)return l;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:n,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${i.userID}_${V()}`},p=await this.ctx.api.collection.openPack(o);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,n=1){let s=this.ctx.auth.context;if(!s)return l;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:n,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${V()}`},o=await this.ctx.api.collection.openCollectionChest(i);return o.ok&&(this.ctx.data.user.applyResourcesWithDelta(o.data.Resources,o.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",o.data)),o}async useCollectibleJoker(e,t){let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${n.userID}_${V()}`},i=await this.ctx.api.collection.useCollectibleJoker(s);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",i.data)),i}async claimSetReward(e,t){let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${n.userID}_${V()}`},i=await this.ctx.api.collection.claimSetReward(s);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",i.data)),i}async claimSetRewardsBatch(e){if(!e||e.length===0)return h("client","sets is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},n=await this.ctx.api.collection.claimSetRewardsBatch(t);if(n.ok){let s=false;for(let i of n.data)!s&&i.Success&&i.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",n.data);}return n}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${V()}`},s=await this.ctx.api.collection.claimGrandPrize(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,n,s,i,o=false){let p=this.ctx.auth.context;if(!p)return l;let m={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:n,ReceiverUserID:s,RequestedCollectibleID:i,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${p.userID}_${s}_${V()}`},g=await this.ctx.api.collection.sendTradeOffer(m);return g.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",g.data)),g}async cancelTradeOffer(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${V()}`},n=await this.ctx.api.collection.cancelTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",n.data)),n}async acceptTradeOffer(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${V()}`},n=await this.ctx.api.collection.acceptTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",n.data)),n}async declineTradeOffer(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${V()}`},n=await this.ctx.api.collection.declineTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",n.data)),n}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return l;t.CollectionID=e;let n=await this.ctx.api.collection.getMyTradeOffers(t);return n.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",n.data),n}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return l;t.CollectionID=e;let n=await this.ctx.api.collection.getIncomingTradeOffers(t);return n.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",n.data),n}};var cb=zod.z.object({}).passthrough().transform(r=>r),pb={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},hb={Active:"Active",Left:"Left",Replaced:"Replaced"},db=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),mb=zod.z.object({UserID:zod.z.string().nullish(),PublicData:_e.nullish(),BuildObjectsProgress:db.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),fb=zod.z.object({Index:zod.z.number().nullish(),OwnerUserID:zod.z.string().nullish(),CurrentProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish(),IsCompleted:zod.z.boolean().nullish()}).passthrough(),gb=zod.z.object({Objects:zod.z.array(fb).nullish()}).passthrough(),nh=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CoopChainID:zod.z.string().nullish(),CoopEventID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),Members:zod.z.array(mb).nullish(),BuildObjectsState:gb.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),sh=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>ih).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),yb=zod.z.string(),Xa=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Weight:zod.z.number().nullish(),MinProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish()}).passthrough(),Rb=zod.z.object({Index:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxProgress:zod.z.number().nullish(),CompletionReward:$.nullish()}).passthrough(),Cb=zod.z.object({Objects:zod.z.array(Rb).nullish(),PriceOptions:me.nullish(),SpinnerTable:zod.z.array(Xa).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),ih=zod.z.object({CoopEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),EventType:yb.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:Cb.nullish(),GrandPrize:$.nullish()}).passthrough(),Sb=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Se.nullish(),Events:zod.z.array(ih).nullish(),Gate:te.nullish()}).passthrough(),nr=zod.z.object({ServerTimeUtc:u.nullish(),UserState:cb.nullish(),ActiveGroup:nh.nullish()}),el=zod.z.object({ServerTimeUtc:u.nullish(),Group:nh.nullish(),SecondsRemaining:Q.nullish()}),rh=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Resources:O.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:Xa.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(Xa).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:Q.nullish(),MaxProgress:Q.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),tl=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),oh=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),sr=zod.z.object({Chains:zod.z.record(zod.z.string(),Sb).nullish()}).passthrough(),wt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var ah="CoopEvent",lh={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},ir=class{constructor(e){this.ctx=e;e.cache.bindLoginView(lh,{schema:nr,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ah,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.coopEvent.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(ah,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return h("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.CoopChainID=e;let n=await this.ctx.api.coopEvent.getActiveEvent(t);return n.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",n.data),n}getUserState(e){return this.ctx.cache.read(lh,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return h("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.GroupID=e;let n=await this.ctx.api.coopEvent.getGroupState(t);return n.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",n.data),n}async joinOrCreateGroup(e){if(!e)return h("client","CoopChainID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},n=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(n.ok){let s=n.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",n.data);}return n}async spin(e,t,n=1,s,i){if(!e||!t)return h("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:n,SelectedOptionID:s,CreditsConfirmationID:i,RelatedEntityID:V()},p=await this.ctx.api.coopEvent.spin(o);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(p.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",p.data)),p}async claimObjectReward(e){if(!e)return h("client","GroupID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.claimObjectReward(t);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",n.data)),n}async claimGrandPrize(e){if(!e)return h("client","GroupID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.claimGrandPrize(t);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",n.data)),n}async leaveGroup(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.leaveGroup(t);return n.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",n.data)),n}};var bb={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},xb={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},Db=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:u.nullish(),CompletedAtUtc:u.nullish(),LastExecutedAtUtc:u.nullish(),NextAvailableAtUtc:u.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),Ib=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),uh=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:u.nullish(),ExhaustedAtUtc:u.nullish(),ExpiredAtUtc:u.nullish(),DismissedAtUtc:u.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:u.nullish(),Nodes:zod.z.record(zod.z.string(),Db).nullish(),Tracks:zod.z.record(zod.z.string(),Ib).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),Pb=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:u.nullish(),ActiveOfferExpiresAtUtc:u.nullish(),ActiveOffer:uh.nullish(),NextCycleStartsAtUtc:u.nullish(),LastUpdatedUtc:u.nullish(),DismissSkipAvailableAtUtc:u.nullish(),LastDismissedAtUtc:u.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),vb=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),Ab=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:u.nullish(),LastActivatedAtUtc:u.nullish(),LastExhaustedAtUtc:u.nullish(),NodeCounts:zod.z.record(zod.z.string(),vb).nullish()}).passthrough(),Tb=zod.z.object({Slots:zod.z.record(zod.z.string(),Pb).nullish(),OfferHistory:zod.z.record(zod.z.string(),Ab).nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),wb={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},kb={Eq:"Eq",Gte:"Gte",Lte:"Lte"},zb=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),rr=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ch=zod.z.object({Schedule:Se.nullish(),Gate:te.nullish()}).passthrough(),ph=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),Mb=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Behaviour:J.nullish()}).passthrough(),Ob=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:rr.nullish(),Availability:ch.nullish(),Behaviour:ph.nullish(),Queue:zod.z.array(zb).nullish(),Presets:Mb.nullish()}).passthrough(),Eb=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),qb=zod.z.object({RewardedVideo:Eb.nullish()}).passthrough(),Ub=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),Lb=zod.z.object({Identity:J.nullish(),Graph:J.nullish(),Milestones:J.nullish()}).passthrough(),Bb=zod.z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish()}).passthrough(),Gb=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),Nb=zod.z.object({TrackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),StartValue:zod.z.number().nullish(),MinValue:zod.z.number().nullish(),MaxValue:zod.z.number().nullish(),ClampToMin:zod.z.boolean().nullish(),ClampToMax:zod.z.boolean().nullish(),HiddenFromUI:zod.z.boolean().nullish()}).passthrough(),_b=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(Ub).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),hh=zod.z.object({Options:me.nullish()}).passthrough(),dh=zod.z.object({Grants:$.nullish(),TrackChanges:zod.z.array(Gb).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),Vb=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:rr.nullish(),Pricing:hh.nullish(),Reward:dh.nullish(),Action:qb.nullish(),UnlockRules:_b.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:ve.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:Bb.nullish()}).passthrough(),mh=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(Vb).nullish(),Tracks:zod.z.array(Nb).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),fh=zod.z.object({Milestones:zod.z.record(zod.z.string(),je).nullish(),ClaimMode:zod.z.string().nullish(),Token:Mt.nullish()}).passthrough(),gh=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:rr.nullish(),Graph:mh.nullish(),Milestones:fh.nullish(),Presets:Lb.nullish()}).passthrough(),Fb=zod.z.object({Identity:zod.z.record(zod.z.string(),rr).nullish(),Availability:zod.z.record(zod.z.string(),ch).nullish(),Behaviour:zod.z.record(zod.z.string(),ph).nullish(),Graph:zod.z.record(zod.z.string(),mh).nullish(),Milestones:zod.z.record(zod.z.string(),fh).nullish(),Pricing:zod.z.record(zod.z.string(),hh).nullish(),Reward:zod.z.record(zod.z.string(),dh).nullish()}).passthrough(),nl=zod.z.object({Slots:zod.z.record(zod.z.string(),Ob).nullish(),Offers:zod.z.record(zod.z.string(),gh).nullish(),Presets:Fb.nullish()}).passthrough(),yh=zod.z.object({DealOfferDefinitions:nl.nullish()}),Rh=zod.z.object({DealOffers:Tb.nullish()}),jb=zod.z.object({EntityID:zod.z.string().nullish(),TotalEarned:zod.z.number().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),ReachedUnclaimedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Wb=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:gh.nullish(),ActivationState:uh.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:u.nullish(),Cost:Nt.nullish(),Milestone:jb.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),or=zod.z.object({Slots:zod.z.array(Wb).nullish()}),Ch=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Sh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),bh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),xh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Dh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:O.nullish(),Inventory:K.nullish()}),qt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var Hb="DealOffer",Ih={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},ar=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ih,{schema:or,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(Hb,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(Ih,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return h("client","SlotID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${V()}`},n=await this.ctx.api.dealOffer.dismissDeal(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",n.data)),n}async executeNode(e,t,n,s){if(!e||!t)return h("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return l;let i=n&&n.trim().length>0?n.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:i??`deal_exec_${e}_${t}_${V()}`},p=await this.ctx.api.dealOffer.executeNode(o);return p.ok&&!p.data.CreditsConfirmation&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return h("client","SlotID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${V()}`},n=await this.ctx.api.dealOffer.recordShow(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",n.data)),n}async claimMilestone(e,t){if(!e||!t)return h("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${V()}`},s=await this.ctx.api.dealOffer.claimMilestone(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return h("client","SlotID is required.");if(!this.ctx.auth.context)return l;let n=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:n,RelatedEntityID:`deal_milestone_batch_${e}_${V()}`},i=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",i.data)),i}};var Ph="Referral",lr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ph,e);if(t){let i={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",i),G(i)}let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.referral.getDefinitions(n);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Ph,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=fn.parseReferralCode(e)?.toUpperCase();if(!t)return h("client","ReferralCode is required.");let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${n.userID}`},i=await this.ctx.api.referral.activateReferralCode(s);if(i.ok){let o=i.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID,o.QualificationPending),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return i}async claimInviteReward(e){let t=e.trim();if(!t)return h("client","InviteRewardID is required.");let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${n.userID}`},i=await this.ctx.api.referral.claimInviteReward(s);if(i.ok){let o=i.data;o.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(o.RewardID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",o);}return i}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return h("client","InviteRewardIDs is required.");let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${n.userID}`},i=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(i.ok){let o=i.data;for(let p of o.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return i}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.referral.checkQualification(e);return t.ok&&t.data.Qualification&&!t.data.QualificationPending&&await this.getUserState(),t}async checkQualificationIfPending(){this.ctx.data.user.state?.Referral?.QualificationPending===true&&await this.checkQualification();}};var vh=zod.z.object({ServerTimeUtc:u,SourceType:kn,SourceID:zod.z.string(),TargetType:kn,TargetID:zod.z.string(),SourceSpent:Q,FeeAmount:Q,RateApplied:se,TargetCredited:Q}),Ah=zod.z.object({ServerTimeUtc:u,SourceType:kn,SourceID:zod.z.string(),TargetType:kn,TargetID:zod.z.string(),SourceSpent:se,FeeAmount:se,RateApplied:se,TargetCredited:se}),Th=zod.z.object({ServerTimeUtc:u,SpendID:zod.z.string(),Resources:O.nullish()}),hs={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},Kb={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},wh=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),Qb={Automatic:"Automatic",Manual:"Manual"},$b=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),Jb=zod.z.object({ValueInUSD:se.nullish(),ValueInUSDUpdatedAt:u.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),Zb=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),Yb=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),Xb=zod.z.object({TargetCurrencyType:kn.nullish(),TargetCurrencyID:zod.z.string(),Rate:se.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),kh=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:$b.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(Xb).nullish()}).passthrough(),zh=zod.z.object({CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough(),ex=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:Jb.nullish(),Recharge:Zb.nullish(),Conversion:kh.nullish(),Permissions:Yb.nullish(),Audit:zh.nullish(),Status:wh.nullish()}).passthrough(),tx=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:se.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),nx=zod.z.object({DailyWithdrawUsd:se.nullish(),MonthlyWithdrawUsd:se.nullish(),KycRequiredAboveUsd:se.nullish()}).passthrough(),sx=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),ix=zod.z.object({Mode:zod.z.string().nullish(),FundingNetworkID:zod.z.string().nullish(),PerPlayerDailyTokens:zod.z.number().nullish(),TitleDailyTokens:zod.z.number().nullish(),RefuseOverCap:zod.z.boolean().nullish()}).passthrough(),sl=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),DisplayDecimals:zod.z.number().nullish(),ValueInUSD:se.nullish(),ValueInUSDUpdatedAt:u.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:se.nullish(),CommunityMarketingWithdrawalFeePercent:se.nullish(),WithdrawalBurnPercent:se.nullish(),PlayerTradeFeePercent:se.nullish(),TradeShareCommunityMarketingPercent:se.nullish(),Networks:zod.z.array(tx).nullish(),Limits:nx.nullish(),Permissions:sx.nullish(),Conversion:kh.nullish(),Audit:zh.nullish(),Status:wh.nullish(),ServerGrantPolicy:ix.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),rx=zod.z.object({SpendID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),PriceOptions:zod.z.record(zod.z.string(),hi).nullish()}).passthrough(),ur=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),ex).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),sl).nullish(),Spends:zod.z.record(zod.z.string(),rx).nullish()}).passthrough(),ox={Marketplace:"Marketplace",MailboxTransfer:"MailboxTransfer",Match:"Match",Workshop:"Workshop"},ax={Pending:"Pending",Released:"Released",Voided:"Voided"},Ct=zod.z.object({PayoutID:zod.z.string().nullish(),Source:zod.z.string().nullish(),SourceRefID:zod.z.string().nullish(),Status:zod.z.enum(["Pending","Released","Voided"]).catch("Pending").nullish(),Amount:he.nullish(),CreatedAt:u.nullish(),ReleaseAt:u.nullish(),ReturnedGoods:he.nullish(),GoodsReturned:zod.z.boolean().nullish()}).passthrough(),Mh=zod.z.object({Pending:zod.z.array(Ct).nullish(),Released:zod.z.array(Ct).nullish(),Voided:zod.z.array(Ct).nullish()}).passthrough();var lx={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Oh=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),ux={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},cx=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),px={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},hx=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),ht={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},dx={Disabled:"MAILBOX_DISABLED",MessageNotFound:"MESSAGE_NOT_FOUND",MessageIDRequired:"MESSAGE_ID_REQUIRED",AlreadyClaimed:"ALREADY_CLAIMED",Expired:"EXPIRED",NoRewards:"NO_REWARDS",HasUnclaimedRewards:"HAS_UNCLAIMED_REWARDS",NotFriends:"NOT_FRIENDS",Blocked:"BLOCKED",RecipientNotFound:"RECIPIENT_NOT_FOUND",CannotGiftSelf:"CANNOT_GIFT_SELF",GiftNotFound:"GIFT_NOT_FOUND",GiftNotAllowed:"GIFT_NOT_ALLOWED",AlreadySent:"ALREADY_SENT",SendLimit:"SEND_LIMIT",NotEnoughResources:"NOT_ENOUGH_RESOURCES",AmountTooSmall:"AMOUNT_TOO_SMALL",RecipientLimit:"RECIPIENT_LIMIT",TransferDisabled:"TRANSFER_DISABLED",ResourceNotGiftable:"RESOURCE_NOT_GIFTABLE",AmountTooLarge:"AMOUNT_TOO_LARGE",AmountInvalid:"AMOUNT_INVALID",TooManyEntries:"TOO_MANY_ENTRIES",EntriesRequired:"ENTRIES_REQUIRED",FriendshipTooNew:"FRIENDSHIP_TOO_NEW",RequestIDRequired:"RELATED_ENTITY_ID_REQUIRED",CryptoForbidden:"CRYPTO_FORBIDDEN",ModuleRewardUnavailable:"MODULE_REWARD_UNAVAILABLE",Conflict:"CONFLICT"},mx=100,fx=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),Eh=zod.z.object({FeatureID:zod.z.string().nullish(),Args:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Url:zod.z.string().nullish(),Label:zod.z.string().nullish()}).passthrough(),gx=zod.z.object({Texts:zod.z.record(zod.z.string(),fx).nullish(),Category:Oh.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:Eh.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),yx=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:he.nullish(),Cost:he.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),SenderGate:te.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),Rx=zod.z.object({Type:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxAmountPerGift:zod.z.number().nullish()}).passthrough(),Cx=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(Rx).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),AllowItemInstances:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:he.nullish(),SenderGate:te.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),qh=zod.z.object({Enabled:zod.z.boolean().nullish(),Capacity:zod.z.number().nullish(),RewardLetterDays:zod.z.number().nullish(),PlainLetterDays:zod.z.number().nullish(),ClaimedRetentionDays:zod.z.number().nullish(),DefaultLanguage:zod.z.string().nullish(),Templates:zod.z.record(zod.z.string(),gx).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),yx).nullish(),Transfer:Cx.nullish()}).passthrough().nullish(),Integrations:zod.z.object({Leaderboard:zod.z.boolean().nullish(),CoopEvent:zod.z.boolean().nullish(),Season:zod.z.boolean().nullish(),Referral:zod.z.boolean().nullish()}).passthrough().nullish()}).passthrough(),Sx=zod.z.object({MessageID:zod.z.string(),Source:cx,Category:Oh,TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:Eh.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:$.nullish(),Instances:zod.z.array(En).nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:u,ExpiresAt:u.nullish(),ReadAt:u.nullish(),ClaimedAt:u.nullish()}).passthrough(),bx=zod.z.object({MessageID:zod.z.string(),Module:hx,Key:zod.z.string(),TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:$.nullish()}).passthrough(),il=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),Uh=zod.z.object({ServerTimeUtc:u.nullish(),Messages:zod.z.array(Sx).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(bx).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),cr=zod.z.object({ServerTimeUtc:u.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),rl=zod.z.object({ServerTimeUtc:u.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(il).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),xx=zod.z.object({MessageID:zod.z.string(),Rewards:he.nullish(),Instances:zod.z.array(En).nullish(),HeldPayout:Ct.nullish()}).passthrough(),pr=zod.z.object({ServerTimeUtc:u.nullish(),Claimed:zod.z.array(xx).default([]),Failed:zod.z.array(il).default([]),Resources:O.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Lh=zod.z.object({ServerTimeUtc:u.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(il).default([]),Resources:O.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough(),Bh=zod.z.object({ServerTimeUtc:u.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish(),RecipientReceives:he.nullish(),RecipientInstances:zod.z.array(En).nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),Gh=zod.z.object({ServerTimeUtc:u.nullish(),ResetsAt:u.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:u.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough().nullish()}).passthrough();var ol="Mailbox",al={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},hr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(al,{schema:cr,apply:t=>this.emitCounters(t)});}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}emitCounters(e){if(e.UnreadCount==null||e.UnclaimedCount==null)return;let t={UnreadCount:e.UnreadCount,UnclaimedCount:e.UnclaimedCount};this.ctx.cache.put(al,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(ol)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(ol,e);if(t)return G(t);let n=this.request();if(!n)return l;let s=await this.ctx.api.mailbox.getDefinitions(n);return s.ok&&this.ctx.data.config.patchSection(ol,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return l;let n=await this.ctx.api.mailbox.getMessages(t);return n.ok&&(this.emitCounters(n.data),this.ctx.emitter.emit("mailbox:messagesLoaded",n.data)),n}getUnreadCount(e){return this.ctx.cache.read(al,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return l;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return l;let n=await this.ctx.api.mailbox.readMessages(t);return n.ok&&this.emitCounters(n.data),n}async claimReward(e){let t=e?.trim();if(!t)return h("client","MessageID is required.");let n=this.request({MessageID:t});return n?this.afterClaim(await this.ctx.api.mailbox.claimReward(n)):l}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return h("client","MessageIDs are required.");let n=this.request({MessageIDs:t});return n?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(n)):l}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):l}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let n=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!n)return l;let s=await this.ctx.api.mailbox.deleteMessages(n);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return h("client","GiftID is required.");let n=(t??[]).filter(Boolean);if(n.length===0)return h("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:n});if(!s)return l;let i=await this.ctx.api.mailbox.sendGift(s);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",i.data)),i}async sendTransfer(e,t,n){if(!e?.trim())return h("client","RecipientUserID is required.");if(!n?.requestID?.trim())return h("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,TransferInstanceIDs:n.instanceIDs?.length?n.instanceIDs:void 0,Note:n.note,RelatedEntityID:n.requestID.trim()});if(!s)return l;let i=await this.ctx.api.mailbox.sendTransfer(s);return i.ok&&(i.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(i.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",i.data)),i}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):l}};var Dx={Head:"Head",Torso:"Torso",Legs:"Legs"},dr=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),Ix={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},ll=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),_h=zod.z.object({AttackTarget:dr,DefenseTarget:dr});var Px=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),vx=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:dr.nullish(),DefenseZone:dr.nullish(),HitType:Px.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),Ax=zod.z.object({MaxHp:zod.z.number().nullish(),CurrentHp:zod.z.number().nullish(),Damage:zod.z.number().nullish(),AttackSpeed:zod.z.number().nullish(),CritChance:zod.z.number().nullish(),CritMultiplier:zod.z.number().nullish(),Armor:zod.z.number().nullish(),DodgeChance:zod.z.number().nullish()}).passthrough(),Tx=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Nh=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:cs.nullish(),BattleStrategy:zod.z.array(_h).nullish(),UnstackableItems:zod.z.record(zod.z.string(),Tx).nullish(),Stats:Ax.nullish()}).passthrough(),ds=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:he.nullish(),NetReward:he.nullish(),BattleLog:zod.z.array(vx).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:Nh.nullish(),P2BattleProfile:Nh.nullish()}).passthrough(),Vh=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:u.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(_h).nullish(),TargetUserID:zod.z.string().nullish(),Entry:he.nullish(),CreationCostPaid:he.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:u.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:u.nullish(),Status:ll.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:u.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:u.nullish()}).passthrough(),Fh=zod.z.object({Status:ll,MatchID:zod.z.string(),Entry:he.nullish(),Resources:O.nullish()}),jh=zod.z.object({Match:Vh.nullish()}),Wh=zod.z.object({MatchID:zod.z.string(),Status:ll,Resources:O.nullish()}),Hh=zod.z.object({Battle:ds.nullish(),Resources:O.nullish(),ResourcesDual:_t.nullish(),HeldPayout:Ct.nullish()}),ul=zod.z.object({Matches:zod.z.array(Vh).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),Ut={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var wx=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var kx=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),zx=zod.z.object({HealthStatID:zod.z.string().nullish(),DamageStatID:zod.z.string().nullish(),ArmorStatID:zod.z.string().nullish(),AttackSpeedStatID:zod.z.string().nullish(),CritChanceStatID:zod.z.string().nullish(),CritDamageStatID:zod.z.string().nullish(),DodgeStatID:zod.z.string().nullish(),AllMightStatID:zod.z.string().nullish()}).passthrough(),Mx=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),Ox=zod.z.object({MaxRounds:zod.z.number().nullish(),BlockDamageMultiplier:zod.z.number().nullish(),MinHitDamage:zod.z.number().nullish(),DefaultCritMultiplier:zod.z.number().nullish(),MaxCritChance:zod.z.number().nullish(),MaxDodgeChance:zod.z.number().nullish(),ArmorMode:Mx.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),Ex=zod.z.object({Kind:kx.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Ze.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),qx=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(Ex).nullish()}).passthrough(),Rn=zod.z.object({Terms:zod.z.array(qx).nullish()}).passthrough(),Ux=zod.z.object({Health:Rn.nullish(),Damage:Rn.nullish(),Armor:Rn.nullish(),AttackSpeed:Rn.nullish(),CritChance:Rn.nullish(),CritDamage:Rn.nullish(),Dodge:Rn.nullish()}).passthrough(),Kh=zod.z.object({StatMapping:zx.nullish(),Combat:Ox.nullish(),Formula:Ux.nullish()}).passthrough(),Lx=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),ms=zod.z.object({Kind:wx.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:Os.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),Qh=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(ms).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),$h=zod.z.object({PriceOptions:me.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:ve.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),Bx=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:Lx.nullish(),Entry:Qh.nullish(),Creation:$h.nullish(),Settings:Kh.nullish()}).passthrough(),Gx=zod.z.object({Rules:zod.z.record(zod.z.string(),Bx).nullish(),Defaults:Kh.nullish(),EntryDefaults:Qh.nullish(),CreationDefaults:$h.nullish()}).passthrough(),cl=zod.z.object({InstantBattle:Gx.nullish()}).passthrough(),Jh=cl;var Nx={Open:"Open",Request:"Request",InviteOnly:"InviteOnly"},_x=zod.z.enum(["Open","Request","InviteOnly"]).catch("Open"),Vx={Application:"Application",Invite:"Invite"},Fx={Invite:"invite",ManageApplications:"manage_applications",Kick:"kick",SetRole:"set_role",EditInfo:"edit_info",EditAnnouncement:"edit_announcement",ModerateChat:"moderate_chat",CreateRequest:"create_request",SpendTreasury:"spend_treasury",ManageProjects:"manage_projects",StartActivity:"start_activity",SelectQuests:"select_quests"},Be={GetDefinitions:"GetDefinitions",GetMyClans:"GetMyClans",SearchClans:"SearchClans",GetRecommendedClans:"GetRecommendedClans",GetClan:"GetClan",GetClanMembers:"GetClanMembers",GetRankings:"GetRankings",CreateClan:"CreateClan",UpdateClan:"UpdateClan",DisbandClan:"DisbandClan",JoinClan:"JoinClan",ApplyToClan:"ApplyToClan",CancelApplication:"CancelApplication",GetApplications:"GetApplications",AcceptApplication:"AcceptApplication",RejectApplication:"RejectApplication",InvitePlayer:"InvitePlayer",GetMyInvites:"GetMyInvites",AcceptInvite:"AcceptInvite",DeclineInvite:"DeclineInvite",LeaveClan:"LeaveClan",KickMember:"KickMember",SetMemberRole:"SetMemberRole",TransferLeadership:"TransferLeadership",GetClanLog:"GetClanLog",CreateRequest:"CreateRequest",Donate:"Donate",Help:"Help",ClaimRequest:"ClaimRequest",GetRequests:"GetRequests",GetGifts:"GetGifts",ClaimGift:"ClaimGift",ClaimAllGifts:"ClaimAllGifts",GetRewards:"GetRewards",ClaimRewards:"ClaimRewards",GetTreasury:"GetTreasury",DepositToTreasury:"DepositToTreasury",BuyTreasuryPurchase:"BuyTreasuryPurchase",GetProjects:"GetProjects",ContributeToProject:"ContributeToProject",SetRecommendedProject:"SetRecommendedProject",GetActivities:"GetActivities",StartActivity:"StartActivity",SubmitActivityScore:"SubmitActivityScore",ClaimActivityRewards:"ClaimActivityRewards",GetClanQuests:"GetClanQuests",SelectClanQuests:"SelectClanQuests",TakeClanQuest:"TakeClanQuest",AbandonClanQuest:"AbandonClanQuest",ClaimClanQuestRewards:"ClaimClanQuestRewards",GetCompetitions:"GetCompetitions",RegisterForCompetition:"RegisterForCompetition",GetBracket:"GetBracket",ClaimCompetitionRewards:"ClaimCompetitionRewards",StartWarAttack:"StartWarAttack",GetDiplomacy:"GetDiplomacy",SetDiplomacy:"SetDiplomacy",GetRevenges:"GetRevenges",TakeRevenge:"TakeRevenge",GetLeague:"GetLeague",ClaimSeasonReward:"ClaimSeasonReward"},jx={Disabled:"CLAN_DISABLED",UnknownKind:"CLAN_UNKNOWN_KIND",KindRequired:"CLAN_KIND_REQUIRED",NotFound:"CLAN_NOT_FOUND",NotMember:"CLAN_NOT_MEMBER",AlreadyInClan:"CLAN_ALREADY_IN_CLAN",Full:"CLAN_FULL",NoPermission:"CLAN_NO_PERMISSION",RankTooLow:"CLAN_RANK_TOO_LOW",RoleFull:"CLAN_ROLE_FULL",UnknownRole:"CLAN_UNKNOWN_ROLE",NameTaken:"CLAN_NAME_TAKEN",TagTaken:"CLAN_TAG_TAKEN",NameInvalid:"CLAN_NAME_INVALID",TagInvalid:"CLAN_TAG_INVALID",TextInvalid:"CLAN_TEXT_INVALID",TextBlocked:"CLAN_TEXT_BLOCKED",GateFailed:"CLAN_GATE_FAILED",RequirementsNotMet:"CLAN_REQUIREMENTS_NOT_MET",JoinModeMismatch:"CLAN_JOIN_MODE_MISMATCH",JoinCooldown:"CLAN_JOIN_COOLDOWN",RejoinCooldown:"CLAN_REJOIN_COOLDOWN",TooManyApplications:"CLAN_TOO_MANY_APPLICATIONS",ApplicationNotFound:"CLAN_APPLICATION_NOT_FOUND",InviteNotFound:"CLAN_INVITE_NOT_FOUND",PlayerNotFound:"CLAN_PLAYER_NOT_FOUND",LeaderMustTransfer:"CLAN_LEADER_MUST_TRANSFER",CannotTargetSelf:"CLAN_CANNOT_TARGET_SELF",KickLimit:"CLAN_KICK_LIMIT",RenameCooldown:"CLAN_RENAME_COOLDOWN",InvalidArgument:"CLAN_INVALID_ARGUMENT",FeatureDisabled:"CLAN_FEATURE_DISABLED",RequestNotFound:"CLAN_REQUEST_NOT_FOUND",RequestClosed:"CLAN_REQUEST_CLOSED",RequestCooldown:"CLAN_REQUEST_COOLDOWN",RequestLimit:"CLAN_REQUEST_LIMIT",RequestFilled:"CLAN_REQUEST_FILLED",DonateLimit:"CLAN_DONATE_LIMIT",AlreadyHelped:"CLAN_ALREADY_HELPED",NothingToClaim:"CLAN_NOTHING_TO_CLAIM",GiftNotFound:"CLAN_GIFT_NOT_FOUND",TenureRequired:"CLAN_TENURE_REQUIRED",Conflict:"CLAN_CONFLICT",SystemCapReached:"CLAN_SYSTEM_CAP_REACHED",ItemNotAllowed:"CLAN_ITEM_NOT_ALLOWED",ItemLevelTooHigh:"CLAN_ITEM_LEVEL_TOO_HIGH",ItemEquipped:"CLAN_ITEM_EQUIPPED",ItemWrongLevel:"CLAN_ITEM_WRONG_LEVEL",NotEnoughTreasury:"CLAN_NOT_ENOUGH_TREASURY",DepositLimit:"CLAN_DEPOSIT_LIMIT",PurchaseNotFound:"CLAN_PURCHASE_NOT_FOUND",BuffActive:"CLAN_BUFF_ACTIVE",LevelTooLow:"CLAN_LEVEL_TOO_LOW",ProjectNotFound:"CLAN_PROJECT_NOT_FOUND",ProjectLocked:"CLAN_PROJECT_LOCKED",ProjectMaxed:"CLAN_PROJECT_MAXED",ContributeLimit:"CLAN_CONTRIBUTE_LIMIT",ActivityNotFound:"CLAN_ACTIVITY_NOT_FOUND",ActivityNotActive:"CLAN_ACTIVITY_NOT_ACTIVE",ActivityRunning:"CLAN_ACTIVITY_RUNNING",ActivityCooldown:"CLAN_ACTIVITY_COOLDOWN",NoAttempts:"CLAN_NO_ATTEMPTS",ScoreRejected:"CLAN_SCORE_REJECTED",BossDefeated:"CLAN_BOSS_DEFEATED",BoardNotFound:"CLAN_BOARD_NOT_FOUND",QuestNotFound:"CLAN_QUEST_NOT_FOUND",QuestFull:"CLAN_QUEST_FULL",TakeLimit:"CLAN_TAKE_LIMIT",QuestNotTaken:"CLAN_QUEST_NOT_TAKEN",QuestDone:"CLAN_QUEST_DONE",AbandonCooldown:"CLAN_ABANDON_COOLDOWN",SelectionLocked:"CLAN_SELECTION_LOCKED",ClaimAfterEnd:"CLAN_CLAIM_AFTER_END",NotEligible:"CLAN_NOT_ELIGIBLE",ClaimExpired:"CLAN_CLAIM_EXPIRED",CompetitionNotFound:"CLAN_COMPETITION_NOT_FOUND",CompetitionNotActive:"CLAN_COMPETITION_NOT_ACTIVE",RegistrationClosed:"CLAN_REGISTRATION_CLOSED",NotRegistered:"CLAN_NOT_REGISTERED",TooFewMembers:"CLAN_TOO_FEW_MEMBERS",WarPreparation:"CLAN_WAR_PREPARATION",NotInRoster:"CLAN_NOT_IN_ROSTER",TargetInvalid:"CLAN_TARGET_INVALID",AttackPending:"CLAN_ATTACK_PENDING",AttackNotFound:"CLAN_ATTACK_NOT_FOUND",AttackExpired:"CLAN_ATTACK_EXPIRED",RelationExists:"CLAN_RELATION_EXISTS",RelationLimit:"CLAN_RELATION_LIMIT",RelationNotFound:"CLAN_RELATION_NOT_FOUND",RelationDisabled:"CLAN_RELATION_DISABLED"},Wx={Duel:"Duel",Battle:"Battle",League:"League",War:"War"},Hx={Ally:"Ally",Pact:"Pact",Enemy:"Enemy",None:"None"},mr="clan",Cn=zod.z.array(zod.z.string()).nullish(),Y=zod.z.number().nullish(),Kx=zod.z.record(zod.z.string(),zod.z.number()).nullish(),Qx=zod.z.object({NounKey:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SortOrder:Y}).passthrough(),$x=zod.z.object({NameMinLength:Y,NameMaxLength:Y,TagRequired:zod.z.boolean().nullish(),TagMinLength:Y,TagMaxLength:Y,DescriptionMaxLength:Y,AnnouncementMaxLength:Y,Emblem:zod.z.object({Backgrounds:Cn,Symbols:Cn,Colors:Cn}).passthrough().nullish(),Languages:Cn,Attributes:zod.z.record(zod.z.string(),zod.z.object({NameKey:zod.z.string().nullish(),Values:Cn,Required:zod.z.boolean().nullish()}).passthrough()).nullish(),RenameCooldownHours:Y}).passthrough(),Jx=zod.z.object({BaseCapacity:Y,JoinModes:zod.z.array(zod.z.string()).nullish(),DefaultJoinMode:zod.z.string().nullish(),ApplicationHours:Y,InviteHours:Y,JoinCooldownHours:Y,TenureHoursForRewards:Y,NoBoardAttacksOnClanmates:zod.z.boolean().nullish(),SuggestJoinAfterHours:Y,KickInactiveDays:Y}).passthrough(),Zx=zod.z.object({Rank:zod.z.number().catch(0),NameKey:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),MaxCount:Y,Permissions:Cn}).passthrough(),Yx=zod.z.object({Enabled:zod.z.boolean().nullish(),Type:zod.z.string().catch("Resource"),NameKey:zod.z.string().nullish(),CooldownMinutes:Y,LifetimeHours:Y,MaxOpenPerMember:Y,Resources:zod.z.array(zt.passthrough()).nullish(),Funding:zod.z.string().nullish(),MaxPerDonor:Y,MaxHelps:Y,MaxItemLevel:Y,MinMembershipHoursToDonate:Y}).passthrough(),Xx=zod.z.object({Enabled:zod.z.boolean().nullish(),Identity:Qx.nullish(),Create:$x.nullish(),Membership:Jx.nullish(),Roles:zod.z.object({Roles:zod.z.record(zod.z.string(),Zx).nullish(),LeaderRoleID:zod.z.string().nullish(),DefaultRoleID:zod.z.string().nullish()}).passthrough().nullish(),Rankings:zod.z.object({Metrics:Cn,ByLanguage:zod.z.boolean().nullish(),ByRegion:zod.z.boolean().nullish()}).passthrough().nullish(),Counters:zod.z.record(zod.z.string(),zod.z.object({}).passthrough()).nullish(),Progression:zod.z.object({}).passthrough().nullish(),Requests:zod.z.record(zod.z.string(),Yx).nullish(),Gifts:zod.z.object({Gifts:zod.z.record(zod.z.string(),zod.z.object({}).passthrough()).nullish(),ShowSender:zod.z.boolean().nullish()}).passthrough().nullish(),Treasury:zod.z.object({Currencies:zod.z.record(zod.z.string(),zod.z.object({NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),Deposits:zod.z.array(zod.z.object({Resource:zt.passthrough().nullish(),Gives:zod.z.number().catch(1)}).passthrough()).nullish(),DailyDepositCapPerMember:Y,Max:Y}).passthrough()).nullish(),Purchases:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),Cost:Kx,DurationHours:zod.z.number().catch(24),MinClanLevel:Y}).passthrough()).nullish()}).passthrough().nullish(),Projects:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SortOrder:Y,Inputs:zod.z.array(zod.z.object({Resource:zt.passthrough().nullish(),TreasuryCurrencyID:zod.z.string().nullish(),PointsPerUnit:Y}).passthrough()).nullish()}).passthrough()).nullish(),Activities:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),Type:zod.z.string().catch("Goal"),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish()}).passthrough()).nullish(),Quests:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),Mode:zod.z.string().catch("Shared"),NameKey:zod.z.string().nullish()}).passthrough()).nullish(),Competitions:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),Type:zod.z.string().catch("Battle"),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),Registration:zod.z.string().nullish(),MinMembers:Y,BracketSize:Y,Phases:zod.z.array(zod.z.object({DurationHours:zod.z.number().catch(24),NameKey:zod.z.string().nullish()}).passthrough()).nullish(),War:zod.z.object({AttacksPerMember:Y,MaxStars:Y,RosterSize:Y,PreparationHours:Y,ResultSource:zod.z.string().nullish()}).passthrough().nullish()}).passthrough()).nullish(),Leagues:zod.z.object({StartRating:Y,Tiers:zod.z.array(zod.z.object({LeagueID:zod.z.string(),MinRating:zod.z.number().catch(0),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SeasonReward:$.nullish()}).passthrough()).nullish(),Season:zod.z.object({IntervalSeconds:Y,AnchorUtc:zod.z.string().nullish(),KeepPercent:Y}).passthrough().nullish()}).passthrough().nullish(),Revenge:zod.z.object({Enabled:zod.z.boolean().nullish(),WindowHours:Y,MaxPerMemberPerDay:Y}).passthrough().nullish(),ChatNotices:zod.z.object({Enabled:zod.z.boolean().nullish(),Events:zod.z.array(zod.z.string()).nullish()}).passthrough().nullish(),Diplomacy:zod.z.object({MaxAllies:Y,MaxPacts:Y,MaxEnemies:Y,ProposalHours:Y}).passthrough().nullish()}).passthrough(),eD=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Kinds:zod.z.record(zod.z.string(),Xx).nullish(),RefreshSeconds:Y}).passthrough(),hl=zod.z.record(zod.z.string(),zod.z.string()).nullish(),pl=zod.z.record(zod.z.string(),zod.z.number()).nullish(),nn=zod.z.object({ClanID:zod.z.string(),KindID:zod.z.string().catch(mr),Name:zod.z.string().catch(""),Tag:zod.z.string().nullish(),Description:zod.z.string().nullish(),Announcement:zod.z.string().nullish(),Emblem:zod.z.object({Background:zod.z.string().nullish(),Symbol:zod.z.string().nullish(),Color:zod.z.string().nullish()}).passthrough().nullish(),Language:zod.z.string().nullish(),Country:zod.z.string().nullish(),Attributes:hl,JoinMode:_x,MinPower:Y,MinLevel:Y,LeaderUserID:zod.z.string().nullish(),MemberCount:zod.z.number().catch(0),Capacity:zod.z.number().catch(0),Level:zod.z.number().catch(1),Xp:zod.z.number().catch(0),NextLevelXp:Y,GiftPoints:zod.z.number().catch(0),GiftLevel:zod.z.number().catch(0),Power:zod.z.number().catch(0),Trophies:zod.z.number().catch(0),Counters:pl,Perks:pl,Modifiers:zod.z.array(zod.z.object({}).passthrough()).nullish(),Treasury:pl,RecommendedProjectID:zod.z.string().nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),CreatedAt:u.nullish(),ActiveAt:u.nullish()}).passthrough(),dl=zod.z.object({RoleID:zod.z.string().catch(""),JoinedAt:u.nullish(),Permissions:zod.z.array(zod.z.string()).catch([]),IsLeader:zod.z.boolean().catch(false),ContributionTotal:zod.z.number().catch(0),ContributionToday:zod.z.number().catch(0),ContributionWeek:zod.z.number().catch(0),DonatedTotal:zod.z.number().catch(0),RewardsFrom:u.nullish()}).passthrough(),tD=zod.z.object({KindID:zod.z.string(),Clan:nn.nullish(),Membership:dl.nullish(),JoinAllowedAt:u.nullish(),InvitesCount:zod.z.number().catch(0),MyApplicationsCount:zod.z.number().catch(0),ClaimableRewards:zod.z.number().catch(0),ClaimableGifts:zod.z.number().catch(0),ClaimableCompetitions:zod.z.number().catch(0),SuggestJoin:zod.z.boolean().catch(false)}).passthrough(),Yh=zod.z.object({ServerTimeUtc:u.nullish(),RefreshSeconds:zod.z.number().catch(30),Kinds:zod.z.array(tD).catch([])}).passthrough(),ml=zod.z.object({ServerTimeUtc:u.nullish(),Clans:zod.z.array(nn).catch([]),NextCursor:zod.z.string().nullish()}).passthrough(),Xh=zod.z.object({ServerTimeUtc:u.nullish(),Clan:nn,Membership:dl.nullish(),Applied:zod.z.boolean().catch(false)}).passthrough(),ed=zod.z.object({UserID:zod.z.string(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),PlayerLevel:zod.z.number().catch(0),RoleID:zod.z.string().catch(""),JoinedAt:u.nullish(),ActiveAt:u.nullish(),Power:zod.z.number().catch(0),Trophies:zod.z.number().catch(0),ContributionTotal:zod.z.number().catch(0),ContributionWeek:zod.z.number().catch(0),ContributionToday:zod.z.number().catch(0),DonatedTotal:zod.z.number().catch(0)}).passthrough(),td=zod.z.object({ServerTimeUtc:u.nullish(),ClanID:zod.z.string().nullish(),Members:zod.z.array(ed).catch([])}).passthrough(),Zh=zod.z.object({Rank:zod.z.number().catch(0),Value:zod.z.number().catch(0),Clan:nn}).passthrough(),nd=zod.z.object({ServerTimeUtc:u.nullish(),Metric:zod.z.string().nullish(),Slice:zod.z.string().nullish(),Rows:zod.z.array(Zh).catch([]),Mine:Zh.nullish()}).passthrough(),nD=zod.z.object({ID:zod.z.string(),Type:zod.z.string().catch("Application"),KindID:zod.z.string().nullish(),ClanID:zod.z.string().nullish(),Clan:nn.nullish(),UserID:zod.z.string().nullish(),Player:ed.nullish(),InviterUserID:zod.z.string().nullish(),Message:zod.z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),fl=zod.z.object({ServerTimeUtc:u.nullish(),Items:zod.z.array(nD).catch([])}).passthrough(),sD=zod.z.object({Type:zod.z.string().catch(""),ActorUserID:zod.z.string().nullish(),TargetUserID:zod.z.string().nullish(),Params:hl,At:u.nullish()}).passthrough(),sd=zod.z.object({ServerTimeUtc:u.nullish(),Entries:zod.z.array(sD).catch([]),NextCursor:zod.z.string().nullish()}).passthrough(),id=zod.z.object({RequestID:zod.z.string(),RequestKindID:zod.z.string().catch(""),Type:zod.z.string().catch("Resource"),UserID:zod.z.string().catch(""),Username:zod.z.string().nullish(),Resource:zt.passthrough().nullish(),ItemLevel:zod.z.number().nullish(),Needed:zod.z.number().catch(0),Filled:zod.z.number().catch(0),Claimed:zod.z.number().catch(0),MyDonation:zod.z.number().catch(0),TaskKey:zod.z.string().nullish(),Helps:zod.z.number().catch(0),MaxHelps:zod.z.number().catch(0),HelpedByMe:zod.z.boolean().catch(false),Status:zod.z.string().catch("Open"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),rd=zod.z.object({ServerTimeUtc:u.nullish(),Requests:zod.z.array(id).catch([])}).passthrough(),iD=zod.z.object({GiftUid:zod.z.string(),GiftID:zod.z.string().catch(""),SenderUserID:zod.z.string().nullish(),Level:zod.z.number().catch(0),Content:$.nullish(),Claimed:zod.z.boolean().catch(false),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),od=zod.z.object({ServerTimeUtc:u.nullish(),GiftLevel:zod.z.number().catch(0),GiftPoints:zod.z.number().catch(0),NextGiftLevelPoints:Y,Gifts:zod.z.array(iD).catch([])}).passthrough(),fr=zod.z.object({Key:zod.z.string(),Source:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),RequiredProgress:zod.z.number().catch(0),Rewards:$.nullish(),ReachedAt:u.nullish(),Claimed:zod.z.boolean().catch(false),Claimable:zod.z.boolean().catch(false),Blocked:zod.z.string().nullish()}).passthrough(),ad=zod.z.object({ServerTimeUtc:u.nullish(),Rewards:zod.z.array(fr).catch([])}).passthrough(),ld=zod.z.object({AttackID:zod.z.string(),AttackerUserID:zod.z.string().nullish(),TargetUserID:zod.z.string().nullish(),Status:zod.z.string().catch("Pending"),Stars:zod.z.number().catch(0),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),ud=zod.z.object({ClanID:zod.z.string(),Clan:nn.nullish(),Relation:zod.z.string().catch("None"),Status:zod.z.string().catch("Active"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),cd=zod.z.object({ServerTimeUtc:u.nullish(),Clan:nn.nullish(),Membership:dl.nullish(),Request:id.nullish(),Resources:O.nullish(),Inventory:K.nullish(),Done:zod.z.array(zod.z.string()).nullish(),Failed:hl,WarAttack:ld.nullish(),WarBattle:ds.nullish(),Relation:ud.nullish()}).passthrough(),pd=zod.z.object({ServerTimeUtc:u.nullish(),Definitions:eD.nullish(),DefaultKindID:zod.z.string().nullish()}).passthrough(),rD=zod.z.object({Target:zod.z.string().catch(""),Operation:zod.z.string().catch("AddPercent"),Value:zod.z.number().catch(0),Tag:zod.z.string().nullish()}).passthrough(),oD=zod.z.object({PurchaseID:zod.z.string(),ExpiresAt:u.nullish(),Modifiers:zod.z.array(rD).nullish()}).passthrough(),aD=zod.z.object({CurrencyID:zod.z.string().catch(""),Delta:zod.z.number().catch(0),Kind:zod.z.string().nullish(),ActorUserID:zod.z.string().nullish(),RefID:zod.z.string().nullish(),At:u.nullish()}).passthrough(),hd=zod.z.object({ServerTimeUtc:u.nullish(),Balances:zod.z.record(zod.z.string(),zod.z.number()).catch({}),Buffs:zod.z.array(oD).catch([]),Ledger:zod.z.array(aD).catch([]),NextCursor:zod.z.string().nullish(),MyDepositsToday:zod.z.record(zod.z.string(),zod.z.number()).catch({})}).passthrough(),lD=zod.z.object({ProjectID:zod.z.string(),Points:zod.z.number().catch(0),Level:zod.z.number().catch(0),MaxLevel:zod.z.number().catch(0),NextLevelPoints:Y,Locked:zod.z.string().nullish(),MyPointsToday:zod.z.number().catch(0),DailyCap:Y,Recommended:zod.z.boolean().catch(false)}).passthrough(),dd=zod.z.object({ServerTimeUtc:u.nullish(),RecommendedProjectID:zod.z.string().nullish(),Projects:zod.z.array(lD).catch([])}).passthrough(),uD=zod.z.object({ActivityID:zod.z.string(),Type:zod.z.string().catch("Goal"),Status:zod.z.string().catch("Idle"),InstanceKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),Points:zod.z.number().catch(0),MyPoints:zod.z.number().catch(0),MyPointsToday:zod.z.number().catch(0),BossLevel:zod.z.number().catch(0),BossHp:zod.z.number().catch(0),BossDamage:zod.z.number().catch(0),BossDefeated:zod.z.boolean().catch(false),AttemptsLeft:zod.z.number().catch(0),CanStart:zod.z.boolean().catch(false),StartAllowedAt:u.nullish(),Rewards:zod.z.array(fr).catch([])}).passthrough(),md=zod.z.object({ServerTimeUtc:u.nullish(),Activities:zod.z.array(uD).catch([])}).passthrough(),cD=zod.z.object({ObjectiveID:zod.z.string().catch(""),Target:zod.z.number().catch(0),Progress:zod.z.number().catch(0),MyProgress:zod.z.number().catch(0)}).passthrough(),pD=zod.z.object({QuestID:zod.z.string(),Identity:zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough().nullish(),Objectives:zod.z.array(cD).catch([]),Reward:zod.z.object({Grant:$.nullish(),PointsReward:Y}).passthrough().nullish(),ClanXp:Y,Status:zod.z.string().catch("Available"),Takers:zod.z.number().catch(0),MyContribution:zod.z.number().catch(0),Claimable:zod.z.boolean().catch(false),Claimed:zod.z.boolean().catch(false),Blocked:zod.z.string().nullish()}).passthrough(),hD=zod.z.object({BoardID:zod.z.string(),Mode:zod.z.string().catch("Shared"),CycleKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),Ended:zod.z.boolean().catch(false),Points:zod.z.number().catch(0),MyPoints:zod.z.number().catch(0),MyTaken:zod.z.number().catch(0),MaxTaken:zod.z.number().catch(0),TakeAllowedAt:u.nullish(),SelectedBy:zod.z.string().nullish(),CanSelect:zod.z.boolean().catch(false),Quests:zod.z.array(pD).catch([]),Rewards:zod.z.array(fr).catch([])}).passthrough(),fd=zod.z.object({ServerTimeUtc:u.nullish(),Boards:zod.z.array(hD).catch([])}).passthrough(),dD=zod.z.object({CompetitionID:zod.z.string(),Type:zod.z.string().catch("Battle"),Status:zod.z.string().catch("Idle"),InstanceKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),PhaseIndex:Y,PhaseEndsAt:u.nullish(),Registered:zod.z.boolean().catch(false),CanRegister:zod.z.boolean().catch(false),RegisterBlocked:zod.z.string().nullish(),RegistrationClosesAt:u.nullish(),BracketID:zod.z.string().nullish(),ClansInBracket:zod.z.number().catch(0),Score:zod.z.number().catch(0),Place:Y,Finalized:zod.z.boolean().catch(false),NoContest:zod.z.boolean().catch(false),RatingDelta:Y,MyPoints:zod.z.number().catch(0),MyPointsToday:zod.z.number().catch(0),AttacksLeft:Y,InRoster:zod.z.boolean().nullish(),AttacksFrom:u.nullish(),Rewards:zod.z.array(fr).catch([])}).passthrough(),gd=zod.z.object({ServerTimeUtc:u.nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),Competitions:zod.z.array(dD).catch([])}).passthrough(),mD=zod.z.object({Place:zod.z.number().catch(0),Clan:nn.nullish(),Score:zod.z.number().catch(0),RatingDelta:Y,IsMine:zod.z.boolean().catch(false)}).passthrough(),fD=zod.z.object({UserID:zod.z.string(),ClanID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Power:zod.z.number().catch(0),BestStars:zod.z.number().catch(0),AttacksUsed:zod.z.number().catch(0)}).passthrough(),yd=zod.z.object({ServerTimeUtc:u.nullish(),BracketID:zod.z.string().nullish(),CompetitionID:zod.z.string().nullish(),Type:zod.z.string().catch("Battle"),InstanceKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),Finalized:zod.z.boolean().catch(false),NoContest:zod.z.boolean().catch(false),Rows:zod.z.array(mD).catch([]),War:zod.z.array(fD).nullish(),MyAttacks:zod.z.array(ld).nullish()}).passthrough(),Rd=zod.z.object({ServerTimeUtc:u.nullish(),CanManage:zod.z.boolean().catch(false),Relations:zod.z.array(ud).catch([]),Limits:zod.z.record(zod.z.string(),zod.z.number()).catch({}),Counts:zod.z.record(zod.z.string(),zod.z.number()).catch({})}).passthrough(),gD=zod.z.object({RevengeID:zod.z.string(),VictimUserID:zod.z.string().nullish(),VictimName:zod.z.string().nullish(),AttackerUserID:zod.z.string().nullish(),AttackerName:zod.z.string().nullish(),AttackerAvatarUrl:zod.z.string().nullish(),Action:zod.z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish(),TakenBy:zod.z.string().nullish(),TakenByName:zod.z.string().nullish(),IsMine:zod.z.boolean().catch(false)}).passthrough(),Cd=zod.z.object({ServerTimeUtc:u.nullish(),Revenges:zod.z.array(gD).catch([]),TakenToday:zod.z.number().catch(0),DailyLimit:zod.z.number().catch(0)}).passthrough(),yD=zod.z.object({Key:zod.z.string().nullish(),LeagueID:zod.z.string().nullish(),Rating:zod.z.number().catch(0),EndedAt:u.nullish(),Reward:$.nullish(),Claimable:zod.z.boolean().catch(false),Claimed:zod.z.boolean().catch(false)}).passthrough(),Sd=zod.z.object({ServerTimeUtc:u.nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),SeasonKey:zod.z.string().nullish(),SeasonEndsAt:u.nullish(),LastSeason:yD.nullish()}).passthrough();var gl="Clan",gr=class{constructor(e){this.ctx=e;}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}get definitions(){return this.ctx.data.config.getSection(gl)}get enabled(){let e=this.definitions;return !e||e.IsEnabled===false?false:Object.values(e.Kinds??{}).some(t=>t?.Enabled!==false)}get kindIDs(){let e=this.definitions?.Kinds??{};return Object.entries(e).filter(([,t])=>t?.Enabled!==false).sort(([,t],[,n])=>(t?.Identity?.SortOrder??0)-(n?.Identity?.SortOrder??0)).map(([t])=>t)}kind(e){return (this.definitions?.Kinds??{})[e??this.kindIDs[0]??mr]}async getDefinitions(e){let t=this.ctx.cache.configSection(gl,e);if(t)return G(t);let n=this.request();if(!n)return l;let s=await this.ctx.api.clan.getDefinitions(n);if(!s.ok)return s;let i=s.data.Definitions??{};return this.ctx.data.config.patchSection(gl,i),G(i)}async getMyClans(){let e=this.request();if(!e)return l;let t=await this.ctx.api.clan.getMyClans(e);return t.ok&&this.ctx.emitter.emit("clan:myClansLoaded",t.data),t}async searchClans(e){let t=this.request({KindID:e?.kindID,Query:e?.query,OnlyOpen:e?.onlyOpen,NotFull:e?.notFull,Language:e?.language,PageSize:e?.pageSize});return t?this.ctx.api.clan.searchClans(t):l}async getRecommendedClans(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRecommendedClans(t):l}async getClan(e,t){if(!e?.trim())return h("client","ClanID is required.");let n=this.request({ClanID:e.trim(),KindID:t});return n?this.ctx.api.clan.getClan(n):l}async getMembers(e,t){let n=this.request({ClanID:e,KindID:t});return n?this.ctx.api.clan.getClanMembers(n):l}async getRankings(e){let t=this.request({KindID:e?.kindID,Metric:e?.metric,Slice:e?.slice,PageSize:e?.pageSize});return t?this.ctx.api.clan.getRankings(t):l}async getApplications(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getApplications(t):l}async getMyInvites(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getMyInvites(t):l}async getLog(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getClanLog(t):l}async getRequests(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRequests(t):l}async getGifts(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getGifts(t):l}async getRewards(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRewards(t):l}async getTreasury(e,t){let n=this.request({KindID:e,Cursor:t});return n?this.ctx.api.clan.getTreasury(n):l}async getProjects(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getProjects(t):l}async getActivities(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getActivities(t):l}async getClanQuests(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getClanQuests(t):l}async getCompetitions(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getCompetitions(t):l}async getBracket(e,t){let n=this.request({CompetitionID:e,BracketID:t?.bracketID,InstanceKey:t?.instanceKey,KindID:t?.kindID});return n?this.ctx.api.clan.getBracket(n):l}async getDiplomacy(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getDiplomacy(t):l}async getRevenges(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRevenges(t):l}async getLeague(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getLeague(t):l}async mutate(e,t){let n=this.request(t);if(!n)return l;let s=await this.ctx.api.clan.mutate(e,n);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("clan:changed",{action:e,...s.data})),s}info(e){return {ClanName:e.name,Tag:e.tag,Description:e.description,Announcement:e.announcement,Emblem:e.emblem,Language:e.language,Attributes:e.attributes,JoinMode:e.joinMode,MinPower:e.minPower,MinLevel:e.minLevel,PriceOptionID:e.priceOptionID}}createClan(e,t){return e?.name?.trim()?this.mutate("CreateClan",{KindID:t,...this.info(e)}):Promise.resolve(h("client","Name is required."))}updateClan(e,t){return this.mutate("UpdateClan",{KindID:t,...this.info(e)})}disbandClan(e){return this.mutate("DisbandClan",{KindID:e})}joinClan(e,t){return this.mutate("JoinClan",{ClanID:e,KindID:t})}applyToClan(e,t,n){return this.mutate("ApplyToClan",{ClanID:e,Message:t,KindID:n})}cancelApplication(e,t){return this.mutate("CancelApplication",{ClanID:e,KindID:t})}acceptApplication(e,t){return this.mutate("AcceptApplication",{TargetUserID:e,KindID:t})}rejectApplication(e,t){return this.mutate("RejectApplication",{TargetUserID:e,KindID:t})}invitePlayer(e,t,n){return this.mutate("InvitePlayer",{TargetUserID:e,Message:t,KindID:n})}acceptInvite(e,t){return this.mutate("AcceptInvite",{ClanID:e,KindID:t})}declineInvite(e,t){return this.mutate("DeclineInvite",{ClanID:e,KindID:t})}leaveClan(e){return this.mutate("LeaveClan",{KindID:e})}kickMember(e,t){return this.mutate("KickMember",{TargetUserID:e,KindID:t})}setMemberRole(e,t,n){return this.mutate("SetMemberRole",{TargetUserID:e,RoleID:t,KindID:n})}transferLeadership(e,t){return this.mutate("TransferLeadership",{TargetUserID:e,KindID:t})}createRequest(e,t){return this.mutate("CreateRequest",{RequestKindID:e,Resource:t?.resource,TaskKey:t?.taskKey,ItemInstanceID:t?.itemInstanceID,KindID:t?.kindID})}donateItems(e,t,n){return this.mutate("Donate",{RequestID:e,ItemInstanceIDs:t,KindID:n})}donate(e,t=1,n){return this.mutate("Donate",{RequestID:e,Amount:t,KindID:n})}help(e,t){return this.mutate("Help",{RequestID:e,KindID:t})}claimRequest(e,t){return this.mutate("ClaimRequest",{RequestID:e,KindID:t})}claimGift(e,t){return this.mutate("ClaimGift",{GiftUid:e,KindID:t})}claimAllGifts(e){return this.mutate("ClaimAllGifts",{KindID:e})}claimRewards(e,t){return this.mutate("ClaimRewards",{RewardKeys:e,KindID:t})}depositToTreasury(e,t,n=1,s){return this.mutate("DepositToTreasury",{CurrencyID:e,PayWith:t,Steps:n,KindID:s,RelatedEntityID:`clan_deposit_${V()}`})}buyTreasuryPurchase(e,t){return this.mutate("BuyTreasuryPurchase",{PurchaseID:e,KindID:t})}contributeToProject(e,t){return this.mutate("ContributeToProject",{ProjectID:e,Amount:t.amount,PayWith:t.payWith,FromTreasury:t.fromTreasury,CurrencyID:t.currencyID,KindID:t.kindID,RelatedEntityID:`clan_project_${V()}`})}setRecommendedProject(e,t){return this.mutate("SetRecommendedProject",{ProjectID:e??void 0,KindID:t})}startActivity(e,t){return this.mutate("StartActivity",{ActivityID:e,KindID:t})}submitActivityScore(e,t,n){return this.mutate("SubmitActivityScore",{ActivityID:e,Score:t,KindID:n})}claimActivityRewards(e){return this.mutate("ClaimActivityRewards",{ActivityID:e?.activityID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}selectClanQuests(e,t,n){return this.mutate("SelectClanQuests",{BoardID:e,QuestIDs:t,KindID:n})}takeClanQuest(e,t,n){return this.mutate("TakeClanQuest",{BoardID:e,QuestID:t,KindID:n})}abandonClanQuest(e,t,n){return this.mutate("AbandonClanQuest",{BoardID:e,QuestID:t,KindID:n})}claimClanQuestRewards(e){return this.mutate("ClaimClanQuestRewards",{BoardID:e?.boardID,QuestID:e?.questID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}registerForCompetition(e,t){return this.mutate("RegisterForCompetition",{CompetitionID:e,KindID:t})}claimCompetitionRewards(e){return this.mutate("ClaimCompetitionRewards",{CompetitionID:e?.competitionID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}startWarAttack(e,t,n){return this.mutate("StartWarAttack",{CompetitionID:e,TargetUserID:t,CharacterID:n?.characterID,KindID:n?.kindID})}setDiplomacy(e,t,n){return this.mutate("SetDiplomacy",{TargetClanID:e,Relation:t,KindID:n})}takeRevenge(e,t){return this.mutate("TakeRevenge",{RevengeID:e,KindID:t})}claimSeasonReward(e){return this.mutate("ClaimSeasonReward",{KindID:e})}};var Vn={GetDefinitions:"GetDefinitions",GetAvatars:"GetAvatars",GetShop:"GetShop",BuyItem:"BuyItem"},RD={TooManyUsers:"AVATAR_TOO_MANY_USERS",Disabled:"AVATAR_DISABLED",NotForSale:"AVATAR_ITEM_NOT_FOR_SALE"},yr=50,Rr=zod.z.object({Enabled:zod.z.boolean().nullish(),Styles:zod.z.array(zod.z.string()).nullish(),BlockedSlots:zod.z.array(zod.z.string()).nullish(),HeightMin:zod.z.number().nullish(),HeightMax:zod.z.number().nullish()}).passthrough(),CD=48,SD=zod.z.object({UserID:zod.z.string(),Rev:zod.z.string(),NotModified:zod.z.boolean().nullish(),HasAvatar:zod.z.boolean(),Spec:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),bd=zod.z.object({id:zod.z.string(),slot:zod.z.string()}).passthrough(),xd=zod.z.object({Enabled:zod.z.boolean(),Avatars:zod.z.array(SD).nullish().transform(r=>r??[]),Items:zod.z.record(zod.z.string(),bd).nullish().transform(r=>r??{})}).passthrough(),bD=zod.z.object({ItemID:zod.z.string(),Slot:zod.z.string(),PriceCredits:zod.z.number(),OnSale:zod.z.boolean().nullish(),Name:zod.z.string().nullish(),Source:zod.z.enum(["platform","authors"]).nullish().catch(null),AuthorName:zod.z.string().nullish(),IsOwned:zod.z.boolean().nullish()}).passthrough(),Dd=zod.z.object({Enabled:zod.z.boolean(),Offers:zod.z.array(bD).nullish().transform(r=>r??[]),Owned:zod.z.array(zod.z.string()).nullish().transform(r=>r??[]),LoginRequired:zod.z.boolean().nullish().transform(r=>r??false),Items:zod.z.record(zod.z.string(),bd).nullish().transform(r=>r??{}),Paged:zod.z.boolean().nullish(),Next:zod.z.string().nullish(),Slots:zod.z.array(zod.z.string()).nullish(),AuthorsOpen:zod.z.boolean().nullish()}).passthrough(),Id=zod.z.object({ItemID:zod.z.string().nullish(),Owned:zod.z.boolean().nullish().transform(r=>r??false),TestPurchase:zod.z.boolean().nullish().transform(r=>r??false),CreditsConfirmation:Re.nullish()}).passthrough();var xD="Avatar",Cr=class{constructor(e){this.ctx=e;e.emitter.on("auth:loggedOut",()=>{this.held.clear(),this.inflight.clear(),this.disabled=false;});}ctx;held=new Map;inflight=new Map;disabled=false;get definitions(){return this.ctx.cache.configSection(xD)??null}get enabled(){return this.definitions?.Enabled===true&&!this.disabled}peek(e){return this.held.get(e)}async getMine(){let e=this.ctx.auth.context?.userID;if(!e)return l;let t=await this.get([e]);return t.ok?G(t.data[0]??null):t}async get(e){if(!this.ctx.authedRequest())return l;let n=[...new Set(e.map(o=>o?.trim()).filter(o=>!!o))];if(n.length===0)return G([]);let s=new Set,i=[];for(let o of n){let p=this.inflight.get(o);p?s.add(p):i.push(o);}for(let o=0;o<i.length;o+=yr){let p=i.slice(o,o+yr),m=this.request(p);for(let g of p)this.inflight.set(g,m);m.finally(()=>{for(let g of p)this.inflight.get(g)===m&&this.inflight.delete(g);}),s.add(m);}for(let o of await Promise.all(s)){if(!o.ok)return o;if(!o.data.Enabled)return G([])}return G(n.map(o=>this.held.get(o)).filter(o=>!!o))}async getShop(){let e=this.ctx.authedRequest();return e?this.ctx.api.avatar.getShop(e):l}async browseShop(e={}){let t=this.ctx.authedRequest();if(!t)return l;t.Sort=e.sort??"new",e.slot&&(t.Slot=e.slot);let n=e.query?.trim();return n&&(t.Query=n),e.ownedOnly&&(t.OwnedOnly=true),e.source&&(t.Source=e.source),e.cursor&&(t.Cursor=e.cursor),this.ctx.api.avatar.getShop(t)}async buyItem(e,t,n){let s=this.ctx.authedRequest();return s?(s.ItemID=e,s.PriceCredits=t,n&&(s.CreditsConfirmationID=n),this.ctx.api.avatar.buyItem(s)):l}async request(e){let t=this.ctx.authedRequest();if(!t)return l;t.UserIDs=e;let n={};for(let i of e){let o=this.held.get(i);o&&(n[i]=o.rev);}Object.keys(n).length>0&&(t.KnownRevs=n);let s=await this.ctx.api.avatar.getAvatars(t);if(!s.ok)return s;if(this.disabled=!s.data.Enabled,!s.data.Enabled){for(let i of e)this.held.delete(i);return s}if(s.data.Avatars.some(i=>i.NotModified&&this.held.get(i.UserID)?.rev!==i.Rev)){for(let p of e)this.held.delete(p);let i=this.ctx.authedRequest();if(!i)return l;i.UserIDs=e;let o=await this.ctx.api.avatar.getAvatars(i);return o.ok?o.data.Avatars.some(p=>p.NotModified)?h("client","AVATAR_REVISION_MISMATCH"):(this.apply(o.data),o):o}return this.apply(s.data),s}apply(e){let t=[];for(let n of e.Avatars){if(n.NotModified)continue;let s=n.HasAvatar?n.Spec??null:null;this.held.set(n.UserID,{userID:n.UserID,rev:n.Rev,hasAvatar:n.HasAvatar&&!!s,spec:s,items:s?DD(s,e.Items):[]}),t.push(n.UserID);}t.length>0&&this.ctx.emitter.emit("avatar:changed",{userIDs:t});}};function DD(r,e){let t=r.wear;if(!t||typeof t!="object")return [];let n=[];for(let s of Object.values(t))typeof s=="string"&&e[s]&&n.push(e[s]);return n}var Sr=class{constructor(e){this.ctx=e;}ctx;async getMine(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.getMyPartnership(e):l}async apply(e){let t=this.ctx.authedRequest();return t?(t.Links=(e.links??[]).map(n=>n.trim()).filter(n=>n.length>0),e.publicName?.trim()&&(t.PublicName=e.publicName.trim()),e.about?.trim()&&(t.About=e.about.trim()),typeof e.followers=="number"&&e.followers>=0&&(t.Followers=Math.floor(e.followers)),this.ctx.api.partners.apply(t)):l}async acceptInvite(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.acceptInvite(e):l}async getStats(e){let t=this.ctx.authedRequest();return t?(typeof e=="number"&&e>0&&(t.Days=Math.floor(e)),this.ctx.api.partners.getStats(t)):l}async listCreators(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.listCreators(e):l}async getPayouts(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.getPayouts(e):l}};var br={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},yl="idos-app",Pd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),Allowed:zod.z.boolean(),DenyReason:zod.z.string().nullish(),Message:zod.z.string().nullish(),RetryAfterSeconds:zod.z.number().nullish(),RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),AdUnitID:zod.z.string().nullish(),Type:zod.z.string().nullish(),ExpiresAtUtc:zod.z.string().nullish(),CreditsToAward:zod.z.number().nullish(),RequiresServerSideVerification:zod.z.boolean().nullish()}),vd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),RequestID:zod.z.string().nullish(),Status:zod.z.string(),CreditsAwarded:zod.z.number().nullish(),RetryAfterSeconds:zod.z.number().nullish(),ExpiresAtUtc:zod.z.string().nullish(),AlreadyProcessed:zod.z.boolean().nullish(),GrantedWithoutSsv:zod.z.boolean().nullish(),Resources:O.nullish()});var ID=new Set(["CANCELLED","DECLINED","CLOSED"]),PD=45e3,vD=r=>new Promise(e=>setTimeout(e,r)),xr=class{constructor(e){this.ctx=e;}ctx;get available(){return this.ctx.host.supports.rewardedAds}async showRewarded(e){if(!this.ctx.host.supports.rewardedAds)return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let n=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!n.ok)return {status:"unavailable",reason:n.error};let s=n.data;if(!s.Allowed)return {status:"denied",reason:s.DenyReason??void 0,retryAfterSeconds:s.RetryAfterSeconds??void 0};if(!s.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let i=null;if(s.ProviderID!==yl&&(i=this.titleProvider(s.ProviderID),!i))return {status:"unavailable",reason:"NO_WEB_ADS"};let o=await this.ctx.host.showRewardedAd({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:s.RequestID,placementID:e,adUnitID:s.AdUnitID,provider:i});return o.ok?{...await this.awaitReward(s.RequestID,o.via),requestID:s.RequestID}:{status:ID.has(o.error??"")?"cancelled":"unavailable",reason:o.error}}titleProvider(e){if(!this.ctx.host.supports.titleAds||!e)return null;let n=this.ctx.data.config.getSection("Advertising")?.Providers?.[e];if(!n||n.Enabled===false)return null;let s=this.ctx.host.getClientPlatform(),i=s===Ne.Android?n.AndroidAppID:s===Ne.Ios?n.IosAppID:n.WebAppID;return i?{id:e,kind:n.Kind??"AppLovinMax",appKey:i}:null}async awaitReward(e,t){let n=Date.now()+PD;for(;;){let s=this.ctx.authedRequest();if(!s)return {status:"pending",via:t};let i=await this.ctx.api.advertising.completeView({...s,RequestID:e});if(i.ok&&i.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:i.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((i.ok?i.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>n)return {status:"pending",via:t,reason:i.ok?void 0:i.error};await vD(o);}}};var Wt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},AD={Client:"Client",Server:"Server",System:"System"},TD=zod.z.enum(["Client","Server","System"]).catch("Client"),Rl=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:TD.nullish(),ExpiresAt:u.nullish()}).passthrough(),Dr=zod.z.record(zod.z.string(),Rl),Ad=zod.z.object({Version:zod.z.number().nullish(),Private:Dr.nullish(),Public:Dr.nullish(),ReadOnly:Dr.nullish()}),Cl=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Dr.nullish()}),Sl=zod.z.object({ServerTimeUtc:u.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),wD=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),Td=zod.z.object({ServerTimeUtc:u.nullish(),Results:zod.z.array(wD).nullish()}),wd=zod.z.object({ServerTimeUtc:u.nullish(),DeletedCount:zod.z.number().nullish()}),kd=zod.z.object({Results:zod.z.array(Cl).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),kD={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},zD=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),MD=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:zD.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Ir=zod.z.object({Keys:zod.z.record(zod.z.string(),MD).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),kt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var OD={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},ED={Title:"Title",Platform:"Platform"},zd=zod.z.object({UserID:zod.z.string(),PublicData:_e.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()});var qD=zod.z.object({StageLevel:zod.z.number().nullish(),SpecialPlayedCount:zod.z.number().nullish()}),Md=zod.z.object({UserID:zod.z.string(),IsSelf:zod.z.boolean().nullish(),PublicData:_e.nullish(),Characters:zod.z.record(zod.z.string(),cs).nullish(),StrongestCharacterID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),Board:qD.nullish(),PublicCustomData:zod.z.record(zod.z.string(),Rl).nullish(),Relation:zod.z.enum(["None","Friend","RequestSent","RequestReceived"]).nullish(),FriendSource:zod.z.enum(["Title","Platform"]).nullish(),BlockedByMe:zod.z.boolean().nullish(),FriendRequestsAllowed:zod.z.boolean().nullish()});var fs=zod.z.object({Friends:zod.z.array(zd).nullish()}),UD=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),gs=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:zd.nullish(),Counters:UD.nullish()}),LD={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},BD={Like:"Like",Favorite:"Favorite"},GD={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},ND={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},_D={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived",ArenaDefeat:"ArenaDefeat"},VD=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),FD=zod.z.object({Id:zod.z.string(),Verb:zod.z.string().nullish(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Count:zod.z.number().nullish(),LastActors:zod.z.array(VD).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),OccurredAt:u.nullish(),OwnerImpact:O.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),Od=zod.z.object({Items:zod.z.array(FD).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),ys=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),jD=zod.z.object({Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),Followers:zod.z.number().nullish(),Following:zod.z.number().nullish(),Comments:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Posts:zod.z.number().nullish(),Dislikes:zod.z.number().nullish()}).passthrough(),sn=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:jD.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),Ed=zod.z.object({Items:zod.z.array(sn).nullish()}).passthrough(),bl={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},WD=zod.z.object({UserID:zod.z.string(),PublicData:_e.nullish(),Mutual:zod.z.boolean().nullish(),Since:u.nullish()}).passthrough(),Pr=zod.z.object({Items:zod.z.array(WD).nullish(),...bl}).passthrough(),HD=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:u.nullish()}).passthrough(),qd=zod.z.object({Items:zod.z.array(HD).nullish(),...bl}).passthrough(),vr=zod.z.object({CommentID:zod.z.string(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),ParentCommentID:zod.z.string().nullish(),AuthorUserID:zod.z.string().nullish(),AuthorPublicData:_e.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:u.nullish(),EditedAt:u.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Ud=zod.z.object({Items:zod.z.array(vr).nullish(),...bl,TotalCount:zod.z.number().nullish()}).passthrough(),Ld=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),Bd=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),Gd=zod.z.object({CommentsEnabled:zod.z.boolean().nullish(),CommentableTypes:zod.z.array(zod.z.string()).nullish(),CommentMaxLength:zod.z.number().nullish(),CommentMaxLinks:zod.z.number().nullish()}).passthrough(),KD="FRIENDS_FROM_PLATFORM",QD={Off:"Off",Default:"Default",Always:"Always"},$D={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Nd=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:zod.z.boolean().nullish()}).passthrough(),Pe={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report",GetPlayerProfile:"GetPlayerProfile"};var xl={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Ar=class{constructor(e){this.ctx=e;e.cache.bindLoginView(xl,{schema:ys,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return l;t.Limit=e;let n=await this.ctx.api.social.getRecommendedFriends(t);return n.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",n.data),n}async getPlayerProfile(e){if(!e)return h("client","TargetUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.getPlayerProfile(t);return n.ok&&this.ctx.emitter.emit("social:playerProfileLoaded",n.data),n}async sendFriendRequest(e){if(!e)return h("client","TargetUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.sendFriendRequest(t);return n.ok&&(n.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",n.data)),n}async acceptFriendRequest(e){if(!e)return h("client","RequesterUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.acceptFriendRequest(t);return n.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",n.data)),n}async declineFriendRequest(e){if(!e)return h("client","RequesterUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.declineFriendRequest(t);return n.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",n.data)),n}async removeFriend(e){if(!e)return h("client","FriendUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.removeFriend(t);return n.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRemoved",n.data)),n}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return l;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let n=await this.ctx.api.social.getInbox(t);return n.ok&&this.ctx.emitter.emit("social:inboxLoaded",n.data),n}getInboxUnread(e){return this.ctx.cache.read(xl,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(xl,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let n=this.ctx.authedRequest();return n?(n.ReactionKind=e,n.EntityType=t.entityType,this.applyPage(n,t.cursor,t.limit),this.ctx.api.social.getMyReactions(n)):l}async getEntityStates(e,t){if(!t?.length)return h("client","EntityIDs are required.");let n=this.ctx.authedRequest();return n?(n.EntityType=e,n.EntityIDs=t,this.ctx.api.social.getEntityStates(n)):l}async addComment(e,t,n,s){let i=this.targetRequest(e,t);if("ok"in i)return i;if(!n?.trim())return h("client","Text is required.");i.Text=n,i.ParentCommentID=s;let o=await this.ctx.api.social.addComment(i);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return h("client","CommentID is required.");if(!t?.trim())return h("client","Text is required.");let n=this.ctx.authedRequest();if(!n)return l;n.CommentID=e,n.Text=t;let s=await this.ctx.api.social.editComment(n);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return h("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.CommentID=e;let n=await this.ctx.api.social.deleteComment(t);return n.ok&&this.ctx.emitter.emit("social:commentDeleted",n.data),n}async getComments(e,t,n={}){let s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=n.parentCommentID,this.applyPage(s,n.cursor,n.limit),this.ctx.api.social.getComments(s))}async report(e,t,n,s){let i=this.targetRequest(e,t);if("ok"in i)return i;if(!n)return h("client","ReportReason is required.");i.ReportReason=n,i.ReportComment=s;let o=await this.ctx.api.social.report(i);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,n,s){let i=this.targetRequest(t,n);if("ok"in i)return i;i.ReactionKind=s;let o=await this.ctx.api.social[e](i);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,n){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,n),this.ctx.api.social[e](s)):l}applyPage(e,t,n){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=n;}targetRequest(e,t){if(!e)return h("client","EntityType is required.");if(!t)return h("client","EntityID is required.");let n=this.ctx.authedRequest();return n?(n.EntityType=e,n.EntityID=t,n):l}};var _d="TimedBoost";function JD(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Tr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(_d,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.timedBoost.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(_d,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let n=e.trim();if(!JD(n))return h("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:n,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${n}_${V()}`},i=await this.ctx.api.timedBoost.activate(s);if(i.ok&&!i.data.CreditsConfirmation){let o=i.data;if(o.ActivatedBoost){let p=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,p);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return i}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var ZD="UserCustomData";function Vd(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var wr=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(ZD,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return h("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(n);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,Wt.Private)}async setPublicData(e,t){return this.setData(e,t,Wt.Public)}async setData(e,t,n){let s=e.trim();if(!Vd(s))return h("client",'KeyID is required and must not contain "." or "$".');if(t==null)return h("client","Value is required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(n===Wt.Private?this.ctx.api.userCustomData.setPrivateData(i):this.ctx.api.userCustomData.setPublicData(i));if(p.ok){let m=p.data;this.ctx.data.user.patchUserCustomDataKey(n,m.KeyID,t,m.Version??0,m.ExpiresAt),this.ctx.emitter.emit(n===Wt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",m);}return p}async deleteKey(e,t){let n=e.trim();if(!Vd(n))return h("client",'KeyID is required and must not contain "." or "$".');if(t!==Wt.Private&&t!==Wt.Public)return h("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Bucket:t},i=await this.ctx.api.userCustomData.deleteKey(s);return i.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,n),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),i}async batchSet(e){if(!e.length)return h("client","At least one item is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},n=await this.ctx.api.userCustomData.batchSet(t);if(n.ok){for(let s of n.data.Results??[]){let i=s.Bucket??Wt.Private,o=e.find(p=>p.Bucket===i&&p.KeyID===s.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(i,s.KeyID,o.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",n.data);}return n}async batchDelete(e){if(!e.length)return h("client","At least one item is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},n=await this.ctx.api.userCustomData.batchDelete(t);if(n.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",n.data);}return n}async batchGetPublicUserCustomDataOf(e){if(!e.length)return h("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return l;t.TargetUserIDs=e;let n=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return n.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",n.data),n}};var YD="TitleCustomDataDefinitions",Fd=50;function XD(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function Dl(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function eI(r){let e={};for(let[t,n]of Object.entries(r))Dl(n)||(e[t]=n);return e}var kr=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(YD,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return l;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let n=await this.ctx.api.titleCustomData.getPublicTitleData(t);return n.ok&&this.absorb(n.data),n}async getPublicTitleDataKeys(e){let t=e.map(i=>i.trim()).filter(i=>i.length>0);if(!t.length)return h("client","At least one KeyID is required.");if(t.some(i=>!XD(i)))return h("client",'KeyID must not contain "." or "$".');if(t.length>Fd)return h("client",`At most ${Fd} keys per call \u2014 request them in chunks.`);let n=this.ctx.authedRequest();if(!n)return l;n.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(n);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Dl(t))return t.Value;let n=this.staticCache[e];if(n?.Value!=null&&!Dl(n))return n.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=eI(this.runtimeCache),e.Runtime=this.runtimeCache):e.Runtime&&(this.runtimeCache=e.Runtime),e.RuntimeVersion!=null&&(this.lastRuntimeVersion=e.RuntimeVersion),this.ctx.emitter.emit("titleCustomData:publicDataLoaded",e);}};var zr=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var tI={Fast:"Fast",Sequential:"Sequential"},nI={Instant:"Instant",Timed:"Timed"};var sI={Hit:"Hit",Blocked:"Blocked"},iI=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),rI=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:$.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:$.nullish()}).passthrough();var oI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:$.nullish()}).passthrough(),aI=zod.z.object({Reward:$.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough();zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(oI).nullish(),Rate:aI.nullish()}).passthrough();zod.z.object({PlayedCount:zod.z.number().nullish(),RewardsClaimedCount:zod.z.number().nullish(),InstantClaimsCount:zod.z.number().nullish(),EarlyClaimsCount:zod.z.number().nullish(),LateClaimsCount:zod.z.number().nullish(),AdViewsTotal:zod.z.number().nullish(),StatRewardClaimsCount:zod.z.number().nullish(),StatReportsClampedCount:zod.z.number().nullish(),StatReportsUnknownMetricCount:zod.z.number().nullish()}).passthrough();var jd=zod.z.object({}).passthrough().transform(r=>r),Wd=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Xe=zod.z.object({Operation:O.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),lI=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),uI=zod.z.object({ShieldChance:zod.z.number().nullish(),DamagedBuildingChance:zod.z.number().nullish(),RankMultiplierMin:zod.z.number().nullish(),RankMultiplierMax:zod.z.number().nullish(),RankOffsetMin:zod.z.number().nullish(),RankOffsetMax:zod.z.number().nullish(),StageLevelSpread:zod.z.number().nullish()}).passthrough(),cI=zod.z.object({CostMatrixTemplatesByID:zod.z.record(zod.z.string(),zod.z.array(zod.z.array(zod.z.number()))).nullish(),PerBoardGrowth:zod.z.number().nullish(),VisualTemplateCycle:zod.z.array(zod.z.string()).nullish(),EconomyScaledResources:he.nullish(),ScaleRaidStealWithEconomy:zod.z.boolean().nullish(),ScaleAttackRewardWithEconomy:zod.z.boolean().nullish(),AttackValueFromCostMatrix:zod.z.boolean().nullish(),AttackBlockedRewardFactor:zod.z.number().nullish(),ScaleVictimLossWithEconomy:zod.z.boolean().nullish(),ScaleVictimLossWithTier:zod.z.boolean().nullish(),SynthesizedBuildingSlots:zod.z.number().nullish(),SynthesizedBuildingMaxLevel:zod.z.number().nullish(),DifficultyGrowthPerBoard:zod.z.number().nullish()}).passthrough(),pI=zod.z.object({CostMatrix:zod.z.array(zod.z.array(zod.z.number())).nullish(),PerBoardGrowth:zod.z.number().nullish(),EconomyScale:zod.z.number().nullish(),ScaledResources:he.nullish()}).passthrough(),Hd=zod.z.object({SlotIndex:zod.z.number().nullish(),Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxLevel:zod.z.number().nullish(),MaxLevelReward:$.nullish()}).passthrough(),hI=zod.z.object({Index:zod.z.number().nullish(),Type:zod.z.string().nullish(),CustomTypeID:zod.z.string().nullish(),RandomActionAttackWeight:zod.z.number().nullish(),RandomActionRaidWeight:zod.z.number().nullish(),ChanceTableID:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),dI=zod.z.object({Tiles:zod.z.record(zod.z.string(),hI).nullish()}).passthrough(),mI=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Xe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),fI=zod.z.object({Weight:zod.z.number().nullish(),Tag:zod.z.string().nullish(),MinBonusCells:zod.z.number().nullish(),MaxBonusCells:zod.z.number().nullish(),BonusPool:zod.z.array(mI).nullish(),GuaranteedBonus:Xe.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),gI=zod.z.object({Variants:zod.z.array(fI).nullish()}).passthrough(),yI=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:Xe.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),RI=zod.z.object({Outcomes:zod.z.array(yI).nullish()}).passthrough(),Kd=zod.z.object({PerAdMultiplierRange:Wd.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish(),PremiumMultiplier:zod.z.number().nullish(),MinPremiumTier:zod.z.number().nullish()}).passthrough(),CI=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Xe.nullish()}).passthrough(),SI=zod.z.object({Tiers:zod.z.array(CI).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Xe.nullish()}).passthrough(),bI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Xe.nullish()}).passthrough(),xI=zod.z.object({Reward:Xe.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),DI=zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(bI).nullish(),Rate:xI.nullish()}).passthrough(),Qd=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),DI).nullish()}).passthrough(),II=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Xe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:me.nullish(),Multipliers:Kd.nullish(),Gradation:SI.nullish(),RunStats:Qd.nullish()}).passthrough(),PI=zod.z.object({Choices:zod.z.array(II).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),vI=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Xe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),AI=zod.z.object({OnPassStart:Xe.nullish(),OnTileLanding:zod.z.record(zod.z.string(),Xe).nullish(),OnAttack:zod.z.record(zod.z.string(),Xe).nullish(),OnRaid:zod.z.record(zod.z.string(),Xe).nullish(),OnBuild:Xe.nullish(),OnStageComplete:Xe.nullish(),OnAttackBonusDrops:zod.z.array(vI).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),RI).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),PI).nullish()}).passthrough(),$d=zod.z.object({BaseAttackReward:$.nullish(),BaseRaidReward:$.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Hd).nullish(),HeistGridBonusConfig:gI.nullish(),StageOperations:AI.nullish(),TileLandingMultiplier:Wd.nullish(),EconomyOverride:pI.nullish()}).passthrough(),TI=zod.z.object({Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BoardTemplateID:zod.z.string().nullish(),Buildings:zod.z.array(Hd).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:$d.nullish()}).passthrough(),wI=zod.z.object({AttackCooldownSeconds:zod.z.number().nullish(),RaidCooldownSeconds:zod.z.number().nullish(),MaxRecentTargets:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),LiveOpponentPoolSize:zod.z.number().nullish(),LiveOpponentPoolCacheSeconds:zod.z.number().nullish(),MaxLiveCandidateReads:zod.z.number().nullish(),VictimImmunitySeconds:zod.z.number().nullish()}).passthrough(),kI=zod.z.object({Enabled:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),MaxPerCatchUp:zod.z.number().nullish(),Chance:zod.z.number().nullish(),AttackWeight:zod.z.number().nullish(),RaidWeight:zod.z.number().nullish(),MinBoardStageLevel:zod.z.number().nullish(),RaidLossMultiplier:zod.z.number().nullish()}).passthrough(),zI=zod.z.object({Enabled:zod.z.boolean().nullish(),Sources:zod.z.array(zod.z.string()).nullish(),AdMultiplier:zod.z.number().nullish(),PremiumMultiplier:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),AdDailyLimit:zod.z.number().nullish(),PremiumDailyLimit:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),MinPremiumTier:zod.z.number().nullish()}).passthrough(),Mr=zod.z.object({RollCurrencyID:zod.z.string().nullish(),ShieldCurrencyID:zod.z.string().nullish(),RaidMode:zod.z.string().nullish(),AllowedRollMultipliers:zod.z.array(zod.z.number()).nullish(),BoardTemplatesByID:zod.z.record(zod.z.string(),dI).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),$d).nullish(),StagesByLevel:zod.z.record(zod.z.string(),TI).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:cI.nullish(),Dice:lI.nullish(),Bots:uI.nullish(),Targeting:wI.nullish(),BotRaids:kI.nullish(),RewardBoost:zI.nullish()}).passthrough(),MI=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:u.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),GrandPrize:$.nullish()}).passthrough(),Or=zod.z.object({Board:Mr.nullish(),CommunityChest:MI.nullish()}).passthrough(),Jd=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),he).nullish()}).passthrough(),OI=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:_e.nullish(),TargetBuildingStates:zod.z.array(iI).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:Jd.nullish()}).passthrough(),EI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Xe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:me.nullish(),Multipliers:Kd.nullish(),RunStats:Qd.nullish()}).passthrough(),qI=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(EI).nullish()}).passthrough(),UI=zod.z.object({GroupID:zod.z.string().nullish(),Delta:Q.nullish(),NewProgress:Q.nullish(),MaxProgress:Q.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),Zd=zod.z.object({UsedMultiplier:zod.z.number().nullish(),Steps:zod.z.number().nullish(),DiceValues:zod.z.array(zod.z.number()).nullish(),OldPosition:zod.z.number().nullish(),NewPosition:zod.z.number(),CyclesCompletedDelta:Q.nullish(),LandedTileType:zod.z.string().nullish(),Operation:O.nullish(),Inventory:K.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:OI.nullish(),SpecialModeOffer:qI.nullish(),CommunityChestContribution:UI.nullish()}).passthrough(),Er={Ad:"Ad",Premium:"Premium"},Yd=zod.z.object({BoostID:zod.z.string().nullish(),Source:zod.z.string().nullish(),ExpiresAtUtc:u.nullish(),AdMultiplier:zod.z.number().nullish(),PremiumMultiplier:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),MinPremiumTier:zod.z.number().nullish(),AdRemainingToday:zod.z.number().nullish(),PremiumRemainingToday:zod.z.number().nullish(),BaseEntries:zod.z.array(zt).nullish()}).passthrough(),Xd=zod.z.object({BoostID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Multiplier:zod.z.number().nullish(),AlreadyApplied:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish(),AdRemainingToday:zod.z.number().nullish(),PremiumRemainingToday:zod.z.number().nullish()}).passthrough(),em=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:_t.nullish(),RewardBoost:Yd.nullish()}).passthrough(),Il=zod.z.object({Status:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),FoundSymbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),FoundBonus:$.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(rI).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:_t.nullish(),RaidRewardPreview:Jd.nullish(),RewardBoost:Yd.nullish()}).passthrough(),tm=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish()}).passthrough(),nm=zod.z.object({CreditsConfirmation:Re.nullish(),Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:O.nullish(),Inventory:K.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish()}).passthrough(),sm=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish(),PremiumApplied:zod.z.boolean().nullish()}).passthrough(),LI=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),im=zod.z.object({FinalMultiplier:zod.z.number().nullish(),AdViewsUsed:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),IsEarlyClaim:zod.z.boolean().nullish(),ReachedTierIndex:zod.z.number().nullish(),Operation:O.nullish(),Inventory:K.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(LI).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:$.nullish()}).passthrough(),BI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},rm=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),GI={Active:"Active",Left:"Left",Replaced:"Replaced"},NI=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),_I=zod.z.object({CurrentProgress:Q.nullish(),MaxProgress:Q.nullish()}).passthrough(),VI=zod.z.object({UserID:zod.z.string().nullish(),PublicData:_e.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:Q.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),tc).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:NI.nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),om=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(VI).nullish(),SharedProgress:_I.nullish(),Status:rm.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),FI=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:rm.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:u.nullish()}).passthrough(),jI=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(FI).nullish()}).passthrough(),am=zod.z.object({ServerTimeUtc:u.nullish(),UserState:jI.nullish(),ActiveGroup:om.nullish(),SecondsRemaining:Q.nullish()}),lm=zod.z.object({ServerTimeUtc:u.nullish(),Group:om.nullish(),SecondsRemaining:Q.nullish()}),Pl=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),um=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),He={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",BoardRewardBoostApply:"BoardRewardBoostApply",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var WI=15,HI="GameLoop",cm="BoardDefinition",Rs="InventoryV2",KI="GameLoop",qr=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(HI,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let n=this.ctx.cache.configSection(cm,t);if(n)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n),G(n);let s=this.ctx.authedRequest();if(!s)return l;let i=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return i.ok&&(this.ctx.data.config.patchSection(cm,i.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i.data)),i}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return h("client","stageLevel must be > 0.");let n=this.ctx.authedRequest();if(!n)return l;n.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(n,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return l;let t=false,n=this.ctx.emitter.on("user:stateVersions",({versions:i})=>{i[Rs]!==void 0&&(t=true);}),s;try{s=await this.ctx.api.gameLoop.getUserBoardState(e);}finally{n();}return s.ok&&(this.ctx.data.user.applyBoardState(s.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",s.data),t&&(this.ctx.cache.invalidateState([Rs]),this.ctx.cache.ensureState([Rs]),this.ctx.emitter.emit("user:changedElsewhere",{containers:[Rs]}))),s}async boardLoopRoll(e=1){if(e<1)return h("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${V()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(n);if(s.ok){let i=s.data,o=Ac(new Date,WI);this.ctx.data.user.patchBoardState(p=>{p.Position=i.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(i.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),i.ActionRequired&&i.ActionData?p.Pending={Type:i.ActionRequired,TargetUserID:i.ActionData.TargetUserID,TargetPublicData:i.ActionData.PublicData,TargetBuildingStates:i.ActionData.TargetBuildingStates??void 0,TargetHasShield:i.ActionData.TargetHasShield??void 0,RollMultiplier:i.UsedMultiplier??1,ExpiresAtUtc:o}:i.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:i.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:i.SpecialModeOffer.ModeID??void 0,Choices:i.SpecialModeOffer.Choices??void 0}});}),i.Operation&&this.ctx.data.user.applyResourcesWithDelta(i.Operation,i.Inventory,this.itemDefs),i.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",i);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${V()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(n);if(s.ok){let i=s.data;this.ctx.data.user.clearBoardPending(),i.IsBotTarget&&i.Operation?this.ctx.data.user.applyResourcesWithDelta(i.Operation,i.Inventory,this.itemDefs):!i.IsBotTarget&&i.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(i.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",i);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return h("client","digIndex must be between 0 and 11.");let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${n.userID}_${V()}`},i=await this.ctx.api.gameLoop.boardLoopRaid(s);if(i.ok){let o=i.data;o.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(o.RaidLayout,o.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(o)),this.ctx.emitter.emit("gameLoop:boardRaided",o);}else await this.getUserBoardState();return i}async boardLoopRaidFast(e){if(!e.length)return h("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${V()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(n);if(s.ok){let i=s.data;i.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(i)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",i);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return h("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${V()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(n);if(!s.ok&&s.reason==="server"&&await this.ctx.cache.ensureState([Rs,KI],{force:true}),s.ok){let i=s.data;i.StageComplete?this.ctx.data.user.patchBoardState(o=>{o.StageLevel=(o.StageLevel??1)+1,o.Position=0,o.Pending=null,o.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(i.BuiltIndex,o=>{i.NewLevel!=null&&(o.Level=i.NewLevel),o.IsDamaged=false,i.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),i.Operation&&this.ctx.data.user.applyResourcesWithDelta(i.Operation,i.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",i);}return s}async boardSpecialChoose(e,t,n){if(!e)return h("client","choiceID must not be empty.");let s=this.ctx.auth.context;if(!s)return l;let i={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:n,RelatedEntityID:`special_choose_${s.userID}_${V()}`},o=await this.ctx.api.gameLoop.boardSpecialChoose(i);if(o.ok&&!o.data.CreditsConfirmation){let p=o.data;p.Mode==="Instant"||p.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(g=>{g.ChoiceID=e,g.ChosenMode=p.Mode??"Timed",g.StartedAtUtc=p.StartedAtUtc??null,g.DurationSeconds=p.DurationSeconds??null,g.AdViewsUsed=0;}),p.Operation&&this.ctx.data.user.applyResourcesWithDelta(p.Operation,p.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",p);}return o}async boardSpecialApplyMultiplier(e,t=Er.Ad){let n=this.ctx.auth.context;if(!n)return l;let s=t===Er.Premium,i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_${s?"vip":"ad"}_${n.userID}_${V()}`,...s?{BoostMode:Er.Premium}:{}},o=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(o.ok){let p=o.data;this.ctx.data.user.patchBoardSpecialPending(m=>{m.AdViewsUsed=p.AdViewsUsed??0,m.AccumulatedMultiplier=p.AccumulatedMultiplier??0,p.PremiumApplied&&(m.PremiumApplied=true);}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",p);}return o}async boardRewardBoostApply(e,t){if(!this.ctx.auth.context)return l;if(!e)return h("client","boostID must not be empty.");let s={...this.ctx.buildAuthedBaseRequest(),BoostID:e,BoostMode:t,RelatedEntityID:`boost_${e}_${t}`},i=await this.ctx.api.gameLoop.boardRewardBoostApply(s);if(i.ok){let o=i.data;!o.AlreadyApplied&&o.Operation&&this.ctx.data.user.applyResourcesWithDelta(o.Operation,o.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardRewardBoostApplied",o);}return i}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${V()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(n);if(s.ok){let i=s.data;this.ctx.data.user.clearBoardPending(),i.Operation&&this.ctx.data.user.applyResourcesWithDelta(i.Operation,i.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",i);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return l;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let n=t.data.Group;n?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:n.GroupID,ActiveRoundIndex:n.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return h("client","milestoneID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(n);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",n.data)),n}async leaveCommunityChest(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.gameLoop.leaveCommunityChest(t);return n.ok&&(n.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",n.data)),n}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var Ur=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,n,s){let i=e.trim();if(!i)return h("client","FunctionName is required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:i,FunctionParameter:t,RevisionSelection:n,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(o);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var QI={EVM:"EVM",Solana:"Solana"},$I=zod.z.enum(["EVM","Solana"]).catch("EVM"),JI={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},ZI=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),YI={Token:"Token",Nft:"Nft"},pm=zod.z.enum(["Token","Nft"]).catch("Token"),XI={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},eP=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),tP={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},nP=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),sP={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},vl=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),hm={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Lr(r){let e=r?.trim();return e||hm.GameTopUp}var iP={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},dm=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),rP=zod.z.object({ContractAddress:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),mm=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),oP=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:$I.nullish(),ChainID:zod.z.number().nullish(),ChainTicker:zod.z.string().nullish(),RewardPoolAddress:zod.z.string().nullish(),VaultDepositAddress:zod.z.string().nullish(),ChainConfigVersion:zod.z.number().nullish(),RequiredConfirmations:zod.z.number().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:mm.nullish(),NftCollections:zod.z.array(rP).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RpcUrl:zod.z.string().nullish(),GasPrice:zod.z.number().nullish(),NftBridgeAddress:zod.z.string().nullish(),SignatureEpoch:zod.z.number().nullish()}).passthrough(),aP=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:mm.nullish()}).passthrough(),lP=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),uP={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},cP=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),fm=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:se.nullish(),BalanceSource:cP.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),pP=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),hP={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Cs=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),dP=zod.z.object({Mode:Cs.nullish(),TokenGates:zod.z.array(fm).nullish()}).passthrough(),Al=zod.z.object({SystemState:aP.nullish(),Networks:zod.z.record(zod.z.string(),oP).nullish(),AccountSafety:lP.nullish(),WalletLogin:pP.nullish(),PlayAccess:dP.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),mP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:u.nullish(),LastUsedAt:u.nullish(),LinkType:ZI.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),gm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:pm.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:se.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),fP=zod.z.object({Status:eP.nullish(),Tier:nP.nullish(),VerifiedAt:u.nullish(),ExpiresAt:u.nullish(),RejectedAt:u.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),gP=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:se.nullish(),DepositsVolumeUsd:se.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:se.nullish(),WithdrawalsVolumeUsd:se.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),yP=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:se.nullish(),TotalWithdrawalsVolumeUsd:se.nullish(),PerCurrency:zod.z.record(zod.z.string(),gP).nullish()}).passthrough(),RP=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),CP=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),PerCollection:zod.z.record(zod.z.string(),RP).nullish()}).passthrough(),SP=zod.z.object({Tokens:yP.nullish(),Nfts:CP.nullish()}).passthrough(),Tl=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:se.nullish(),MinBalance:se.nullish()}).passthrough(),rn=zod.z.object({Granted:zod.z.boolean(),Mode:Cs.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:u.nullish(),Balances:zod.z.array(Tl).nullish()}).passthrough(),bP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:u.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:u.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(Tl).nullish()}).passthrough(),xP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),ym=zod.z.object({Mode:Cs.nullish(),TokenGates:zod.z.array(fm).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(xP).nullish(),Status:rn.nullish()}).passthrough(),DP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:u.nullish(),LoggedInAt:u.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(Tl).nullish()}).passthrough(),IP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:u.nullish()}).passthrough(),PP=zod.z.object({Version:zod.z.number().nullish(),Stats:SP.nullish(),LinkedWallets:zod.z.record(zod.z.string(),mP).nullish(),LastWalletLogin:DP.nullish(),PlayAccess:bP.nullish(),PendingWithdrawals:zod.z.array(gm).nullish(),Kyc:fP.nullish(),FirstActivityAt:u.nullish(),LastActivityAt:u.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(IP).nullish()}).passthrough(),vP=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:se,FrozenDelta:se,UpdatedAt:u}).passthrough(),Fn=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),vP).nullish(),PendingAdded:gm.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),AP=zod.z.object({Amount:se,Frozen:se,CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough().transform(r=>r),TP=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:dm.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:se.nullish(),Status:vl.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:se.nullish(),NetPayoutAmount:se.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:u.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:u.nullish(),RefundCheckedAt:u.nullish()}).passthrough(),wP=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:dm.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:se.nullish(),Status:vl.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:u.nullish()}).passthrough(),Rm=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),wl=zod.z.object({TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ContractAddress:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(Rm).nullish(),Signature:zod.z.string().nullish()}).passthrough(),kl=zod.z.object({Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),ProgramID:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(Rm).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Cm=zod.z.object({Blockchain:Al.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),sl).nullish()}).passthrough(),Sm=zod.z.object({State:PP.nullish(),CryptoBalances:zod.z.record(zod.z.string(),AP).nullish()}).passthrough(),bm=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:se.nullish(),AmountUsd:se.nullish(),StateDelta:Fn.nullish()}).passthrough(),xm=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),Dm=zod.z.object({ServerTimeUtc:u.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:se.nullish(),NetAmountNative:se.nullish(),BurnAmountNative:se.nullish(),AmountUsd:se.nullish(),ExpiresAt:u.nullish(),EvmSignature:wl.nullish(),SolanaSignature:kl.nullish(),StateDelta:Fn.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),Im=zod.z.object({ServerTimeUtc:u.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish(),EvmSignature:wl.nullish(),SolanaSignature:kl.nullish(),StateDelta:Fn.nullish(),Inventory:K.nullish()}).passthrough(),Pm=zod.z.object({TokenTransactions:zod.z.array(TP).nullish(),NFTTransactions:zod.z.array(wP).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),zl=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:se.nullish(),AmountUsd:se.nullish(),Target:zod.z.string().nullish()}).passthrough(),vm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:pm.nullish(),EvmSignature:wl.nullish(),SolanaSignature:kl.nullish()}).passthrough(),Am=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:vl.nullish(),StateDelta:Fn.nullish()}).passthrough(),rt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",DepositToken:"DepositToken",DepositNFT:"DepositNFT",RequestTokenWithdrawal:"RequestTokenWithdrawal",RequestNFTWithdrawal:"RequestNFTWithdrawal",GetTransactionHistory:"GetTransactionHistory",RetryWithdrawal:"RetryWithdrawal",ConfirmWithdrawal:"ConfirmWithdrawal",DonateToDeveloper:"DonateToDeveloper",DonateToUsersPool:"DonateToUsersPool",GetPlayAccess:"GetPlayAccess",ConfirmPlayAccess:"ConfirmPlayAccess"};var kP="Blockchain",Tm="Blockchain:Definitions",Br=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Tm,e);if(t)return G(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let n=this.ctx.authedRequest();if(!n)return l;let s=this.ctx.api.blockchain.getDefinitions(n).then(i=>(i.ok&&(this.ctx.data.config.patchSection(kP,i.data.Blockchain),this.ctx.data.config.patchSection(Tm,i.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",i.data)),i)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(n);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,n,s,i){if(!e)return h("client","CurrencyID is required.");if(!t)return h("client","NetworkID is required.");if(!n)return h("client","WalletAddress is required.");if(!s)return h("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return l;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=n,o.Amount=s,o.Category=Lr(i);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,n,s,i,o,p){if(!e)return h("client","ItemID is required.");if(!t)return h("client","NetworkID is required.");if(!n)return h("client","WalletAddress is required.");if(!s)return h("client","Amount is required.");let m=this.ctx.authedRequest();if(!m)return l;m.ItemID=e,m.NetworkID=t,m.WalletAddress=n,m.Amount=s,m.Category=Lr(i),o!==void 0&&(m.Level=o),p&&(m.ItemInstanceID=p);let g=await this.ctx.api.blockchain.requestNFTWithdrawal(m);return g.ok&&(this.ctx.data.user.applyBlockchainStateDelta(g.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(g.data.Resources,g.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",g.data)),g}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return l;t.Amount=String(e);let n=await this.ctx.api.blockchain.getTransactionHistory(t);return n.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",n.data),n}async retryWithdrawal(e){if(!e)return h("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.TitleTransactionID=e;let n=await this.ctx.api.blockchain.retryWithdrawal(t);return n.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",n.data),n}async confirmWithdrawal(e,t){if(!e)return h("client","TitleTransactionID is required.");if(!t)return h("client","On-chain TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.TitleTransactionID=e,n.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(n);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(n);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(n);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.NetworkID=e);let n=await this.ctx.api.blockchain.confirmPlayAccess(t);return n.ok&&this.ctx.auth.setPlayAccess(n.data),n}};var zP={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Ml=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),MP={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Ol=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),OP={Burn:"Burn",Ledger:"Ledger"},EP=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Nr={Item:"Item",VirtualCurrency:"VirtualCurrency"},El=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),qP=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:Q.nullish()}).passthrough(),_r=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(ms).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),ql=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:Q.nullish(),Sink:EP.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),qP).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),UP=zod.z.object({AllowedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedItemIDs:zod.z.array(zod.z.string()).nullish(),AllowUnstackableWithState:zod.z.boolean().nullish(),AllowedCurrencyIDs:zod.z.array(zod.z.string()).nullish(),DeniedCurrencyIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),LP=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:ve.nullish(),BuyLimits:ve.nullish(),ListingFeeOptions:me.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),BP=zod.z.object({Enabled:zod.z.boolean().nullish(),MinDurationHours:zod.z.number().nullish(),MaxDurationHours:zod.z.number().nullish(),AntiSnipeWindowSeconds:zod.z.number().nullish(),AntiSnipeExtensionSeconds:zod.z.number().nullish(),MaxAntiSnipeExtensions:zod.z.number().nullish(),MinBidStepPercent:zod.z.number().nullish(),MinBidStepAbsolute:Q.nullish(),BidLimits:ve.nullish()}).passthrough(),GP=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:ve.nullish(),FillLimits:ve.nullish()}).passthrough(),NP=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:ve.nullish()}).passthrough(),_P=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Ul=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:te.nullish(),Schedule:Se.nullish(),PricePolicy:_r.nullish(),Commission:ql.nullish(),Tradability:UP.nullish(),Listings:LP.nullish(),Auctions:BP.nullish(),BuyOrders:GP.nullish(),DirectTrades:NP.nullish(),Matching:_P.nullish()}).passthrough(),wm=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:Q.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:u.nullish()}).passthrough(),VP=zod.z.object({BidAxisType:zn.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:Q.nullish(),CurrentBid:Q.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(wm).nullish()}).passthrough(),Gr=zod.z.object({LastAt:u.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),FP=zod.z.object({Create:Gr.nullish(),Buy:Gr.nullish(),Sell:Gr.nullish(),Bid:Gr.nullish()}).passthrough(),jP=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),WP=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),EquippedSlot:jP.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Ht=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Ml.nullish(),Status:Ol.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:_e.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:El.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:Q.nullish(),GoodsInstances:zod.z.array(WP).nullish(),Price:he.nullish(),Auction:VP.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),HP=zod.z.object({GoodsType:El.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(Ml,Q).nullish()}).passthrough(),km=zod.z.object({Definitions:Ul.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),Ll=zod.z.object({Offers:zod.z.array(Ht).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),zm=zod.z.object({Groups:zod.z.array(HP).nullish()}).passthrough(),Mm=zod.z.object({Offer:Ht.nullish()}).passthrough(),St=zod.z.object({OfferID:zod.z.string().nullish(),Status:Ol.nullish(),Settlement:_t.nullish(),Resources:O.nullish(),CommissionTaken:he.nullish(),HeldPayout:Ct.nullish()}).passthrough(),Ss=zod.z.object({OfferID:zod.z.string().nullish(),Offer:Ht.nullish(),Resources:O.nullish(),Matched:zod.z.boolean().nullish(),Settlement:St.nullish()}).passthrough(),Om=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:Q.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish()}).passthrough(),Vr=zod.z.object({MyOffers:zod.z.array(Ht).nullish(),MyBids:zod.z.array(Ht).nullish(),MyBuyOrders:zod.z.array(Ht).nullish(),IncomingTrades:zod.z.array(Ht).nullish(),OutgoingTrades:zod.z.array(Ht).nullish(),Claimables:zod.z.array(Ht).nullish(),DrainedRefunds:zod.z.array(wm).nullish(),Limits:FP.nullish(),PendingPayouts:zod.z.array(Ct).nullish(),ReleasedPayouts:zod.z.array(Ct).nullish(),VoidedPayouts:zod.z.array(Ct).nullish(),PayoutOperations:zod.z.array(O).nullish()}).passthrough(),KP=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Ml.nullish(),FinalStatus:Ol.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:El.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:Q.nullish(),PricePaid:he.nullish(),CommissionTaken:he.nullish(),CompletedAt:u.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),Em=zod.z.object({Entries:zod.z.array(KP).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Ge={GetDefinitions:"GetDefinitions",GetGroupedOffers:"GetGroupedOffers",GetOffersByItem:"GetOffersByItem",GetOffer:"GetOffer",GetBuyOrders:"GetBuyOrders",GetMyState:"GetMyState",GetHistory:"GetHistory",CreateListing:"CreateListing",CancelListing:"CancelListing",Buy:"Buy",MarketBuy:"MarketBuy",MarketSell:"MarketSell",CreateAuction:"CreateAuction",PlaceBid:"PlaceBid",ClaimAuction:"ClaimAuction",CreateBuyOrder:"CreateBuyOrder",CancelBuyOrder:"CancelBuyOrder",FillBuyOrder:"FillBuyOrder",CreateDirectTrade:"CreateDirectTrade",RespondDirectTrade:"RespondDirectTrade",CancelDirectTrade:"CancelDirectTrade",ClaimBack:"ClaimBack"};var QP="Marketplace",qm={key:"marketplace.myState",login:"MarketplaceMyState",ttlMs:6e4,dependsOn:["Marketplace"],invalidateOn:["marketplace:listingCreated","marketplace:listingCancelled","marketplace:bought","marketplace:marketBought","marketplace:marketSold","marketplace:auctionCreated","marketplace:bidPlaced","marketplace:auctionClaimed","marketplace:buyOrderCreated","marketplace:buyOrderCancelled","marketplace:buyOrderFilled","marketplace:directTradeCreated","marketplace:directTradeResponded","marketplace:directTradeCancelled","marketplace:claimedBack"]},Fr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(qm,{schema:Vr,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(QP,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,n,s=20){if(!e)return h("client","ItemID is required.");let i=this.ctx.authedRequest();if(!i)return l;i.ItemID=e,i.OfferTypeFilter=t,i.ContinuationToken=n,i.PageSize=s;let o=await this.ctx.api.marketplace.getOffersByItem(i);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.getOffer(t);return n.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",n.data),n}async getBuyOrders(e,t,n=20){let s=this.ctx.authedRequest();if(!s)return l;s.ItemID=e,s.ContinuationToken=t,s.PageSize=n;let i=await this.ctx.api.marketplace.getBuyOrders(s);return i.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",i.data),i}getMyState(e,t){return this.ctx.cache.read(qm,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.MyBidsFilter=e);let n=await this.ctx.api.marketplace.getMyState(t);if(n.ok){for(let s of n.data.PayoutOperations??[])this.ctx.data.user.applyResourceOperation(s,this.ctx.data.config.itemDefinitions);this.applyMyState(n.data);}return n}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,n){let s=this.ctx.authedRequest();if(!s)return l;n&&(s.HistoryFilter=n),s.ContinuationToken=e,s.PageSize=t;let i=await this.ctx.api.marketplace.getHistory(s);return i.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",i.data),i}async createListing(e,t,n,s,i,o,p){if(!e)return h("client","ItemID is required.");if(!t)return h("client","CatalogID is required.");if(!s)return h("client","PriceBundle is required.");let m=this.ctx.authedRequest();if(!m)return l;m.ItemID=e,m.CatalogID=t,m.GoodsAmount=n,m.PriceBundle=s,m.DurationHours=i,m.ItemInstanceIDs=o,m.SelectedOptionID=p;let g=await this.ctx.api.marketplace.createListing(m);return this.applyCreateOfferResult(g,"marketplace:listingCreated"),g}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.buy(t);return n.ok&&(this.applyDualPartySettlement(n.data.Settlement),this.ctx.emitter.emit("marketplace:bought",n.data)),n}async marketBuy(e,t,n){if(!e||e<=0)return h("client","GoodsAmount must be positive.");if(!t)return h("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return l;let i=this.applyGoodsSelector(s,n);if(i)return i;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,n){if(!e||e<=0)return h("client","GoodsAmount must be positive.");if(!t)return h("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return l;let i=this.applyGoodsSelector(s,n);if(i)return i;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,n,s,i,o,p={}){if(!e)return h("client","ItemID is required.");if(!t)return h("client","CatalogID is required.");let m=this.ctx.authedRequest();if(!m)return l;m.ItemID=e,m.CatalogID=t,m.GoodsAmount=n,m.BidAxisType=s,m.BidCurrencyID=p.bidCurrencyID,m.BidCatalogID=p.bidCatalogID,m.BidItemID=p.bidItemID,m.StartingBid=i,m.DurationHours=o,m.ItemInstanceIDs=p.itemInstanceIDs,m.SelectedOptionID=p.selectedOptionID;let g=await this.ctx.api.marketplace.createAuction(m);return this.applyCreateOfferResult(g,"marketplace:auctionCreated"),g}async placeBid(e,t){if(!e)return h("client","OfferID is required.");if(!t||t<=0)return h("client","BidAmount must be positive.");let n=this.ctx.authedRequest();if(!n)return l;n.OfferID=e,n.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(n);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.claimAuction(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",n.data)),n}async createBuyOrder(e,t,n,s,i){if(!e)return h("client","ItemID is required.");if(!t)return h("client","CatalogID is required.");if(!s)return h("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return l;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=n,o.PriceBundle=s,o.DurationHours=i;let p=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.fillBuyOrder(t);return n.ok&&(this.applyDualPartySettlement(n.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",n.data)),n}async createDirectTrade(e,t,n,s,i){if(!e)return h("client","TargetUserID is required.");if(!t)return h("client","CatalogID is required.");if(!n)return h("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return l;o.TargetUserID=e,o.CatalogID=t,o.ItemID=n,o.ItemInstanceIDs=s,o.RequestedBundle=i;let p=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return h("client","OfferID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.OfferID=e,n.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(n);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.claimBack(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",n.data)),n}async cancelOffer(e,t,n){if(!e)return h("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return l;s.OfferID=e;let i=await t(s);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(n,i.data)),i}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=Nr.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Nr.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):h("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let n=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,n):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,n);}};var jr=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return h("client","RoomName is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomName=e,n.Topology=t.topology,n.ChatMode=t.chatMode,n.MaxPlayers=t.maxPlayers,n.Visibility=t.visibility,n.JoinCode=t.joinCode,n.Mode=t.mode,n.Voice=t.voice;let s=await this.ctx.api.multiplayer.createRoom(n);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return h("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(n);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return h("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(n,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return h("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.RoomID=e;let n=await this.ctx.api.multiplayer.claimHost(t);return n.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",n.data),n}async kickMember(e,t,n=false){if(!e)return h("client","RoomID is required.");if(!t)return h("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return l;s.RoomID=e,s.TargetUserID=t,s.Ban=n;let i=await this.ctx.api.multiplayer.kickMember(s);return i.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",i.data),i}async unbanMember(e,t){if(!e)return h("client","RoomID is required.");if(!t)return h("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(n);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let n=this.ctx.authedRequest();if(!n)return l;n.Page=e,n.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(n);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return h("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.RoomID=e;let n=await this.ctx.api.multiplayer.getRoom(t);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",n.data),n}async closeRoom(e){if(!e)return h("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.RoomID=e;let n=await this.ctx.api.multiplayer.closeRoom(t);return n.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",n.data),n}async poll(e,t){if(!e)return h("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(n);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,n,s){if(!e)return h("client","RoomID is required.");if(!t)return h("client","TargetUserID is required.");if(!n)return h("client","SignalKind is required.");let i=this.ctx.authedRequest();if(!i)return l;i.RoomID=e,i.TargetUserID=t,i.SignalKind=n,i.Payload=s;let o=await this.ctx.api.multiplayer.sendSignal(i);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return h("client","RoomID is required.");if(!t)return h("client","ChatText is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(n);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,n){if(!e)return h("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return l;s.RoomID=e,s.Ready=t,s.MemberState=n;let i=await this.ctx.api.multiplayer.setMemberState(s);return i.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",i.data),i}};var Um=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Wr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.ParentContentID=e.parentContentID,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):l}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return h("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):l}async getCreatorProfile(e,t,n){if(!e)return h("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=n,this.ctx.api.workshop.getCreatorProfile(s)):l}async publish(e){if(!e.files||e.files.length===0)return h("client","At least one file is required.");let t=new Map,n=e.files.map((m,g)=>{if("sourceAssetUrl"in m)return {Role:m.role,ContentType:m.contentType,SourceAssetUrl:m.sourceAssetUrl};let j=Lm(m.data,m.contentType);return t.set(g,j),{Role:m.role,ContentType:m.contentType,Size:j.size}}),s=e.thumbnail?Lm(e.thumbnail.data,e.thumbnail.contentType):null,i=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:n,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!i.ok)return i;let o=i.data.Uploads??[];for(let m=0;m<o.length;m++){let g=o[m];if(!g||g.ServerCopy||!g.Url)continue;let j=t.get(m);if(!j)return h("client",`No bytes for file #${m+1}.`);let pe=await this.putBytes(g.Url,j,g.ContentType??j.type);if(!pe.ok)return pe}let p=i.data.ThumbnailUpload;if(p?.Url&&s){let m=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!m.ok)return m}return this.ctx.credits.pay(m=>this.publishUploaded({CreditsConfirmationID:m,ContentID:i.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID}),e.credits)}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):l}async publishUploaded(e){if(!e.ContentID)return h("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return l;let n=await this.ctx.api.workshop.publish({...t,...e});return n.ok&&!n.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",n.data)),n}async updateContent(e,t){let n=this.contentRequest(e);if("ok"in n)return n;n.Title=t.title,n.Description=t.description,n.Tags=t.tags,n.Metadata=t.metadata,n.Visibility=t.visibility,n.Access=t.access;let s=await this.ctx.api.workshop.updateContent(n);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let n=await this.ctx.api.workshop.unpublish(t);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async getMyContent(e,t,n){let s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=n,this.ctx.api.workshop.getMyContent(s)):l}async acquire(e,t){let n=this.contentRequest(e);if("ok"in n)return n;n.OptionID=t?.OptionID??void 0,n.ExpectedPrice=t?.Price??void 0;let s=await this.ctx.api.workshop.acquire(n);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let n=[];for(let s of t.data.Files??[])if(s.Url)try{let i=await this.ctx.fetchImpl(s.Url);if(!i.ok)return h("connection",`Download failed (HTTP ${i.status}).`);n.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await i.arrayBuffer()});}catch(i){return h("connection",`Download failed: ${i instanceof Error?i.message:String(i)}${Um}`)}return G({download:t.data,files:n})}async getMyLicenses(e,t){let n=this.ctx.authedRequest();return n?(n.ContinuationToken=e,n.PageSize=t,this.ctx.api.workshop.getMyLicenses(n)):l}async getMyFavorites(e,t){let n=this.ctx.authedRequest();return n?(n.ContinuationToken=e,n.PageSize=t,this.ctx.api.workshop.getMyFavorites(n)):l}async putBytes(e,t,n){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":n},body:t});return s.ok?G(!0):h("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return h("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${Um}`)}}contentRequest(e){if(!e)return h("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):l}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let n=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,n):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,n);}};function Lm(r,e){return r instanceof Blob?r:typeof r=="string"?new Blob([new TextEncoder().encode(r)],{type:e}):r instanceof Uint8Array?new Blob([r.slice().buffer],{type:e}):new Blob([r],{type:e})}var $P={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},JP=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),ZP={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Bm=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),YP={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Gm=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),XP={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},ev=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),tv={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},nv=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),sv={Count:"Count",Sum:"Sum"},iv=zod.z.enum(["Count","Sum"]).catch("Count"),rv={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},ov=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),av={Strict:"Strict",Loose:"Loose"},lv=zod.z.enum(["Strict","Loose"]).catch("Strict"),uv=zod.z.object({Kind:nv,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),cv=zod.z.object({Type:Bm,ItemType:Bm.nullish(),Ref:uv.nullish(),Required:zod.z.boolean().optional(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),MaxItems:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish(),Unique:zod.z.boolean().optional(),UniqueIgnoreCase:zod.z.boolean().optional(),Indexed:zod.z.boolean().optional(),Visibility:Gm.optional(),ClientWritable:zod.z.boolean().nullish(),Immutable:zod.z.boolean().optional(),Description:zod.z.string().nullish(),AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxFileBytes:zod.z.number().nullish()}),pv=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Hr=zod.z.object({Mode:ev,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),hv=zod.z.object({Read:zod.z.array(Hr).nullish(),Create:zod.z.array(Hr).nullish(),Update:zod.z.array(Hr).nullish(),Delete:zod.z.array(Hr).nullish()}),Bl=zod.z.object({Cost:he.nullish(),Grant:he.nullish()}),dv=zod.z.object({ID:zod.z.string(),SortKey:zod.z.string(),PartitionField:zod.z.string().nullish(),PageSize:zod.z.number().optional(),MaxItems:zod.z.number().optional(),PublishItems:zod.z.boolean().optional()}),mv=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Namespace:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Enabled:zod.z.boolean().nullish(),Kind:JP,Mode:lv.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),cv).nullish(),SortKeys:zod.z.array(pv).nullish(),Access:hv.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:ov.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:iv,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:Gm.optional()})).nullish(),Economy:zod.z.object({OnCreate:Bl.nullish(),OnUpdate:Bl.nullish(),OnDelete:Bl.nullish()}).nullish(),WriteGate:te.nullish(),PublicViews:zod.z.array(dv).nullish(),AnonymousSearch:zod.z.boolean().nullish(),Integrations:zod.z.object({QuestMetricOnCreate:zod.z.string().nullish(),QuestMetricOnUpdate:zod.z.string().nullish(),QuestMetricOnDelete:zod.z.string().nullish(),AnalyticsEventOnCreate:zod.z.string().nullish(),AnalyticsEventOnUpdate:zod.z.string().nullish(),AnalyticsEventOnDelete:zod.z.string().nullish(),TriggerOnCreate:zod.z.string().nullish(),TriggerOnUpdate:zod.z.string().nullish(),TriggerOnDelete:zod.z.string().nullish()}).nullish(),Moderation:zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish()}).nullish()}),Nm=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),mv).default({})}),fv=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),_m=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),jn=zod.z.object({Collection:zod.z.string(),ItemID:zod.z.string(),OwnerUserID:zod.z.string().nullish(),Data:zod.z.record(zod.z.string(),zod.z.unknown()).default({}),Version:zod.z.number(),CreatedAt:zod.z.string(),UpdatedAt:zod.z.string(),ExpireAt:zod.z.string().nullish(),Expanded:zod.z.record(zod.z.string(),zod.z.unknown()).nullish(),Files:zod.z.record(zod.z.string(),fv).nullish()}),Gl=zod.z.object({Item:jn}),Vm=zod.z.object({Items:zod.z.array(jn).default([]),Missing:zod.z.array(zod.z.string()).default([])}),Nl=zod.z.object({Items:zod.z.array(jn).default([]),NextCursor:zod.z.string().nullish()}),Fm=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),_l=zod.z.object({Item:jn,AlreadyExists:zod.z.boolean().optional(),Economy:O.nullish()}),jm=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:O.nullish()}),Wm=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),Hm=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:jn.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),Km=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),Qm=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),$m=zod.z.object({Version:zod.z.string(),Collection:zod.z.string(),View:zod.z.string(),SortKey:zod.z.string().nullish(),PageSize:zod.z.number(),UpdatedAt:zod.z.string(),BaseUrl:zod.z.string(),Partitions:zod.z.record(zod.z.string(),zod.z.object({Segment:zod.z.string(),Pages:zod.z.number(),Total:zod.z.number()})).default({})}),Jm=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(jn).default([])}),gv={GetDefinitions:"GetDefinitions",Get:"Get",GetMany:"GetMany",Query:"Query",Count:"Count",Create:"Create",Update:"Update",Delete:"Delete",Batch:"Batch",GetCounter:"GetCounter",GetMyRoles:"GetMyRoles",BeginFileUpload:"BeginFileUpload"};var yv=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Xm=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Fl=100,Zm=25,Ym=100;function Rv(r,e,t){return {Field:r,Op:e,Value:t}}var Kr=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(l)}get(e,t,n={}){let s=dt(e)??bs(t);return s?Promise.resolve(s):this.call(i=>this.ctx.api.dataCollections.get({...i,Collection:e,ItemID:t,Expand:n.expand}))}getMany(e,t,n={}){let s=dt(e);if(s)return Promise.resolve(s);let i=[...new Set(t.filter(o=>Xm.test(o)))];return i.length?i.length>Ym?Promise.resolve(h("client",`At most ${Ym} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:i,Expand:n.expand})):Promise.resolve(h("client","At least one valid item id is required."))}query(e,t={},n={}){let s=dt(e)??Vl(t);return s?Promise.resolve(s):this.call(i=>this.ctx.api.dataCollections.query({...i,Collection:e,Query:t,Expand:n.expand}))}async queryAll(e,t={},n={}){let s=Math.max(1,n.maxItems??500),i=[],o=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:o,Limit:t.Limit??Fl},n);if(!p.ok)return p;if(i.push(...p.data.Items),o=p.data.NextCursor??void 0,!o||i.length>=s)return G(i.slice(0,s))}}count(e,t={}){let n=dt(e)??Vl(t);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,n={}){let s=dt(e)??(n.itemID?bs(n.itemID):null);return s?Promise.resolve(s):this.call(i=>this.ctx.api.dataCollections.create({...i,Collection:e,ItemID:n.itemID,Data:t}))}update(e,t,n,s={}){let i=dt(e)??bs(t);return i?Promise.resolve(i):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:n,ExpectedVersion:s.expectedVersion}))}set(e,t,n,s={}){return this.update(e,t,{Set:n},s)}increment(e,t,n,s=1){return this.update(e,t,{Inc:{[n]:s}})}delete(e,t,n={}){let s=dt(e)??bs(t);return s?Promise.resolve(s):this.call(i=>this.ctx.api.dataCollections.delete({...i,Collection:e,ItemID:t,ExpectedVersion:n.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(h("client","Operations are empty."));if(e.length>Zm)return Promise.resolve(h("client",`At most ${Zm} operations per batch.`));let t=e.map(n=>dt(n.Collection)).find(n=>n!=null);return t?Promise.resolve(t):this.call(n=>this.ctx.api.dataCollections.batch({...n,Operations:e}))}getCounter(e,t,n){let s=dt(e);return s?Promise.resolve(s):this.call(i=>this.ctx.api.dataCollections.getCounter({...i,Collection:e,CounterID:t,Group:n}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,n,s){let i=dt(e);return i?Promise.resolve(i):t?s>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:n,FileSize:s})):Promise.resolve(h("client","File size must be positive.")):Promise.resolve(h("client","Field is required."))}async uploadFile(e,t,n,s={}){let i=s.contentType||n.type||"application/octet-stream",o=await this.beginFileUpload(e,t,i,n.size);if(!o.ok)return o;let p=await this.putBytes(o.data.UploadUrl,n,o.data.ContentType||i);return p.ok?o:p}async getPublicViews(e){let t=dt(e);if(t)return t;let n=this.publicViews.get(e);if(n)return G(n);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,n={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let i=s.data.Views[t];if(!i)return h("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(i,$m);if(!o.ok)return o;let p=o.data.Partitions[n.partition??""],m=Math.max(1,n.page??1);if(!p||m>p.Pages)return G({pointer:o.data,page:{Page:m,HasMore:false,Items:[]}});let g=await this.fetchJson(`${o.data.BaseUrl}${p.Segment}/page-${m}.json`,Jm);return g.ok?G({pointer:o.data,page:g.data}):g}getPublic(e,t){let n=dt(e)??bs(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let n=dt(e)??Vl(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(l)}async putBytes(e,t,n){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":n},body:t});return s.ok?G(!0):h("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return h("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let n;try{n=await this.ctx.fetchImpl(e);}catch{return h("connection","Internet Connection Error")}if(!n.ok)return h("server",`CDN answered ${n.status}.`);let s;try{s=await n.json();}catch{return h("server","CDN answer is not JSON.")}let i=t.safeParse(s);return i.success?G(i.data):h("server","CDN answer has an unexpected shape.")}};function dt(r){return yv.test(r??"")?null:h("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function bs(r){return Xm.test(r??"")?null:h("client",`Item id '${r}' is invalid.`)}function Vl(r){return r.Limit!=null&&(r.Limit<1||r.Limit>Fl)?h("client",`Limit must be 1..${Fl}.`):(r.Where?.length??0)>8?h("client","At most 8 filters per query."):null}var jl={Open:"Open",Declared:"Declared"},Cv=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),Sv=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),ef=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Cv).nullish(),Dimensions:zod.z.array(Sv).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),on={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Lt={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Qr=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,bv={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},xv=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),tf=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(xv).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Wl={LogEvents:"LogEvents"};function nf(r,e=0){let t=r??"",n=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(n){let p=n[1]??"iPhone";return {osName:"iOS",osVersion:(n[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let p=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let i=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(i)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(i[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let o=/\bWindows NT (\d+\.\d+)/.exec(t);return o?{osName:"Windows",osVersion:o[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function sf(r){let e=typeof navigator>"u"?void 0:navigator,t=nf(e?.userAgent??"",e?.maxTouchPoints??0),n={};r.appVersion&&(n.AppVersion=r.appVersion),t.osName&&(n.OsName=t.osName),t.osVersion&&(n.OsVersion=t.osVersion),t.deviceCategory&&(n.DeviceCategory=t.deviceCategory),t.deviceModel&&(n.DeviceModel=t.deviceModel);let s=r.locale||e?.language;return s&&(n.Language=s),n}var Dv=25,Iv=3e4,rf=1800*1e3,of=500,Pv=5,vv=1e3,Av=3600*1e3,af="idos_analytics_queue",Hl="idos_analytics_pending",Kl="idos_analytics_opt_out",lf="idos_analytics_first_open",uf="idos_analytics_last_activity",cf="idos_analytics_last_context",pf="idos_analytics_owner",$r=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;stopVisibility=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,n){return typeof e!="string"||!Qr.test(e)?h("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Tv(e)?h("client",`Event name "${e}" uses a reserved prefix (${Lt.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,n,false))}logScreenView(e,t){if(!e)return h("client","screenName is required.");let n={screen_name:e};return t&&(n.screen_class=t),this.enqueue(on.ScreenView,n,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return G(null);if(this.config()?.Enabled===false)return this.clear(),G(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return G(null);this.pending={BatchID:V(),Events:this.queue.splice(0,Lt.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return l;let t=this.pending;this.flushing=true;try{let n=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return n.ok?(this.pending=null,n.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),n.data.Dropped&&n.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",n.data.Dropped),this.ctx.emitter.emit("analytics:flushed",n.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),n):(n.reason!=="throttled"&&t.Attempts++,(n.reason==="validation"||t.Attempts>=Pv)&&(this.pending=null),this.persist(),n)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Kl);return}this.write(Kl,"1"),this.clear();}get isEnabled(){return this.read(Kl)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(pf);e&&t&&t!==e&&this.clear(),e&&this.write(pf,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Iv),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide),this.beginAutomatic(),this.flush();}async stop(){this.started&&(this.started=false,this.automaticDone=false,this.timer&&clearInterval(this.timer),this.drainTimer&&clearTimeout(this.drainTimer),this.timer=null,this.drainTimer=null,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null,this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),await this.flush());}beginAutomatic(){if(this.automaticDone||!this.started)return;if(this.config()?.Enabled!==true){this.stopWaitingForConfig??=this.ctx.emitter.on("title:publicConfigurationReceived",()=>this.beginAutomatic());return}this.automaticDone=true,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null;let e=Number(this.read(uf)??"0");this.read(lf)||(this.write(lf,new Date().toISOString()),this.enqueue(on.FirstOpen,void 0,void 0,true));let t=this.clientContext(),n=this.readJson(cf);n?.AppVersion&&t.AppVersion&&n.AppVersion!==t.AppVersion&&this.enqueue(on.AppUpdate,{previous_app_version:n.AppVersion},void 0,true),n?.OsVersion&&t.OsVersion&&n.OsVersion!==t.OsVersion&&this.enqueue(on.OsUpdate,{previous_os_version:n.OsVersion},void 0,true),this.writeJson(cf,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=rf)&&this.enqueue(on.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=e=>{if(!e){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=rf&&this.enqueue(on.SessionStart,void 0,void 0,true),this.hiddenAt=null;};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,n,s){if(!this.isEnabled||this.disabledByServer)return G(null);let i=this.config();if(i?.Enabled===false)return G(null);if(s&&i?.AutomaticEvents===false)return G(null);if(i?.Events?.[e]?.Blocked)return h("client",`Event "${e}" is blocked by the title.`);if(!s&&i?.EventNaming?.toLowerCase()===jl.Declared.toLowerCase()&&!i.Events?.[e])return h("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(n!==void 0&&!Number.isFinite(n))return h("client","value must be a finite number.");let o=wv(t);if(o.error)return h("client",o.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(p.Params=o.params),n!==void 0&&(p.Value=n),this.queue.push(p),this.queue.length>of&&this.queue.splice(0,this.queue.length-of),this.touch(),this.persist(),this.started&&this.queue.length>=Dv&&this.flush(),G(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},vv));}dropStale(){let e=Date.now()-(Lt.maxEventAgeMs-Av);this.queue=this.queue.filter(t=>{let n=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(n)||n>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=sf({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(af);Array.isArray(e)&&(this.queue=e.filter(n=>typeof n?.Name=="string").concat(this.queue));let t=this.readJson(Hl);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(af,this.queue),this.pending?this.writeJson(Hl,this.pending):this.remove(Hl);}touch(){this.write(uf,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.host.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.host.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.host.storage.remove(this.key(e));}catch{}}readJson(e){let t=this.read(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}writeJson(e,t){this.write(e,JSON.stringify(t));}};function Tv(r){let e=r.toLowerCase();return Lt.reservedPrefixes.some(t=>e.startsWith(t))}function wv(r){if(!r)return {};let e=Object.keys(r);if(e.length===0)return {};if(e.length>Lt.maxParams)return {error:`Too many parameters: ${e.length}, max ${Lt.maxParams}.`};let t={};for(let n of e){if(!Qr.test(n))return {error:`Invalid parameter name "${n}".`};let s=r[n];typeof s=="string"?t[n]=s.length>Lt.maxStringValueLength?s.slice(0,Lt.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[n]=s):typeof s=="boolean"&&(t[n]=s);}return {params:t}}var kv="idos_experiments",Jr=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return l;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let n=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),n.length>0&&this.ctx.emitter.emit("experiments:changed",n);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,n){let s=this.getParams(e)[t];if(s===void 0)return n;if(typeof n=="number"){let i=Number(s);return s.trim()!==""&&Number.isFinite(i)?i:n}if(typeof n=="boolean"){let i=s.trim().toLowerCase();return i==="true"||i==="1"?true:i==="false"||i==="0"?false:n}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let n=[];for(let[s,i]of t){let o=this.views.get(s);(!o||o.VariantID!==i.VariantID||o.Status!==i.Status)&&n.push(i);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,n}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.host.storage.getString(this.key());if(!t)return;let n=JSON.parse(t);n?.UserID===e&&n.Data&&this.apply(n.Data);}catch{}}save(e,t){try{let n={UserID:e,Data:t};this.ctx.host.storage.setString(this.key(),JSON.stringify(n));}catch{}}key(){return `${kv}:${this.ctx.settings.titleID}`}};function an(r,e,t,n){let i=`api/v2/${r&&r.length>0?r:"0"}/Client/${e}/${t}`;return n==null?i:`${i}/${n}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return an(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,n,s){return this.ctx.transport.post(this.endpoint(e,t),t,n,{...s,ticket:t.ClientSessionTicket})}};var Zr=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Wl.LogEvents,e,tf,{silent:true})}};var zv=zod.z.object({VariantID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Weight:zod.z.number().nullish(),IsControl:zod.z.boolean().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Mv={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Ov=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),Ev=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:Se.nullish(),Gate:te.nullish(),Variants:zod.z.array(zv).nullish(),Salt:zod.z.string().nullish(),LayerID:zod.z.string().nullish(),StickyAssignment:zod.z.boolean().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Goals:zod.z.array(Ov).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),hf=zod.z.object({Experiments:zod.z.record(zod.z.string(),Ev).nullish()}).passthrough(),qv={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Uv=zod.z.object({ExperimentID:zod.z.string().nullish(),VariantID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),df=zod.z.object({Experiments:zod.z.array(Uv).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),Ql={GetExperiments:"GetExperiments"};var Yr=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Ql.GetExperiments,e,df)}};var Lv={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},mf=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Bv=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),ff=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),Bv).nullish(),MissingKeyMode:mf.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),Gv=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),gf=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:Gv.nullish()}).passthrough(),Xr={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Nv=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),yf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:mf.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(Nv).nullish()}).passthrough(),Rf=zod.z.object({RequestedLocale:zod.z.string().nullish(),Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),NotModified:zod.z.boolean().nullish(),Entries:zod.z.record(zod.z.string(),zod.z.string()).nullish(),FallbackLocale:zod.z.string().nullish(),FallbackVersion:zod.z.number().nullish()}).passthrough();var xs=zod.z.object({TitleConfigVersion:zod.z.string().nullish(),TitleConfigUrl:zod.z.string().nullish(),User:zod.z.unknown().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish(),Localization:gf.nullish(),Views:zod.z.array(zod.z.object({Name:zod.z.string(),Key:zod.z.string().nullish(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().nullish()}).passthrough()).nullish(),PeerPayouts:Mh.nullish()}).passthrough().transform(r=>r),Cf=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(r=>r),Sf=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),User:zod.z.unknown().nullish()}).passthrough().transform(r=>r),bf=zod.z.object({}).passthrough().transform(r=>r),xf=zod.z.object({}).passthrough().transform(r=>r),Df=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:u.nullish(),LastActiveAt:u.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),If=zod.z.object({Username:zod.z.string()}),bt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Pf=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:u.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,PlayAccess:rn.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:u.nullish(),ClientState:xs.nullish()}),vf=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,RefreshToken:zod.z.string(),RefreshTokenExpiration:u.nullish(),PlayAccess:rn.nullish()}),_v=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Af=zod.z.object({Google:zod.z.object({Enabled:zod.z.boolean().nullish(),WebClientID:zod.z.string().nullish(),PlatformFallback:zod.z.boolean().nullish(),AndroidClientID:zod.z.string().nullish(),IosClientID:zod.z.string().nullish(),DesktopClientID:zod.z.string().nullish()}).passthrough().nullish(),Apple:zod.z.object({Enabled:zod.z.boolean().nullish(),BundleID:zod.z.string().nullish(),ServiceID:zod.z.string().nullish()}).passthrough().nullish(),PlayAccessMode:Cs.nullish(),WalletLoginNetworks:zod.z.array(zod.z.object({NetworkID:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:zod.z.boolean().nullish(),NativeSso:_v.nullish()}).passthrough(),Tf=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:u.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:rn.nullish()}).passthrough(),wf=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:u.nullish(),PlayAccess:rn.nullish()}).passthrough(),kf=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Qe=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:u.nullish()}),zf=zod.z.object({Message:zod.z.string(),ExpiresAt:u}),Ke={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",ResolvePlatformGameSession:"ResolvePlatformGameSession",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var eo=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return an(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,Pf,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ke.RefreshSession),e,vf,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ke.GetAuthOptions),e,Af,{ticket:null})}linkWallet(e){return this.ctx.transport.post(an(this.ctx.settings.titleID,"Authentication",Ke.LinkWallet,e.UserID??""),e,Tf,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(an(this.ctx.settings.titleID,"Authentication",Ke.UnlinkWallet,e.UserID??""),e,wf,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ke.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ke.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ke.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ke.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ke.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ke.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(Ke.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ke.RegisterWithEmail),e,kf,{ticket:null})}confirmEmailRegistration(e){return this.login(Ke.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ke.ResendVerificationCode),e,Qe,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ke.RequestWalletChallenge),e,zf,{ticket:null})}loginWithWallet(e){return this.login(Ke.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ke.ForgotPassword),e,Qe,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ke.ResetPassword),e,Qe,{ticket:null})}};var to=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(bt.GetClientState,e,xs)}getClientStateExcept(e){return this.send(bt.GetClientStateExcept,e,xs)}getStateVersions(e){return this.send(bt.GetStateVersions,e,Cf)}getUserState(e){return this.send(bt.GetUserState,e,Sf)}getInventory(e){return this.send(bt.GetInventory,e,bf)}getEventTokens(e){return this.send(bt.GetEventTokens,e,xf)}getUsageTime(e){return this.send(bt.GetUsageTime,e,Df)}addUsageTime(e){return this.send(bt.AddUsageTime,e,Qe,{silent:true})}deleteUserAccount(e){return this.send(bt.DeleteUserAccount,e,Qe)}changeUsername(e){return this.send(bt.ChangeUsername,e,If)}};var no=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(hs.Convert,e,vh)}spend(e){return this.send(hs.Spend,e,Th)}cryptoConvert(e){return this.send(hs.CryptoConvert,e,Ah)}};var Vv=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),$l=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:O.nullish(),FodderConsumed:zod.z.array(Vv).nullish()}),Mf=zod.z.array(Ee($l)),so={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Fv={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},jv=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Wv={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Hv=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Kv=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),Qv=zod.z.object({Networks:zod.z.record(zod.z.string(),Kv).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),$v=zod.z.object({FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),Jv=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),UseRequirements:zod.z.record(zod.z.string(),zod.z.number()).nullish(),AllowedCharacterIDs:zod.z.array(zod.z.string()).nullish(),AllowedSlotIDs:zod.z.array(zod.z.string()).nullish(),IdleRateBonus:zod.z.number().nullish()}).passthrough(),Zv=zod.z.object({ValuationMode:jv.nullish(),WeightCurve:Ze.nullish(),Selection:Hv.nullish()}).passthrough(),Yv=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:me.nullish(),CostCurve:Ze.nullish(),FlatBonusCurve:Ze.nullish(),PercentBonusCurve:Ze.nullish(),PowerCurve:Ze.nullish(),Fodder:Zv.nullish()}).passthrough(),Xv=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),eA=zod.z.object({ItemID:zod.z.string(),CatalogID:zod.z.string(),ItemClass:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsStackable:zod.z.boolean().nullish(),IsTradable:zod.z.boolean().nullish(),Weight:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),NFT:Qv.nullish(),Stats:$v.nullish(),Equipment:Jv.nullish(),Upgrade:Yv.nullish(),Metadata:Xv.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),tA=zod.z.object({Items:zod.z.record(zod.z.string(),eA).nullish()}).passthrough(),nA={Cumulative:"Cumulative",HighestOnly:"HighestOnly"},sA=zod.z.enum(["Cumulative","HighestOnly"]).catch("Cumulative"),iA=zod.z.object({Pieces:zod.z.number().nullish(),FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),rA=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BonusMode:zod.z.enum(["Cumulative","HighestOnly"]).nullish().catch(null),Bonuses:zod.z.array(iA).nullish()}).passthrough(),oA=zod.z.object({BonusMode:sA.nullish()}).passthrough(),io=zod.z.object({Catalogs:zod.z.record(zod.z.string(),tA).nullish(),Sets:zod.z.record(zod.z.string(),rA).nullish(),SetSettings:oA.nullish()}).passthrough();function ke(r){return zod.z.unknown().transform((e,t)=>{let n=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(n!=null){let i=Re.safeParse(n);return i.success?{...e,CreditsConfirmation:i.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${i.error.message}`}),zod.z.NEVER)}let s=r.safeParse(e);return s.success?s.data:(t.addIssue({code:"custom",message:s.error.message}),zod.z.NEVER)})}var ro=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(so.UpgradeLevel,e,ke($l))}upgradeLevelsBatch(e){return this.send(so.UpgradeLevelsBatch,e,Mf)}};var oo=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(Ft.Purchase,e,qa)}purchaseBatch(e){return this.send(Ft.PurchaseBatch,e,Ec)}getDefinitions(e){return this.send(Ft.GetDefinitions,e,mi)}getUserState(e){return this.send(Ft.GetUserState,e,qc)}getStorefront(e){return this.send(Ft.GetStorefront,e,fi)}getCreditsConfirmation(e){return this.send(Ft.GetCreditsConfirmation,e,Re)}getCreditsBalance(e){return this.send(Ft.GetCreditsBalance,e,Oc)}};var aA={Apple:"Apple",Google:"Google"},ao=zod.z.object({PremiumID:zod.z.string().nullish(),PurchaseDate:zod.z.string().nullish(),ExpirationDate:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),IsAutoRenewEnabled:zod.z.boolean().nullish()}).passthrough(),lo=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),ao).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(r=>r),lA=zod.z.object({PremiumID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Tier:zod.z.number().nullish(),DurationDays:zod.z.number().nullish(),TrialDurationDays:zod.z.number().nullish(),PriceOptions:me.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Zl=zod.z.object({Definitions:zod.z.record(zod.z.string(),lA).nullish()}).passthrough(),Of=zod.z.object({Premium:Zl.nullish()}),Ef=zod.z.object({ServerTimeUtc:u.nullish(),Premium:lo.nullish()}),uo=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u.nullish(),Premium:lo.nullish(),Subscription:ao.nullish(),Resources:O.nullish()}),Sn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var uA={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},cA=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),qf=zod.z.object({StartUtc:u.nullish(),EndUtc:u.nullish(),Gate:te.nullish(),Limits:ve.nullish()}).passthrough(),Yl=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),pA=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:$.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),hA=zod.z.object({Rewards:J.nullish(),Rules:J.nullish(),Refund:J.nullish()}).passthrough(),dA=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:cA.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:$.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:qf.nullish(),Refund:Yl.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:pA.nullish(),Presets:hA.nullish()}).passthrough(),mA=zod.z.object({StoreID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),PackageName:zod.z.string().nullish(),VerificationMode:zod.z.string().nullish(),PlayPublicKey:zod.z.string().nullish(),RequireCertificateChain:zod.z.boolean().nullish(),SecretName:zod.z.string().nullish(),IssuerID:zod.z.string().nullish(),KeyID:zod.z.string().nullish(),AcknowledgePurchases:zod.z.boolean().nullish(),NotificationPackageName:zod.z.string().nullish()}).passthrough(),fA=zod.z.object({Rewards:$.nullish()}).passthrough(),gA=zod.z.object({Rules:qf.nullish()}).passthrough(),yA=zod.z.object({Refund:Yl.nullish()}).passthrough(),RA=zod.z.object({Rewards:zod.z.record(zod.z.string(),fA).nullish(),Rules:zod.z.record(zod.z.string(),gA).nullish(),Refund:zod.z.record(zod.z.string(),yA).nullish()}).passthrough(),CA=zod.z.object({MaxPurchaseAgeDays:zod.z.number().nullish(),AllowSandbox:zod.z.boolean().nullish(),RequirePackageMatch:zod.z.boolean().nullish(),MaxReceiptsPerBatch:zod.z.number().nullish(),RefundCheckHorizonDays:zod.z.number().nullish(),RejectCrossUserReceipts:zod.z.boolean().nullish()}).passthrough(),SA=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),dA).nullish(),Stores:zod.z.record(zod.z.string(),mA).nullish(),Presets:RA.nullish(),Validation:CA.nullish(),Refund:Yl.nullish()}).passthrough(),Uf=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:u.nullish(),LastPurchasedAt:u.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Lf=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:u.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:u.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:u.nullish()}).passthrough(),bA=zod.z.object({Products:zod.z.record(zod.z.string(),Uf).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Lf).nullish(),LastRefundCheckAt:u.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:u.nullish(),LastPurchaseAt:u.nullish()}).passthrough(),xA=zod.z.object({ProductID:zod.z.string(),Available:zod.z.boolean(),Owned:zod.z.boolean(),Blocked:zod.z.boolean(),Reason:zod.z.string().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Bf=zod.z.object({ServerTimeUtc:u,Purchase:SA.nullish(),Availability:zod.z.array(xA).nullish()}),Gf=zod.z.object({ServerTimeUtc:u,Purchase:bA.nullish()}),DA={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},IA=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Xl=zod.z.object({ServerTimeUtc:u,Store:Ms.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:IA.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish(),ProductState:Uf.nullish(),Premium:lo.nullish(),Subscription:ao.nullish(),SubscriptionMirror:Lf.nullish()}).passthrough(),Nf=zod.z.object({ServerTimeUtc:u,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:u.nullish()}).passthrough(),_f=Ot(Xl),bn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var co=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(bn.GetDefinitions,e,Bf)}getUserState(e){return this.send(bn.GetUserState,e,Gf)}validatePurchase(e){return this.send(bn.ValidatePurchase,e,Xl)}validatePurchasesBatch(e){return this.send(bn.ValidatePurchasesBatch,e,_f)}createTelegramInvoice(e){return this.send(bn.CreateTelegramInvoice,e,Nf)}};var PA=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Vf=zod.z.object({Reward:$.nullish(),Weight:zod.z.number().nullish(),AmountRange:PA.nullish()}).passthrough(),Wn=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(Vf).nullish()}).passthrough(),Hn=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(Vf).nullish()}).passthrough(),vA=zod.z.object({RewardSlots:zod.z.array(Wn).nullish()}).passthrough(),AA=zod.z.object({PityRules:zod.z.array(Hn).nullish()}).passthrough(),po=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),vA).nullish(),PityPresets:zod.z.record(zod.z.string(),AA).nullish()}).passthrough();var TA=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),Ff=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish(),Results:zod.z.array(O).nullish(),TriggeredPity:zod.z.array(TA).nullish()}),wA=zod.z.object({RewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),kA=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:Q.nullish()}).passthrough(),zA=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:me.nullish(),RewardSlots:zod.z.array(Wn).nullish(),PityRules:zod.z.array(Hn).nullish(),Presets:wA.nullish(),RewardMultiplier:Ns.nullish(),SupplyLimits:zod.z.array(kA).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),MA=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),eu=zod.z.object({Definitions:zod.z.record(zod.z.string(),zA).nullish(),RewardPools:po.nullish(),Settings:MA.nullish()}).passthrough(),jf=zod.z.object({LootboxDefinitions:eu.nullish()}),ho={GetDefinitions:"GetDefinitions",Open:"Open"};var mo=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(ho.GetDefinitions,e,jf)}open(e){return this.send(ho.Open,e,ke(Ff))}};var OA=zod.z.object({}).passthrough().transform(r=>r),EA=zod.z.object({}).passthrough().transform(r=>r),qA=zod.z.object({}).passthrough().transform(r=>r),UA=zod.z.object({}).passthrough().transform(r=>r),LA=zod.z.object({}).passthrough().transform(r=>r),BA=zod.z.object({}).passthrough().transform(r=>r),Wf=zod.z.object({ServerTimeUtc:u,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:OA,Resources:O.nullish(),Inventory:K.nullish()}),Hf=zod.z.object({ServerTimeUtc:u,AccrualID:zod.z.string(),AccruedSeconds:Q.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:EA,Resources:O.nullish(),Inventory:K.nullish()}),Kf=zod.z.object({ServerTimeUtc:u,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:qA,Resources:O.nullish(),Inventory:K.nullish()}),Qf=zod.z.object({ServerTimeUtc:u,ClaimID:zod.z.string(),ClaimState:UA,Resources:O.nullish(),Inventory:K.nullish()}),GA={None:"None",Ad:"Ad",Vip:"Vip"},$f=zod.z.object({ServerTimeUtc:u,WindowID:zod.z.string(),Boost:zod.z.string().nullish(),BaseAmount:Q.nullish(),Multiplier:zod.z.number().nullish(),Granted:Q.nullish(),WindowState:LA,Resources:O.nullish(),Inventory:K.nullish()}),Jf=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:Q.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),NA=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),_A=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:$.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ds=zod.z.object({Gate:te.nullish(),Limits:ve.nullish()}).passthrough(),tu=zod.z.object({Availability:J.nullish()}).passthrough(),VA=zod.z.object({Availability:zod.z.record(zod.z.string(),Ds).nullish()}).passthrough(),FA=zod.z.object({CalendarID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Days:zod.z.array(_A).nullish(),IsLooping:zod.z.boolean().nullish(),MissBehavior:zod.z.string().nullish(),ResetByDays:zod.z.number().nullish(),MissThresholdMultiplier:zod.z.number().nullish(),ClaimMode:zod.z.string().nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),Availability:Ds.nullish(),Presets:tu.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),jA=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),WA=zod.z.object({BaseRatePerSecond:zod.z.number().nullish(),PowerCoefficient:zod.z.number().nullish(),BoardRankCoefficient:zod.z.number().nullish(),EquipmentBonusEnabled:zod.z.boolean().nullish(),EquipmentCharacterID:zod.z.string().nullish(),PremiumMultipliers:zod.z.array(jA).nullish()}).passthrough(),HA=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Ds.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),KA=zod.z.object({AccrualID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rate:WA.nullish(),Rewards:$.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:HA.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),QA=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:$.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$A=zod.z.object({ComebackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(QA).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Ds.nullish(),Presets:tu.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),JA=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxClaimsPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish(),TotalClaimLimit:zod.z.number().nullish()}).passthrough(),ZA=zod.z.object({ClaimID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Mode:zod.z.string().nullish(),Rewards:$.nullish(),PremiumLimitOverrides:zod.z.array(JA).nullish(),Availability:Ds.nullish(),Presets:tu.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),YA=zod.z.object({CurrencyID:zod.z.string().nullish(),MaxBaseAmount:zod.z.number().nullish(),AdPlacementID:zod.z.string().nullish(),AdMultiplier:zod.z.number().nullish(),VipMultiplier:zod.z.number().nullish(),VipPremiumID:zod.z.string().nullish(),Limits:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),nu=zod.z.object({TierRewards:NA.nullish(),MilestoneRewardMultiplier:Ns.nullish(),DailyCalendars:zod.z.record(zod.z.string(),FA).nullish(),IdleAccruals:zod.z.record(zod.z.string(),KA).nullish(),Comebacks:zod.z.record(zod.z.string(),$A).nullish(),Claims:zod.z.record(zod.z.string(),ZA).nullish(),Windows:zod.z.record(zod.z.string(),YA).nullish(),Presets:VA.nullish()}).passthrough(),Zf=zod.z.object({RewardDefinitions:nu.nullish()}),Yf=zod.z.object({Rewards:BA.nullish()}),Bt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var fo=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Bt.GetRewardDefinitions,e,Zf)}getUserRewardsState(e){return this.send(Bt.GetUserRewardsState,e,Yf)}getMilestoneRewardMultiplier(e){return this.send(Bt.GetMilestoneRewardMultiplier,e,Jf)}claimDailyReward(e){return this.send(Bt.ClaimDailyReward,e,Wf)}collectIdleAccrual(e){return this.send(Bt.CollectIdleAccrual,e,Hf)}claimComebackReward(e){return this.send(Bt.ClaimComebackReward,e,Kf)}claimReward(e){return this.send(Bt.ClaimReward,e,Qf)}claimRewardWindow(e){return this.send(Bt.ClaimRewardWindow,e,$f)}};var go=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(gt.GetTutorialDefinitions,e,fc)}getUserTutorialState(e){return this.send(gt.GetUserTutorialState,e,Fs)}startFlow(e){return this.send(gt.StartFlow,e,Jt)}reportStepShown(e){return this.send(gt.ReportStepShown,e,Jt)}completeStep(e){return this.send(gt.CompleteStep,e,Jt)}completeStepsBatch(e){return this.send(gt.CompleteStepsBatch,e,Rc)}skipStep(e){return this.send(gt.SkipStep,e,Jt)}skipFlow(e){return this.send(gt.SkipFlow,e,Jt)}claimFlowReward(e){return this.send(gt.ClaimFlowReward,e,yc)}resetFlow(e){return this.send(gt.ResetFlow,e,Jt)}};var XA={Open:"Open",Application:"Application"},eT=zod.z.enum(["Open","Application"]).catch("Open"),tT={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Xf=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),nT={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},su=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),sT={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var xn={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},iT=zod.z.object({CampaignID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IsRunning:zod.z.boolean().nullish()}).passthrough(),eg=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:eT.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:Xf.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(iT).nullish()}).passthrough(),rT=zod.z.object({Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),CountedMetrics:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ReachedMilestones:zod.z.array(zod.z.string()).nullish(),CappedBySubmissionLimit:zod.z.boolean().nullish(),CappedByCreatorLimit:zod.z.boolean().nullish(),NotPaidAsCopy:zod.z.boolean().nullish()}).passthrough(),oT=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:su.nullish(),CurrencyID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),Granted:zod.z.number().nullish(),Paid:zod.z.number().nullish(),Overpaid:zod.z.number().nullish(),Claimable:zod.z.number().nullish(),BySubmission:zod.z.record(zod.z.string(),rT).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),aT=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:su.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),tg=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(oT).nullish(),Payouts:zod.z.array(aT).nullish()}).passthrough(),ng=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:su.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),lT=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),uT=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),Signature:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(lT).nullish()}).passthrough(),cT=zod.z.object({Kind:zod.z.string().nullish(),Target:zod.z.string().nullish(),Required:zod.z.number().nullish(),Actual:zod.z.number().nullish(),Passed:zod.z.boolean().nullish()}).passthrough(),sg=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:Xf.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(cT).nullish()}).passthrough(),pT=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),hT=zod.z.object({ProgramID:zod.z.string().nullish(),Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(pT).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),ig=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:zod.z.number().nullish(),NetAmountNative:zod.z.number().nullish(),BurnAmountNative:zod.z.number().nullish(),AmountUsd:zod.z.number().nullish(),ExpiresAt:zod.z.string().nullish(),EvmSignature:uT.nullish(),SolanaSignature:hT.nullish(),StateDelta:Fn.nullish()}).passthrough();var yo=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(xn.GetCommunityMarketingState,e,eg)}getEarnings(e){return this.send(xn.GetEarnings,e,tg)}claim(e){return this.send(xn.Claim,e,ng)}checkJoinEligibility(e){return this.send(xn.CheckJoinEligibility,e,sg)}withdrawCryptoReward(e){return this.send(xn.WithdrawCryptoReward,e,ig)}};var Ro=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(st.GetChatDefinitions,e,Zc)}getChannels(e){return this.send(st.GetChannels,e,Ai)}poll(e){return this.send(st.Poll,e,Yc)}getHistory(e){return this.send(st.GetHistory,e,Xc)}getConversations(e){return this.send(st.GetConversations,e,np)}sendMessage(e){return this.send(st.SendMessage,e,ep)}openDirectChannel(e){return this.send(st.OpenDirectChannel,e,tp)}markRead(e){return this.send(st.MarkRead,e,Nn)}joinChannel(e){return this.send(st.JoinChannel,e,Nn)}leaveChannel(e){return this.send(st.LeaveChannel,e,Nn)}reportMessage(e){return this.send(st.ReportMessage,e,sp)}ignoreUser(e){return this.send(st.IgnoreUser,e,Nn)}unignoreUser(e){return this.send(st.UnignoreUser,e,Nn)}};var Co=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(_n.GetPushConfig,e,op)}subscribePush(e){return this.send(_n.SubscribePush,e,Ba)}unsubscribePush(e){return this.send(_n.UnsubscribePush,e,Qe)}getPushSubscriptions(e){return this.send(_n.GetPushSubscriptions,e,ap)}};var So=class extends B{constructor(e){super(e,"Localization");}send(e,t,n,s){let i=this.endpoint(e,t);return super.send(e,t,n,{throttleKey:t.Locale?`${i}:${t.Locale}`:i,...s})}getLocalizationManifest(e){return this.send(Xr.GetLocalizationManifest,e,yf)}getLocalizationTable(e){return this.send(Xr.GetLocalizationTable,e,Rf)}};var bo=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(At.GetQuestDefinitions,e,Vs)}getUserQuestState(e){return this.send(At.GetUserQuestState,e,sc)}refreshQuestCycles(e){return this.send(At.RefreshQuestCycles,e,Qe)}claimQuestReward(e){return this.send(At.ClaimQuestReward,e,Da)}claimQuestRewardsBatch(e){return this.send(At.ClaimQuestRewardsBatch,e,oc)}claimMilestoneReward(e){return this.send(At.ClaimMilestoneReward,e,Ia)}claimMilestoneRewardsBatch(e){return this.send(At.ClaimMilestoneRewardsBatch,e,ac)}claimGroupCompletionReward(e){return this.send(At.ClaimGroupCompletionReward,e,ic)}addQuestProgress(e){return this.send(At.AddQuestProgress,e,rc)}};var xo=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(Rt.GetActiveEvents,e,Ei)}getDefinitions(e){return this.send(Rt.GetDefinitions,e,Oi)}getUserLteState(e){return this.send(Rt.GetUserLteState,e,pp)}grantTokens(e){return this.send(Rt.GrantTokens,e,O)}spendTokens(e){return this.send(Rt.SpendTokens,e,_a)}claimMilestone(e){return this.send(Rt.ClaimMilestone,e,Va)}claimMilestonesBatch(e){return this.send(Rt.ClaimMilestonesBatch,e,Fa)}claimAllMilestones(e){return this.send(Rt.ClaimAllMilestones,e,Fa)}spendTokensBatch(e){return this.send(Rt.SpendTokensBatch,e,hp)}grantTokensBatch(e){return this.send(Rt.GrantTokensBatch,e,dp)}};var Do=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ye.GetDefinitions,e,_i)}getLeaderboard(e){return this.send(Ye.GetLeaderboard,e,us)}getMyProgress(e){return this.send(Ye.GetMyProgress,e,Ui)}submitScore(e){return this.send(Ye.SubmitScore,e,Li)}submitScoreFromSource(e){return this.send(Ye.SubmitScoreFromSource,e,Li)}claimCycleReward(e){return this.send(Ye.ClaimCycleReward,e,Bi)}claimMilestone(e){return this.send(Ye.ClaimMilestone,e,Gi)}getFriendsLeaderboard(e){return this.send(Ye.GetFriendsLeaderboard,e,us)}getLeaderboardsBatch(e){return this.send(Ye.GetLeaderboardsBatch,e,gp)}getProgressBatch(e){return this.send(Ye.GetProgressBatch,e,Ni)}claimCycleRewardsBatch(e){return this.send(Ye.ClaimCycleRewardsBatch,e,yp)}claimMilestonesBatch(e){return this.send(Ye.ClaimMilestonesBatch,e,Rp)}submitScoresBatch(e){return this.send(Ye.SubmitScoresBatch,e,Cp)}claimAllRewardsBatch(e){return this.send(Ye.ClaimAllRewardsBatch,e,Sp)}getOverviewBatch(e){return this.send(Ye.GetOverviewBatch,e,bp)}};var Io=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Xt.GetDefinitions,e,ji)}getActiveSeason(e){return this.send(Xt.GetActiveSeason,e,Fi)}getUserState(e){return this.send(Xt.GetUserState,e,ja)}grantStatusTokens(e){return this.send(Xt.GrantStatusTokens,e,Pp)}claimTierReward(e){return this.send(Xt.ClaimTierReward,e,Wa)}claimTierRewardsBatch(e){return this.send(Xt.ClaimTierRewardsBatch,e,vp)}};var Po=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Sn.GetDefinitions,e,Of)}getUserState(e){return this.send(Sn.GetUserState,e,Ef)}activateTrial(e){return this.send(Sn.ActivateTrial,e,uo)}purchaseItemOrCurrency(e){return this.send(Sn.PurchaseWithResources,e,ke(uo))}purchaseRealMoney(e){return this.send(Sn.PurchaseRealMoney,e,uo)}};var vo=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(Je.GetCharacterDefinitions,e,Qi)}getUserCharacters(e){return this.send(Je.GetUserCharacters,e,Mp)}unlockCharacter(e){return this.send(Je.UnlockCharacter,e,ke(Qa))}upgradeStatLevel(e){return this.send(Je.UpgradeStatLevel,e,ke(Ha))}upgradeCharacterLevel(e){return this.send(Je.UpgradeCharacterLevel,e,ke(Ka))}equipItems(e){return this.send(Je.EquipItems,e,Op)}unequipItems(e){return this.send(Je.UnequipItems,e,Ep)}unequipAllCharacters(e){return this.send(Je.UnequipAllCharacters,e,qp)}unlockCharactersBatch(e){return this.send(Je.UnlockCharactersBatch,e,_p)}upgradeCharacterLevelsBatch(e){return this.send(Je.UpgradeCharacterLevelsBatch,e,Vp)}upgradeStatLevelsBatch(e){return this.send(Je.UpgradeStatLevelsBatch,e,Fp)}unlockSkin(e){return this.send(Je.UnlockSkin,e,ke(Up))}equipSkin(e){return this.send(Je.EquipSkin,e,Lp)}unequipSkin(e){return this.send(Je.UnequipSkin,e,Bp)}getCharacterSkins(e){return this.send(Je.GetCharacterSkins,e,Gp)}selectCharacter(e){return this.send(Je.SelectCharacter,e,Np)}};var Ao=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(Ut.CreateMatch,e,Fh)}updateMatch(e){return this.send(Ut.UpdateMatch,e,jh)}cancelMatch(e){return this.send(Ut.CancelMatch,e,Wh)}instantBattle(e){return this.send(Ut.InstantBattle,e,Hh)}saveStrategy(e){return this.send(Ut.SaveStrategy,e,Qe)}getMyMatches(e){return this.send(Ut.GetMyMatches,e,ul)}getAvailableMatches(e){return this.send(Ut.GetAvailableMatches,e,ul)}getDefinitions(e){return this.send(Ut.GetDefinitions,e,Jh)}};var dT={Arena:"Arena"},og=zod.z.string(),Kn={GetState:"GetState",RefreshOpponents:"RefreshOpponents",Attempt:"Attempt",ClaimMilestone:"ClaimMilestone"},mT=zod.z.object({TierID:zod.z.string().nullish(),MinPowerRatio:zod.z.number().nullish(),MaxPowerRatio:zod.z.number().nullish(),PointsOnWin:zod.z.number().nullish(),BotStatScale:zod.z.number().nullish()}).passthrough(),fT=zod.z.object({RuleID:zod.z.string().nullish(),Tiers:zod.z.array(mT).nullish(),RefreshCooldownSeconds:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),MaxCandidateReads:zod.z.number().nullish(),RevengeEnabled:zod.z.boolean().nullish(),RevengeCost:zod.z.number().nullish(),RevengePoints:zod.z.number().nullish(),WinReward:$.nullish()}).passthrough(),gT=zod.z.object({ChallengeID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),Mode:og.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AttemptCost:zod.z.number().nullish(),DailyAttemptLimit:zod.z.number().nullish(),Points:Mt.nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),ClaimMode:zod.z.string().nullish(),Arena:fT.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),yT=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:Se.nullish(),Challenges:zod.z.array(gT).nullish(),Ticket:Mt.nullish(),Gate:te.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ag=zod.z.object({Chains:zod.z.record(zod.z.string(),yT).nullish()}).passthrough(),lg=zod.z.object({TierID:zod.z.string().nullish(),OpponentID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Country:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BotStatScale:zod.z.number().nullish(),Defeated:zod.z.boolean().nullish()}).passthrough(),RT=zod.z.object({RevengeID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),AttackerUserID:zod.z.string().nullish(),AttackerName:zod.z.string().nullish(),AttackerAvatarUrl:zod.z.string().nullish(),AttackerPower:zod.z.number().nullish(),CreatedAtUtc:u.nullish(),Used:zod.z.boolean().nullish()}).passthrough(),CT=zod.z.object({AttemptID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),OpponentID:zod.z.string().nullish(),TierID:zod.z.string().nullish(),IsRevenge:zod.z.boolean().nullish(),Win:zod.z.boolean().nullish(),PointsGranted:zod.z.number().nullish(),TicketsSpent:zod.z.number().nullish(),AtUtc:u.nullish()}).passthrough(),ST=zod.z.object({Opponents:zod.z.array(lg).nullish(),Revenges:zod.z.array(RT).nullish(),RevengeCost:zod.z.number().nullish(),RevengePoints:zod.z.number().nullish(),RefreshAvailableAtUtc:u.nullish()}).passthrough(),rg=zod.z.object({ChallengeID:zod.z.string().nullish(),Mode:og.nullish(),InstanceKey:zod.z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),AttemptCost:zod.z.number().nullish(),AttemptsToday:zod.z.number().nullish(),DailyAttemptLimit:zod.z.number().nullish(),PointsEarned:zod.z.number().nullish(),ClaimedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Arena:ST.nullish()}).passthrough(),bT=zod.z.object({ChainID:zod.z.string().nullish(),Tickets:zod.z.number().nullish(),Active:rg.nullish(),Ended:zod.z.array(rg).nullish()}).passthrough(),xT=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),TicketsBurned:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),Converted:zod.z.number().nullish(),CarriedToInstanceKey:zod.z.string().nullish()}).passthrough(),iu=zod.z.object({Chains:zod.z.array(bT).nullish(),ServerTimeUtc:u.nullish(),Burns:zod.z.array(xT).nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough(),ug=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),Attempt:CT.nullish(),IsReplay:zod.z.boolean().nullish(),Battle:ds.nullish(),Opponent:lg.nullish(),Tickets:zod.z.number().nullish(),PointsEarned:zod.z.number().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough(),cg=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough();var To=class extends B{constructor(e){super(e,"Challenge");}getState(e){return this.send(Kn.GetState,e,iu)}refreshOpponents(e){return this.send(Kn.RefreshOpponents,e,iu)}attempt(e){return this.send(Kn.Attempt,e,ug)}claimMilestone(e){return this.send(Kn.ClaimMilestone,e,cg)}};var DT={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},pg=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),IT={None:"None",Min:"Min",Average:"Average",Max:"Max",Weighted:"Weighted"},PT=zod.z.enum(["None","Min","Average","Max","Weighted"]).catch("None"),vT={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},AT=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),TT={Clamp:"Clamp",Reject:"Reject"},wT=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),kT=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),zT=zod.z.object({Index:zod.z.number().nullish(),BurnedItemIDs:zod.z.array(zod.z.string()).nullish(),RolledCollectionID:zod.z.string().nullish(),UsedCollections:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Output:zt.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(kT).nullish()}),hg=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,Type:pg.nullish(),CraftID:zod.z.string(),CraftedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),InputRarity:zod.z.string().nullish(),OutputRarity:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish(),Results:zod.z.array(zT).nullish()}),MT=zod.z.object({CraftID:zod.z.string().nullish(),Type:pg.nullish(),CatalogID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),InputRarityID:zod.z.string().nullish(),OutputRarityID:zod.z.string().nullish(),RequiredItemCount:zod.z.number().nullish(),PriceOptions:me.nullish(),OutputLevelMode:PT.nullish(),OutputLevelWeightPower:zod.z.number().nullish(),InputSelection:AT.nullish(),OutputLevelOverflow:wT.nullish()}).passthrough(),ru=zod.z.object({Definitions:zod.z.record(zod.z.string(),MT).nullish()}).passthrough(),dg=zod.z.object({ServerTimeUtc:u.nullish(),CraftDefinitions:ru.nullish()}),wo={GetDefinitions:"GetDefinitions",Craft:"Craft"};var ko=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(wo.GetDefinitions,e,dg)}craft(e){return this.send(wo.Craft,e,ke(hg))}};var OT=2e5,zo=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,ke(Xi),{timeoutMs:OT,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Xi,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(We.GetDefinitions,e,eh)}generateText(e){return this.generate(We.GenerateText,e)}getText(e){return this.readGeneration(We.GetText,e)}generateImage(e){return this.generate(We.GenerateImage,e)}editImage(e){return this.generate(We.EditImage,e)}getImage(e){return this.readGeneration(We.GetImage,e)}generateVideo(e){return this.generate(We.GenerateVideo,e)}getVideo(e){return this.readGeneration(We.GetVideo,e)}generateAudio(e){return this.generate(We.GenerateAudio,e)}getAudio(e){return this.readGeneration(We.GetAudio,e)}generateMusic(e){return this.generate(We.GenerateMusic,e)}getMusic(e){return this.readGeneration(We.GetMusic,e)}generateFromTemplate(e){return this.generate(We.GenerateFromTemplate,e)}estimateTemplatePrice(e){return this.send(We.EstimateTemplatePrice,e,Xp,{throttleKey:`AI:EstimateTemplatePrice:${e.FeatureKey??""}:${JSON.stringify(e.Params??{})}`})}generateThreeD(e){return this.generate(We.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(We.GetThreeD,e)}listGenerations(e){return this.send(We.ListGenerations,e,Zp)}getGeneration(e){return this.readGeneration(We.GetGeneration,e)}};var ET={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},qT=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),mg=zod.z.object({}).passthrough().transform(r=>r),Qn=zod.z.object({CollectibleID:zod.z.string(),Rarity:zod.z.number().nullish(),IsSpecial:zod.z.boolean().nullish(),IsDuplicate:zod.z.boolean().nullish(),CollectionCurrencyConverted:zod.z.number().nullish()}),fg=zod.z.object({GrantedCollectibles:zod.z.array(Qn).nullish(),DuplicateCollectibles:zod.z.array(Qn).nullish(),CollectionCurrencyEarned:Q.nullish()}),gg=zod.z.object({CreditsConfirmation:Re.nullish(),OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(fg).nullish(),GrantedCollectibles:zod.z.array(Qn).nullish(),DuplicateCollectibles:zod.z.array(Qn).nullish(),CollectionCurrencyEarned:Q.nullish(),NewCollectionCurrencyBalance:Q.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),yg=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(fg).nullish(),GrantedCollectibles:zod.z.array(Qn).nullish(),DuplicateCollectibles:zod.z.array(Qn).nullish(),CollectionCurrencyEarned:Q.nullish(),NewCollectionCurrencyBalance:Q.nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Rg=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),ou=zod.z.object({SetID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish()}),Cg=zod.z.array(Ee(ou)),Sg=zod.z.object({Resources:O.nullish(),Inventory:K.nullish()}),UT=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:_e.nullish(),OfferedCollectibleID:zod.z.string().nullish(),OfferedCollectibleIsSpecial:zod.z.boolean().nullish(),ReceiverUserID:zod.z.string().nullish(),RequestedCollectibleID:zod.z.string().nullish(),RequestedCollectibleIsSpecial:zod.z.boolean().nullish(),Status:qT.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RespondedAtUtc:u.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),bg=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:u.nullish(),Resources:O.nullish()}),xg=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),Dg=zod.z.object({OfferID:zod.z.string(),ReceivedCollectibleID:zod.z.string().nullish(),ReceivedIsSpecial:zod.z.boolean().nullish(),SentCollectibleID:zod.z.string().nullish(),SentCollectibleIsSpecial:zod.z.boolean().nullish(),Transfer:zod.z.unknown().nullish()}),Ig=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),au=zod.z.object({Offers:zod.z.array(UT).nullish()}),LT=zod.z.object({CollectibleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rarity:zod.z.number().nullish(),HasSpecialVersion:zod.z.boolean().nullish(),SortOrder:zod.z.number().nullish()}).passthrough(),BT=zod.z.object({SetID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SortOrder:zod.z.number().nullish(),Collectibles:zod.z.array(LT).nullish(),SetCompletionReward:$.nullish()}).passthrough(),GT=zod.z.object({CollectionID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SeasonChainID:zod.z.string().nullish(),Sets:zod.z.array(BT).nullish(),GrandPrize:$.nullish()}).passthrough(),Pg=zod.z.object({BonusRewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),NT=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:me.nullish(),BonusRewardSlots:zod.z.array(Wn).nullish(),PityRules:zod.z.array(Hn).nullish(),Presets:Pg.nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectibleCount:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),GuaranteeMaxRarity:zod.z.boolean().nullish(),RarityWeights:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ColorTier:zod.z.number().nullish()}).passthrough(),_T=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),VT=zod.z.object({CollectionChestID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectionCurrencyCost:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),MinCollectibleCount:zod.z.number().nullish(),MaxCollectibleCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),BonusRewardSlots:zod.z.array(Wn).nullish(),PityRules:zod.z.array(Hn).nullish(),Presets:Pg.nullish(),Tier:zod.z.number().nullish()}).passthrough(),FT=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),jT=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),Mo=zod.z.object({Collections:zod.z.record(zod.z.string(),GT).nullish(),PackTypes:zod.z.record(zod.z.string(),NT).nullish(),CollectionChests:zod.z.array(VT).nullish(),DuplicateConversions:zod.z.array(_T).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(FT).nullish(),RewardPools:po.nullish(),Settings:jT.nullish()}).passthrough(),et={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var Oo=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(et.GetDefinitions,e,Mo)}getUserState(e){return this.send(et.GetUserState,e,mg)}openPack(e){return this.send(et.OpenPack,e,ke(gg))}openCollectionChest(e){return this.send(et.OpenCollectionChest,e,yg)}useCollectibleJoker(e){return this.send(et.UseCollectibleJoker,e,Rg)}claimSetReward(e){return this.send(et.ClaimSetReward,e,ou)}claimSetRewardsBatch(e){return this.send(et.ClaimSetRewardsBatch,e,Cg)}claimGrandPrize(e){return this.send(et.ClaimGrandPrize,e,Sg)}sendTradeOffer(e){return this.send(et.SendTradeOffer,e,bg)}cancelTradeOffer(e){return this.send(et.CancelTradeOffer,e,xg)}acceptTradeOffer(e){return this.send(et.AcceptTradeOffer,e,Dg)}declineTradeOffer(e){return this.send(et.DeclineTradeOffer,e,Ig)}getMyTradeOffers(e){return this.send(et.GetMyTradeOffers,e,au)}getIncomingTradeOffers(e){return this.send(et.GetIncomingTradeOffers,e,au)}};var Eo=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(wt.GetDefinitions,e,sr)}getActiveEvent(e){return this.send(wt.GetActiveEvent,e,sh)}getUserState(e){return this.send(wt.GetUserState,e,nr)}getGroupState(e){return this.send(wt.GetGroupState,e,el)}joinOrCreateGroup(e){return this.send(wt.JoinOrCreateGroup,e,el)}spin(e){return this.send(wt.Spin,e,ke(rh))}claimObjectReward(e){return this.send(wt.ClaimObjectReward,e,tl)}claimGrandPrize(e){return this.send(wt.ClaimGrandPrize,e,tl)}leaveGroup(e){return this.send(wt.LeaveGroup,e,oh)}};var qo=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(qt.GetDefinition,e,yh)}getUserState(e){return this.send(qt.GetUserState,e,Rh)}getActiveDeals(e){return this.send(qt.GetActiveDeals,e,or)}dismissDeal(e){return this.send(qt.DismissDeal,e,Sh)}executeNode(e){return this.send(qt.ExecuteNode,e,ke(Ch))}recordShow(e){return this.send(qt.RecordShow,e,bh)}claimMilestone(e){return this.send(qt.ClaimMilestone,e,xh)}claimMilestonesBatch(e){return this.send(qt.ClaimMilestonesBatch,e,Dh)}};var WT=zod.z.object({}).passthrough().transform(r=>r),HT=zod.z.object({FeatureKey:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Rate:zod.z.number().nullish(),Basis:zod.z.string().nullish(),SourceCurrencyID:zod.z.string().nullish(),TargetCurrencyID:zod.z.string().nullish(),MinSourceAmount:zod.z.number().nullish(),MaxRewardPerOperation:zod.z.number().nullish(),Limits:ve.nullish()}).passthrough(),lu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:$.nullish(),InviteRewards:zod.z.record(zod.z.string(),je).nullish(),SpendRewards:zod.z.array(HT).nullish(),Qualification:zod.z.object({}).passthrough().transform(r=>r).nullish()}).passthrough(),uu=zod.z.object({Pending:zod.z.boolean().nullish(),Qualified:zod.z.boolean().nullish(),Groups:zod.z.array(zod.z.object({GroupID:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Conditions:zod.z.array(zod.z.object({Type:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Current:zod.z.number().nullish(),Required:zod.z.number().nullish()}).passthrough()).nullish()}).passthrough()).nullish()}).passthrough(),vg=zod.z.object({ReferralDefinitions:lu.nullish()}).passthrough(),Ag=zod.z.object({Referral:WT.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:uu.nullish()}).passthrough(),Tg=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:uu.nullish()}).passthrough(),wg=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish(),QualificationPending:zod.z.boolean().nullish(),Qualification:uu.nullish()}).passthrough(),cu=zod.z.object({RewardID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),kg=Ot(cu),ln={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var Uo=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(ln.GetDefinitions,e,vg)}getUserState(e){return this.send(ln.GetUserState,e,Ag)}activateReferralCode(e){return this.send(ln.ActivateReferralCode,e,wg)}claimInviteReward(e){return this.send(ln.ClaimInviteReward,e,cu)}claimInviteRewardsBatch(e){return this.send(ln.ClaimInviteRewardsBatch,e,kg)}checkQualification(e){return this.send(ln.CheckQualification,e,Tg)}};var Lo=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(ht.GetDefinitions,e,qh)}getMessages(e){return this.send(ht.GetMessages,e,Uh)}getUnreadCount(e){return this.send(ht.GetUnreadCount,e,cr)}readMessages(e){return this.send(ht.ReadMessages,e,rl)}claimReward(e){return this.send(ht.ClaimReward,e,pr)}claimRewardsBatch(e){return this.send(ht.ClaimRewardsBatch,e,pr)}claimAll(e){return this.send(ht.ClaimAll,e,pr)}deleteMessages(e){return this.send(ht.DeleteMessages,e,rl)}sendGift(e){return this.send(ht.SendGift,e,Lh)}sendTransfer(e){return this.send(ht.SendTransfer,e,Bh)}getGiftStatus(e){return this.send(ht.GetGiftStatus,e,Gh)}};var Bo=class extends B{constructor(e){super(e,"Clan");}getDefinitions(e){return this.send(Be.GetDefinitions,e,pd)}getMyClans(e){return this.send(Be.GetMyClans,e,Yh)}searchClans(e){return this.send(Be.SearchClans,e,ml)}getRecommendedClans(e){return this.send(Be.GetRecommendedClans,e,ml)}getClan(e){return this.send(Be.GetClan,e,Xh)}getClanMembers(e){return this.send(Be.GetClanMembers,e,td)}getRankings(e){return this.send(Be.GetRankings,e,nd)}getApplications(e){return this.send(Be.GetApplications,e,fl)}getMyInvites(e){return this.send(Be.GetMyInvites,e,fl)}getClanLog(e){return this.send(Be.GetClanLog,e,sd)}getRequests(e){return this.send(Be.GetRequests,e,rd)}getGifts(e){return this.send(Be.GetGifts,e,od)}getRewards(e){return this.send(Be.GetRewards,e,ad)}getTreasury(e){return this.send(Be.GetTreasury,e,hd)}getProjects(e){return this.send(Be.GetProjects,e,dd)}getActivities(e){return this.send(Be.GetActivities,e,md)}getClanQuests(e){return this.send(Be.GetClanQuests,e,fd)}getCompetitions(e){return this.send(Be.GetCompetitions,e,gd)}getBracket(e){return this.send(Be.GetBracket,e,yd)}getDiplomacy(e){return this.send(Be.GetDiplomacy,e,Rd)}getRevenges(e){return this.send(Be.GetRevenges,e,Cd)}getLeague(e){return this.send(Be.GetLeague,e,Sd)}mutate(e,t){return this.send(e,t,cd)}};var Go=class extends B{constructor(e){super(e,"Avatar");}getDefinitions(e){return this.send(Vn.GetDefinitions,e,Rr)}getAvatars(e){return this.send(Vn.GetAvatars,e,xd)}getShop(e){return this.send(Vn.GetShop,e,Dd)}buyItem(e){return this.send(Vn.BuyItem,e,Id)}};var un={GetMyPartnership:"GetMyPartnership",Apply:"Apply",AcceptInvite:"AcceptInvite",GetStats:"GetStats",GetPayouts:"GetPayouts",ListCreators:"ListCreators"},KT={Off:"Off",InviteOnly:"InviteOnly",Moderated:"Moderated",Auto:"Auto"},QT={Applied:"Applied",Invited:"Invited",Active:"Active",Rejected:"Rejected",Removed:"Removed"},$T={ProgramOff:"PARTNER_PROGRAM_OFF",ApplicationsClosed:"PARTNER_APPLICATIONS_CLOSED",SignInRequired:"PARTNER_SIGN_IN_REQUIRED",AlreadyPartner:"PARTNER_ALREADY",AlreadyApplied:"PARTNER_ALREADY_APPLIED",Removed:"PARTNER_REMOVED",NoInvite:"PARTNER_NO_INVITE",BadInput:"PARTNER_BAD_INPUT",NotPartner:"PARTNER_NOT_FOUND",Conflict:"PARTNER_CONFLICT"},JT=zod.z.enum(["Off","InviteOnly","Moderated","Auto"]).catch("Off"),ZT=zod.z.enum(["Applied","Invited","Active","Rejected","Removed"]),pu=zod.z.record(zod.z.string(),zod.z.string()).nullish(),YT=zod.z.object({Mode:JT,DefaultSharePercent:zod.z.number().nullish(),Terms:pu,AskLinks:zod.z.boolean().nullish(),AskAbout:zod.z.boolean().nullish(),AskFollowers:zod.z.boolean().nullish(),CanApply:zod.z.boolean().nullish()}).passthrough(),XT=zod.z.object({PublicName:zod.z.string().nullish(),Links:zod.z.array(zod.z.string()).nullish(),About:zod.z.string().nullish(),Followers:zod.z.number().nullish(),SubmittedAt:zod.z.string().nullish()}).passthrough(),ew=zod.z.object({FeatureKey:zod.z.string(),Name:pu,PreviewUrl:zod.z.string().nullish(),PreviewType:zod.z.string().nullish()}).passthrough(),No=zod.z.object({Program:YT,Status:ZT.nullish(),SharePercent:zod.z.number().nullish(),Templates:zod.z.array(ew).nullish(),DecisionNote:zod.z.string().nullish(),Application:XT.nullish(),SignInRequired:zod.z.boolean().nullish()}).passthrough(),zg=zod.z.object({Days:zod.z.number(),ByDay:zod.z.array(zod.z.object({Day:zod.z.string(),Generations:zod.z.number(),Paid:zod.z.number(),PartnerCredits:zod.z.number()}).passthrough()).nullish(),ByTemplate:zod.z.array(zod.z.object({FeatureKey:zod.z.string(),Name:pu,Generations:zod.z.number(),Paid:zod.z.number(),PartnerCredits:zod.z.number()}).passthrough()).nullish(),Generations:zod.z.number(),PeriodCredits:zod.z.number(),AccruedCredits:zod.z.number(),PaidOutCredits:zod.z.number(),BalanceCredits:zod.z.number()}).passthrough(),Mg=zod.z.object({Payouts:zod.z.array(zod.z.object({Credits:zod.z.number(),Note:zod.z.string().nullish(),PaidAt:zod.z.string()}).passthrough()).nullish()}).passthrough(),tw=zod.z.object({Id:zod.z.string(),Name:zod.z.string(),Links:zod.z.array(zod.z.string()).nullish(),FeatureKeys:zod.z.array(zod.z.string()).nullish()}).passthrough(),Og=zod.z.object({Creators:zod.z.array(tw).nullish()}).passthrough();var _o=class extends B{constructor(e){super(e,"Partners");}getMyPartnership(e){return this.send(un.GetMyPartnership,e,No)}apply(e){return this.send(un.Apply,e,No)}acceptInvite(e){return this.send(un.AcceptInvite,e,No)}getStats(e){return this.send(un.GetStats,e,zg)}getPayouts(e){return this.send(un.GetPayouts,e,Mg)}listCreators(e){return this.send(un.ListCreators,e,Og)}};var Vo=class extends B{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(br.RequestAdPermit,e,Pd)}completeView(e){return this.send(br.CompleteView,e,vd)}};var Fo=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Pe.GetFriendsList,e,fs)}getIncomingRequests(e){return this.send(Pe.GetIncomingRequests,e,fs)}getOutgoingRequests(e){return this.send(Pe.GetOutgoingRequests,e,fs)}getRecommendedFriends(e){return this.send(Pe.GetRecommendedFriends,e,fs)}sendFriendRequest(e){return this.send(Pe.SendFriendRequest,e,gs)}acceptFriendRequest(e){return this.send(Pe.AcceptFriendRequest,e,gs)}declineFriendRequest(e){return this.send(Pe.DeclineFriendRequest,e,gs)}removeFriend(e){return this.send(Pe.RemoveFriend,e,gs)}getPlayerProfile(e){return this.send(Pe.GetPlayerProfile,e,Md)}getInbox(e){return this.send(Pe.GetInbox,e,Od)}markInboxSeen(e){return this.send(Pe.MarkInboxSeen,e,ys)}getInboxUnread(e){return this.send(Pe.GetInboxUnread,e,ys)}follow(e){return this.send(Pe.Follow,e,sn)}unfollow(e){return this.send(Pe.Unfollow,e,sn)}getFollowers(e){return this.send(Pe.GetFollowers,e,Pr)}getFollowing(e){return this.send(Pe.GetFollowing,e,Pr)}block(e){return this.send(Pe.Block,e,sn)}unblock(e){return this.send(Pe.Unblock,e,sn)}getBlocked(e){return this.send(Pe.GetBlocked,e,Pr)}react(e){return this.send(Pe.React,e,sn)}unreact(e){return this.send(Pe.Unreact,e,sn)}getMyReactions(e){return this.send(Pe.GetMyReactions,e,qd)}getEntityStates(e){return this.send(Pe.GetEntityStates,e,Ed)}addComment(e){return this.send(Pe.AddComment,e,vr)}editComment(e){return this.send(Pe.EditComment,e,vr)}deleteComment(e){return this.send(Pe.DeleteComment,e,Ld)}getComments(e){return this.send(Pe.GetComments,e,Ud)}report(e){return this.send(Pe.Report,e,Bd)}};var nw={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Dn=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),sw=zod.z.object({BoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:me.nullish(),Effect:Dn.nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),jo=zod.z.object({Schedule:Se.nullish(),Gate:te.nullish()}).passthrough(),hu=zod.z.object({Availability:J.nullish(),Effects:J.nullish()}).passthrough(),iw=zod.z.object({ScheduledBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Effects:zod.z.array(Dn).nullish(),Availability:jo.nullish(),Presets:hu.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rw=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(Dn).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ow=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Phases:zod.z.array(rw).nullish(),Availability:jo.nullish(),Presets:hu.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),aw=zod.z.object({TriggeredBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Sources:zod.z.array(ft).nullish(),Effects:zod.z.array(Dn).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:jo.nullish(),Presets:hu.nullish()}).passthrough(),lw=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),uw=zod.z.object({Effects:zod.z.array(Dn).nullish()}).passthrough(),cw=zod.z.object({Availability:zod.z.record(zod.z.string(),jo).nullish(),Effects:zod.z.record(zod.z.string(),uw).nullish()}).passthrough(),pw=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),lw).nullish()}).passthrough(),Wo=zod.z.object({Definitions:zod.z.record(zod.z.string(),sw).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),iw).nullish(),BoostChains:zod.z.record(zod.z.string(),ow).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),aw).nullish(),Settings:pw.nullish(),Presets:cw.nullish()}).passthrough(),Eg=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:Dn.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:u.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:u.nullish()}).passthrough();var qg=zod.z.object({ServerTimeUtc:u.nullish(),Active:zod.z.record(zod.z.string(),Eg).nullish()}),Ug=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:Eg.nullish(),Resources:O.nullish()}),hw={Scheduled:"Scheduled",Chain:"Chain"},dw=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),Effects:zod.z.array(Dn).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Lg=zod.z.object({ServerTimeUtc:u.nullish(),Windows:zod.z.array(dw).nullish()}),In={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Ho=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(In.GetDefinitions,e,Wo)}getActive(e){return this.send(In.GetActive,e,qg)}getActiveWindows(e){return this.send(In.GetActiveWindows,e,Lg)}activate(e){return this.send(In.Activate,e,ke(Ug))}cleanupExpired(e){return this.send(In.CleanupExpired,e,Qe)}};var Ko=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(kt.GetUserCustomDataDefinitions,e,Ir)}getMyUserCustomData(e){return this.send(kt.GetMyUserCustomData,e,Ad)}getPublicUserCustomDataOf(e){return this.send(kt.GetPublicUserCustomDataOf,e,Cl)}setPrivateData(e){return this.send(kt.SetPrivateData,e,Sl)}setPublicData(e){return this.send(kt.SetPublicData,e,Sl)}deleteKey(e){return this.send(kt.DeleteKey,e,Qe)}batchSet(e){return this.send(kt.BatchSet,e,Td)}batchDelete(e){return this.send(kt.BatchDelete,e,wd)}batchGetPublicUserCustomDataOf(e){return this.send(kt.BatchGetPublicUserCustomDataOf,e,kd)}};var mw={Static:"Static",Runtime:"Runtime"},fw={Public:"Public",Private:"Private"},gw=zod.z.enum(["Client","Server","System"]).catch("Client"),yw=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),Rw=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:gw.nullish(),ExpiresAt:u.nullish()}).passthrough(),Bg=zod.z.record(zod.z.string(),Rw),du=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:Bg.nullish(),Runtime:Bg.nullish(),NotModified:zod.z.boolean().nullish()}),Cw=zod.z.object({KeyID:zod.z.string(),Scope:zod.z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:zod.z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:yw.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Qo=zod.z.object({Keys:zod.z.record(zod.z.string(),Cw).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),Is={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var $o=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Is.GetTitleCustomDataDefinitions,e,Qo)}getPublicTitleData(e){return this.send(Is.GetPublicTitleData,e,du)}getPublicTitleDataKeys(e){return this.send(Is.GetPublicTitleDataKeys,e,du)}};var Gg=zod.z.object({Theme:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Radius:zod.z.number().nullish(),ButtonRadius:zod.z.number().nullish(),Outline:zod.z.number().nullish(),Background:zod.z.string().nullish(),MotionSpeed:zod.z.number().nullish(),MotionIntensity:zod.z.number().nullish(),Particles:zod.z.boolean().nullish(),SoundSet:zod.z.string().nullish()}).passthrough();var Sw={Mesh:"Mesh",Host:"Host"},mu=zod.z.enum(["Mesh","Host"]).catch("Mesh"),bw={ServerRelay:"ServerRelay",P2P:"P2P"},fu=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),xw={Public:"Public",Private:"Private"},Dw=zod.z.enum(["Public","Private"]).catch("Public"),Iw={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},Pw=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Ng=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),vw=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),_g=zod.z.object({SystemState:vw.nullish(),DefaultTopology:mu.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:fu.nullish(),AllowCreatorChatOverride:zod.z.boolean().nullish(),MaxPlayersPerRoom:zod.z.number().nullish(),RoomTtlSeconds:zod.z.number().nullish(),MaxRoomLifetimeSeconds:zod.z.number().nullish(),HeartbeatIntervalMs:zod.z.number().nullish(),MemberTimeoutMs:zod.z.number().nullish(),MaxSignalPayloadBytes:zod.z.number().nullish(),MaxChatTextLength:zod.z.number().nullish(),RoomLogCap:zod.z.number().nullish(),VoiceEnabled:zod.z.boolean().nullish(),RecordVoices:zod.z.boolean().nullish(),IceServers:zod.z.array(Ng).nullish()}).passthrough(),Aw=zod.z.object({UserID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),Ready:zod.z.boolean().nullish(),State:zod.z.record(zod.z.string(),zod.z.string()).nullish(),JoinedAt:zod.z.number().nullish(),IsHost:zod.z.boolean().nullish(),LastSeenMs:zod.z.number().nullish()}).passthrough(),Tw=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:mu.nullish(),ChatMode:fu.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),ww=zod.z.object({Seq:zod.z.number().nullish(),Type:Pw.nullish(),FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Payload:zod.z.string().nullish(),Ts:zod.z.number().nullish()}).passthrough(),Ps=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:mu.nullish(),ChatMode:fu.nullish(),Visibility:Dw.nullish(),Status:zod.z.string().nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),Members:zod.z.array(Aw).nullish(),IceServers:zod.z.array(Ng).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Vg=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),Fg=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),gu=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),jg=zod.z.object({Rooms:zod.z.array(Tw).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Wg=zod.z.object({Envelopes:zod.z.array(ww).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Jo=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),ot={CreateRoom:"CreateRoom",JoinRoom:"JoinRoom",LeaveRoom:"LeaveRoom",ListRooms:"ListRooms",GetRoom:"GetRoom",CloseRoom:"CloseRoom",Poll:"Poll",SendSignal:"SendSignal",SendChat:"SendChat",SetMemberState:"SetMemberState",ClaimHost:"ClaimHost",KickMember:"KickMember",UnbanMember:"UnbanMember"};var yu=zod.z.object({TitleCustomData:Qo.nullish(),Character:Qi.nullish(),Item:io.nullish(),Currency:ur.nullish(),Store:mi.nullish(),Lootbox:eu.nullish(),Quest:Vs.nullish(),TimedEvent:Oi.nullish(),Leaderboard:_i.nullish(),Season:ji.nullish(),Reward:nu.nullish(),Collection:Mo.nullish(),Craft:ru.nullish(),DealOffer:nl.nullish(),Premium:Zl.nullish(),TimedBoost:Wo.nullish(),CoopEvent:sr.nullish(),GameLoop:Or.nullish(),Match:cl.nullish(),Challenge:ag.nullish(),Experiment:hf.nullish(),Blockchain:Al.nullish(),Marketplace:Ul.nullish(),Multiplayer:_g.nullish(),UserCustomData:Ir.nullish(),Referral:lu.nullish(),Localization:ff.nullish(),Analytics:ef.nullish(),Social:Gd.nullish(),PlatformBridge:Nd.nullish(),GameSpec:zod.z.string().nullish(),Look:Gg.nullish(),Avatar:Rr.nullish()}).passthrough();var Pn={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Zo=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(Pn.GetTitlePublicConfiguration,e,yu)}getTitlePublicConfigurationExcept(e){return this.send(Pn.GetTitlePublicConfigurationExcept,e,yu)}getCurrencyDefinitions(e){return this.send(Pn.GetCurrencyDefinitions,e,ur)}getItemDefinitions(e){return this.send(Pn.GetItemDefinitions,e,io)}getServerTime(e){return this.send(Pn.GetServerTime,e,Qe)}};var Yo=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(He.GetGameLoops,e,Or)}getBoardDefinition(e,t=false){return this.send(He.GetBoardDefinition,e,Mr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(He.GetBoardDefinitionForLevel,e,Mr,{silent:t})}getUserBoardState(e){return this.send(He.GetUserBoardState,e,jd)}boardLoopRoll(e){return this.send(He.BoardLoopRoll,e,Zd)}boardLoopAttack(e){return this.send(He.BoardLoopAttack,e,em)}boardLoopRaid(e){return this.send(He.BoardLoopRaid,e,Il)}boardLoopRaidFast(e){return this.send(He.BoardLoopRaidFast,e,Il)}boardLoopBuild(e){return this.send(He.BoardLoopBuild,e,tm)}boardSpecialChoose(e){return this.send(He.BoardSpecialChoose,e,ke(nm))}boardSpecialApplyMultiplier(e){return this.send(He.BoardSpecialApplyMultiplier,e,sm)}boardRewardBoostApply(e){return this.send(He.BoardRewardBoostApply,e,Xd)}boardSpecialClaim(e){return this.send(He.BoardSpecialClaim,e,im)}getCommunityChestState(e){return this.send(He.GetCommunityChestState,e,am)}joinOrCreateCommunityChest(e){return this.send(He.JoinOrCreateCommunityChest,e,lm)}claimCommunityChestMilestone(e){return this.send(He.ClaimCommunityChestMilestone,e,Pl)}claimCommunityChestGrandPrize(e){return this.send(He.ClaimCommunityChestGrandPrize,e,Pl)}leaveCommunityChest(e){return this.send(He.LeaveCommunityChest,e,um)}};var kw={Live:"Live",Latest:"Latest",Specific:"Specific"},zw={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},Mw=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),Ow={None:"None",Disabled:"Disabled",NoActiveRevision:"NoActiveRevision",RevisionNotFound:"RevisionNotFound",InvalidFieldName:"InvalidFieldName",RateLimited:"RateLimited",HandlerNotFound:"HandlerNotFound",HandlerDisabled:"HandlerDisabled",Timeout:"Timeout",StatementCountExceeded:"StatementCountExceeded",StackOverflow:"StackOverflow",ApiCallLimitExceeded:"ApiCallLimitExceeded",JavaScriptException:"JavaScriptException",ExecutionError:"ExecutionError"},Ew=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),qw=zod.z.object({Level:Mw,Message:zod.z.string().nullish(),Data:en.nullish()}),Uw=zod.z.object({Error:Ew,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Kg=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:en.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(qw).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:Uw.nullish()}),Ru={Execute:"Execute"};var Xo=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(Ru.Execute,e,Kg)}};var ea=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(rt.GetDefinitions,e,Cm)}getUserState(e){return this.send(rt.GetUserState,e,Sm)}depositToken(e){return this.send(rt.DepositToken,e,bm)}depositNFT(e){return this.send(rt.DepositNFT,e,xm)}requestTokenWithdrawal(e){return this.send(rt.RequestTokenWithdrawal,e,Dm)}requestNFTWithdrawal(e){return this.send(rt.RequestNFTWithdrawal,e,Im)}getTransactionHistory(e){return this.send(rt.GetTransactionHistory,e,Pm)}retryWithdrawal(e){return this.send(rt.RetryWithdrawal,e,vm)}confirmWithdrawal(e){return this.send(rt.ConfirmWithdrawal,e,Am)}donateToDeveloper(e){return this.send(rt.DonateToDeveloper,e,zl)}donateToUsersPool(e){return this.send(rt.DonateToUsersPool,e,zl)}getPlayAccess(e){return this.send(rt.GetPlayAccess,e,ym)}confirmPlayAccess(e){return this.send(rt.ConfirmPlayAccess,e,rn)}};var ta=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Ge.GetDefinitions,e,km)}getGroupedOffers(e){return this.send(Ge.GetGroupedOffers,e,zm)}getOffersByItem(e){return this.send(Ge.GetOffersByItem,e,Ll)}getOffer(e){return this.send(Ge.GetOffer,e,Mm)}getBuyOrders(e){return this.send(Ge.GetBuyOrders,e,Ll)}getMyState(e){return this.send(Ge.GetMyState,e,Vr)}getHistory(e){return this.send(Ge.GetHistory,e,Em)}createListing(e){return this.send(Ge.CreateListing,e,Ss)}cancelListing(e){return this.send(Ge.CancelListing,e,St)}buy(e){return this.send(Ge.Buy,e,St)}marketBuy(e){return this.send(Ge.MarketBuy,e,St)}marketSell(e){return this.send(Ge.MarketSell,e,St)}createAuction(e){return this.send(Ge.CreateAuction,e,Ss)}placeBid(e){return this.send(Ge.PlaceBid,e,Om)}claimAuction(e){return this.send(Ge.ClaimAuction,e,St)}createBuyOrder(e){return this.send(Ge.CreateBuyOrder,e,Ss)}cancelBuyOrder(e){return this.send(Ge.CancelBuyOrder,e,St)}fillBuyOrder(e){return this.send(Ge.FillBuyOrder,e,St)}createDirectTrade(e){return this.send(Ge.CreateDirectTrade,e,Ss)}respondDirectTrade(e){return this.send(Ge.RespondDirectTrade,e,St)}cancelDirectTrade(e){return this.send(Ge.CancelDirectTrade,e,St)}claimBack(e){return this.send(Ge.ClaimBack,e,St)}};var na=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(ot.CreateRoom,e,Ps)}joinRoom(e){return this.send(ot.JoinRoom,e,Ps)}leaveRoom(e,t=false){return this.send(ot.LeaveRoom,e,gu,{keepalive:t})}listRooms(e){return this.send(ot.ListRooms,e,jg)}getRoom(e){return this.send(ot.GetRoom,e,Ps)}closeRoom(e){return this.send(ot.CloseRoom,e,gu)}poll(e){return this.send(ot.Poll,e,Wg)}sendSignal(e){return this.send(ot.SendSignal,e,Jo,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(ot.ClaimHost,e,Ps)}kickMember(e){return this.send(ot.KickMember,e,Vg)}unbanMember(e){return this.send(ot.UnbanMember,e,Fg)}sendChat(e){return this.send(ot.SendChat,e,Jo)}setMemberState(e){return this.send(ot.SetMemberState,e,Jo)}};var Lw={Free:"Free",Price:"Price",Holding:"Holding"},Cu=zod.z.enum(["Free","Price","Holding"]).catch("Free"),Bw={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},Gw=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),Nw={All:"All",Any:"Any"},_w=zod.z.enum(["All","Any"]).catch("All"),Vw={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},Fw=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),jw={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},Ww=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),Hw={Purchase:"Purchase",Free:"Free",Holding:"Holding"},$g=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),Kw={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},Qw={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},$w=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),Jw=zod.z.object({Type:zn.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),MinLevel:zod.z.number().nullish()}).passthrough(),Zw=zod.z.object({Requirements:zod.z.array(Jw).nullish(),Match:_w.nullish(),Mode:Gw.nullish()}).passthrough(),Yw=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Cu.nullish(),Price:he.nullish(),Holding:Zw.nullish()}).passthrough(),Xw=zod.z.object({AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxBytes:zod.z.number().nullish(),MaxCount:zod.z.number().nullish(),Required:zod.z.boolean().nullish()}).passthrough(),ek=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),Xw).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(Cu).nullish(),PricePolicy:_r.nullish(),PublishGate:te.nullish(),PublishFeeOptions:me.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),tk=zod.z.object({Allowed:zod.z.array(ms).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),nk=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),sk=zod.z.object({MaxTitleLength:zod.z.number().nullish(),MaxDescriptionLength:zod.z.number().nullish(),MaxTags:zod.z.number().nullish(),MaxTagLength:zod.z.number().nullish(),MaxMetadataKeys:zod.z.number().nullish(),MaxMetadataValueLength:zod.z.number().nullish(),MaxAccessOptions:zod.z.number().nullish(),ThumbnailMaxBytes:zod.z.number().nullish()}).passthrough(),ik=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Schedule:Se.nullish(),Gate:te.nullish(),Order:zod.z.number().nullish()}).passthrough(),rk=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:te.nullish(),Schedule:Se.nullish(),ContentTypes:zod.z.record(zod.z.string(),ek).nullish(),PricePolicy:_r.nullish(),Commission:ql.nullish(),HoldingPolicy:tk.nullish(),Moderation:nk.nullish(),Limits:sk.nullish(),Featured:zod.z.array(ik).nullish()}).passthrough(),ok=zod.z.object({Acquisitions:zod.z.number().nullish(),Downloads:zod.z.number().nullish(),Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),ReportCount:zod.z.number().nullish(),Remixes:zod.z.number().nullish()}).passthrough(),vn=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:_e.nullish(),Title:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Metadata:zod.z.record(zod.z.string(),zod.z.string()).nullish(),ThumbnailUrl:zod.z.string().nullish(),Visibility:Fw.nullish(),Access:zod.z.array(Yw).nullish(),Status:Ww.nullish(),ModerationNote:zod.z.string().nullish(),Stats:ok.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),PublishedAt:u.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),ak=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Cu.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),Jg=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Order:zod.z.number().nullish()}).passthrough(),Zg=zod.z.object({Definitions:rk.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish(),CanPublish:zod.z.record(zod.z.string(),zod.z.boolean()).nullish(),Collections:zod.z.array(Jg).nullish()}).passthrough(),sa=zod.z.object({Items:zod.z.array(vn).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Yg=zod.z.object({Content:vn.nullish(),AccessState:zod.z.array(ak).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Xg=zod.z.object({Collection:Jg.nullish(),Items:zod.z.array(vn).nullish()}).passthrough(),ey=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:_e.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(vn).nullish()}).passthrough(),Qg=zod.z.object({Role:zod.z.string().nullish(),Index:zod.z.number().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish(),ServerCopy:zod.z.boolean().nullish()}).passthrough(),ty=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(Qg).nullish(),ThumbnailUpload:Qg.nullish(),ExpiresAt:u.nullish()}).passthrough(),ny=zod.z.object({CreditsConfirmation:Re.nullish(),Content:vn.nullish(),Resources:O.nullish()}).passthrough(),Su=zod.z.object({Content:vn.nullish()}).passthrough(),sy=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:$g.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:_t.nullish(),Resources:O.nullish(),CommissionTaken:he.nullish()}).passthrough(),lk=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),iy=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:$w.nullish(),Files:zod.z.array(lk).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:u.nullish()}).passthrough(),uk=zod.z.object({ContentID:zod.z.string().nullish(),Source:$g.nullish(),OptionID:zod.z.string().nullish(),PricePaid:he.nullish(),AcquiredAt:u.nullish(),Content:vn.nullish()}).passthrough(),ry=zod.z.object({Licenses:zod.z.array(uk).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),tt={GetDefinitions:"GetDefinitions",Browse:"Browse",GetContent:"GetContent",GetCollection:"GetCollection",GetCreatorProfile:"GetCreatorProfile",BeginUpload:"BeginUpload",Publish:"Publish",UpdateContent:"UpdateContent",Unpublish:"Unpublish",GetMyContent:"GetMyContent",Acquire:"Acquire",GetDownload:"GetDownload",GetMyLicenses:"GetMyLicenses",GetMyFavorites:"GetMyFavorites"};var ia=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(tt.GetDefinitions,e,Zg)}browse(e){return this.send(tt.Browse,e,sa)}getContent(e){return this.send(tt.GetContent,e,Yg)}getCollection(e){return this.send(tt.GetCollection,e,Xg)}getCreatorProfile(e){return this.send(tt.GetCreatorProfile,e,ey)}beginUpload(e){return this.send(tt.BeginUpload,e,ty)}publish(e){return this.send(tt.Publish,e,ke(ny))}updateContent(e){return this.send(tt.UpdateContent,e,Su)}unpublish(e){return this.send(tt.Unpublish,e,Su)}getMyContent(e){return this.send(tt.GetMyContent,e,sa)}acquire(e){return this.send(tt.Acquire,e,sy)}getDownload(e){return this.send(tt.GetDownload,e,iy)}getMyLicenses(e){return this.send(tt.GetMyLicenses,e,ry)}getMyFavorites(e){return this.send(tt.GetMyFavorites,e,sa)}};var ra=class extends B{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,n,s){return this.send(e,t,n,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,n,s){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,n,{throttleKey:`${o}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,Nm,"defs")}get(e){return this.sendKeyed("Get",e,Gl,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Vm,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,Nl,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Fm,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,_l,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,_l,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,jm,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,Hm,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Wm,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,Km,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,_m,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Qm,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,Gl,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,Nl,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var oa=class{settings;emitter;host;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;credits;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;challenge;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;clan;avatar;partners;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.host=e.host??Ca(),this.settings=Pu(e,this.host),this.emitter=new Zn,this.clientPlatform=e.clientPlatform??this.host.getClientPlatform(),this.acquisition=new fn(this.host),this.acquisition.capture(),this.playtime=new os(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{}),this.host.supports.storePurchases&&this.purchase.restorePending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new $s({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e.fetch,debugLogging:this.settings.debugLogging,throttleMs:e.throttleMs,maxRequestsPerSecond:e.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new Xs(this.emitter),this.cache=new ti(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:n})=>{this.userService.noteStateVersions(t,n);}),this.authStore=new ni(this.host.storage,this.settings.titleID),this.api={authentication:new eo(this),user:new to(this),currency:new no(this),item:new ro(this),store:new oo(this),purchase:new co(this),lootbox:new mo(this),reward:new fo(this),quest:new bo(this),tutorial:new go(this),communityMarketing:new yo(this),chat:new Ro(this),push:new Co(this),localization:new So(this),timedEvent:new xo(this),leaderboard:new Do(this),season:new Io(this),premium:new Po(this),character:new vo(this),match:new Ao(this),challenge:new To(this),craft:new ko(this),ai:new zo(this),collection:new Oo(this),coopEvent:new Eo(this),dealOffer:new qo(this),referral:new Uo(this),mailbox:new Lo(this),clan:new Bo(this),avatar:new Go(this),partners:new _o(this),advertising:new Vo(this),social:new Fo(this),timedBoost:new Ho(this),userCustomData:new Ko(this),titleCustomData:new $o(this),title:new Zo(this),gameLoop:new Yo(this),cloudCode:new Xo(this),blockchain:new ea(this),marketplace:new ta(this),multiplayer:new na(this),workshop:new ia(this),dataCollections:new ra(this),analytics:new Zr(this),experiment:new Yr(this)},this.userService=new li(this),this.cache.attachState(this.userService),this.auth=new ii(this),this.currency=new ci(this),this.item=new pi(this),this.store=new gi(this),this.credits=new yi(this),this.purchase=new Ri(this),this.checkout=new Ci(this),this.lootbox=new Si(this),this.reward=new xi(this),this.quest=new Mi(this),this.tutorial=new Ii(this),this.communityMarketing=new Pi(this),this.chat=new Ti(this),this.push=new wi(this),this.localization=new zi(this),this.timedEvent=new qi(this),this.leaderboard=new Vi(this),this.season=new Wi(this),this.premium=new Hi(this),this.character=new $i(this),this.match=new Ji(this),this.challenge=new Zi(this),this.craft=new Yi(this),this.ai=new er(this),this.collection=new tr(this),this.coopEvent=new ir(this),this.dealOffer=new ar(this),this.referral=new lr(this),this.mailbox=new hr(this),this.clan=new gr(this),this.avatar=new Cr(this),this.partners=new Sr(this),this.ads=new xr(this),this.social=new Ar(this),this.timedBoost=new Tr(this),this.userCustomData=new wr(this),this.titleCustomData=new kr(this),this.title=new zr(this),this.gameLoop=new qr(this),this.cloudCode=new Ur(this),this.blockchain=new Br(this),this.marketplace=new Fr(this),this.multiplayer=new jr(this),this.workshop=new Wr(this),this.dataCollections=new Kr(this),this.analytics=new $r(this),this.experiments=new Jr(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.host.getFullURL(),RelatedEntityID:V()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var aa=class{ctx;constructor(e){this.ctx=new oa(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,n={}){let s=this.ctx.buildAuthedBaseRequest(),i=an(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(i,{...s,...n},zod.z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get challenge(){return this.ctx.challenge}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get clan(){return this.ctx.clan}get avatar(){return this.ctx.avatar}get partners(){return this.ctx.partners}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get host(){return this.ctx.host}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function pk(r){return new aa(r)}var oy="idos_sso",ay="state",bu="idos:sso:state",hk="https://idosgames.com/sso/",dk=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],mk=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function fk(){if(typeof window>"u")return false;let{origin:r}=window.location;return dk.includes(r)||mk.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function gk(){if(typeof window>"u")return null;let r=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!r)return null;let e=new URLSearchParams(r),t=e.get(oy);if(!t)return null;let n=e.get(ay)??"",s=bk();return Dk(e),xk(),s&&n!==s?null:{code:t,state:n}}function yk(r){if(typeof window>"u")return;let e=r.returnTo??Rk(),t=Ck();Sk(t);let n=new URL(r.ssoUrl??hk);n.searchParams.set("title",r.titleID),n.searchParams.set("return_to",e),n.searchParams.set("state",t),window.location.assign(n.toString());}function Rk(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function Ck(){let r=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(r);else for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*256);return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function Sk(r){try{window.sessionStorage.setItem(bu,r);}catch{}}function bk(){try{return window.sessionStorage.getItem(bu)}catch{return null}}function xk(){try{window.sessionStorage.removeItem(bu);}catch{}}function Dk(r){r.delete(oy),r.delete(ay);let e=r.toString(),{pathname:t,search:n}=window.location;window.history.replaceState(null,"",`${t}${n}${e?`#${e}`:""}`);}var Ik={EMAIL_SENDER_NOT_CONFIGURED:"Sign-in by e-mail is unavailable in this game right now. Try another way to sign in.",INVALID_VERIFICATION_CODE:"That code is not right. Check the e-mail and try again.",VERIFICATION_CODE_ATTEMPTS_EXCEEDED:"Too many wrong attempts. Ask for a new code.",INCORRECT_EMAIL_OR_PASSWORD:"Wrong e-mail or password.",INCORRECT_EMAIL:"That does not look like an e-mail address.",PASSWORD_LENGTH_INVALID:"The password must be 8 to 100 characters long.",TOO_MANY_FAILED_ATTEMPTS:"Too many attempts. Please try again a little later.",RATE_LIMIT_EXCEEDED:"Too many requests. Please try again in a moment.",APPLE_EMAIL_MISSING:"Apple did not share an e-mail address. Try again and allow it, or use another way to sign in.",INVALID_WALLET_SIGNATURE:"The signature does not match the wallet. Please try again.",WALLET_CHALLENGE_EXPIRED:"The request expired. Please try again.",WALLET_CHANGES_TOO_FREQUENT:"Too many wallets were changed this week. Try again in a few days.",WALLET_UNLINK_COOLDOWN:"This wallet was unlinked from another account less than 7 days ago. Try again after the 7 days.",PLAY_ACCESS_GUEST_DISABLED:"Guest play is off in this game. Sign in to link a crypto wallet.",PLAY_ACCESS_WALLET_LOGIN_ONLY:"This game can only be entered with a crypto wallet or your iDos Games account.",PLAY_ACCESS_WALLET_USED_BY_ANOTHER_ACCOUNT:"This wallet already plays with another account.",PLAY_ACCESS_WALLET_REQUIRED:"Link a crypto wallet to play.",PLAY_ACCESS_WALLET_NETWORK_NOT_GATED:"This wallet's network is not accepted here. Link a wallet of the required network.",PLAY_ACCESS_REQUIRED:"Check your balance to continue.",PLAY_ACCESS_CHECK_FAILED:"Could not check your balance right now. Please try again in a moment."};function Pk(r,e="Something went wrong. Please try again."){return r?Ik[r]??r:e}function vk(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function Ak(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function Tk(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function uy(r,e,t,n=1){if(!r)return e;let s=r.Base??e,i=Math.max(0,t-n),o;switch(r.Shape??"Flat"){case "PerStep":o=s+(r.PerStep??0)*i;break;case "PerStepRate":o=s*(1+(r.PerStepRate??0)*i);break;case "Geometric":o=s*Math.pow(1+(r.GrowthRate??0),i);break;case "Table":o=s*ly(r,t,1);break;case "TableAbsolute":o=ly(r,t,s);break;default:o=s;break}return Number.isNaN(o)?s:(r.MinResult!=null&&o<r.MinResult&&(o=r.MinResult),r.MaxResult!=null&&o>r.MaxResult&&(o=r.MaxResult),o)}function wk(r,e,t=1){return uy(r,1,e,t)}function kk(r){if(!r)return false;switch(r.Shape??"Flat"){case "PerStep":return (r.PerStep??0)!==0;case "PerStepRate":return (r.PerStepRate??0)!==0;case "Geometric":return (r.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return cy(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function zk(r){if(Number.isNaN(r)||r<=0)return 0;if(!Number.isFinite(r))return Number.MAX_SAFE_INTEGER;let e=Math.round(r);return Math.abs(r-e)<=1e-9*Math.max(1,Math.abs(r))?e:Math.ceil(r)}function cy(r){if(!r)return [];let e=[];for(let t of r)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function ly(r,e,t){let n=cy(r.Points);if(n.length===0)return t;let s=null,i=null,o=null;for(let p of n)(o===null||p.AtStep>o.AtStep)&&(o=p),p.AtStep<=e&&(s===null||p.AtStep>=s.AtStep)&&(s=p),p.AtStep>e&&(i===null||p.AtStep<i.AtStep)&&(i=p);if(s===null)return t;if(i===null){let p=r.TailGrowthRate??0;return p===0?o.Value:o.Value*Math.pow(1+p,e-o.AtStep)}switch(r.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(i.AtStep-s.AtStep);return s.Value+p*(i.Value-s.Value)}case "Geometric":{if(s.Value<=0||i.Value<=0){let m=(e-s.AtStep)/(i.AtStep-s.AtStep);return s.Value+m*(i.Value-s.Value)}let p=(e-s.AtStep)/(i.AtStep-s.AtStep);return s.Value*Math.pow(i.Value/s.Value,p)}default:return s.Value}}function py(r,e){return e?.BonusMode??r?.SetSettings?.BonusMode??"Cumulative"}function hy(r,e,t){if(!r?.Bonuses||e<=0)return [];let n=r.Bonuses.filter(s=>!!s&&(s.Pieces??0)>0&&(s.Pieces??0)<=e).sort((s,i)=>(s.Pieces??0)-(i.Pieces??0));if(n.length===0)return [];if(t==="HighestOnly"){let s=n[n.length-1]?.Pieces??0;return n.filter(i=>(i.Pieces??0)===s)}return n}function Mk(r,e){let t=e?.Sets,n=e?.Catalogs;if(!t||!r||!n||Object.keys(t).length===0)return [];let s=new Map;for(let[p,m]of Object.entries(r)){if(!p||p.startsWith("@")||!m?.ItemID)continue;let j=Ek(n,m.ItemID,m.CatalogID??null)?.Metadata?.CollectionID;!j||!(j in t)||s.set(j,(s.get(j)??0)+1);}let i=[...s.keys()].sort((p,m)=>p<m?-1:p>m?1:0),o=[];for(let p of i){let m=t[p];if(!m)continue;let g=s.get(p)??0,j=py(e,m);o.push({SetID:p,Definition:m,Pieces:g,Mode:j,ActiveTiers:hy(m,g,j)});}return o}function Ok(r,e){if(!r||!e)return 0;let t=0;for(let n of Object.values(r))for(let s of Object.values(n?.Items??{}))s?.Metadata?.CollectionID===e&&t++;return t}function Ek(r,e,t){if(t){let s=r[t]?.Items?.[e];if(s)return s}let n=null;for(let s of Object.values(r)){let i=s?.Items?.[e];if(i){if(n)return null;n=i;}}return n}var qk={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},xu=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),Uk={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Lk=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),Bk=zod.z.object({PlacementID:zod.z.string().nullish(),Type:xu.nullish(),Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),CreditsRewarded:zod.z.number().nullish(),AllowedProviderIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Gk=zod.z.object({DefaultCreditsPerView:zod.z.number().nullish(),MaxCreditsBalance:zod.z.number().nullish(),DailyCreditEarnCap:zod.z.number().nullish(),DailyViewCap:zod.z.number().nullish(),MinSecondsBetweenViews:zod.z.number().nullish()}).passthrough(),Nk=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),_k=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:Lk.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),Vk=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),Fk=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),jk=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),DisableInterstitials:zod.z.boolean().nullish(),DisableBanners:zod.z.boolean().nullish(),DisableAppOpen:zod.z.boolean().nullish()}).passthrough(),Wk=zod.z.object({RequirePersonalizedAdsConsent:zod.z.boolean().nullish(),RequireTrackingConsent:zod.z.boolean().nullish(),CurrentPolicyVersion:zod.z.string().nullish(),RegulatedRegions:zod.z.array(zod.z.string()).nullish()}).passthrough(),Hk=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),Kk=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:xu.nullish()}).passthrough(),Qk={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},$k=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),Jk=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:$k.nullish(),Enabled:zod.z.boolean().nullish(),Priority:zod.z.number().nullish(),AndroidAppID:zod.z.string().nullish(),IosAppID:zod.z.string().nullish(),WebAppID:zod.z.string().nullish(),Units:zod.z.record(zod.z.string(),Kk).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),Bk).nullish(),Providers:zod.z.record(zod.z.string(),Jk).nullish(),RewardedVideo:Gk.nullish(),Interstitial:Nk.nullish(),Banner:_k.nullish(),AppOpen:Vk.nullish(),FrequencyCapping:Fk.nullish(),PremiumAdReductions:zod.z.array(jk).nullish(),Consent:Wk.nullish(),Verification:Hk.nullish()}).passthrough();var Zk=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),Yk=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:u.nullish(),LastCompletedAt:u.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),Xk=zod.z.object({Date:u.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),ez=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:u.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),tz=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:u.nullish(),ConsentRevokedAt:u.nullish()}).passthrough(),nz=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:xu.nullish(),IssuedAt:u.nullish(),ExpiresAt:u.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),sz=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:u.nullish()}).passthrough();zod.z.object({Credits:Zk.nullish(),Placements:zod.z.record(zod.z.string(),Yk).nullish(),Daily:Xk.nullish(),Session:ez.nullish(),LastImpressionAt:u.nullish(),LastInterstitialAt:u.nullish(),LastRewardedAt:u.nullish(),LastAppOpenAt:u.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:u.nullish(),Consent:tz.nullish(),PendingRequests:zod.z.record(zod.z.string(),nz).nullish(),FraudFlags:sz.nullish(),UpdatedAt:u.nullish()}).passthrough();
2
- exports.AIAction=We;exports.AIErrorCode=JS;exports.AIGenerationStatus=yn;exports.AIModality=tn;exports.AVATAR_MAX_USERS=yr;exports.AVATAR_SHOP_PAGE_SIZE=CD;exports.AcquisitionCapture=fn;exports.AdProviderKind=Qk;exports.AdType=qk;exports.AdvertisingAction=br;exports.AnalyticsAction=Wl;exports.AnalyticsDropReason=bv;exports.AnalyticsEventNaming=jl;exports.AnalyticsLimits=Lt;exports.AttackOutcome=sI;exports.AuthType=Ue;exports.AuthenticationAction=Ke;exports.AutomaticEvent=on;exports.AvatarAction=Vn;exports.AvatarErrors=RD;exports.BannerPosition=Uk;exports.BlockchainAction=rt;exports.BlockchainNetworkType=QI;exports.BlockchainOperationCategory=hm;exports.BlockchainTransactionStatus=sP;exports.BlockchainTransactionType=YI;exports.BodyPart=Dx;exports.BoostWindowKind=hw;exports.BrowserFileStore=cn;exports.BrowserStorage=pn;exports.CLAN_DEFAULT_KIND_ID=mr;exports.ChallengeAction=Kn;exports.ChallengeMode=dT;exports.CharacterAction=Je;exports.ChatAction=st;exports.ChatAuthorType=BC;exports.ChatBlockedTermAction=UC;exports.ChatChannelType=zC;exports.ChatDirectAudience=EC;exports.ChatPartitioning=MC;exports.ChatReportReason=NC;exports.ClanAction=Be;exports.ClanCompetitionType=Wx;exports.ClanErrors=jx;exports.ClanInviteType=Vx;exports.ClanJoinMode=Nx;exports.ClanPermission=Fx;exports.ClanRelation=Hx;exports.ClientPlatform=Ne;exports.CloudCodeAction=Ru;exports.CloudCodeErrorCode=Ow;exports.CloudCodeLogLevel=zw;exports.CloudCodeRevisionSelection=kw;exports.CollectionAction=et;exports.CommissionSink=OP;exports.CommunityChestMemberStatus=GI;exports.CommunityChestStatus=BI;exports.CommunityCreatorStatus=tT;exports.CommunityMarketingAction=xn;exports.CommunityMetricKind=sT;exports.CommunityParticipationMode=XA;exports.CommunityPayoutCurrencyKind=nT;exports.ConversionRateMode=Qb;exports.CoopEventAction=wt;exports.CoopGroupStatus=pb;exports.CoopMemberStatus=hb;exports.CraftAction=wo;exports.CraftInputSelectionMode=vT;exports.CraftOutputLevelMode=IT;exports.CraftOutputLevelOverflow=TT;exports.CraftType=DT;exports.CreditsConfirmationStatus=ls;exports.CreditsError=uC;exports.CurrencyAction=hs;exports.CurrencyStatus=Kb;exports.CurrencyType=Dt;exports.CurveInterpolation=Zy;exports.CurveShape=$y;exports.CustomDataBucket=Wt;exports.CustomDataValueType=kD;exports.CustomDataWriter=AD;exports.DEFAULT_BASE_URL=Iu;exports.DataAccessMode=XP;exports.DataCollectionKind=$P;exports.DataCollectionSchemaMode=av;exports.DataCollectionsAction=gv;exports.DataCounterKind=sv;exports.DataFieldType=ZP;exports.DataFieldVisibility=YP;exports.DataOwnerDeletedPolicy=rv;exports.DataRefKind=tv;exports.DealComparisonOperator=kb;exports.DealNodeRuntimeStatus=xb;exports.DealNodeType=wb;exports.DealOfferAction=qt;exports.DealOfferActivationStatus=bb;exports.EVENT_NAME_PATTERN=Qr;exports.EnvelopeType=Iw;exports.EventTokenType=gy;exports.ExperimentAction=Ql;exports.ExperimentGoalKind=Mv;exports.FRIENDS_FROM_PLATFORM=KD;exports.FodderSelectionMode=Wv;exports.FodderValuationMode=Fv;exports.FriendActionStatus=OD;exports.FriendSource=ED;exports.GameLoopAction=He;exports.IDosGamesClient=aa;exports.IapProductType=uA;exports.IapPurchaseStatus=DA;exports.IapStoreValues=fy;exports.ItemAction=so;exports.ItemSetBonusMode=nA;exports.KycStatus=XI;exports.KycTier=tP;exports.LeaderboardAction=Ye;exports.LocalizationAction=Xr;exports.LocalizationMissingKeyMode=Lv;exports.LootboxAction=ho;exports.MAILBOX_COUNTER_CAP=mx;exports.MailboxAction=ht;exports.MailboxCategory=lx;exports.MailboxErrors=dx;exports.MailboxLetterSource=ux;exports.MailboxRewardModule=px;exports.MarketGoodsType=Nr;exports.MarketOfferStatus=MP;exports.MarketOfferType=zP;exports.MarketplaceAction=Ge;exports.MatchAction=Ut;exports.MatchStatus=Ix;exports.MemoryFileStore=An;exports.MemoryHost=ts;exports.MemoryStorage=Xn;exports.MultiplayerAction=ot;exports.MultiplayerChatMode=bw;exports.MultiplayerTopology=Sw;exports.NATIVE_HOST_GLOBAL=Au;exports.NATIVE_HOST_PROTOCOL=ua;exports.NativeHost=ss;exports.OFFER_NOT_IN_ROTATION=wC;exports.PLATFORM_AD_MESSAGES=fa;exports.PLATFORM_AD_PROVIDER=yl;exports.PLATFORM_BRIDGE_ACK=zu;exports.PLATFORM_CREDITS_CONFIRM_FINAL=ky;exports.PLATFORM_CREDITS_CONFIRM_MESSAGES=ga;exports.PLATFORM_ORIGINS=It;exports.PLATFORM_PAGE_UNAVAILABLE=Ls;exports.PLATFORM_SIGN_IN_MESSAGES=ha;exports.PLATFORM_TOPUP_MESSAGES=ma;exports.PLATFORM_TRADE_MESSAGES=ya;exports.PartnerErrors=$T;exports.PartnerProgramMode=KT;exports.PartnerStatus=QT;exports.PartnersAction=un;exports.PeerPayoutSource=ox;exports.PeerPayoutStatus=ax;exports.PlatformFriendsMode=$D;exports.PlatformProfileMode=QD;exports.PlayAccessMode=hP;exports.PlayerExperimentStatus=qv;exports.PlaytimeTracker=os;exports.PremiumAction=Sn;exports.PurchaseAction=bn;exports.PushAction=_n;exports.PushPermissionState=it;exports.PushTopic=eS;exports.PushTransport=YC;exports.QuestAction=At;exports.QuestObjectiveSource=lR;exports.QuestPrerequisiteMode=cR;exports.QuestStatus=rR;exports.RaidMode=tI;exports.ReferralAction=ln;exports.ResourceEntryType=ks;exports.RewardAction=Bt;exports.RewardWindowBoost=GA;exports.RoomVisibility=xw;exports.SITE_FRAME_HIDDEN_MESSAGE=Fu;exports.SKIN_ALREADY_OWNED=QS;exports.SKIN_SLOT=Ja;exports.ScheduleMode=yy;exports.SeasonAction=Xt;exports.SocialAction=Pe;exports.SocialContentStatus=ND;exports.SocialEntityType=LD;exports.SocialInboxVerb=_D;exports.SocialReactionKind=BD;exports.SocialReportReason=GD;exports.SpecialChoiceMode=nI;exports.StoreAction=Ft;exports.StoreRotationMode=hC;exports.StoreType=aA;exports.TimedBoostAction=In;exports.TimedBoostStackingPolicy=nw;exports.TimedEventAction=Rt;exports.TitleAction=Pn;exports.TitleCustomDataAction=Is;exports.TitleDataBucket=fw;exports.TitleDataScope=mw;exports.TradeOfferStatus=ET;exports.TransactionDirection=iP;exports.TutorialAction=gt;exports.TutorialBoardAction=PR;exports.TutorialFlowStatus=xR;exports.TutorialGateMode=Fy;exports.TutorialRestartPolicy=SR;exports.TutorialScriptModule=IR;exports.TutorialStepCompletionMode=RR;exports.TypedEmitter=Zn;exports.UserAction=bt;exports.UserCustomDataAction=kt;exports.WalletGateBalanceSource=uP;exports.WalletLinkType=JI;exports.WebHost=rs;exports.WorkshopAccessMode=Lw;exports.WorkshopAccessVia=Qw;exports.WorkshopAction=tt;exports.WorkshopContentStatus=jw;exports.WorkshopHoldingMatch=Nw;exports.WorkshopHoldingMode=Bw;exports.WorkshopLicenseSource=Hw;exports.WorkshopSort=Kw;exports.WorkshopVisibility=Vw;exports.activeSetTiers=hy;exports.askPlatformPage=Pt;exports.authErrorText=Pk;exports.beginSsoRedirect=yk;exports.claimedMilestoneIDs=Ak;exports.countSetMembers=Ok;exports.createDefaultHost=Ca;exports.createIDosGamesClient=pk;exports.cryptoShortfallFromError=Un;exports.curveMultiplier=wk;exports.defineView=QR;exports.describeUserAgent=nf;exports.effectiveSetMode=py;exports.evaluateCurve=uy;exports.getTelegramWebApp=Qt;exports.grantedPremiumTiers=Tk;exports.isAIGenerationTerminal=ps;exports.isCurveConfigured=kk;exports.isFail=Gy;exports.isMilestoneClaimed=vk;exports.isOk=By;exports.isPlatformParentOrigin=hn;exports.isReservedSlot=LS;exports.isSsoAvailable=fk;exports.normalizeBlockchainCategory=Lr;exports.parseAIErrorCode=ZS;exports.platformTradeUrl=Ra;exports.readNativeHostGlobal=ca;exports.readSsoCodeFromUrl=gk;exports.resolveItemSets=Mk;exports.roundAmount=zk;exports.shareFallbackText=ns;exports.where=Rv;exports.zPaymentProof=lC;exports.zPriceOption=hi;exports.zPriceOptions=me;
1
+ 'use strict';var zod=require('zod'),gn=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var gn__default=/*#__PURE__*/_interopDefault(gn);var Zn=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.off(e,t);}}once(e,t){let n=this.on(e,s=>{n(),t(s);});return n}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e));}emit(e,t){let n=this.listeners.get(e);if(n)for(let s of [...n])s(t);}removeAllListeners(){this.listeners.clear();}};function Du(r){return {get:e=>r.getString(e),set:(e,t)=>r.setString(e,t),remove:e=>r.remove(e)}}var Iu="https://api.idosgames.com";function Pu(r,e){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??Iu).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??Du(e.storage),locale:r.locale??e.getLanguage(),appVersion:r.appVersion??""}}function V(){return crypto.randomUUID()}var dy="idos-host-files",vs="files";function As(r){return new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error);})}function my(r){return r.slice().buffer}var An=class{map=new Map;async read(e){let t=this.map.get(e);return t?t.bytes.slice():null}async write(e,t){return this.map.set(e,{bytes:t.slice(),updatedAt:Date.now()}),true}async remove(e){this.map.delete(e);}async list(e=""){let t=[];for(let[n,s]of this.map)n.startsWith(e)&&t.push({key:n,size:s.bytes.byteLength,updatedAt:s.updatedAt});return t.sort((n,s)=>s.updatedAt-n.updatedAt)}},cn=class{db=null;fallback=new An;open(){return this.db||(this.db=(async()=>{try{if(typeof indexedDB>"u")return null;let e=indexedDB.open(dy,1);return e.onupgradeneeded=()=>{e.result.objectStoreNames.contains(vs)||e.result.createObjectStore(vs,{keyPath:"key"});},await As(e)}catch{return null}})()),this.db}async store(e){let t=await this.open();if(!t)return null;try{return t.transaction(vs,e).objectStore(vs)}catch{return null}}async read(e){let t=await this.store("readonly");if(!t)return this.fallback.read(e);try{let n=await As(t.get(e));return n?new Uint8Array(n.bytes):null}catch{return null}}async write(e,t){let n=await this.store("readwrite");if(!n)return this.fallback.write(e,t);try{let s={key:e,bytes:my(t),size:t.byteLength,updatedAt:Date.now()};return await As(n.put(s)),!0}catch{return false}}async remove(e){let t=await this.store("readwrite");if(!t)return this.fallback.remove(e);try{await As(t.delete(e));}catch{}}async list(e=""){let t=await this.store("readonly");if(!t)return this.fallback.list(e);try{let n=e&&typeof IDBKeyRange<"u"?IDBKeyRange.bound(e,e+"\uFFFF"):void 0,s=[];return await new Promise((i,o)=>{let p=t.openCursor(n);p.onerror=()=>o(p.error),p.onsuccess=()=>{let m=p.result;if(!m)return i();let g=m.value;g.key.startsWith(e)&&s.push({key:g.key,size:g.size,updatedAt:g.updatedAt}),m.continue();};}),s.sort((i,o)=>o.updatedAt-i.updatedAt)}catch{return []}}};function Yn(){return typeof document<"u"&&typeof document.createElement=="function"}function Ts(r={}){return Yn()?new Promise(e=>{let t=false,n=document.createElement("input");n.type="file",r.accept?.length&&(n.accept=r.accept.join(",")),n.multiple=r.multiple===true,n.style.display="none";let s=i=>{t||(t=true,n.remove(),e(i));};n.addEventListener("cancel",()=>s([])),n.addEventListener("change",()=>{let i=[...n.files??[]];Promise.all(i.map(async o=>{try{return {bytes:new Uint8Array(await o.arrayBuffer()),name:o.name,mime:o.type||"application/octet-stream"}}catch{return null}})).then(o=>s(o.filter(p=>p!==null)));}),document.body?.appendChild(n),n.click();}):Promise.resolve([])}var vu="idos_device_id",la="idos:platformSignIn:declined:",nt="UNAVAILABLE",Tn=Object.freeze({autoSignIn:false,signIn:false,rewardedAds:false,titleAds:false,storePurchases:false,creditsPayments:true,creditsConfirm:false,cryptoTopUp:false,tokenTrade:false,sceneCaptureRequests:false,share:false,vibration:false,sharedMemory:false,filePicker:false,pushNotifications:false}),Kt=class{storage;files;visible=true;visibilityListeners=new Set;linkListeners=new Set;constructor(e,t=new An){this.storage=e,this.files=t;}openTrade(e){return Promise.resolve({ok:false,error:nt})}buyProduct(e){return Promise.resolve({ok:false,error:nt})}finishPurchase(e,t){return Promise.resolve(false)}pendingPurchases(){return Promise.resolve([])}pickFiles(e){return Promise.resolve([])}requestPushToken(e){return Promise.resolve({error:nt})}getDeviceID(){let e=this.storage.getString(vu);return e||(e=this.newDeviceID(),this.storage.setString(vu,e)),e}newDeviceID(){return V()}setSignInDeclined(e,t){t?this.storage.setString(la+e,"1"):this.storage.remove(la+e);}isSignInDeclined(e){return this.storage.getString(la+e)==="1"}isVisible(){return this.visible}onVisibilityChange(e){return this.visibilityListeners.add(e),()=>{this.visibilityListeners.delete(e);}}onLinkOpened(e){return this.linkListeners.add(e),()=>{this.linkListeners.delete(e);}}emitLink(e){for(let t of [...this.linkListeners])try{t(e);}catch{}}setVisible(e){if(e!==this.visible){this.visible=e;for(let t of [...this.visibilityListeners])try{t(e);}catch{}}}};function ws(r){return (typeof r=="number"?[r]:[...r]).map(t=>Math.max(0,Math.round(t)))}var pn=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,t){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,t);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},Xn=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,t){this.map.set(e,t);}remove(e){this.map.delete(e);}};var Dt={Virtual:"Virtual",Crypto:"Crypto"},kn=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),ks={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},zn=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),Ne={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},zs=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),fy={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Ms=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),gy={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Challenge:"Challenge",ChallengePoints:"ChallengePoints"},Os=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season","Challenge","ChallengePoints"]).catch("TimedEvent"),yy={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},es=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),Ue={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};var ts=class extends Kt{id="memory";supports;clientPlatform;deviceId;constructor(e={}){let t="getString"in e?{storage:e}:e;super(t.storage??new Xn),this.supports=Object.freeze({...Tn,...t.supports}),this.clientPlatform=t.clientPlatform??Ne.Web,this.deviceId=t.deviceId??"memory-device";}setVisibleForTest(e){this.setVisible(e);}newDeviceID(){return this.deviceId}getPlatform(){return "Web"}getClientPlatform(){return this.clientPlatform}getFullURL(){return ""}getStartParameter(){return null}getReferrer(){return null}getTelegramInitDataRaw(){return null}getDeviceModel(){return "Memory"}getLanguage(){return ""}async signIn(){return {error:nt}}async showRewardedAd(){return {ok:false,error:nt}}async confirmCredits(){return {ok:false,error:nt}}async topUp(){return {ok:false,error:nt}}openInvoice(){}openUrl(){}async share(){return "unavailable"}async shareFile(){return "unavailable"}async copyText(){return false}vibrate(){}createWorker(){return null}};function ns(r){return [r.text,r.url].filter(e=>!!e).join(" ")}function Es(){return globalThis.crossOriginIsolated===true&&typeof SharedArrayBuffer<"u"}function qs(r,e={}){if(typeof Worker>"u")return null;try{let t=typeof location<"u"?location.href:void 0,n=t?new URL(r,t):new URL(r),s={type:"module",name:e.name};if(n.protocol==="blob:"||n.protocol==="data:"||!t||n.origin===new URL(t).origin)return new Worker(n.href,s);let i=URL.createObjectURL(new Blob([`import ${JSON.stringify(n.href)};`],{type:"text/javascript"}));return new Worker(i,s)}catch{return null}}var ua=1,Au="__IDOS_HOST__";function ca(){let r=globalThis[Au];return !r||typeof r!="object"||r.protocol!==1||typeof r.post!="function"?null:r}var Ry={signIn:30*6e4,showRewardedAd:5*6e4,confirmCredits:10*6e4,topUp:15*6e4,openInvoice:3e4,openUrl:3e4,share:10*6e4,shareFile:10*6e4,copyText:3e4,vibrate:3e4,buyProduct:30*6e4,finishPurchase:6e4,pendingPurchases:6e4,requestPushToken:10*6e4};function Cy(r){switch((r??"").toLowerCase()){case "android":return Ne.Android;case "ios":return Ne.Ios;case "web":return Ne.Web;default:return Ne.Unknown}}var ss=class extends Kt{id;supports;shell;pending=new Map;nextId=1;constructor(e,t=new pn){super(t,new cn),this.shell=e,this.id=`native:${e.id??"unknown"}`;let n=e.capabilities??{},s=i=>n[i]??Tn[i];this.supports=Object.freeze({autoSignIn:s("autoSignIn"),signIn:s("signIn")||s("autoSignIn"),rewardedAds:s("rewardedAds")||s("titleAds"),titleAds:s("titleAds"),storePurchases:s("storePurchases"),creditsPayments:s("creditsPayments"),creditsConfirm:s("creditsConfirm"),cryptoTopUp:s("cryptoTopUp"),tokenTrade:false,sceneCaptureRequests:false,share:s("share"),vibration:s("vibration"),sharedMemory:Es(),filePicker:Yn(),pushNotifications:s("pushNotifications")}),e.receive=i=>this.receive(i),e.info?.visible===false&&this.setVisible(false);}receive(e){let t;try{t=JSON.parse(e);}catch{return}if(!(!t||t.v!==1)){if(t.kind==="response"&&typeof t.id=="string"){let n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id),clearTimeout(n.timer),n.resolve(t.ok===true?{ok:true,result:t.result??{}}:{ok:false,error:typeof t.error=="string"?t.error:"FAILED"});return}if(t.kind==="event"&&t.name==="visibility"){let n=t.data;typeof n?.visible=="boolean"&&this.setVisible(n.visible);return}if(t.kind==="event"&&t.name==="link"){let n=t.data;typeof n?.url=="string"&&n.url&&this.emitLink(n.url);}}}request(e,t){let n=`r${this.nextId++}`,s={v:1,kind:"request",id:n,method:e,params:t};return new Promise(i=>{let o=setTimeout(()=>{this.pending.delete(n),i({ok:false,error:"TIMEOUT"});},Ry[e]);this.pending.set(n,{resolve:i,timer:o});try{this.shell.post(JSON.stringify(s));}catch{clearTimeout(o),this.pending.delete(n),i({ok:false,error:"UNAVAILABLE"});}})}notify(e,t){this.request(e,t);}newDeviceID(){return this.shell.info?.deviceId||super.newDeviceID()}getPlatform(){return this.getClientPlatform()===Ne.Ios?"iOS":this.getClientPlatform()}getClientPlatform(){return Cy(this.shell.clientPlatform)}getFullURL(){return this.shell.info?.launchUrl??""}getStartParameter(){return this.shell.info?.startParameter??null}getReferrer(){return null}getTelegramInitDataRaw(){return null}getDeviceModel(){return this.shell.info?.deviceModel||this.id}getLanguage(){return this.shell.info?.language||""}async signIn(e){if(!this.supports.signIn)return {error:"UNAVAILABLE"};let t=await this.request("signIn",{titleID:e});if(!t.ok)return {error:t.error};let{code:n,ticket:s}=t.result;return typeof s=="string"&&s.length>0?{ticket:s}:typeof n=="string"&&n.length>0?{code:n}:{error:"no_code"}}async showRewardedAd(e){if(!this.supports.rewardedAds)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("showRewardedAd",e);return t.ok?{ok:true,via:t.result.via==="unit"?"unit":"ad"}:{ok:false,error:t.error}}async confirmCredits(e){if(!this.supports.creditsConfirm)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("confirmCredits",e);return t.ok?{ok:true}:{ok:false,error:t.error}}async topUp(e){if(!this.supports.cryptoTopUp)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("topUp",e);return t.ok?{ok:true}:{ok:false,error:t.error}}openInvoice(e){this.notify("openInvoice",{url:e});}async buyProduct(e){if(!this.supports.storePurchases)return {ok:false,error:"UNAVAILABLE"};let t=await this.request("buyProduct",e);if(!t.ok)return {ok:false,error:t.error};let n=t.result.receipt;return n&&typeof n.receipt=="string"&&n.receipt?{ok:true,receipt:n}:{ok:false,error:"FAILED"}}async finishPurchase(e,t){return this.supports.storePurchases?(await this.request("finishPurchase",{receipt:e,consumable:t})).ok:false}async pendingPurchases(){if(!this.supports.storePurchases)return [];let e=await this.request("pendingPurchases",{});return !e.ok||!Array.isArray(e.result.receipts)?[]:e.result.receipts.filter(t=>t&&typeof t.receipt=="string"&&t.receipt)}async requestPushToken(e){if(!this.supports.pushNotifications)return {error:"UNAVAILABLE"};let t=await this.request("requestPushToken",{prompt:e.prompt===true});if(!t.ok)return {error:t.error};let{token:n,transport:s}=t.result;return typeof n!="string"||!n?{error:"UNAVAILABLE"}:{token:n,transport:s==="Apns"?"Apns":"Fcm"}}openUrl(e){this.notify("openUrl",{url:e});}async share(e){if(!this.supports.share)return await this.copyText(ns(e))?"copied":"unavailable";let t=await this.request("share",e);return t.ok?t.result.outcome??"shared":t.error==="CANCELLED"?"cancelled":"unavailable"}pickFiles(e){return Ts(e)}async shareFile(e){let t=await this.request("shareFile",{name:e.name,mime:e.mime,data:Sy(e.bytes)});return t.ok?t.result.outcome??"shared":t.error==="CANCELLED"?"cancelled":"unavailable"}async copyText(e){return (await this.request("copyText",{text:e})).ok}vibrate(e){this.supports.vibration&&this.notify("vibrate",{pattern:ws(e)});}createWorker(e,t){return qs(e,t)}};function Sy(r){let e="";for(let n=0;n<r.length;n+=32768)e+=String.fromCharCode(...r.subarray(n,n+32768));return btoa(e)}function Qt(){return globalThis.Telegram?.WebApp??null}function wu(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return Tu(e);let t=r.cordova?.platformId;return t?Tu(t):r.navigator?.userAgent??""?Ne.Web:Ne.Unknown}function Tu(r){let e=r.toLowerCase();return e==="android"?Ne.Android:e==="ios"?Ne.Ios:e==="web"?Ne.Web:Ne.Unknown}var It=["https://idosgames.com","https://www.idosgames.com"],Us="https://platform.idosgames.com",ku=/^[a-z0-9]{8}-preview\.idos\.games$/;function pa(r){return r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r.endsWith(".localhost")}function is(){if(typeof window>"u")return false;let r=window.location.hostname.toLowerCase();return ku.test(r)?true:pa(r)&&globalThis.__IDOS_PREVIEW__!=null}function hn(r){if(typeof window<"u"&&ku.test(window.location.hostname.toLowerCase()))return r===Us;if(It.includes(r))return true;if(typeof window>"u"||!pa(window.location.hostname))return false;try{return pa(new URL(r).hostname)}catch{return false}}var zu="IDOS_PLATFORM_WALLET_ACK",Ls="PLATFORM_WALLET_UNAVAILABLE",by=5e3,xy=18e4;function Dy(){if(hn(Us))return [Us];let r=[...It],e=window.location.ancestorOrigins?.[0];return e&&!r.includes(e)&&hn(e)&&r.push(e),r}function Iy(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Pt(r,e,t,n={}){let s={ok:false,error:Ls,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(s);let i=window.parent;if(!i)return Promise.resolve(s);let o=Iy(),p=n.answerTimeoutMs??xy;return new Promise(m=>{let g=false,j,pe=fe=>{g||(g=true,window.removeEventListener("message",Ae),clearTimeout(j),m(fe));},Ae=fe=>{if(!hn(fe.origin))return;let xe=fe.data;if(!(!xe||xe.requestId!==o)){if(xe.type===zu){clearTimeout(j),j=setTimeout(()=>pe({ok:false,error:"TIMEOUT",data:{}}),p);return}xe.type===e&&pe({ok:xe.ok===true,error:typeof xe.error=="string"?xe.error:void 0,data:xe});}};j=setTimeout(()=>pe(s),by),window.addEventListener("message",Ae);for(let fe of Dy())try{i.postMessage({type:r,requestId:o,...t},fe);}catch{}})}var ha={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},Py=30*6e4;function Mu(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(is())return false;let r=window.location.ancestorOrigins?.[0];if(r&&!It.includes(r))try{let e=new URL(r).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}function da(){if(typeof window>"u"||!is())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function Ou(r){let e=await Pt(ha.request,ha.response,{titleID:r,supports:["pgs"]},{answerTimeoutMs:Py}),t=e.data.ticket;if(e.ok&&typeof t=="string"&&t.length>0)return {ticket:t};let n=e.data.code;return e.ok&&typeof n=="string"&&n.length>0?{code:n}:{error:e.error??"no_code"}}var ma={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},vy=15*6e4,Ay=/^[a-z0-9]{8}-preview\.idos\.games$/;function Mn(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !Ay.test(window.location.hostname.toLowerCase())}async function Eu(r){let e=await Pt(ma.request,ma.response,{titleID:r.titleID,userID:r.userID,currencyID:r.currencyID,amount:r.amount},{answerTimeoutMs:vy});return e.ok?{ok:true}:{ok:false,error:e.error}}var fa={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},Ty=5*6e4;function qu(){return Mn()}async function Uu(r){let e=await Pt(fa.request,fa.response,{titleID:r.titleID,userID:r.userID,requestID:r.requestID,placementID:r.placementID,adUnitID:r.adUnitID??null},{answerTimeoutMs:Ty});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var ga={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},wy=10*6e4,ky=["DECLINED","NOT_ENOUGH_CREDITS"];function Lu(){let r=globalThis.navigator?.userAgent??"";if(!/\biDosGamesApp\/(?:player|studio)\//.test(r))return true;let e=/\biDosGamesPlatform\/(ios|android)\b/.exec(r);return (e?e[1]:/\bAndroid\b/.test(r)?"android":"ios")!=="ios"}function Bu(){return Mn()}async function Gu(r){let e=await Pt(ga.request,ga.response,{titleID:r.titleID,confirmationID:r.confirmationID},{answerTimeoutMs:wy});return e.ok?{ok:true}:{ok:false,error:e.error}}var ya={request:"IDOS_PLATFORM_TRADE_REQUEST",response:"IDOS_PLATFORM_TRADE_RESPONSE"};function Nu(r){return typeof r=="string"&&/^\d{1,15}(\.\d{1,18})?$/.test(r)&&Number(r)>0}function Ra(r,e,t){let n=`trade=${e}${t?`&amount=${encodeURIComponent(t)}`:""}`;return `${It[0]}/app/${encodeURIComponent(r)}?${n}`}async function _u(r){let e=await Pt(ya.request,ya.response,{titleID:r.titleID,side:r.side,amount:r.amount??null});return e.ok?{ok:true}:{ok:false,error:e.error}}var Fu="IDOS_APP_FRAME_HIDDEN";function dn(){return globalThis.navigator??null}function Bs(){return typeof window<"u"}function Vu(){if(!Bs())return false;try{return window.self!==window.top}catch{return true}}var rs=class extends Kt{id;supports;hiddenBySite=false;documentHidden=false;constructor(e=new pn){if(super(e,new cn),!Bs()){this.id="web",this.supports=Tn;return}let t=dn(),n=Mu();this.supports=Object.freeze({autoSignIn:n,signIn:n||da(),rewardedAds:qu(),titleAds:false,storePurchases:false,creditsPayments:Lu(),creditsConfirm:Bu(),cryptoTopUp:Mn(),tokenTrade:!is(),sceneCaptureRequests:Vu(),share:typeof t?.share=="function",vibration:typeof t?.vibrate=="function",sharedMemory:Es(),filePicker:Yn(),pushNotifications:false}),this.id=Qt()?"telegram":da()?"preview":this.supports.cryptoTopUp?"site":"web",this.watchVisibility(),window.addEventListener("hashchange",()=>this.emitLink(window.location.href));}watchVisibility(){typeof document<"u"&&(this.documentHidden=document.visibilityState==="hidden",document.addEventListener("visibilitychange",()=>{this.documentHidden=document.visibilityState==="hidden",this.update();})),Vu()&&window.addEventListener("message",e=>{let t=e.data;!t||t.type!==Fu||hn(e.origin)&&(this.hiddenBySite=t.hidden===true,this.update());}),this.update();}update(){this.setVisible(!this.documentHidden&&!this.hiddenBySite);}getPlatform(){return Qt()?.platform??"Web"}getClientPlatform(){return wu()}getFullURL(){return Bs()?window.location.href:""}getStartParameter(){let e=Qt()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){return typeof document>"u"?null:document.referrer||null}getTelegramInitDataRaw(){let e=Qt()?.initData;return e&&e.length>0?e:null}getDeviceModel(){return dn()?.userAgent||"Web"}getLanguage(){return dn()?.language||""}async signIn(e){return this.supports.signIn?Ou(e):{error:nt}}async showRewardedAd(e){return this.supports.rewardedAds?Uu(e):{ok:false,error:nt}}async confirmCredits(e){return this.supports.creditsConfirm?Gu(e):{ok:false,error:nt}}async topUp(e){return this.supports.cryptoTopUp?Eu(e):{ok:false,error:nt}}async openTrade(e){if(!this.supports.tokenTrade)return {ok:false,error:nt};let t=e?.side,n=e?.amount;if(!e?.titleID||t!=="buy"&&t!=="sell"||n!=null&&n!==""&&!Nu(n))return {ok:false,error:"BAD_REQUEST"};if(this.supports.cryptoTopUp){let s=await _u({titleID:e.titleID,side:t,amount:n||null});return s.ok?{ok:true}:{ok:false,error:s.error===Ls?nt:s.error}}return this.openUrl(Ra(e.titleID,t,n||null)),{ok:true}}openInvoice(e){let t=Qt();if(t?.openInvoice){t.openInvoice(e);return}this.openUrl(e);}openUrl(e){let t=Qt();if(t?.openTelegramLink&&/^https:\/\/t\.me\//i.test(e)){t.openTelegramLink(e);return}Bs()&&window.open(e,"_blank","noopener");}async share(e){let t=dn();if(t?.share)try{return await t.share({url:e.url||void 0,title:e.title,text:e.text}),"shared"}catch(n){if(n?.name==="AbortError")return "cancelled"}return await this.copyText(ns(e))?"copied":"unavailable"}pickFiles(e){return Ts(e)}async shareFile(e){if(typeof document>"u"||typeof Blob>"u")return "unavailable";let t=new Blob([e.bytes],{type:e.mime}),n=dn();if(typeof File<"u"&&n?.share&&n.canShare){let i=new File([t],e.name,{type:e.mime});if(n.canShare({files:[i]}))try{return await n.share({files:[i],title:e.name}),"shared"}catch(o){if(o?.name==="AbortError")return "cancelled"}}let s=document.createElement("a");return s.href=URL.createObjectURL(t),s.download=e.name,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(s.href),3e4),"saved"}async copyText(e){let t=dn();if(t?.clipboard)try{return await t.clipboard.writeText(e),!0}catch{}return zy(e)}vibrate(e){try{dn()?.vibrate?.(ws(e));}catch{}}createWorker(e,t){return qs(e,t)}};function zy(r){if(typeof document>"u"||!document.body)return false;let e=document.createElement("textarea");e.value=r,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();let t=false;try{t=document.execCommand("copy");}catch{t=false;}return e.remove(),t}function Ca(){let r=ca();return r?new ss(r):typeof window>"u"?new ts:new rs}var Sa="idos_acq",ju=["gclid","fbclid","ttclid","msclkid","yclid"],My=["ref","r"],Oy=["ref_","ref-","ref=","r_","r-"];var fn=class{constructor(e){this.host=e;}host;capture(){let e=this.readFromEnvironment();Ey(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),n=t?{...t.signal}:{},s=Ly(this.host.getDeviceModel());return s&&(n.OsVersion=s),e&&(n.AppVersion=e),Object.keys(n).length>0?n:void 0}clear(){this.host.storage.remove(Sa);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let n=Ku(Hu(t));if(n)return n}return Gs(t)}readFromEnvironment(){let e={},t=Hu(this.host.getFullURL());mn(e,"UtmSource",t.get("utm_source")),mn(e,"UtmMedium",t.get("utm_medium")),mn(e,"UtmCampaign",t.get("utm_campaign")),mn(e,"UtmTerm",t.get("utm_term")),mn(e,"UtmContent",t.get("utm_content")),mn(e,"ClaimToken",t.get("idos_click"));for(let g of ju){let j=t.get(g);if(j){e.ClickID=j;break}}let n=this.host.getStartParameter()??"",s=Uy(n);if(s){for(let g of qy)mn(e,g,s.get(Qu[g])??null);for(let g of ju){let j=s.get(g);if(j){e.ClickID=j;break}}}let i=Gs(s?s.get("ref")??s.get("r")??"":n),o=Ku(t),p=i||o;p&&(e.ReferralCode=p,e.ChannelHint=i?"telegram":"query");let m=this.host.getReferrer();return m&&(e.Referrer=m),e}read(){try{let e=this.host.storage.getString(Sa);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.host.storage.setString(Sa,JSON.stringify(e));}catch{}}};function Ey(r){return !!(r.UtmSource||r.UtmMedium||r.UtmCampaign||r.ClickID||r.Referrer||r.ReferralCode||r.ClaimToken)}function mn(r,e,t){t&&(r[e]=t);}var Wu="a1_",Qu={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},qy=Object.keys(Qu);function Uy(r){let e=(r||"").trim();if(!e.startsWith(Wu))return null;let t=e.slice(Wu.length);if(!t)return null;try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(n+"=".repeat((4-n.length%4)%4)),i=Uint8Array.from(s,m=>m.charCodeAt(0)),o=new TextDecoder().decode(i),p=new URLSearchParams(o);return [...p.keys()].length>0?p:null}catch{return null}}function Hu(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function Ku(r){for(let e of My){let t=r.get(e);if(t)return Gs(t)}return null}function Gs(r){let e=(r||"").trim();if(!e)return null;for(let t of Oy)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Ly(r){let e=r||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let n=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(n)return n[1]}var $u="idos_usage_pending",Ju="idos_usage_session",Zu="idos_usage_closed_session",Yu="idos_usage_new_session",Xu="idos_usage_last_activity",os=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;stopVisibility=null;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=!this.ctx.host.isVisible(),this.timer=setInterval(()=>this.tick(),200*1e3),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=e=>{if(!e){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,n=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,n,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=n,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=n,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber($u),this.currentSessionSeconds=this.readNumber(Ju),this.pendingClosedSessionSeconds=this.readNumber(Zu),this.isNewSessionPending=this.readNumber(Yu)!==0;let e=this.readNumber(Xu);this.currentSessionSeconds>0&&e>0&&(Date.now()-e)/1e3>=1800&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,Math.floor(this.currentSessionSeconds)),this.currentSessionSeconds=0);}persist(){this.writeNumber($u,this.pendingSeconds),this.writeNumber(Ju,this.currentSessionSeconds),this.writeNumber(Zu,this.pendingClosedSessionSeconds),this.writeNumber(Yu,this.isNewSessionPending?1:0),this.writeNumber(Xu,Date.now());}readNumber(e){let t=this.ctx.host.storage.getString(e),n=t?Number(t):0;return Number.isFinite(n)&&n>0?n:0}writeNumber(e,t){try{this.ctx.host.storage.setString(e,String(Math.floor(t)));}catch{}}};function G(r){return {ok:true,data:r}}function h(r,e){return {ok:false,reason:r,error:e}}var l=h("unauthorized","Not logged in.");function By(r){return r.ok}function Gy(r){return !r.ok}var Q=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="string"?Number(r):r;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(r)}`}),zod.z.NEVER)}),se=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="number"?String(r):r.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(r)}`}),zod.z.NEVER):t}),u=zod.z.string();var zt=zod.z.object({Type:zn.nullish(),CurrencyID:zod.z.string().nullish(),Amount:Q.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),Ny=zod.z.object({Type:Os.nullish(),EntityID:zod.z.string()}),_y=zod.z.object({Address:Ny.nullish(),Amount:Q.nullish(),Source:zod.z.string().nullish()}),he=zod.z.object({Entries:zod.z.array(zt).nullish(),EventTokens:zod.z.array(_y).nullish()}),ec=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:he.nullish()}),$=zod.z.object({Standard:he.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(ec).nullish()}),Nt=zod.z.object({Standard:he.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(ec).nullish()}),O=zod.z.object({Grant:$.nullish(),Consume:Nt.nullish()}),_t=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:O.nullish(),ToResult:O.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:he.nullish()});var Vy=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Fy={Completed:"Completed",Started:"Started",StepReached:"StepReached"},jy=zod.z.object({FlowIDs:zod.z.array(zod.z.string()).nullish(),Mode:zod.z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:zod.z.string().nullish(),Negate:zod.z.boolean().nullish(),SkippedCountsAsCompleted:zod.z.boolean().nullish()}).passthrough(),te=zod.z.object({Segments:zod.z.array(zod.z.string()).nullish(),MinPremiumTier:zod.z.number().nullish(),RequiredPremiumIDs:zod.z.array(zod.z.string()).nullish(),MinLevel:zod.z.number().nullish(),MaxLevel:zod.z.number().nullish(),Countries:zod.z.array(zod.z.string()).nullish(),RegisteredWithinDays:zod.z.number().nullish(),ActiveWithinDays:zod.z.number().nullish(),Experiment:Vy.nullish(),Tutorial:jy.nullish(),Platforms:zod.z.array(zs).nullish()}).passthrough();var ve=zod.z.object({TotalCap:zod.z.number().nullish(),DailyCap:zod.z.number().nullish(),DailyWeightCap:zod.z.number().nullish(),PerActivationCap:zod.z.number().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish()}).passthrough();var Wy=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Hy=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Ky=zod.z.object({AnchorUtc:zod.z.string().nullish(),MaxCycles:zod.z.number().nullish(),PauseBetweenPhasesSec:zod.z.number().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish()}).passthrough();zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();var Qy=zod.z.object({Reset:zod.z.string().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:zod.z.string().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();zod.z.object({SourceType:zod.z.string().nullish(),TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var ft=zod.z.object({SourceType:zod.z.string().nullish(),BaseWeight:zod.z.number().nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish(),TileTypeFilter:zod.z.array(zod.z.string()).nullish(),TileIndexFilter:zod.z.array(zod.z.number()).nullish(),ChanceOutcomeFilter:zod.z.array(zod.z.string()).nullish(),OutcomeFilter:zod.z.array(zod.z.string()).nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Limits:ve.nullish()}).passthrough(),Se=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:Hy.nullish(),Chain:Ky.nullish(),Cyclic:Qy.nullish(),ActivationTriggers:zod.z.array(ft).nullish(),Relative:Wy.nullish()}).passthrough();var $y={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},Jy=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Zy={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Yy=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),Xy=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Ze=zod.z.object({Base:zod.z.number().nullish(),Shape:Jy.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(Xy).nullish(),Interpolation:Yy.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var eR=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:$.nullish()}).passthrough(),tR=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),ba=zod.z.object({Bundles:zod.z.array(eR).nullish(),Multipliers:zod.z.array(tR).nullish()}).passthrough();var nR=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Ns=zod.z.object({Source:nR.nullish(),SourceKey:zod.z.string().nullish(),Curve:Ze.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:he.nullish(),ExcludeRewards:he.nullish()}).passthrough(),tc=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),je=zod.z.object({MilestoneID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredProgress:zod.z.number().nullish(),Rewards:$.nullish(),BonusRewards:$.nullish(),SeasonTierRewards:ba.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),On=zod.z.object({Milestones:zod.z.record(zod.z.string(),je).nullish()}).passthrough();var J=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var sR=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Mt=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxBalance:zod.z.number().nullish(),MaxPerGrant:zod.z.number().nullish(),DailyEarnCap:zod.z.number().nullish(),BurnOnEventEnd:zod.z.boolean().nullish(),BurnConversion:sR.nullish()}).passthrough();var iR=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),En=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),EquippedSlot:iR.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),K=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),En).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var Ee=r=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:r.nullish()}),Ot=r=>zod.z.object({ServerTimeUtc:u,Items:zod.z.array(Ee(r)),Resources:O.nullish(),Inventory:K.nullish()});var rR={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},nc=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),oR=zod.z.object({}).passthrough().transform(r=>r),aR=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:u.nullish(),CycleEndUtc:u.nullish(),PointsTotalEarned:Q.nullish(),PointsCurrent:Q.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:je.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),xa=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:Q.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:nc}),sc=zod.z.object({State:oR.nullish(),PointsTracks:zod.z.record(zod.z.string(),aR).nullish()}),Da=zod.z.object({ServerTimeUtc:u,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:nc.nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Ia=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:Q.nullish(),Resources:O.nullish(),Inventory:K.nullish(),NextMilestone:je.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),ic=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),rc=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(xa).nullish()}),oc=zod.z.array(Ee(Da)),ac=zod.z.array(Ee(Ia)),lR={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},uR=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),cR={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},pR=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),lc=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:uR.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(ft).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),Pa=zod.z.object({Milestones:J.nullish(),Linking:J.nullish(),Availability:J.nullish(),Reward:J.nullish(),Objectives:J.nullish()}).passthrough(),hR=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),uc=zod.z.object({CycleIDs:zod.z.array(zod.z.string()).nullish(),GroupID:zod.z.string().nullish(),PhaseIDs:zod.z.array(zod.z.string()).nullish(),RequiredQuestIDs:zod.z.array(zod.z.string()).nullish(),PrerequisiteMode:pR.nullish()}).passthrough(),cc=zod.z.object({Schedule:Se.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:te.nullish(),Limits:ve.nullish()}).passthrough(),pc=zod.z.object({Grant:$.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),dR=zod.z.object({QuestID:zod.z.string().nullish(),Identity:hR.nullish(),Linking:uc.nullish(),Availability:cc.nullish(),Objectives:zod.z.record(zod.z.string(),lc).nullish(),Reward:pc.nullish(),Presets:Pa.nullish()}).passthrough(),mR=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:te.nullish(),Reward:$.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),fR=zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Gate:te.nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),Presets:Pa.nullish(),PointsToken:Mt.nullish()}).passthrough(),gR=zod.z.object({Milestones:zod.z.record(zod.z.string(),On).nullish(),Linking:zod.z.record(zod.z.string(),uc).nullish(),Availability:zod.z.record(zod.z.string(),cc).nullish(),Reward:zod.z.record(zod.z.string(),pc).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),lc)).nullish()}).passthrough(),yR=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Se.nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),Gate:te.nullish(),PointsToken:Mt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),mR).nullish(),Phases:zod.z.record(zod.z.string(),fR).nullish(),Presets:Pa.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Vs=zod.z.object({Cycles:zod.z.record(zod.z.string(),yR).nullish(),Quests:zod.z.record(zod.z.string(),dR).nullish(),Presets:gR.nullish()}).passthrough(),At={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var RR={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},CR=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),SR={Never:"Never",OnRequest:"OnRequest",Always:"Always"},bR=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),xR={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},DR=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),IR={GameLoop:"GameLoop"},PR={Raid:"Raid",Attack:"Attack"},vR=zod.z.object({Title:zod.z.string().nullish(),TitleKey:zod.z.string().nullish(),Body:zod.z.string().nullish(),BodyKey:zod.z.string().nullish(),AnchorID:zod.z.string().nullish(),HighlightTarget:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),UiHint:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),AR=zod.z.object({Mode:CR.nullish(),Triggers:zod.z.array(ft).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),TR=zod.z.object({Grant:$.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),wR=zod.z.object({TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),RandomActionType:zod.z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),kR=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:wR.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),zR=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),va=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:vR.nullish(),Completion:AR.nullish(),Effects:TR.nullish(),Script:kR.nullish(),Policy:zR.nullish()}).passthrough(),MR=zod.z.object({DisplayName:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),Description:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),hc=zod.z.object({Schedule:Se.nullish(),Gate:te.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:ft.nullish()}).passthrough(),dc=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:bR.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),mc=zod.z.object({Grant:$.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),OR=zod.z.object({Availability:J.nullish(),Policy:J.nullish(),Reward:J.nullish(),Steps:J.nullish()}).passthrough(),ER=zod.z.object({FlowID:zod.z.string().nullish(),Identity:MR.nullish(),Availability:hc.nullish(),Policy:dc.nullish(),Steps:zod.z.record(zod.z.string(),va).nullish(),Reward:mc.nullish(),Presets:OR.nullish()}).passthrough(),qR=zod.z.object({BlockingFlowIDs:zod.z.array(zod.z.string()).nullish(),BlockedModules:zod.z.array(zod.z.string()).nullish(),BlockedActions:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),BlockBeforeStart:zod.z.boolean().nullish(),SkipLiftsBlock:zod.z.boolean().nullish()}).passthrough(),UR=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:qR.nullish()}).passthrough(),LR=zod.z.object({Availability:zod.z.record(zod.z.string(),hc).nullish(),Policy:zod.z.record(zod.z.string(),dc).nullish(),Reward:zod.z.record(zod.z.string(),mc).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),va)).nullish()}).passthrough(),fc=zod.z.object({Flows:zod.z.record(zod.z.string(),ER).nullish(),Settings:UR.nullish(),Presets:LR.nullish()}).passthrough(),BR=zod.z.object({}).passthrough().transform(r=>r),gc=zod.z.object({FlowID:zod.z.string(),Status:DR,CurrentStepID:zod.z.string().nullish(),CurrentStep:va.nullish(),TotalSteps:zod.z.number(),CompletedSteps:zod.z.number(),CanSkip:zod.z.boolean(),RewardClaimed:zod.z.boolean(),RewardPending:zod.z.boolean(),VariantID:zod.z.string().nullish()}).passthrough(),Fs=zod.z.object({State:BR.nullish(),Flows:zod.z.array(gc).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Jt=zod.z.object({Flow:gc.nullish()}).passthrough(),yc=zod.z.object({FlowID:zod.z.string().nullish(),Granted:O.nullish()}).passthrough(),Rc=zod.z.array(Ee(Jt)),Cc=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),gt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function js(r){return Array.isArray(r)?r.filter(e=>e!==null).map(js):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,js(t)])):r}var Ws=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),n=this.last.get(e);return n!==void 0&&t-n<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var Hs=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Sc(r){return r===429||r>=500&&r<=599}function Ks(r,e=Math.random){let t=Math.min(500*Math.pow(2,r-1),4e3),n=t*.2*(e()*2-1);return Math.max(50,t+n)}function Zt(r){return new Promise(e=>setTimeout(e,r))}var bc=15e3;async function xc(r){try{let t=JSON.parse(await r.text()),n=Number(t?.RetryAfterMs);if(Number.isFinite(n)&&n>0)return n}catch{}let e=Number(r.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Dc(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function Ic(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var Aa=15,Pc=1e3,Qs=class{constructor(e=Aa,t=()=>Date.now(),n=Zt){this.perSecond=e;this.now=t;this.wait=n;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=Pc;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(Pc-(e-this.starts[0])+5);}}};var GR=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function Un(r){if(!r)return null;let e=GR.exec(r);if(!e)return null;let[,t,n,s]=e;if(!t||n===void 0||s===void 0)return null;let i=new gn__default.default(n),o=new gn__default.default(s),p=o.minus(gn__default.default.max(i,0));return p.lte(0)?null:{currencyID:t,required:o.toNumber(),available:i.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var NR=12e3,_R=new Set(["RelatedEntityID"]);function VR(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[n,s]of Object.entries(e))_R.has(n)||(t[n]=s);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var FR=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(xa).nullish(),TutorialProgress:zod.z.array(Cc).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),$s=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Hs;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new Ws(e.throttleMs),this.pacer=new Qs(e.maxRequestsPerSecond??Aa),this.clientPlatform=e.clientPlatform??Ne.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,n,s={}){let i=s.throttleKey??VR(e,t);if(!this.throttler.tryAcquire(i))return h("throttled","Throttled");if(!this.inflight.add(i))return h("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,p=JSON.stringify(t),m=s.ticket??null,g=s.silent??!1,j=s.timeoutMs??NR,pe=s.autoRetry??!0,Ae=!1,fe=!1,xe=0;for(;;){let Gt;s.keepalive||await this.pacer.take();try{Gt=await this.doFetch(o,p,m,j,s.keepalive??!1);}catch{if(pe&&xe<3){xe++,await Zt(Ks(xe));continue}return this.connectionFailure("Internet Connection Error",g)}let lt=Gt.status;if(lt>=200&&lt<300){let ce=!fe&&this.cryptoTopUpHandler!==null,Oe=await this.parseSuccess(Gt,n,g,e,ce);if(!Oe.ok&&ce){let ye=Un(Oe.error);if(ye){if(fe=!0,await this.runTopUp(ye))continue;g||this.emitter.emit("error:global",Oe.error);}}return Oe}if(lt===401){if(!Ae&&this.sessionRefreshHandler){Ae=!0;let ce=null;try{ce=await this.sessionRefreshHandler();}catch{ce=null;}if(ce){m=ce;continue}}return this.emitter.emit("auth:unauthorized",void 0),h("unauthorized","Unauthorized")}if(Sc(lt)){let ce=lt===429?await xc(Gt):null;if(ce!==null&&ce>bc)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ce/1e3)} s`,g);if(pe&&xe<3){xe++,await Zt(ce!==null?Dc(ce):lt===429?Ic(xe):Ks(xe));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${lt})`,g)}let $n="";try{$n=await Gt.text();}catch{}if(lt===409&&/operation in progress/i.test($n)&&pe&&xe<3){xe++,await Zt(Ks(xe));continue}return this.handleWebError($n,lt,g)}}finally{this.inflight.remove(i),this.lowerBusy();}}async doFetch(e,t,n,s,i=false){let o=new AbortController,p=setTimeout(()=>{o.abort();},s);try{let m={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return n&&(m.Authorization=`Bearer ${n}`),await this.fetchImpl(e,{method:"POST",body:t,headers:m,signal:o.signal,...i?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,n,s,i=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",n)}let p;try{p=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",n)}let m=FR.safeParse(p);if(!m.success)return this.globalError("Malformed response envelope",n);if(!m.data.Success){let fe=m.data.Error??"Server returned Success=false",xe=i&&Un(fe);return !n&&!xe&&this.emitter.emit("error:global",fe),h("server",fe)}let g=m.data.StateVersions;g&&Object.keys(g).length>0&&this.emitter.emit("user:stateVersions",{epoch:m.data.StateEpoch??null,versions:g});let j=m.data.QuestProgress;j&&j.length>0&&this.emitter.emit("quest:systemProgress",j);let pe=m.data.TutorialProgress;pe&&pe.length>0&&this.emitter.emit("tutorial:systemProgress",pe);let Ae=t.safeParse(m.data.Data);if(!Ae.success){let fe=t.safeParse(js(m.data.Data));fe.success&&(Ae=fe);}if(!Ae.success){let fe=`Validation error (${s}): ${Ae.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",fe),n||this.emitter.emit("error:global",fe),h("validation",fe)}return G(Ae.data)}handleWebError(e,t,n){let s=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),h("server","PLAY_ACCESS_REQUIRED");s=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return n||this.emitter.emit("error:global",s),h("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),h("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),h("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function Ln(r){return (typeof r=="string"?r:r.toISOString()).slice(0,10)}function as(r){return `${Ln(r)}T00:00:00.000Z`}function vc(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Ac(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function ka(r,e,t,n){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;r.InventoryV2??={};let i=r.InventoryV2,o=n.toISOString(),p=new Map,m=new Map,g=new Map,j=new Map,pe=new Map,Ae=new Map,fe=new Map,xe=new Map,Gt=e.Grant?.PremiumTiers??[],lt=Gt.length;for(let ce=0;;ce++){let Oe,ye;if(ce===0)Oe=e.Grant?.Standard?.Entries,ye=false;else if(ce-1<lt)Oe=Gt[ce-1]?.Resources?.Entries,ye=false;else if(ce===1+lt)Oe=e.Consume?.Standard?.Entries,ye=true;else break;if(Oe)for(let ge of Oe){if(ge.Type==null)continue;let Ce=Math.max(0,ge.Amount??0);if(!(Ce<=0))switch(ge.Type){case "VirtualCurrency":{if(!ge.CurrencyID)continue;let be=ye?m:p;be.set(ge.CurrencyID,(be.get(ge.CurrencyID)??0)+Ce);break}case "CryptoCurrency":{if(!ge.CurrencyID)continue;let be=ye?j:g;be.set(ge.CurrencyID,(be.get(ge.CurrencyID)??new gn__default.default(0)).plus(Ce));break}case "Item":{if(!ge.ItemID)continue;let be=WR(t,ge.CatalogID,ge.ItemID),we=(be?be.IsStackable??true:true)?ye?Ae:pe:ye?xe:fe;we.set(ge.ItemID,(we.get(ge.ItemID)??0)+Ce);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||m.size>0,s.vcChanged){i.VirtualCurrencies??={};for(let ce of new Set([...p.keys(),...m.keys()])){let Oe=p.get(ce)??0,ye=m.get(ce)??0,ge=Oe-ye,Ce=i.VirtualCurrencies[ce];Ce?(Ce.Amount+=ge,Ce.UpdatedAt=o,Ce.Daily&&Ln(Ce.Daily.PeriodStartUtc)===Ln(n)?(Ce.Daily.Earned+=Oe,Ce.Daily.Spent+=ye):Ce.Daily={PeriodStartUtc:as(n),Earned:Oe,Spent:ye}):i.VirtualCurrencies[ce]={Amount:ge,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:as(n),Earned:Oe,Spent:ye}};}}if(s.ccChanged=g.size>0||j.size>0,s.ccChanged){i.CryptoCurrencies??={};for(let ce of new Set([...g.keys(),...j.keys()])){let Oe=g.get(ce)??new gn__default.default(0),ye=j.get(ce)??new gn__default.default(0),ge=Oe.minus(ye),Ce=i.CryptoCurrencies[ce];Ce?(Ce.Amount=new gn__default.default(Ce.Amount).plus(ge).toString(),Ce.UpdatedAt=o):i.CryptoCurrencies[ce]={Amount:ge.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(s.itemsChanged=pe.size>0||Ae.size>0||fe.size>0||xe.size>0,s.itemsChanged){i.Items??={},i.UnstackableItems??={};let ce=i.UnstackableItems,Oe=new Set([...pe.keys(),...Ae.keys(),...fe.keys(),...xe.keys()]);for(let ye of Oe){let ge=(pe.get(ye)??0)-(Ae.get(ye)??0),Ce=(fe.get(ye)??0)-(xe.get(ye)??0),be=ge+Ce,mt=i.Items[ye];mt?(ge!==0&&(mt.StackableAmount+=ge),Ce!==0&&(mt.UnstackableAmount+=Ce),be!==0&&(mt.TotalAmount+=be)):i.Items[ye]={StackableAmount:Math.max(0,ge),UnstackableAmount:Math.max(0,Ce),TotalAmount:Math.max(0,be)};}for(let[ye,ge]of xe){if(ge<=0)continue;let Ce=Object.values(ce).filter(be=>be.ItemID===ye&&be.EquippedSlot==null&&(be.ExpiresAt==null||new Date(be.ExpiresAt)>n)).sort(jR).slice(0,ge).map(be=>be.ItemInstanceID);for(let be of Ce)delete ce[be];}for(let[ye,ge]of fe){let Ce=HR(t,ye);for(let be=0;be<ge;be++){let mt=V();ce[mt]={ItemInstanceID:mt,ItemID:ye,CatalogID:Ce,RemainingUses:1,AcquiredAt:o};}}}r.EventToken??={};let $n=r.EventToken;for(let ce=0;;ce++){let Oe,ye;if(ce===0)Oe=e.Grant?.Standard?.EventTokens,ye=false;else if(ce-1<lt)Oe=Gt[ce-1]?.Resources?.EventTokens,ye=false;else if(ce===1+lt)Oe=e.Consume?.Standard?.EventTokens,ye=true;else break;if(!(!Oe||Oe.length===0))for(let ge of Oe){let Ce=ge.Address;if(!Ce||Ce.Type==null)continue;let be=ge.Amount??0;if(be<=0)continue;let mt=KR($n,Ce.Type);if(!mt)continue;let we=mt[Ce.EntityID];we||(we={},mt[Ce.EntityID]=we),we.Balance??={Current:0,TotalEarned:0,TotalSpent:0},we.Daily??={Date:as(n),TotalEarned:0},we.Meta??={};let Jn=ge.Source&&ge.Source.length>0?ge.Source:"CustomAction";ye?(we.Balance.Current-=be,we.Balance.TotalSpent+=be):(we.Balance.Current+=be,we.Balance.TotalEarned+=be,Ln(we.Daily.Date)!==Ln(n)&&(we.Daily={Date:as(n),TotalEarned:0}),we.Daily.TotalEarned+=be,we.Daily.EarnedBySource??={},we.Daily.EarnedBySource[Jn]=(we.Daily.EarnedBySource[Jn]??0)+be,we.Daily.TriggersBySource??={},we.Daily.TriggersBySource[Jn]=(we.Daily.TriggersBySource[Jn]??0)+1,we.Daily.LastTriggerBySource??={},we.Daily.LastTriggerBySource[Jn]=o,we.Meta.JoinedAtUtc||(we.Meta.JoinedAtUtc=o),we.Meta.LastEarnedAtUtc=o),s.tokensChanged=true;}}return s}function jR(r,e){return r.AcquiredAt!==e.AcquiredAt?r.AcquiredAt<e.AcquiredAt?-1:1:r.ItemInstanceID===e.ItemInstanceID?0:r.ItemInstanceID<e.ItemInstanceID?-1:1}function WR(r,e,t){let n=r?.Catalogs;if(n){if(e){let s=n[e]?.Items?.[t];if(s)return s}for(let s of Object.values(n)){let i=s.Items?.[t];if(i)return i}}}function HR(r,e){let t=r?.Catalogs;if(t){for(let[n,s]of Object.entries(t))if(s.Items&&e in s.Items)return n}}function KR(r,e){switch(e){case "TimedEvent":return r.TimedEvent??={};case "Quest":return r.Quest??={};case "Leaderboard":return r.Leaderboard??={};case "CoopEvent":return r.CoopEvent??={};case "Season":return r.Season??={};case "Challenge":return r.Challenge??={};case "ChallengePoints":return r.ChallengePoints??={};default:return null}}function Tc(r,e,t){let n={drop:[],restore:{}};if(!t)return n;let s=t.ChangedInstances??{},i=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let m of Object.values(s))m?.ItemID&&o.add(m.ItemID);for(let m of i){let g=r[m]?.ItemID;g&&o.add(g);}if(o.size===0)return n;let p=m=>i.has(m)||m in s;if(e){for(let[m,g]of Object.entries(e))m in r||p(m)||g&&o.has(g.ItemID)&&n.drop.push(m);for(let[m,g]of Object.entries(r))m in e||p(m)||g&&o.has(g.ItemID)&&(n.restore[m]=g);}return n}function za(r,e){return r===e||r.startsWith(`${e}:`)}var Zs=class r{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let n of Object.values(t))n&&(typeof n.Amount=="number"&&(n.Amount=String(n.Amount)),typeof n.Frozen=="number"&&(n.Frozen=String(n.Frozen)));}applyUserState(e){r.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let n of t)this.currentState[n]=e[n];r.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){r.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,n=new Date){if(!this.currentState)return;let s=ka(this.currentState,e,t,n);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,n,s=new Date){if(!this.currentState)return;let i=this.currentState,o={...i.InventoryV2?.UnstackableItems??{}},p=ka(i,e,n,s),m=Tc(o,i.InventoryV2?.UnstackableItems,t),g=Object.entries(t?.ChangedInstances??{}),j=t?.RemovedInstanceIDs??[],pe=m.drop.length>0||Object.keys(m.restore).length>0||g.length>0||j.length>0;if(pe){i.InventoryV2??={},i.InventoryV2.UnstackableItems??={};let Ae=i.InventoryV2.UnstackableItems;for(let fe of m.drop)delete Ae[fe];for(let[fe,xe]of Object.entries(m.restore))Ae[fe]=xe;for(let[fe,xe]of g)Ae[fe]=xe;for(let fe of j)delete Ae[fe];}this.emitResourceChanges(p,pe);}emitResourceChanges(e,t){let n=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),n&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(n||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,n,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let i=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof gn__default.default?t:new gn__default.default(t),p=s===void 0?new gn__default.default(0):s instanceof gn__default.default?s:new gn__default.default(s),m=n??new Date().toISOString(),g=i[e];g?(g.Amount=new gn__default.default(g.Amount).plus(o).toString(),p.isZero()||(g.Frozen=new gn__default.default(g.Frozen??0).plus(p).toString()),g.UpdatedAt=m):i[e]={Amount:o.toString(),Frozen:p.toString(),CreatedAt:m,UpdatedAt:m},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,n){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,i=s[e];i||(i={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=i),i.TotalPurchases+=t,i.LastPurchasedAt=n,n>=i.DailyResetUtc?(i.DailyPurchases=t,i.DailyResetUtc=vc(n)):i.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,n){if(!e||n<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let i=new Date().toISOString();for(let o of t)o.RuleID&&(s.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:i});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchRewardWindowState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Windows??={},this.currentState.Reward.Windows[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,n){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let i=s.Cycles[t];if(!i)return;i.Quests??={};let o=i.Quests[e]??={QuestID:e,Status:n};o.Status=n,n==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let i=s.PermanentQuests[e]??={QuestID:e,Status:n};i.Status=n,n==="Claimed"&&(i.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let n=this.getQuestPointsProgress(e);n&&(n.Milestone??={},this.markMilestoneClaimed(n.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let n of Object.values(e)){if(!n.CycleID)continue;let s=n.InstanceKey?`${n.CycleID}:${n.InstanceKey}`:n.CycleID,i=t[s]??={};i.Balance??={Current:0,TotalEarned:0,TotalSpent:0},i.Balance.Current=n.PointsCurrent??0,i.Balance.TotalEarned=n.PointsTotalEarned??0,i.Milestone??={};for(let o of n.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(i.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let n=this.currentState.Quest.Cycles[e];n&&(n.ClaimedGroupCompletionIDs??=[],n.ClaimedGroupCompletionIDs.includes(t)||n.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let n=t.Flows[e.FlowID]??={FlowID:e.FlowID};n.Status=e.Status,n.CurrentStepID=e.CurrentStepID??null,n.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(n.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let n of e){if(!n.FlowID||!n.StepID)continue;let s=t.Flows[n.FlowID]??={FlowID:n.FlowID,Status:"InProgress"};s.Steps??={};let i=s.Steps[n.StepID]??={StepID:n.StepID};i.Progress=n.Progress,n.Completed&&(i.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===n.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let n of e){if(!n.QuestID)continue;let s;if(!n.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[n.QuestID]??={QuestID:n.QuestID,Status:n.Status};else {t.Cycles??={};let i=t.Cycles[n.CycleID];if(!i)continue;i.Quests??={},s=i.Quests[n.QuestID]??={QuestID:n.QuestID,Status:n.Status};}if(s.Status=n.Status,n.ObjectiveID){s.Objectives??={};let i=s.Objectives[n.ObjectiveID]??={ObjectiveID:n.ObjectiveID,CurrentValue:0,Completed:false};i.CurrentValue=n.NewValue??0,n.ObjectiveCompleted&&(i.Completed=true,i.CompletedAtUtc??=new Date().toISOString());}n.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[n,s]of Object.entries(t))if(za(n,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,n,s){if(!(!t||!n)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[i,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((s?i!==s:!za(i,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),n));this.patchActiveEventMilestoneClaimed(e,t,n,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,n,s){let i=this.activeEventsCache?.ActiveEvents;if(i)for(let o of i)o.Type!==e||o.TimedEventID!==t||s&&o.TokenEntityID&&o.TokenEntityID!==s||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),n));}markMilestoneClaimed(e,t){e.Claims??={};let n=e.Claims[t]??={};n.ClaimedAt??=new Date().toISOString(),n.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let n=this.ensureLeaderboardProgress(e);n.CurrentScore=t.CurrentScore??0,n.LastKnownRank=t.LastKnownRank??0,n.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,n.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,n.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,n,s){if(!e)return;let i=this.ensureLeaderboardProgress(e);(i.ScoreCycleVersion??0)<s&&(i.ScoreEarnedThisCycle=0,i.ClaimedMilestoneIDs=[],i.BracketID=null),i.CurrentScore=t,i.ScoreEarnedThisCycle=(i.ScoreEarnedThisCycle??0)+n,i.ScoreCycleVersion=s,i.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let n=this.ensureLeaderboardProgress(e);n.ClaimedMilestoneIDs??=[],n.ClaimedMilestoneIDs.includes(t)||n.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,n=t[e];return n||(n={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=n),n}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let n=this.ensureSeasonState(e);n.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let n=this.ensureSeasonState(e);n.ClaimedTierRewards??=[],n.ClaimedTierRewards.includes(t)||n.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,n=t[e];return n||(n={SeasonChainID:e},t[e]=n),n}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let n=this.currentState?.Character?.Characters;if(!n)return;let s=false;for(let i of Object.values(n))for(let o of Object.values(i.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySelectedCharacter(e){this.currentState??={},this.currentState.Character??={};let t=e??null;(this.currentState.Character.SelectedCharacterID??null)!==t&&(this.currentState.Character.SelectedCharacterID=t,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let n=this.currentState.Character.Characters,s=n[e];s||(s={CharacterID:e},n[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,n){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},n===null?delete s.Equipment[t]:s.Equipment[t]=n,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,n=false;for(let[s,i]of Object.entries(e.ChangedInstances??{}))t[s]=i,n=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],n=true);n&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,n){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=n,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(n=>n!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(n=>n!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(n=>n!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),n=false;typeof e.FriendsCount=="number"&&(n||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(n||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(n||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),n&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let n=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(n)){let i=n[s];i&&i.BoostID===e.BoostID&&s!==e.InstanceID&&delete n[s];}n[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,n,s,i){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,p={Value:n,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:i??null};if(e==="Private")o.Private??={},o.Private[t]=p;else if(e==="Public")o.Public??={},o.Public[t]=p;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let n=this.currentState.CustomData;if(e==="Private")n.Private&&delete n.Private[t];else if(e==="Public")n.Public&&delete n.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let n=this.ensureBoard();n.BuildingStates??=[];let s=n.BuildingStates.find(i=>i.SlotIndex===e);s||(s={SlotIndex:e},n.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let n=this.ensureBoard().Pending;!n||n.Type.toUpperCase()!=="SPECIAL"||(n.Special??={},e(n.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),n=e.PendingAdded;if(t.size>0||n){let s=this.currentState.Blockchain??={},i=s.PendingWithdrawals??[];t.size>0&&(i=i.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),n&&!i.some(o=>o.TitleTransactionID===n.TitleTransactionID)&&(i=[...i,n]),s.PendingWithdrawals=i;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var Ys=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,n]of Object.entries(e))this.sections.has(t)||this.sections.set(t,n);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let n=this.config?.[e];return n??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var Xs=class{user;config;constructor(e){this.user=new Zs(e),this.config=new Ys;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function QR(r){return r}var $R=0,JR=1500,ZR=3,ti=class{constructor(e,t,n=null,s="",i="auto"){this.emitter=e;this.config=t;this.storage=n;this.titleId=s;this.loginMode=i;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return G(void 0);let n=Date.now(),s=[],i=[];for(let m of new Set(e)){let g=this.rules.get(m);if(g&&(t?.force||g.needsServer(n))){s.push(this.runRule(m,g));continue}(t?.force||!this.state.isStateFresh(m,t?.maxAgeMs))&&i.push(m);}let p=(await Promise.all([...s,i.length>0?this.queueSlice(i):Promise.resolve(G(void 0))])).find(m=>!m.ok);return p&&!p.ok?p:G(void 0)}runRule(e,t){let n=this.ruleInflight.get(e);if(n)return n;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}queueSlice(e){for(let n of e)this.pending.add(n);let t=new Promise(n=>this.waiters.push(n));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},$R),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let n;this.batchRunning=new Promise(s=>n=s);try{let s=this.state?await this.state.readStateSlice(e):G(void 0),i=s.ok?G(void 0):s;for(let o of t)o(i);}finally{this.batchRunning=null,n();}}async read(e,t,n){this.register(e);let s=ei(e,n?.args);if(this.noteUsed(e,n?.args,n?.loginParams),!n?.forceRefresh){let g=this.fresh(s,n?.maxAgeMs);if(g)return G(g.data);let j=this.loginFailures.get(s);if(j)return this.loginFailures.delete(s),j;let pe=this.inflight.get(s);if(pe)return pe}let i=this.generation.get(s)??0,o=Date.now(),m=t().then(g=>{if(!g.ok)return g;let j=Date.now();if((this.generation.get(s)??0)===i)return this.entries.set(s,{data:g.data,storedAt:j,expiresAt:Ma(e,g.data,j)}),g;let pe=this.entries.get(s);if(pe&&pe.storedAt>=o)return g;let Ae=Ma(e,g.data,j);return this.entries.set(s,{data:g.data,storedAt:j,expiresAt:Math.min(Ae??1/0,j+JR)}),g}).finally(()=>{this.inflight.get(s)===m&&this.inflight.delete(s);});return this.inflight.set(s,m),m}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...n})=>n))}acceptLoginViews(e){for(let t of e??[]){let n=this.loginBindings.get(t.Name);if(!n)continue;let s=t.Key?t.Key:void 0,i=ei(n.view,s);if(!t.Success){this.loginFailures.set(i,h("server",t.Error??"View failed."));continue}let o=n.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(i),n.apply(o.data,s),this.put(n.view,o.data,s));}}noteUsed(e,t,n){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let i=wc({Name:s,Key:t});this.used.get(i)?.n!==this.session&&(this.used.set(i,{Name:s,Key:t??"",...n,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>ZR||this.used.set(wc(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),n=t?JSON.parse(t):null;return !n||typeof n.s!="number"||!Array.isArray(n.v)?e:{session:n.s,views:n.v.filter(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(ei(e,t))?.data}put(e,t,n){this.register(e);let s=ei(e,n);this.bump(s);let i=Date.now();this.entries.set(s,{data:t,storedAt:i,expiresAt:Ma(e,t,i)});}invalidate(e,t){let n=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${n}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===n||s.startsWith(`${n}|`))&&this.drop(s);this.drop(n);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,n])=>({key:t,ageMs:e-n.storedAt,expiresInMs:n.expiresAt===null?null:n.expiresAt-e}))}fresh(e,t){let n=this.entries.get(e);if(!n)return;let s=Date.now();if(!(n.expiresAt!==null&&s>=n.expiresAt)&&!(t!==void 0&&s-n.storedAt>t))return n}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let n of this.views.values())n.dependsOn?.some(s=>t.has(s))&&this.invalidate(n);}};function ei(r,e){return e===void 0?r.key:`${r.key}|${e}`}function wc(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function Ma(r,e,t){let n=r.expiresAt?.(e)??null,s=r.ttlMs!==void 0?t+r.ttlMs:null;return n!==null&&s!==null?Math.min(n,s):n??s}var ni=class{constructor(e,t){this.storage=e;this.authTypeKey=`Saved_AuthType_${t}`,this.emailKey=`Saved_Auth_Email_${t}`,this.passwordKey=`Saved_Auth_Password_${t}`,this.refreshTokenKey=`Saved_Auth_RefreshToken_${t}`;}storage;authTypeKey;emailKey;passwordKey;refreshTokenKey;get lastAuthType(){let e=this.storage.getString(this.authTypeKey);return YR(e)?e:Ue.None}saveAuthType(e){this.storage.setString(this.authTypeKey,e);}get savedEmail(){return this.storage.getString(this.emailKey)??""}get savedPassword(){return this.storage.getString(this.passwordKey)??""}saveEmailAndPassword(e,t){this.storage.setString(this.emailKey,e),this.storage.setString(this.passwordKey,t);}get savedRefreshToken(){return this.storage.getString(this.refreshTokenKey)??""}saveRefreshToken(e){e?this.storage.setString(this.refreshTokenKey,e):this.storage.remove(this.refreshTokenKey);}clear(){this.storage.remove(this.authTypeKey),this.storage.remove(this.emailKey),this.storage.remove(this.passwordKey),this.storage.remove(this.refreshTokenKey);}};function YR(r){return r!==null&&Object.values(Ue).includes(r)}var XR=8,eC=100,tC=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,si=["GameLoop"];function nC(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var ii=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=Ue.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,n){let s=this.authContext;if(!s)return l;let i=this.baseRequest();i.UserID=s.userID,i.ClientSessionTicket=s.clientSessionTicket,i.WalletAddress=e,i.NetworkID=t,n&&(i.WalletSignature=n);let o=await this.ctx.api.authentication.linkWallet(i);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return l;let n=this.baseRequest();n.UserID=t.userID,n.ClientSessionTicket=t.clientSessionTicket,n.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(n);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.host.getDeviceID(),e.Device=this.ctx.host.getDeviceModel(),e.Platform=this.ctx.host.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(Ue.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.host.getTelegramInitDataRaw();if(!e)return h("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let n=await this.ctx.api.authentication.loginWithTelegram(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Ue.Telegram)):n}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.Password=t;let s=await this.ctx.api.authentication.loginWithEmail(n);if(!s.ok)return s;this.applyAuthContext(s.data);let i=await this.fetchAndApplyClientState(Ue.Email);return i.ok&&this.keepEmailCredentials(e,t),i}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.Password=t,n.DeviceID=this.ctx.host.getDeviceID(),n.Device=this.ctx.host.getDeviceModel(),n.Platform=this.ctx.host.getPlatform();let s=await this.ctx.api.authentication.registerWithEmail(n);return s.ok?(this.pendingRegistration={email:e,password:t},G({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.Email=e,n.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(n);if(!s.ok)return s;this.applyAuthContext(s.data);let i=await this.fetchAndApplyClientState(Ue.Email);return i.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,i}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let n=await this.ctx.api.authentication.resendVerificationCode(t);return n.ok?G(void 0):n}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let n=await this.ctx.api.authentication.loginWithGoogle(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Ue.Google)):n}async loginWithApple(e,t){if(!e?.trim())return h("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.AppleIDToken=e,t?.nonce&&(n.AuthNonce=t.nonce),t?.name?.trim()&&(n.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(n);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(Ue.Apple)):s}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.WalletAddress=e,n.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(n)}async loginWithWallet(e,t,n){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=n,s.Platform=this.ctx.host.getPlatform(),s.Device=this.ctx.host.getDeviceModel(),s.DeviceID=this.ctx.host.getDeviceID();let i=await this.ctx.api.authentication.loginWithWallet(s);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(Ue.Wallet)):i}async loginWithSsoCode(e){if(!e)return h("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.host.getDeviceID(),t.Device=this.ctx.host.getDeviceModel(),t.Platform=this.ctx.host.getPlatform();let n=await this.ctx.api.authentication.loginWithSsoCode(t);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Ue.iDosGames)):n}async loginWithPlatformGameTicket(e){if(!e)return h("client","Platform game ticket is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.PlatformGameTicket=e;let n=await this.ctx.userService.prepareLoginClientState(si,si);t.ClientState=n.request;let s=await this.ctx.api.authentication.resolvePlatformGameSession(t);if(!s.ok)return s;this.applyAuthContext(s.data),this.platformGameSession=true;let i=s.data.ClientState;return this.fetchAndApplyClientState(Ue.iDosGames,i?()=>n.finish(i):void 0)}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,n){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=n,this.ctx.api.authentication.resetPassword(s)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==Ue.None?e:Ue.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let n=this.baseRequest();n.RefreshToken=t,e?.appOpened&&(n.AppOpened=true);let s=await this.ctx.api.authentication.refreshSession(n);return s.ok?(this.applyRefresh(s.data),"ok"):(nC(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,n){switch(e){case Ue.Email:return this.loginWithEmail(t,n);case Ue.Device:case Ue.None:return this.loginWithDeviceID();case Ue.Telegram:return this.loginWithTelegram();default:return Promise.resolve(h("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;if(this.platformGameSession){this.refreshing=true;try{let t=await this.ctx.host.signIn(this.ctx.settings.titleID);if(!t.ticket)return null;let n=this.baseRequest();n.PlatformGameTicket=t.ticket;let s=await this.ctx.api.authentication.resolvePlatformGameSession(n);return s.ok?(this.applyAuthContext(s.data),this.platformGameSession=!0,s.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==Ue.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===Ue.None)return null;this.refreshing=true;try{return (await this.replay(e,this.sessionEmail||this.ctx.authStore.savedEmail,this.sessionPassword||this.ctx.authStore.savedPassword)).ok&&this.authContext?this.authContext.clientSessionTicket:null}catch{return null}finally{this.refreshing=false;}}logout(){this.authContext=null,this.playAccessStatus=null,this.forgetSession(),this.ctx.authStore.clear(),this.ctx.data.reset(),this.ctx.emitter.emit("auth:loggedOut",void 0);}static isValidEmail(e){return e.length>0&&tC.test(e)}static isValidPasswordLength(e){return e.length>=XR&&e.length<=eC}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=Ue.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e,t){let n=t?await t():await this.ctx.userService.getClientStateExcept(si,si);return n.ok&&(this.sessionAuthType=e,this.rememberSession?(this.ctx.authStore.saveAuthType(e),this.ctx.authStore.saveRefreshToken(this.sessionRefreshToken)):this.ctx.authStore.clear(),this.ctx.emitter.emit("auth:loggedIn",void 0)),n}};var sC="idos:cfg",Bn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${kc(t)}`:e&&e.length>0?`f:${kc(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.v!="string"||!n.c?null:n}catch{return null}}async write(e,t,n){try{let s={v:t,c:n};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${sC}:${this.titleId}:${e}`}};function kc(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var zc="idos:loc",Gn=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.v!="number"||!n.t||typeof n.t!="object"?null:n}catch{return null}}async write(e,t,n){try{let s={v:t,t:n};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let n={};for(let[s,i]of Object.entries(t))typeof i=="number"&&i>0&&(n[s]=i);return n}catch{return {}}}async noteVersion(e,t){let n=await this.readVersions();n[e]!==t&&(n[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(n)));}keyOf(e){return `${zc}:${this.titleId}:${e}`}versionsKey(){return `${zc}:${this.titleId}:versions`}};var iC="idos:sec",ri=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let n=JSON.parse(t);return !n||typeof n!="object"||n.v!==e||!n.s||typeof n.s!="object"?{}:n.s}catch{return {}}}async write(e,t){try{let n={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(n));}catch{}}keyOf(){return `${iC}:${this.titleId}`}};var rC="idos:state",oi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let n=JSON.parse(t);return !n||typeof n!="object"||typeof n.e!="string"||!n.v||!n.s?null:n}catch{return null}}async write(e,t,n,s){if(!(!e||!t))try{let i={e:t,v:n,s};await this.storage.set(this.keyOf(e),JSON.stringify(i));}catch{}}keyOf(e){return `${rC}:${this.titleId}:${e}`}};function oC(r,e){if(!r)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return r;let n={};for(let[s,i]of Object.entries(r))t.has(s.toLowerCase())||(n[s]=i);return n}function Oa(r,e,t,n){let s={...r??{}};if(!e||!t||!n)return s;for(let[i,o]of Object.entries(t))n[i]===o&&i in e&&(s[i]=e[i]);return s}function aC(r){return {...r??{}}}function Ea(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.StateEpoch:null}var ai=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,n=Date.now()){if(this.versions[e]===void 0)return false;let s=this.confirmedAt[e];return s===void 0?false:t===void 0||n-s<=t}forget(e){let t=[];for(let n of e)this.versions[n]!==void 0&&(delete this.versions[n],delete this.confirmedAt[n],t.push(n));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=oC(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let o=Object.keys(this.versions);this.reset(e),this.notify(o);}return []}let n=Date.now(),s=[],i=[];for(let[o,p]of Object.entries(t)){let m=this.versions[o];m!==p&&(m!==void 0&&p===m+1?(this.versions[o]=p,this.confirmedAt[o]=n):(delete this.versions[o],delete this.confirmedAt[o],m!==void 0&&p>m+1&&i.push(o)),s.push(o),this.dirty=true);}return this.notify(s),i}afterFullRead(e,t){let n=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=aC(t);let s=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=s;this.dirty=true;let i=new Set;for(let o of new Set([...Object.keys(n),...Object.keys(this.versions)]))n[o]!==this.versions[o]&&i.add(o);this.notify([...i]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let n=Date.now(),s=[];for(let[i,o]of Object.entries(t??{}))this.versions[i]!==o&&s.push(i),this.versions[i]=o,this.confirmedAt[i]=n;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Mc=h("server","Title configuration is unavailable (CDN and API both failed)."),li=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:V()}:null}get configCache(){return this.cache??=new Bn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new Gn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new ri(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new ai(new oi(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){if(!this.ctx.auth.context?.userID||!this.stateStore.currentEpoch)return;let s=this.stateStore.noteMutation(e,t);s.length>0&&(this.ctx.cache.ensureState(s),this.ctx.emitter.emit("user:changedElsewhere",{containers:s}));}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return l;let t=Bn.scopeOf(e.TitleFields,null),n=await this.configCache.read(t);n&&(e.KnownTitleConfigVersion=n.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let i=await this.ctx.api.user.getClientState(e);if(!i.ok)return i;let o=await this.resolveTitleConfig(i.data,t,n,{Fields:e.TitleFields});return o==null?Mc:(this.finishStateHandshake(i.data,s),await this.restoreSections(i.data.TitleConfigVersion,o),await this.applyClientState(i.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(i.data.Views),await this.applyLocalization(i.data.Localization),await this.flushState(s),i)}async prepareStateHandshake(e,t){let n=this.ctx.auth.context?.userID;if(!n)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(n),await this.stateStore.flush(n,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let i=this.stateStore.currentEpoch;i&&(e.KnownStateEpoch=i);}return {userId:n,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let n=Oa(e.User,t.cached,t.sent,e.StateVersions);e.User=n;let s=Ea(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,n,s){let i=e.TitleConfigVersion;if(n&&i&&n.v===i)return n.c;if(e.TitleConfigUrl){let p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return i&&await this.configCache.write(t,i,p),p}let o=await this.fetchConfigFromApi(s);return o!=null?(i&&await this.configCache.write(t,i,o),o):n?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let n=await t.json();return n&&typeof n=="object"?n:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let n={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(n):await this.ctx.api.title.getTitlePublicConfiguration(n);return s.ok?s.data:null}async getClientStateExcept(e,t){let n=this.baseRequest();if(!n)return l;let s=await this.prepareClientStateExcept(n,e,t,true),i=await this.ctx.api.user.getClientStateExcept(n);return i.ok?this.finishClientStateExcept(s,i.data):i}async prepareLoginClientState(e,t){let n={BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:V()},s=await this.prepareClientStateExcept(n,e,t,false);return {request:n,finish:async i=>{let o=this.ctx.auth.context?.userID??null;return o&&await this.stateStore.load(o),s.handshake={userId:o,cached:null,sent:void 0},this.finishClientStateExcept(s,i)}}}async prepareClientStateExcept(e,t,n,s){e.ExcludeFields=t,e.ExcludeTitleFields=n;let i=Bn.scopeOf(null,n??[]),o=await this.configCache.read(i);o&&(e.KnownTitleConfigVersion=o.v),await this.prepareLocalization(e);let p=s?await this.prepareStateHandshake(e,t??null):{userId:null,cached:null,sent:void 0};return await this.prepareLoginViews(e),{scope:i,cached:o,handshake:p,excludeFields:t,excludeTitleFields:n}}async finishClientStateExcept(e,t){let n=await this.resolveTitleConfig(t,e.scope,e.cached,{ExcludeFields:e.excludeTitleFields??[]});return n==null?Mc:(this.finishStateHandshake(t,e.handshake),await this.restoreSections(t.TitleConfigVersion,n),await this.applyClientState(t,n,e.excludeFields,e.excludeTitleFields),this.ctx.cache.acceptLoginViews(t.Views),await this.applyLocalization(t.Localization),await this.flushState(e.handshake),G(t))}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let n=t,s={};for(let[i,o]of Object.entries(await this.sectionCache.read(e)))n[i]==null&&(s[i]=o);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((i,o)=>{n[i]!=null||o==null||(s[i]=o,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let n=await this.localizationCache.readVersions();Object.keys(n).length>0&&(e.KnownLocalizationVersions=n);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),n=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:n});}async resolveLocalizationTable(e){let t=e.Locale??null,n=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(n<=0)return s?.t??null;if(s&&s.v===n)return s.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,n,o),o}let i=await this.fetchLocalizationFromApi(t,s?.v??0);return i??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let n=await t.json();return n&&typeof n=="object"?n:null}catch{return null}}async fetchLocalizationFromApi(e,t){let n=this.baseRequest();if(!n)return null;let s=await this.ctx.api.localization.getLocalizationTable({...n,Locale:e,KnownVersion:t});if(!s.ok)return null;let i=s.data;if(i.NotModified)return null;let o=i.Entries??{},p=i.Version??0,m=i.Locale??e;return p>0&&await this.localizationCache.write(m,p,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):l}async getUserState(e){let t=this.baseRequest();if(!t)return l;e&&e.length>0&&(t.Fields=e);let n=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let i=Oa(s.data.User,n.cached,n.sent,s.data.StateVersions);s.data.User=i;let o=n.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([g,j])=>o[g]!==j||this.ctx.data.user.state?.[g]===void 0).map(([g])=>g);this.ctx.data.user.applyUserStateContainers(i,p);let m=Ea(s.data);return m&&(this.stateStore.afterSliceRead(m,s.data.StateVersions),await this.flushState(n)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,n){let s=this.baseRequest();if(!s)return l;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=n;let i=await this.ctx.api.user.addUsageTime(s);return i.ok&&this.ctx.emitter.emit("user:usageTimeAdded",i.data),i}async deleteUserAccount(){let e=this.baseRequest();if(!e)return l;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return l;t.Username=e;let n=await this.ctx.api.user.changeUsername(t);return n.ok&&this.ctx.emitter.emit("user:usernameChanged",n.data),n}async applyClientState(e,t,n,s){let i=n?.includes("GameLoop")===true,o=s?.includes("GameLoop")===true,p=i?this.ctx.data.user.state?.GameLoop:void 0,m=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let g=this.ctx.data.user.state;i&&g&&g.GameLoop==null&&(g.GameLoop=p);let j=this.ctx.data.config.titlePublicConfiguration;o&&j&&j.GameLoop==null&&(j.GameLoop=m),this.ctx.emitter.emit("user:clientStateReceived",e);}};var ci=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return h("client","SpendID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${V()}`},s=await this.ctx.api.currency.spend(n);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",s.data)),s}async convert(e,t,n,s,i,o){if(!t)return h("client","SourceID is required.");if(!s)return h("client","TargetID is required.");if(i<=0)return h("client","Amount must be positive.");if(e===n&&t===s)return h("client","Source and target must differ.");if(e===Dt.Crypto||n===Dt.Crypto)return h("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return l;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:n,TargetID:s,SourceAmount:String(Math.trunc(i)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${n}_${s}_${V()}`},m=await this.ctx.api.currency.convert(p);if(m.ok){let g=m.data,j={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:g.SourceID,Amount:g.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:g.TargetID,Amount:g.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(j,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",g);}return m}async cryptoConvert(e,t,n,s,i,o){let p=i instanceof gn__default.default?i:new gn__default.default(i);if(!t)return h("client","SourceID is required.");if(!s)return h("client","TargetID is required.");if(p.lte(0))return h("client","SourceAmount must be a positive decimal.");if(e===n&&t===s)return h("client","Source and target must differ.");if(e===Dt.Virtual&&n===Dt.Virtual)return h("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===Dt.Virtual&&!p.isInteger())return h("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return l;let m={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:n,TargetID:s,SourceAmount:p.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${n}_${s}_${V()}`},g=await this.ctx.api.currency.cryptoConvert(m);if(g.ok){let j=g.data,pe=[],Ae=[];if(j.SourceType===Dt.Virtual&&pe.push({Type:"VirtualCurrency",CurrencyID:j.SourceID,Amount:Math.trunc(Number(j.SourceSpent))}),j.TargetType===Dt.Virtual&&Ae.push({Type:"VirtualCurrency",CurrencyID:j.TargetID,Amount:Math.trunc(Number(j.TargetCredited))}),pe.length>0||Ae.length>0){let fe={Consume:pe.length>0?{Standard:{Entries:pe}}:null,Grant:Ae.length>0?{Standard:{Entries:Ae}}:null};this.ctx.data.user.applyResourceOperation(fe,this.ctx.data.config.itemDefinitions);}j.SourceType===Dt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.SourceID,new gn__default.default(j.SourceSpent).negated(),j.ServerTimeUtc),j.TargetType===Dt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.TargetID,new gn__default.default(j.TargetCredited),j.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",j);}return g}};var pi=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,n,s){let i=e.trim();if(!i)return h("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:i,SelectedOptionID:n,CreditsConfirmationID:s,RelatedEntityID:`upgrade_item_${i}_${V()}`};t&&t.length>0&&(o.FodderInstanceIDs=[...t]);let p=await this.ctx.api.item.upgradeLevel(o);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(p.data.ItemInstanceID??i,p.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",p.data)),p}async upgradeLevelsBatch(e){if(!e||e.length===0)return h("client","upgrades is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},n=await this.ctx.api.item.upgradeLevelsBatch(t);if(n.ok){for(let s of n.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",n.data);}return n}};var hi=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:Nt.nullish(),AllowedPlatforms:zod.z.array(zs).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),me=zod.z.record(zod.z.string(),hi),lC=zod.z.object({Store:Ms,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var ls={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},Re=zod.z.object({ConfirmationID:zod.z.string(),Url:zod.z.string(),Status:zod.z.string(),PriceCredits:zod.z.number(),ExpiresAt:u}).passthrough(),Oc=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),uC={LoginRequired:"CREDITS_LOGIN_REQUIRED",NotEnough:"NOT_ENOUGH_CREDITS",SellerUnknown:"CREDITS_SELLER_UNKNOWN",PriceChanged:"CREDITS_PRICE_CHANGED",ConfirmationPending:"CREDITS_CONFIRMATION_PENDING",ConfirmationDeclined:"CREDITS_CONFIRMATION_DECLINED",ConfirmationExpired:"CREDITS_CONFIRMATION_EXPIRED",ConfirmationNotFound:"CREDITS_CONFIRMATION_NOT_FOUND",ConfirmationMismatch:"CREDITS_CONFIRMATION_MISMATCH",BatchForbidden:"CREDITS_BATCH_FORBIDDEN",NotAllowedHere:"CREDITS_NOT_ALLOWED_HERE",MixedWithStorePayment:"CREDITS_MIXED_WITH_STORE_PAYMENT",SellerNotReady:"CREDITS_SELLER_NOT_READY",ConfirmationInUse:"CREDITS_CONFIRMATION_IN_USE"},qa=zod.z.object({ServerTimeUtc:u,OfferID:zod.z.string(),Count:zod.z.number(),Resources:O.nullish(),Inventory:K.nullish(),CreditsConfirmation:Re.nullish()}),Ec=zod.z.array(Ee(qa)),cC=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:u,LastPurchasedAt:u}),pC=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:u}),qc=zod.z.object({Purchases:zod.z.record(zod.z.string(),cC).nullish(),Rotations:zod.z.record(zod.z.string(),pC).nullish()}).passthrough().transform(r=>r),Vt=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),di=zod.z.object({Schedule:Se.nullish(),Gate:te.nullish()}).passthrough(),hC={Fixed:"Fixed",Title:"Title",Player:"Player"},dC=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:te.nullish()}).passthrough(),Uc=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(dC).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),mC=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Rotation:J.nullish()}).passthrough(),fC=zod.z.object({SlotID:zod.z.string().nullish(),Identity:Vt.nullish(),Availability:di.nullish(),Rotation:Uc.nullish(),Presets:mC.nullish()}).passthrough(),gC=zod.z.object({Identity:J.nullish(),Availability:J.nullish()}).passthrough(),yC=zod.z.object({SectionID:zod.z.string().nullish(),Identity:Vt.nullish(),Availability:di.nullish(),Slots:zod.z.record(zod.z.string(),fC).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:gC.nullish()}).passthrough(),Lc=zod.z.object({Sections:zod.z.record(zod.z.string(),yC).nullish()}).passthrough(),RC=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Layout:J.nullish()}).passthrough(),CC=zod.z.object({StoreID:zod.z.string().nullish(),Identity:Vt.nullish(),Availability:di.nullish(),Layout:Lc.nullish(),Presets:RC.nullish()}).passthrough(),Bc=zod.z.object({Options:me.nullish(),CompareAt:zod.z.record(zod.z.string(),Nt).nullish()}).passthrough(),Gc=zod.z.object({Grant:$.nullish()}).passthrough(),Nc=zod.z.object({Schedule:Se.nullish(),Gate:te.nullish(),Limits:ve.nullish()}).passthrough(),SC=zod.z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish(),Availability:J.nullish()}).passthrough(),bC=zod.z.object({OfferID:zod.z.string().nullish(),Identity:Vt.nullish(),Pricing:Bc.nullish(),Reward:Gc.nullish(),Availability:Nc.nullish(),Presets:SC.nullish()}).passthrough(),xC=zod.z.object({Identity:zod.z.record(zod.z.string(),Vt).nullish(),Availability:zod.z.record(zod.z.string(),di).nullish(),Layout:zod.z.record(zod.z.string(),Lc).nullish(),Rotation:zod.z.record(zod.z.string(),Uc).nullish(),Pricing:zod.z.record(zod.z.string(),Bc).nullish(),Reward:zod.z.record(zod.z.string(),Gc).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Nc).nullish()}).passthrough(),mi=zod.z.object({Stores:zod.z.record(zod.z.string(),CC).nullish(),StoreOffers:zod.z.record(zod.z.string(),bC).nullish(),Presets:xC.nullish()}).passthrough(),DC=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:u.nullish()}).passthrough(),IC=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:Nt.nullish(),CompareAtCost:Nt.nullish(),DiscountPercent:zod.z.number().nullish(),IsFree:zod.z.boolean(),IsAdPaid:zod.z.boolean(),IsStorePaid:zod.z.boolean(),IsCreditsPaid:zod.z.boolean().nullish(),CreditsPrice:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),PC=zod.z.object({OfferID:zod.z.string(),Identity:Vt.nullish(),PriceOptions:zod.z.array(IC).nullish(),Rewards:$.nullish(),State:DC.nullish()}).passthrough(),vC=zod.z.object({SlotID:zod.z.string(),Identity:Vt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:u.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:PC.nullish()}).passthrough(),AC=zod.z.object({SectionID:zod.z.string(),Identity:Vt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(vC).nullish()}).passthrough(),TC=zod.z.object({StoreID:zod.z.string(),Identity:Vt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:u.nullish(),Sections:zod.z.array(AC).nullish()}).passthrough(),fi=zod.z.object({ServerTimeUtc:u,Stores:zod.z.array(TC).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Ft={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},wC="OFFER_NOT_IN_ROTATION";var _c="Store",Vc={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=null;for(let t of r.Stores??[])for(let n of t.Sections??[])for(let s of n.Slots??[]){let i=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},gi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Vc,{schema:fi,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,n){if(!e)return h("client","OfferID is required.");if(t<1)return h("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return l;let i={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,StoreID:n?.slot?.storeID,SectionID:n?.slot?.sectionID,SlotID:n?.slot?.slotID,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${s.userID}_${V()}`},o=await this.ctx.api.store.purchase(i);if(o.ok&&!o.data.CreditsConfirmation){let p=o.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return o}async purchaseWithCredits(e,t=1,n={}){return await this.ctx.credits.pay(s=>this.purchase(e,t,{selectedOptionID:n.selectedOptionID,slot:n.slot,creditsConfirmationID:s}),{onConfirmation:n.onConfirmation,signal:n.signal,pollMs:n.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):l}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):l}async purchaseBatch(e){if(!e||e.length===0)return h("client","purchases is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},n=await this.ctx.api.store.purchaseBatch(t);if(n.ok){let s=false;for(let i of n.data)!i.Success||!i.Data||!i.Data.OfferID||(this.ctx.data.user.patchStorePurchase(i.Data.OfferID,i.Data.Count,i.Data.ServerTimeUtc),!s&&i.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",n.data);}return n}async getDefinitions(e){let t=this.ctx.cache.configSection(_c,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.store.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(_c,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(Vc,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let n of t.Sections??[])for(let s of n.Slots??[]){let i=s.RefreshesAtUtc;i&&(e===null||Date.parse(i)<Date.parse(e))&&(e=i);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var yi=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let n=await e(void 0);if(!n.ok||!n.data.CreditsConfirmation)return n;let s=n.data.CreditsConfirmation,i=()=>e(s.ConfirmationID);if(this.ctx.host.supports.creditsConfirm){let m=await this.ctx.host.confirmCredits({titleID:this.ctx.settings.titleID,confirmationID:s.ConfirmationID});if(m.ok)return await i();if(m.error==="DECLINED")return h("server","CREDITS_CONFIRMATION_DECLINED");if(m.error==="NOT_ENOUGH_CREDITS")return h("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(s);let o=Math.max(1e3,t.pollMs??2500),p=Date.parse(s.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return h("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>p)return h("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(j=>setTimeout(j,o));let m=await this.ctx.store.getCreditsConfirmation(s.ConfirmationID);if(!m.ok)continue;let g=m.data.Status;if(g!==ls.Pending)return g===ls.Declined?h("server","CREDITS_CONFIRMATION_DECLINED"):g===ls.Expired?h("server","CREDITS_CONFIRMATION_EXPIRED"):await i()}}};var Ri=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return l;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return l;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?G(t.data.Purchase??{}):t}async validatePurchase(e,t,n){if(!t)return h("client","Receipt is required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:n?.signature,ProductID:n?.productID,TransactionID:n?.transactionID},i=await this.ctx.api.purchase.validatePurchase(s);return i.ok&&this.applyValidation(i.data),i}async buyWithTelegramStars(e,t){if(!e)return h("client","productID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(n);return s.ok&&t?.open!==false&&this.ctx.host.openInvoice(s.data.InvoiceLink),s}async buy(e){if(!e)return h("client","productID is required.");if(!this.ctx.host.supports.storePurchases)return h("client","UNAVAILABLE");if(!this.ctx.auth.context)return l;let t=await this.getDefinitions();if(!t.ok)return t;let n=t.data.Purchase?.Products?.[e],s=this.hostStore(),i=n?.StoreProductIDs?.[s];if(!n||n.Enabled===false||!i)return h("client","NOT_SOLD");let o=this.ctx.buildAuthedBaseRequest(),p=await this.ctx.host.buyProduct({storeProductID:i,type:n.Type??"Consumable",accountID:o.UserID??void 0});return !p.ok||!p.receipt?h("client",p.error??"FAILED"):this.deliver(p.receipt,n)}async restorePending(){if(!this.ctx.host.supports.storePurchases||!this.ctx.auth.context)return 0;let e=await this.ctx.host.pendingPurchases();if(e.length===0)return 0;let t=await this.getDefinitions(),n=t.ok?Object.values(t.data.Purchase?.Products??{}):[],s=0;for(let i of e){let o=n.find(p=>i.storeProductID&&p.StoreProductIDs?.[i.store]===i.storeProductID);(await this.deliver(i,o)).ok&&s++;}return s}async deliver(e,t){let n=await this.validatePurchase(e.store,e.receipt,{signature:e.signature});return n.ok&&await this.ctx.host.finishPurchase(e,(t?.Type??"Consumable")==="Consumable"),n}hostStore(){return this.ctx.host.getClientPlatform()===Ne.Ios?"AppleAppStore":"GooglePlay"}async validatePurchasesBatch(e){if(!e||e.length===0)return h("client","receipts is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},n=await this.ctx.api.purchase.validatePurchasesBatch(t);if(n.ok)for(let s of n.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return n}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Fc=3,kC=700,Ci=class{constructor(e){this.ctx=e;e.host.supports.cryptoTopUp&&this.setTopUpHandler(this.hostTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return Un(e)}hostTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let n=await this.ctx.host.topUp({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return n.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:n.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=Fc;t++){let n=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(n.ok)return;if(n.reason!=="throttled"||t===Fc)break;await Zt(kC);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,n])=>({...n,OptionID:n.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,n)=>(t.OptionID??"").localeCompare(n.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let n of t)if(n?.Type===ks.Purchase&&n.ProductID)return n.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let n of t){if(n?.Type!==ks.CryptoCurrency||!n.CurrencyID)continue;let s=Number(n.Amount??0);if(!(s>0))continue;let i=this.cryptoBalance(n.CurrencyID);return i>=s?null:{currencyID:n.CurrencyID,required:s,available:i,missing:s-i}}return null}cryptoBalance(e){let n=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(n?.Amount??0)}};var jc="Lootbox",Si=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(jc,e);if(t){let i={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),G(i)}let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.lootbox.getDefinitions(n);if(s.ok){let i=s.data.LootboxDefinitions;i&&(this.ctx.data.config.patchSection(jc,i),this.ctx.emitter.emit("lootbox:definitionsLoaded",i));}return s}async open(e,t,n,s,i){if(!e)return h("client","LootboxID is required.");if(t<1)return h("client","Count must be at least 1.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:n,Payment:s,CreditsConfirmationID:i,RelatedEntityID:`lootbox_${e}_${n??"default"}_${V()}`},p=await this.ctx.api.lootbox.open(o);if(p.ok&&!p.data.CreditsConfirmation){let m=p.data;m.TriggeredPity&&m.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,m.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(m.Resources,m.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",m);}return p}};var Ua="Reward";function bi(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var xi=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Reward",{needsServer:()=>!t&&Object.values(e.cache.configSection(Ua)?.Comebacks??{}).some(n=>n?.TrackPresenceOnRead===true),refresh:async()=>{let n=await this.getUserRewardsState();return n.ok&&(t=true),n}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(Ua,e);if(t){let i={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),G(i)}let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.reward.getRewardDefinitions(n);if(s.ok){let i=s.data.RewardDefinitions;i&&(this.ctx.data.config.patchSection(Ua,i),this.ctx.emitter.emit("reward:definitionsLoaded",i));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let n=t.data;this.multiplierEnabled=n.Enabled,this.multiplier=n.Enabled?n.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",n);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${V()}`},s=await this.ctx.api.reward.claimDailyReward(n);if(s.ok){let i=s.data;this.ctx.data.user.patchDailyCalendarState(i.CalendarID,i.DailyState),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",i);}return s}async collectIdleAccrual(e){if(!bi(e))return h("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${V()}`},n=await this.ctx.api.reward.collectIdleAccrual(t);if(n.ok){let s=n.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return n}async claimComebackReward(e){if(!bi(e))return h("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${V()}`},n=await this.ctx.api.reward.claimComebackReward(t);if(n.ok){let s=n.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return n}async claimReward(e){if(!bi(e))return h("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${V()}`},n=await this.ctx.api.reward.claimReward(t);if(n.ok){let s=n.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return n}async claimRewardWindow(e,t,n={}){if(!bi(e))return h("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return h("client","Amount must be a positive number.");let s=n.boost??"None";if(s==="Ad"&&!n.adRequestID)return h("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:s,...n.adRequestID?{AdRequestID:n.adRequestID}:{},RelatedEntityID:n.roundID??`reward_window_${e}_${V()}`},o=await this.ctx.api.reward.claimRewardWindow(i);if(o.ok){let p=o.data;this.ctx.data.user.patchRewardWindowState(p.WindowID,p.WindowState),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:windowClaimed",p);}return o}};var Di="Tutorial",Wc={key:"tutorial.state",login:"TutorialState",ttlMs:5*6e4,dependsOn:["Tutorial"],invalidateOn:["tutorial:flowStarted","tutorial:flowSkipped","tutorial:flowReset","tutorial:stepChanged","tutorial:stepsCompletedBatch","tutorial:rewardClaimed","tutorial:systemProgress"]},Ii=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Wc,{schema:Fs,apply:n=>this.applyUserTutorialState(n)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(Di)?.Flows??{}).length>0,refresh:async()=>{let n=await this.getUserTutorialState();return n.ok&&(t=true),n}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(Di,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.tutorial.getTutorialDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Di,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(Wc,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return l;t.AutoStart=e;let n=await this.ctx.api.tutorial.getUserTutorialState(t);return n.ok&&this.applyUserTutorialState(n.data),n}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.reportStepShown(n))}async completeStep(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.completeStep(n),{relatedEntityID:`tutorial_step_${e}_${t}_${V()}`})}async completeStepsBatch(e,t){let n=e?.trim();if(!n)return h("client","FlowID is required.");if(!t||t.length===0)return h("client","stepIDs is required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepIDs:t,RelatedEntityID:`tutorial_batch_${n}_${V()}`},i=await this.ctx.api.tutorial.completeStepsBatch(s);return i.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",i.data)),i}async skipStep(e,t){return this.stepCall(e,t,n=>this.ctx.api.tutorial.skipStep(n))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return h("client","FlowID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${V()}`},s=await this.ctx.api.tutorial.claimFlowReward(n);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,n){let s=e?.trim();if(!s)return h("client","FlowID is required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:s},o=await t(i);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(n.event,o.data)),o}async stepCall(e,t,n,s){let i=e?.trim(),o=t?.trim();if(!i)return h("client","FlowID is required.");if(!o)return h("client","StepID is required.");if(!this.ctx.auth.context)return l;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepID:o};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let m=this.ctx.data.user.state?.Tutorial?.Flows?.[i]?.RewardClaimed===true,g=await n(p);return g.ok&&(this.applyFlowView(g.data),this.mayHavePaid(i,o,m,g.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",g.data)),g}mayHavePaid(e,t,n,s){return !n&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Di)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}};var Pi=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return l;e>0&&(t.Limit=e);let n=await this.ctx.api.communityMarketing.getEarnings(t);return n.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",n.data),n}async claim(e){if(!e)return h("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.CampaignID=e;let n=await this.ctx.api.communityMarketing.claim(t);return n.ok&&this.ctx.emitter.emit("communityMarketing:claimed",n.data),n}async withdrawCryptoReward(e,t,n){if(!e)return h("client","campaignID is required.");if(!t)return h("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return l;s.CampaignID=e,s.WalletAddress=t,n&&(s.Amount=n);let i=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return i.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",i.data),i}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var _e=zod.z.object({Username:zod.z.string().nullish(),Country:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Premium:zod.z.boolean().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BoardRank:zod.z.number().nullish()}).passthrough();var zC={Global:"Global",Announcement:"Announcement",Group:"Group"},Kc=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),MC={None:"None",Language:"Language",Region:"Region"},OC=zod.z.enum(["None","Language","Region"]).catch("None"),EC={Anyone:"Anyone",Friends:"Friends"},qC=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),UC={Reject:"Reject",Mask:"Mask"},LC=zod.z.enum(["Reject","Mask"]).catch("Reject"),BC={Player:"Player",Publisher:"Publisher",System:"System"},GC=zod.z.enum(["Player","Publisher","System"]).catch("Player"),NC={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var _C=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),Qc=zod.z.object({Gate:te.nullish(),Schedule:Se.nullish()}).passthrough(),$c=zod.z.object({Gate:te.nullish(),Limits:ve.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Jc=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),VC=zod.z.object({Availability:J.nullish(),Write:J.nullish(),Retention:J.nullish()}).passthrough(),FC=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:_C.nullish(),Type:Kc.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:OC.nullish(),Capacity:zod.z.number().nullish(),Availability:Qc.nullish(),Write:$c.nullish(),Retention:Jc.nullish(),Presets:VC.nullish()}).passthrough(),jC=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:te.nullish(),WhoCanMessage:qC.nullish(),Limits:ve.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),WC=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:LC.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:ve.nullish()}).passthrough(),HC=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),KC=zod.z.object({Availability:zod.z.record(zod.z.string(),Qc).nullish(),Write:zod.z.record(zod.z.string(),$c).nullish(),Retention:zod.z.record(zod.z.string(),Jc).nullish()}).passthrough(),Zc=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),FC).nullish(),Direct:jC.nullish(),Moderation:WC.nullish(),Polling:HC.nullish(),Presets:KC.nullish()}).passthrough(),QC=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),Hc=zod.z.object({LastAt:zod.z.string().nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:zod.z.string().nullish(),TotalCount:zod.z.number().nullish(),LastTextHash:zod.z.string().nullish()}).passthrough();zod.z.object({MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish(),Ignored:zod.z.array(zod.z.string()).nullish(),Channels:zod.z.record(zod.z.string(),QC).nullish(),Limits:zod.z.record(zod.z.string(),Hc).nullish(),ReportLimits:Hc.nullish()}).passthrough();var La=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),vi=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:_e.nullish(),AuthorType:GC.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),SystemKey:zod.z.string().nullish(),SystemParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$C=zod.z.object({ChannelID:zod.z.string().nullish(),RoomID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Type:Kc.nullish(),CanWrite:zod.z.boolean().nullish(),WriteBlockedReason:zod.z.string().nullish(),SlowModeSeconds:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Ai=zod.z.object({Channels:zod.z.array($C).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),JC=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(vi).nullish(),NextCursor:La.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Yc=zod.z.object({Rooms:zod.z.array(JC).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Xc=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(vi).nullish(),NextBefore:La.nullish()}).passthrough(),ep=zod.z.object({Message:vi.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),tp=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:_e.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),ZC=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:_e.nullish(),LastMessage:vi.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),np=zod.z.object({Conversations:zod.z.array(ZC).nullish()}).passthrough(),Nn=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:La.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),sp=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),st={GetChatDefinitions:"GetChatDefinitions",GetChannels:"GetChannels",Poll:"Poll",GetHistory:"GetHistory",GetConversations:"GetConversations",SendMessage:"SendMessage",OpenDirectChannel:"OpenDirectChannel",MarkRead:"MarkRead",JoinChannel:"JoinChannel",LeaveChannel:"LeaveChannel",ReportMessage:"ReportMessage",IgnoreUser:"IgnoreUser",UnignoreUser:"UnignoreUser"};var ip="Chat",rp={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Ti=class{constructor(e){this.ctx=e;e.cache.bindLoginView(rp,{schema:Ai,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(ip,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.chat.getChatDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(ip,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(rp,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.Locale=e);let n=await this.ctx.api.chat.getChannels(t);return n.ok&&this.ctx.emitter.emit("chat:channelsLoaded",n.data),n}async poll(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let n=await this.ctx.api.chat.poll(t);if(!n.ok)return n;for(let s of n.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return n}async getHistory(e,t,n){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),n&&(s.Limit=n),this.ctx.api.chat.getHistory(s)):l}async sendMessage(e,t,n){let s=this.ctx.authedRequest();if(!s)return l;s.ChannelID=e,s.Text=t,n&&(s.Locale=n);let i=await this.ctx.api.chat.sendMessage(s);return i.ok&&this.ctx.emitter.emit("chat:sent",i.data),i}async sendDirect(e,t){let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.Text=t;let s=await this.ctx.api.chat.sendMessage(n);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):l}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):l}async markRead(e,t){let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(n);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):l}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):l}async reportMessage(e,t,n,s){let i=this.ctx.authedRequest();return i?(i.RoomID=e,i.MessageID=t,i.Reason=n,s&&(i.Comment=s),this.ctx.api.chat.reportMessage(i)):l}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):l}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):l}resetCursors(){this.cursors.clear();}};var YC={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},XC=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),eS={Player:"player",Title:"title",Creator:"creator"},_n={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},op=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),tS=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),Ba=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:XC.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(tS).nullish()}).passthrough(),ap=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(Ba).nullish()}).passthrough(),it={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var nS="IDOS_PLATFORM_PUSH_REQUEST",sS="IDOS_PLATFORM_PUSH_RESPONSE",iS=12e4;function lp(r){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(n=>{let s=false,i=m=>{s||(s=true,window.removeEventListener("message",o),clearTimeout(p),n(m));},o=m=>{let g=m?.data;!g||g.type!==sS||g.requestId!==t||It.includes(m.origin)&&i(g.ok===true);},p=setTimeout(()=>i(false),iS);window.addEventListener("message",o);for(let m of It)try{e.postMessage({type:nS,requestId:t,titleID:r},m);}catch{}})}var rS="idos:push:deviceToken:",wi=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let n=await this.ctx.api.push.getPushConfig(t),s=n.ok?n.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,n.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(this.ctx.host.supports.pushNotifications){if(!e.Configured)return it.Unsupported;let i=await this.ctx.host.requestPushToken({prompt:false});return i.error==="BLOCKED"?it.Blocked:i.token?this.ctx.host.storage.getString(this.deviceTokenKey())===i.token?it.Subscribed:it.Idle:i.error==="NOT_GRANTED"?it.Idle:it.Unsupported}if(!e.Configured||!e.PublicKey)return it.Unsupported;if(this.isEmbedded())return it.Embedded;if(!this.isSupported())return it.Unsupported;let t=Notification.permission;return t==="denied"?it.Blocked:t!=="granted"?it.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?it.Subscribed:it.Idle}async subscribe(e={}){let t=await this.getConfig();if(this.ctx.host.supports.pushNotifications)return this.subscribeDevice(t,e);if(!t.Configured||!t.PublicKey)return h("client","Push notifications are not available for this title.");if(this.isEmbedded())return await lp(this.ctx.settings.titleID)?G({Where:"portal",Subscription:null}):h("client","The portal did not complete the subscription.");if(!this.isSupported())return h("client","This browser has no Push API.");let n=await Notification.requestPermission();if(n!=="granted")return h("client",n==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:oS(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return l;let m=o.toJSON();p.PushEndpoint=m.endpoint,p.PushP256dh=m.keys?.p256dh,p.PushAuth=m.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let g=await this.ctx.api.push.subscribePush(p);return g.ok?(this.ctx.emitter.emit("push:subscribed",g.data),G({Where:"game",Subscription:g.data})):g}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return l;if(this.ctx.host.supports.pushNotifications){let n=this.ctx.host.storage.getString(this.deviceTokenKey());if(!n)return h("client","This device has no push subscription to remove.");e.PushDeviceToken=n;let s=await this.ctx.api.push.unsubscribePush(e);return s.ok&&(this.ctx.host.storage.remove(this.deviceTokenKey()),this.ctx.emitter.emit("push:unsubscribed",void 0)),s}if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return h("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):l}async unsubscribeByHash(e){if(!e)return h("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return l;t.PushEndpointHash=e;let n=await this.ctx.api.push.unsubscribePush(t);return n.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),n}async subscribeDevice(e,t){if(!e.Configured)return h("client","Push notifications are not available for this title.");let n=await this.ctx.host.requestPushToken({prompt:true});if(!n.token)return h("client",n.error==="BLOCKED"?"The player blocked notifications for this app.":"The device gave no push token.");let s=this.ctx.authedRequest();if(!s)return l;s.PushTransport=n.transport??"Fcm",s.PushDeviceToken=n.token,s.PushLocale=t.locale??(this.ctx.host.getLanguage()||void 0),s.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let i=await this.ctx.api.push.subscribePush(s);return i.ok?(this.ctx.host.storage.setString(this.deviceTokenKey(),n.token),this.ctx.emitter.emit("push:subscribed",i.data),G({Where:"game",Subscription:i.data})):i}deviceTokenKey(){return rS+this.ctx.settings.titleID}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function oS(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),n=new ArrayBuffer(t.length),s=new Uint8Array(n);for(let i=0;i<t.length;i++)s[i]=t.charCodeAt(i);return n}var ki=Object.freeze({}),zi=class{constructor(e){this.ctx=e;}ctx;table={...ki};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new Gn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,n])=>({Locale:n?.Locale??t,DisplayName:n?.DisplayName??null,Order:n?.Order??0})).sort((t,n)=>(t.Order??0)-(n.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let n=this.resolveKey(e,t),s=this.lookup(n)??this.lookup(e);return s===void 0?this.onMissing(e):t?aS(s,t):s}applyState(e,t){if(!e){this.reset();return}let n=e.Locale??null;this.table=t.table??{...ki},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return l;let n=await this.loadTableFromApi(e);if(!n.ok)return n;let{locale:s,table:i,fallbackLocale:o}=n.data,p=null;if(o){let m=await this.loadTableFromApi(o);m.ok&&(p=m.data.table);}return this.table=i,this.fallbackTable=p,this.currentFallbackLocale=o,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:o,entryCount:Object.keys(i).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):l}reset(){this.table={...ki},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:V()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return l;t.Locale=e;let n=await this.cache.read(up(e));n&&(t.KnownVersion=n.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let i=s.data,o=i.Locale??up(e),p=i.Version??0;if(i.NotModified){let g=n??await this.cache.read(o);return {ok:true,data:{locale:o,table:g?.t??{...ki},fallbackLocale:i.FallbackLocale??null}}}let m=i.Entries??{};return p>0&&await this.cache.write(o,p,m),{ok:true,data:{locale:o,table:m,fallbackLocale:i.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let n=t?.count;if(typeof n!="number")return e;let s=this.pluralCategory(n),i=`${e}.${s}`;if(this.lookup(i)!==void 0)return i;let o=`${e}.other`;return this.lookup(o)!==void 0?o:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function aS(r,e){return r.replace(/\{(\w+)\}/g,(t,n)=>{let s=e[n];return s===void 0?t:String(s)})}function up(r){return r.trim().replace(/_/g,"-").toLowerCase()}var Ga="Quest",lS={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:r=>{let e=Date.now(),t=null,n=[...Object.values(r.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(r.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of n){let i=Date.parse(s??"");!Number.isNaN(i)&&i>e&&(t===null||i<t)&&(t=i);}return t}},Mi=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:n=>{let s=e.cache.configSection(Ga)?.Cycles;if(!s)return false;let i=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(s)){let p=Date.parse(i[o]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=n&&t<p)return true}return false},refresh:async()=>{let n=await this.getUserQuestState(true,{forceRefresh:true});return n.ok&&(t=Date.now()),n}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(Ga,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.quest.getQuestDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Ga,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(lS,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return l;t.AutoRefreshCycles=e;let n=await this.ctx.api.quest.getUserQuestState(t);if(n.ok){let s=n.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(n.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return n}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let n=e.trim();if(!n)return h("client","QuestID is required.");if(!this.ctx.auth.context)return l;let s=t&&t.trim().length>0?t.trim():void 0,i={...this.ctx.buildAuthedBaseRequest(),QuestID:n,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${n}_${V()}`},o=await this.ctx.api.quest.claimQuestReward(i);if(o.ok){let p=o.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return h("client","quests is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},n=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(n.ok){let s=false;for(let i of n.data)!i.Success||!i.Data||(this.ctx.data.user.patchQuestStatus(i.Data.QuestID,i.Data.CycleID,"Claimed"),!s&&i.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",n.data);}return n}async claimMilestoneReward(e,t){let n=e.trim(),s=t.trim();if(!n||!s)return h("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),CycleID:n,MilestoneID:s,RelatedEntityID:`milestone_claim_${n}_${s}_${V()}`},o=await this.ctx.api.quest.claimMilestoneReward(i);if(o.ok){let p=o.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return h("client","milestones is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(n.ok){let s=false;for(let i of n.data)!i.Success||!i.Data||(this.ctx.data.user.patchMilestoneClaimed(i.Data.CycleID,i.Data.MilestoneID),!s&&i.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",n.data);}return n}async claimGroupCompletionReward(e,t){let n=e.trim(),s=t.trim();if(!n||!s)return h("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),CycleID:n,GroupCompletionID:s,RelatedEntityID:`group_completion_${n}_${s}_${V()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(i);if(o.ok){let p=o.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return o}async addQuestProgress(e,t){let n=e.trim();if(!n)return h("client","MetricID is required.");if(t<0)return h("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:n,ProgressValue:t},i=await this.ctx.api.quest.addQuestProgress(s);return i.ok&&(this.ctx.data.user.patchQuestProgressUpdates(i.data.Updates),this.ctx.emitter.emit("quest:progressAdded",i.data)),i}};var cp=zod.z.object({}).passthrough().transform(r=>r);var uS=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),cS=zod.z.object({Schedule:zod.z.array(uS).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),pS=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:u.nullish(),NextBonusStartUtc:u.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),hS=zod.z.object({Milestones:J.nullish()}).passthrough(),Na=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Category:zod.z.string().nullish(),Token:Mt.nullish(),TokenSources:zod.z.array(ft).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),Presets:hS.nullish(),BonusWindow:cS.nullish()}).passthrough(),dS=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:Na.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),mS=zod.z.object({TimedEventID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:Se.nullish(),Content:Na.nullish(),Events:zod.z.array(dS).nullish(),Gate:te.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),fS=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),gS=zod.z.object({Milestones:zod.z.record(zod.z.string(),On).nullish()}).passthrough(),Oi=zod.z.object({Definitions:zod.z.record(zod.z.string(),mS).nullish(),Settings:fS.nullish(),Presets:gS.nullish()}).passthrough(),yS=zod.z.object({Type:es,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:Na.nullish(),Progress:cp.nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:je.nullish(),BonusWindow:pS.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),Ei=zod.z.object({ActiveEvents:zod.z.array(yS).nullish()}).passthrough(),pp=zod.z.object({Tokens:zod.z.record(zod.z.string(),cp).nullish()}),_a=zod.z.object({Type:es.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),Va=zod.z.object({Type:es.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}),RS=zod.z.object({Type:es.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),Fa=zod.z.array(Ee(Va)),hp=zod.z.array(Ee(_a)),dp=zod.z.array(Ee(RS)),Rt={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var mp="TimedEvent",fp={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:r=>{let e=null;for(let t of r.ActiveEvents??[]){let n=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},qi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fp,{schema:Ei,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(fp,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(mp,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.timedEvent.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(mp,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,n,s,i,o,p=1){if(!t)return h("client","LteID is required.");if(!n)return h("client","SourceType is required.");if(!this.ctx.auth.context)return l;let m={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:n,Outcome:s,AmountOverride:i,SourceParams:o,RollMultiplier:p},g=await this.ctx.api.timedEvent.grantTokens(m);return g.ok&&(this.ctx.data.user.applyResourceOperation(g.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",g.data)),g}async spendTokens(e,t,n){if(!t)return h("client","LteID is required.");if(n<=0)return h("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:n},i=await this.ctx.api.timedEvent.spendTokens(s);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",i.data)),i}async claimMilestone(e,t,n){if(!t||!n)return h("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:n},i=await this.ctx.api.timedEvent.claimMilestone(s);if(i.ok){let o=i.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,n,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return h("client","milestones is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return n.ok&&(this.applyMilestoneClaimBatch(n.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",n.data)),n}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return l;e&&e.length>0&&(t.Events=e);let n=await this.ctx.api.timedEvent.claimAllMilestones(t);return n.ok&&(this.applyMilestoneClaimBatch(n.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",n.data)),n}async spendTokensBatch(e){if(!e||e.length===0)return h("client","spends is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},n=await this.ctx.api.timedEvent.spendTokensBatch(t);if(n.ok){let s=false;for(let i of n.data)!s&&i.Success&&i.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(i.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",n.data);}return n}async grantTokensBatch(e){if(!e||e.length===0)return h("client","grants is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},n=await this.ctx.api.timedEvent.grantTokensBatch(t);if(n.ok){let s=false;for(let i of n.data)!s&&i.Success&&i.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(i.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",n.data);}return n}applyMilestoneClaimBatch(e){let t=false;for(let n of e){if(!n.Success||!n.Data)continue;let s=n.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var CS=zod.z.object({UserID:zod.z.string(),Score:Q.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:u.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:_e.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),us=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:Q.nullish(),CycleEndUtc:u.nullish(),TopUsers:zod.z.array(CS).nullish(),BracketID:zod.z.string().nullish()}),SS=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),MilestoneTokensEarned:Q.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Ui=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:Q.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:Q.nullish(),MilestoneTokensEarned:Q.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:je.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(SS).nullish()}),Li=zod.z.object({LeaderboardID:zod.z.string(),NewScore:Q,CycleVersion:zod.z.number()}),Bi=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Gi=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish()}),gp=zod.z.array(Ee(us)),Ni=zod.z.array(Ee(Ui)),yp=zod.z.array(Ee(Bi)),Rp=zod.z.array(Ee(Gi)),Cp=zod.z.array(Ee(Li)),bS=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:Ee(Bi).nullish(),Milestones:zod.z.array(Ee(Gi)).nullish()}),Sp=zod.z.array(bS),xS=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:Ee(us).nullish(),Progress:Ee(Ui).nullish()}),bp=zod.z.array(xS),DS=zod.z.string(),xp=zod.z.object({Rank:zod.z.string().nullish(),Rewards:$.nullish(),SeasonTierRewards:ba.nullish()}).passthrough(),IS=zod.z.object({RankRewards:zod.z.array(xp).nullish()}).passthrough(),PS=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),vS=zod.z.object({Milestones:J.nullish(),RankRewards:J.nullish()}).passthrough(),AS=zod.z.object({LeaderboardID:zod.z.string(),DisplayName:zod.z.string().nullish(),ScoreDisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsEnabled:zod.z.boolean().nullish(),ScoreAggregation:DS.nullish(),Schedule:Se.nullish(),ChainEvents:zod.z.array(PS).nullish(),Gate:te.nullish(),TopUsersLimit:zod.z.number().nullish(),MinScoreToEnterTop:zod.z.number().nullish(),BracketSize:zod.z.number().nullish(),LinkedSeasonChainID:zod.z.string().nullish(),RankRewards:zod.z.array(xp).nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),Presets:vS.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(ft).nullish()}).passthrough(),TS=zod.z.object({Milestones:zod.z.record(zod.z.string(),On).nullish(),RankRewards:zod.z.record(zod.z.string(),IS).nullish()}).passthrough(),_i=zod.z.object({Definitions:zod.z.record(zod.z.string(),AS).nullish(),Presets:TS.nullish()}).passthrough(),Ye={GetDefinitions:"GetDefinitions",GetLeaderboard:"GetLeaderboard",GetMyProgress:"GetMyProgress",SubmitScore:"SubmitScore",SubmitScoreFromSource:"SubmitScoreFromSource",ClaimCycleReward:"ClaimCycleReward",ClaimMilestone:"ClaimMilestone",GetFriendsLeaderboard:"GetFriendsLeaderboard",GetLeaderboardsBatch:"GetLeaderboardsBatch",GetProgressBatch:"GetProgressBatch",ClaimCycleRewardsBatch:"ClaimCycleRewardsBatch",ClaimMilestonesBatch:"ClaimMilestonesBatch",SubmitScoresBatch:"SubmitScoresBatch",ClaimAllRewardsBatch:"ClaimAllRewardsBatch",GetOverviewBatch:"GetOverviewBatch"};var Dp="Leaderboard",Ip={key:"leaderboard.progress",login:"LeaderboardProgress",ttlMs:5*6e4,dependsOn:["Leaderboard","EventToken"],invalidateOn:["leaderboard:scoreSubmitted","leaderboard:scoresSubmittedBatch","leaderboard:cycleRewardClaimed","leaderboard:cycleRewardsClaimedBatch","leaderboard:milestoneClaimed","leaderboard:milestonesClaimedBatch","leaderboard:allRewardsClaimedBatch"]},Vi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ip,{schema:Ni,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Dp,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.leaderboard.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Dp,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return h("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getLeaderboard(t);return n.ok&&this.ctx.emitter.emit("leaderboard:loaded",n.data),n}async getMyProgress(e){if(!e)return h("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getMyProgress(t);return n.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),n.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",n.data)),n}async submitScore(e,t){if(!e)return h("client","LeaderboardID is required.");if(t<=0)return h("client","Score must be positive.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(n);if(s.ok){let i=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),i.NewScore,t,i.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",i);}return s}async submitScoreFromSource(e,t,n,s,i=1){if(!e)return h("client","LeaderboardID is required.");if(!t)return h("client","SourceType is required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:n,Params:s,RollMultiplier:i},p=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(p.ok){let m=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),m.NewScore,m.NewScore,m.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",m);}return p}async claimCycleReward(e){if(!e)return h("client","LeaderboardID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},n=await this.ctx.api.leaderboard.claimCycleReward(t);if(n.ok){let s=n.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return n}async claimMilestone(e,t,n){if(!e||!t)return h("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...n?{CycleKey:n}:{}},i=await this.ctx.api.leaderboard.claimMilestone(s);if(i.ok){let o=i.data;n||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",o);}return i}async getFriendsLeaderboard(e){if(!e)return h("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardID=e;let n=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return n.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",n.data),n}async getLeaderboardsBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return n.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",n.data),n}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(h("client","leaderboardIDs is required.")):this.ctx.cache.read(Ip,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getProgressBatch(t);return n.ok&&this.applyProgressBatch(n.data),n}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},n=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(n.ok){for(let s of n.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",n.data);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return h("client","milestones is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},n=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(n.ok){for(let s of n.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",n.data);}return n}async submitScoresBatch(e){if(!e||e.length===0)return h("client","scores is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},n=await this.ctx.api.leaderboard.submitScoresBatch(t);if(n.ok){for(let s of n.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",n.data);}return n}async claimAllRewardsBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},n=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(n.ok){for(let s of n.data){let i=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(i),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of s.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(i,o.Data.MilestoneID),o.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(o.Data.Resources,o.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",n.data);}return n}async getOverviewBatch(e){if(!e||e.length===0)return h("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return l;t.LeaderboardIDs=e;let n=await this.ctx.api.leaderboard.getOverviewBatch(t);if(n.ok){for(let s of n.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",n.data);}return n}};var ja=zod.z.object({}).passthrough().transform(r=>r),Fi=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>Tp).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:Q.nullish(),UserState:ja.nullish(),NextTier:zod.z.lazy(()=>Ap).nullish()}).passthrough(),Pp=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:Q.nullish(),NewStatusTokens:Q.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),Wa=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:O.nullish(),Inventory:K.nullish()}),vp=Ot(Wa);var Ap=zod.z.object({Tier:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredTokens:Q.nullish(),TierReachedReward:$.nullish()}).passthrough(),Tp=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:Q.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(Ap).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var wS=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Se.nullish(),Seasons:zod.z.array(Tp).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:te.nullish()}).passthrough(),ji=zod.z.object({Chains:zod.z.record(zod.z.string(),wS).nullish()}).passthrough(),Xt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var wp="Season",kp={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=Date.parse(r.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Wi=class{constructor(e){this.ctx=e;e.cache.bindLoginView(kp,{schema:Fi,apply:(t,n)=>this.applyActiveSeason(n??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(wp,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.season.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(wp,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(kp,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(h("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return l;t.SeasonChainID=e;let n=await this.ctx.api.season.getActiveSeason(t);return n.ok&&this.applyActiveSeason(e,n.data),n}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return h("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.SeasonChainID=e;let n=await this.ctx.api.season.getUserState(t);return n.ok&&(this.ctx.data.user.patchSeasonState(e,n.data),this.ctx.emitter.emit("season:userStateLoaded",n.data)),n}async grantStatusTokens(e,t){if(!e)return h("client","SeasonChainID is required.");if(t<=0)return h("client","Amount must be positive.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${V()}`},s=await this.ctx.api.season.grantStatusTokens(n);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return h("client","SeasonChainID is required.");if(t<=0)return h("client","TierNumber must be positive.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${V()}`},s=await this.ctx.api.season.claimTierReward(n);if(s.ok){let i=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(i.Resources,i.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",i);}return s}async claimTierRewardsBatch(e,t){if(!e)return h("client","SeasonChainID is required.");let n=(t??[]).filter(o=>o>0);if(n.length===0)return h("client","TierNumbers is required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:n,RelatedEntityID:`season_tier_batch_${e}_${V()}`},i=await this.ctx.api.season.claimTierRewardsBatch(s);if(i.ok){let o=i.data;for(let p of o.Items??[]){let m=p.Data?.TierNumber;p.Success&&typeof m=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,m);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return i}};var zp="Premium",Hi=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(zp,e);if(t){let i={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",i),G(i)}let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.premium.getDefinitions(n);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(zp,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return h("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(n);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,n="Default",s=1,i){if(!e||!t)return h("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:n,Count:s,CreditsConfirmationID:i,RelatedEntityID:`premium_purchase_${e}_${t}`},p=await this.ctx.api.premium.purchaseItemOrCurrency(o);if(p.ok&&!p.data.CreditsConfirmation){let m=p.data;m.Premium&&this.ctx.data.user.applyPremium(m.Premium),this.ctx.data.user.applyResourceOperation(m.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",m);}return p}async purchaseRealMoney(e,t,n,s,i,o,p,m){if(!e||!t)return h("client","PremiumID and TransactionID are required.");if(!s||!i)return h("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return l;let g={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:n,ProductID:s,ReceiptData:i,PurchaseToken:o,PackageName:p,AppStoreEnvironment:m,RelatedEntityID:`premium_iap_${e}_${t}`},j=await this.ctx.api.premium.purchaseRealMoney(g);if(j.ok){let pe=j.data;pe.Premium&&this.ctx.data.user.applyPremium(pe.Premium),this.ctx.data.user.applyResourceOperation(pe.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",pe);}return j}};var Ki=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:u.nullish()}),cs=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:Q.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),Ki).nullish(),UpdatedAt:u.nullish()}).passthrough(),Mp=zod.z.object({Characters:zod.z.record(zod.z.string(),cs).nullish(),SelectedCharacterID:zod.z.string().nullish()}),Ha=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Ka=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Op=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Ki).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Ep=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),kS=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),qp=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),kS).nullish(),Inventory:K.nullish()}),Qa=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Up=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:Ki.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Lp=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Ki.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Bp=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),zS=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:u.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:me.nullish()}),MS=zod.z.object({CharacterID:zod.z.string(),CharacterOpen:zod.z.boolean().nullish(),DefaultSkinID:zod.z.string().nullish(),WornSkinID:zod.z.string().nullish(),Skins:zod.z.array(zS).nullish()}),Gp=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),MS).nullish()}),Np=zod.z.object({ServerTimeUtc:u,SelectedCharacterID:zod.z.string().nullish()}),_p=Ot(Qa),Vp=Ot(Ka),Fp=Ot(Ha),$a=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),jp=zod.z.object({StatID:zod.z.string(),TypeID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish(),Weight:zod.z.number().nullish(),PriceOptions:me.nullish(),CostCurve:Ze.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Ze.nullish(),RankCurve:Ze.nullish(),Requirements:zod.z.array($a).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),OS=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array($a).nullish(),AllowedRarityIDs:zod.z.array(zod.z.string()).nullish(),AllowedItemTags:zod.z.array(zod.z.string()).nullish(),MinItemLevel:zod.z.number().nullish(),MaxItemLevel:zod.z.number().nullish()}).passthrough(),Wp=zod.z.object({Slots:zod.z.record(zod.z.string(),OS).nullish()}).passthrough(),Hp=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Lore:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ES=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),qS=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:me.nullish()}).passthrough(),US=zod.z.object({Stats:J.nullish(),Levels:J.nullish(),Equipment:J.nullish()}).passthrough(),Kp=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:me.nullish(),CostCurve:Ze.nullish()}).passthrough(),Ja="@skin";function LS(r){return !!r&&r.startsWith("@")}var BS=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),GS=zod.z.object({PriceOptions:me.nullish(),Schedule:Se.nullish(),Gate:te.nullish()}).passthrough(),NS=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array($a).nullish()}).passthrough(),_S=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Hp.nullish(),Item:BS.nullish(),Sale:GS.nullish(),Requirements:NS.nullish()}).passthrough(),VS=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),_S).nullish()}).passthrough(),FS=zod.z.object({CharacterID:zod.z.string(),Identity:Hp.nullish(),Classification:ES.nullish(),Unlock:qS.nullish(),Presets:US.nullish(),Equipment:Wp.nullish(),Stats:zod.z.record(zod.z.string(),jp).nullish(),RankLadder:Kp.nullish(),RankStatCurve:Ze.nullish(),StatMaxLevelCurve:Ze.nullish(),Skins:VS.nullish()}).passthrough(),jS=zod.z.object({Stats:zod.z.record(zod.z.string(),jp).nullish()}).passthrough(),WS=zod.z.object({RankLadder:Kp.nullish()}).passthrough(),HS=zod.z.object({Equipment:Wp.nullish()}).passthrough(),KS=zod.z.object({Stats:zod.z.record(zod.z.string(),jS).nullish(),Levels:zod.z.record(zod.z.string(),WS).nullish(),Equipment:zod.z.record(zod.z.string(),HS).nullish()}).passthrough(),Qi=zod.z.object({Definitions:zod.z.record(zod.z.string(),FS).nullish(),Presets:KS.nullish()}).passthrough(),Je={GetCharacterDefinitions:"GetCharacterDefinitions",GetUserCharacters:"GetUserCharacters",UnlockCharacter:"UnlockCharacter",UpgradeStatLevel:"UpgradeStatLevel",UpgradeCharacterLevel:"UpgradeCharacterLevel",EquipItems:"EquipItems",UnequipItems:"UnequipItems",UnequipAllCharacters:"UnequipAllCharacters",UnlockCharactersBatch:"UnlockCharactersBatch",UpgradeCharacterLevelsBatch:"UpgradeCharacterLevelsBatch",UpgradeStatLevelsBatch:"UpgradeStatLevelsBatch",UnlockSkin:"UnlockSkin",EquipSkin:"EquipSkin",UnequipSkin:"UnequipSkin",GetCharacterSkins:"GetCharacterSkins",SelectCharacter:"SelectCharacter"},QS="SKIN_ALREADY_OWNED";var Za="Character",$i=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Za)?.Definitions,n=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,i])=>i?.Unlock?.UnlockedByDefault===true&&!n[i.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(Za,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.character.getCharacterDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Za,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let n=t.data.Characters??{};this.ctx.data.user.applyCharacter(n),this.ctx.data.user.applySelectedCharacter(t.data.SelectedCharacterID),this.ctx.emitter.emit("character:userCharactersLoaded",n);}return t}async unlockCharacter(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${V()}`},s=await this.ctx.api.character.unlockCharacter(n);if(s.ok&&!s.data.CreditsConfirmation){let i=s.data;this.ctx.data.user.patchCharacter(i.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},i.Power!=null&&(o.Power=i.Power),o.UpdatedAt=i.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(i.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",i);}return s}async upgradeStatLevel(e,t,n){if(!e||!t)return h("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${V()}`,SelectedOptionID:n?.selectedOptionID,CreditsConfirmationID:n?.creditsConfirmationID,...n?.levels!=null?{Levels:n.levels}:{},...n?.targetLevel!=null?{TargetLevel:n.targetLevel}:{}},i=await this.ctx.api.character.upgradeStatLevel(s);if(i.ok&&!i.data.CreditsConfirmation){let o=i.data;this.ctx.data.user.patchCharacter(o.CharacterID,p=>{p.StatLevels??={},p.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(p.Power=o.Power),p.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return i}async upgradeCharacterLevel(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${V()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(n);if(s.ok&&!s.data.CreditsConfirmation){let i=s.data;this.ctx.data.user.patchCharacter(i.CharacterID,o=>{o.Level=i.NewLevel,i.Power!=null&&(o.Power=i.Power),o.UpdatedAt=i.ServerTimeUtc,i.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(i.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",i);}return s}async equipItems(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(n);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(n);if(s.ok){let i=s.data;this.applyUnequipChangesLocally(e,i),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:i.ClearedSlotIDs??[],power:i.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,n){if(!e||!t)return h("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,AutoEquip:n?.autoEquip??false,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${V()}`},i=await this.ctx.api.character.unlockSkin(s);if(i.ok&&!i.data.CreditsConfirmation){let o=i.data;this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),o.Equipped&&o.Equipment&&this.applySkinLocally(o.CharacterID,o.Equipment,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",o);}return i}async equipSkin(e,t,n){if(!e||!t)return h("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:n},i=await this.ctx.api.character.equipSkin(s);if(i.ok){let o=i.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return i}async unequipSkin(e){if(!e)return h("client","CharacterID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},n=await this.ctx.api.character.unequipSkin(t);if(n.ok){let s=n.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return n}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):l}async selectCharacter(e){let t=this.ctx.authedRequest();if(!t)return l;let n=e?.trim();if(!n)return h("client","CharacterID is required.");t.CharacterID=n;let s=await this.ctx.api.character.selectCharacter(t);return s.ok&&(this.ctx.data.user.applySelectedCharacter(s.data.SelectedCharacterID),this.ctx.emitter.emit("character:selected",s.data)),s}applySkinLocally(e,t,n,s){let i=this.ctx.data.user;i.patchCharacterEquipment(e,Ja,t??null),i.patchCharacter(e,o=>{n!=null&&(o.Power=n),o.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return h("client","characterIDs is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},n=await this.ctx.api.character.unlockCharactersBatch(t);return n.ok&&(this.applyBatchResults(n.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,i=>{i.Level??=1,i.StatLevels??={},i.Equipment??={},s.Power!=null&&(i.Power=s.Power),i.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",n.data)),n}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return h("client","upgrades is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},n=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return n.ok&&(this.applyBatchResults(n.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,i=>{i.Level=s.NewLevel,s.Power!=null&&(i.Power=s.Power),i.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(i.StatLevels??={},i.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",n.data)),n}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return h("client","upgrades is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},n=await this.ctx.api.character.upgradeStatLevelsBatch(t);return n.ok&&(this.applyBatchResults(n.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,i=>{i.StatLevels??={},i.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(i.Power=s.Power),i.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",n.data)),n}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let n of e.Items??[])!n.Success||!n.Data||t(n.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[s,i]of Object.entries(t.Equipment??{}))n.patchCharacterEquipment(e,s,i);n.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let n=t.ClearedSlotIDs??[];if(n.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let i of n)s.patchCharacterEquipment(e,i,null);s.patchCharacter(e,i=>{t.Power!=null&&(i.Power=t.Power),i.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[n,s]of Object.entries(e.Characters??{})){for(let i of s.ClearedSlotIDs??[])t.patchCharacterEquipment(n,i,null);t.patchCharacter(n,i=>{s.Power!=null&&(i.Power=s.Power),i.UpdatedAt=e.ServerTimeUtc;});}}};var Qp="Match",Ji=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,n,s,i,o){let p=this.ctx.auth.context;if(!p)return l;let m={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:n,BattleStrategy:s,TargetUserID:i,SelectedOptionID:o,RelatedEntityID:`pvp_create_${p.userID}_${V()}`},g=await this.ctx.api.match.createMatch(m);return g.ok&&(this.ctx.data.user.applyResourceOperation(g.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",g.data)),g}async updateMatch(e,t={}){if(!e)return h("client","MatchID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(n);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return h("client","MatchID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},n=await this.ctx.api.match.cancelMatch(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",n.data)),n}async instantBattle(e,t,n,s){let i=this.ctx.auth.context;if(!i)return l;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:n,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${V()}`},p=await this.ctx.api.match.instantBattle(o);if(p.ok){let m=p.data,g=this.ctx.data.config.itemDefinitions;if(m.Resources)this.ctx.data.user.applyResourceOperation(m.Resources,g);else if(m.ResourcesDual){let j=m.ResourcesDual;j.FromUserID===i.userID&&j.FromResult?this.ctx.data.user.applyResourceOperation(j.FromResult,g):j.ToUserID===i.userID&&j.ToResult&&this.ctx.data.user.applyResourceOperation(j.ToResult,g);}this.ctx.emitter.emit("match:instantBattleCompleted",m);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},n=await this.ctx.api.match.saveStrategy(t);return n.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),n}async getMyMatches(e=0,t=20,n){let s=this.ctx.authedRequest();if(!s)return l;s.Page=e,s.PageSize=t,s.Statuses=n;let i=await this.ctx.api.match.getMyMatches(s);return i.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",i.data),i}async getAvailableMatches(e=0,t=20,n=false){let s=this.ctx.authedRequest();if(!s)return l;s.Page=e,s.PageSize=t,s.OnlyPublic=n;let i=await this.ctx.api.match.getAvailableMatches(s);return i.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",i.data),i}async getDefinitions(e){let t=this.ctx.cache.configSection(Qp,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.match.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Qp,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var $S="Challenge",Zi=class{constructor(e){this.ctx=e;}ctx;lastState=null;get definitions(){return this.ctx.cache.configSection($S)??null}get state(){return this.lastState}chainDefinition(e){return this.definitions?.Chains?.[e]??null}phaseDefinition(e,t){return t?this.chainDefinition(e)?.Challenges?.find(n=>n?.ChallengeID===t)??null:null}chainView(e){return this.lastState?.Chains?.find(t=>t.ChainID===e)??null}newAttemptID(){return V().replace(/-/g,"")}async getState(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.ChainID=e);let n=await this.ctx.api.challenge.getState(t);return n.ok&&this.applyState(n.data,e),n}async refreshOpponents(e){if(!e)return h("client","ChainID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.ChainID=e;let n=await this.ctx.api.challenge.refreshOpponents(t);return n.ok&&this.applyState(n.data,e),n}async attempt(e,t,n,s,i){if(!e)return h("client","ChainID is required.");if(!n)return h("client","AttemptID is required.");let o=this.ctx.authedRequest();if(!o)return l;o.ChainID=e,o.AttemptID=n,"tierID"in t?o.TierID=t.tierID:o.RevengeID=t.revengeID,s&&(o.CharacterID=s),i&&(o.BattleStrategy=i);let p=await this.ctx.api.challenge.attempt(o);if(p.ok){let m=p.data;m.IsReplay||this.ctx.data.user.applyResourcesWithDelta(m.Rewards,m.Inventory,this.ctx.data.config.itemDefinitions),this.patchAfterAttempt(e,m,"revengeID"in t?t.revengeID:void 0),this.ctx.emitter.emit("challenge:attemptCompleted",m);}return p}async claimMilestone(e,t,n){if(!e||!t)return h("client","ChainID and MilestoneID are required.");let s=this.ctx.authedRequest();if(!s)return l;s.ChainID=e,s.MilestoneID=t,n&&(s.InstanceKey=n);let i=await this.ctx.api.challenge.claimMilestone(s);if(i.ok){let o=i.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.markClaimed(e,o.InstanceKey??n,t),this.ctx.emitter.emit("challenge:milestoneClaimed",o);}return i}async claimReachedMilestones(e){if(!this.ctx.auth.context)return l;let t=[],n=(this.lastState?.Chains??[]).filter(s=>!e||s.ChainID===e);for(let s of n){if(!s.ChainID)continue;let i=[s.Active,...s.Ended??[]].filter(o=>!!o&&!!o.CanClaim);for(let o of i)for(let p of this.reachedUnclaimed(s.ChainID,o)){let m=await this.claimMilestone(s.ChainID,p,o.InstanceKey??void 0);m.ok&&t.push(m.data);}}return G(t)}reachedUnclaimed(e,t){let n=this.phaseDefinition(e,t.ChallengeID),s=t.PointsEarned??0,i=new Set(t.ClaimedMilestoneIDs??[]);return Object.entries(n?.Milestones??{}).filter(([o,p])=>!i.has(o)&&(p?.RequiredProgress??1/0)<=s).sort((o,p)=>(o[1]?.RequiredProgress??0)-(p[1]?.RequiredProgress??0)).map(([o])=>o)}applyState(e,t){if((e.Rewards||e.Inventory)&&this.ctx.data.user.applyResourcesWithDelta(e.Rewards,e.Inventory,this.ctx.data.config.itemDefinitions),t&&this.lastState){let n=(this.lastState.Chains??[]).filter(s=>s.ChainID!==t);this.lastState={...e,Chains:[...n,...e.Chains??[]]};}else this.lastState=e;this.ctx.emitter.emit("challenge:stateLoaded",e);}patchAfterAttempt(e,t,n){let s=this.chainView(e);if(!s)return;t.Tickets!=null&&(s.Tickets=t.Tickets);let i=s.Active;if(!i||i.InstanceKey!==t.InstanceKey)return;t.PointsEarned!=null&&(i.PointsEarned=t.PointsEarned),t.IsReplay||(i.AttemptsToday=(i.AttemptsToday??0)+1);let o=t.Attempt;if(!(!o?.Win||!i.Arena))if(o.IsRevenge)i.Arena.Revenges=(i.Arena.Revenges??[]).filter(p=>p.RevengeID!==n);else for(let p of i.Arena.Opponents??[])p.TierID===o.TierID&&p.OpponentID===o.OpponentID&&(p.Defeated=true);}markClaimed(e,t,n){let s=this.chainView(e);if(s)for(let i of [s.Active,...s.Ended??[]])i&&(t&&i.InstanceKey!==t||!t&&i!==s.Active||(i.ClaimedMilestoneIDs=[...new Set([...i.ClaimedMilestoneIDs??[],n])]));}};var $p="Craft",Yi=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection($p,e);if(t){let i={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),G(i)}let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.craft.getDefinitions(n);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection($p,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,n=1,s,i,o){if(!e)return h("client","CraftID is required.");let p=this.ctx.auth.context;if(!p)return l;let m={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:n,SelectedOptionID:s,InputInstanceIDs:i,CreditsConfirmationID:o,RelatedEntityID:`craft_${e}_${p.userID}_${V()}`},g=await this.ctx.api.craft.craft(m);return g.ok&&!g.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(g.data.Resources,g.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",g.data)),g}};var en=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(en),zod.z.record(zod.z.string(),en)]));var tn={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Jp=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),yn={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function ps(r){return r!==yn.Pending&&r!==yn.Running}var JS={Disabled:"AI_DISABLED",FeatureNotFound:"AI_FEATURE_NOT_FOUND",FeatureDisabled:"AI_FEATURE_DISABLED",WrongAction:"AI_WRONG_ACTION",NotAvailableForPlayer:"AI_NOT_AVAILABLE_FOR_PLAYER",FeatureClosed:"AI_FEATURE_CLOSED",LimitReached:"AI_LIMIT_REACHED",Cooldown:"AI_COOLDOWN",BadInput:"AI_BAD_INPUT",PromptRejected:"AI_PROMPT_REJECTED",Unavailable:"AI_UNAVAILABLE",GenerationFailed:"AI_GENERATION_FAILED",GenerationNotFound:"AI_GENERATION_NOT_FOUND"};function ZS(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var YS=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),XS=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),Xi=zod.z.object({CreditsConfirmation:Re.nullish(),GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Jp.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),en).nullish(),Assets:zod.z.array(YS).nullish(),Error:XS.nullish(),Charge:O.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:O.nullish(),Context:zod.z.record(zod.z.string(),en).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreditsPrice:zod.z.number().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish()}),Zp=zod.z.object({Data:zod.z.array(Xi).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),eb=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish()}).passthrough(),Tt=zod.z.record(zod.z.string(),zod.z.string()),tb=zod.z.object({Key:zod.z.string().nullish(),Role:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),Label:Tt.nullish()}).passthrough(),nb=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Default:zod.z.string().nullish(),Multiline:zod.z.boolean().nullish(),Label:Tt.nullish(),Placeholder:Tt.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string().nullish(),Label:Tt.nullish()}).passthrough()).nullish()}).passthrough(),Yp=zod.z.object({Key:zod.z.string(),Kind:zod.z.string().nullish(),Name:Tt.nullish(),Hint:Tt.nullish(),Unit:Tt.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string(),Name:Tt.nullish(),Group:zod.z.string().nullish()}).passthrough()).nullish(),Groups:zod.z.array(zod.z.object({Key:zod.z.string(),Name:Tt.nullish()}).passthrough()).nullish(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),Step:zod.z.number().nullish()}).passthrough(),Xp=zod.z.object({PriceOptions:me.nullish()}).passthrough(),sb=zod.z.object({Id:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Action:zod.z.string().nullish(),IsTrend:zod.z.boolean().nullish(),Category:zod.z.string().nullish(),Order:zod.z.number().nullish(),Name:Tt.nullish(),Description:Tt.nullish(),Preview:zod.z.object({Url:zod.z.string().nullish(),PosterUrl:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough().nullish(),Inputs:zod.z.array(tb).nullish(),Variables:zod.z.array(nb).nullish(),Settings:zod.z.array(Yp).nullish()}).passthrough(),ib=zod.z.object({Modality:Jp.nullish(),Async:zod.z.boolean().nullish(),Limits:ve.nullish(),PriceOptions:me.nullish(),Tags:zod.z.array(zod.z.string()).nullish(),HistoryMessages:zod.z.number().nullish(),MaxTokens:zod.z.number().nullish(),AllowImages:zod.z.boolean().nullish(),MaxInputImages:zod.z.number().nullish(),MaxInputImageBytes:zod.z.number().nullish(),AllowedImageTypes:zod.z.array(zod.z.string()).nullish(),MaxImages:zod.z.number().nullish(),AllowEdit:zod.z.boolean().nullish(),AllowReferenceImage:zod.z.boolean().nullish(),MaxPromptChars:zod.z.number().nullish(),LockBehavior:zod.z.boolean().nullish(),ImageSize:zod.z.string().nullish(),VideoSize:zod.z.string().nullish(),VideoSeconds:zod.z.number().nullish(),Voice:zod.z.string().nullish(),AudioFormat:zod.z.string().nullish(),MusicFormat:zod.z.string().nullish(),ThreeDOperation:zod.z.string().nullish(),ThreeDAnimations:zod.z.array(zod.z.string()).nullish(),Reward:$.nullish(),PromptVariables:zod.z.array(eb).nullish(),AllowFreePrompt:zod.z.boolean().nullish(),PlatformTemplateId:zod.z.string().nullish(),PlatformTemplate:sb.nullish(),Settings:zod.z.array(Yp).nullish(),FreePerDay:zod.z.number().nullish(),FreeLeftToday:zod.z.number().nullish()}).passthrough(),eh=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),ib).nullish()}).passthrough(),We={GetDefinitions:"GetDefinitions",GenerateText:"GenerateText",GetText:"GetText",GenerateImage:"GenerateImage",EditImage:"EditImage",GenerateVideo:"GenerateVideo",GetVideo:"GetVideo",GenerateAudio:"GenerateAudio",GenerateMusic:"GenerateMusic",GenerateThreeD:"GenerateThreeD",GetThreeD:"GetThreeD",ListGenerations:"ListGenerations",GetGeneration:"GetGeneration",GetImage:"GetImage",GetAudio:"GetAudio",GetMusic:"GetMusic",GenerateFromTemplate:"GenerateFromTemplate",EstimateTemplatePrice:"EstimateTemplatePrice"};var th="AI",rb=/^[A-Za-z0-9_-]{1,128}$/,ob=2e3,ab=5e3,lb=30*6e4;function ub(r,e){return new Promise(t=>{if(e?.aborted){t();return}let n=()=>{clearTimeout(s),e?.removeEventListener("abort",n),t();},s=setTimeout(n,r);e?.addEventListener("abort",n,{once:true});})}var er=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(th,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.ai.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(th,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,n){return this.generate(e,{Text:t},n,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,n){return this.generate(e,{Image:t},n,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,n){return this.generate(e,{ImageEdit:t},n,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,n){return this.generate(e,{Video:t},n,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,n){return this.generate(e,{Audio:t},n,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,n){return this.generate(e,{Music:t},n,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,n){return this.generate(e,{TemplateInputs:t},n,s=>this.ctx.api.ai.generateFromTemplate(s))}async estimateTemplatePrice(e,t,n){return e?this.ctx.auth.context?this.ctx.api.ai.estimateTemplatePrice({...this.ctx.buildAuthedBaseRequest(),FeatureKey:e,Params:t,Variables:n}):l:h("client","FeatureKey is required.")}generateThreeD(e,t,n){return this.generate(e,{ThreeD:t},n,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):l}async getGeneration(e){if(!e)return h("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):l}isTerminal(e){return ps(e)}async waitForGeneration(e,t={}){let n;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;n=p.data;}else {if(!e?.GenerationID)return h("client","GenerationID is required.");n=e;}let s=Date.now()+(t.timeoutMs??lb),i=Math.max(1,t.intervalMs??ob),o=Math.max(i,t.maxIntervalMs??ab);for(;!ps(n.Status);){if(t.signal?.aborted)return h("client","Stopped waiting: the wait was aborted.");if(Date.now()+i>s)return h("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await ub(i,t.signal),t.signal?.aborted)return h("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(n);if(i=Math.min(o,Math.round(i*1.5)),!p.ok){if(p.reason==="connection")continue;return p}n=p.data,ps(n.Status)||t.onUpdate?.(n);}return G(n)}pollFor(e){switch(e.Modality){case tn.Text:return this.getText(e.GenerationID);case tn.Image:return this.getImage(e.GenerationID);case tn.Audio:return this.getAudio(e.GenerationID);case tn.Music:return this.getMusic(e.GenerationID);case tn.Video:return this.getVideo(e.GenerationID);case tn.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,n,s){if(!e)return h("client","FeatureKey is required.");let i=n?.relatedEntityID;if(i!==void 0&&!rb.test(i))return h("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,Variables:n?.variables,Params:n?.params,Context:n?.context,RelatedEntityID:i??V()},p=await s(o);return p.ok&&!p.data.CreditsConfirmation&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return h("client","GenerationID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.GenerationID=e;let s=await t(n);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===yn.Completed&&!this.rewarded.has(e.GenerationID)&&(this.rewarded.add(e.GenerationID),await this.ctx.userService.getUserInventory()),!(!t||!e.Charge||this.charged.has(e.GenerationID))&&(this.charged.add(e.GenerationID),this.ctx.data.user.applyResourceOperation(e.Charge,this.ctx.data.config.itemDefinitions));}emitView(e){this.ctx.emitter.emit("ai:generationUpdated",e),e.Status===yn.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===yn.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Ya="Collection",tr=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let n=e.cache.configSection(Ya),s=Object.keys(n?.Collections??{});if(s.length===0||t)return false;let i=e.cache.configSection("Season");return Object.values(i?.Chains??{}).some(p=>(p?.Seasons??[]).some(m=>!!m?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let n=await this.getUserState();return n.ok&&(t=true),n}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ya,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.collection.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(Ya,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,n=1,s){let i=this.ctx.auth.context;if(!i)return l;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:n,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${i.userID}_${V()}`},p=await this.ctx.api.collection.openPack(o);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,n=1){let s=this.ctx.auth.context;if(!s)return l;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:n,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${V()}`},o=await this.ctx.api.collection.openCollectionChest(i);return o.ok&&(this.ctx.data.user.applyResourcesWithDelta(o.data.Resources,o.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",o.data)),o}async useCollectibleJoker(e,t){let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${n.userID}_${V()}`},i=await this.ctx.api.collection.useCollectibleJoker(s);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",i.data)),i}async claimSetReward(e,t){let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${n.userID}_${V()}`},i=await this.ctx.api.collection.claimSetReward(s);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",i.data)),i}async claimSetRewardsBatch(e){if(!e||e.length===0)return h("client","sets is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},n=await this.ctx.api.collection.claimSetRewardsBatch(t);if(n.ok){let s=false;for(let i of n.data)!s&&i.Success&&i.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(i.Data.Resources,i.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",n.data);}return n}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${V()}`},s=await this.ctx.api.collection.claimGrandPrize(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,n,s,i,o=false){let p=this.ctx.auth.context;if(!p)return l;let m={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:n,ReceiverUserID:s,RequestedCollectibleID:i,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${p.userID}_${s}_${V()}`},g=await this.ctx.api.collection.sendTradeOffer(m);return g.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",g.data)),g}async cancelTradeOffer(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${V()}`},n=await this.ctx.api.collection.cancelTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",n.data)),n}async acceptTradeOffer(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${V()}`},n=await this.ctx.api.collection.acceptTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",n.data)),n}async declineTradeOffer(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${V()}`},n=await this.ctx.api.collection.declineTradeOffer(t);return n.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",n.data)),n}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return l;t.CollectionID=e;let n=await this.ctx.api.collection.getMyTradeOffers(t);return n.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",n.data),n}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return l;t.CollectionID=e;let n=await this.ctx.api.collection.getIncomingTradeOffers(t);return n.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",n.data),n}};var cb=zod.z.object({}).passthrough().transform(r=>r),pb={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},hb={Active:"Active",Left:"Left",Replaced:"Replaced"},db=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),mb=zod.z.object({UserID:zod.z.string().nullish(),PublicData:_e.nullish(),BuildObjectsProgress:db.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),fb=zod.z.object({Index:zod.z.number().nullish(),OwnerUserID:zod.z.string().nullish(),CurrentProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish(),IsCompleted:zod.z.boolean().nullish()}).passthrough(),gb=zod.z.object({Objects:zod.z.array(fb).nullish()}).passthrough(),nh=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CoopChainID:zod.z.string().nullish(),CoopEventID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),Members:zod.z.array(mb).nullish(),BuildObjectsState:gb.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),sh=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>ih).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),yb=zod.z.string(),Xa=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Weight:zod.z.number().nullish(),MinProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish()}).passthrough(),Rb=zod.z.object({Index:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxProgress:zod.z.number().nullish(),CompletionReward:$.nullish()}).passthrough(),Cb=zod.z.object({Objects:zod.z.array(Rb).nullish(),PriceOptions:me.nullish(),SpinnerTable:zod.z.array(Xa).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),ih=zod.z.object({CoopEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),EventType:yb.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:Cb.nullish(),GrandPrize:$.nullish()}).passthrough(),Sb=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Se.nullish(),Events:zod.z.array(ih).nullish(),Gate:te.nullish()}).passthrough(),nr=zod.z.object({ServerTimeUtc:u.nullish(),UserState:cb.nullish(),ActiveGroup:nh.nullish()}),el=zod.z.object({ServerTimeUtc:u.nullish(),Group:nh.nullish(),SecondsRemaining:Q.nullish()}),rh=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Resources:O.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:Xa.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(Xa).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:Q.nullish(),MaxProgress:Q.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),tl=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),oh=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),sr=zod.z.object({Chains:zod.z.record(zod.z.string(),Sb).nullish()}).passthrough(),wt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var ah="CoopEvent",lh={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},ir=class{constructor(e){this.ctx=e;e.cache.bindLoginView(lh,{schema:nr,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ah,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.coopEvent.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(ah,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return h("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.CoopChainID=e;let n=await this.ctx.api.coopEvent.getActiveEvent(t);return n.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",n.data),n}getUserState(e){return this.ctx.cache.read(lh,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return h("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.GroupID=e;let n=await this.ctx.api.coopEvent.getGroupState(t);return n.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",n.data),n}async joinOrCreateGroup(e){if(!e)return h("client","CoopChainID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},n=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(n.ok){let s=n.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",n.data);}return n}async spin(e,t,n=1,s,i){if(!e||!t)return h("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:n,SelectedOptionID:s,CreditsConfirmationID:i,RelatedEntityID:V()},p=await this.ctx.api.coopEvent.spin(o);return p.ok&&!p.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(p.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",p.data)),p}async claimObjectReward(e){if(!e)return h("client","GroupID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.claimObjectReward(t);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",n.data)),n}async claimGrandPrize(e){if(!e)return h("client","GroupID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.claimGrandPrize(t);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",n.data)),n}async leaveGroup(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.coopEvent.leaveGroup(t);return n.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",n.data)),n}};var bb={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},xb={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},Db=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:u.nullish(),CompletedAtUtc:u.nullish(),LastExecutedAtUtc:u.nullish(),NextAvailableAtUtc:u.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),Ib=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),uh=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:u.nullish(),ExhaustedAtUtc:u.nullish(),ExpiredAtUtc:u.nullish(),DismissedAtUtc:u.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:u.nullish(),Nodes:zod.z.record(zod.z.string(),Db).nullish(),Tracks:zod.z.record(zod.z.string(),Ib).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),Pb=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:u.nullish(),ActiveOfferExpiresAtUtc:u.nullish(),ActiveOffer:uh.nullish(),NextCycleStartsAtUtc:u.nullish(),LastUpdatedUtc:u.nullish(),DismissSkipAvailableAtUtc:u.nullish(),LastDismissedAtUtc:u.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),vb=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),Ab=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:u.nullish(),LastActivatedAtUtc:u.nullish(),LastExhaustedAtUtc:u.nullish(),NodeCounts:zod.z.record(zod.z.string(),vb).nullish()}).passthrough(),Tb=zod.z.object({Slots:zod.z.record(zod.z.string(),Pb).nullish(),OfferHistory:zod.z.record(zod.z.string(),Ab).nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),wb={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},kb={Eq:"Eq",Gte:"Gte",Lte:"Lte"},zb=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),rr=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ch=zod.z.object({Schedule:Se.nullish(),Gate:te.nullish()}).passthrough(),ph=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),Mb=zod.z.object({Identity:J.nullish(),Availability:J.nullish(),Behaviour:J.nullish()}).passthrough(),Ob=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:rr.nullish(),Availability:ch.nullish(),Behaviour:ph.nullish(),Queue:zod.z.array(zb).nullish(),Presets:Mb.nullish()}).passthrough(),Eb=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),qb=zod.z.object({RewardedVideo:Eb.nullish()}).passthrough(),Ub=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),Lb=zod.z.object({Identity:J.nullish(),Graph:J.nullish(),Milestones:J.nullish()}).passthrough(),Bb=zod.z.object({Identity:J.nullish(),Pricing:J.nullish(),Reward:J.nullish()}).passthrough(),Gb=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),Nb=zod.z.object({TrackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),StartValue:zod.z.number().nullish(),MinValue:zod.z.number().nullish(),MaxValue:zod.z.number().nullish(),ClampToMin:zod.z.boolean().nullish(),ClampToMax:zod.z.boolean().nullish(),HiddenFromUI:zod.z.boolean().nullish()}).passthrough(),_b=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(Ub).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),hh=zod.z.object({Options:me.nullish()}).passthrough(),dh=zod.z.object({Grants:$.nullish(),TrackChanges:zod.z.array(Gb).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),Vb=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:rr.nullish(),Pricing:hh.nullish(),Reward:dh.nullish(),Action:qb.nullish(),UnlockRules:_b.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:ve.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:Bb.nullish()}).passthrough(),mh=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(Vb).nullish(),Tracks:zod.z.array(Nb).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),fh=zod.z.object({Milestones:zod.z.record(zod.z.string(),je).nullish(),ClaimMode:zod.z.string().nullish(),Token:Mt.nullish()}).passthrough(),gh=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:rr.nullish(),Graph:mh.nullish(),Milestones:fh.nullish(),Presets:Lb.nullish()}).passthrough(),Fb=zod.z.object({Identity:zod.z.record(zod.z.string(),rr).nullish(),Availability:zod.z.record(zod.z.string(),ch).nullish(),Behaviour:zod.z.record(zod.z.string(),ph).nullish(),Graph:zod.z.record(zod.z.string(),mh).nullish(),Milestones:zod.z.record(zod.z.string(),fh).nullish(),Pricing:zod.z.record(zod.z.string(),hh).nullish(),Reward:zod.z.record(zod.z.string(),dh).nullish()}).passthrough(),nl=zod.z.object({Slots:zod.z.record(zod.z.string(),Ob).nullish(),Offers:zod.z.record(zod.z.string(),gh).nullish(),Presets:Fb.nullish()}).passthrough(),yh=zod.z.object({DealOfferDefinitions:nl.nullish()}),Rh=zod.z.object({DealOffers:Tb.nullish()}),jb=zod.z.object({EntityID:zod.z.string().nullish(),TotalEarned:zod.z.number().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),ReachedUnclaimedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Wb=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:gh.nullish(),ActivationState:uh.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:u.nullish(),Cost:Nt.nullish(),Milestone:jb.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),or=zod.z.object({Slots:zod.z.array(Wb).nullish()}),Ch=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Sh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),bh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),xh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Dh=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:O.nullish(),Inventory:K.nullish()}),qt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var Hb="DealOffer",Ih={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},ar=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ih,{schema:or,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(Hb,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(Ih,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return h("client","SlotID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${V()}`},n=await this.ctx.api.dealOffer.dismissDeal(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",n.data)),n}async executeNode(e,t,n,s){if(!e||!t)return h("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return l;let i=n&&n.trim().length>0?n.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:i??`deal_exec_${e}_${t}_${V()}`},p=await this.ctx.api.dealOffer.executeNode(o);return p.ok&&!p.data.CreditsConfirmation&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return h("client","SlotID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${V()}`},n=await this.ctx.api.dealOffer.recordShow(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",n.data)),n}async claimMilestone(e,t){if(!e||!t)return h("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${V()}`},s=await this.ctx.api.dealOffer.claimMilestone(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return h("client","SlotID is required.");if(!this.ctx.auth.context)return l;let n=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:n,RelatedEntityID:`deal_milestone_batch_${e}_${V()}`},i=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",i.data)),i}};var Ph="Referral",lr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ph,e);if(t){let i={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",i),G(i)}let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.referral.getDefinitions(n);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Ph,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=fn.parseReferralCode(e)?.toUpperCase();if(!t)return h("client","ReferralCode is required.");let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${n.userID}`},i=await this.ctx.api.referral.activateReferralCode(s);if(i.ok){let o=i.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID,o.QualificationPending),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return i}async claimInviteReward(e){let t=e.trim();if(!t)return h("client","InviteRewardID is required.");let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${n.userID}`},i=await this.ctx.api.referral.claimInviteReward(s);if(i.ok){let o=i.data;o.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(o.RewardID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",o);}return i}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return h("client","InviteRewardIDs is required.");let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${n.userID}`},i=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(i.ok){let o=i.data;for(let p of o.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return i}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.referral.checkQualification(e);return t.ok&&t.data.Qualification&&!t.data.QualificationPending&&await this.getUserState(),t}async checkQualificationIfPending(){this.ctx.data.user.state?.Referral?.QualificationPending===true&&await this.checkQualification();}};var vh=zod.z.object({ServerTimeUtc:u,SourceType:kn,SourceID:zod.z.string(),TargetType:kn,TargetID:zod.z.string(),SourceSpent:Q,FeeAmount:Q,RateApplied:se,TargetCredited:Q}),Ah=zod.z.object({ServerTimeUtc:u,SourceType:kn,SourceID:zod.z.string(),TargetType:kn,TargetID:zod.z.string(),SourceSpent:se,FeeAmount:se,RateApplied:se,TargetCredited:se}),Th=zod.z.object({ServerTimeUtc:u,SpendID:zod.z.string(),Resources:O.nullish()}),hs={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},Kb={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},wh=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),Qb={Automatic:"Automatic",Manual:"Manual"},$b=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),Jb=zod.z.object({ValueInUSD:se.nullish(),ValueInUSDUpdatedAt:u.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),Zb=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),Yb=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),Xb=zod.z.object({TargetCurrencyType:kn.nullish(),TargetCurrencyID:zod.z.string(),Rate:se.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),kh=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:$b.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(Xb).nullish()}).passthrough(),zh=zod.z.object({CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough(),ex=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:Jb.nullish(),Recharge:Zb.nullish(),Conversion:kh.nullish(),Permissions:Yb.nullish(),Audit:zh.nullish(),Status:wh.nullish()}).passthrough(),tx=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:se.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),nx=zod.z.object({DailyWithdrawUsd:se.nullish(),MonthlyWithdrawUsd:se.nullish(),KycRequiredAboveUsd:se.nullish()}).passthrough(),sx=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),ix=zod.z.object({Mode:zod.z.string().nullish(),FundingNetworkID:zod.z.string().nullish(),PerPlayerDailyTokens:zod.z.number().nullish(),TitleDailyTokens:zod.z.number().nullish(),RefuseOverCap:zod.z.boolean().nullish()}).passthrough(),sl=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),DisplayDecimals:zod.z.number().nullish(),ValueInUSD:se.nullish(),ValueInUSDUpdatedAt:u.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:se.nullish(),CommunityMarketingWithdrawalFeePercent:se.nullish(),WithdrawalBurnPercent:se.nullish(),PlayerTradeFeePercent:se.nullish(),TradeShareCommunityMarketingPercent:se.nullish(),Networks:zod.z.array(tx).nullish(),Limits:nx.nullish(),Permissions:sx.nullish(),Conversion:kh.nullish(),Audit:zh.nullish(),Status:wh.nullish(),ServerGrantPolicy:ix.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),rx=zod.z.object({SpendID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),PriceOptions:zod.z.record(zod.z.string(),hi).nullish()}).passthrough(),ur=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),ex).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),sl).nullish(),Spends:zod.z.record(zod.z.string(),rx).nullish()}).passthrough(),ox={Marketplace:"Marketplace",MailboxTransfer:"MailboxTransfer",Match:"Match",Workshop:"Workshop"},ax={Pending:"Pending",Released:"Released",Voided:"Voided"},Ct=zod.z.object({PayoutID:zod.z.string().nullish(),Source:zod.z.string().nullish(),SourceRefID:zod.z.string().nullish(),Status:zod.z.enum(["Pending","Released","Voided"]).catch("Pending").nullish(),Amount:he.nullish(),CreatedAt:u.nullish(),ReleaseAt:u.nullish(),ReturnedGoods:he.nullish(),GoodsReturned:zod.z.boolean().nullish()}).passthrough(),Mh=zod.z.object({Pending:zod.z.array(Ct).nullish(),Released:zod.z.array(Ct).nullish(),Voided:zod.z.array(Ct).nullish()}).passthrough();var lx={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Oh=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),ux={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},cx=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),px={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},hx=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),ht={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},dx={Disabled:"MAILBOX_DISABLED",MessageNotFound:"MESSAGE_NOT_FOUND",MessageIDRequired:"MESSAGE_ID_REQUIRED",AlreadyClaimed:"ALREADY_CLAIMED",Expired:"EXPIRED",NoRewards:"NO_REWARDS",HasUnclaimedRewards:"HAS_UNCLAIMED_REWARDS",NotFriends:"NOT_FRIENDS",Blocked:"BLOCKED",RecipientNotFound:"RECIPIENT_NOT_FOUND",CannotGiftSelf:"CANNOT_GIFT_SELF",GiftNotFound:"GIFT_NOT_FOUND",GiftNotAllowed:"GIFT_NOT_ALLOWED",AlreadySent:"ALREADY_SENT",SendLimit:"SEND_LIMIT",NotEnoughResources:"NOT_ENOUGH_RESOURCES",AmountTooSmall:"AMOUNT_TOO_SMALL",RecipientLimit:"RECIPIENT_LIMIT",TransferDisabled:"TRANSFER_DISABLED",ResourceNotGiftable:"RESOURCE_NOT_GIFTABLE",AmountTooLarge:"AMOUNT_TOO_LARGE",AmountInvalid:"AMOUNT_INVALID",TooManyEntries:"TOO_MANY_ENTRIES",EntriesRequired:"ENTRIES_REQUIRED",FriendshipTooNew:"FRIENDSHIP_TOO_NEW",RequestIDRequired:"RELATED_ENTITY_ID_REQUIRED",CryptoForbidden:"CRYPTO_FORBIDDEN",ModuleRewardUnavailable:"MODULE_REWARD_UNAVAILABLE",Conflict:"CONFLICT"},mx=100,fx=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),Eh=zod.z.object({FeatureID:zod.z.string().nullish(),Args:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Url:zod.z.string().nullish(),Label:zod.z.string().nullish()}).passthrough(),gx=zod.z.object({Texts:zod.z.record(zod.z.string(),fx).nullish(),Category:Oh.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:Eh.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),yx=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:he.nullish(),Cost:he.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),SenderGate:te.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),Rx=zod.z.object({Type:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxAmountPerGift:zod.z.number().nullish()}).passthrough(),Cx=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(Rx).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),AllowItemInstances:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:he.nullish(),SenderGate:te.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),qh=zod.z.object({Enabled:zod.z.boolean().nullish(),Capacity:zod.z.number().nullish(),RewardLetterDays:zod.z.number().nullish(),PlainLetterDays:zod.z.number().nullish(),ClaimedRetentionDays:zod.z.number().nullish(),DefaultLanguage:zod.z.string().nullish(),Templates:zod.z.record(zod.z.string(),gx).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),yx).nullish(),Transfer:Cx.nullish()}).passthrough().nullish(),Integrations:zod.z.object({Leaderboard:zod.z.boolean().nullish(),CoopEvent:zod.z.boolean().nullish(),Season:zod.z.boolean().nullish(),Referral:zod.z.boolean().nullish()}).passthrough().nullish()}).passthrough(),Sx=zod.z.object({MessageID:zod.z.string(),Source:cx,Category:Oh,TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:Eh.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:$.nullish(),Instances:zod.z.array(En).nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:u,ExpiresAt:u.nullish(),ReadAt:u.nullish(),ClaimedAt:u.nullish()}).passthrough(),bx=zod.z.object({MessageID:zod.z.string(),Module:hx,Key:zod.z.string(),TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:$.nullish()}).passthrough(),il=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),Uh=zod.z.object({ServerTimeUtc:u.nullish(),Messages:zod.z.array(Sx).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(bx).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),cr=zod.z.object({ServerTimeUtc:u.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),rl=zod.z.object({ServerTimeUtc:u.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(il).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),xx=zod.z.object({MessageID:zod.z.string(),Rewards:he.nullish(),Instances:zod.z.array(En).nullish(),HeldPayout:Ct.nullish()}).passthrough(),pr=zod.z.object({ServerTimeUtc:u.nullish(),Claimed:zod.z.array(xx).default([]),Failed:zod.z.array(il).default([]),Resources:O.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Lh=zod.z.object({ServerTimeUtc:u.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(il).default([]),Resources:O.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough(),Bh=zod.z.object({ServerTimeUtc:u.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish(),RecipientReceives:he.nullish(),RecipientInstances:zod.z.array(En).nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),Gh=zod.z.object({ServerTimeUtc:u.nullish(),ResetsAt:u.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:u.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough().nullish()}).passthrough();var ol="Mailbox",al={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},hr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(al,{schema:cr,apply:t=>this.emitCounters(t)});}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}emitCounters(e){if(e.UnreadCount==null||e.UnclaimedCount==null)return;let t={UnreadCount:e.UnreadCount,UnclaimedCount:e.UnclaimedCount};this.ctx.cache.put(al,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(ol)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(ol,e);if(t)return G(t);let n=this.request();if(!n)return l;let s=await this.ctx.api.mailbox.getDefinitions(n);return s.ok&&this.ctx.data.config.patchSection(ol,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return l;let n=await this.ctx.api.mailbox.getMessages(t);return n.ok&&(this.emitCounters(n.data),this.ctx.emitter.emit("mailbox:messagesLoaded",n.data)),n}getUnreadCount(e){return this.ctx.cache.read(al,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return l;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return l;let n=await this.ctx.api.mailbox.readMessages(t);return n.ok&&this.emitCounters(n.data),n}async claimReward(e){let t=e?.trim();if(!t)return h("client","MessageID is required.");let n=this.request({MessageID:t});return n?this.afterClaim(await this.ctx.api.mailbox.claimReward(n)):l}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return h("client","MessageIDs are required.");let n=this.request({MessageIDs:t});return n?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(n)):l}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):l}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let n=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!n)return l;let s=await this.ctx.api.mailbox.deleteMessages(n);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return h("client","GiftID is required.");let n=(t??[]).filter(Boolean);if(n.length===0)return h("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:n});if(!s)return l;let i=await this.ctx.api.mailbox.sendGift(s);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",i.data)),i}async sendTransfer(e,t,n){if(!e?.trim())return h("client","RecipientUserID is required.");if(!n?.requestID?.trim())return h("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,TransferInstanceIDs:n.instanceIDs?.length?n.instanceIDs:void 0,Note:n.note,RelatedEntityID:n.requestID.trim()});if(!s)return l;let i=await this.ctx.api.mailbox.sendTransfer(s);return i.ok&&(i.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(i.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",i.data)),i}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):l}};var Dx={Head:"Head",Torso:"Torso",Legs:"Legs"},dr=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),Ix={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},ll=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),_h=zod.z.object({AttackTarget:dr,DefenseTarget:dr});var Px=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),vx=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:dr.nullish(),DefenseZone:dr.nullish(),HitType:Px.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),Ax=zod.z.object({MaxHp:zod.z.number().nullish(),CurrentHp:zod.z.number().nullish(),Damage:zod.z.number().nullish(),AttackSpeed:zod.z.number().nullish(),CritChance:zod.z.number().nullish(),CritMultiplier:zod.z.number().nullish(),Armor:zod.z.number().nullish(),DodgeChance:zod.z.number().nullish()}).passthrough(),Tx=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Nh=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:cs.nullish(),BattleStrategy:zod.z.array(_h).nullish(),UnstackableItems:zod.z.record(zod.z.string(),Tx).nullish(),Stats:Ax.nullish()}).passthrough(),ds=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:he.nullish(),NetReward:he.nullish(),BattleLog:zod.z.array(vx).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:Nh.nullish(),P2BattleProfile:Nh.nullish()}).passthrough(),Vh=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:u.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(_h).nullish(),TargetUserID:zod.z.string().nullish(),Entry:he.nullish(),CreationCostPaid:he.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:u.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:u.nullish(),Status:ll.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:u.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:u.nullish()}).passthrough(),Fh=zod.z.object({Status:ll,MatchID:zod.z.string(),Entry:he.nullish(),Resources:O.nullish()}),jh=zod.z.object({Match:Vh.nullish()}),Wh=zod.z.object({MatchID:zod.z.string(),Status:ll,Resources:O.nullish()}),Hh=zod.z.object({Battle:ds.nullish(),Resources:O.nullish(),ResourcesDual:_t.nullish(),HeldPayout:Ct.nullish()}),ul=zod.z.object({Matches:zod.z.array(Vh).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),Ut={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var wx=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var kx=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),zx=zod.z.object({HealthStatID:zod.z.string().nullish(),DamageStatID:zod.z.string().nullish(),ArmorStatID:zod.z.string().nullish(),AttackSpeedStatID:zod.z.string().nullish(),CritChanceStatID:zod.z.string().nullish(),CritDamageStatID:zod.z.string().nullish(),DodgeStatID:zod.z.string().nullish(),AllMightStatID:zod.z.string().nullish()}).passthrough(),Mx=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),Ox=zod.z.object({MaxRounds:zod.z.number().nullish(),BlockDamageMultiplier:zod.z.number().nullish(),MinHitDamage:zod.z.number().nullish(),DefaultCritMultiplier:zod.z.number().nullish(),MaxCritChance:zod.z.number().nullish(),MaxDodgeChance:zod.z.number().nullish(),ArmorMode:Mx.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),Ex=zod.z.object({Kind:kx.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Ze.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),qx=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(Ex).nullish()}).passthrough(),Rn=zod.z.object({Terms:zod.z.array(qx).nullish()}).passthrough(),Ux=zod.z.object({Health:Rn.nullish(),Damage:Rn.nullish(),Armor:Rn.nullish(),AttackSpeed:Rn.nullish(),CritChance:Rn.nullish(),CritDamage:Rn.nullish(),Dodge:Rn.nullish()}).passthrough(),Kh=zod.z.object({StatMapping:zx.nullish(),Combat:Ox.nullish(),Formula:Ux.nullish()}).passthrough(),Lx=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),ms=zod.z.object({Kind:wx.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:Os.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),Qh=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(ms).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),$h=zod.z.object({PriceOptions:me.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:ve.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),Bx=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:Lx.nullish(),Entry:Qh.nullish(),Creation:$h.nullish(),Settings:Kh.nullish()}).passthrough(),Gx=zod.z.object({Rules:zod.z.record(zod.z.string(),Bx).nullish(),Defaults:Kh.nullish(),EntryDefaults:Qh.nullish(),CreationDefaults:$h.nullish()}).passthrough(),cl=zod.z.object({InstantBattle:Gx.nullish()}).passthrough(),Jh=cl;var Nx={Open:"Open",Request:"Request",InviteOnly:"InviteOnly"},_x=zod.z.enum(["Open","Request","InviteOnly"]).catch("Open"),Vx={Application:"Application",Invite:"Invite"},Fx={Invite:"invite",ManageApplications:"manage_applications",Kick:"kick",SetRole:"set_role",EditInfo:"edit_info",EditAnnouncement:"edit_announcement",ModerateChat:"moderate_chat",CreateRequest:"create_request",SpendTreasury:"spend_treasury",ManageProjects:"manage_projects",StartActivity:"start_activity",SelectQuests:"select_quests"},Be={GetDefinitions:"GetDefinitions",GetMyClans:"GetMyClans",SearchClans:"SearchClans",GetRecommendedClans:"GetRecommendedClans",GetClan:"GetClan",GetClanMembers:"GetClanMembers",GetRankings:"GetRankings",CreateClan:"CreateClan",UpdateClan:"UpdateClan",DisbandClan:"DisbandClan",JoinClan:"JoinClan",ApplyToClan:"ApplyToClan",CancelApplication:"CancelApplication",GetApplications:"GetApplications",AcceptApplication:"AcceptApplication",RejectApplication:"RejectApplication",InvitePlayer:"InvitePlayer",GetMyInvites:"GetMyInvites",AcceptInvite:"AcceptInvite",DeclineInvite:"DeclineInvite",LeaveClan:"LeaveClan",KickMember:"KickMember",SetMemberRole:"SetMemberRole",TransferLeadership:"TransferLeadership",GetClanLog:"GetClanLog",CreateRequest:"CreateRequest",Donate:"Donate",Help:"Help",ClaimRequest:"ClaimRequest",GetRequests:"GetRequests",GetGifts:"GetGifts",ClaimGift:"ClaimGift",ClaimAllGifts:"ClaimAllGifts",GetRewards:"GetRewards",ClaimRewards:"ClaimRewards",GetTreasury:"GetTreasury",DepositToTreasury:"DepositToTreasury",BuyTreasuryPurchase:"BuyTreasuryPurchase",GetProjects:"GetProjects",ContributeToProject:"ContributeToProject",SetRecommendedProject:"SetRecommendedProject",GetActivities:"GetActivities",StartActivity:"StartActivity",SubmitActivityScore:"SubmitActivityScore",ClaimActivityRewards:"ClaimActivityRewards",GetClanQuests:"GetClanQuests",SelectClanQuests:"SelectClanQuests",TakeClanQuest:"TakeClanQuest",AbandonClanQuest:"AbandonClanQuest",ClaimClanQuestRewards:"ClaimClanQuestRewards",GetCompetitions:"GetCompetitions",RegisterForCompetition:"RegisterForCompetition",GetBracket:"GetBracket",ClaimCompetitionRewards:"ClaimCompetitionRewards",StartWarAttack:"StartWarAttack",GetDiplomacy:"GetDiplomacy",SetDiplomacy:"SetDiplomacy",GetRevenges:"GetRevenges",TakeRevenge:"TakeRevenge",GetLeague:"GetLeague",ClaimSeasonReward:"ClaimSeasonReward"},jx={Disabled:"CLAN_DISABLED",UnknownKind:"CLAN_UNKNOWN_KIND",KindRequired:"CLAN_KIND_REQUIRED",NotFound:"CLAN_NOT_FOUND",NotMember:"CLAN_NOT_MEMBER",AlreadyInClan:"CLAN_ALREADY_IN_CLAN",Full:"CLAN_FULL",NoPermission:"CLAN_NO_PERMISSION",RankTooLow:"CLAN_RANK_TOO_LOW",RoleFull:"CLAN_ROLE_FULL",UnknownRole:"CLAN_UNKNOWN_ROLE",NameTaken:"CLAN_NAME_TAKEN",TagTaken:"CLAN_TAG_TAKEN",NameInvalid:"CLAN_NAME_INVALID",TagInvalid:"CLAN_TAG_INVALID",TextInvalid:"CLAN_TEXT_INVALID",TextBlocked:"CLAN_TEXT_BLOCKED",GateFailed:"CLAN_GATE_FAILED",RequirementsNotMet:"CLAN_REQUIREMENTS_NOT_MET",JoinModeMismatch:"CLAN_JOIN_MODE_MISMATCH",JoinCooldown:"CLAN_JOIN_COOLDOWN",RejoinCooldown:"CLAN_REJOIN_COOLDOWN",TooManyApplications:"CLAN_TOO_MANY_APPLICATIONS",ApplicationNotFound:"CLAN_APPLICATION_NOT_FOUND",InviteNotFound:"CLAN_INVITE_NOT_FOUND",PlayerNotFound:"CLAN_PLAYER_NOT_FOUND",LeaderMustTransfer:"CLAN_LEADER_MUST_TRANSFER",CannotTargetSelf:"CLAN_CANNOT_TARGET_SELF",KickLimit:"CLAN_KICK_LIMIT",RenameCooldown:"CLAN_RENAME_COOLDOWN",InvalidArgument:"CLAN_INVALID_ARGUMENT",FeatureDisabled:"CLAN_FEATURE_DISABLED",RequestNotFound:"CLAN_REQUEST_NOT_FOUND",RequestClosed:"CLAN_REQUEST_CLOSED",RequestCooldown:"CLAN_REQUEST_COOLDOWN",RequestLimit:"CLAN_REQUEST_LIMIT",RequestFilled:"CLAN_REQUEST_FILLED",DonateLimit:"CLAN_DONATE_LIMIT",AlreadyHelped:"CLAN_ALREADY_HELPED",NothingToClaim:"CLAN_NOTHING_TO_CLAIM",GiftNotFound:"CLAN_GIFT_NOT_FOUND",TenureRequired:"CLAN_TENURE_REQUIRED",Conflict:"CLAN_CONFLICT",SystemCapReached:"CLAN_SYSTEM_CAP_REACHED",ItemNotAllowed:"CLAN_ITEM_NOT_ALLOWED",ItemLevelTooHigh:"CLAN_ITEM_LEVEL_TOO_HIGH",ItemEquipped:"CLAN_ITEM_EQUIPPED",ItemWrongLevel:"CLAN_ITEM_WRONG_LEVEL",NotEnoughTreasury:"CLAN_NOT_ENOUGH_TREASURY",DepositLimit:"CLAN_DEPOSIT_LIMIT",PurchaseNotFound:"CLAN_PURCHASE_NOT_FOUND",BuffActive:"CLAN_BUFF_ACTIVE",LevelTooLow:"CLAN_LEVEL_TOO_LOW",ProjectNotFound:"CLAN_PROJECT_NOT_FOUND",ProjectLocked:"CLAN_PROJECT_LOCKED",ProjectMaxed:"CLAN_PROJECT_MAXED",ContributeLimit:"CLAN_CONTRIBUTE_LIMIT",ActivityNotFound:"CLAN_ACTIVITY_NOT_FOUND",ActivityNotActive:"CLAN_ACTIVITY_NOT_ACTIVE",ActivityRunning:"CLAN_ACTIVITY_RUNNING",ActivityCooldown:"CLAN_ACTIVITY_COOLDOWN",NoAttempts:"CLAN_NO_ATTEMPTS",ScoreRejected:"CLAN_SCORE_REJECTED",BossDefeated:"CLAN_BOSS_DEFEATED",BoardNotFound:"CLAN_BOARD_NOT_FOUND",QuestNotFound:"CLAN_QUEST_NOT_FOUND",QuestFull:"CLAN_QUEST_FULL",TakeLimit:"CLAN_TAKE_LIMIT",QuestNotTaken:"CLAN_QUEST_NOT_TAKEN",QuestDone:"CLAN_QUEST_DONE",AbandonCooldown:"CLAN_ABANDON_COOLDOWN",SelectionLocked:"CLAN_SELECTION_LOCKED",ClaimAfterEnd:"CLAN_CLAIM_AFTER_END",NotEligible:"CLAN_NOT_ELIGIBLE",ClaimExpired:"CLAN_CLAIM_EXPIRED",CompetitionNotFound:"CLAN_COMPETITION_NOT_FOUND",CompetitionNotActive:"CLAN_COMPETITION_NOT_ACTIVE",RegistrationClosed:"CLAN_REGISTRATION_CLOSED",NotRegistered:"CLAN_NOT_REGISTERED",TooFewMembers:"CLAN_TOO_FEW_MEMBERS",WarPreparation:"CLAN_WAR_PREPARATION",NotInRoster:"CLAN_NOT_IN_ROSTER",TargetInvalid:"CLAN_TARGET_INVALID",AttackPending:"CLAN_ATTACK_PENDING",AttackNotFound:"CLAN_ATTACK_NOT_FOUND",AttackExpired:"CLAN_ATTACK_EXPIRED",RelationExists:"CLAN_RELATION_EXISTS",RelationLimit:"CLAN_RELATION_LIMIT",RelationNotFound:"CLAN_RELATION_NOT_FOUND",RelationDisabled:"CLAN_RELATION_DISABLED"},Wx={Duel:"Duel",Battle:"Battle",League:"League",War:"War"},Hx={Ally:"Ally",Pact:"Pact",Enemy:"Enemy",None:"None"},mr="clan",Cn=zod.z.array(zod.z.string()).nullish(),Y=zod.z.number().nullish(),Kx=zod.z.record(zod.z.string(),zod.z.number()).nullish(),Qx=zod.z.object({NounKey:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SortOrder:Y}).passthrough(),$x=zod.z.object({NameMinLength:Y,NameMaxLength:Y,TagRequired:zod.z.boolean().nullish(),TagMinLength:Y,TagMaxLength:Y,DescriptionMaxLength:Y,AnnouncementMaxLength:Y,Emblem:zod.z.object({Backgrounds:Cn,Symbols:Cn,Colors:Cn}).passthrough().nullish(),Languages:Cn,Attributes:zod.z.record(zod.z.string(),zod.z.object({NameKey:zod.z.string().nullish(),Values:Cn,Required:zod.z.boolean().nullish()}).passthrough()).nullish(),RenameCooldownHours:Y}).passthrough(),Jx=zod.z.object({BaseCapacity:Y,JoinModes:zod.z.array(zod.z.string()).nullish(),DefaultJoinMode:zod.z.string().nullish(),ApplicationHours:Y,InviteHours:Y,JoinCooldownHours:Y,TenureHoursForRewards:Y,NoBoardAttacksOnClanmates:zod.z.boolean().nullish(),SuggestJoinAfterHours:Y,KickInactiveDays:Y}).passthrough(),Zx=zod.z.object({Rank:zod.z.number().catch(0),NameKey:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),MaxCount:Y,Permissions:Cn}).passthrough(),Yx=zod.z.object({Enabled:zod.z.boolean().nullish(),Type:zod.z.string().catch("Resource"),NameKey:zod.z.string().nullish(),CooldownMinutes:Y,LifetimeHours:Y,MaxOpenPerMember:Y,Resources:zod.z.array(zt.passthrough()).nullish(),Funding:zod.z.string().nullish(),MaxPerDonor:Y,MaxHelps:Y,MaxItemLevel:Y,MinMembershipHoursToDonate:Y}).passthrough(),Xx=zod.z.object({Enabled:zod.z.boolean().nullish(),Identity:Qx.nullish(),Create:$x.nullish(),Membership:Jx.nullish(),Roles:zod.z.object({Roles:zod.z.record(zod.z.string(),Zx).nullish(),LeaderRoleID:zod.z.string().nullish(),DefaultRoleID:zod.z.string().nullish()}).passthrough().nullish(),Rankings:zod.z.object({Metrics:Cn,ByLanguage:zod.z.boolean().nullish(),ByRegion:zod.z.boolean().nullish()}).passthrough().nullish(),Counters:zod.z.record(zod.z.string(),zod.z.object({}).passthrough()).nullish(),Progression:zod.z.object({}).passthrough().nullish(),Requests:zod.z.record(zod.z.string(),Yx).nullish(),Gifts:zod.z.object({Gifts:zod.z.record(zod.z.string(),zod.z.object({}).passthrough()).nullish(),ShowSender:zod.z.boolean().nullish()}).passthrough().nullish(),Treasury:zod.z.object({Currencies:zod.z.record(zod.z.string(),zod.z.object({NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),Deposits:zod.z.array(zod.z.object({Resource:zt.passthrough().nullish(),Gives:zod.z.number().catch(1)}).passthrough()).nullish(),DailyDepositCapPerMember:Y,Max:Y}).passthrough()).nullish(),Purchases:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),Cost:Kx,DurationHours:zod.z.number().catch(24),MinClanLevel:Y}).passthrough()).nullish()}).passthrough().nullish(),Projects:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SortOrder:Y,Inputs:zod.z.array(zod.z.object({Resource:zt.passthrough().nullish(),TreasuryCurrencyID:zod.z.string().nullish(),PointsPerUnit:Y}).passthrough()).nullish()}).passthrough()).nullish(),Activities:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),Type:zod.z.string().catch("Goal"),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish()}).passthrough()).nullish(),Quests:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),Mode:zod.z.string().catch("Shared"),NameKey:zod.z.string().nullish()}).passthrough()).nullish(),Competitions:zod.z.record(zod.z.string(),zod.z.object({Enabled:zod.z.boolean().nullish(),Type:zod.z.string().catch("Battle"),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),Registration:zod.z.string().nullish(),MinMembers:Y,BracketSize:Y,Phases:zod.z.array(zod.z.object({DurationHours:zod.z.number().catch(24),NameKey:zod.z.string().nullish()}).passthrough()).nullish(),War:zod.z.object({AttacksPerMember:Y,MaxStars:Y,RosterSize:Y,PreparationHours:Y,ResultSource:zod.z.string().nullish()}).passthrough().nullish()}).passthrough()).nullish(),Leagues:zod.z.object({StartRating:Y,Tiers:zod.z.array(zod.z.object({LeagueID:zod.z.string(),MinRating:zod.z.number().catch(0),NameKey:zod.z.string().nullish(),Icon:zod.z.string().nullish(),SeasonReward:$.nullish()}).passthrough()).nullish(),Season:zod.z.object({IntervalSeconds:Y,AnchorUtc:zod.z.string().nullish(),KeepPercent:Y}).passthrough().nullish()}).passthrough().nullish(),Revenge:zod.z.object({Enabled:zod.z.boolean().nullish(),WindowHours:Y,MaxPerMemberPerDay:Y}).passthrough().nullish(),ChatNotices:zod.z.object({Enabled:zod.z.boolean().nullish(),Events:zod.z.array(zod.z.string()).nullish()}).passthrough().nullish(),Diplomacy:zod.z.object({MaxAllies:Y,MaxPacts:Y,MaxEnemies:Y,ProposalHours:Y}).passthrough().nullish()}).passthrough(),eD=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Kinds:zod.z.record(zod.z.string(),Xx).nullish(),RefreshSeconds:Y}).passthrough(),hl=zod.z.record(zod.z.string(),zod.z.string()).nullish(),pl=zod.z.record(zod.z.string(),zod.z.number()).nullish(),nn=zod.z.object({ClanID:zod.z.string(),KindID:zod.z.string().catch(mr),Name:zod.z.string().catch(""),Tag:zod.z.string().nullish(),Description:zod.z.string().nullish(),Announcement:zod.z.string().nullish(),Emblem:zod.z.object({Background:zod.z.string().nullish(),Symbol:zod.z.string().nullish(),Color:zod.z.string().nullish()}).passthrough().nullish(),Language:zod.z.string().nullish(),Country:zod.z.string().nullish(),Attributes:hl,JoinMode:_x,MinPower:Y,MinLevel:Y,LeaderUserID:zod.z.string().nullish(),MemberCount:zod.z.number().catch(0),Capacity:zod.z.number().catch(0),Level:zod.z.number().catch(1),Xp:zod.z.number().catch(0),NextLevelXp:Y,GiftPoints:zod.z.number().catch(0),GiftLevel:zod.z.number().catch(0),Power:zod.z.number().catch(0),Trophies:zod.z.number().catch(0),Counters:pl,Perks:pl,Modifiers:zod.z.array(zod.z.object({}).passthrough()).nullish(),Treasury:pl,RecommendedProjectID:zod.z.string().nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),CreatedAt:u.nullish(),ActiveAt:u.nullish()}).passthrough(),dl=zod.z.object({RoleID:zod.z.string().catch(""),JoinedAt:u.nullish(),Permissions:zod.z.array(zod.z.string()).catch([]),IsLeader:zod.z.boolean().catch(false),ContributionTotal:zod.z.number().catch(0),ContributionToday:zod.z.number().catch(0),ContributionWeek:zod.z.number().catch(0),DonatedTotal:zod.z.number().catch(0),RewardsFrom:u.nullish()}).passthrough(),tD=zod.z.object({KindID:zod.z.string(),Clan:nn.nullish(),Membership:dl.nullish(),JoinAllowedAt:u.nullish(),InvitesCount:zod.z.number().catch(0),MyApplicationsCount:zod.z.number().catch(0),ClaimableRewards:zod.z.number().catch(0),ClaimableGifts:zod.z.number().catch(0),ClaimableCompetitions:zod.z.number().catch(0),SuggestJoin:zod.z.boolean().catch(false)}).passthrough(),Yh=zod.z.object({ServerTimeUtc:u.nullish(),RefreshSeconds:zod.z.number().catch(30),Kinds:zod.z.array(tD).catch([])}).passthrough(),ml=zod.z.object({ServerTimeUtc:u.nullish(),Clans:zod.z.array(nn).catch([]),NextCursor:zod.z.string().nullish()}).passthrough(),Xh=zod.z.object({ServerTimeUtc:u.nullish(),Clan:nn,Membership:dl.nullish(),Applied:zod.z.boolean().catch(false)}).passthrough(),ed=zod.z.object({UserID:zod.z.string(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),PlayerLevel:zod.z.number().catch(0),RoleID:zod.z.string().catch(""),JoinedAt:u.nullish(),ActiveAt:u.nullish(),Power:zod.z.number().catch(0),Trophies:zod.z.number().catch(0),ContributionTotal:zod.z.number().catch(0),ContributionWeek:zod.z.number().catch(0),ContributionToday:zod.z.number().catch(0),DonatedTotal:zod.z.number().catch(0)}).passthrough(),td=zod.z.object({ServerTimeUtc:u.nullish(),ClanID:zod.z.string().nullish(),Members:zod.z.array(ed).catch([])}).passthrough(),Zh=zod.z.object({Rank:zod.z.number().catch(0),Value:zod.z.number().catch(0),Clan:nn}).passthrough(),nd=zod.z.object({ServerTimeUtc:u.nullish(),Metric:zod.z.string().nullish(),Slice:zod.z.string().nullish(),Rows:zod.z.array(Zh).catch([]),Mine:Zh.nullish()}).passthrough(),nD=zod.z.object({ID:zod.z.string(),Type:zod.z.string().catch("Application"),KindID:zod.z.string().nullish(),ClanID:zod.z.string().nullish(),Clan:nn.nullish(),UserID:zod.z.string().nullish(),Player:ed.nullish(),InviterUserID:zod.z.string().nullish(),Message:zod.z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),fl=zod.z.object({ServerTimeUtc:u.nullish(),Items:zod.z.array(nD).catch([])}).passthrough(),sD=zod.z.object({Type:zod.z.string().catch(""),ActorUserID:zod.z.string().nullish(),TargetUserID:zod.z.string().nullish(),Params:hl,At:u.nullish()}).passthrough(),sd=zod.z.object({ServerTimeUtc:u.nullish(),Entries:zod.z.array(sD).catch([]),NextCursor:zod.z.string().nullish()}).passthrough(),id=zod.z.object({RequestID:zod.z.string(),RequestKindID:zod.z.string().catch(""),Type:zod.z.string().catch("Resource"),UserID:zod.z.string().catch(""),Username:zod.z.string().nullish(),Resource:zt.passthrough().nullish(),ItemLevel:zod.z.number().nullish(),Needed:zod.z.number().catch(0),Filled:zod.z.number().catch(0),Claimed:zod.z.number().catch(0),MyDonation:zod.z.number().catch(0),TaskKey:zod.z.string().nullish(),Helps:zod.z.number().catch(0),MaxHelps:zod.z.number().catch(0),HelpedByMe:zod.z.boolean().catch(false),Status:zod.z.string().catch("Open"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),rd=zod.z.object({ServerTimeUtc:u.nullish(),Requests:zod.z.array(id).catch([])}).passthrough(),iD=zod.z.object({GiftUid:zod.z.string(),GiftID:zod.z.string().catch(""),SenderUserID:zod.z.string().nullish(),Level:zod.z.number().catch(0),Content:$.nullish(),Claimed:zod.z.boolean().catch(false),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),od=zod.z.object({ServerTimeUtc:u.nullish(),GiftLevel:zod.z.number().catch(0),GiftPoints:zod.z.number().catch(0),NextGiftLevelPoints:Y,Gifts:zod.z.array(iD).catch([])}).passthrough(),fr=zod.z.object({Key:zod.z.string(),Source:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),RequiredProgress:zod.z.number().catch(0),Rewards:$.nullish(),ReachedAt:u.nullish(),Claimed:zod.z.boolean().catch(false),Claimable:zod.z.boolean().catch(false),Blocked:zod.z.string().nullish()}).passthrough(),ad=zod.z.object({ServerTimeUtc:u.nullish(),Rewards:zod.z.array(fr).catch([])}).passthrough(),ld=zod.z.object({AttackID:zod.z.string(),AttackerUserID:zod.z.string().nullish(),TargetUserID:zod.z.string().nullish(),Status:zod.z.string().catch("Pending"),Stars:zod.z.number().catch(0),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),ud=zod.z.object({ClanID:zod.z.string(),Clan:nn.nullish(),Relation:zod.z.string().catch("None"),Status:zod.z.string().catch("Active"),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),cd=zod.z.object({ServerTimeUtc:u.nullish(),Clan:nn.nullish(),Membership:dl.nullish(),Request:id.nullish(),Resources:O.nullish(),Inventory:K.nullish(),Done:zod.z.array(zod.z.string()).nullish(),Failed:hl,WarAttack:ld.nullish(),WarBattle:ds.nullish(),Relation:ud.nullish()}).passthrough(),pd=zod.z.object({ServerTimeUtc:u.nullish(),Definitions:eD.nullish(),DefaultKindID:zod.z.string().nullish()}).passthrough(),rD=zod.z.object({Target:zod.z.string().catch(""),Operation:zod.z.string().catch("AddPercent"),Value:zod.z.number().catch(0),Tag:zod.z.string().nullish()}).passthrough(),oD=zod.z.object({PurchaseID:zod.z.string(),ExpiresAt:u.nullish(),Modifiers:zod.z.array(rD).nullish()}).passthrough(),aD=zod.z.object({CurrencyID:zod.z.string().catch(""),Delta:zod.z.number().catch(0),Kind:zod.z.string().nullish(),ActorUserID:zod.z.string().nullish(),RefID:zod.z.string().nullish(),At:u.nullish()}).passthrough(),hd=zod.z.object({ServerTimeUtc:u.nullish(),Balances:zod.z.record(zod.z.string(),zod.z.number()).catch({}),Buffs:zod.z.array(oD).catch([]),Ledger:zod.z.array(aD).catch([]),NextCursor:zod.z.string().nullish(),MyDepositsToday:zod.z.record(zod.z.string(),zod.z.number()).catch({})}).passthrough(),lD=zod.z.object({ProjectID:zod.z.string(),Points:zod.z.number().catch(0),Level:zod.z.number().catch(0),MaxLevel:zod.z.number().catch(0),NextLevelPoints:Y,Locked:zod.z.string().nullish(),MyPointsToday:zod.z.number().catch(0),DailyCap:Y,Recommended:zod.z.boolean().catch(false)}).passthrough(),dd=zod.z.object({ServerTimeUtc:u.nullish(),RecommendedProjectID:zod.z.string().nullish(),Projects:zod.z.array(lD).catch([])}).passthrough(),uD=zod.z.object({ActivityID:zod.z.string(),Type:zod.z.string().catch("Goal"),Status:zod.z.string().catch("Idle"),InstanceKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),Points:zod.z.number().catch(0),MyPoints:zod.z.number().catch(0),MyPointsToday:zod.z.number().catch(0),BossLevel:zod.z.number().catch(0),BossHp:zod.z.number().catch(0),BossDamage:zod.z.number().catch(0),BossDefeated:zod.z.boolean().catch(false),AttemptsLeft:zod.z.number().catch(0),CanStart:zod.z.boolean().catch(false),StartAllowedAt:u.nullish(),Rewards:zod.z.array(fr).catch([])}).passthrough(),md=zod.z.object({ServerTimeUtc:u.nullish(),Activities:zod.z.array(uD).catch([])}).passthrough(),cD=zod.z.object({ObjectiveID:zod.z.string().catch(""),Target:zod.z.number().catch(0),Progress:zod.z.number().catch(0),MyProgress:zod.z.number().catch(0)}).passthrough(),pD=zod.z.object({QuestID:zod.z.string(),Identity:zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough().nullish(),Objectives:zod.z.array(cD).catch([]),Reward:zod.z.object({Grant:$.nullish(),PointsReward:Y}).passthrough().nullish(),ClanXp:Y,Status:zod.z.string().catch("Available"),Takers:zod.z.number().catch(0),MyContribution:zod.z.number().catch(0),Claimable:zod.z.boolean().catch(false),Claimed:zod.z.boolean().catch(false),Blocked:zod.z.string().nullish()}).passthrough(),hD=zod.z.object({BoardID:zod.z.string(),Mode:zod.z.string().catch("Shared"),CycleKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),Ended:zod.z.boolean().catch(false),Points:zod.z.number().catch(0),MyPoints:zod.z.number().catch(0),MyTaken:zod.z.number().catch(0),MaxTaken:zod.z.number().catch(0),TakeAllowedAt:u.nullish(),SelectedBy:zod.z.string().nullish(),CanSelect:zod.z.boolean().catch(false),Quests:zod.z.array(pD).catch([]),Rewards:zod.z.array(fr).catch([])}).passthrough(),fd=zod.z.object({ServerTimeUtc:u.nullish(),Boards:zod.z.array(hD).catch([])}).passthrough(),dD=zod.z.object({CompetitionID:zod.z.string(),Type:zod.z.string().catch("Battle"),Status:zod.z.string().catch("Idle"),InstanceKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),ClaimUntil:u.nullish(),PhaseIndex:Y,PhaseEndsAt:u.nullish(),Registered:zod.z.boolean().catch(false),CanRegister:zod.z.boolean().catch(false),RegisterBlocked:zod.z.string().nullish(),RegistrationClosesAt:u.nullish(),BracketID:zod.z.string().nullish(),ClansInBracket:zod.z.number().catch(0),Score:zod.z.number().catch(0),Place:Y,Finalized:zod.z.boolean().catch(false),NoContest:zod.z.boolean().catch(false),RatingDelta:Y,MyPoints:zod.z.number().catch(0),MyPointsToday:zod.z.number().catch(0),AttacksLeft:Y,InRoster:zod.z.boolean().nullish(),AttacksFrom:u.nullish(),Rewards:zod.z.array(fr).catch([])}).passthrough(),gd=zod.z.object({ServerTimeUtc:u.nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),Competitions:zod.z.array(dD).catch([])}).passthrough(),mD=zod.z.object({Place:zod.z.number().catch(0),Clan:nn.nullish(),Score:zod.z.number().catch(0),RatingDelta:Y,IsMine:zod.z.boolean().catch(false)}).passthrough(),fD=zod.z.object({UserID:zod.z.string(),ClanID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Power:zod.z.number().catch(0),BestStars:zod.z.number().catch(0),AttacksUsed:zod.z.number().catch(0)}).passthrough(),yd=zod.z.object({ServerTimeUtc:u.nullish(),BracketID:zod.z.string().nullish(),CompetitionID:zod.z.string().nullish(),Type:zod.z.string().catch("Battle"),InstanceKey:zod.z.string().nullish(),StartsAt:u.nullish(),EndsAt:u.nullish(),Finalized:zod.z.boolean().catch(false),NoContest:zod.z.boolean().catch(false),Rows:zod.z.array(mD).catch([]),War:zod.z.array(fD).nullish(),MyAttacks:zod.z.array(ld).nullish()}).passthrough(),Rd=zod.z.object({ServerTimeUtc:u.nullish(),CanManage:zod.z.boolean().catch(false),Relations:zod.z.array(ud).catch([]),Limits:zod.z.record(zod.z.string(),zod.z.number()).catch({}),Counts:zod.z.record(zod.z.string(),zod.z.number()).catch({})}).passthrough(),gD=zod.z.object({RevengeID:zod.z.string(),VictimUserID:zod.z.string().nullish(),VictimName:zod.z.string().nullish(),AttackerUserID:zod.z.string().nullish(),AttackerName:zod.z.string().nullish(),AttackerAvatarUrl:zod.z.string().nullish(),Action:zod.z.string().nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish(),TakenBy:zod.z.string().nullish(),TakenByName:zod.z.string().nullish(),IsMine:zod.z.boolean().catch(false)}).passthrough(),Cd=zod.z.object({ServerTimeUtc:u.nullish(),Revenges:zod.z.array(gD).catch([]),TakenToday:zod.z.number().catch(0),DailyLimit:zod.z.number().catch(0)}).passthrough(),yD=zod.z.object({Key:zod.z.string().nullish(),LeagueID:zod.z.string().nullish(),Rating:zod.z.number().catch(0),EndedAt:u.nullish(),Reward:$.nullish(),Claimable:zod.z.boolean().catch(false),Claimed:zod.z.boolean().catch(false)}).passthrough(),Sd=zod.z.object({ServerTimeUtc:u.nullish(),LeagueRating:zod.z.number().catch(0),LeagueID:zod.z.string().nullish(),SeasonKey:zod.z.string().nullish(),SeasonEndsAt:u.nullish(),LastSeason:yD.nullish()}).passthrough();var gl="Clan",gr=class{constructor(e){this.ctx=e;}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}get definitions(){return this.ctx.data.config.getSection(gl)}get enabled(){let e=this.definitions;return !e||e.IsEnabled===false?false:Object.values(e.Kinds??{}).some(t=>t?.Enabled!==false)}get kindIDs(){let e=this.definitions?.Kinds??{};return Object.entries(e).filter(([,t])=>t?.Enabled!==false).sort(([,t],[,n])=>(t?.Identity?.SortOrder??0)-(n?.Identity?.SortOrder??0)).map(([t])=>t)}kind(e){return (this.definitions?.Kinds??{})[e??this.kindIDs[0]??mr]}async getDefinitions(e){let t=this.ctx.cache.configSection(gl,e);if(t)return G(t);let n=this.request();if(!n)return l;let s=await this.ctx.api.clan.getDefinitions(n);if(!s.ok)return s;let i=s.data.Definitions??{};return this.ctx.data.config.patchSection(gl,i),G(i)}async getMyClans(){let e=this.request();if(!e)return l;let t=await this.ctx.api.clan.getMyClans(e);return t.ok&&this.ctx.emitter.emit("clan:myClansLoaded",t.data),t}async searchClans(e){let t=this.request({KindID:e?.kindID,Query:e?.query,OnlyOpen:e?.onlyOpen,NotFull:e?.notFull,Language:e?.language,PageSize:e?.pageSize});return t?this.ctx.api.clan.searchClans(t):l}async getRecommendedClans(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRecommendedClans(t):l}async getClan(e,t){if(!e?.trim())return h("client","ClanID is required.");let n=this.request({ClanID:e.trim(),KindID:t});return n?this.ctx.api.clan.getClan(n):l}async getMembers(e,t){let n=this.request({ClanID:e,KindID:t});return n?this.ctx.api.clan.getClanMembers(n):l}async getRankings(e){let t=this.request({KindID:e?.kindID,Metric:e?.metric,Slice:e?.slice,PageSize:e?.pageSize});return t?this.ctx.api.clan.getRankings(t):l}async getApplications(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getApplications(t):l}async getMyInvites(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getMyInvites(t):l}async getLog(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getClanLog(t):l}async getRequests(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRequests(t):l}async getGifts(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getGifts(t):l}async getRewards(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRewards(t):l}async getTreasury(e,t){let n=this.request({KindID:e,Cursor:t});return n?this.ctx.api.clan.getTreasury(n):l}async getProjects(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getProjects(t):l}async getActivities(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getActivities(t):l}async getClanQuests(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getClanQuests(t):l}async getCompetitions(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getCompetitions(t):l}async getBracket(e,t){let n=this.request({CompetitionID:e,BracketID:t?.bracketID,InstanceKey:t?.instanceKey,KindID:t?.kindID});return n?this.ctx.api.clan.getBracket(n):l}async getDiplomacy(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getDiplomacy(t):l}async getRevenges(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getRevenges(t):l}async getLeague(e){let t=this.request({KindID:e});return t?this.ctx.api.clan.getLeague(t):l}async mutate(e,t){let n=this.request(t);if(!n)return l;let s=await this.ctx.api.clan.mutate(e,n);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("clan:changed",{action:e,...s.data})),s}info(e){return {ClanName:e.name,Tag:e.tag,Description:e.description,Announcement:e.announcement,Emblem:e.emblem,Language:e.language,Attributes:e.attributes,JoinMode:e.joinMode,MinPower:e.minPower,MinLevel:e.minLevel,PriceOptionID:e.priceOptionID}}createClan(e,t){return e?.name?.trim()?this.mutate("CreateClan",{KindID:t,...this.info(e)}):Promise.resolve(h("client","Name is required."))}updateClan(e,t){return this.mutate("UpdateClan",{KindID:t,...this.info(e)})}disbandClan(e){return this.mutate("DisbandClan",{KindID:e})}joinClan(e,t){return this.mutate("JoinClan",{ClanID:e,KindID:t})}applyToClan(e,t,n){return this.mutate("ApplyToClan",{ClanID:e,Message:t,KindID:n})}cancelApplication(e,t){return this.mutate("CancelApplication",{ClanID:e,KindID:t})}acceptApplication(e,t){return this.mutate("AcceptApplication",{TargetUserID:e,KindID:t})}rejectApplication(e,t){return this.mutate("RejectApplication",{TargetUserID:e,KindID:t})}invitePlayer(e,t,n){return this.mutate("InvitePlayer",{TargetUserID:e,Message:t,KindID:n})}acceptInvite(e,t){return this.mutate("AcceptInvite",{ClanID:e,KindID:t})}declineInvite(e,t){return this.mutate("DeclineInvite",{ClanID:e,KindID:t})}leaveClan(e){return this.mutate("LeaveClan",{KindID:e})}kickMember(e,t){return this.mutate("KickMember",{TargetUserID:e,KindID:t})}setMemberRole(e,t,n){return this.mutate("SetMemberRole",{TargetUserID:e,RoleID:t,KindID:n})}transferLeadership(e,t){return this.mutate("TransferLeadership",{TargetUserID:e,KindID:t})}createRequest(e,t){return this.mutate("CreateRequest",{RequestKindID:e,Resource:t?.resource,TaskKey:t?.taskKey,ItemInstanceID:t?.itemInstanceID,KindID:t?.kindID})}donateItems(e,t,n){return this.mutate("Donate",{RequestID:e,ItemInstanceIDs:t,KindID:n})}donate(e,t=1,n){return this.mutate("Donate",{RequestID:e,Amount:t,KindID:n})}help(e,t){return this.mutate("Help",{RequestID:e,KindID:t})}claimRequest(e,t){return this.mutate("ClaimRequest",{RequestID:e,KindID:t})}claimGift(e,t){return this.mutate("ClaimGift",{GiftUid:e,KindID:t})}claimAllGifts(e){return this.mutate("ClaimAllGifts",{KindID:e})}claimRewards(e,t){return this.mutate("ClaimRewards",{RewardKeys:e,KindID:t})}depositToTreasury(e,t,n=1,s){return this.mutate("DepositToTreasury",{CurrencyID:e,PayWith:t,Steps:n,KindID:s,RelatedEntityID:`clan_deposit_${V()}`})}buyTreasuryPurchase(e,t){return this.mutate("BuyTreasuryPurchase",{PurchaseID:e,KindID:t})}contributeToProject(e,t){return this.mutate("ContributeToProject",{ProjectID:e,Amount:t.amount,PayWith:t.payWith,FromTreasury:t.fromTreasury,CurrencyID:t.currencyID,KindID:t.kindID,RelatedEntityID:`clan_project_${V()}`})}setRecommendedProject(e,t){return this.mutate("SetRecommendedProject",{ProjectID:e??void 0,KindID:t})}startActivity(e,t){return this.mutate("StartActivity",{ActivityID:e,KindID:t})}submitActivityScore(e,t,n){return this.mutate("SubmitActivityScore",{ActivityID:e,Score:t,KindID:n})}claimActivityRewards(e){return this.mutate("ClaimActivityRewards",{ActivityID:e?.activityID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}selectClanQuests(e,t,n){return this.mutate("SelectClanQuests",{BoardID:e,QuestIDs:t,KindID:n})}takeClanQuest(e,t,n){return this.mutate("TakeClanQuest",{BoardID:e,QuestID:t,KindID:n})}abandonClanQuest(e,t,n){return this.mutate("AbandonClanQuest",{BoardID:e,QuestID:t,KindID:n})}claimClanQuestRewards(e){return this.mutate("ClaimClanQuestRewards",{BoardID:e?.boardID,QuestID:e?.questID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}registerForCompetition(e,t){return this.mutate("RegisterForCompetition",{CompetitionID:e,KindID:t})}claimCompetitionRewards(e){return this.mutate("ClaimCompetitionRewards",{CompetitionID:e?.competitionID,InstanceKey:e?.instanceKey,RewardKeys:e?.keys,KindID:e?.kindID})}startWarAttack(e,t,n){return this.mutate("StartWarAttack",{CompetitionID:e,TargetUserID:t,CharacterID:n?.characterID,KindID:n?.kindID})}setDiplomacy(e,t,n){return this.mutate("SetDiplomacy",{TargetClanID:e,Relation:t,KindID:n})}takeRevenge(e,t){return this.mutate("TakeRevenge",{RevengeID:e,KindID:t})}claimSeasonReward(e){return this.mutate("ClaimSeasonReward",{KindID:e})}};var Vn={GetDefinitions:"GetDefinitions",GetAvatars:"GetAvatars",GetShop:"GetShop",BuyItem:"BuyItem"},RD={TooManyUsers:"AVATAR_TOO_MANY_USERS",Disabled:"AVATAR_DISABLED",NotForSale:"AVATAR_ITEM_NOT_FOR_SALE"},yr=50,Rr=zod.z.object({Enabled:zod.z.boolean().nullish(),Styles:zod.z.array(zod.z.string()).nullish(),BlockedSlots:zod.z.array(zod.z.string()).nullish(),HeightMin:zod.z.number().nullish(),HeightMax:zod.z.number().nullish()}).passthrough(),CD=48,SD=zod.z.object({UserID:zod.z.string(),Rev:zod.z.string(),NotModified:zod.z.boolean().nullish(),HasAvatar:zod.z.boolean(),Spec:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),bd=zod.z.object({id:zod.z.string(),slot:zod.z.string()}).passthrough(),xd=zod.z.object({Enabled:zod.z.boolean(),Avatars:zod.z.array(SD).nullish().transform(r=>r??[]),Items:zod.z.record(zod.z.string(),bd).nullish().transform(r=>r??{})}).passthrough(),bD=zod.z.object({ItemID:zod.z.string(),Slot:zod.z.string(),PriceCredits:zod.z.number(),OnSale:zod.z.boolean().nullish(),Name:zod.z.string().nullish(),Source:zod.z.enum(["platform","authors"]).nullish().catch(null),AuthorName:zod.z.string().nullish(),IsOwned:zod.z.boolean().nullish()}).passthrough(),Dd=zod.z.object({Enabled:zod.z.boolean(),Offers:zod.z.array(bD).nullish().transform(r=>r??[]),Owned:zod.z.array(zod.z.string()).nullish().transform(r=>r??[]),LoginRequired:zod.z.boolean().nullish().transform(r=>r??false),Items:zod.z.record(zod.z.string(),bd).nullish().transform(r=>r??{}),Paged:zod.z.boolean().nullish(),Next:zod.z.string().nullish(),Slots:zod.z.array(zod.z.string()).nullish(),AuthorsOpen:zod.z.boolean().nullish()}).passthrough(),Id=zod.z.object({ItemID:zod.z.string().nullish(),Owned:zod.z.boolean().nullish().transform(r=>r??false),TestPurchase:zod.z.boolean().nullish().transform(r=>r??false),CreditsConfirmation:Re.nullish()}).passthrough();var xD="Avatar",Cr=class{constructor(e){this.ctx=e;e.emitter.on("auth:loggedOut",()=>{this.held.clear(),this.inflight.clear(),this.disabled=false;});}ctx;held=new Map;inflight=new Map;disabled=false;get definitions(){return this.ctx.cache.configSection(xD)??null}get enabled(){return this.definitions?.Enabled===true&&!this.disabled}peek(e){return this.held.get(e)}async getMine(){let e=this.ctx.auth.context?.userID;if(!e)return l;let t=await this.get([e]);return t.ok?G(t.data[0]??null):t}async get(e){if(!this.ctx.authedRequest())return l;let n=[...new Set(e.map(o=>o?.trim()).filter(o=>!!o))];if(n.length===0)return G([]);let s=new Set,i=[];for(let o of n){let p=this.inflight.get(o);p?s.add(p):i.push(o);}for(let o=0;o<i.length;o+=yr){let p=i.slice(o,o+yr),m=this.request(p);for(let g of p)this.inflight.set(g,m);m.finally(()=>{for(let g of p)this.inflight.get(g)===m&&this.inflight.delete(g);}),s.add(m);}for(let o of await Promise.all(s)){if(!o.ok)return o;if(!o.data.Enabled)return G([])}return G(n.map(o=>this.held.get(o)).filter(o=>!!o))}async getShop(){let e=this.ctx.authedRequest();return e?this.ctx.api.avatar.getShop(e):l}async browseShop(e={}){let t=this.ctx.authedRequest();if(!t)return l;t.Sort=e.sort??"new",e.slot&&(t.Slot=e.slot);let n=e.query?.trim();return n&&(t.Query=n),e.ownedOnly&&(t.OwnedOnly=true),e.source&&(t.Source=e.source),e.cursor&&(t.Cursor=e.cursor),this.ctx.api.avatar.getShop(t)}async buyItem(e,t,n){let s=this.ctx.authedRequest();return s?(s.ItemID=e,s.PriceCredits=t,n&&(s.CreditsConfirmationID=n),this.ctx.api.avatar.buyItem(s)):l}async request(e){let t=this.ctx.authedRequest();if(!t)return l;t.UserIDs=e;let n={};for(let i of e){let o=this.held.get(i);o&&(n[i]=o.rev);}Object.keys(n).length>0&&(t.KnownRevs=n);let s=await this.ctx.api.avatar.getAvatars(t);if(!s.ok)return s;if(this.disabled=!s.data.Enabled,!s.data.Enabled){for(let i of e)this.held.delete(i);return s}if(s.data.Avatars.some(i=>i.NotModified&&this.held.get(i.UserID)?.rev!==i.Rev)){for(let p of e)this.held.delete(p);let i=this.ctx.authedRequest();if(!i)return l;i.UserIDs=e;let o=await this.ctx.api.avatar.getAvatars(i);return o.ok?o.data.Avatars.some(p=>p.NotModified)?h("client","AVATAR_REVISION_MISMATCH"):(this.apply(o.data),o):o}return this.apply(s.data),s}apply(e){let t=[];for(let n of e.Avatars){if(n.NotModified)continue;let s=n.HasAvatar?n.Spec??null:null;this.held.set(n.UserID,{userID:n.UserID,rev:n.Rev,hasAvatar:n.HasAvatar&&!!s,spec:s,items:s?DD(s,e.Items):[]}),t.push(n.UserID);}t.length>0&&this.ctx.emitter.emit("avatar:changed",{userIDs:t});}};function DD(r,e){let t=r.wear;if(!t||typeof t!="object")return [];let n=[];for(let s of Object.values(t))typeof s=="string"&&e[s]&&n.push(e[s]);return n}var Sr=class{constructor(e){this.ctx=e;}ctx;async getMine(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.getMyPartnership(e):l}async apply(e){let t=this.ctx.authedRequest();return t?(t.Links=(e.links??[]).map(n=>n.trim()).filter(n=>n.length>0),e.publicName?.trim()&&(t.PublicName=e.publicName.trim()),e.about?.trim()&&(t.About=e.about.trim()),typeof e.followers=="number"&&e.followers>=0&&(t.Followers=Math.floor(e.followers)),this.ctx.api.partners.apply(t)):l}async acceptInvite(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.acceptInvite(e):l}async getStats(e){let t=this.ctx.authedRequest();return t?(typeof e=="number"&&e>0&&(t.Days=Math.floor(e)),this.ctx.api.partners.getStats(t)):l}async listCreators(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.listCreators(e):l}async getPayouts(){let e=this.ctx.authedRequest();return e?this.ctx.api.partners.getPayouts(e):l}};var br={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},yl="idos-app",Pd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),Allowed:zod.z.boolean(),DenyReason:zod.z.string().nullish(),Message:zod.z.string().nullish(),RetryAfterSeconds:zod.z.number().nullish(),RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),AdUnitID:zod.z.string().nullish(),Type:zod.z.string().nullish(),ExpiresAtUtc:zod.z.string().nullish(),CreditsToAward:zod.z.number().nullish(),RequiresServerSideVerification:zod.z.boolean().nullish()}),vd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),RequestID:zod.z.string().nullish(),Status:zod.z.string(),CreditsAwarded:zod.z.number().nullish(),RetryAfterSeconds:zod.z.number().nullish(),ExpiresAtUtc:zod.z.string().nullish(),AlreadyProcessed:zod.z.boolean().nullish(),GrantedWithoutSsv:zod.z.boolean().nullish(),Resources:O.nullish()});var ID=new Set(["CANCELLED","DECLINED","CLOSED"]),PD=45e3,vD=r=>new Promise(e=>setTimeout(e,r)),xr=class{constructor(e){this.ctx=e;}ctx;get available(){return this.ctx.host.supports.rewardedAds}async showRewarded(e){if(!this.ctx.host.supports.rewardedAds)return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let n=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!n.ok)return {status:"unavailable",reason:n.error};let s=n.data;if(!s.Allowed)return {status:"denied",reason:s.DenyReason??void 0,retryAfterSeconds:s.RetryAfterSeconds??void 0};if(!s.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let i=null;if(s.ProviderID!==yl&&(i=this.titleProvider(s.ProviderID),!i))return {status:"unavailable",reason:"NO_WEB_ADS"};let o=await this.ctx.host.showRewardedAd({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:s.RequestID,placementID:e,adUnitID:s.AdUnitID,provider:i});return o.ok?{...await this.awaitReward(s.RequestID,o.via),requestID:s.RequestID}:{status:ID.has(o.error??"")?"cancelled":"unavailable",reason:o.error}}titleProvider(e){if(!this.ctx.host.supports.titleAds||!e)return null;let n=this.ctx.data.config.getSection("Advertising")?.Providers?.[e];if(!n||n.Enabled===false)return null;let s=this.ctx.host.getClientPlatform(),i=s===Ne.Android?n.AndroidAppID:s===Ne.Ios?n.IosAppID:n.WebAppID;return i?{id:e,kind:n.Kind??"AppLovinMax",appKey:i}:null}async awaitReward(e,t){let n=Date.now()+PD;for(;;){let s=this.ctx.authedRequest();if(!s)return {status:"pending",via:t};let i=await this.ctx.api.advertising.completeView({...s,RequestID:e});if(i.ok&&i.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:i.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((i.ok?i.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>n)return {status:"pending",via:t,reason:i.ok?void 0:i.error};await vD(o);}}};var Wt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},AD={Client:"Client",Server:"Server",System:"System"},TD=zod.z.enum(["Client","Server","System"]).catch("Client"),Rl=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:TD.nullish(),ExpiresAt:u.nullish()}).passthrough(),Dr=zod.z.record(zod.z.string(),Rl),Ad=zod.z.object({Version:zod.z.number().nullish(),Private:Dr.nullish(),Public:Dr.nullish(),ReadOnly:Dr.nullish()}),Cl=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Dr.nullish()}),Sl=zod.z.object({ServerTimeUtc:u.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),wD=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),Td=zod.z.object({ServerTimeUtc:u.nullish(),Results:zod.z.array(wD).nullish()}),wd=zod.z.object({ServerTimeUtc:u.nullish(),DeletedCount:zod.z.number().nullish()}),kd=zod.z.object({Results:zod.z.array(Cl).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),kD={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},zD=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),MD=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:zD.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Ir=zod.z.object({Keys:zod.z.record(zod.z.string(),MD).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),kt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var OD={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},ED={Title:"Title",Platform:"Platform"},zd=zod.z.object({UserID:zod.z.string(),PublicData:_e.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()});var qD=zod.z.object({StageLevel:zod.z.number().nullish(),SpecialPlayedCount:zod.z.number().nullish()}),Md=zod.z.object({UserID:zod.z.string(),IsSelf:zod.z.boolean().nullish(),PublicData:_e.nullish(),Characters:zod.z.record(zod.z.string(),cs).nullish(),StrongestCharacterID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),Board:qD.nullish(),PublicCustomData:zod.z.record(zod.z.string(),Rl).nullish(),Relation:zod.z.enum(["None","Friend","RequestSent","RequestReceived"]).nullish(),FriendSource:zod.z.enum(["Title","Platform"]).nullish(),BlockedByMe:zod.z.boolean().nullish(),FriendRequestsAllowed:zod.z.boolean().nullish()});var fs=zod.z.object({Friends:zod.z.array(zd).nullish()}),UD=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),gs=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:zd.nullish(),Counters:UD.nullish()}),LD={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},BD={Like:"Like",Favorite:"Favorite"},GD={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},ND={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},_D={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived",ArenaDefeat:"ArenaDefeat"},VD=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),FD=zod.z.object({Id:zod.z.string(),Verb:zod.z.string().nullish(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Count:zod.z.number().nullish(),LastActors:zod.z.array(VD).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),OccurredAt:u.nullish(),OwnerImpact:O.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),Od=zod.z.object({Items:zod.z.array(FD).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),ys=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),jD=zod.z.object({Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),Followers:zod.z.number().nullish(),Following:zod.z.number().nullish(),Comments:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Posts:zod.z.number().nullish(),Dislikes:zod.z.number().nullish()}).passthrough(),sn=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:jD.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),Ed=zod.z.object({Items:zod.z.array(sn).nullish()}).passthrough(),bl={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},WD=zod.z.object({UserID:zod.z.string(),PublicData:_e.nullish(),Mutual:zod.z.boolean().nullish(),Since:u.nullish()}).passthrough(),Pr=zod.z.object({Items:zod.z.array(WD).nullish(),...bl}).passthrough(),HD=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:u.nullish()}).passthrough(),qd=zod.z.object({Items:zod.z.array(HD).nullish(),...bl}).passthrough(),vr=zod.z.object({CommentID:zod.z.string(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),ParentCommentID:zod.z.string().nullish(),AuthorUserID:zod.z.string().nullish(),AuthorPublicData:_e.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:u.nullish(),EditedAt:u.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Ud=zod.z.object({Items:zod.z.array(vr).nullish(),...bl,TotalCount:zod.z.number().nullish()}).passthrough(),Ld=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),Bd=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),Gd=zod.z.object({CommentsEnabled:zod.z.boolean().nullish(),CommentableTypes:zod.z.array(zod.z.string()).nullish(),CommentMaxLength:zod.z.number().nullish(),CommentMaxLinks:zod.z.number().nullish()}).passthrough(),KD="FRIENDS_FROM_PLATFORM",QD={Off:"Off",Default:"Default",Always:"Always"},$D={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Nd=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:zod.z.boolean().nullish()}).passthrough(),Pe={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report",GetPlayerProfile:"GetPlayerProfile"};var xl={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Ar=class{constructor(e){this.ctx=e;e.cache.bindLoginView(xl,{schema:ys,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return l;t.Limit=e;let n=await this.ctx.api.social.getRecommendedFriends(t);return n.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",n.data),n}async getPlayerProfile(e){if(!e)return h("client","TargetUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.getPlayerProfile(t);return n.ok&&this.ctx.emitter.emit("social:playerProfileLoaded",n.data),n}async sendFriendRequest(e){if(!e)return h("client","TargetUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.sendFriendRequest(t);return n.ok&&(n.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",n.data)),n}async acceptFriendRequest(e){if(!e)return h("client","RequesterUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.acceptFriendRequest(t);return n.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",n.data)),n}async declineFriendRequest(e){if(!e)return h("client","RequesterUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.declineFriendRequest(t);return n.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",n.data)),n}async removeFriend(e){if(!e)return h("client","FriendUserID is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},n=await this.ctx.api.social.removeFriend(t);return n.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(n.data.Counters),this.ctx.emitter.emit("social:friendRemoved",n.data)),n}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return l;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let n=await this.ctx.api.social.getInbox(t);return n.ok&&this.ctx.emitter.emit("social:inboxLoaded",n.data),n}getInboxUnread(e){return this.ctx.cache.read(xl,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(xl,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let n=this.ctx.authedRequest();return n?(n.ReactionKind=e,n.EntityType=t.entityType,this.applyPage(n,t.cursor,t.limit),this.ctx.api.social.getMyReactions(n)):l}async getEntityStates(e,t){if(!t?.length)return h("client","EntityIDs are required.");let n=this.ctx.authedRequest();return n?(n.EntityType=e,n.EntityIDs=t,this.ctx.api.social.getEntityStates(n)):l}async addComment(e,t,n,s){let i=this.targetRequest(e,t);if("ok"in i)return i;if(!n?.trim())return h("client","Text is required.");i.Text=n,i.ParentCommentID=s;let o=await this.ctx.api.social.addComment(i);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return h("client","CommentID is required.");if(!t?.trim())return h("client","Text is required.");let n=this.ctx.authedRequest();if(!n)return l;n.CommentID=e,n.Text=t;let s=await this.ctx.api.social.editComment(n);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return h("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.CommentID=e;let n=await this.ctx.api.social.deleteComment(t);return n.ok&&this.ctx.emitter.emit("social:commentDeleted",n.data),n}async getComments(e,t,n={}){let s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=n.parentCommentID,this.applyPage(s,n.cursor,n.limit),this.ctx.api.social.getComments(s))}async report(e,t,n,s){let i=this.targetRequest(e,t);if("ok"in i)return i;if(!n)return h("client","ReportReason is required.");i.ReportReason=n,i.ReportComment=s;let o=await this.ctx.api.social.report(i);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,n,s){let i=this.targetRequest(t,n);if("ok"in i)return i;i.ReactionKind=s;let o=await this.ctx.api.social[e](i);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,n){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,n),this.ctx.api.social[e](s)):l}applyPage(e,t,n){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=n;}targetRequest(e,t){if(!e)return h("client","EntityType is required.");if(!t)return h("client","EntityID is required.");let n=this.ctx.authedRequest();return n?(n.EntityType=e,n.EntityID=t,n):l}};var _d="TimedBoost";function JD(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Tr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(_d,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),G(t);let n=this.ctx.authedRequest();if(!n)return l;let s=await this.ctx.api.timedBoost.getDefinitions(n);return s.ok&&(this.ctx.data.config.patchSection(_d,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let n=e.trim();if(!JD(n))return h("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:n,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${n}_${V()}`},i=await this.ctx.api.timedBoost.activate(s);if(i.ok&&!i.data.CreditsConfirmation){let o=i.data;if(o.ActivatedBoost){let p=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,p);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return i}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var ZD="UserCustomData";function Vd(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var wr=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(ZD,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return h("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(n);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,Wt.Private)}async setPublicData(e,t){return this.setData(e,t,Wt.Public)}async setData(e,t,n){let s=e.trim();if(!Vd(s))return h("client",'KeyID is required and must not contain "." or "$".');if(t==null)return h("client","Value is required.");if(!this.ctx.auth.context)return l;let i={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(n===Wt.Private?this.ctx.api.userCustomData.setPrivateData(i):this.ctx.api.userCustomData.setPublicData(i));if(p.ok){let m=p.data;this.ctx.data.user.patchUserCustomDataKey(n,m.KeyID,t,m.Version??0,m.ExpiresAt),this.ctx.emitter.emit(n===Wt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",m);}return p}async deleteKey(e,t){let n=e.trim();if(!Vd(n))return h("client",'KeyID is required and must not contain "." or "$".');if(t!==Wt.Private&&t!==Wt.Public)return h("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return l;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Bucket:t},i=await this.ctx.api.userCustomData.deleteKey(s);return i.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,n),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),i}async batchSet(e){if(!e.length)return h("client","At least one item is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},n=await this.ctx.api.userCustomData.batchSet(t);if(n.ok){for(let s of n.data.Results??[]){let i=s.Bucket??Wt.Private,o=e.find(p=>p.Bucket===i&&p.KeyID===s.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(i,s.KeyID,o.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",n.data);}return n}async batchDelete(e){if(!e.length)return h("client","At least one item is required.");if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},n=await this.ctx.api.userCustomData.batchDelete(t);if(n.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",n.data);}return n}async batchGetPublicUserCustomDataOf(e){if(!e.length)return h("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return l;t.TargetUserIDs=e;let n=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return n.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",n.data),n}};var YD="TitleCustomDataDefinitions",Fd=50;function XD(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function Dl(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function eI(r){let e={};for(let[t,n]of Object.entries(r))Dl(n)||(e[t]=n);return e}var kr=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(YD,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return l;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let n=await this.ctx.api.titleCustomData.getPublicTitleData(t);return n.ok&&this.absorb(n.data),n}async getPublicTitleDataKeys(e){let t=e.map(i=>i.trim()).filter(i=>i.length>0);if(!t.length)return h("client","At least one KeyID is required.");if(t.some(i=>!XD(i)))return h("client",'KeyID must not contain "." or "$".');if(t.length>Fd)return h("client",`At most ${Fd} keys per call \u2014 request them in chunks.`);let n=this.ctx.authedRequest();if(!n)return l;n.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(n);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Dl(t))return t.Value;let n=this.staticCache[e];if(n?.Value!=null&&!Dl(n))return n.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=eI(this.runtimeCache),e.Runtime=this.runtimeCache):e.Runtime&&(this.runtimeCache=e.Runtime),e.RuntimeVersion!=null&&(this.lastRuntimeVersion=e.RuntimeVersion),this.ctx.emitter.emit("titleCustomData:publicDataLoaded",e);}};var zr=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var tI={Fast:"Fast",Sequential:"Sequential"},nI={Instant:"Instant",Timed:"Timed"};var sI={Hit:"Hit",Blocked:"Blocked"},iI=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),rI=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:$.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:$.nullish()}).passthrough();var oI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:$.nullish()}).passthrough(),aI=zod.z.object({Reward:$.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough();zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(oI).nullish(),Rate:aI.nullish()}).passthrough();zod.z.object({PlayedCount:zod.z.number().nullish(),RewardsClaimedCount:zod.z.number().nullish(),InstantClaimsCount:zod.z.number().nullish(),EarlyClaimsCount:zod.z.number().nullish(),LateClaimsCount:zod.z.number().nullish(),AdViewsTotal:zod.z.number().nullish(),StatRewardClaimsCount:zod.z.number().nullish(),StatReportsClampedCount:zod.z.number().nullish(),StatReportsUnknownMetricCount:zod.z.number().nullish()}).passthrough();var jd=zod.z.object({}).passthrough().transform(r=>r),Wd=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Xe=zod.z.object({Operation:O.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),lI=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),uI=zod.z.object({ShieldChance:zod.z.number().nullish(),DamagedBuildingChance:zod.z.number().nullish(),RankMultiplierMin:zod.z.number().nullish(),RankMultiplierMax:zod.z.number().nullish(),RankOffsetMin:zod.z.number().nullish(),RankOffsetMax:zod.z.number().nullish(),StageLevelSpread:zod.z.number().nullish()}).passthrough(),cI=zod.z.object({CostMatrixTemplatesByID:zod.z.record(zod.z.string(),zod.z.array(zod.z.array(zod.z.number()))).nullish(),PerBoardGrowth:zod.z.number().nullish(),VisualTemplateCycle:zod.z.array(zod.z.string()).nullish(),EconomyScaledResources:he.nullish(),ScaleRaidStealWithEconomy:zod.z.boolean().nullish(),ScaleAttackRewardWithEconomy:zod.z.boolean().nullish(),AttackValueFromCostMatrix:zod.z.boolean().nullish(),AttackBlockedRewardFactor:zod.z.number().nullish(),ScaleVictimLossWithEconomy:zod.z.boolean().nullish(),ScaleVictimLossWithTier:zod.z.boolean().nullish(),SynthesizedBuildingSlots:zod.z.number().nullish(),SynthesizedBuildingMaxLevel:zod.z.number().nullish(),DifficultyGrowthPerBoard:zod.z.number().nullish()}).passthrough(),pI=zod.z.object({CostMatrix:zod.z.array(zod.z.array(zod.z.number())).nullish(),PerBoardGrowth:zod.z.number().nullish(),EconomyScale:zod.z.number().nullish(),ScaledResources:he.nullish()}).passthrough(),Hd=zod.z.object({SlotIndex:zod.z.number().nullish(),Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxLevel:zod.z.number().nullish(),MaxLevelReward:$.nullish()}).passthrough(),hI=zod.z.object({Index:zod.z.number().nullish(),Type:zod.z.string().nullish(),CustomTypeID:zod.z.string().nullish(),RandomActionAttackWeight:zod.z.number().nullish(),RandomActionRaidWeight:zod.z.number().nullish(),ChanceTableID:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),dI=zod.z.object({Tiles:zod.z.record(zod.z.string(),hI).nullish()}).passthrough(),mI=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Xe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),fI=zod.z.object({Weight:zod.z.number().nullish(),Tag:zod.z.string().nullish(),MinBonusCells:zod.z.number().nullish(),MaxBonusCells:zod.z.number().nullish(),BonusPool:zod.z.array(mI).nullish(),GuaranteedBonus:Xe.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),gI=zod.z.object({Variants:zod.z.array(fI).nullish()}).passthrough(),yI=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:Xe.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),RI=zod.z.object({Outcomes:zod.z.array(yI).nullish()}).passthrough(),Kd=zod.z.object({PerAdMultiplierRange:Wd.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish(),PremiumMultiplier:zod.z.number().nullish(),MinPremiumTier:zod.z.number().nullish()}).passthrough(),CI=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Xe.nullish()}).passthrough(),SI=zod.z.object({Tiers:zod.z.array(CI).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Xe.nullish()}).passthrough(),bI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Xe.nullish()}).passthrough(),xI=zod.z.object({Reward:Xe.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),DI=zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(bI).nullish(),Rate:xI.nullish()}).passthrough(),Qd=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),DI).nullish()}).passthrough(),II=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Xe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:me.nullish(),Multipliers:Kd.nullish(),Gradation:SI.nullish(),RunStats:Qd.nullish()}).passthrough(),PI=zod.z.object({Choices:zod.z.array(II).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),vI=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Xe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),AI=zod.z.object({OnPassStart:Xe.nullish(),OnTileLanding:zod.z.record(zod.z.string(),Xe).nullish(),OnAttack:zod.z.record(zod.z.string(),Xe).nullish(),OnRaid:zod.z.record(zod.z.string(),Xe).nullish(),OnBuild:Xe.nullish(),OnStageComplete:Xe.nullish(),OnAttackBonusDrops:zod.z.array(vI).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),RI).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),PI).nullish()}).passthrough(),$d=zod.z.object({BaseAttackReward:$.nullish(),BaseRaidReward:$.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Hd).nullish(),HeistGridBonusConfig:gI.nullish(),StageOperations:AI.nullish(),TileLandingMultiplier:Wd.nullish(),EconomyOverride:pI.nullish()}).passthrough(),TI=zod.z.object({Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BoardTemplateID:zod.z.string().nullish(),Buildings:zod.z.array(Hd).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:$d.nullish()}).passthrough(),wI=zod.z.object({AttackCooldownSeconds:zod.z.number().nullish(),RaidCooldownSeconds:zod.z.number().nullish(),MaxRecentTargets:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),LiveOpponentPoolSize:zod.z.number().nullish(),LiveOpponentPoolCacheSeconds:zod.z.number().nullish(),MaxLiveCandidateReads:zod.z.number().nullish(),VictimImmunitySeconds:zod.z.number().nullish()}).passthrough(),kI=zod.z.object({Enabled:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),MaxPerCatchUp:zod.z.number().nullish(),Chance:zod.z.number().nullish(),AttackWeight:zod.z.number().nullish(),RaidWeight:zod.z.number().nullish(),MinBoardStageLevel:zod.z.number().nullish(),RaidLossMultiplier:zod.z.number().nullish()}).passthrough(),zI=zod.z.object({Enabled:zod.z.boolean().nullish(),Sources:zod.z.array(zod.z.string()).nullish(),AdMultiplier:zod.z.number().nullish(),PremiumMultiplier:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),AdDailyLimit:zod.z.number().nullish(),PremiumDailyLimit:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),MinPremiumTier:zod.z.number().nullish()}).passthrough(),Mr=zod.z.object({RollCurrencyID:zod.z.string().nullish(),ShieldCurrencyID:zod.z.string().nullish(),RaidMode:zod.z.string().nullish(),AllowedRollMultipliers:zod.z.array(zod.z.number()).nullish(),BoardTemplatesByID:zod.z.record(zod.z.string(),dI).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),$d).nullish(),StagesByLevel:zod.z.record(zod.z.string(),TI).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:cI.nullish(),Dice:lI.nullish(),Bots:uI.nullish(),Targeting:wI.nullish(),BotRaids:kI.nullish(),RewardBoost:zI.nullish()}).passthrough(),MI=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:u.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),GrandPrize:$.nullish()}).passthrough(),Or=zod.z.object({Board:Mr.nullish(),CommunityChest:MI.nullish()}).passthrough(),Jd=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),he).nullish()}).passthrough(),OI=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:_e.nullish(),TargetBuildingStates:zod.z.array(iI).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:Jd.nullish()}).passthrough(),EI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Xe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:me.nullish(),Multipliers:Kd.nullish(),RunStats:Qd.nullish()}).passthrough(),qI=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(EI).nullish()}).passthrough(),UI=zod.z.object({GroupID:zod.z.string().nullish(),Delta:Q.nullish(),NewProgress:Q.nullish(),MaxProgress:Q.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),Zd=zod.z.object({UsedMultiplier:zod.z.number().nullish(),Steps:zod.z.number().nullish(),DiceValues:zod.z.array(zod.z.number()).nullish(),OldPosition:zod.z.number().nullish(),NewPosition:zod.z.number(),CyclesCompletedDelta:Q.nullish(),LandedTileType:zod.z.string().nullish(),Operation:O.nullish(),Inventory:K.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:OI.nullish(),SpecialModeOffer:qI.nullish(),CommunityChestContribution:UI.nullish()}).passthrough(),Er={Ad:"Ad",Premium:"Premium"},Yd=zod.z.object({BoostID:zod.z.string().nullish(),Source:zod.z.string().nullish(),ExpiresAtUtc:u.nullish(),AdMultiplier:zod.z.number().nullish(),PremiumMultiplier:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),MinPremiumTier:zod.z.number().nullish(),AdRemainingToday:zod.z.number().nullish(),PremiumRemainingToday:zod.z.number().nullish(),BaseEntries:zod.z.array(zt).nullish()}).passthrough(),Xd=zod.z.object({BoostID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Multiplier:zod.z.number().nullish(),AlreadyApplied:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish(),AdRemainingToday:zod.z.number().nullish(),PremiumRemainingToday:zod.z.number().nullish()}).passthrough(),em=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:_t.nullish(),RewardBoost:Yd.nullish()}).passthrough(),Il=zod.z.object({Status:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),FoundSymbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),FoundBonus:$.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(rI).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:_t.nullish(),RaidRewardPreview:Jd.nullish(),RewardBoost:Yd.nullish()}).passthrough(),tm=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish()}).passthrough(),nm=zod.z.object({CreditsConfirmation:Re.nullish(),Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:O.nullish(),Inventory:K.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish()}).passthrough(),sm=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish(),PremiumApplied:zod.z.boolean().nullish()}).passthrough(),LI=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),im=zod.z.object({FinalMultiplier:zod.z.number().nullish(),AdViewsUsed:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),IsEarlyClaim:zod.z.boolean().nullish(),ReachedTierIndex:zod.z.number().nullish(),Operation:O.nullish(),Inventory:K.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(LI).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:$.nullish()}).passthrough(),BI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},rm=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),GI={Active:"Active",Left:"Left",Replaced:"Replaced"},NI=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),_I=zod.z.object({CurrentProgress:Q.nullish(),MaxProgress:Q.nullish()}).passthrough(),VI=zod.z.object({UserID:zod.z.string().nullish(),PublicData:_e.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:Q.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),tc).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:NI.nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),om=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(VI).nullish(),SharedProgress:_I.nullish(),Status:rm.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),FI=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:rm.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:u.nullish()}).passthrough(),jI=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(FI).nullish()}).passthrough(),am=zod.z.object({ServerTimeUtc:u.nullish(),UserState:jI.nullish(),ActiveGroup:om.nullish(),SecondsRemaining:Q.nullish()}),lm=zod.z.object({ServerTimeUtc:u.nullish(),Group:om.nullish(),SecondsRemaining:Q.nullish()}),Pl=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),um=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),He={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",BoardRewardBoostApply:"BoardRewardBoostApply",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var WI=15,HI="GameLoop",cm="BoardDefinition",Rs="InventoryV2",KI="GameLoop",qr=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(HI,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let n=this.ctx.cache.configSection(cm,t);if(n)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n),G(n);let s=this.ctx.authedRequest();if(!s)return l;let i=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return i.ok&&(this.ctx.data.config.patchSection(cm,i.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i.data)),i}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return h("client","stageLevel must be > 0.");let n=this.ctx.authedRequest();if(!n)return l;n.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(n,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return l;let t=false,n=this.ctx.emitter.on("user:stateVersions",({versions:i})=>{i[Rs]!==void 0&&(t=true);}),s;try{s=await this.ctx.api.gameLoop.getUserBoardState(e);}finally{n();}return s.ok&&(this.ctx.data.user.applyBoardState(s.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",s.data),t&&(this.ctx.cache.invalidateState([Rs]),this.ctx.cache.ensureState([Rs]),this.ctx.emitter.emit("user:changedElsewhere",{containers:[Rs]}))),s}async boardLoopRoll(e=1){if(e<1)return h("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${V()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(n);if(s.ok){let i=s.data,o=Ac(new Date,WI);this.ctx.data.user.patchBoardState(p=>{p.Position=i.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(i.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),i.ActionRequired&&i.ActionData?p.Pending={Type:i.ActionRequired,TargetUserID:i.ActionData.TargetUserID,TargetPublicData:i.ActionData.PublicData,TargetBuildingStates:i.ActionData.TargetBuildingStates??void 0,TargetHasShield:i.ActionData.TargetHasShield??void 0,RollMultiplier:i.UsedMultiplier??1,ExpiresAtUtc:o}:i.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:i.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:i.SpecialModeOffer.ModeID??void 0,Choices:i.SpecialModeOffer.Choices??void 0}});}),i.Operation&&this.ctx.data.user.applyResourcesWithDelta(i.Operation,i.Inventory,this.itemDefs),i.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",i);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${V()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(n);if(s.ok){let i=s.data;this.ctx.data.user.clearBoardPending(),i.IsBotTarget&&i.Operation?this.ctx.data.user.applyResourcesWithDelta(i.Operation,i.Inventory,this.itemDefs):!i.IsBotTarget&&i.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(i.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",i);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return h("client","digIndex must be between 0 and 11.");let n=this.ctx.auth.context;if(!n)return l;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${n.userID}_${V()}`},i=await this.ctx.api.gameLoop.boardLoopRaid(s);if(i.ok){let o=i.data;o.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(o.RaidLayout,o.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(o)),this.ctx.emitter.emit("gameLoop:boardRaided",o);}else await this.getUserBoardState();return i}async boardLoopRaidFast(e){if(!e.length)return h("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${V()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(n);if(s.ok){let i=s.data;i.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(i)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",i);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return h("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${V()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(n);if(!s.ok&&s.reason==="server"&&await this.ctx.cache.ensureState([Rs,KI],{force:true}),s.ok){let i=s.data;i.StageComplete?this.ctx.data.user.patchBoardState(o=>{o.StageLevel=(o.StageLevel??1)+1,o.Position=0,o.Pending=null,o.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(i.BuiltIndex,o=>{i.NewLevel!=null&&(o.Level=i.NewLevel),o.IsDamaged=false,i.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),i.Operation&&this.ctx.data.user.applyResourcesWithDelta(i.Operation,i.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",i);}return s}async boardSpecialChoose(e,t,n){if(!e)return h("client","choiceID must not be empty.");let s=this.ctx.auth.context;if(!s)return l;let i={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:n,RelatedEntityID:`special_choose_${s.userID}_${V()}`},o=await this.ctx.api.gameLoop.boardSpecialChoose(i);if(o.ok&&!o.data.CreditsConfirmation){let p=o.data;p.Mode==="Instant"||p.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(g=>{g.ChoiceID=e,g.ChosenMode=p.Mode??"Timed",g.StartedAtUtc=p.StartedAtUtc??null,g.DurationSeconds=p.DurationSeconds??null,g.AdViewsUsed=0;}),p.Operation&&this.ctx.data.user.applyResourcesWithDelta(p.Operation,p.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",p);}return o}async boardSpecialApplyMultiplier(e,t=Er.Ad){let n=this.ctx.auth.context;if(!n)return l;let s=t===Er.Premium,i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_${s?"vip":"ad"}_${n.userID}_${V()}`,...s?{BoostMode:Er.Premium}:{}},o=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(o.ok){let p=o.data;this.ctx.data.user.patchBoardSpecialPending(m=>{m.AdViewsUsed=p.AdViewsUsed??0,m.AccumulatedMultiplier=p.AccumulatedMultiplier??0,p.PremiumApplied&&(m.PremiumApplied=true);}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",p);}return o}async boardRewardBoostApply(e,t){if(!this.ctx.auth.context)return l;if(!e)return h("client","boostID must not be empty.");let s={...this.ctx.buildAuthedBaseRequest(),BoostID:e,BoostMode:t,RelatedEntityID:`boost_${e}_${t}`},i=await this.ctx.api.gameLoop.boardRewardBoostApply(s);if(i.ok){let o=i.data;!o.AlreadyApplied&&o.Operation&&this.ctx.data.user.applyResourcesWithDelta(o.Operation,o.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardRewardBoostApplied",o);}return i}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return l;let n={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${V()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(n);if(s.ok){let i=s.data;this.ctx.data.user.clearBoardPending(),i.Operation&&this.ctx.data.user.applyResourcesWithDelta(i.Operation,i.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",i);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return l;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let n=t.data.Group;n?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:n.GroupID,ActiveRoundIndex:n.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return h("client","milestoneID is required.");if(!this.ctx.auth.context)return l;let n={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(n);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",n.data)),n}async leaveCommunityChest(e){if(!this.ctx.auth.context)return l;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},n=await this.ctx.api.gameLoop.leaveCommunityChest(t);return n.ok&&(n.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",n.data)),n}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var Ur=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,n,s){let i=e.trim();if(!i)return h("client","FunctionName is required.");if(!this.ctx.auth.context)return l;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:i,FunctionParameter:t,RevisionSelection:n,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(o);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var QI={EVM:"EVM",Solana:"Solana"},$I=zod.z.enum(["EVM","Solana"]).catch("EVM"),JI={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},ZI=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),YI={Token:"Token",Nft:"Nft"},pm=zod.z.enum(["Token","Nft"]).catch("Token"),XI={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},eP=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),tP={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},nP=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),sP={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},vl=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),hm={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Lr(r){let e=r?.trim();return e||hm.GameTopUp}var iP={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},dm=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),rP=zod.z.object({ContractAddress:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),mm=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),oP=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:$I.nullish(),ChainID:zod.z.number().nullish(),ChainTicker:zod.z.string().nullish(),RewardPoolAddress:zod.z.string().nullish(),VaultDepositAddress:zod.z.string().nullish(),ChainConfigVersion:zod.z.number().nullish(),RequiredConfirmations:zod.z.number().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:mm.nullish(),NftCollections:zod.z.array(rP).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RpcUrl:zod.z.string().nullish(),GasPrice:zod.z.number().nullish(),NftBridgeAddress:zod.z.string().nullish(),SignatureEpoch:zod.z.number().nullish()}).passthrough(),aP=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:mm.nullish()}).passthrough(),lP=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),uP={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},cP=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),fm=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:se.nullish(),BalanceSource:cP.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),pP=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),hP={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Cs=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),dP=zod.z.object({Mode:Cs.nullish(),TokenGates:zod.z.array(fm).nullish()}).passthrough(),Al=zod.z.object({SystemState:aP.nullish(),Networks:zod.z.record(zod.z.string(),oP).nullish(),AccountSafety:lP.nullish(),WalletLogin:pP.nullish(),PlayAccess:dP.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),mP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:u.nullish(),LastUsedAt:u.nullish(),LinkType:ZI.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),gm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:pm.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:se.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),fP=zod.z.object({Status:eP.nullish(),Tier:nP.nullish(),VerifiedAt:u.nullish(),ExpiresAt:u.nullish(),RejectedAt:u.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),gP=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:se.nullish(),DepositsVolumeUsd:se.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:se.nullish(),WithdrawalsVolumeUsd:se.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),yP=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:se.nullish(),TotalWithdrawalsVolumeUsd:se.nullish(),PerCurrency:zod.z.record(zod.z.string(),gP).nullish()}).passthrough(),RP=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),CP=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),PerCollection:zod.z.record(zod.z.string(),RP).nullish()}).passthrough(),SP=zod.z.object({Tokens:yP.nullish(),Nfts:CP.nullish()}).passthrough(),Tl=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:se.nullish(),MinBalance:se.nullish()}).passthrough(),rn=zod.z.object({Granted:zod.z.boolean(),Mode:Cs.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:u.nullish(),Balances:zod.z.array(Tl).nullish()}).passthrough(),bP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:u.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:u.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(Tl).nullish()}).passthrough(),xP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),ym=zod.z.object({Mode:Cs.nullish(),TokenGates:zod.z.array(fm).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(xP).nullish(),Status:rn.nullish()}).passthrough(),DP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:u.nullish(),LoggedInAt:u.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(Tl).nullish()}).passthrough(),IP=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:u.nullish()}).passthrough(),PP=zod.z.object({Version:zod.z.number().nullish(),Stats:SP.nullish(),LinkedWallets:zod.z.record(zod.z.string(),mP).nullish(),LastWalletLogin:DP.nullish(),PlayAccess:bP.nullish(),PendingWithdrawals:zod.z.array(gm).nullish(),Kyc:fP.nullish(),FirstActivityAt:u.nullish(),LastActivityAt:u.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(IP).nullish()}).passthrough(),vP=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:se,FrozenDelta:se,UpdatedAt:u}).passthrough(),Fn=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),vP).nullish(),PendingAdded:gm.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),AP=zod.z.object({Amount:se,Frozen:se,CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough().transform(r=>r),TP=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:dm.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:se.nullish(),Status:vl.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:se.nullish(),NetPayoutAmount:se.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:u.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:u.nullish(),RefundCheckedAt:u.nullish()}).passthrough(),wP=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:dm.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:se.nullish(),Status:vl.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:u.nullish()}).passthrough(),Rm=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),wl=zod.z.object({TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ContractAddress:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(Rm).nullish(),Signature:zod.z.string().nullish()}).passthrough(),kl=zod.z.object({Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),ProgramID:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(Rm).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Cm=zod.z.object({Blockchain:Al.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),sl).nullish()}).passthrough(),Sm=zod.z.object({State:PP.nullish(),CryptoBalances:zod.z.record(zod.z.string(),AP).nullish()}).passthrough(),bm=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:se.nullish(),AmountUsd:se.nullish(),StateDelta:Fn.nullish()}).passthrough(),xm=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),Dm=zod.z.object({ServerTimeUtc:u.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:se.nullish(),NetAmountNative:se.nullish(),BurnAmountNative:se.nullish(),AmountUsd:se.nullish(),ExpiresAt:u.nullish(),EvmSignature:wl.nullish(),SolanaSignature:kl.nullish(),StateDelta:Fn.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),Im=zod.z.object({ServerTimeUtc:u.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish(),EvmSignature:wl.nullish(),SolanaSignature:kl.nullish(),StateDelta:Fn.nullish(),Inventory:K.nullish()}).passthrough(),Pm=zod.z.object({TokenTransactions:zod.z.array(TP).nullish(),NFTTransactions:zod.z.array(wP).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),zl=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:se.nullish(),AmountUsd:se.nullish(),Target:zod.z.string().nullish()}).passthrough(),vm=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:pm.nullish(),EvmSignature:wl.nullish(),SolanaSignature:kl.nullish()}).passthrough(),Am=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:vl.nullish(),StateDelta:Fn.nullish()}).passthrough(),rt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",DepositToken:"DepositToken",DepositNFT:"DepositNFT",RequestTokenWithdrawal:"RequestTokenWithdrawal",RequestNFTWithdrawal:"RequestNFTWithdrawal",GetTransactionHistory:"GetTransactionHistory",RetryWithdrawal:"RetryWithdrawal",ConfirmWithdrawal:"ConfirmWithdrawal",DonateToDeveloper:"DonateToDeveloper",DonateToUsersPool:"DonateToUsersPool",GetPlayAccess:"GetPlayAccess",ConfirmPlayAccess:"ConfirmPlayAccess"};var kP="Blockchain",Tm="Blockchain:Definitions",Br=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Tm,e);if(t)return G(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let n=this.ctx.authedRequest();if(!n)return l;let s=this.ctx.api.blockchain.getDefinitions(n).then(i=>(i.ok&&(this.ctx.data.config.patchSection(kP,i.data.Blockchain),this.ctx.data.config.patchSection(Tm,i.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",i.data)),i)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(n);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,n,s,i){if(!e)return h("client","CurrencyID is required.");if(!t)return h("client","NetworkID is required.");if(!n)return h("client","WalletAddress is required.");if(!s)return h("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return l;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=n,o.Amount=s,o.Category=Lr(i);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,n,s,i,o,p){if(!e)return h("client","ItemID is required.");if(!t)return h("client","NetworkID is required.");if(!n)return h("client","WalletAddress is required.");if(!s)return h("client","Amount is required.");let m=this.ctx.authedRequest();if(!m)return l;m.ItemID=e,m.NetworkID=t,m.WalletAddress=n,m.Amount=s,m.Category=Lr(i),o!==void 0&&(m.Level=o),p&&(m.ItemInstanceID=p);let g=await this.ctx.api.blockchain.requestNFTWithdrawal(m);return g.ok&&(this.ctx.data.user.applyBlockchainStateDelta(g.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(g.data.Resources,g.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",g.data)),g}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return l;t.Amount=String(e);let n=await this.ctx.api.blockchain.getTransactionHistory(t);return n.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",n.data),n}async retryWithdrawal(e){if(!e)return h("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.TitleTransactionID=e;let n=await this.ctx.api.blockchain.retryWithdrawal(t);return n.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",n.data),n}async confirmWithdrawal(e,t){if(!e)return h("client","TitleTransactionID is required.");if(!t)return h("client","On-chain TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.TitleTransactionID=e,n.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(n);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(n);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return h("client","NetworkID is required.");if(!t)return h("client","TransactionHash is required.");let n=this.ctx.authedRequest();if(!n)return l;n.NetworkID=e,n.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(n);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.NetworkID=e);let n=await this.ctx.api.blockchain.confirmPlayAccess(t);return n.ok&&this.ctx.auth.setPlayAccess(n.data),n}};var zP={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Ml=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),MP={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Ol=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),OP={Burn:"Burn",Ledger:"Ledger"},EP=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Nr={Item:"Item",VirtualCurrency:"VirtualCurrency"},El=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),qP=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:Q.nullish()}).passthrough(),_r=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(ms).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),ql=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:Q.nullish(),Sink:EP.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),qP).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),UP=zod.z.object({AllowedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedItemIDs:zod.z.array(zod.z.string()).nullish(),AllowUnstackableWithState:zod.z.boolean().nullish(),AllowedCurrencyIDs:zod.z.array(zod.z.string()).nullish(),DeniedCurrencyIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),LP=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:ve.nullish(),BuyLimits:ve.nullish(),ListingFeeOptions:me.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),BP=zod.z.object({Enabled:zod.z.boolean().nullish(),MinDurationHours:zod.z.number().nullish(),MaxDurationHours:zod.z.number().nullish(),AntiSnipeWindowSeconds:zod.z.number().nullish(),AntiSnipeExtensionSeconds:zod.z.number().nullish(),MaxAntiSnipeExtensions:zod.z.number().nullish(),MinBidStepPercent:zod.z.number().nullish(),MinBidStepAbsolute:Q.nullish(),BidLimits:ve.nullish()}).passthrough(),GP=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:ve.nullish(),FillLimits:ve.nullish()}).passthrough(),NP=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:ve.nullish()}).passthrough(),_P=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Ul=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:te.nullish(),Schedule:Se.nullish(),PricePolicy:_r.nullish(),Commission:ql.nullish(),Tradability:UP.nullish(),Listings:LP.nullish(),Auctions:BP.nullish(),BuyOrders:GP.nullish(),DirectTrades:NP.nullish(),Matching:_P.nullish()}).passthrough(),wm=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:Q.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:u.nullish()}).passthrough(),VP=zod.z.object({BidAxisType:zn.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:Q.nullish(),CurrentBid:Q.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(wm).nullish()}).passthrough(),Gr=zod.z.object({LastAt:u.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),FP=zod.z.object({Create:Gr.nullish(),Buy:Gr.nullish(),Sell:Gr.nullish(),Bid:Gr.nullish()}).passthrough(),jP=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),WP=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),EquippedSlot:jP.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Ht=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Ml.nullish(),Status:Ol.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:_e.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:El.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:Q.nullish(),GoodsInstances:zod.z.array(WP).nullish(),Price:he.nullish(),Auction:VP.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),HP=zod.z.object({GoodsType:El.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(Ml,Q).nullish()}).passthrough(),km=zod.z.object({Definitions:Ul.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),Ll=zod.z.object({Offers:zod.z.array(Ht).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),zm=zod.z.object({Groups:zod.z.array(HP).nullish()}).passthrough(),Mm=zod.z.object({Offer:Ht.nullish()}).passthrough(),St=zod.z.object({OfferID:zod.z.string().nullish(),Status:Ol.nullish(),Settlement:_t.nullish(),Resources:O.nullish(),CommissionTaken:he.nullish(),HeldPayout:Ct.nullish()}).passthrough(),Ss=zod.z.object({OfferID:zod.z.string().nullish(),Offer:Ht.nullish(),Resources:O.nullish(),Matched:zod.z.boolean().nullish(),Settlement:St.nullish()}).passthrough(),Om=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:Q.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:O.nullish()}).passthrough(),Vr=zod.z.object({MyOffers:zod.z.array(Ht).nullish(),MyBids:zod.z.array(Ht).nullish(),MyBuyOrders:zod.z.array(Ht).nullish(),IncomingTrades:zod.z.array(Ht).nullish(),OutgoingTrades:zod.z.array(Ht).nullish(),Claimables:zod.z.array(Ht).nullish(),DrainedRefunds:zod.z.array(wm).nullish(),Limits:FP.nullish(),PendingPayouts:zod.z.array(Ct).nullish(),ReleasedPayouts:zod.z.array(Ct).nullish(),VoidedPayouts:zod.z.array(Ct).nullish(),PayoutOperations:zod.z.array(O).nullish()}).passthrough(),KP=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Ml.nullish(),FinalStatus:Ol.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:El.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:Q.nullish(),PricePaid:he.nullish(),CommissionTaken:he.nullish(),CompletedAt:u.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),Em=zod.z.object({Entries:zod.z.array(KP).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Ge={GetDefinitions:"GetDefinitions",GetGroupedOffers:"GetGroupedOffers",GetOffersByItem:"GetOffersByItem",GetOffer:"GetOffer",GetBuyOrders:"GetBuyOrders",GetMyState:"GetMyState",GetHistory:"GetHistory",CreateListing:"CreateListing",CancelListing:"CancelListing",Buy:"Buy",MarketBuy:"MarketBuy",MarketSell:"MarketSell",CreateAuction:"CreateAuction",PlaceBid:"PlaceBid",ClaimAuction:"ClaimAuction",CreateBuyOrder:"CreateBuyOrder",CancelBuyOrder:"CancelBuyOrder",FillBuyOrder:"FillBuyOrder",CreateDirectTrade:"CreateDirectTrade",RespondDirectTrade:"RespondDirectTrade",CancelDirectTrade:"CancelDirectTrade",ClaimBack:"ClaimBack"};var QP="Marketplace",qm={key:"marketplace.myState",login:"MarketplaceMyState",ttlMs:6e4,dependsOn:["Marketplace"],invalidateOn:["marketplace:listingCreated","marketplace:listingCancelled","marketplace:bought","marketplace:marketBought","marketplace:marketSold","marketplace:auctionCreated","marketplace:bidPlaced","marketplace:auctionClaimed","marketplace:buyOrderCreated","marketplace:buyOrderCancelled","marketplace:buyOrderFilled","marketplace:directTradeCreated","marketplace:directTradeResponded","marketplace:directTradeCancelled","marketplace:claimedBack"]},Fr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(qm,{schema:Vr,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(QP,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,n,s=20){if(!e)return h("client","ItemID is required.");let i=this.ctx.authedRequest();if(!i)return l;i.ItemID=e,i.OfferTypeFilter=t,i.ContinuationToken=n,i.PageSize=s;let o=await this.ctx.api.marketplace.getOffersByItem(i);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.getOffer(t);return n.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",n.data),n}async getBuyOrders(e,t,n=20){let s=this.ctx.authedRequest();if(!s)return l;s.ItemID=e,s.ContinuationToken=t,s.PageSize=n;let i=await this.ctx.api.marketplace.getBuyOrders(s);return i.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",i.data),i}getMyState(e,t){return this.ctx.cache.read(qm,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return l;e&&(t.MyBidsFilter=e);let n=await this.ctx.api.marketplace.getMyState(t);if(n.ok){for(let s of n.data.PayoutOperations??[])this.ctx.data.user.applyResourceOperation(s,this.ctx.data.config.itemDefinitions);this.applyMyState(n.data);}return n}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,n){let s=this.ctx.authedRequest();if(!s)return l;n&&(s.HistoryFilter=n),s.ContinuationToken=e,s.PageSize=t;let i=await this.ctx.api.marketplace.getHistory(s);return i.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",i.data),i}async createListing(e,t,n,s,i,o,p){if(!e)return h("client","ItemID is required.");if(!t)return h("client","CatalogID is required.");if(!s)return h("client","PriceBundle is required.");let m=this.ctx.authedRequest();if(!m)return l;m.ItemID=e,m.CatalogID=t,m.GoodsAmount=n,m.PriceBundle=s,m.DurationHours=i,m.ItemInstanceIDs=o,m.SelectedOptionID=p;let g=await this.ctx.api.marketplace.createListing(m);return this.applyCreateOfferResult(g,"marketplace:listingCreated"),g}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.buy(t);return n.ok&&(this.applyDualPartySettlement(n.data.Settlement),this.ctx.emitter.emit("marketplace:bought",n.data)),n}async marketBuy(e,t,n){if(!e||e<=0)return h("client","GoodsAmount must be positive.");if(!t)return h("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return l;let i=this.applyGoodsSelector(s,n);if(i)return i;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,n){if(!e||e<=0)return h("client","GoodsAmount must be positive.");if(!t)return h("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return l;let i=this.applyGoodsSelector(s,n);if(i)return i;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,n,s,i,o,p={}){if(!e)return h("client","ItemID is required.");if(!t)return h("client","CatalogID is required.");let m=this.ctx.authedRequest();if(!m)return l;m.ItemID=e,m.CatalogID=t,m.GoodsAmount=n,m.BidAxisType=s,m.BidCurrencyID=p.bidCurrencyID,m.BidCatalogID=p.bidCatalogID,m.BidItemID=p.bidItemID,m.StartingBid=i,m.DurationHours=o,m.ItemInstanceIDs=p.itemInstanceIDs,m.SelectedOptionID=p.selectedOptionID;let g=await this.ctx.api.marketplace.createAuction(m);return this.applyCreateOfferResult(g,"marketplace:auctionCreated"),g}async placeBid(e,t){if(!e)return h("client","OfferID is required.");if(!t||t<=0)return h("client","BidAmount must be positive.");let n=this.ctx.authedRequest();if(!n)return l;n.OfferID=e,n.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(n);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.claimAuction(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",n.data)),n}async createBuyOrder(e,t,n,s,i){if(!e)return h("client","ItemID is required.");if(!t)return h("client","CatalogID is required.");if(!s)return h("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return l;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=n,o.PriceBundle=s,o.DurationHours=i;let p=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return h("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.fillBuyOrder(t);return n.ok&&(this.applyDualPartySettlement(n.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",n.data)),n}async createDirectTrade(e,t,n,s,i){if(!e)return h("client","TargetUserID is required.");if(!t)return h("client","CatalogID is required.");if(!n)return h("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return l;o.TargetUserID=e,o.CatalogID=t,o.ItemID=n,o.ItemInstanceIDs=s,o.RequestedBundle=i;let p=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return h("client","OfferID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.OfferID=e,n.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(n);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return l;t.OfferID=e;let n=await this.ctx.api.marketplace.claimBack(t);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",n.data)),n}async cancelOffer(e,t,n){if(!e)return h("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return l;s.OfferID=e;let i=await t(s);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(n,i.data)),i}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=Nr.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Nr.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):h("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let n=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,n):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,n);}};var jr=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return h("client","RoomName is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomName=e,n.Topology=t.topology,n.ChatMode=t.chatMode,n.MaxPlayers=t.maxPlayers,n.Visibility=t.visibility,n.JoinCode=t.joinCode,n.Mode=t.mode,n.Voice=t.voice;let s=await this.ctx.api.multiplayer.createRoom(n);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return h("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(n);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return h("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(n,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return h("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.RoomID=e;let n=await this.ctx.api.multiplayer.claimHost(t);return n.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",n.data),n}async kickMember(e,t,n=false){if(!e)return h("client","RoomID is required.");if(!t)return h("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return l;s.RoomID=e,s.TargetUserID=t,s.Ban=n;let i=await this.ctx.api.multiplayer.kickMember(s);return i.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",i.data),i}async unbanMember(e,t){if(!e)return h("client","RoomID is required.");if(!t)return h("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(n);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let n=this.ctx.authedRequest();if(!n)return l;n.Page=e,n.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(n);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return h("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.RoomID=e;let n=await this.ctx.api.multiplayer.getRoom(t);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",n.data),n}async closeRoom(e){if(!e)return h("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return l;t.RoomID=e;let n=await this.ctx.api.multiplayer.closeRoom(t);return n.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",n.data),n}async poll(e,t){if(!e)return h("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(n);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,n,s){if(!e)return h("client","RoomID is required.");if(!t)return h("client","TargetUserID is required.");if(!n)return h("client","SignalKind is required.");let i=this.ctx.authedRequest();if(!i)return l;i.RoomID=e,i.TargetUserID=t,i.SignalKind=n,i.Payload=s;let o=await this.ctx.api.multiplayer.sendSignal(i);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return h("client","RoomID is required.");if(!t)return h("client","ChatText is required.");let n=this.ctx.authedRequest();if(!n)return l;n.RoomID=e,n.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(n);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,n){if(!e)return h("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return l;s.RoomID=e,s.Ready=t,s.MemberState=n;let i=await this.ctx.api.multiplayer.setMemberState(s);return i.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",i.data),i}};var Um=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Wr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return l;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.ParentContentID=e.parentContentID,t.OfficialOnly=e.officialOnly,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):l}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return h("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):l}async getCreatorProfile(e,t,n){if(!e)return h("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=n,this.ctx.api.workshop.getCreatorProfile(s)):l}async publish(e){if(!e.files||e.files.length===0)return h("client","At least one file is required.");let t=new Map,n=e.files.map((m,g)=>{if("sourceAssetUrl"in m)return {Role:m.role,ContentType:m.contentType,SourceAssetUrl:m.sourceAssetUrl};let j=Lm(m.data,m.contentType);return t.set(g,j),{Role:m.role,ContentType:m.contentType,Size:j.size}}),s=e.thumbnail?Lm(e.thumbnail.data,e.thumbnail.contentType):null,i=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,AsOfficial:e.asOfficial,Files:n,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!i.ok)return i;let o=i.data.Uploads??[];for(let m=0;m<o.length;m++){let g=o[m];if(!g||g.ServerCopy||!g.Url)continue;let j=t.get(m);if(!j)return h("client",`No bytes for file #${m+1}.`);let pe=await this.putBytes(g.Url,j,g.ContentType??j.type);if(!pe.ok)return pe}let p=i.data.ThumbnailUpload;if(p?.Url&&s){let m=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!m.ok)return m}return this.ctx.credits.pay(m=>this.publishUploaded({CreditsConfirmationID:m,ContentID:i.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID,AsOfficial:e.asOfficial}),e.credits)}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):l}async publishUploaded(e){if(!e.ContentID)return h("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return l;let n=await this.ctx.api.workshop.publish({...t,...e});return n.ok&&!n.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",n.data)),n}async updateContent(e,t){let n=this.contentRequest(e);if("ok"in n)return n;n.Title=t.title,n.Description=t.description,n.Tags=t.tags,n.Metadata=t.metadata,n.Visibility=t.visibility,n.Access=t.access;let s=await this.ctx.api.workshop.updateContent(n);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let n=await this.ctx.api.workshop.unpublish(t);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async getMyContent(e,t,n){let s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=n,this.ctx.api.workshop.getMyContent(s)):l}async acquire(e,t){let n=this.contentRequest(e);if("ok"in n)return n;n.OptionID=t?.OptionID??void 0,n.ExpectedPrice=t?.Price??void 0;let s=await this.ctx.api.workshop.acquire(n);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let n=[];for(let s of t.data.Files??[])if(s.Url)try{let i=await this.ctx.fetchImpl(s.Url);if(!i.ok)return h("connection",`Download failed (HTTP ${i.status}).`);n.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await i.arrayBuffer()});}catch(i){return h("connection",`Download failed: ${i instanceof Error?i.message:String(i)}${Um}`)}return G({download:t.data,files:n})}async getMyLicenses(e,t){let n=this.ctx.authedRequest();return n?(n.ContinuationToken=e,n.PageSize=t,this.ctx.api.workshop.getMyLicenses(n)):l}async getMyFavorites(e,t){let n=this.ctx.authedRequest();return n?(n.ContinuationToken=e,n.PageSize=t,this.ctx.api.workshop.getMyFavorites(n)):l}async putBytes(e,t,n){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":n},body:t});return s.ok?G(!0):h("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return h("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${Um}`)}}contentRequest(e){if(!e)return h("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):l}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let n=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,n):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,n);}};function Lm(r,e){return r instanceof Blob?r:typeof r=="string"?new Blob([new TextEncoder().encode(r)],{type:e}):r instanceof Uint8Array?new Blob([r.slice().buffer],{type:e}):new Blob([r],{type:e})}var $P={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},JP=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),ZP={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Bm=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),YP={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Gm=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),XP={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},ev=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),tv={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},nv=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),sv={Count:"Count",Sum:"Sum"},iv=zod.z.enum(["Count","Sum"]).catch("Count"),rv={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},ov=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),av={Strict:"Strict",Loose:"Loose"},lv=zod.z.enum(["Strict","Loose"]).catch("Strict"),uv=zod.z.object({Kind:nv,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),cv=zod.z.object({Type:Bm,ItemType:Bm.nullish(),Ref:uv.nullish(),Required:zod.z.boolean().optional(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),MaxItems:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish(),Unique:zod.z.boolean().optional(),UniqueIgnoreCase:zod.z.boolean().optional(),Indexed:zod.z.boolean().optional(),Visibility:Gm.optional(),ClientWritable:zod.z.boolean().nullish(),Immutable:zod.z.boolean().optional(),Description:zod.z.string().nullish(),AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxFileBytes:zod.z.number().nullish()}),pv=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Hr=zod.z.object({Mode:ev,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),hv=zod.z.object({Read:zod.z.array(Hr).nullish(),Create:zod.z.array(Hr).nullish(),Update:zod.z.array(Hr).nullish(),Delete:zod.z.array(Hr).nullish()}),Bl=zod.z.object({Cost:he.nullish(),Grant:he.nullish()}),dv=zod.z.object({ID:zod.z.string(),SortKey:zod.z.string(),PartitionField:zod.z.string().nullish(),PageSize:zod.z.number().optional(),MaxItems:zod.z.number().optional(),PublishItems:zod.z.boolean().optional()}),mv=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Namespace:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Enabled:zod.z.boolean().nullish(),Kind:JP,Mode:lv.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),cv).nullish(),SortKeys:zod.z.array(pv).nullish(),Access:hv.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:ov.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:iv,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:Gm.optional()})).nullish(),Economy:zod.z.object({OnCreate:Bl.nullish(),OnUpdate:Bl.nullish(),OnDelete:Bl.nullish()}).nullish(),WriteGate:te.nullish(),PublicViews:zod.z.array(dv).nullish(),AnonymousSearch:zod.z.boolean().nullish(),Integrations:zod.z.object({QuestMetricOnCreate:zod.z.string().nullish(),QuestMetricOnUpdate:zod.z.string().nullish(),QuestMetricOnDelete:zod.z.string().nullish(),AnalyticsEventOnCreate:zod.z.string().nullish(),AnalyticsEventOnUpdate:zod.z.string().nullish(),AnalyticsEventOnDelete:zod.z.string().nullish(),TriggerOnCreate:zod.z.string().nullish(),TriggerOnUpdate:zod.z.string().nullish(),TriggerOnDelete:zod.z.string().nullish()}).nullish(),Moderation:zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish()}).nullish()}),Nm=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),mv).default({})}),fv=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),_m=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),jn=zod.z.object({Collection:zod.z.string(),ItemID:zod.z.string(),OwnerUserID:zod.z.string().nullish(),Data:zod.z.record(zod.z.string(),zod.z.unknown()).default({}),Version:zod.z.number(),CreatedAt:zod.z.string(),UpdatedAt:zod.z.string(),ExpireAt:zod.z.string().nullish(),Expanded:zod.z.record(zod.z.string(),zod.z.unknown()).nullish(),Files:zod.z.record(zod.z.string(),fv).nullish()}),Gl=zod.z.object({Item:jn}),Vm=zod.z.object({Items:zod.z.array(jn).default([]),Missing:zod.z.array(zod.z.string()).default([])}),Nl=zod.z.object({Items:zod.z.array(jn).default([]),NextCursor:zod.z.string().nullish()}),Fm=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),_l=zod.z.object({Item:jn,AlreadyExists:zod.z.boolean().optional(),Economy:O.nullish()}),jm=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:O.nullish()}),Wm=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),Hm=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:jn.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),Km=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),Qm=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),$m=zod.z.object({Version:zod.z.string(),Collection:zod.z.string(),View:zod.z.string(),SortKey:zod.z.string().nullish(),PageSize:zod.z.number(),UpdatedAt:zod.z.string(),BaseUrl:zod.z.string(),Partitions:zod.z.record(zod.z.string(),zod.z.object({Segment:zod.z.string(),Pages:zod.z.number(),Total:zod.z.number()})).default({})}),Jm=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(jn).default([])}),gv={GetDefinitions:"GetDefinitions",Get:"Get",GetMany:"GetMany",Query:"Query",Count:"Count",Create:"Create",Update:"Update",Delete:"Delete",Batch:"Batch",GetCounter:"GetCounter",GetMyRoles:"GetMyRoles",BeginFileUpload:"BeginFileUpload"};var yv=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Xm=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Fl=100,Zm=25,Ym=100;function Rv(r,e,t){return {Field:r,Op:e,Value:t}}var Kr=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(l)}get(e,t,n={}){let s=dt(e)??bs(t);return s?Promise.resolve(s):this.call(i=>this.ctx.api.dataCollections.get({...i,Collection:e,ItemID:t,Expand:n.expand}))}getMany(e,t,n={}){let s=dt(e);if(s)return Promise.resolve(s);let i=[...new Set(t.filter(o=>Xm.test(o)))];return i.length?i.length>Ym?Promise.resolve(h("client",`At most ${Ym} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:i,Expand:n.expand})):Promise.resolve(h("client","At least one valid item id is required."))}query(e,t={},n={}){let s=dt(e)??Vl(t);return s?Promise.resolve(s):this.call(i=>this.ctx.api.dataCollections.query({...i,Collection:e,Query:t,Expand:n.expand}))}async queryAll(e,t={},n={}){let s=Math.max(1,n.maxItems??500),i=[],o=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:o,Limit:t.Limit??Fl},n);if(!p.ok)return p;if(i.push(...p.data.Items),o=p.data.NextCursor??void 0,!o||i.length>=s)return G(i.slice(0,s))}}count(e,t={}){let n=dt(e)??Vl(t);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,n={}){let s=dt(e)??(n.itemID?bs(n.itemID):null);return s?Promise.resolve(s):this.call(i=>this.ctx.api.dataCollections.create({...i,Collection:e,ItemID:n.itemID,Data:t}))}update(e,t,n,s={}){let i=dt(e)??bs(t);return i?Promise.resolve(i):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:n,ExpectedVersion:s.expectedVersion}))}set(e,t,n,s={}){return this.update(e,t,{Set:n},s)}increment(e,t,n,s=1){return this.update(e,t,{Inc:{[n]:s}})}delete(e,t,n={}){let s=dt(e)??bs(t);return s?Promise.resolve(s):this.call(i=>this.ctx.api.dataCollections.delete({...i,Collection:e,ItemID:t,ExpectedVersion:n.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(h("client","Operations are empty."));if(e.length>Zm)return Promise.resolve(h("client",`At most ${Zm} operations per batch.`));let t=e.map(n=>dt(n.Collection)).find(n=>n!=null);return t?Promise.resolve(t):this.call(n=>this.ctx.api.dataCollections.batch({...n,Operations:e}))}getCounter(e,t,n){let s=dt(e);return s?Promise.resolve(s):this.call(i=>this.ctx.api.dataCollections.getCounter({...i,Collection:e,CounterID:t,Group:n}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,n,s){let i=dt(e);return i?Promise.resolve(i):t?s>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:n,FileSize:s})):Promise.resolve(h("client","File size must be positive.")):Promise.resolve(h("client","Field is required."))}async uploadFile(e,t,n,s={}){let i=s.contentType||n.type||"application/octet-stream",o=await this.beginFileUpload(e,t,i,n.size);if(!o.ok)return o;let p=await this.putBytes(o.data.UploadUrl,n,o.data.ContentType||i);return p.ok?o:p}async getPublicViews(e){let t=dt(e);if(t)return t;let n=this.publicViews.get(e);if(n)return G(n);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,n={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let i=s.data.Views[t];if(!i)return h("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(i,$m);if(!o.ok)return o;let p=o.data.Partitions[n.partition??""],m=Math.max(1,n.page??1);if(!p||m>p.Pages)return G({pointer:o.data,page:{Page:m,HasMore:false,Items:[]}});let g=await this.fetchJson(`${o.data.BaseUrl}${p.Segment}/page-${m}.json`,Jm);return g.ok?G({pointer:o.data,page:g.data}):g}getPublic(e,t){let n=dt(e)??bs(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let n=dt(e)??Vl(t);return n?Promise.resolve(n):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(l)}async putBytes(e,t,n){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":n},body:t});return s.ok?G(!0):h("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return h("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let n;try{n=await this.ctx.fetchImpl(e);}catch{return h("connection","Internet Connection Error")}if(!n.ok)return h("server",`CDN answered ${n.status}.`);let s;try{s=await n.json();}catch{return h("server","CDN answer is not JSON.")}let i=t.safeParse(s);return i.success?G(i.data):h("server","CDN answer has an unexpected shape.")}};function dt(r){return yv.test(r??"")?null:h("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function bs(r){return Xm.test(r??"")?null:h("client",`Item id '${r}' is invalid.`)}function Vl(r){return r.Limit!=null&&(r.Limit<1||r.Limit>Fl)?h("client",`Limit must be 1..${Fl}.`):(r.Where?.length??0)>8?h("client","At most 8 filters per query."):null}var jl={Open:"Open",Declared:"Declared"},Cv=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),Sv=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),ef=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Cv).nullish(),Dimensions:zod.z.array(Sv).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),on={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Lt={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Qr=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,bv={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},xv=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),tf=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(xv).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Wl={LogEvents:"LogEvents"};function nf(r,e=0){let t=r??"",n=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(n){let p=n[1]??"iPhone";return {osName:"iOS",osVersion:(n[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let p=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let i=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(i)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(i[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let o=/\bWindows NT (\d+\.\d+)/.exec(t);return o?{osName:"Windows",osVersion:o[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function sf(r){let e=typeof navigator>"u"?void 0:navigator,t=nf(e?.userAgent??"",e?.maxTouchPoints??0),n={};r.appVersion&&(n.AppVersion=r.appVersion),t.osName&&(n.OsName=t.osName),t.osVersion&&(n.OsVersion=t.osVersion),t.deviceCategory&&(n.DeviceCategory=t.deviceCategory),t.deviceModel&&(n.DeviceModel=t.deviceModel);let s=r.locale||e?.language;return s&&(n.Language=s),n}var Dv=25,Iv=3e4,rf=1800*1e3,of=500,Pv=5,vv=1e3,Av=3600*1e3,af="idos_analytics_queue",Hl="idos_analytics_pending",Kl="idos_analytics_opt_out",lf="idos_analytics_first_open",uf="idos_analytics_last_activity",cf="idos_analytics_last_context",pf="idos_analytics_owner",$r=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;stopVisibility=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,n){return typeof e!="string"||!Qr.test(e)?h("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Tv(e)?h("client",`Event name "${e}" uses a reserved prefix (${Lt.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,n,false))}logScreenView(e,t){if(!e)return h("client","screenName is required.");let n={screen_name:e};return t&&(n.screen_class=t),this.enqueue(on.ScreenView,n,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return G(null);if(this.config()?.Enabled===false)return this.clear(),G(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return G(null);this.pending={BatchID:V(),Events:this.queue.splice(0,Lt.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return l;let t=this.pending;this.flushing=true;try{let n=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return n.ok?(this.pending=null,n.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),n.data.Dropped&&n.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",n.data.Dropped),this.ctx.emitter.emit("analytics:flushed",n.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),n):(n.reason!=="throttled"&&t.Attempts++,(n.reason==="validation"||t.Attempts>=Pv)&&(this.pending=null),this.persist(),n)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Kl);return}this.write(Kl,"1"),this.clear();}get isEnabled(){return this.read(Kl)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(pf);e&&t&&t!==e&&this.clear(),e&&this.write(pf,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Iv),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide),this.beginAutomatic(),this.flush();}async stop(){this.started&&(this.started=false,this.automaticDone=false,this.timer&&clearInterval(this.timer),this.drainTimer&&clearTimeout(this.drainTimer),this.timer=null,this.drainTimer=null,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null,this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),await this.flush());}beginAutomatic(){if(this.automaticDone||!this.started)return;if(this.config()?.Enabled!==true){this.stopWaitingForConfig??=this.ctx.emitter.on("title:publicConfigurationReceived",()=>this.beginAutomatic());return}this.automaticDone=true,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null;let e=Number(this.read(uf)??"0");this.read(lf)||(this.write(lf,new Date().toISOString()),this.enqueue(on.FirstOpen,void 0,void 0,true));let t=this.clientContext(),n=this.readJson(cf);n?.AppVersion&&t.AppVersion&&n.AppVersion!==t.AppVersion&&this.enqueue(on.AppUpdate,{previous_app_version:n.AppVersion},void 0,true),n?.OsVersion&&t.OsVersion&&n.OsVersion!==t.OsVersion&&this.enqueue(on.OsUpdate,{previous_os_version:n.OsVersion},void 0,true),this.writeJson(cf,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=rf)&&this.enqueue(on.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=e=>{if(!e){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=rf&&this.enqueue(on.SessionStart,void 0,void 0,true),this.hiddenAt=null;};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,n,s){if(!this.isEnabled||this.disabledByServer)return G(null);let i=this.config();if(i?.Enabled===false)return G(null);if(s&&i?.AutomaticEvents===false)return G(null);if(i?.Events?.[e]?.Blocked)return h("client",`Event "${e}" is blocked by the title.`);if(!s&&i?.EventNaming?.toLowerCase()===jl.Declared.toLowerCase()&&!i.Events?.[e])return h("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(n!==void 0&&!Number.isFinite(n))return h("client","value must be a finite number.");let o=wv(t);if(o.error)return h("client",o.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(p.Params=o.params),n!==void 0&&(p.Value=n),this.queue.push(p),this.queue.length>of&&this.queue.splice(0,this.queue.length-of),this.touch(),this.persist(),this.started&&this.queue.length>=Dv&&this.flush(),G(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},vv));}dropStale(){let e=Date.now()-(Lt.maxEventAgeMs-Av);this.queue=this.queue.filter(t=>{let n=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(n)||n>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=sf({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(af);Array.isArray(e)&&(this.queue=e.filter(n=>typeof n?.Name=="string").concat(this.queue));let t=this.readJson(Hl);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(af,this.queue),this.pending?this.writeJson(Hl,this.pending):this.remove(Hl);}touch(){this.write(uf,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.host.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.host.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.host.storage.remove(this.key(e));}catch{}}readJson(e){let t=this.read(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}writeJson(e,t){this.write(e,JSON.stringify(t));}};function Tv(r){let e=r.toLowerCase();return Lt.reservedPrefixes.some(t=>e.startsWith(t))}function wv(r){if(!r)return {};let e=Object.keys(r);if(e.length===0)return {};if(e.length>Lt.maxParams)return {error:`Too many parameters: ${e.length}, max ${Lt.maxParams}.`};let t={};for(let n of e){if(!Qr.test(n))return {error:`Invalid parameter name "${n}".`};let s=r[n];typeof s=="string"?t[n]=s.length>Lt.maxStringValueLength?s.slice(0,Lt.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[n]=s):typeof s=="boolean"&&(t[n]=s);}return {params:t}}var kv="idos_experiments",Jr=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return l;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let n=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),n.length>0&&this.ctx.emitter.emit("experiments:changed",n);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,n){let s=this.getParams(e)[t];if(s===void 0)return n;if(typeof n=="number"){let i=Number(s);return s.trim()!==""&&Number.isFinite(i)?i:n}if(typeof n=="boolean"){let i=s.trim().toLowerCase();return i==="true"||i==="1"?true:i==="false"||i==="0"?false:n}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let n=[];for(let[s,i]of t){let o=this.views.get(s);(!o||o.VariantID!==i.VariantID||o.Status!==i.Status)&&n.push(i);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,n}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.host.storage.getString(this.key());if(!t)return;let n=JSON.parse(t);n?.UserID===e&&n.Data&&this.apply(n.Data);}catch{}}save(e,t){try{let n={UserID:e,Data:t};this.ctx.host.storage.setString(this.key(),JSON.stringify(n));}catch{}}key(){return `${kv}:${this.ctx.settings.titleID}`}};function an(r,e,t,n){let i=`api/v2/${r&&r.length>0?r:"0"}/Client/${e}/${t}`;return n==null?i:`${i}/${n}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return an(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,n,s){return this.ctx.transport.post(this.endpoint(e,t),t,n,{...s,ticket:t.ClientSessionTicket})}};var Zr=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Wl.LogEvents,e,tf,{silent:true})}};var zv=zod.z.object({VariantID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Weight:zod.z.number().nullish(),IsControl:zod.z.boolean().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Mv={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Ov=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),Ev=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:Se.nullish(),Gate:te.nullish(),Variants:zod.z.array(zv).nullish(),Salt:zod.z.string().nullish(),LayerID:zod.z.string().nullish(),StickyAssignment:zod.z.boolean().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Goals:zod.z.array(Ov).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),hf=zod.z.object({Experiments:zod.z.record(zod.z.string(),Ev).nullish()}).passthrough(),qv={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Uv=zod.z.object({ExperimentID:zod.z.string().nullish(),VariantID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),df=zod.z.object({Experiments:zod.z.array(Uv).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),Ql={GetExperiments:"GetExperiments"};var Yr=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Ql.GetExperiments,e,df)}};var Lv={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},mf=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Bv=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),ff=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),Bv).nullish(),MissingKeyMode:mf.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),Gv=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),gf=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:Gv.nullish()}).passthrough(),Xr={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Nv=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),yf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:mf.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(Nv).nullish()}).passthrough(),Rf=zod.z.object({RequestedLocale:zod.z.string().nullish(),Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),NotModified:zod.z.boolean().nullish(),Entries:zod.z.record(zod.z.string(),zod.z.string()).nullish(),FallbackLocale:zod.z.string().nullish(),FallbackVersion:zod.z.number().nullish()}).passthrough();var xs=zod.z.object({TitleConfigVersion:zod.z.string().nullish(),TitleConfigUrl:zod.z.string().nullish(),User:zod.z.unknown().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish(),Localization:gf.nullish(),Views:zod.z.array(zod.z.object({Name:zod.z.string(),Key:zod.z.string().nullish(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().nullish()}).passthrough()).nullish(),PeerPayouts:Mh.nullish()}).passthrough().transform(r=>r),Cf=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(r=>r),Sf=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),User:zod.z.unknown().nullish()}).passthrough().transform(r=>r),bf=zod.z.object({}).passthrough().transform(r=>r),xf=zod.z.object({}).passthrough().transform(r=>r),Df=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:u.nullish(),LastActiveAt:u.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),If=zod.z.object({Username:zod.z.string()}),bt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Pf=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:u.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,PlayAccess:rn.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:u.nullish(),ClientState:xs.nullish()}),vf=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,RefreshToken:zod.z.string(),RefreshTokenExpiration:u.nullish(),PlayAccess:rn.nullish()}),_v=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Af=zod.z.object({Google:zod.z.object({Enabled:zod.z.boolean().nullish(),WebClientID:zod.z.string().nullish(),PlatformFallback:zod.z.boolean().nullish(),AndroidClientID:zod.z.string().nullish(),IosClientID:zod.z.string().nullish(),DesktopClientID:zod.z.string().nullish()}).passthrough().nullish(),Apple:zod.z.object({Enabled:zod.z.boolean().nullish(),BundleID:zod.z.string().nullish(),ServiceID:zod.z.string().nullish()}).passthrough().nullish(),PlayAccessMode:Cs.nullish(),WalletLoginNetworks:zod.z.array(zod.z.object({NetworkID:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:zod.z.boolean().nullish(),NativeSso:_v.nullish()}).passthrough(),Tf=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:u.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:rn.nullish()}).passthrough(),wf=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:u.nullish(),PlayAccess:rn.nullish()}).passthrough(),kf=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Qe=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:u.nullish()}),zf=zod.z.object({Message:zod.z.string(),ExpiresAt:u}),Ke={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",ResolvePlatformGameSession:"ResolvePlatformGameSession",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var eo=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return an(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,Pf,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ke.RefreshSession),e,vf,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ke.GetAuthOptions),e,Af,{ticket:null})}linkWallet(e){return this.ctx.transport.post(an(this.ctx.settings.titleID,"Authentication",Ke.LinkWallet,e.UserID??""),e,Tf,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(an(this.ctx.settings.titleID,"Authentication",Ke.UnlinkWallet,e.UserID??""),e,wf,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ke.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ke.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ke.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ke.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ke.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ke.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(Ke.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ke.RegisterWithEmail),e,kf,{ticket:null})}confirmEmailRegistration(e){return this.login(Ke.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ke.ResendVerificationCode),e,Qe,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ke.RequestWalletChallenge),e,zf,{ticket:null})}loginWithWallet(e){return this.login(Ke.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ke.ForgotPassword),e,Qe,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ke.ResetPassword),e,Qe,{ticket:null})}};var to=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(bt.GetClientState,e,xs)}getClientStateExcept(e){return this.send(bt.GetClientStateExcept,e,xs)}getStateVersions(e){return this.send(bt.GetStateVersions,e,Cf)}getUserState(e){return this.send(bt.GetUserState,e,Sf)}getInventory(e){return this.send(bt.GetInventory,e,bf)}getEventTokens(e){return this.send(bt.GetEventTokens,e,xf)}getUsageTime(e){return this.send(bt.GetUsageTime,e,Df)}addUsageTime(e){return this.send(bt.AddUsageTime,e,Qe,{silent:true})}deleteUserAccount(e){return this.send(bt.DeleteUserAccount,e,Qe)}changeUsername(e){return this.send(bt.ChangeUsername,e,If)}};var no=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(hs.Convert,e,vh)}spend(e){return this.send(hs.Spend,e,Th)}cryptoConvert(e){return this.send(hs.CryptoConvert,e,Ah)}};var Vv=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),$l=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:O.nullish(),FodderConsumed:zod.z.array(Vv).nullish()}),Mf=zod.z.array(Ee($l)),so={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Fv={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},jv=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Wv={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Hv=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Kv=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),Qv=zod.z.object({Networks:zod.z.record(zod.z.string(),Kv).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),$v=zod.z.object({FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),Jv=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),UseRequirements:zod.z.record(zod.z.string(),zod.z.number()).nullish(),AllowedCharacterIDs:zod.z.array(zod.z.string()).nullish(),AllowedSlotIDs:zod.z.array(zod.z.string()).nullish(),IdleRateBonus:zod.z.number().nullish()}).passthrough(),Zv=zod.z.object({ValuationMode:jv.nullish(),WeightCurve:Ze.nullish(),Selection:Hv.nullish()}).passthrough(),Yv=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:me.nullish(),CostCurve:Ze.nullish(),FlatBonusCurve:Ze.nullish(),PercentBonusCurve:Ze.nullish(),PowerCurve:Ze.nullish(),Fodder:Zv.nullish()}).passthrough(),Xv=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),eA=zod.z.object({ItemID:zod.z.string(),CatalogID:zod.z.string(),ItemClass:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsStackable:zod.z.boolean().nullish(),IsTradable:zod.z.boolean().nullish(),Weight:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),NFT:Qv.nullish(),Stats:$v.nullish(),Equipment:Jv.nullish(),Upgrade:Yv.nullish(),Metadata:Xv.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),tA=zod.z.object({Items:zod.z.record(zod.z.string(),eA).nullish()}).passthrough(),nA={Cumulative:"Cumulative",HighestOnly:"HighestOnly"},sA=zod.z.enum(["Cumulative","HighestOnly"]).catch("Cumulative"),iA=zod.z.object({Pieces:zod.z.number().nullish(),FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),rA=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BonusMode:zod.z.enum(["Cumulative","HighestOnly"]).nullish().catch(null),Bonuses:zod.z.array(iA).nullish()}).passthrough(),oA=zod.z.object({BonusMode:sA.nullish()}).passthrough(),io=zod.z.object({Catalogs:zod.z.record(zod.z.string(),tA).nullish(),Sets:zod.z.record(zod.z.string(),rA).nullish(),SetSettings:oA.nullish()}).passthrough();function ke(r){return zod.z.unknown().transform((e,t)=>{let n=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(n!=null){let i=Re.safeParse(n);return i.success?{...e,CreditsConfirmation:i.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${i.error.message}`}),zod.z.NEVER)}let s=r.safeParse(e);return s.success?s.data:(t.addIssue({code:"custom",message:s.error.message}),zod.z.NEVER)})}var ro=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(so.UpgradeLevel,e,ke($l))}upgradeLevelsBatch(e){return this.send(so.UpgradeLevelsBatch,e,Mf)}};var oo=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(Ft.Purchase,e,qa)}purchaseBatch(e){return this.send(Ft.PurchaseBatch,e,Ec)}getDefinitions(e){return this.send(Ft.GetDefinitions,e,mi)}getUserState(e){return this.send(Ft.GetUserState,e,qc)}getStorefront(e){return this.send(Ft.GetStorefront,e,fi)}getCreditsConfirmation(e){return this.send(Ft.GetCreditsConfirmation,e,Re)}getCreditsBalance(e){return this.send(Ft.GetCreditsBalance,e,Oc)}};var aA={Apple:"Apple",Google:"Google"},ao=zod.z.object({PremiumID:zod.z.string().nullish(),PurchaseDate:zod.z.string().nullish(),ExpirationDate:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),IsAutoRenewEnabled:zod.z.boolean().nullish()}).passthrough(),lo=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),ao).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(r=>r),lA=zod.z.object({PremiumID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Tier:zod.z.number().nullish(),DurationDays:zod.z.number().nullish(),TrialDurationDays:zod.z.number().nullish(),PriceOptions:me.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Zl=zod.z.object({Definitions:zod.z.record(zod.z.string(),lA).nullish()}).passthrough(),Of=zod.z.object({Premium:Zl.nullish()}),Ef=zod.z.object({ServerTimeUtc:u.nullish(),Premium:lo.nullish()}),uo=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u.nullish(),Premium:lo.nullish(),Subscription:ao.nullish(),Resources:O.nullish()}),Sn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var uA={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},cA=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),qf=zod.z.object({StartUtc:u.nullish(),EndUtc:u.nullish(),Gate:te.nullish(),Limits:ve.nullish()}).passthrough(),Yl=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),pA=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:$.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),hA=zod.z.object({Rewards:J.nullish(),Rules:J.nullish(),Refund:J.nullish()}).passthrough(),dA=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:cA.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:$.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:qf.nullish(),Refund:Yl.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:pA.nullish(),Presets:hA.nullish()}).passthrough(),mA=zod.z.object({StoreID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),PackageName:zod.z.string().nullish(),VerificationMode:zod.z.string().nullish(),PlayPublicKey:zod.z.string().nullish(),RequireCertificateChain:zod.z.boolean().nullish(),SecretName:zod.z.string().nullish(),IssuerID:zod.z.string().nullish(),KeyID:zod.z.string().nullish(),AcknowledgePurchases:zod.z.boolean().nullish(),NotificationPackageName:zod.z.string().nullish()}).passthrough(),fA=zod.z.object({Rewards:$.nullish()}).passthrough(),gA=zod.z.object({Rules:qf.nullish()}).passthrough(),yA=zod.z.object({Refund:Yl.nullish()}).passthrough(),RA=zod.z.object({Rewards:zod.z.record(zod.z.string(),fA).nullish(),Rules:zod.z.record(zod.z.string(),gA).nullish(),Refund:zod.z.record(zod.z.string(),yA).nullish()}).passthrough(),CA=zod.z.object({MaxPurchaseAgeDays:zod.z.number().nullish(),AllowSandbox:zod.z.boolean().nullish(),RequirePackageMatch:zod.z.boolean().nullish(),MaxReceiptsPerBatch:zod.z.number().nullish(),RefundCheckHorizonDays:zod.z.number().nullish(),RejectCrossUserReceipts:zod.z.boolean().nullish()}).passthrough(),SA=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),dA).nullish(),Stores:zod.z.record(zod.z.string(),mA).nullish(),Presets:RA.nullish(),Validation:CA.nullish(),Refund:Yl.nullish()}).passthrough(),Uf=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:u.nullish(),LastPurchasedAt:u.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Lf=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:u.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:u.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:u.nullish()}).passthrough(),bA=zod.z.object({Products:zod.z.record(zod.z.string(),Uf).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Lf).nullish(),LastRefundCheckAt:u.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:u.nullish(),LastPurchaseAt:u.nullish()}).passthrough(),xA=zod.z.object({ProductID:zod.z.string(),Available:zod.z.boolean(),Owned:zod.z.boolean(),Blocked:zod.z.boolean(),Reason:zod.z.string().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Bf=zod.z.object({ServerTimeUtc:u,Purchase:SA.nullish(),Availability:zod.z.array(xA).nullish()}),Gf=zod.z.object({ServerTimeUtc:u,Purchase:bA.nullish()}),DA={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},IA=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Xl=zod.z.object({ServerTimeUtc:u,Store:Ms.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:IA.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish(),ProductState:Uf.nullish(),Premium:lo.nullish(),Subscription:ao.nullish(),SubscriptionMirror:Lf.nullish()}).passthrough(),Nf=zod.z.object({ServerTimeUtc:u,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:u.nullish()}).passthrough(),_f=Ot(Xl),bn={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var co=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(bn.GetDefinitions,e,Bf)}getUserState(e){return this.send(bn.GetUserState,e,Gf)}validatePurchase(e){return this.send(bn.ValidatePurchase,e,Xl)}validatePurchasesBatch(e){return this.send(bn.ValidatePurchasesBatch,e,_f)}createTelegramInvoice(e){return this.send(bn.CreateTelegramInvoice,e,Nf)}};var PA=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Vf=zod.z.object({Reward:$.nullish(),Weight:zod.z.number().nullish(),AmountRange:PA.nullish()}).passthrough(),Wn=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(Vf).nullish()}).passthrough(),Hn=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(Vf).nullish()}).passthrough(),vA=zod.z.object({RewardSlots:zod.z.array(Wn).nullish()}).passthrough(),AA=zod.z.object({PityRules:zod.z.array(Hn).nullish()}).passthrough(),po=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),vA).nullish(),PityPresets:zod.z.record(zod.z.string(),AA).nullish()}).passthrough();var TA=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),Ff=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish(),Results:zod.z.array(O).nullish(),TriggeredPity:zod.z.array(TA).nullish()}),wA=zod.z.object({RewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),kA=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:Q.nullish()}).passthrough(),zA=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:me.nullish(),RewardSlots:zod.z.array(Wn).nullish(),PityRules:zod.z.array(Hn).nullish(),Presets:wA.nullish(),RewardMultiplier:Ns.nullish(),SupplyLimits:zod.z.array(kA).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),MA=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),eu=zod.z.object({Definitions:zod.z.record(zod.z.string(),zA).nullish(),RewardPools:po.nullish(),Settings:MA.nullish()}).passthrough(),jf=zod.z.object({LootboxDefinitions:eu.nullish()}),ho={GetDefinitions:"GetDefinitions",Open:"Open"};var mo=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(ho.GetDefinitions,e,jf)}open(e){return this.send(ho.Open,e,ke(Ff))}};var OA=zod.z.object({}).passthrough().transform(r=>r),EA=zod.z.object({}).passthrough().transform(r=>r),qA=zod.z.object({}).passthrough().transform(r=>r),UA=zod.z.object({}).passthrough().transform(r=>r),LA=zod.z.object({}).passthrough().transform(r=>r),BA=zod.z.object({}).passthrough().transform(r=>r),Wf=zod.z.object({ServerTimeUtc:u,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:OA,Resources:O.nullish(),Inventory:K.nullish()}),Hf=zod.z.object({ServerTimeUtc:u,AccrualID:zod.z.string(),AccruedSeconds:Q.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:EA,Resources:O.nullish(),Inventory:K.nullish()}),Kf=zod.z.object({ServerTimeUtc:u,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:qA,Resources:O.nullish(),Inventory:K.nullish()}),Qf=zod.z.object({ServerTimeUtc:u,ClaimID:zod.z.string(),ClaimState:UA,Resources:O.nullish(),Inventory:K.nullish()}),GA={None:"None",Ad:"Ad",Vip:"Vip"},$f=zod.z.object({ServerTimeUtc:u,WindowID:zod.z.string(),Boost:zod.z.string().nullish(),BaseAmount:Q.nullish(),Multiplier:zod.z.number().nullish(),Granted:Q.nullish(),WindowState:LA,Resources:O.nullish(),Inventory:K.nullish()}),Jf=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:Q.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),NA=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),_A=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:$.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ds=zod.z.object({Gate:te.nullish(),Limits:ve.nullish()}).passthrough(),tu=zod.z.object({Availability:J.nullish()}).passthrough(),VA=zod.z.object({Availability:zod.z.record(zod.z.string(),Ds).nullish()}).passthrough(),FA=zod.z.object({CalendarID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Days:zod.z.array(_A).nullish(),IsLooping:zod.z.boolean().nullish(),MissBehavior:zod.z.string().nullish(),ResetByDays:zod.z.number().nullish(),MissThresholdMultiplier:zod.z.number().nullish(),ClaimMode:zod.z.string().nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),Availability:Ds.nullish(),Presets:tu.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),jA=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),WA=zod.z.object({BaseRatePerSecond:zod.z.number().nullish(),PowerCoefficient:zod.z.number().nullish(),BoardRankCoefficient:zod.z.number().nullish(),EquipmentBonusEnabled:zod.z.boolean().nullish(),EquipmentCharacterID:zod.z.string().nullish(),PremiumMultipliers:zod.z.array(jA).nullish()}).passthrough(),HA=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Ds.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),KA=zod.z.object({AccrualID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rate:WA.nullish(),Rewards:$.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:HA.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),QA=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:$.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$A=zod.z.object({ComebackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(QA).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Ds.nullish(),Presets:tu.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),JA=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxClaimsPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish(),TotalClaimLimit:zod.z.number().nullish()}).passthrough(),ZA=zod.z.object({ClaimID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Mode:zod.z.string().nullish(),Rewards:$.nullish(),PremiumLimitOverrides:zod.z.array(JA).nullish(),Availability:Ds.nullish(),Presets:tu.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),YA=zod.z.object({CurrencyID:zod.z.string().nullish(),MaxBaseAmount:zod.z.number().nullish(),AdPlacementID:zod.z.string().nullish(),AdMultiplier:zod.z.number().nullish(),VipMultiplier:zod.z.number().nullish(),VipPremiumID:zod.z.string().nullish(),Limits:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),nu=zod.z.object({TierRewards:NA.nullish(),MilestoneRewardMultiplier:Ns.nullish(),DailyCalendars:zod.z.record(zod.z.string(),FA).nullish(),IdleAccruals:zod.z.record(zod.z.string(),KA).nullish(),Comebacks:zod.z.record(zod.z.string(),$A).nullish(),Claims:zod.z.record(zod.z.string(),ZA).nullish(),Windows:zod.z.record(zod.z.string(),YA).nullish(),Presets:VA.nullish()}).passthrough(),Zf=zod.z.object({RewardDefinitions:nu.nullish()}),Yf=zod.z.object({Rewards:BA.nullish()}),Bt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var fo=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Bt.GetRewardDefinitions,e,Zf)}getUserRewardsState(e){return this.send(Bt.GetUserRewardsState,e,Yf)}getMilestoneRewardMultiplier(e){return this.send(Bt.GetMilestoneRewardMultiplier,e,Jf)}claimDailyReward(e){return this.send(Bt.ClaimDailyReward,e,Wf)}collectIdleAccrual(e){return this.send(Bt.CollectIdleAccrual,e,Hf)}claimComebackReward(e){return this.send(Bt.ClaimComebackReward,e,Kf)}claimReward(e){return this.send(Bt.ClaimReward,e,Qf)}claimRewardWindow(e){return this.send(Bt.ClaimRewardWindow,e,$f)}};var go=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(gt.GetTutorialDefinitions,e,fc)}getUserTutorialState(e){return this.send(gt.GetUserTutorialState,e,Fs)}startFlow(e){return this.send(gt.StartFlow,e,Jt)}reportStepShown(e){return this.send(gt.ReportStepShown,e,Jt)}completeStep(e){return this.send(gt.CompleteStep,e,Jt)}completeStepsBatch(e){return this.send(gt.CompleteStepsBatch,e,Rc)}skipStep(e){return this.send(gt.SkipStep,e,Jt)}skipFlow(e){return this.send(gt.SkipFlow,e,Jt)}claimFlowReward(e){return this.send(gt.ClaimFlowReward,e,yc)}resetFlow(e){return this.send(gt.ResetFlow,e,Jt)}};var XA={Open:"Open",Application:"Application"},eT=zod.z.enum(["Open","Application"]).catch("Open"),tT={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Xf=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),nT={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},su=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),sT={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var xn={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},iT=zod.z.object({CampaignID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IsRunning:zod.z.boolean().nullish()}).passthrough(),eg=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:eT.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:Xf.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(iT).nullish()}).passthrough(),rT=zod.z.object({Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),CountedMetrics:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ReachedMilestones:zod.z.array(zod.z.string()).nullish(),CappedBySubmissionLimit:zod.z.boolean().nullish(),CappedByCreatorLimit:zod.z.boolean().nullish(),NotPaidAsCopy:zod.z.boolean().nullish()}).passthrough(),oT=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:su.nullish(),CurrencyID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),Granted:zod.z.number().nullish(),Paid:zod.z.number().nullish(),Overpaid:zod.z.number().nullish(),Claimable:zod.z.number().nullish(),BySubmission:zod.z.record(zod.z.string(),rT).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),aT=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:su.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),tg=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(oT).nullish(),Payouts:zod.z.array(aT).nullish()}).passthrough(),ng=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:su.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),lT=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),uT=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),Signature:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(lT).nullish()}).passthrough(),cT=zod.z.object({Kind:zod.z.string().nullish(),Target:zod.z.string().nullish(),Required:zod.z.number().nullish(),Actual:zod.z.number().nullish(),Passed:zod.z.boolean().nullish()}).passthrough(),sg=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:Xf.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(cT).nullish()}).passthrough(),pT=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),hT=zod.z.object({ProgramID:zod.z.string().nullish(),Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(pT).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),ig=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:zod.z.number().nullish(),NetAmountNative:zod.z.number().nullish(),BurnAmountNative:zod.z.number().nullish(),AmountUsd:zod.z.number().nullish(),ExpiresAt:zod.z.string().nullish(),EvmSignature:uT.nullish(),SolanaSignature:hT.nullish(),StateDelta:Fn.nullish()}).passthrough();var yo=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(xn.GetCommunityMarketingState,e,eg)}getEarnings(e){return this.send(xn.GetEarnings,e,tg)}claim(e){return this.send(xn.Claim,e,ng)}checkJoinEligibility(e){return this.send(xn.CheckJoinEligibility,e,sg)}withdrawCryptoReward(e){return this.send(xn.WithdrawCryptoReward,e,ig)}};var Ro=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(st.GetChatDefinitions,e,Zc)}getChannels(e){return this.send(st.GetChannels,e,Ai)}poll(e){return this.send(st.Poll,e,Yc)}getHistory(e){return this.send(st.GetHistory,e,Xc)}getConversations(e){return this.send(st.GetConversations,e,np)}sendMessage(e){return this.send(st.SendMessage,e,ep)}openDirectChannel(e){return this.send(st.OpenDirectChannel,e,tp)}markRead(e){return this.send(st.MarkRead,e,Nn)}joinChannel(e){return this.send(st.JoinChannel,e,Nn)}leaveChannel(e){return this.send(st.LeaveChannel,e,Nn)}reportMessage(e){return this.send(st.ReportMessage,e,sp)}ignoreUser(e){return this.send(st.IgnoreUser,e,Nn)}unignoreUser(e){return this.send(st.UnignoreUser,e,Nn)}};var Co=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(_n.GetPushConfig,e,op)}subscribePush(e){return this.send(_n.SubscribePush,e,Ba)}unsubscribePush(e){return this.send(_n.UnsubscribePush,e,Qe)}getPushSubscriptions(e){return this.send(_n.GetPushSubscriptions,e,ap)}};var So=class extends B{constructor(e){super(e,"Localization");}send(e,t,n,s){let i=this.endpoint(e,t);return super.send(e,t,n,{throttleKey:t.Locale?`${i}:${t.Locale}`:i,...s})}getLocalizationManifest(e){return this.send(Xr.GetLocalizationManifest,e,yf)}getLocalizationTable(e){return this.send(Xr.GetLocalizationTable,e,Rf)}};var bo=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(At.GetQuestDefinitions,e,Vs)}getUserQuestState(e){return this.send(At.GetUserQuestState,e,sc)}refreshQuestCycles(e){return this.send(At.RefreshQuestCycles,e,Qe)}claimQuestReward(e){return this.send(At.ClaimQuestReward,e,Da)}claimQuestRewardsBatch(e){return this.send(At.ClaimQuestRewardsBatch,e,oc)}claimMilestoneReward(e){return this.send(At.ClaimMilestoneReward,e,Ia)}claimMilestoneRewardsBatch(e){return this.send(At.ClaimMilestoneRewardsBatch,e,ac)}claimGroupCompletionReward(e){return this.send(At.ClaimGroupCompletionReward,e,ic)}addQuestProgress(e){return this.send(At.AddQuestProgress,e,rc)}};var xo=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(Rt.GetActiveEvents,e,Ei)}getDefinitions(e){return this.send(Rt.GetDefinitions,e,Oi)}getUserLteState(e){return this.send(Rt.GetUserLteState,e,pp)}grantTokens(e){return this.send(Rt.GrantTokens,e,O)}spendTokens(e){return this.send(Rt.SpendTokens,e,_a)}claimMilestone(e){return this.send(Rt.ClaimMilestone,e,Va)}claimMilestonesBatch(e){return this.send(Rt.ClaimMilestonesBatch,e,Fa)}claimAllMilestones(e){return this.send(Rt.ClaimAllMilestones,e,Fa)}spendTokensBatch(e){return this.send(Rt.SpendTokensBatch,e,hp)}grantTokensBatch(e){return this.send(Rt.GrantTokensBatch,e,dp)}};var Do=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ye.GetDefinitions,e,_i)}getLeaderboard(e){return this.send(Ye.GetLeaderboard,e,us)}getMyProgress(e){return this.send(Ye.GetMyProgress,e,Ui)}submitScore(e){return this.send(Ye.SubmitScore,e,Li)}submitScoreFromSource(e){return this.send(Ye.SubmitScoreFromSource,e,Li)}claimCycleReward(e){return this.send(Ye.ClaimCycleReward,e,Bi)}claimMilestone(e){return this.send(Ye.ClaimMilestone,e,Gi)}getFriendsLeaderboard(e){return this.send(Ye.GetFriendsLeaderboard,e,us)}getLeaderboardsBatch(e){return this.send(Ye.GetLeaderboardsBatch,e,gp)}getProgressBatch(e){return this.send(Ye.GetProgressBatch,e,Ni)}claimCycleRewardsBatch(e){return this.send(Ye.ClaimCycleRewardsBatch,e,yp)}claimMilestonesBatch(e){return this.send(Ye.ClaimMilestonesBatch,e,Rp)}submitScoresBatch(e){return this.send(Ye.SubmitScoresBatch,e,Cp)}claimAllRewardsBatch(e){return this.send(Ye.ClaimAllRewardsBatch,e,Sp)}getOverviewBatch(e){return this.send(Ye.GetOverviewBatch,e,bp)}};var Io=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Xt.GetDefinitions,e,ji)}getActiveSeason(e){return this.send(Xt.GetActiveSeason,e,Fi)}getUserState(e){return this.send(Xt.GetUserState,e,ja)}grantStatusTokens(e){return this.send(Xt.GrantStatusTokens,e,Pp)}claimTierReward(e){return this.send(Xt.ClaimTierReward,e,Wa)}claimTierRewardsBatch(e){return this.send(Xt.ClaimTierRewardsBatch,e,vp)}};var Po=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Sn.GetDefinitions,e,Of)}getUserState(e){return this.send(Sn.GetUserState,e,Ef)}activateTrial(e){return this.send(Sn.ActivateTrial,e,uo)}purchaseItemOrCurrency(e){return this.send(Sn.PurchaseWithResources,e,ke(uo))}purchaseRealMoney(e){return this.send(Sn.PurchaseRealMoney,e,uo)}};var vo=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(Je.GetCharacterDefinitions,e,Qi)}getUserCharacters(e){return this.send(Je.GetUserCharacters,e,Mp)}unlockCharacter(e){return this.send(Je.UnlockCharacter,e,ke(Qa))}upgradeStatLevel(e){return this.send(Je.UpgradeStatLevel,e,ke(Ha))}upgradeCharacterLevel(e){return this.send(Je.UpgradeCharacterLevel,e,ke(Ka))}equipItems(e){return this.send(Je.EquipItems,e,Op)}unequipItems(e){return this.send(Je.UnequipItems,e,Ep)}unequipAllCharacters(e){return this.send(Je.UnequipAllCharacters,e,qp)}unlockCharactersBatch(e){return this.send(Je.UnlockCharactersBatch,e,_p)}upgradeCharacterLevelsBatch(e){return this.send(Je.UpgradeCharacterLevelsBatch,e,Vp)}upgradeStatLevelsBatch(e){return this.send(Je.UpgradeStatLevelsBatch,e,Fp)}unlockSkin(e){return this.send(Je.UnlockSkin,e,ke(Up))}equipSkin(e){return this.send(Je.EquipSkin,e,Lp)}unequipSkin(e){return this.send(Je.UnequipSkin,e,Bp)}getCharacterSkins(e){return this.send(Je.GetCharacterSkins,e,Gp)}selectCharacter(e){return this.send(Je.SelectCharacter,e,Np)}};var Ao=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(Ut.CreateMatch,e,Fh)}updateMatch(e){return this.send(Ut.UpdateMatch,e,jh)}cancelMatch(e){return this.send(Ut.CancelMatch,e,Wh)}instantBattle(e){return this.send(Ut.InstantBattle,e,Hh)}saveStrategy(e){return this.send(Ut.SaveStrategy,e,Qe)}getMyMatches(e){return this.send(Ut.GetMyMatches,e,ul)}getAvailableMatches(e){return this.send(Ut.GetAvailableMatches,e,ul)}getDefinitions(e){return this.send(Ut.GetDefinitions,e,Jh)}};var dT={Arena:"Arena"},og=zod.z.string(),Kn={GetState:"GetState",RefreshOpponents:"RefreshOpponents",Attempt:"Attempt",ClaimMilestone:"ClaimMilestone"},mT=zod.z.object({TierID:zod.z.string().nullish(),MinPowerRatio:zod.z.number().nullish(),MaxPowerRatio:zod.z.number().nullish(),PointsOnWin:zod.z.number().nullish(),BotStatScale:zod.z.number().nullish()}).passthrough(),fT=zod.z.object({RuleID:zod.z.string().nullish(),Tiers:zod.z.array(mT).nullish(),RefreshCooldownSeconds:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),MaxCandidateReads:zod.z.number().nullish(),RevengeEnabled:zod.z.boolean().nullish(),RevengeCost:zod.z.number().nullish(),RevengePoints:zod.z.number().nullish(),WinReward:$.nullish()}).passthrough(),gT=zod.z.object({ChallengeID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),Mode:og.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AttemptCost:zod.z.number().nullish(),DailyAttemptLimit:zod.z.number().nullish(),Points:Mt.nullish(),Milestones:zod.z.record(zod.z.string(),je).nullish(),ClaimMode:zod.z.string().nullish(),Arena:fT.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),yT=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:Se.nullish(),Challenges:zod.z.array(gT).nullish(),Ticket:Mt.nullish(),Gate:te.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ag=zod.z.object({Chains:zod.z.record(zod.z.string(),yT).nullish()}).passthrough(),lg=zod.z.object({TierID:zod.z.string().nullish(),OpponentID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Country:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BotStatScale:zod.z.number().nullish(),Defeated:zod.z.boolean().nullish()}).passthrough(),RT=zod.z.object({RevengeID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),AttackerUserID:zod.z.string().nullish(),AttackerName:zod.z.string().nullish(),AttackerAvatarUrl:zod.z.string().nullish(),AttackerPower:zod.z.number().nullish(),CreatedAtUtc:u.nullish(),Used:zod.z.boolean().nullish()}).passthrough(),CT=zod.z.object({AttemptID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),OpponentID:zod.z.string().nullish(),TierID:zod.z.string().nullish(),IsRevenge:zod.z.boolean().nullish(),Win:zod.z.boolean().nullish(),PointsGranted:zod.z.number().nullish(),TicketsSpent:zod.z.number().nullish(),AtUtc:u.nullish()}).passthrough(),ST=zod.z.object({Opponents:zod.z.array(lg).nullish(),Revenges:zod.z.array(RT).nullish(),RevengeCost:zod.z.number().nullish(),RevengePoints:zod.z.number().nullish(),RefreshAvailableAtUtc:u.nullish()}).passthrough(),rg=zod.z.object({ChallengeID:zod.z.string().nullish(),Mode:og.nullish(),InstanceKey:zod.z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),AttemptCost:zod.z.number().nullish(),AttemptsToday:zod.z.number().nullish(),DailyAttemptLimit:zod.z.number().nullish(),PointsEarned:zod.z.number().nullish(),ClaimedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Arena:ST.nullish()}).passthrough(),bT=zod.z.object({ChainID:zod.z.string().nullish(),Tickets:zod.z.number().nullish(),Active:rg.nullish(),Ended:zod.z.array(rg).nullish()}).passthrough(),xT=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),TicketsBurned:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),Converted:zod.z.number().nullish(),CarriedToInstanceKey:zod.z.string().nullish()}).passthrough(),iu=zod.z.object({Chains:zod.z.array(bT).nullish(),ServerTimeUtc:u.nullish(),Burns:zod.z.array(xT).nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough(),ug=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),Attempt:CT.nullish(),IsReplay:zod.z.boolean().nullish(),Battle:ds.nullish(),Opponent:lg.nullish(),Tickets:zod.z.number().nullish(),PointsEarned:zod.z.number().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough(),cg=zod.z.object({ChainID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}).passthrough();var To=class extends B{constructor(e){super(e,"Challenge");}getState(e){return this.send(Kn.GetState,e,iu)}refreshOpponents(e){return this.send(Kn.RefreshOpponents,e,iu)}attempt(e){return this.send(Kn.Attempt,e,ug)}claimMilestone(e){return this.send(Kn.ClaimMilestone,e,cg)}};var DT={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},pg=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),IT={None:"None",Min:"Min",Average:"Average",Max:"Max",Weighted:"Weighted"},PT=zod.z.enum(["None","Min","Average","Max","Weighted"]).catch("None"),vT={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},AT=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),TT={Clamp:"Clamp",Reject:"Reject"},wT=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),kT=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),zT=zod.z.object({Index:zod.z.number().nullish(),BurnedItemIDs:zod.z.array(zod.z.string()).nullish(),RolledCollectionID:zod.z.string().nullish(),UsedCollections:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Output:zt.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(kT).nullish()}),hg=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u,Type:pg.nullish(),CraftID:zod.z.string(),CraftedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),InputRarity:zod.z.string().nullish(),OutputRarity:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish(),Results:zod.z.array(zT).nullish()}),MT=zod.z.object({CraftID:zod.z.string().nullish(),Type:pg.nullish(),CatalogID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),InputRarityID:zod.z.string().nullish(),OutputRarityID:zod.z.string().nullish(),RequiredItemCount:zod.z.number().nullish(),PriceOptions:me.nullish(),OutputLevelMode:PT.nullish(),OutputLevelWeightPower:zod.z.number().nullish(),InputSelection:AT.nullish(),OutputLevelOverflow:wT.nullish()}).passthrough(),ru=zod.z.object({Definitions:zod.z.record(zod.z.string(),MT).nullish()}).passthrough(),dg=zod.z.object({ServerTimeUtc:u.nullish(),CraftDefinitions:ru.nullish()}),wo={GetDefinitions:"GetDefinitions",Craft:"Craft"};var ko=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(wo.GetDefinitions,e,dg)}craft(e){return this.send(wo.Craft,e,ke(hg))}};var OT=2e5,zo=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,ke(Xi),{timeoutMs:OT,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Xi,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(We.GetDefinitions,e,eh)}generateText(e){return this.generate(We.GenerateText,e)}getText(e){return this.readGeneration(We.GetText,e)}generateImage(e){return this.generate(We.GenerateImage,e)}editImage(e){return this.generate(We.EditImage,e)}getImage(e){return this.readGeneration(We.GetImage,e)}generateVideo(e){return this.generate(We.GenerateVideo,e)}getVideo(e){return this.readGeneration(We.GetVideo,e)}generateAudio(e){return this.generate(We.GenerateAudio,e)}getAudio(e){return this.readGeneration(We.GetAudio,e)}generateMusic(e){return this.generate(We.GenerateMusic,e)}getMusic(e){return this.readGeneration(We.GetMusic,e)}generateFromTemplate(e){return this.generate(We.GenerateFromTemplate,e)}estimateTemplatePrice(e){return this.send(We.EstimateTemplatePrice,e,Xp,{throttleKey:`AI:EstimateTemplatePrice:${e.FeatureKey??""}:${JSON.stringify(e.Params??{})}`})}generateThreeD(e){return this.generate(We.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(We.GetThreeD,e)}listGenerations(e){return this.send(We.ListGenerations,e,Zp)}getGeneration(e){return this.readGeneration(We.GetGeneration,e)}};var ET={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},qT=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),mg=zod.z.object({}).passthrough().transform(r=>r),Qn=zod.z.object({CollectibleID:zod.z.string(),Rarity:zod.z.number().nullish(),IsSpecial:zod.z.boolean().nullish(),IsDuplicate:zod.z.boolean().nullish(),CollectionCurrencyConverted:zod.z.number().nullish()}),fg=zod.z.object({GrantedCollectibles:zod.z.array(Qn).nullish(),DuplicateCollectibles:zod.z.array(Qn).nullish(),CollectionCurrencyEarned:Q.nullish()}),gg=zod.z.object({CreditsConfirmation:Re.nullish(),OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(fg).nullish(),GrantedCollectibles:zod.z.array(Qn).nullish(),DuplicateCollectibles:zod.z.array(Qn).nullish(),CollectionCurrencyEarned:Q.nullish(),NewCollectionCurrencyBalance:Q.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),yg=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(fg).nullish(),GrantedCollectibles:zod.z.array(Qn).nullish(),DuplicateCollectibles:zod.z.array(Qn).nullish(),CollectionCurrencyEarned:Q.nullish(),NewCollectionCurrencyBalance:Q.nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Rg=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),ou=zod.z.object({SetID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish()}),Cg=zod.z.array(Ee(ou)),Sg=zod.z.object({Resources:O.nullish(),Inventory:K.nullish()}),UT=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:_e.nullish(),OfferedCollectibleID:zod.z.string().nullish(),OfferedCollectibleIsSpecial:zod.z.boolean().nullish(),ReceiverUserID:zod.z.string().nullish(),RequestedCollectibleID:zod.z.string().nullish(),RequestedCollectibleIsSpecial:zod.z.boolean().nullish(),Status:qT.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RespondedAtUtc:u.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),bg=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:u.nullish(),Resources:O.nullish()}),xg=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),Dg=zod.z.object({OfferID:zod.z.string(),ReceivedCollectibleID:zod.z.string().nullish(),ReceivedIsSpecial:zod.z.boolean().nullish(),SentCollectibleID:zod.z.string().nullish(),SentCollectibleIsSpecial:zod.z.boolean().nullish(),Transfer:zod.z.unknown().nullish()}),Ig=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),au=zod.z.object({Offers:zod.z.array(UT).nullish()}),LT=zod.z.object({CollectibleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rarity:zod.z.number().nullish(),HasSpecialVersion:zod.z.boolean().nullish(),SortOrder:zod.z.number().nullish()}).passthrough(),BT=zod.z.object({SetID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SortOrder:zod.z.number().nullish(),Collectibles:zod.z.array(LT).nullish(),SetCompletionReward:$.nullish()}).passthrough(),GT=zod.z.object({CollectionID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SeasonChainID:zod.z.string().nullish(),Sets:zod.z.array(BT).nullish(),GrandPrize:$.nullish()}).passthrough(),Pg=zod.z.object({BonusRewardSlots:J.nullish(),PityRules:J.nullish()}).passthrough(),NT=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:me.nullish(),BonusRewardSlots:zod.z.array(Wn).nullish(),PityRules:zod.z.array(Hn).nullish(),Presets:Pg.nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectibleCount:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),GuaranteeMaxRarity:zod.z.boolean().nullish(),RarityWeights:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ColorTier:zod.z.number().nullish()}).passthrough(),_T=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),VT=zod.z.object({CollectionChestID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectionCurrencyCost:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),MinCollectibleCount:zod.z.number().nullish(),MaxCollectibleCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),BonusRewardSlots:zod.z.array(Wn).nullish(),PityRules:zod.z.array(Hn).nullish(),Presets:Pg.nullish(),Tier:zod.z.number().nullish()}).passthrough(),FT=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),jT=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),Mo=zod.z.object({Collections:zod.z.record(zod.z.string(),GT).nullish(),PackTypes:zod.z.record(zod.z.string(),NT).nullish(),CollectionChests:zod.z.array(VT).nullish(),DuplicateConversions:zod.z.array(_T).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(FT).nullish(),RewardPools:po.nullish(),Settings:jT.nullish()}).passthrough(),et={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var Oo=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(et.GetDefinitions,e,Mo)}getUserState(e){return this.send(et.GetUserState,e,mg)}openPack(e){return this.send(et.OpenPack,e,ke(gg))}openCollectionChest(e){return this.send(et.OpenCollectionChest,e,yg)}useCollectibleJoker(e){return this.send(et.UseCollectibleJoker,e,Rg)}claimSetReward(e){return this.send(et.ClaimSetReward,e,ou)}claimSetRewardsBatch(e){return this.send(et.ClaimSetRewardsBatch,e,Cg)}claimGrandPrize(e){return this.send(et.ClaimGrandPrize,e,Sg)}sendTradeOffer(e){return this.send(et.SendTradeOffer,e,bg)}cancelTradeOffer(e){return this.send(et.CancelTradeOffer,e,xg)}acceptTradeOffer(e){return this.send(et.AcceptTradeOffer,e,Dg)}declineTradeOffer(e){return this.send(et.DeclineTradeOffer,e,Ig)}getMyTradeOffers(e){return this.send(et.GetMyTradeOffers,e,au)}getIncomingTradeOffers(e){return this.send(et.GetIncomingTradeOffers,e,au)}};var Eo=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(wt.GetDefinitions,e,sr)}getActiveEvent(e){return this.send(wt.GetActiveEvent,e,sh)}getUserState(e){return this.send(wt.GetUserState,e,nr)}getGroupState(e){return this.send(wt.GetGroupState,e,el)}joinOrCreateGroup(e){return this.send(wt.JoinOrCreateGroup,e,el)}spin(e){return this.send(wt.Spin,e,ke(rh))}claimObjectReward(e){return this.send(wt.ClaimObjectReward,e,tl)}claimGrandPrize(e){return this.send(wt.ClaimGrandPrize,e,tl)}leaveGroup(e){return this.send(wt.LeaveGroup,e,oh)}};var qo=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(qt.GetDefinition,e,yh)}getUserState(e){return this.send(qt.GetUserState,e,Rh)}getActiveDeals(e){return this.send(qt.GetActiveDeals,e,or)}dismissDeal(e){return this.send(qt.DismissDeal,e,Sh)}executeNode(e){return this.send(qt.ExecuteNode,e,ke(Ch))}recordShow(e){return this.send(qt.RecordShow,e,bh)}claimMilestone(e){return this.send(qt.ClaimMilestone,e,xh)}claimMilestonesBatch(e){return this.send(qt.ClaimMilestonesBatch,e,Dh)}};var WT=zod.z.object({}).passthrough().transform(r=>r),HT=zod.z.object({FeatureKey:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Rate:zod.z.number().nullish(),Basis:zod.z.string().nullish(),SourceCurrencyID:zod.z.string().nullish(),TargetCurrencyID:zod.z.string().nullish(),MinSourceAmount:zod.z.number().nullish(),MaxRewardPerOperation:zod.z.number().nullish(),Limits:ve.nullish()}).passthrough(),lu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:$.nullish(),InviteRewards:zod.z.record(zod.z.string(),je).nullish(),SpendRewards:zod.z.array(HT).nullish(),Qualification:zod.z.object({}).passthrough().transform(r=>r).nullish()}).passthrough(),uu=zod.z.object({Pending:zod.z.boolean().nullish(),Qualified:zod.z.boolean().nullish(),Groups:zod.z.array(zod.z.object({GroupID:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Conditions:zod.z.array(zod.z.object({Type:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Current:zod.z.number().nullish(),Required:zod.z.number().nullish()}).passthrough()).nullish()}).passthrough()).nullish()}).passthrough(),vg=zod.z.object({ReferralDefinitions:lu.nullish()}).passthrough(),Ag=zod.z.object({Referral:WT.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:uu.nullish()}).passthrough(),Tg=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:uu.nullish()}).passthrough(),wg=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish(),QualificationPending:zod.z.boolean().nullish(),Qualification:uu.nullish()}).passthrough(),cu=zod.z.object({RewardID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),kg=Ot(cu),ln={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var Uo=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(ln.GetDefinitions,e,vg)}getUserState(e){return this.send(ln.GetUserState,e,Ag)}activateReferralCode(e){return this.send(ln.ActivateReferralCode,e,wg)}claimInviteReward(e){return this.send(ln.ClaimInviteReward,e,cu)}claimInviteRewardsBatch(e){return this.send(ln.ClaimInviteRewardsBatch,e,kg)}checkQualification(e){return this.send(ln.CheckQualification,e,Tg)}};var Lo=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(ht.GetDefinitions,e,qh)}getMessages(e){return this.send(ht.GetMessages,e,Uh)}getUnreadCount(e){return this.send(ht.GetUnreadCount,e,cr)}readMessages(e){return this.send(ht.ReadMessages,e,rl)}claimReward(e){return this.send(ht.ClaimReward,e,pr)}claimRewardsBatch(e){return this.send(ht.ClaimRewardsBatch,e,pr)}claimAll(e){return this.send(ht.ClaimAll,e,pr)}deleteMessages(e){return this.send(ht.DeleteMessages,e,rl)}sendGift(e){return this.send(ht.SendGift,e,Lh)}sendTransfer(e){return this.send(ht.SendTransfer,e,Bh)}getGiftStatus(e){return this.send(ht.GetGiftStatus,e,Gh)}};var Bo=class extends B{constructor(e){super(e,"Clan");}getDefinitions(e){return this.send(Be.GetDefinitions,e,pd)}getMyClans(e){return this.send(Be.GetMyClans,e,Yh)}searchClans(e){return this.send(Be.SearchClans,e,ml)}getRecommendedClans(e){return this.send(Be.GetRecommendedClans,e,ml)}getClan(e){return this.send(Be.GetClan,e,Xh)}getClanMembers(e){return this.send(Be.GetClanMembers,e,td)}getRankings(e){return this.send(Be.GetRankings,e,nd)}getApplications(e){return this.send(Be.GetApplications,e,fl)}getMyInvites(e){return this.send(Be.GetMyInvites,e,fl)}getClanLog(e){return this.send(Be.GetClanLog,e,sd)}getRequests(e){return this.send(Be.GetRequests,e,rd)}getGifts(e){return this.send(Be.GetGifts,e,od)}getRewards(e){return this.send(Be.GetRewards,e,ad)}getTreasury(e){return this.send(Be.GetTreasury,e,hd)}getProjects(e){return this.send(Be.GetProjects,e,dd)}getActivities(e){return this.send(Be.GetActivities,e,md)}getClanQuests(e){return this.send(Be.GetClanQuests,e,fd)}getCompetitions(e){return this.send(Be.GetCompetitions,e,gd)}getBracket(e){return this.send(Be.GetBracket,e,yd)}getDiplomacy(e){return this.send(Be.GetDiplomacy,e,Rd)}getRevenges(e){return this.send(Be.GetRevenges,e,Cd)}getLeague(e){return this.send(Be.GetLeague,e,Sd)}mutate(e,t){return this.send(e,t,cd)}};var Go=class extends B{constructor(e){super(e,"Avatar");}getDefinitions(e){return this.send(Vn.GetDefinitions,e,Rr)}getAvatars(e){return this.send(Vn.GetAvatars,e,xd)}getShop(e){return this.send(Vn.GetShop,e,Dd)}buyItem(e){return this.send(Vn.BuyItem,e,Id)}};var un={GetMyPartnership:"GetMyPartnership",Apply:"Apply",AcceptInvite:"AcceptInvite",GetStats:"GetStats",GetPayouts:"GetPayouts",ListCreators:"ListCreators"},KT={Off:"Off",InviteOnly:"InviteOnly",Moderated:"Moderated",Auto:"Auto"},QT={Applied:"Applied",Invited:"Invited",Active:"Active",Rejected:"Rejected",Removed:"Removed"},$T={ProgramOff:"PARTNER_PROGRAM_OFF",ApplicationsClosed:"PARTNER_APPLICATIONS_CLOSED",SignInRequired:"PARTNER_SIGN_IN_REQUIRED",AlreadyPartner:"PARTNER_ALREADY",AlreadyApplied:"PARTNER_ALREADY_APPLIED",Removed:"PARTNER_REMOVED",NoInvite:"PARTNER_NO_INVITE",BadInput:"PARTNER_BAD_INPUT",NotPartner:"PARTNER_NOT_FOUND",Conflict:"PARTNER_CONFLICT"},JT=zod.z.enum(["Off","InviteOnly","Moderated","Auto"]).catch("Off"),ZT=zod.z.enum(["Applied","Invited","Active","Rejected","Removed"]),pu=zod.z.record(zod.z.string(),zod.z.string()).nullish(),YT=zod.z.object({Mode:JT,DefaultSharePercent:zod.z.number().nullish(),Terms:pu,AskLinks:zod.z.boolean().nullish(),AskAbout:zod.z.boolean().nullish(),AskFollowers:zod.z.boolean().nullish(),CanApply:zod.z.boolean().nullish()}).passthrough(),XT=zod.z.object({PublicName:zod.z.string().nullish(),Links:zod.z.array(zod.z.string()).nullish(),About:zod.z.string().nullish(),Followers:zod.z.number().nullish(),SubmittedAt:zod.z.string().nullish()}).passthrough(),ew=zod.z.object({FeatureKey:zod.z.string(),Name:pu,PreviewUrl:zod.z.string().nullish(),PreviewType:zod.z.string().nullish()}).passthrough(),No=zod.z.object({Program:YT,Status:ZT.nullish(),SharePercent:zod.z.number().nullish(),Templates:zod.z.array(ew).nullish(),DecisionNote:zod.z.string().nullish(),Application:XT.nullish(),SignInRequired:zod.z.boolean().nullish()}).passthrough(),zg=zod.z.object({Days:zod.z.number(),ByDay:zod.z.array(zod.z.object({Day:zod.z.string(),Generations:zod.z.number(),Paid:zod.z.number(),PartnerCredits:zod.z.number()}).passthrough()).nullish(),ByTemplate:zod.z.array(zod.z.object({FeatureKey:zod.z.string(),Name:pu,Generations:zod.z.number(),Paid:zod.z.number(),PartnerCredits:zod.z.number()}).passthrough()).nullish(),Generations:zod.z.number(),PeriodCredits:zod.z.number(),AccruedCredits:zod.z.number(),PaidOutCredits:zod.z.number(),BalanceCredits:zod.z.number()}).passthrough(),Mg=zod.z.object({Payouts:zod.z.array(zod.z.object({Credits:zod.z.number(),Note:zod.z.string().nullish(),PaidAt:zod.z.string()}).passthrough()).nullish()}).passthrough(),tw=zod.z.object({Id:zod.z.string(),Name:zod.z.string(),Links:zod.z.array(zod.z.string()).nullish(),FeatureKeys:zod.z.array(zod.z.string()).nullish()}).passthrough(),Og=zod.z.object({Creators:zod.z.array(tw).nullish()}).passthrough();var _o=class extends B{constructor(e){super(e,"Partners");}getMyPartnership(e){return this.send(un.GetMyPartnership,e,No)}apply(e){return this.send(un.Apply,e,No)}acceptInvite(e){return this.send(un.AcceptInvite,e,No)}getStats(e){return this.send(un.GetStats,e,zg)}getPayouts(e){return this.send(un.GetPayouts,e,Mg)}listCreators(e){return this.send(un.ListCreators,e,Og)}};var Vo=class extends B{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(br.RequestAdPermit,e,Pd)}completeView(e){return this.send(br.CompleteView,e,vd)}};var Fo=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Pe.GetFriendsList,e,fs)}getIncomingRequests(e){return this.send(Pe.GetIncomingRequests,e,fs)}getOutgoingRequests(e){return this.send(Pe.GetOutgoingRequests,e,fs)}getRecommendedFriends(e){return this.send(Pe.GetRecommendedFriends,e,fs)}sendFriendRequest(e){return this.send(Pe.SendFriendRequest,e,gs)}acceptFriendRequest(e){return this.send(Pe.AcceptFriendRequest,e,gs)}declineFriendRequest(e){return this.send(Pe.DeclineFriendRequest,e,gs)}removeFriend(e){return this.send(Pe.RemoveFriend,e,gs)}getPlayerProfile(e){return this.send(Pe.GetPlayerProfile,e,Md)}getInbox(e){return this.send(Pe.GetInbox,e,Od)}markInboxSeen(e){return this.send(Pe.MarkInboxSeen,e,ys)}getInboxUnread(e){return this.send(Pe.GetInboxUnread,e,ys)}follow(e){return this.send(Pe.Follow,e,sn)}unfollow(e){return this.send(Pe.Unfollow,e,sn)}getFollowers(e){return this.send(Pe.GetFollowers,e,Pr)}getFollowing(e){return this.send(Pe.GetFollowing,e,Pr)}block(e){return this.send(Pe.Block,e,sn)}unblock(e){return this.send(Pe.Unblock,e,sn)}getBlocked(e){return this.send(Pe.GetBlocked,e,Pr)}react(e){return this.send(Pe.React,e,sn)}unreact(e){return this.send(Pe.Unreact,e,sn)}getMyReactions(e){return this.send(Pe.GetMyReactions,e,qd)}getEntityStates(e){return this.send(Pe.GetEntityStates,e,Ed)}addComment(e){return this.send(Pe.AddComment,e,vr)}editComment(e){return this.send(Pe.EditComment,e,vr)}deleteComment(e){return this.send(Pe.DeleteComment,e,Ld)}getComments(e){return this.send(Pe.GetComments,e,Ud)}report(e){return this.send(Pe.Report,e,Bd)}};var nw={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Dn=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),sw=zod.z.object({BoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:me.nullish(),Effect:Dn.nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),jo=zod.z.object({Schedule:Se.nullish(),Gate:te.nullish()}).passthrough(),hu=zod.z.object({Availability:J.nullish(),Effects:J.nullish()}).passthrough(),iw=zod.z.object({ScheduledBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Effects:zod.z.array(Dn).nullish(),Availability:jo.nullish(),Presets:hu.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rw=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(Dn).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ow=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Phases:zod.z.array(rw).nullish(),Availability:jo.nullish(),Presets:hu.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),aw=zod.z.object({TriggeredBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Sources:zod.z.array(ft).nullish(),Effects:zod.z.array(Dn).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:jo.nullish(),Presets:hu.nullish()}).passthrough(),lw=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),uw=zod.z.object({Effects:zod.z.array(Dn).nullish()}).passthrough(),cw=zod.z.object({Availability:zod.z.record(zod.z.string(),jo).nullish(),Effects:zod.z.record(zod.z.string(),uw).nullish()}).passthrough(),pw=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),lw).nullish()}).passthrough(),Wo=zod.z.object({Definitions:zod.z.record(zod.z.string(),sw).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),iw).nullish(),BoostChains:zod.z.record(zod.z.string(),ow).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),aw).nullish(),Settings:pw.nullish(),Presets:cw.nullish()}).passthrough(),Eg=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:Dn.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:u.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:u.nullish()}).passthrough();var qg=zod.z.object({ServerTimeUtc:u.nullish(),Active:zod.z.record(zod.z.string(),Eg).nullish()}),Ug=zod.z.object({CreditsConfirmation:Re.nullish(),ServerTimeUtc:u.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:Eg.nullish(),Resources:O.nullish()}),hw={Scheduled:"Scheduled",Chain:"Chain"},dw=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),Effects:zod.z.array(Dn).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Lg=zod.z.object({ServerTimeUtc:u.nullish(),Windows:zod.z.array(dw).nullish()}),In={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Ho=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(In.GetDefinitions,e,Wo)}getActive(e){return this.send(In.GetActive,e,qg)}getActiveWindows(e){return this.send(In.GetActiveWindows,e,Lg)}activate(e){return this.send(In.Activate,e,ke(Ug))}cleanupExpired(e){return this.send(In.CleanupExpired,e,Qe)}};var Ko=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(kt.GetUserCustomDataDefinitions,e,Ir)}getMyUserCustomData(e){return this.send(kt.GetMyUserCustomData,e,Ad)}getPublicUserCustomDataOf(e){return this.send(kt.GetPublicUserCustomDataOf,e,Cl)}setPrivateData(e){return this.send(kt.SetPrivateData,e,Sl)}setPublicData(e){return this.send(kt.SetPublicData,e,Sl)}deleteKey(e){return this.send(kt.DeleteKey,e,Qe)}batchSet(e){return this.send(kt.BatchSet,e,Td)}batchDelete(e){return this.send(kt.BatchDelete,e,wd)}batchGetPublicUserCustomDataOf(e){return this.send(kt.BatchGetPublicUserCustomDataOf,e,kd)}};var mw={Static:"Static",Runtime:"Runtime"},fw={Public:"Public",Private:"Private"},gw=zod.z.enum(["Client","Server","System"]).catch("Client"),yw=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),Rw=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:gw.nullish(),ExpiresAt:u.nullish()}).passthrough(),Bg=zod.z.record(zod.z.string(),Rw),du=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:Bg.nullish(),Runtime:Bg.nullish(),NotModified:zod.z.boolean().nullish()}),Cw=zod.z.object({KeyID:zod.z.string(),Scope:zod.z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:zod.z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:yw.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Qo=zod.z.object({Keys:zod.z.record(zod.z.string(),Cw).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),Is={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var $o=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Is.GetTitleCustomDataDefinitions,e,Qo)}getPublicTitleData(e){return this.send(Is.GetPublicTitleData,e,du)}getPublicTitleDataKeys(e){return this.send(Is.GetPublicTitleDataKeys,e,du)}};var Gg=zod.z.object({Theme:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Radius:zod.z.number().nullish(),ButtonRadius:zod.z.number().nullish(),Outline:zod.z.number().nullish(),Background:zod.z.string().nullish(),MotionSpeed:zod.z.number().nullish(),MotionIntensity:zod.z.number().nullish(),Particles:zod.z.boolean().nullish(),SoundSet:zod.z.string().nullish()}).passthrough();var Sw={Mesh:"Mesh",Host:"Host"},mu=zod.z.enum(["Mesh","Host"]).catch("Mesh"),bw={ServerRelay:"ServerRelay",P2P:"P2P"},fu=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),xw={Public:"Public",Private:"Private"},Dw=zod.z.enum(["Public","Private"]).catch("Public"),Iw={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},Pw=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Ng=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),vw=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),_g=zod.z.object({SystemState:vw.nullish(),DefaultTopology:mu.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:fu.nullish(),AllowCreatorChatOverride:zod.z.boolean().nullish(),MaxPlayersPerRoom:zod.z.number().nullish(),RoomTtlSeconds:zod.z.number().nullish(),MaxRoomLifetimeSeconds:zod.z.number().nullish(),HeartbeatIntervalMs:zod.z.number().nullish(),MemberTimeoutMs:zod.z.number().nullish(),MaxSignalPayloadBytes:zod.z.number().nullish(),MaxChatTextLength:zod.z.number().nullish(),RoomLogCap:zod.z.number().nullish(),VoiceEnabled:zod.z.boolean().nullish(),RecordVoices:zod.z.boolean().nullish(),IceServers:zod.z.array(Ng).nullish()}).passthrough(),Aw=zod.z.object({UserID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),Ready:zod.z.boolean().nullish(),State:zod.z.record(zod.z.string(),zod.z.string()).nullish(),JoinedAt:zod.z.number().nullish(),IsHost:zod.z.boolean().nullish(),LastSeenMs:zod.z.number().nullish()}).passthrough(),Tw=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:mu.nullish(),ChatMode:fu.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),ww=zod.z.object({Seq:zod.z.number().nullish(),Type:Pw.nullish(),FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Payload:zod.z.string().nullish(),Ts:zod.z.number().nullish()}).passthrough(),Ps=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:mu.nullish(),ChatMode:fu.nullish(),Visibility:Dw.nullish(),Status:zod.z.string().nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),Members:zod.z.array(Aw).nullish(),IceServers:zod.z.array(Ng).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Vg=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),Fg=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),gu=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),jg=zod.z.object({Rooms:zod.z.array(Tw).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Wg=zod.z.object({Envelopes:zod.z.array(ww).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Jo=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),ot={CreateRoom:"CreateRoom",JoinRoom:"JoinRoom",LeaveRoom:"LeaveRoom",ListRooms:"ListRooms",GetRoom:"GetRoom",CloseRoom:"CloseRoom",Poll:"Poll",SendSignal:"SendSignal",SendChat:"SendChat",SetMemberState:"SetMemberState",ClaimHost:"ClaimHost",KickMember:"KickMember",UnbanMember:"UnbanMember"};var yu=zod.z.object({TitleCustomData:Qo.nullish(),Character:Qi.nullish(),Item:io.nullish(),Currency:ur.nullish(),Store:mi.nullish(),Lootbox:eu.nullish(),Quest:Vs.nullish(),TimedEvent:Oi.nullish(),Leaderboard:_i.nullish(),Season:ji.nullish(),Reward:nu.nullish(),Collection:Mo.nullish(),Craft:ru.nullish(),DealOffer:nl.nullish(),Premium:Zl.nullish(),TimedBoost:Wo.nullish(),CoopEvent:sr.nullish(),GameLoop:Or.nullish(),Match:cl.nullish(),Challenge:ag.nullish(),Experiment:hf.nullish(),Blockchain:Al.nullish(),Marketplace:Ul.nullish(),Multiplayer:_g.nullish(),UserCustomData:Ir.nullish(),Referral:lu.nullish(),Localization:ff.nullish(),Analytics:ef.nullish(),Social:Gd.nullish(),PlatformBridge:Nd.nullish(),GameSpec:zod.z.string().nullish(),Look:Gg.nullish(),Avatar:Rr.nullish()}).passthrough();var Pn={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Zo=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(Pn.GetTitlePublicConfiguration,e,yu)}getTitlePublicConfigurationExcept(e){return this.send(Pn.GetTitlePublicConfigurationExcept,e,yu)}getCurrencyDefinitions(e){return this.send(Pn.GetCurrencyDefinitions,e,ur)}getItemDefinitions(e){return this.send(Pn.GetItemDefinitions,e,io)}getServerTime(e){return this.send(Pn.GetServerTime,e,Qe)}};var Yo=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(He.GetGameLoops,e,Or)}getBoardDefinition(e,t=false){return this.send(He.GetBoardDefinition,e,Mr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(He.GetBoardDefinitionForLevel,e,Mr,{silent:t})}getUserBoardState(e){return this.send(He.GetUserBoardState,e,jd)}boardLoopRoll(e){return this.send(He.BoardLoopRoll,e,Zd)}boardLoopAttack(e){return this.send(He.BoardLoopAttack,e,em)}boardLoopRaid(e){return this.send(He.BoardLoopRaid,e,Il)}boardLoopRaidFast(e){return this.send(He.BoardLoopRaidFast,e,Il)}boardLoopBuild(e){return this.send(He.BoardLoopBuild,e,tm)}boardSpecialChoose(e){return this.send(He.BoardSpecialChoose,e,ke(nm))}boardSpecialApplyMultiplier(e){return this.send(He.BoardSpecialApplyMultiplier,e,sm)}boardRewardBoostApply(e){return this.send(He.BoardRewardBoostApply,e,Xd)}boardSpecialClaim(e){return this.send(He.BoardSpecialClaim,e,im)}getCommunityChestState(e){return this.send(He.GetCommunityChestState,e,am)}joinOrCreateCommunityChest(e){return this.send(He.JoinOrCreateCommunityChest,e,lm)}claimCommunityChestMilestone(e){return this.send(He.ClaimCommunityChestMilestone,e,Pl)}claimCommunityChestGrandPrize(e){return this.send(He.ClaimCommunityChestGrandPrize,e,Pl)}leaveCommunityChest(e){return this.send(He.LeaveCommunityChest,e,um)}};var kw={Live:"Live",Latest:"Latest",Specific:"Specific"},zw={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},Mw=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),Ow={None:"None",Disabled:"Disabled",NoActiveRevision:"NoActiveRevision",RevisionNotFound:"RevisionNotFound",InvalidFieldName:"InvalidFieldName",RateLimited:"RateLimited",HandlerNotFound:"HandlerNotFound",HandlerDisabled:"HandlerDisabled",Timeout:"Timeout",StatementCountExceeded:"StatementCountExceeded",StackOverflow:"StackOverflow",ApiCallLimitExceeded:"ApiCallLimitExceeded",JavaScriptException:"JavaScriptException",ExecutionError:"ExecutionError"},Ew=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),qw=zod.z.object({Level:Mw,Message:zod.z.string().nullish(),Data:en.nullish()}),Uw=zod.z.object({Error:Ew,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Kg=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:en.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(qw).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:Uw.nullish()}),Ru={Execute:"Execute"};var Xo=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(Ru.Execute,e,Kg)}};var ea=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(rt.GetDefinitions,e,Cm)}getUserState(e){return this.send(rt.GetUserState,e,Sm)}depositToken(e){return this.send(rt.DepositToken,e,bm)}depositNFT(e){return this.send(rt.DepositNFT,e,xm)}requestTokenWithdrawal(e){return this.send(rt.RequestTokenWithdrawal,e,Dm)}requestNFTWithdrawal(e){return this.send(rt.RequestNFTWithdrawal,e,Im)}getTransactionHistory(e){return this.send(rt.GetTransactionHistory,e,Pm)}retryWithdrawal(e){return this.send(rt.RetryWithdrawal,e,vm)}confirmWithdrawal(e){return this.send(rt.ConfirmWithdrawal,e,Am)}donateToDeveloper(e){return this.send(rt.DonateToDeveloper,e,zl)}donateToUsersPool(e){return this.send(rt.DonateToUsersPool,e,zl)}getPlayAccess(e){return this.send(rt.GetPlayAccess,e,ym)}confirmPlayAccess(e){return this.send(rt.ConfirmPlayAccess,e,rn)}};var ta=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Ge.GetDefinitions,e,km)}getGroupedOffers(e){return this.send(Ge.GetGroupedOffers,e,zm)}getOffersByItem(e){return this.send(Ge.GetOffersByItem,e,Ll)}getOffer(e){return this.send(Ge.GetOffer,e,Mm)}getBuyOrders(e){return this.send(Ge.GetBuyOrders,e,Ll)}getMyState(e){return this.send(Ge.GetMyState,e,Vr)}getHistory(e){return this.send(Ge.GetHistory,e,Em)}createListing(e){return this.send(Ge.CreateListing,e,Ss)}cancelListing(e){return this.send(Ge.CancelListing,e,St)}buy(e){return this.send(Ge.Buy,e,St)}marketBuy(e){return this.send(Ge.MarketBuy,e,St)}marketSell(e){return this.send(Ge.MarketSell,e,St)}createAuction(e){return this.send(Ge.CreateAuction,e,Ss)}placeBid(e){return this.send(Ge.PlaceBid,e,Om)}claimAuction(e){return this.send(Ge.ClaimAuction,e,St)}createBuyOrder(e){return this.send(Ge.CreateBuyOrder,e,Ss)}cancelBuyOrder(e){return this.send(Ge.CancelBuyOrder,e,St)}fillBuyOrder(e){return this.send(Ge.FillBuyOrder,e,St)}createDirectTrade(e){return this.send(Ge.CreateDirectTrade,e,Ss)}respondDirectTrade(e){return this.send(Ge.RespondDirectTrade,e,St)}cancelDirectTrade(e){return this.send(Ge.CancelDirectTrade,e,St)}claimBack(e){return this.send(Ge.ClaimBack,e,St)}};var na=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(ot.CreateRoom,e,Ps)}joinRoom(e){return this.send(ot.JoinRoom,e,Ps)}leaveRoom(e,t=false){return this.send(ot.LeaveRoom,e,gu,{keepalive:t})}listRooms(e){return this.send(ot.ListRooms,e,jg)}getRoom(e){return this.send(ot.GetRoom,e,Ps)}closeRoom(e){return this.send(ot.CloseRoom,e,gu)}poll(e){return this.send(ot.Poll,e,Wg)}sendSignal(e){return this.send(ot.SendSignal,e,Jo,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(ot.ClaimHost,e,Ps)}kickMember(e){return this.send(ot.KickMember,e,Vg)}unbanMember(e){return this.send(ot.UnbanMember,e,Fg)}sendChat(e){return this.send(ot.SendChat,e,Jo)}setMemberState(e){return this.send(ot.SetMemberState,e,Jo)}};var Lw={Free:"Free",Price:"Price",Holding:"Holding"},Cu=zod.z.enum(["Free","Price","Holding"]).catch("Free"),Bw={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},Gw=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),Nw={All:"All",Any:"Any"},_w=zod.z.enum(["All","Any"]).catch("All"),Vw={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},Fw=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),jw={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},Ww=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),Hw={Purchase:"Purchase",Free:"Free",Holding:"Holding"},$g=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),Kw={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},Qw={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},$w=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),Jw=zod.z.object({Type:zn.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),MinLevel:zod.z.number().nullish()}).passthrough(),Zw=zod.z.object({Requirements:zod.z.array(Jw).nullish(),Match:_w.nullish(),Mode:Gw.nullish()}).passthrough(),Yw=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Cu.nullish(),Price:he.nullish(),Holding:Zw.nullish()}).passthrough(),Xw=zod.z.object({AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxBytes:zod.z.number().nullish(),MaxCount:zod.z.number().nullish(),Required:zod.z.boolean().nullish()}).passthrough(),ek=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),Xw).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(Cu).nullish(),PricePolicy:_r.nullish(),PublishGate:te.nullish(),PublishFeeOptions:me.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),tk=zod.z.object({Allowed:zod.z.array(ms).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),nk=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),sk=zod.z.object({MaxTitleLength:zod.z.number().nullish(),MaxDescriptionLength:zod.z.number().nullish(),MaxTags:zod.z.number().nullish(),MaxTagLength:zod.z.number().nullish(),MaxMetadataKeys:zod.z.number().nullish(),MaxMetadataValueLength:zod.z.number().nullish(),MaxAccessOptions:zod.z.number().nullish(),ThumbnailMaxBytes:zod.z.number().nullish()}).passthrough(),ik=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Schedule:Se.nullish(),Gate:te.nullish(),Order:zod.z.number().nullish()}).passthrough(),rk=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:te.nullish(),Schedule:Se.nullish(),ContentTypes:zod.z.record(zod.z.string(),ek).nullish(),PricePolicy:_r.nullish(),Commission:ql.nullish(),HoldingPolicy:tk.nullish(),Moderation:nk.nullish(),Limits:sk.nullish(),Featured:zod.z.array(ik).nullish()}).passthrough(),ok=zod.z.object({Acquisitions:zod.z.number().nullish(),Downloads:zod.z.number().nullish(),Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),ReportCount:zod.z.number().nullish(),Remixes:zod.z.number().nullish()}).passthrough(),vn=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:_e.nullish(),Title:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Metadata:zod.z.record(zod.z.string(),zod.z.string()).nullish(),ThumbnailUrl:zod.z.string().nullish(),Visibility:Fw.nullish(),Access:zod.z.array(Yw).nullish(),Status:Ww.nullish(),ModerationNote:zod.z.string().nullish(),Stats:ok.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),PublishedAt:u.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),ak=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Cu.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),Jg=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Order:zod.z.number().nullish()}).passthrough(),lk=zod.z.object({ContentType:zod.z.string().nullish(),MetadataKey:zod.z.string().nullish(),Over:zod.z.number().nullish(),PriceCredits:zod.z.number().nullish(),OfficialAfter:zod.z.number().nullish()}).passthrough();function uk(r,e,t,n={official:false,officialPublished:0}){let s=0;for(let i of r??[]){if(!i||i.ContentType!==e||!((i.PriceCredits??0)>0))continue;let o=i.OfficialAfter;if(!(o!=null&&(!n.official||n.officialPublished<o))){if(i.MetadataKey){let p=Number(t[i.MetadataKey]);if(!Number.isFinite(p)||p<=(i.Over??0))continue}else if(o==null)continue;s=Math.max(s,Math.ceil(i.PriceCredits??0));}}return s}var Zg=zod.z.object({Definitions:rk.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish(),CanPublish:zod.z.record(zod.z.string(),zod.z.boolean()).nullish(),Collections:zod.z.array(Jg).nullish(),CanPublishOfficial:zod.z.boolean().nullish(),PlatformFees:zod.z.array(lk).nullish()}).passthrough(),sa=zod.z.object({Items:zod.z.array(vn).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Yg=zod.z.object({Content:vn.nullish(),AccessState:zod.z.array(ak).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Xg=zod.z.object({Collection:Jg.nullish(),Items:zod.z.array(vn).nullish()}).passthrough(),ey=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:_e.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(vn).nullish()}).passthrough(),Qg=zod.z.object({Role:zod.z.string().nullish(),Index:zod.z.number().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish(),ServerCopy:zod.z.boolean().nullish()}).passthrough(),ty=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(Qg).nullish(),ThumbnailUpload:Qg.nullish(),ExpiresAt:u.nullish()}).passthrough(),ny=zod.z.object({CreditsConfirmation:Re.nullish(),Content:vn.nullish(),Resources:O.nullish()}).passthrough(),Su=zod.z.object({Content:vn.nullish()}).passthrough(),sy=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:$g.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:_t.nullish(),Resources:O.nullish(),CommissionTaken:he.nullish()}).passthrough(),ck=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),iy=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:$w.nullish(),Files:zod.z.array(ck).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:u.nullish()}).passthrough(),pk=zod.z.object({ContentID:zod.z.string().nullish(),Source:$g.nullish(),OptionID:zod.z.string().nullish(),PricePaid:he.nullish(),AcquiredAt:u.nullish(),Content:vn.nullish()}).passthrough(),ry=zod.z.object({Licenses:zod.z.array(pk).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),tt={GetDefinitions:"GetDefinitions",Browse:"Browse",GetContent:"GetContent",GetCollection:"GetCollection",GetCreatorProfile:"GetCreatorProfile",BeginUpload:"BeginUpload",Publish:"Publish",UpdateContent:"UpdateContent",Unpublish:"Unpublish",GetMyContent:"GetMyContent",Acquire:"Acquire",GetDownload:"GetDownload",GetMyLicenses:"GetMyLicenses",GetMyFavorites:"GetMyFavorites"};var ia=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(tt.GetDefinitions,e,Zg)}browse(e){return this.send(tt.Browse,e,sa)}getContent(e){return this.send(tt.GetContent,e,Yg)}getCollection(e){return this.send(tt.GetCollection,e,Xg)}getCreatorProfile(e){return this.send(tt.GetCreatorProfile,e,ey)}beginUpload(e){return this.send(tt.BeginUpload,e,ty)}publish(e){return this.send(tt.Publish,e,ke(ny))}updateContent(e){return this.send(tt.UpdateContent,e,Su)}unpublish(e){return this.send(tt.Unpublish,e,Su)}getMyContent(e){return this.send(tt.GetMyContent,e,sa)}acquire(e){return this.send(tt.Acquire,e,sy)}getDownload(e){return this.send(tt.GetDownload,e,iy)}getMyLicenses(e){return this.send(tt.GetMyLicenses,e,ry)}getMyFavorites(e){return this.send(tt.GetMyFavorites,e,sa)}};var ra=class extends B{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,n,s){return this.send(e,t,n,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,n,s){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,n,{throttleKey:`${o}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,Nm,"defs")}get(e){return this.sendKeyed("Get",e,Gl,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Vm,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,Nl,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Fm,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,_l,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,_l,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,jm,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,Hm,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Wm,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,Km,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,_m,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Qm,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,Gl,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,Nl,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var oa=class{settings;emitter;host;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;credits;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;challenge;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;clan;avatar;partners;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.host=e.host??Ca(),this.settings=Pu(e,this.host),this.emitter=new Zn,this.clientPlatform=e.clientPlatform??this.host.getClientPlatform(),this.acquisition=new fn(this.host),this.acquisition.capture(),this.playtime=new os(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{}),this.host.supports.storePurchases&&this.purchase.restorePending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new $s({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e.fetch,debugLogging:this.settings.debugLogging,throttleMs:e.throttleMs,maxRequestsPerSecond:e.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new Xs(this.emitter),this.cache=new ti(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:n})=>{this.userService.noteStateVersions(t,n);}),this.authStore=new ni(this.host.storage,this.settings.titleID),this.api={authentication:new eo(this),user:new to(this),currency:new no(this),item:new ro(this),store:new oo(this),purchase:new co(this),lootbox:new mo(this),reward:new fo(this),quest:new bo(this),tutorial:new go(this),communityMarketing:new yo(this),chat:new Ro(this),push:new Co(this),localization:new So(this),timedEvent:new xo(this),leaderboard:new Do(this),season:new Io(this),premium:new Po(this),character:new vo(this),match:new Ao(this),challenge:new To(this),craft:new ko(this),ai:new zo(this),collection:new Oo(this),coopEvent:new Eo(this),dealOffer:new qo(this),referral:new Uo(this),mailbox:new Lo(this),clan:new Bo(this),avatar:new Go(this),partners:new _o(this),advertising:new Vo(this),social:new Fo(this),timedBoost:new Ho(this),userCustomData:new Ko(this),titleCustomData:new $o(this),title:new Zo(this),gameLoop:new Yo(this),cloudCode:new Xo(this),blockchain:new ea(this),marketplace:new ta(this),multiplayer:new na(this),workshop:new ia(this),dataCollections:new ra(this),analytics:new Zr(this),experiment:new Yr(this)},this.userService=new li(this),this.cache.attachState(this.userService),this.auth=new ii(this),this.currency=new ci(this),this.item=new pi(this),this.store=new gi(this),this.credits=new yi(this),this.purchase=new Ri(this),this.checkout=new Ci(this),this.lootbox=new Si(this),this.reward=new xi(this),this.quest=new Mi(this),this.tutorial=new Ii(this),this.communityMarketing=new Pi(this),this.chat=new Ti(this),this.push=new wi(this),this.localization=new zi(this),this.timedEvent=new qi(this),this.leaderboard=new Vi(this),this.season=new Wi(this),this.premium=new Hi(this),this.character=new $i(this),this.match=new Ji(this),this.challenge=new Zi(this),this.craft=new Yi(this),this.ai=new er(this),this.collection=new tr(this),this.coopEvent=new ir(this),this.dealOffer=new ar(this),this.referral=new lr(this),this.mailbox=new hr(this),this.clan=new gr(this),this.avatar=new Cr(this),this.partners=new Sr(this),this.ads=new xr(this),this.social=new Ar(this),this.timedBoost=new Tr(this),this.userCustomData=new wr(this),this.titleCustomData=new kr(this),this.title=new zr(this),this.gameLoop=new qr(this),this.cloudCode=new Ur(this),this.blockchain=new Br(this),this.marketplace=new Fr(this),this.multiplayer=new jr(this),this.workshop=new Wr(this),this.dataCollections=new Kr(this),this.analytics=new $r(this),this.experiments=new Jr(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.host.getFullURL(),RelatedEntityID:V()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var aa=class{ctx;constructor(e){this.ctx=new oa(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,n={}){let s=this.ctx.buildAuthedBaseRequest(),i=an(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(i,{...s,...n},zod.z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get challenge(){return this.ctx.challenge}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get clan(){return this.ctx.clan}get avatar(){return this.ctx.avatar}get partners(){return this.ctx.partners}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get host(){return this.ctx.host}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function dk(r){return new aa(r)}var oy="idos_sso",ay="state",bu="idos:sso:state",mk="https://idosgames.com/sso/",fk=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],gk=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function yk(){if(typeof window>"u")return false;let{origin:r}=window.location;return fk.includes(r)||gk.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function Rk(){if(typeof window>"u")return null;let r=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!r)return null;let e=new URLSearchParams(r),t=e.get(oy);if(!t)return null;let n=e.get(ay)??"",s=Dk();return Pk(e),Ik(),s&&n!==s?null:{code:t,state:n}}function Ck(r){if(typeof window>"u")return;let e=r.returnTo??Sk(),t=bk();xk(t);let n=new URL(r.ssoUrl??mk);n.searchParams.set("title",r.titleID),n.searchParams.set("return_to",e),n.searchParams.set("state",t),window.location.assign(n.toString());}function Sk(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function bk(){let r=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(r);else for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*256);return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function xk(r){try{window.sessionStorage.setItem(bu,r);}catch{}}function Dk(){try{return window.sessionStorage.getItem(bu)}catch{return null}}function Ik(){try{window.sessionStorage.removeItem(bu);}catch{}}function Pk(r){r.delete(oy),r.delete(ay);let e=r.toString(),{pathname:t,search:n}=window.location;window.history.replaceState(null,"",`${t}${n}${e?`#${e}`:""}`);}var vk={EMAIL_SENDER_NOT_CONFIGURED:"Sign-in by e-mail is unavailable in this game right now. Try another way to sign in.",INVALID_VERIFICATION_CODE:"That code is not right. Check the e-mail and try again.",VERIFICATION_CODE_ATTEMPTS_EXCEEDED:"Too many wrong attempts. Ask for a new code.",INCORRECT_EMAIL_OR_PASSWORD:"Wrong e-mail or password.",INCORRECT_EMAIL:"That does not look like an e-mail address.",PASSWORD_LENGTH_INVALID:"The password must be 8 to 100 characters long.",TOO_MANY_FAILED_ATTEMPTS:"Too many attempts. Please try again a little later.",RATE_LIMIT_EXCEEDED:"Too many requests. Please try again in a moment.",APPLE_EMAIL_MISSING:"Apple did not share an e-mail address. Try again and allow it, or use another way to sign in.",INVALID_WALLET_SIGNATURE:"The signature does not match the wallet. Please try again.",WALLET_CHALLENGE_EXPIRED:"The request expired. Please try again.",WALLET_CHANGES_TOO_FREQUENT:"Too many wallets were changed this week. Try again in a few days.",WALLET_UNLINK_COOLDOWN:"This wallet was unlinked from another account less than 7 days ago. Try again after the 7 days.",PLAY_ACCESS_GUEST_DISABLED:"Guest play is off in this game. Sign in to link a crypto wallet.",PLAY_ACCESS_WALLET_LOGIN_ONLY:"This game can only be entered with a crypto wallet or your iDos Games account.",PLAY_ACCESS_WALLET_USED_BY_ANOTHER_ACCOUNT:"This wallet already plays with another account.",PLAY_ACCESS_WALLET_REQUIRED:"Link a crypto wallet to play.",PLAY_ACCESS_WALLET_NETWORK_NOT_GATED:"This wallet's network is not accepted here. Link a wallet of the required network.",PLAY_ACCESS_REQUIRED:"Check your balance to continue.",PLAY_ACCESS_CHECK_FAILED:"Could not check your balance right now. Please try again in a moment."};function Ak(r,e="Something went wrong. Please try again."){return r?vk[r]??r:e}function Tk(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function wk(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function kk(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function uy(r,e,t,n=1){if(!r)return e;let s=r.Base??e,i=Math.max(0,t-n),o;switch(r.Shape??"Flat"){case "PerStep":o=s+(r.PerStep??0)*i;break;case "PerStepRate":o=s*(1+(r.PerStepRate??0)*i);break;case "Geometric":o=s*Math.pow(1+(r.GrowthRate??0),i);break;case "Table":o=s*ly(r,t,1);break;case "TableAbsolute":o=ly(r,t,s);break;default:o=s;break}return Number.isNaN(o)?s:(r.MinResult!=null&&o<r.MinResult&&(o=r.MinResult),r.MaxResult!=null&&o>r.MaxResult&&(o=r.MaxResult),o)}function zk(r,e,t=1){return uy(r,1,e,t)}function Mk(r){if(!r)return false;switch(r.Shape??"Flat"){case "PerStep":return (r.PerStep??0)!==0;case "PerStepRate":return (r.PerStepRate??0)!==0;case "Geometric":return (r.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return cy(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function Ok(r){if(Number.isNaN(r)||r<=0)return 0;if(!Number.isFinite(r))return Number.MAX_SAFE_INTEGER;let e=Math.round(r);return Math.abs(r-e)<=1e-9*Math.max(1,Math.abs(r))?e:Math.ceil(r)}function cy(r){if(!r)return [];let e=[];for(let t of r)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function ly(r,e,t){let n=cy(r.Points);if(n.length===0)return t;let s=null,i=null,o=null;for(let p of n)(o===null||p.AtStep>o.AtStep)&&(o=p),p.AtStep<=e&&(s===null||p.AtStep>=s.AtStep)&&(s=p),p.AtStep>e&&(i===null||p.AtStep<i.AtStep)&&(i=p);if(s===null)return t;if(i===null){let p=r.TailGrowthRate??0;return p===0?o.Value:o.Value*Math.pow(1+p,e-o.AtStep)}switch(r.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(i.AtStep-s.AtStep);return s.Value+p*(i.Value-s.Value)}case "Geometric":{if(s.Value<=0||i.Value<=0){let m=(e-s.AtStep)/(i.AtStep-s.AtStep);return s.Value+m*(i.Value-s.Value)}let p=(e-s.AtStep)/(i.AtStep-s.AtStep);return s.Value*Math.pow(i.Value/s.Value,p)}default:return s.Value}}function py(r,e){return e?.BonusMode??r?.SetSettings?.BonusMode??"Cumulative"}function hy(r,e,t){if(!r?.Bonuses||e<=0)return [];let n=r.Bonuses.filter(s=>!!s&&(s.Pieces??0)>0&&(s.Pieces??0)<=e).sort((s,i)=>(s.Pieces??0)-(i.Pieces??0));if(n.length===0)return [];if(t==="HighestOnly"){let s=n[n.length-1]?.Pieces??0;return n.filter(i=>(i.Pieces??0)===s)}return n}function Ek(r,e){let t=e?.Sets,n=e?.Catalogs;if(!t||!r||!n||Object.keys(t).length===0)return [];let s=new Map;for(let[p,m]of Object.entries(r)){if(!p||p.startsWith("@")||!m?.ItemID)continue;let j=Uk(n,m.ItemID,m.CatalogID??null)?.Metadata?.CollectionID;!j||!(j in t)||s.set(j,(s.get(j)??0)+1);}let i=[...s.keys()].sort((p,m)=>p<m?-1:p>m?1:0),o=[];for(let p of i){let m=t[p];if(!m)continue;let g=s.get(p)??0,j=py(e,m);o.push({SetID:p,Definition:m,Pieces:g,Mode:j,ActiveTiers:hy(m,g,j)});}return o}function qk(r,e){if(!r||!e)return 0;let t=0;for(let n of Object.values(r))for(let s of Object.values(n?.Items??{}))s?.Metadata?.CollectionID===e&&t++;return t}function Uk(r,e,t){if(t){let s=r[t]?.Items?.[e];if(s)return s}let n=null;for(let s of Object.values(r)){let i=s?.Items?.[e];if(i){if(n)return null;n=i;}}return n}var Lk={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},xu=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),Bk={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Gk=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),Nk=zod.z.object({PlacementID:zod.z.string().nullish(),Type:xu.nullish(),Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),CreditsRewarded:zod.z.number().nullish(),AllowedProviderIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),_k=zod.z.object({DefaultCreditsPerView:zod.z.number().nullish(),MaxCreditsBalance:zod.z.number().nullish(),DailyCreditEarnCap:zod.z.number().nullish(),DailyViewCap:zod.z.number().nullish(),MinSecondsBetweenViews:zod.z.number().nullish()}).passthrough(),Vk=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),Fk=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:Gk.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),jk=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),Wk=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),Hk=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),DisableInterstitials:zod.z.boolean().nullish(),DisableBanners:zod.z.boolean().nullish(),DisableAppOpen:zod.z.boolean().nullish()}).passthrough(),Kk=zod.z.object({RequirePersonalizedAdsConsent:zod.z.boolean().nullish(),RequireTrackingConsent:zod.z.boolean().nullish(),CurrentPolicyVersion:zod.z.string().nullish(),RegulatedRegions:zod.z.array(zod.z.string()).nullish()}).passthrough(),Qk=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),$k=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:xu.nullish()}).passthrough(),Jk={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},Zk=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),Yk=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:Zk.nullish(),Enabled:zod.z.boolean().nullish(),Priority:zod.z.number().nullish(),AndroidAppID:zod.z.string().nullish(),IosAppID:zod.z.string().nullish(),WebAppID:zod.z.string().nullish(),Units:zod.z.record(zod.z.string(),$k).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),Nk).nullish(),Providers:zod.z.record(zod.z.string(),Yk).nullish(),RewardedVideo:_k.nullish(),Interstitial:Vk.nullish(),Banner:Fk.nullish(),AppOpen:jk.nullish(),FrequencyCapping:Wk.nullish(),PremiumAdReductions:zod.z.array(Hk).nullish(),Consent:Kk.nullish(),Verification:Qk.nullish()}).passthrough();var Xk=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),ez=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:u.nullish(),LastCompletedAt:u.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),tz=zod.z.object({Date:u.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),nz=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:u.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),sz=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:u.nullish(),ConsentRevokedAt:u.nullish()}).passthrough(),iz=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:xu.nullish(),IssuedAt:u.nullish(),ExpiresAt:u.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),rz=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:u.nullish()}).passthrough();zod.z.object({Credits:Xk.nullish(),Placements:zod.z.record(zod.z.string(),ez).nullish(),Daily:tz.nullish(),Session:nz.nullish(),LastImpressionAt:u.nullish(),LastInterstitialAt:u.nullish(),LastRewardedAt:u.nullish(),LastAppOpenAt:u.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:u.nullish(),Consent:sz.nullish(),PendingRequests:zod.z.record(zod.z.string(),iz).nullish(),FraudFlags:rz.nullish(),UpdatedAt:u.nullish()}).passthrough();
2
+ exports.AIAction=We;exports.AIErrorCode=JS;exports.AIGenerationStatus=yn;exports.AIModality=tn;exports.AVATAR_MAX_USERS=yr;exports.AVATAR_SHOP_PAGE_SIZE=CD;exports.AcquisitionCapture=fn;exports.AdProviderKind=Jk;exports.AdType=Lk;exports.AdvertisingAction=br;exports.AnalyticsAction=Wl;exports.AnalyticsDropReason=bv;exports.AnalyticsEventNaming=jl;exports.AnalyticsLimits=Lt;exports.AttackOutcome=sI;exports.AuthType=Ue;exports.AuthenticationAction=Ke;exports.AutomaticEvent=on;exports.AvatarAction=Vn;exports.AvatarErrors=RD;exports.BannerPosition=Bk;exports.BlockchainAction=rt;exports.BlockchainNetworkType=QI;exports.BlockchainOperationCategory=hm;exports.BlockchainTransactionStatus=sP;exports.BlockchainTransactionType=YI;exports.BodyPart=Dx;exports.BoostWindowKind=hw;exports.BrowserFileStore=cn;exports.BrowserStorage=pn;exports.CLAN_DEFAULT_KIND_ID=mr;exports.ChallengeAction=Kn;exports.ChallengeMode=dT;exports.CharacterAction=Je;exports.ChatAction=st;exports.ChatAuthorType=BC;exports.ChatBlockedTermAction=UC;exports.ChatChannelType=zC;exports.ChatDirectAudience=EC;exports.ChatPartitioning=MC;exports.ChatReportReason=NC;exports.ClanAction=Be;exports.ClanCompetitionType=Wx;exports.ClanErrors=jx;exports.ClanInviteType=Vx;exports.ClanJoinMode=Nx;exports.ClanPermission=Fx;exports.ClanRelation=Hx;exports.ClientPlatform=Ne;exports.CloudCodeAction=Ru;exports.CloudCodeErrorCode=Ow;exports.CloudCodeLogLevel=zw;exports.CloudCodeRevisionSelection=kw;exports.CollectionAction=et;exports.CommissionSink=OP;exports.CommunityChestMemberStatus=GI;exports.CommunityChestStatus=BI;exports.CommunityCreatorStatus=tT;exports.CommunityMarketingAction=xn;exports.CommunityMetricKind=sT;exports.CommunityParticipationMode=XA;exports.CommunityPayoutCurrencyKind=nT;exports.ConversionRateMode=Qb;exports.CoopEventAction=wt;exports.CoopGroupStatus=pb;exports.CoopMemberStatus=hb;exports.CraftAction=wo;exports.CraftInputSelectionMode=vT;exports.CraftOutputLevelMode=IT;exports.CraftOutputLevelOverflow=TT;exports.CraftType=DT;exports.CreditsConfirmationStatus=ls;exports.CreditsError=uC;exports.CurrencyAction=hs;exports.CurrencyStatus=Kb;exports.CurrencyType=Dt;exports.CurveInterpolation=Zy;exports.CurveShape=$y;exports.CustomDataBucket=Wt;exports.CustomDataValueType=kD;exports.CustomDataWriter=AD;exports.DEFAULT_BASE_URL=Iu;exports.DataAccessMode=XP;exports.DataCollectionKind=$P;exports.DataCollectionSchemaMode=av;exports.DataCollectionsAction=gv;exports.DataCounterKind=sv;exports.DataFieldType=ZP;exports.DataFieldVisibility=YP;exports.DataOwnerDeletedPolicy=rv;exports.DataRefKind=tv;exports.DealComparisonOperator=kb;exports.DealNodeRuntimeStatus=xb;exports.DealNodeType=wb;exports.DealOfferAction=qt;exports.DealOfferActivationStatus=bb;exports.EVENT_NAME_PATTERN=Qr;exports.EnvelopeType=Iw;exports.EventTokenType=gy;exports.ExperimentAction=Ql;exports.ExperimentGoalKind=Mv;exports.FRIENDS_FROM_PLATFORM=KD;exports.FodderSelectionMode=Wv;exports.FodderValuationMode=Fv;exports.FriendActionStatus=OD;exports.FriendSource=ED;exports.GameLoopAction=He;exports.IDosGamesClient=aa;exports.IapProductType=uA;exports.IapPurchaseStatus=DA;exports.IapStoreValues=fy;exports.ItemAction=so;exports.ItemSetBonusMode=nA;exports.KycStatus=XI;exports.KycTier=tP;exports.LeaderboardAction=Ye;exports.LocalizationAction=Xr;exports.LocalizationMissingKeyMode=Lv;exports.LootboxAction=ho;exports.MAILBOX_COUNTER_CAP=mx;exports.MailboxAction=ht;exports.MailboxCategory=lx;exports.MailboxErrors=dx;exports.MailboxLetterSource=ux;exports.MailboxRewardModule=px;exports.MarketGoodsType=Nr;exports.MarketOfferStatus=MP;exports.MarketOfferType=zP;exports.MarketplaceAction=Ge;exports.MatchAction=Ut;exports.MatchStatus=Ix;exports.MemoryFileStore=An;exports.MemoryHost=ts;exports.MemoryStorage=Xn;exports.MultiplayerAction=ot;exports.MultiplayerChatMode=bw;exports.MultiplayerTopology=Sw;exports.NATIVE_HOST_GLOBAL=Au;exports.NATIVE_HOST_PROTOCOL=ua;exports.NativeHost=ss;exports.OFFER_NOT_IN_ROTATION=wC;exports.PLATFORM_AD_MESSAGES=fa;exports.PLATFORM_AD_PROVIDER=yl;exports.PLATFORM_BRIDGE_ACK=zu;exports.PLATFORM_CREDITS_CONFIRM_FINAL=ky;exports.PLATFORM_CREDITS_CONFIRM_MESSAGES=ga;exports.PLATFORM_ORIGINS=It;exports.PLATFORM_PAGE_UNAVAILABLE=Ls;exports.PLATFORM_SIGN_IN_MESSAGES=ha;exports.PLATFORM_TOPUP_MESSAGES=ma;exports.PLATFORM_TRADE_MESSAGES=ya;exports.PartnerErrors=$T;exports.PartnerProgramMode=KT;exports.PartnerStatus=QT;exports.PartnersAction=un;exports.PeerPayoutSource=ox;exports.PeerPayoutStatus=ax;exports.PlatformFriendsMode=$D;exports.PlatformProfileMode=QD;exports.PlayAccessMode=hP;exports.PlayerExperimentStatus=qv;exports.PlaytimeTracker=os;exports.PremiumAction=Sn;exports.PurchaseAction=bn;exports.PushAction=_n;exports.PushPermissionState=it;exports.PushTopic=eS;exports.PushTransport=YC;exports.QuestAction=At;exports.QuestObjectiveSource=lR;exports.QuestPrerequisiteMode=cR;exports.QuestStatus=rR;exports.RaidMode=tI;exports.ReferralAction=ln;exports.ResourceEntryType=ks;exports.RewardAction=Bt;exports.RewardWindowBoost=GA;exports.RoomVisibility=xw;exports.SITE_FRAME_HIDDEN_MESSAGE=Fu;exports.SKIN_ALREADY_OWNED=QS;exports.SKIN_SLOT=Ja;exports.ScheduleMode=yy;exports.SeasonAction=Xt;exports.SocialAction=Pe;exports.SocialContentStatus=ND;exports.SocialEntityType=LD;exports.SocialInboxVerb=_D;exports.SocialReactionKind=BD;exports.SocialReportReason=GD;exports.SpecialChoiceMode=nI;exports.StoreAction=Ft;exports.StoreRotationMode=hC;exports.StoreType=aA;exports.TimedBoostAction=In;exports.TimedBoostStackingPolicy=nw;exports.TimedEventAction=Rt;exports.TitleAction=Pn;exports.TitleCustomDataAction=Is;exports.TitleDataBucket=fw;exports.TitleDataScope=mw;exports.TradeOfferStatus=ET;exports.TransactionDirection=iP;exports.TutorialAction=gt;exports.TutorialBoardAction=PR;exports.TutorialFlowStatus=xR;exports.TutorialGateMode=Fy;exports.TutorialRestartPolicy=SR;exports.TutorialScriptModule=IR;exports.TutorialStepCompletionMode=RR;exports.TypedEmitter=Zn;exports.UserAction=bt;exports.UserCustomDataAction=kt;exports.WalletGateBalanceSource=uP;exports.WalletLinkType=JI;exports.WebHost=rs;exports.WorkshopAccessMode=Lw;exports.WorkshopAccessVia=Qw;exports.WorkshopAction=tt;exports.WorkshopContentStatus=jw;exports.WorkshopHoldingMatch=Nw;exports.WorkshopHoldingMode=Bw;exports.WorkshopLicenseSource=Hw;exports.WorkshopSort=Kw;exports.WorkshopVisibility=Vw;exports.activeSetTiers=hy;exports.askPlatformPage=Pt;exports.authErrorText=Ak;exports.beginSsoRedirect=Ck;exports.claimedMilestoneIDs=wk;exports.countSetMembers=qk;exports.createDefaultHost=Ca;exports.createIDosGamesClient=dk;exports.cryptoShortfallFromError=Un;exports.curveMultiplier=zk;exports.defineView=QR;exports.describeUserAgent=nf;exports.effectiveSetMode=py;exports.evaluateCurve=uy;exports.getTelegramWebApp=Qt;exports.grantedPremiumTiers=kk;exports.isAIGenerationTerminal=ps;exports.isCurveConfigured=Mk;exports.isFail=Gy;exports.isMilestoneClaimed=Tk;exports.isOk=By;exports.isPlatformParentOrigin=hn;exports.isReservedSlot=LS;exports.isSsoAvailable=yk;exports.normalizeBlockchainCategory=Lr;exports.parseAIErrorCode=ZS;exports.platformTradeUrl=Ra;exports.readNativeHostGlobal=ca;exports.readSsoCodeFromUrl=Rk;exports.resolveItemSets=Ek;exports.roundAmount=Ok;exports.shareFallbackText=ns;exports.where=Rv;exports.workshopPlatformFee=uk;exports.zPaymentProof=lC;exports.zPriceOption=hi;exports.zPriceOptions=me;