@idosgames/core 0.26.2 → 0.26.3
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/{VoiceController-0Lyo_Tcb.d.ts → VoiceController-CEs7dzqz.d.cts} +27 -3
- package/dist/{VoiceController-C_GJOxvz.d.cts → VoiceController-jjr1_vwJ.d.ts} +27 -3
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/realtime/index.d.cts +2 -2
- package/dist/realtime/index.d.ts +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var zod=require('zod'),Zt=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Zt__default=/*#__PURE__*/_interopDefault(Zt);var zi=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,n=>{i(),t(n);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let n of [...i])n(t);}removeAllListeners(){this.listeners.clear();}};function cf(){let s=new Map;return {get:e=>s.get(e)??null,set:(e,t)=>{s.set(e,t);},remove:e=>{s.delete(e);}}}function xl(){return pf()??cf()}function pf(){try{let s=globalThis.localStorage;if(!s)return null;let e="__idos_probe__";return s.setItem(e,"1"),s.removeItem(e),{get:t=>{try{return s.getItem(t)}catch{return null}},set:(t,i)=>{try{s.setItem(t,i);}catch{try{s.removeItem(t);}catch{}}},remove:t=>{try{s.removeItem(t);}catch{}}}}catch{return null}}var bl="https://api.idosgames.com";function Dl(s){return {titleID:s.titleID,titleTemplateID:s.titleTemplateID??"default",buildKey:s.buildKey??"",baseUrl:(s.baseUrl??bl).replace(/\/+$/,""),devBuild:s.devBuild??false,debugLogging:s.debugLogging??false,configStorage:s.configStorage??xl(),locale:s.locale??df(),appVersion:s.appVersion??""}}function df(){try{return globalThis.navigator?.language??""}catch{return ""}}var li=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{}}},ui=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);}};function ci(){return globalThis.Telegram?.WebApp??null}function G(){return crypto.randomUUID()}var Il="idos_device_id",pi=class{storage;constructor(e=new li){this.storage=e;}getPlatform(){return ci()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=ci()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=ci()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(Il);return e||(e=G(),this.storage.setString(Il,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let t=ci();if(t?.openTelegramLink){t.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let t=ci();if(t?.openInvoice){t.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let t=globalThis;typeof t.showAd=="function"&&await t.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var po="idos_acq",Pl=["gclid","fbclid","ttclid","msclkid","yclid"],hf=["ref","r"],mf=["ref_","ref-","ref=","r_","r-"];var $t=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();ff(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},n=Rf(this.platform.getDeviceModel());return n&&(i.OsVersion=n),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(po);}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 i=Al(Tl(t));if(i)return i}return Ji(t)}readFromEnvironment(){let e={},t=Tl(this.platform.getFullURL());Ht(e,"UtmSource",t.get("utm_source")),Ht(e,"UtmMedium",t.get("utm_medium")),Ht(e,"UtmCampaign",t.get("utm_campaign")),Ht(e,"UtmTerm",t.get("utm_term")),Ht(e,"UtmContent",t.get("utm_content")),Ht(e,"ClaimToken",t.get("idos_click"));for(let y of Pl){let V=t.get(y);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",n=yf(i);if(n){for(let y of gf)Ht(e,y,n.get(wl[y])??null);for(let y of Pl){let V=n.get(y);if(V){e.ClickID=V;break}}}let r=Ji(n?n.get("ref")??n.get("r")??"":i),o=Al(t),c=r||o;c&&(e.ReferralCode=c,e.ChannelHint=r?"telegram":"query");let h=this.platform.getReferrer?.();return h&&(e.Referrer=h),e}read(){try{let e=this.platform.storage.getString(po);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.platform.storage.setString(po,JSON.stringify(e));}catch{}}};function ff(s){return !!(s.UtmSource||s.UtmMedium||s.UtmCampaign||s.ClickID||s.Referrer||s.ReferralCode||s.ClaimToken)}function Ht(s,e,t){t&&(s[e]=t);}var vl="a1_",wl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},gf=Object.keys(wl);function yf(s){let e=(s||"").trim();if(!e.startsWith(vl))return null;let t=e.slice(vl.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(i+"=".repeat((4-i.length%4)%4)),r=Uint8Array.from(n,h=>h.charCodeAt(0)),o=new TextDecoder().decode(r),c=new URLSearchParams(o);return [...c.keys()].length>0?c:null}catch{return null}}function Tl(s){try{let e=s.indexOf("?");return new URLSearchParams(e>=0?s.slice(e):"")}catch{return new URLSearchParams}}function Al(s){for(let e of hf){let t=s.get(e);if(t)return Ji(t)}return null}function Ji(s){let e=(s||"").trim();if(!e)return null;for(let t of mf)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Rf(s){let e=s||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var kl="idos_usage_pending",zl="idos_usage_session",Ml="idos_usage_closed_session",Ol="idos_usage_new_session",El="idos_usage_last_activity",Mi=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;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=typeof document<"u"&&document.visibilityState==="hidden",this.timer=setInterval(()=>this.tick(),200*1e3),window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide)),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){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,i=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,i,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(kl),this.currentSessionSeconds=this.readNumber(zl),this.pendingClosedSessionSeconds=this.readNumber(Ml),this.isNewSessionPending=this.readNumber(Ol)!==0;let e=this.readNumber(El);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(kl,this.pendingSeconds),this.writeNumber(zl,this.currentSessionSeconds),this.writeNumber(Ml,this.pendingClosedSessionSeconds),this.writeNumber(Ol,this.isNewSessionPending?1:0),this.writeNumber(El,Date.now());}readNumber(e){let t=this.ctx.platform.storage.getString(e),i=t?Number(t):0;return Number.isFinite(i)&&i>0?i:0}writeNumber(e,t){try{this.ctx.platform.storage.setString(e,String(Math.floor(t)));}catch{}}};var ht={Virtual:"Virtual",Crypto:"Crypto"},hi=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),Zi={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},mi=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),Rt={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Yi=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),Cf={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Xi=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),Sf={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},en=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),xf={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},Oi=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),ze={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function ql(){let s=globalThis,e=s.Capacitor?.getPlatform?.();if(e)return Ul(e);let t=s.cordova?.platformId;return t?Ul(t):s.navigator?.userAgent??""?Rt.Web:Rt.Unknown}function Ul(s){let e=s.toLowerCase();return e==="android"?Rt.Android:e==="ios"?Rt.Ios:e==="web"?Rt.Web:Rt.Unknown}function N(s){return {ok:true,data:s}}function u(s,e){return {ok:false,reason:s,error:e}}var a=u("unauthorized","Not logged in.");function bf(s){return s.ok}function Df(s){return !s.ok}var W=zod.z.union([zod.z.number(),zod.z.string()]).transform((s,e)=>{let t=typeof s=="string"?Number(s):s;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(s)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((s,e)=>{let t=typeof s=="number"?String(s):s.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(s)}`}),zod.z.NEVER):t}),p=zod.z.string();var ho=zod.z.object({Type:mi.nullish(),CurrencyID:zod.z.string().nullish(),Amount:W.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),If=zod.z.object({Type:en.nullish(),EntityID:zod.z.string()}),Pf=zod.z.object({Address:If.nullish(),Amount:W.nullish(),Source:zod.z.string().nullish()}),pe=zod.z.object({Entries:zod.z.array(ho).nullish(),EventTokens:zod.z.array(Pf).nullish()}),Ll=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:pe.nullish()}),H=zod.z.object({Standard:pe.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Ll).nullish()}),vt=zod.z.object({Standard:pe.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Ll).nullish()}),M=zod.z.object({Grant:H.nullish(),Consume:vt.nullish()}),Tt=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:pe.nullish()});var vf=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Tf={Completed:"Completed",Started:"Started",StepReached:"StepReached"},Af=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(),Z=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:vf.nullish(),Tutorial:Af.nullish(),Platforms:zod.z.array(Yi).nullish()}).passthrough();var Se=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 wf=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),kf=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),zf=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 Mf=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 ot=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:Se.nullish()}).passthrough(),Re=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:kf.nullish(),Chain:zf.nullish(),Cyclic:Mf.nullish(),ActivationTriggers:zod.z.array(ot).nullish(),Relative:wf.nullish()}).passthrough();var Of={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},Ef=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Uf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},qf=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),Lf=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Ne=zod.z.object({Base:zod.z.number().nullish(),Shape:Ef.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(Lf).nullish(),Interpolation:qf.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var Bf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:H.nullish()}).passthrough(),Gf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),mo=zod.z.object({Bundles:zod.z.array(Bf).nullish(),Multipliers:zod.z.array(Gf).nullish()}).passthrough();var Ff=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),tn=zod.z.object({Source:Ff.nullish(),SourceKey:zod.z.string().nullish(),Curve:Ne.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:pe.nullish(),ExcludeRewards:pe.nullish()}).passthrough(),Bl=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),_e=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:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:mo.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),fi=zod.z.object({Milestones:zod.z.record(zod.z.string(),_e).nullish()}).passthrough();var Q=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var _f=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Jt=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:_f.nullish()}).passthrough();var Vf=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),Gl=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:p,ExpiresAt:p.nullish(),EquippedSlot:Vf.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),K=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),Gl).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var we=s=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:s.nullish()}),Ct=s=>zod.z.object({ServerTimeUtc:p,Items:zod.z.array(we(s)),Resources:M.nullish(),Inventory:K.nullish()});var Nf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Fl=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),jf=zod.z.object({}).passthrough().transform(s=>s),Wf=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:p.nullish(),CycleEndUtc:p.nullish(),PointsTotalEarned:W.nullish(),PointsCurrent:W.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),fo=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:W.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:Fl}),_l=zod.z.object({State:jf.nullish(),PointsTracks:zod.z.record(zod.z.string(),Wf).nullish()}),go=zod.z.object({ServerTimeUtc:p,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:Fl.nullish(),Resources:M.nullish(),Inventory:K.nullish()}),yo=zod.z.object({ServerTimeUtc:p,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:W.nullish(),Resources:M.nullish(),Inventory:K.nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Vl=zod.z.object({ServerTimeUtc:p,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Nl=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(fo).nullish()}),jl=zod.z.array(we(go)),Wl=zod.z.array(we(yo)),Kf={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Qf=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Hf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},$f=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),Kl=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:Qf.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(ot).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),Ro=zod.z.object({Milestones:Q.nullish(),Linking:Q.nullish(),Availability:Q.nullish(),Reward:Q.nullish(),Objectives:Q.nullish()}).passthrough(),Jf=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(),Ql=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:$f.nullish()}).passthrough(),Hl=zod.z.object({Schedule:Re.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),$l=zod.z.object({Grant:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Zf=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Jf.nullish(),Linking:Ql.nullish(),Availability:Hl.nullish(),Objectives:zod.z.record(zod.z.string(),Kl).nullish(),Reward:$l.nullish(),Presets:Ro.nullish()}).passthrough(),Yf=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Xf=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:Z.nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:Ro.nullish(),PointsToken:Jt.nullish()}).passthrough(),eg=zod.z.object({Milestones:zod.z.record(zod.z.string(),fi).nullish(),Linking:zod.z.record(zod.z.string(),Ql).nullish(),Availability:zod.z.record(zod.z.string(),Hl).nullish(),Reward:zod.z.record(zod.z.string(),$l).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Kl)).nullish()}).passthrough(),tg=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Gate:Z.nullish(),PointsToken:Jt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),Yf).nullish(),Phases:zod.z.record(zod.z.string(),Xf).nullish(),Presets:Ro.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rn=zod.z.object({Cycles:zod.z.record(zod.z.string(),tg).nullish(),Quests:zod.z.record(zod.z.string(),Zf).nullish(),Presets:eg.nullish()}).passthrough(),ft={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var ig={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},ng=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),rg={Never:"Never",OnRequest:"OnRequest",Always:"Always"},sg=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),og={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},ag=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),lg={GameLoop:"GameLoop"},ug={Raid:"Raid",Attack:"Attack"},cg=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(),pg=zod.z.object({Mode:ng.nullish(),Triggers:zod.z.array(ot).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),dg=zod.z.object({Grant:H.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),hg=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(),mg=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:hg.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),fg=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),Co=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:cg.nullish(),Completion:pg.nullish(),Effects:dg.nullish(),Script:mg.nullish(),Policy:fg.nullish()}).passthrough(),gg=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(),Jl=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:ot.nullish()}).passthrough(),Zl=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:sg.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Yl=zod.z.object({Grant:H.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),yg=zod.z.object({Availability:Q.nullish(),Policy:Q.nullish(),Reward:Q.nullish(),Steps:Q.nullish()}).passthrough(),Rg=zod.z.object({FlowID:zod.z.string().nullish(),Identity:gg.nullish(),Availability:Jl.nullish(),Policy:Zl.nullish(),Steps:zod.z.record(zod.z.string(),Co).nullish(),Reward:Yl.nullish(),Presets:yg.nullish()}).passthrough(),Cg=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(),Sg=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:Cg.nullish()}).passthrough(),xg=zod.z.object({Availability:zod.z.record(zod.z.string(),Jl).nullish(),Policy:zod.z.record(zod.z.string(),Zl).nullish(),Reward:zod.z.record(zod.z.string(),Yl).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Co)).nullish()}).passthrough(),Xl=zod.z.object({Flows:zod.z.record(zod.z.string(),Rg).nullish(),Settings:Sg.nullish(),Presets:xg.nullish()}).passthrough(),bg=zod.z.object({}).passthrough().transform(s=>s),eu=zod.z.object({FlowID:zod.z.string(),Status:ag,CurrentStepID:zod.z.string().nullish(),CurrentStep:Co.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(),sn=zod.z.object({State:bg.nullish(),Flows:zod.z.array(eu).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Lt=zod.z.object({Flow:eu.nullish()}).passthrough(),tu=zod.z.object({FlowID:zod.z.string().nullish(),Granted:M.nullish()}).passthrough(),iu=zod.z.array(we(Lt)),nu=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),at={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function on(s){return Array.isArray(s)?s.filter(e=>e!==null).map(on):s!==null&&typeof s=="object"?Object.fromEntries(Object.entries(s).filter(([,e])=>e!==null).map(([e,t])=>[e,on(t)])):s}var an=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(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var ln=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function ru(s){return s===429||s>=500&&s<=599}function un(s,e=Math.random){let t=Math.min(500*Math.pow(2,s-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Bt(s){return new Promise(e=>setTimeout(e,s))}var su=15e3;async function ou(s){try{let t=JSON.parse(await s.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(s.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function au(s,e=Math.random){return s+10+Math.min(250,s*.2)*e()}function lu(s,e=Math.random){let t=s<=1?1500:s===2?4e3:6e3;return t+t*.1*e()}var So=15,uu=1e3,cn=class{constructor(e=So,t=()=>Date.now(),i=Bt){this.perSecond=e;this.now=t;this.wait=i;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=uu;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(uu-(e-this.starts[0])+5);}}};var Dg=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function yi(s){if(!s)return null;let e=Dg.exec(s);if(!e)return null;let[,t,i,n]=e;if(!t||i===void 0||n===void 0)return null;let r=new Zt__default.default(i),o=new Zt__default.default(n),c=o.minus(Zt__default.default.max(r,0));return c.lte(0)?null:{currencyID:t,required:o.toNumber(),available:r.toNumber(),missing:c.toNumber(),missingAmount:c.toFixed()}}var Ig=12e3,Pg=new Set(["RelatedEntityID"]);function vg(s,e){if(e===null||typeof e!="object"||Array.isArray(e))return s;let t={};for(let[i,n]of Object.entries(e))Pg.has(i)||(t[i]=n);try{return `${s}|${JSON.stringify(t)}`}catch{return s}}var Tg=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(fo).nullish(),TutorialProgress:zod.z.array(nu).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),pn=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new ln;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 an(e.throttleMs),this.pacer=new cn(e.maxRequestsPerSecond??So),this.clientPlatform=e.clientPlatform??Rt.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,n={}){let r=n.throttleKey??vg(e,t);if(!this.throttler.tryAcquire(r))return u("throttled","Throttled");if(!this.inflight.add(r))return u("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,c=JSON.stringify(t),h=n.ticket??null,y=n.silent??!1,V=n.timeoutMs??Ig,oe=n.autoRetry??!0,be=!1,le=!1,ge=0;for(;;){let Pt;n.keepalive||await this.pacer.take();try{Pt=await this.doFetch(o,c,h,V,n.keepalive??!1);}catch{if(oe&&ge<3){ge++,await Bt(un(ge));continue}return this.connectionFailure("Internet Connection Error",y)}let Xe=Pt.status;if(Xe>=200&&Xe<300){let se=!le&&this.cryptoTopUpHandler!==null,Ae=await this.parseSuccess(Pt,i,y,e,se);if(!Ae.ok&&se){let de=yi(Ae.error);if(de){if(le=!0,await this.runTopUp(de))continue;y||this.emitter.emit("error:global",Ae.error);}}return Ae}if(Xe===401){if(!be&&this.sessionRefreshHandler){be=!0;let se=null;try{se=await this.sessionRefreshHandler();}catch{se=null;}if(se){h=se;continue}}return this.emitter.emit("auth:unauthorized",void 0),u("unauthorized","Unauthorized")}if(ru(Xe)){let se=Xe===429?await ou(Pt):null;if(se!==null&&se>su)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(se/1e3)} s`,y);if(oe&&ge<3){ge++,await Bt(se!==null?au(se):Xe===429?lu(ge):un(ge));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Xe})`,y)}let wi="";try{wi=await Pt.text();}catch{}if(Xe===409&&/operation in progress/i.test(wi)&&oe&&ge<3){ge++,await Bt(un(ge));continue}return this.handleWebError(wi,Xe,y)}}finally{this.inflight.remove(r),this.lowerBusy();}}async doFetch(e,t,i,n,r=false){let o=new AbortController,c=setTimeout(()=>{o.abort();},n);try{let h={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(h.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:h,signal:o.signal,...r?{keepalive:!0}:{}})}finally{clearTimeout(c);}}async parseSuccess(e,t,i,n,r=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",i)}let c;try{c=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",i)}let h=Tg.safeParse(c);if(!h.success)return this.globalError("Malformed response envelope",i);if(!h.data.Success){let le=h.data.Error??"Server returned Success=false",ge=r&&yi(le);return !i&&!ge&&this.emitter.emit("error:global",le),u("server",le)}let y=h.data.StateVersions;y&&Object.keys(y).length>0&&this.emitter.emit("user:stateVersions",{epoch:h.data.StateEpoch??null,versions:y});let V=h.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);let oe=h.data.TutorialProgress;oe&&oe.length>0&&this.emitter.emit("tutorial:systemProgress",oe);let be=t.safeParse(h.data.Data);if(!be.success){let le=t.safeParse(on(h.data.Data));le.success&&(be=le);}if(!be.success){let le=`Validation error (${n}): ${be.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",le),i||this.emitter.emit("error:global",le),u("validation",le)}return N(be.data)}handleWebError(e,t,i){let n=`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),u("server","PLAY_ACCESS_REQUIRED");n=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{n=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",n),u("server",n)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),u("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),u("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 Ri(s){return (typeof s=="string"?s:s.toISOString()).slice(0,10)}function Ei(s){return `${Ri(s)}T00:00:00.000Z`}function cu(s){let e=new Date(s);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function pu(s,e){return new Date(s.getTime()+e*6e4).toISOString()}function Do(s,e,t,i){let n={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return n;s.InventoryV2??={};let r=s.InventoryV2,o=i.toISOString(),c=new Map,h=new Map,y=new Map,V=new Map,oe=new Map,be=new Map,le=new Map,ge=new Map,Pt=e.Grant?.PremiumTiers??[],Xe=Pt.length;for(let se=0;;se++){let Ae,de;if(se===0)Ae=e.Grant?.Standard?.Entries,de=false;else if(se-1<Xe)Ae=Pt[se-1]?.Resources?.Entries,de=false;else if(se===1+Xe)Ae=e.Consume?.Standard?.Entries,de=true;else break;if(Ae)for(let ue of Ae){if(ue.Type==null)continue;let he=Math.max(0,ue.Amount??0);if(!(he<=0))switch(ue.Type){case "VirtualCurrency":{if(!ue.CurrencyID)continue;let me=de?h:c;me.set(ue.CurrencyID,(me.get(ue.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!ue.CurrencyID)continue;let me=de?V:y;me.set(ue.CurrencyID,(me.get(ue.CurrencyID)??new Zt__default.default(0)).plus(he));break}case "Item":{if(!ue.ItemID)continue;let me=wg(t,ue.CatalogID,ue.ItemID),Ie=(me?me.IsStackable??true:true)?de?be:oe:de?ge:le;Ie.set(ue.ItemID,(Ie.get(ue.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(n.vcChanged=c.size>0||h.size>0,n.vcChanged){r.VirtualCurrencies??={};for(let se of new Set([...c.keys(),...h.keys()])){let Ae=c.get(se)??0,de=h.get(se)??0,ue=Ae-de,he=r.VirtualCurrencies[se];he?(he.Amount+=ue,he.UpdatedAt=o,he.Daily&&Ri(he.Daily.PeriodStartUtc)===Ri(i)?(he.Daily.Earned+=Ae,he.Daily.Spent+=de):he.Daily={PeriodStartUtc:Ei(i),Earned:Ae,Spent:de}):r.VirtualCurrencies[se]={Amount:ue,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:Ei(i),Earned:Ae,Spent:de}};}}if(n.ccChanged=y.size>0||V.size>0,n.ccChanged){r.CryptoCurrencies??={};for(let se of new Set([...y.keys(),...V.keys()])){let Ae=y.get(se)??new Zt__default.default(0),de=V.get(se)??new Zt__default.default(0),ue=Ae.minus(de),he=r.CryptoCurrencies[se];he?(he.Amount=new Zt__default.default(he.Amount).plus(ue).toString(),he.UpdatedAt=o):r.CryptoCurrencies[se]={Amount:ue.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(n.itemsChanged=oe.size>0||be.size>0||le.size>0||ge.size>0,n.itemsChanged){r.Items??={},r.UnstackableItems??={};let se=r.UnstackableItems,Ae=new Set([...oe.keys(),...be.keys(),...le.keys(),...ge.keys()]);for(let de of Ae){let ue=(oe.get(de)??0)-(be.get(de)??0),he=(le.get(de)??0)-(ge.get(de)??0),me=ue+he,st=r.Items[de];st?(ue!==0&&(st.StackableAmount+=ue),he!==0&&(st.UnstackableAmount+=he),me!==0&&(st.TotalAmount+=me)):r.Items[de]={StackableAmount:Math.max(0,ue),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,me)};}for(let[de,ue]of ge){if(ue<=0)continue;let he=Object.values(se).filter(me=>me.ItemID===de&&me.EquippedSlot==null&&(me.ExpiresAt==null||new Date(me.ExpiresAt)>i)).sort(Ag).slice(0,ue).map(me=>me.ItemInstanceID);for(let me of he)delete se[me];}for(let[de,ue]of le){let he=kg(t,de);for(let me=0;me<ue;me++){let st=G();se[st]={ItemInstanceID:st,ItemID:de,CatalogID:he,RemainingUses:1,AcquiredAt:o};}}}s.EventToken??={};let wi=s.EventToken;for(let se=0;;se++){let Ae,de;if(se===0)Ae=e.Grant?.Standard?.EventTokens,de=false;else if(se-1<Xe)Ae=Pt[se-1]?.Resources?.EventTokens,de=false;else if(se===1+Xe)Ae=e.Consume?.Standard?.EventTokens,de=true;else break;if(!(!Ae||Ae.length===0))for(let ue of Ae){let he=ue.Address;if(!he||he.Type==null)continue;let me=ue.Amount??0;if(me<=0)continue;let st=zg(wi,he.Type);if(!st)continue;let Ie=st[he.EntityID];Ie||(Ie={},st[he.EntityID]=Ie),Ie.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Ie.Daily??={Date:Ei(i),TotalEarned:0},Ie.Meta??={};let ki=ue.Source&&ue.Source.length>0?ue.Source:"CustomAction";de?(Ie.Balance.Current-=me,Ie.Balance.TotalSpent+=me):(Ie.Balance.Current+=me,Ie.Balance.TotalEarned+=me,Ri(Ie.Daily.Date)!==Ri(i)&&(Ie.Daily={Date:Ei(i),TotalEarned:0}),Ie.Daily.TotalEarned+=me,Ie.Daily.EarnedBySource??={},Ie.Daily.EarnedBySource[ki]=(Ie.Daily.EarnedBySource[ki]??0)+me,Ie.Daily.TriggersBySource??={},Ie.Daily.TriggersBySource[ki]=(Ie.Daily.TriggersBySource[ki]??0)+1,Ie.Daily.LastTriggerBySource??={},Ie.Daily.LastTriggerBySource[ki]=o,Ie.Meta.JoinedAtUtc||(Ie.Meta.JoinedAtUtc=o),Ie.Meta.LastEarnedAtUtc=o),n.tokensChanged=true;}}return n}function Ag(s,e){return s.AcquiredAt!==e.AcquiredAt?s.AcquiredAt<e.AcquiredAt?-1:1:s.ItemInstanceID===e.ItemInstanceID?0:s.ItemInstanceID<e.ItemInstanceID?-1:1}function wg(s,e,t){let i=s?.Catalogs;if(i){if(e){let n=i[e]?.Items?.[t];if(n)return n}for(let n of Object.values(i)){let r=n.Items?.[t];if(r)return r}}}function kg(s,e){let t=s?.Catalogs;if(t){for(let[i,n]of Object.entries(t))if(n.Items&&e in n.Items)return i}}function zg(s,e){switch(e){case "TimedEvent":return s.TimedEvent??={};case "Quest":return s.Quest??={};case "Leaderboard":return s.Leaderboard??={};case "CoopEvent":return s.CoopEvent??={};case "Season":return s.Season??={};default:return null}}function du(s,e,t){let i={drop:[],restore:{}};if(!t)return i;let n=t.ChangedInstances??{},r=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let h of Object.values(n))h?.ItemID&&o.add(h.ItemID);for(let h of r){let y=s[h]?.ItemID;y&&o.add(y);}if(o.size===0)return i;let c=h=>r.has(h)||h in n;if(e){for(let[h,y]of Object.entries(e))h in s||c(h)||y&&o.has(y.ItemID)&&i.drop.push(h);for(let[h,y]of Object.entries(s))h in e||c(h)||y&&o.has(y.ItemID)&&(i.restore[h]=y);}return i}function Io(s,e){return s===e||s.startsWith(`${e}:`)}var hn=class s{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 i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){s.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 i of t)this.currentState[i]=e[i];s.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){s.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,i=new Date){if(!this.currentState)return;let n=Do(this.currentState,e,t,i);this.emitResourceChanges(n,false);}applyResourcesWithDelta(e,t,i,n=new Date){if(!this.currentState)return;let r=this.currentState,o={...r.InventoryV2?.UnstackableItems??{}},c=Do(r,e,i,n),h=du(o,r.InventoryV2?.UnstackableItems,t),y=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],oe=h.drop.length>0||Object.keys(h.restore).length>0||y.length>0||V.length>0;if(oe){r.InventoryV2??={},r.InventoryV2.UnstackableItems??={};let be=r.InventoryV2.UnstackableItems;for(let le of h.drop)delete be[le];for(let[le,ge]of Object.entries(h.restore))be[le]=ge;for(let[le,ge]of y)be[le]=ge;for(let le of V)delete be[le];}this.emitResourceChanges(c,oe);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,n){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let r=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof Zt__default.default?t:new Zt__default.default(t),c=n===void 0?new Zt__default.default(0):n instanceof Zt__default.default?n:new Zt__default.default(n),h=i??new Date().toISOString(),y=r[e];y?(y.Amount=new Zt__default.default(y.Amount).plus(o).toString(),c.isZero()||(y.Frozen=new Zt__default.default(y.Frozen??0).plus(c).toString()),y.UpdatedAt=h):r[e]={Amount:o.toString(),Frozen:c.toString(),CreatedAt:h,UpdatedAt:h},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,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let n=this.currentState.Store.Purchases,r=n[e];r||(r={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},n[e]=r),r.TotalPurchases+=t,r.LastPurchasedAt=i,i>=r.DailyResetUtc?(r.DailyPurchases=t,r.DailyResetUtc=cu(i)):r.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let n=this.currentState.Lootbox??={};if(n.Pity??={},t){let r=new Date().toISOString();for(let o of t)o.RuleID&&(n.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:r});}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,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let n=this.currentState.Quest;if(t){n.Cycles??={};let r=n.Cycles[t];if(!r)return;r.Quests??={};let o=r.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {n.PermanentQuests??={};let r=n.PermanentQuests[e]??={QuestID:e,Status:i};r.Status=i,i==="Claimed"&&(r.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 i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.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 i of Object.values(e)){if(!i.CycleID)continue;let n=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,r=t[n]??={};r.Balance??={Current:0,TotalEarned:0,TotalSpent:0},r.Balance.Current=i.PointsCurrent??0,r.Balance.TotalEarned=i.PointsTotalEarned??0,r.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(r.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 i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.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 i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.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 i of e){if(!i.FlowID||!i.StepID)continue;let n=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};n.Steps??={};let r=n.Steps[i.StepID]??={StepID:i.StepID};r.Progress=i.Progress,i.Completed&&(r.CompletedAtUtc??=new Date().toISOString(),n.CurrentStepID===i.StepID&&(n.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 i of e){if(!i.QuestID)continue;let n;if(!i.CycleID)t.PermanentQuests??={},n=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let r=t.Cycles[i.CycleID];if(!r)continue;r.Quests??={},n=r.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(n.Status=i.Status,i.ObjectiveID){n.Objectives??={};let r=n.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};r.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(r.Completed=true,r.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(n.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[i,n]of Object.entries(t))if(Io(i,e)&&n)return n;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,i,n){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[r,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((n?r!==n:!Io(r,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,n),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,n){let r=this.activeEventsCache?.ActiveEvents;if(r)for(let o of r)o.Type!==e||o.TimedEventID!==t||n&&o.TokenEntityID&&o.TokenEntityID!==n||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,n){if(!e)return;let r=this.ensureLeaderboardProgress(e);(r.ScoreCycleVersion??0)<n&&(r.ScoreEarnedThisCycle=0,r.ClaimedMilestoneIDs=[],r.BracketID=null),r.CurrentScore=t,r.ScoreEarnedThisCycle=(r.ScoreEarnedThisCycle??0)+i,r.ScoreCycleVersion=n,r.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 i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.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,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}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 i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.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,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}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 i=this.currentState?.Character?.Characters;if(!i)return;let n=false;for(let r of Object.values(i))for(let o of Object.values(r.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,n=true);n&&(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);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,n=i[e];n||(n={CharacterID:e},i[e]=n),t(n),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let n=this.currentState?.Character?.Characters?.[e];n&&(n.Equipment??={},i===null?delete n.Equipment[t]:n.Equipment[t]=i,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,i=false;for(let[n,r]of Object.entries(e.ChangedInstances??{}))t[n]=r,i=true;for(let n of e.RemovedInstanceIDs??[])n in t&&(delete t[n],i=true);i&&(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,i){this.currentState??={};let n=this.currentState.CoopEvent??={MyObjectIndex:-1};n.ActiveGroupID=e,n.ActiveCoopEventID=t,n.MyObjectIndex=i,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(i=>i!==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(i=>i!==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(i=>i!==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(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(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 i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let n of Object.keys(i)){let r=i[n];r&&r.BoostID===e.BoostID&&n!==e.InstanceID&&delete i[n];}i[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,i,n,r){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,c={Value:i,UpdatedAt:new Date().toISOString(),Version:n,LastWriter:"Client",ExpiresAt:r??null};if(e==="Private")o.Private??={},o.Private[t]=c;else if(e==="Public")o.Public??={},o.Public[t]=c;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 i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.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 i=this.ensureBoard();i.BuildingStates??=[];let n=i.BuildingStates.find(r=>r.SlotIndex===e);n||(n={SlotIndex:e},i.BuildingStates.push(n)),t(n),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let n=this.ensureBoard().Pending;n&&(e&&(n.RaidLayout=e),t>=0&&(n.OpenedIndices??=[],n.OpenedIndices.includes(t)||n.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.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 n of Object.values(e.CryptoBalances??{}))n?.CurrencyID&&this.patchCryptoCurrencyDelta(n.CurrencyID,n.AmountDelta,n.UpdatedAt,n.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let n=this.currentState.Blockchain??={},r=n.PendingWithdrawals??[];t.size>0&&(r=r.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!r.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(r=[...r,i]),n.PendingWithdrawals=r;}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 mn=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,i]of Object.entries(e))this.sections.has(t)||this.sections.set(t,i);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let i=this.config?.[e];return i??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 fn=class{user;config;constructor(e){this.user=new hn(e),this.config=new mn;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Mg(s){return s}var Og=0,Eg=1500,Ug=3,yn=class{constructor(e,t,i=null,n="",r="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=n;this.loginMode=r;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 N(void 0);let i=Date.now(),n=[],r=[];for(let h of new Set(e)){let y=this.rules.get(h);if(y&&(t?.force||y.needsServer(i))){n.push(this.runRule(h,y));continue}(t?.force||!this.state.isStateFresh(h,t?.maxAgeMs))&&r.push(h);}let c=(await Promise.all([...n,r.length>0?this.queueSlice(r):Promise.resolve(N(void 0))])).find(h=>!h.ok);return c&&!c.ok?c:N(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let n=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,n),n}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},Og),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 i;this.batchRunning=new Promise(n=>i=n);try{let n=this.state?await this.state.readStateSlice(e):N(void 0),r=n.ok?N(void 0):n;for(let o of t)o(r);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let n=gn(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let y=this.fresh(n,i?.maxAgeMs);if(y)return N(y.data);let V=this.loginFailures.get(n);if(V)return this.loginFailures.delete(n),V;let oe=this.inflight.get(n);if(oe)return oe}let r=this.generation.get(n)??0,o=Date.now(),h=t().then(y=>{if(!y.ok)return y;let V=Date.now();if((this.generation.get(n)??0)===r)return this.entries.set(n,{data:y.data,storedAt:V,expiresAt:Po(e,y.data,V)}),y;let oe=this.entries.get(n);if(oe&&oe.storedAt>=o)return y;let be=Po(e,y.data,V);return this.entries.set(n,{data:y.data,storedAt:V,expiresAt:Math.min(be??1/0,V+Eg)}),y}).finally(()=>{this.inflight.get(n)===h&&this.inflight.delete(n);});return this.inflight.set(n,h),h}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,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let n=t.Key?t.Key:void 0,r=gn(i.view,n);if(!t.Success){this.loginFailures.set(r,u("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(r),i.apply(o.data,n),this.put(i.view,o.data,n));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let n=e.login;this.loadUsed().then(()=>{let r=hu({Name:n,Key:t});this.used.get(r)?.n!==this.session&&(this.used.set(r,{Name:n,Key:t??"",...i,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>Ug||this.used.set(hu(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()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(n=>n&&typeof n.Name=="string"&&typeof n.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(gn(e,t))?.data}put(e,t,i){this.register(e);let n=gn(e,i);this.bump(n);let r=Date.now();this.entries.set(n,{data:t,storedAt:r,expiresAt:Po(e,t,r)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let n of [...this.entries.keys(),...this.inflight.keys()])(n===i||n.startsWith(`${i}|`))&&this.drop(n);this.drop(i);}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,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let n=Date.now();if(!(i.expiresAt!==null&&n>=i.expiresAt)&&!(t!==void 0&&n-i.storedAt>t))return i}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 i of this.views.values())i.dependsOn?.some(n=>t.has(n))&&this.invalidate(i);}};function gn(s,e){return e===void 0?s.key:`${s.key}|${e}`}function hu(s){return s.Key?`${s.Name}|${s.Key}`:s.Name}function Po(s,e,t){let i=s.expiresAt?.(e)??null,n=s.ttlMs!==void 0?t+s.ttlMs:null;return i!==null&&n!==null?Math.min(i,n):i??n}var Rn=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 qg(e)?e:ze.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 qg(s){return s!==null&&Object.values(ze).includes(s)}var At=["https://idosgames.com","https://www.idosgames.com"],Cn="https://platform.idosgames.com",mu=/^[a-z0-9]{8}-preview\.idos\.games$/;function vo(s){return s==="localhost"||s==="127.0.0.1"||s==="[::1]"||s.endsWith(".localhost")}function To(){if(typeof window>"u")return false;let s=window.location.hostname.toLowerCase();return mu.test(s)?true:vo(s)&&globalThis.__IDOS_PREVIEW__!=null}function Ui(s){if(typeof window<"u"&&mu.test(window.location.hostname.toLowerCase()))return s===Cn;if(At.includes(s))return true;if(typeof window>"u"||!vo(window.location.hostname))return false;try{return vo(new URL(s).hostname)}catch{return false}}var fu="IDOS_PLATFORM_WALLET_ACK",gu="PLATFORM_WALLET_UNAVAILABLE",Lg=5e3,Bg=18e4;function Gg(){if(Ui(Cn))return [Cn];let s=[...At],e=window.location.ancestorOrigins?.[0];return e&&!s.includes(e)&&Ui(e)&&s.push(e),s}function Fg(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function wt(s,e,t,i={}){let n={ok:false,error:gu,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(n);let r=window.parent;if(!r)return Promise.resolve(n);let o=Fg(),c=i.answerTimeoutMs??Bg;return new Promise(h=>{let y=false,V,oe=le=>{y||(y=true,window.removeEventListener("message",be),clearTimeout(V),h(le));},be=le=>{if(!Ui(le.origin))return;let ge=le.data;if(!(!ge||ge.requestId!==o)){if(ge.type===fu){clearTimeout(V),V=setTimeout(()=>oe({ok:false,error:"TIMEOUT",data:{}}),c);return}ge.type===e&&oe({ok:ge.ok===true,error:typeof ge.error=="string"?ge.error:void 0,data:ge});}};V=setTimeout(()=>oe(n),Lg),window.addEventListener("message",be);for(let le of Gg())try{r.postMessage({type:s,requestId:o,...t},le);}catch{}})}var Ao={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},_g=30*6e4,wo="idos:platformSignIn:declined:";function Vg(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(To())return false;let s=window.location.ancestorOrigins?.[0];if(s&&!At.includes(s))try{let e=new URL(s).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}function Ng(){if(typeof window>"u"||!To())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function ko(s){let e=await wt(Ao.request,Ao.response,{titleID:s,supports:["pgs"]},{answerTimeoutMs:_g}),t=e.data.ticket;if(e.ok&&typeof t=="string"&&t.length>0)return {ticket:t};let i=e.data.code;return e.ok&&typeof i=="string"&&i.length>0?{code:i}:{error:e.error??"no_code"}}function jg(s){try{window.localStorage.setItem(wo+s,"1");}catch{}}function Wg(s){try{window.localStorage.removeItem(wo+s);}catch{}}function Kg(s){try{return window.localStorage.getItem(wo+s)==="1"}catch{return false}}var Qg=8,Hg=100,$g=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,yu=["GameLoop"];function Jg(s){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(s)}var Sn=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=ze.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,i){let n=this.authContext;if(!n)return a;let r=this.baseRequest();r.UserID=n.userID,r.ClientSessionTicket=n.clientSessionTicket,r.WalletAddress=e,r.NetworkID=t,i&&(r.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(r);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return a;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let n=await this.ctx.api.authentication.unlinkWallet(i);return n.ok&&n.data.PlayAccess&&this.setPlayAccess(n.data.PlayAccess),n}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.platform.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.platform.getDeviceID(),e.Device=this.ctx.platform.getDeviceModel(),e.Platform=this.ctx.platform.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(ze.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return u("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let n=await this.ctx.api.authentication.loginWithEmail(i);if(!n.ok)return n;this.applyAuthContext(n.data);let r=await this.fetchAndApplyClientState(ze.Email);return r.ok&&this.keepEmailCredentials(e,t),r}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.platform.getDeviceID(),i.Device=this.ctx.platform.getDeviceModel(),i.Platform=this.ctx.platform.getPlatform();let n=await this.ctx.api.authentication.registerWithEmail(i);return n.ok?(this.pendingRegistration={email:e,password:t},N({codeTtlMinutes:n.data.CodeTtlMinutes??0,resendCooldownSeconds:n.data.ResendCooldownSeconds??0})):n}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let n=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!n.ok)return n;this.applyAuthContext(n.data);let r=await this.fetchAndApplyClientState(ze.Email);return r.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,r}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?N(void 0):i}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let i=await this.ctx.api.authentication.loginWithGoogle(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Google)):i}async loginWithApple(e,t){if(!e?.trim())return u("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let n=await this.ctx.api.authentication.loginWithApple(i);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(ze.Apple)):n}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.WalletAddress=e,n.NetworkID=t,n.WalletSignature=i,n.Platform=this.ctx.platform.getPlatform(),n.Device=this.ctx.platform.getDeviceModel(),n.DeviceID=this.ctx.platform.getDeviceID();let r=await this.ctx.api.authentication.loginWithWallet(n);return r.ok?(this.applyAuthContext(r.data),this.fetchAndApplyClientState(ze.Wallet)):r}async loginWithSsoCode(e){if(!e)return u("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.platform.getDeviceID(),t.Device=this.ctx.platform.getDeviceModel(),t.Platform=this.ctx.platform.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.iDosGames)):i}async loginWithPlatformGameTicket(e){if(!e)return u("client","Platform game ticket is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.PlatformGameTicket=e;let i=await this.ctx.api.authentication.resolvePlatformGameSession(t);return i.ok?(this.applyAuthContext(i.data),this.platformGameSession=true,this.fetchAndApplyClientState(ze.iDosGames)):i}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,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.Email=e,n.ResetToken=t,n.Password=i,this.ctx.api.authentication.resetPassword(n)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==ze.None?e:ze.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 i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let n=await this.ctx.api.authentication.refreshSession(i);return n.ok?(this.applyRefresh(n.data),"ok"):(Jg(n.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,i){switch(e){case ze.Email:return this.loginWithEmail(t,i);case ze.Device:case ze.None:return this.loginWithDeviceID();case ze.Telegram:return this.loginWithTelegram();default:return Promise.resolve(u("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 ko(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let n=await this.ctx.api.authentication.resolvePlatformGameSession(i);return n.ok?(this.applyAuthContext(n.data),this.platformGameSession=!0,n.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!==ze.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===ze.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&&$g.test(e)}static isValidPasswordLength(e){return e.length>=Qg&&e.length<=Hg}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=ze.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){let t=await this.ctx.userService.getClientStateExcept(yu,yu);return t.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)),t}};var Zg="idos:cfg",Ci=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Ru(t)}`:e&&e.length>0?`f:${Ru(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${Zg}:${this.titleId}:${e}`}};function Ru(s){return [...s].map(e=>e.toLowerCase()).sort().join(",")}var Cu="idos:loc",Si=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 i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(n)),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 i={};for(let[n,r]of Object.entries(t))typeof r=="number"&&r>0&&(i[n]=r);return i}catch{return {}}}async noteVersion(e,t){let i=await this.readVersions();i[e]!==t&&(i[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(i)));}keyOf(e){return `${Cu}:${this.titleId}:${e}`}versionsKey(){return `${Cu}:${this.titleId}:versions`}};var Yg="idos:sec",xn=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 i=JSON.parse(t);return !i||typeof i!="object"||i.v!==e||!i.s||typeof i.s!="object"?{}:i.s}catch{return {}}}async write(e,t){try{let i={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(i));}catch{}}keyOf(){return `${Yg}:${this.titleId}`}};var Xg="idos:state",bn=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 i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,n){if(!(!e||!t))try{let r={e:t,v:i,s:n};await this.storage.set(this.keyOf(e),JSON.stringify(r));}catch{}}keyOf(e){return `${Xg}:${this.titleId}:${e}`}};function ey(s,e){if(!s)return;let t=new Set((e??[]).map(n=>n.trim().toLowerCase()));if(t.size===0)return s;let i={};for(let[n,r]of Object.entries(s))t.has(n.toLowerCase())||(i[n]=r);return i}function zo(s,e,t,i){let n={...s??{}};if(!e||!t||!i)return n;for(let[r,o]of Object.entries(t))i[r]===o&&r in e&&(n[r]=e[r]);return n}function ty(s){return {...s??{}}}function Mo(s){return typeof s.StateEpoch=="string"&&s.StateEpoch.length>0?s.StateEpoch:null}var Dn=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,i=Date.now()){if(this.versions[e]===void 0)return false;let n=this.confirmedAt[e];return n===void 0?false:t===void 0||i-n<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=ey(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 r=Object.keys(this.versions);this.reset(e),this.notify(r);}return}let i=Date.now(),n=[];for(let[r,o]of Object.entries(t)){let c=this.versions[r];c!==o&&(c!==void 0&&o===c+1?(this.versions[r]=o,this.confirmedAt[r]=i):(delete this.versions[r],delete this.confirmedAt[r]),n.push(r),this.dirty=true);}this.notify(n);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=ty(t);let n=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=n;this.dirty=true;let r=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&r.add(o);this.notify([...r]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),n=[];for(let[r,o]of Object.entries(t??{}))this.versions[r]!==o&&n.push(r),this.versions[r]=o,this.confirmedAt[r]=i;this.dirty=true,this.notify(n);}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 Su=u("server","Title configuration is unavailable (CDN and API both failed)."),In=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.platform.getFullURL(),RelatedEntityID:G()}:null}get configCache(){return this.cache??=new Ci(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new Si(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new xn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new Dn(new bn(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}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 a;let t=Ci.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let n=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let r=await this.ctx.api.user.getClientState(e);if(!r.ok)return r;let o=await this.resolveTitleConfig(r.data,t,i,{Fields:e.TitleFields});return o==null?Su:(this.finishStateHandshake(r.data,n),await this.restoreSections(r.data.TitleConfigVersion,o),await this.applyClientState(r.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(r.data.Views),await this.applyLocalization(r.data.Localization),await this.flushState(n),r)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let n=this.stateStore.versionsFor(t);if(n){e.KnownStateVersions=n;let r=this.stateStore.currentEpoch;r&&(e.KnownStateEpoch=r);}return {userId:i,cached:this.stateStore.cachedState,sent:n}}finishStateHandshake(e,t){let i=zo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let n=Mo(e);!n||!t.userId||this.stateStore.afterFullRead(n,e.StateVersions);}async resolveTitleConfig(e,t,i,n){let r=e.TitleConfigVersion;if(i&&r&&i.v===r)return i.c;if(e.TitleConfigUrl){let c=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(c!=null)return r&&await this.configCache.write(t,r,c),c}let o=await this.fetchConfigFromApi(n);return o!=null?(r&&await this.configCache.write(t,r,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},n=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return n.ok?n.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return a;i.ExcludeFields=e,i.ExcludeTitleFields=t;let n=Ci.scopeOf(null,t??[]),r=await this.configCache.read(n);r&&(i.KnownTitleConfigVersion=r.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let c=await this.ctx.api.user.getClientStateExcept(i);if(!c.ok)return c;let h=await this.resolveTitleConfig(c.data,n,r,{ExcludeFields:t??[]});return h==null?Su:(this.finishStateHandshake(c.data,o),await this.restoreSections(c.data.TitleConfigVersion,h),await this.applyClientState(c.data,h,e,t),this.ctx.cache.acceptLoginViews(c.data.Views),await this.applyLocalization(c.data.Localization),await this.flushState(o),c)}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 i=t,n={};for(let[r,o]of Object.entries(await this.sectionCache.read(e)))i[r]==null&&(n[r]=o);this.ctx.data.config.restoreSections(n),this.ctx.data.config.setSectionSink((r,o)=>{i[r]!=null||o==null||(n[r]=o,this.sectionCache.write(e,n));});}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 i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}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}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let n=await this.localizationCache.read(t);if(i<=0)return n?.t??null;if(n&&n.v===i)return n.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let r=await this.fetchLocalizationFromApi(t,n?.v??0);return r??n?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let n=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!n.ok)return null;let r=n.data;if(r.NotModified)return null;let o=r.Entries??{},c=r.Version??0,h=r.Locale??e;return c>0&&await this.localizationCache.write(h,c,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):a}async getUserState(e){let t=this.baseRequest();if(!t)return a;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),n=await this.ctx.api.user.getUserState(t);if(!n.ok)return n;let r=zo(n.data.User,i.cached,i.sent,n.data.StateVersions);n.data.User=r;let o=i.sent??{},c=Object.entries(n.data.StateVersions??{}).filter(([y,V])=>o[y]!==V||this.ctx.data.user.state?.[y]===void 0).map(([y])=>y);this.ctx.data.user.applyUserStateContainers(r,c);let h=Mo(n.data);return h&&(this.stateStore.afterSliceRead(h,n.data.StateVersions),await this.flushState(i)),n}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 a;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 a;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 a;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,i){let n=this.baseRequest();if(!n)return a;n.UsageTime=e,n.IsNewSession=t,n.SessionDurationSeconds=i;let r=await this.ctx.api.user.addUsageTime(n);return r.ok&&this.ctx.emitter.emit("user:usageTimeAdded",r.data),r}async deleteUserAccount(){let e=this.baseRequest();if(!e)return a;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 a;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,n){let r=i?.includes("GameLoop")===true,o=n?.includes("GameLoop")===true,c=r?this.ctx.data.user.state?.GameLoop:void 0,h=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let y=this.ctx.data.user.state;r&&y&&y.GameLoop==null&&(y.GameLoop=c);let V=this.ctx.data.config.titlePublicConfiguration;o&&V&&V.GameLoop==null&&(V.GameLoop=h),this.ctx.emitter.emit("user:clientStateReceived",e);}};var vn=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return u("client","SpendID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${G()}`},n=await this.ctx.api.currency.spend(i);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",n.data)),n}async convert(e,t,i,n,r,o){if(!t)return u("client","SourceID is required.");if(!n)return u("client","TargetID is required.");if(r<=0)return u("client","Amount must be positive.");if(e===i&&t===n)return u("client","Source and target must differ.");if(e===ht.Crypto||i===ht.Crypto)return u("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return a;let c={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:String(Math.trunc(r)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${n}_${G()}`},h=await this.ctx.api.currency.convert(c);if(h.ok){let y=h.data,V={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:y.SourceID,Amount:y.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:y.TargetID,Amount:y.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",y);}return h}async cryptoConvert(e,t,i,n,r,o){let c=r instanceof Zt__default.default?r:new Zt__default.default(r);if(!t)return u("client","SourceID is required.");if(!n)return u("client","TargetID is required.");if(c.lte(0))return u("client","SourceAmount must be a positive decimal.");if(e===i&&t===n)return u("client","Source and target must differ.");if(e===ht.Virtual&&i===ht.Virtual)return u("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ht.Virtual&&!c.isInteger())return u("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:c.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${n}_${G()}`},y=await this.ctx.api.currency.cryptoConvert(h);if(y.ok){let V=y.data,oe=[],be=[];if(V.SourceType===ht.Virtual&&oe.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===ht.Virtual&&be.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),oe.length>0||be.length>0){let le={Consume:oe.length>0?{Standard:{Entries:oe}}:null,Grant:be.length>0?{Standard:{Entries:be}}:null};this.ctx.data.user.applyResourceOperation(le,this.ctx.data.config.itemDefinitions);}V.SourceType===ht.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new Zt__default.default(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===ht.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new Zt__default.default(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return y}};var Tn=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i,n){let r=e.trim();if(!r)return u("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:r,SelectedOptionID:i,CreditsConfirmationID:n,RelatedEntityID:`upgrade_item_${r}_${G()}`};t&&t.length>0&&(o.FodderInstanceIDs=[...t]);let c=await this.ctx.api.item.upgradeLevel(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(c.data.ItemInstanceID??r,c.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",c.data)),c}async upgradeLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let n of i.data)n.Success&&n.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(n.Data.ItemInstanceID,n.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var An=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:vt.nullish(),AllowedPlatforms:zod.z.array(Yi).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ce=zod.z.record(zod.z.string(),An),iy=zod.z.object({Store:Xi,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var qi={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},fe=zod.z.object({ConfirmationID:zod.z.string(),Url:zod.z.string(),Status:zod.z.string(),PriceCredits:zod.z.number(),ExpiresAt:p}).passthrough(),xu=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),ny={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"},Oo=zod.z.object({ServerTimeUtc:p,OfferID:zod.z.string(),Count:zod.z.number(),Resources:M.nullish(),Inventory:K.nullish(),CreditsConfirmation:fe.nullish()}),bu=zod.z.array(we(Oo)),ry=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:p,LastPurchasedAt:p}),sy=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:p}),Du=zod.z.object({Purchases:zod.z.record(zod.z.string(),ry).nullish(),Rotations:zod.z.record(zod.z.string(),sy).nullish()}).passthrough().transform(s=>s),kt=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(),wn=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),oy={Fixed:"Fixed",Title:"Title",Player:"Player"},ay=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:Z.nullish()}).passthrough(),Iu=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(ay).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),ly=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Rotation:Q.nullish()}).passthrough(),uy=zod.z.object({SlotID:zod.z.string().nullish(),Identity:kt.nullish(),Availability:wn.nullish(),Rotation:Iu.nullish(),Presets:ly.nullish()}).passthrough(),cy=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish()}).passthrough(),py=zod.z.object({SectionID:zod.z.string().nullish(),Identity:kt.nullish(),Availability:wn.nullish(),Slots:zod.z.record(zod.z.string(),uy).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:cy.nullish()}).passthrough(),Pu=zod.z.object({Sections:zod.z.record(zod.z.string(),py).nullish()}).passthrough(),dy=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Layout:Q.nullish()}).passthrough(),hy=zod.z.object({StoreID:zod.z.string().nullish(),Identity:kt.nullish(),Availability:wn.nullish(),Layout:Pu.nullish(),Presets:dy.nullish()}).passthrough(),vu=zod.z.object({Options:ce.nullish(),CompareAt:zod.z.record(zod.z.string(),vt).nullish()}).passthrough(),Tu=zod.z.object({Grant:H.nullish()}).passthrough(),Au=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),my=zod.z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish(),Availability:Q.nullish()}).passthrough(),fy=zod.z.object({OfferID:zod.z.string().nullish(),Identity:kt.nullish(),Pricing:vu.nullish(),Reward:Tu.nullish(),Availability:Au.nullish(),Presets:my.nullish()}).passthrough(),gy=zod.z.object({Identity:zod.z.record(zod.z.string(),kt).nullish(),Availability:zod.z.record(zod.z.string(),wn).nullish(),Layout:zod.z.record(zod.z.string(),Pu).nullish(),Rotation:zod.z.record(zod.z.string(),Iu).nullish(),Pricing:zod.z.record(zod.z.string(),vu).nullish(),Reward:zod.z.record(zod.z.string(),Tu).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Au).nullish()}).passthrough(),kn=zod.z.object({Stores:zod.z.record(zod.z.string(),hy).nullish(),StoreOffers:zod.z.record(zod.z.string(),fy).nullish(),Presets:gy.nullish()}).passthrough(),yy=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:p.nullish()}).passthrough(),Ry=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:vt.nullish(),CompareAtCost:vt.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(),Cy=zod.z.object({OfferID:zod.z.string(),Identity:kt.nullish(),PriceOptions:zod.z.array(Ry).nullish(),Rewards:H.nullish(),State:yy.nullish()}).passthrough(),Sy=zod.z.object({SlotID:zod.z.string(),Identity:kt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:p.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:Cy.nullish()}).passthrough(),xy=zod.z.object({SectionID:zod.z.string(),Identity:kt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(Sy).nullish()}).passthrough(),by=zod.z.object({StoreID:zod.z.string(),Identity:kt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:p.nullish(),Sections:zod.z.array(xy).nullish()}).passthrough(),zn=zod.z.object({ServerTimeUtc:p,Stores:zod.z.array(by).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),zt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},Dy="OFFER_NOT_IN_ROTATION";var wu="Store",ku={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:s=>{let e=null;for(let t of s.Stores??[])for(let i of t.Sections??[])for(let n of i.Slots??[]){let r=Date.parse(n.RefreshesAtUtc??"");!Number.isNaN(r)&&(e===null||r<e)&&(e=r);}return e}},Mn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ku,{schema:zn,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return u("client","OfferID is required.");if(t<1)return u("client","Count must be at least 1.");let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${n.userID}_${G()}`},o=await this.ctx.api.store.purchase(r);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;this.ctx.data.user.patchStorePurchase(e,t,c.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",c);}return o}async purchaseWithCredits(e,t=1,i={}){return await this.ctx.credits.pay(n=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:n}),{onConfirmation:i.onConfirmation,signal:i.signal,pollMs:i.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):a}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):a}async purchaseBatch(e){if(!e||e.length===0)return u("client","purchases is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||!r.Data.OfferID||(this.ctx.data.user.patchStorePurchase(r.Data.OfferID,r.Data.Count,r.Data.ServerTimeUtc),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(wu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.store.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(wu,n.data),this.ctx.emitter.emit("store:definitionsLoaded",n.data)),n}getStorefront(e){return this.ctx.cache.read(ku,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return a;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 i of t.Sections??[])for(let n of i.Slots??[]){let r=n.RefreshesAtUtc;r&&(e===null||Date.parse(r)<Date.parse(e))&&(e=r);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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 Eo={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},Iy=15*6e4,Py=/^[a-z0-9]{8}-preview\.idos\.games$/;function Yt(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !Py.test(window.location.hostname.toLowerCase())}async function Uo(s){let e=await wt(Eo.request,Eo.response,{titleID:s.titleID,userID:s.userID,currencyID:s.currencyID,amount:s.amount},{answerTimeoutMs:Iy});return e.ok?{ok:true}:{ok:false,error:e.error}}var qo={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},vy=10*6e4;function Ty(){let s=globalThis.navigator?.userAgent??"";if(!/\biDosGamesApp\/(?:player|studio)\//.test(s))return true;let e=/\biDosGamesPlatform\/(ios|android)\b/.exec(s);return (e?e[1]:/\bAndroid\b/.test(s)?"android":"ios")!=="ios"}function Lo(){return Yt()}async function Bo(s){let e=await wt(qo.request,qo.response,{titleID:s.titleID,confirmationID:s.confirmationID},{answerTimeoutMs:vy});return e.ok?{ok:true}:{ok:false,error:e.error}}var On=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let i=await e(void 0);if(!i.ok||!i.data.CreditsConfirmation)return i;let n=i.data.CreditsConfirmation,r=()=>e(n.ConfirmationID);if(Lo()){let h=await Bo({titleID:this.ctx.settings.titleID,confirmationID:n.ConfirmationID});if(h.ok)return await r();if(h.error==="DECLINED")return u("server","CREDITS_CONFIRMATION_DECLINED");if(h.error==="NOT_ENOUGH_CREDITS")return u("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(n);let o=Math.max(1e3,t.pollMs??2500),c=Date.parse(n.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return u("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>c)return u("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(V=>setTimeout(V,o));let h=await this.ctx.store.getCreditsConfirmation(n.ConfirmationID);if(!h.ok)continue;let y=h.data.Status;if(y!==qi.Pending)return y===qi.Declined?u("server","CREDITS_CONFIRMATION_DECLINED"):y===qi.Expired?u("server","CREDITS_CONFIRMATION_EXPIRED"):await r()}}};var En=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?N(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return u("client","Receipt is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},r=await this.ctx.api.purchase.validatePurchase(n);return r.ok&&this.applyValidation(r.data),r}async buyWithTelegramStars(e,t){if(!e)return u("client","productID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},n=await this.ctx.api.purchase.createTelegramInvoice(i);return n.ok&&t?.open!==false&&this.ctx.platform.openInvoice(n.data.InvoiceLink),n}async validatePurchasesBatch(e){if(!e||e.length===0)return u("client","receipts is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let n of i.data.Items)n.Success&&n.Data&&this.applyValidation(n.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var zu=3,Ay=700,Un=class{constructor(e){this.ctx=e;Yt()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return yi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await Uo({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return i.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:i.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=zu;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===zu)break;await Bt(Ay);}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,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.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 i of t)if(i?.Type===Zi.Purchase&&i.ProductID)return i.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t){if(i?.Type!==Zi.CryptoCurrency||!i.CurrencyID)continue;let n=Number(i.Amount??0);if(!(n>0))continue;let r=this.cryptoBalance(i.CurrencyID);return r>=n?null:{currencyID:i.CurrencyID,required:n,available:r,missing:n-r}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var Mu="Lootbox",qn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Mu,e);if(t){let r={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.lootbox.getDefinitions(i);if(n.ok){let r=n.data.LootboxDefinitions;r&&(this.ctx.data.config.patchSection(Mu,r),this.ctx.emitter.emit("lootbox:definitionsLoaded",r));}return n}async open(e,t,i,n,r){if(!e)return u("client","LootboxID is required.");if(t<1)return u("client","Count must be at least 1.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:n,CreditsConfirmationID:r,RelatedEntityID:`lootbox_${e}_${i??"default"}_${G()}`},c=await this.ctx.api.lootbox.open(o);if(c.ok&&!c.data.CreditsConfirmation){let h=c.data;h.TriggeredPity&&h.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,h.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(h.Resources,h.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",h);}return c}};var Go="Reward";function Ln(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var Bn=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(Go)?.Comebacks??{}).some(i=>i?.TrackPresenceOnRead===true),refresh:async()=>{let i=await this.getUserRewardsState();return i.ok&&(t=true),i}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(Go,e);if(t){let r={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.reward.getRewardDefinitions(i);if(n.ok){let r=n.data.RewardDefinitions;r&&(this.ctx.data.config.patchSection(Go,r),this.ctx.emitter.emit("reward:definitionsLoaded",r));}return n}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return a;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 a;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${G()}`},n=await this.ctx.api.reward.claimDailyReward(i);if(n.ok){let r=n.data;this.ctx.data.user.patchDailyCalendarState(r.CalendarID,r.DailyState),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",r);}return n}async collectIdleAccrual(e){if(!Ln(e))return u("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${G()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let n=i.data;this.ctx.data.user.patchIdleAccrualState(n.AccrualID,n.IdleState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",n);}return i}async claimComebackReward(e){if(!Ln(e))return u("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchComebackState(n.ComebackID,n.ComebackState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",n);}return i}async claimReward(e){if(!Ln(e))return u("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchClaimRewardState(n.ClaimID,n.ClaimState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",n);}return i}async claimRewardWindow(e,t,i={}){if(!Ln(e))return u("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return u("client","Amount must be a positive number.");let n=i.boost??"None";if(n==="Ad"&&!i.adRequestID)return u("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:n,...i.adRequestID?{AdRequestID:i.adRequestID}:{},RelatedEntityID:i.roundID??`reward_window_${e}_${G()}`},o=await this.ctx.api.reward.claimRewardWindow(r);if(o.ok){let c=o.data;this.ctx.data.user.patchRewardWindowState(c.WindowID,c.WindowState),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:windowClaimed",c);}return o}};var Gn="Tutorial",Ou={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"]},Fn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ou,{schema:sn,apply:i=>this.applyUserTutorialState(i)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(Gn)?.Flows??{}).length>0,refresh:async()=>{let i=await this.getUserTutorialState();return i.ok&&(t=true),i}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(Gn,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.tutorial.getTutorialDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Gn,n.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",n.data)),n}getUserTutorialState(e=true,t){return this.ctx.cache.read(Ou,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}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,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${G()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return u("client","FlowID is required.");if(!t||t.length===0)return u("client","stepIDs is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${G()}`},r=await this.ctx.api.tutorial.completeStepsBatch(n);return r.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",r.data)),r}async skipStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.skipStep(i))}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 u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${G()}`},n=await this.ctx.api.tutorial.claimFlowReward(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",n.data)),n}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let n=e?.trim();if(!n)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),FlowID:n},o=await t(r);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,n){let r=e?.trim(),o=t?.trim();if(!r)return u("client","FlowID is required.");if(!o)return u("client","StepID is required.");if(!this.ctx.auth.context)return a;let c={...this.ctx.buildAuthedBaseRequest(),FlowID:r,StepID:o};n?.relatedEntityID&&(c.RelatedEntityID=n.relatedEntityID);let h=this.ctx.data.user.state?.Tutorial?.Flows?.[r]?.RewardClaimed===true,y=await i(c);return y.ok&&(this.applyFlowView(y.data),this.mayHavePaid(r,o,h,y.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",y.data)),y}mayHavePaid(e,t,i,n){return !i&&n.Flow?.RewardClaimed===true?true:n.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Gn)?.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 _n=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return a;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 a;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return u("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return u("client","campaignID is required.");if(!t)return u("client","walletAddress is required.");let n=this.ctx.authedRequest();if(!n)return a;n.CampaignID=e,n.WalletAddress=t,i&&(n.Amount=i);let r=await this.ctx.api.communityMarketing.withdrawCryptoReward(n);return r.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",r.data),r}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var qe=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 wy={Global:"Global",Announcement:"Announcement",Group:"Group"},Uu=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),ky={None:"None",Language:"Language",Region:"Region"},zy=zod.z.enum(["None","Language","Region"]).catch("None"),My={Anyone:"Anyone",Friends:"Friends"},Oy=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),Ey={Reject:"Reject",Mask:"Mask"},Uy=zod.z.enum(["Reject","Mask"]).catch("Reject"),qy={Player:"Player",Publisher:"Publisher",System:"System"},Ly=zod.z.enum(["Player","Publisher","System"]).catch("Player"),By={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Gy=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),qu=zod.z.object({Gate:Z.nullish(),Schedule:Re.nullish()}).passthrough(),Lu=zod.z.object({Gate:Z.nullish(),Limits:Se.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Bu=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),Fy=zod.z.object({Availability:Q.nullish(),Write:Q.nullish(),Retention:Q.nullish()}).passthrough(),_y=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:Gy.nullish(),Type:Uu.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:zy.nullish(),Capacity:zod.z.number().nullish(),Availability:qu.nullish(),Write:Lu.nullish(),Retention:Bu.nullish(),Presets:Fy.nullish()}).passthrough(),Vy=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:Oy.nullish(),Limits:Se.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),Ny=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:Uy.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Se.nullish()}).passthrough(),jy=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),Wy=zod.z.object({Availability:zod.z.record(zod.z.string(),qu).nullish(),Write:zod.z.record(zod.z.string(),Lu).nullish(),Retention:zod.z.record(zod.z.string(),Bu).nullish()}).passthrough(),Gu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),_y).nullish(),Direct:Vy.nullish(),Moderation:Ny.nullish(),Polling:jy.nullish(),Presets:Wy.nullish()}).passthrough(),Ky=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),Eu=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(),Ky).nullish(),Limits:zod.z.record(zod.z.string(),Eu).nullish(),ReportLimits:Eu.nullish()}).passthrough();var Fo=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),Vn=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:qe.nullish(),AuthorType:Ly.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),Qy=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:Uu.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(),Nn=zod.z.object({Channels:zod.z.array(Qy).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),Hy=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Vn).nullish(),NextCursor:Fo.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Fu=zod.z.object({Rooms:zod.z.array(Hy).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),_u=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Vn).nullish(),NextBefore:Fo.nullish()}).passthrough(),Vu=zod.z.object({Message:Vn.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),Nu=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:qe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),$y=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:qe.nullish(),LastMessage:Vn.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),ju=zod.z.object({Conversations:zod.z.array($y).nullish()}).passthrough(),xi=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:Fo.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),Wu=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),$e={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 Ku="Chat",Qu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},jn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Qu,{schema:Nn,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(Ku,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.chat.getChatDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Ku,n.data),this.ctx.emitter.emit("chat:definitionsLoaded",n.data)),n}getChannels(e,t){return this.ctx.cache.read(Qu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let n of i.data.Rooms??[])n.NextCursor&&n.RoomID&&this.cursors.set(n.RoomID,n.NextCursor),n.Messages&&n.Messages.length>0&&this.ctx.emitter.emit("chat:messages",n);return i}async getHistory(e,t,i){let n=this.ctx.authedRequest();return n?(n.RoomID=e,t&&(n.Before=t),i&&(n.Limit=i),this.ctx.api.chat.getHistory(n)):a}async sendMessage(e,t,i){let n=this.ctx.authedRequest();if(!n)return a;n.ChannelID=e,n.Text=t,i&&(n.Locale=i);let r=await this.ctx.api.chat.sendMessage(n);return r.ok&&this.ctx.emitter.emit("chat:sent",r.data),r}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Text=t;let n=await this.ctx.api.chat.sendMessage(i);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):a}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):a}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let n=await this.ctx.api.chat.markRead(i);return n.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),n}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):a}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):a}async reportMessage(e,t,i,n){let r=this.ctx.authedRequest();return r?(r.RoomID=e,r.MessageID=t,r.Reason=i,n&&(r.Comment=n),this.ctx.api.chat.reportMessage(r)):a}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):a}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):a}resetCursors(){this.cursors.clear();}};var Jy={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},Zy=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),Yy={Player:"player",Title:"title",Creator:"creator"},bi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Hu=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),Xy=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),_o=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:Zy.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(Xy).nullish()}).passthrough(),$u=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(_o).nullish()}).passthrough(),Mt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var eR="IDOS_PLATFORM_PUSH_REQUEST",tR="IDOS_PLATFORM_PUSH_RESPONSE",iR=12e4;function Ju(s){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(i=>{let n=false,r=h=>{n||(n=true,window.removeEventListener("message",o),clearTimeout(c),i(h));},o=h=>{let y=h?.data;!y||y.type!==tR||y.requestId!==t||At.includes(h.origin)&&r(y.ok===true);},c=setTimeout(()=>r(false),iR);window.addEventListener("message",o);for(let h of At)try{e.postMessage({type:eR,requestId:t,titleID:s},h);}catch{}})}var Wn=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 i=await this.ctx.api.push.getPushConfig(t),n=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=n,i.ok&&this.ctx.emitter.emit("push:configLoaded",n),n}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return Mt.Unsupported;if(this.isEmbedded())return Mt.Embedded;if(!this.isSupported())return Mt.Unsupported;let t=Notification.permission;return t==="denied"?Mt.Blocked:t!=="granted"?Mt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?Mt.Subscribed:Mt.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return u("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Ju(this.ctx.settings.titleID)?N({Where:"portal",Subscription:null}):u("client","The portal did not complete the subscription.");if(!this.isSupported())return u("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return u("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let n=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await n.pushManager.getSubscription()??await n.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:nR(t.PublicKey)}),c=this.ctx.authedRequest();if(!c)return a;let h=o.toJSON();c.PushEndpoint=h.endpoint,c.PushP256dh=h.keys?.p256dh,c.PushAuth=h.keys?.auth,c.PushTransport="WebPush",c.PushLocale=e.locale??navigator.language,c.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let y=await this.ctx.api.push.subscribePush(c);return y.ok?(this.ctx.emitter.emit("push:subscribed",y.data),N({Where:"game",Subscription:y.data})):y}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return a;if(this.isSupported()){let n=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();n&&(e.PushEndpoint=n.endpoint,await n.unsubscribe());}if(!e.PushEndpoint)return u("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):a}async unsubscribeByHash(e){if(!e)return u("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return a;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function nR(s){let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),n=new Uint8Array(i);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return i}var Kn=Object.freeze({}),Qn=class{constructor(e){this.ctx=e;}ctx;table={...Kn};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new Si(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,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),n=this.lookup(i)??this.lookup(e);return n===void 0?this.onMissing(e):t?rR(n,t):n}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Kn},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return a;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:n,table:r,fallbackLocale:o}=i.data,c=null;if(o){let h=await this.loadTableFromApi(o);h.ok&&(c=h.data.table);}return this.table=r,this.fallbackTable=c,this.currentFallbackLocale=o,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:o,entryCount:Object.keys(r).length}),{ok:true,data:n}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):a}reset(){this.table={...Kn},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:G()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return a;t.Locale=e;let i=await this.cache.read(Zu(e));i&&(t.KnownVersion=i.v);let n=await this.ctx.api.localization.getLocalizationTable(t);if(!n.ok)return n;let r=n.data,o=r.Locale??Zu(e),c=r.Version??0;if(r.NotModified){let y=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:y?.t??{...Kn},fallbackLocale:r.FallbackLocale??null}}}let h=r.Entries??{};return c>0&&await this.cache.write(o,c,h),{ok:true,data:{locale:o,table:h,fallbackLocale:r.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let n=this.pluralCategory(i),r=`${e}.${n}`;if(this.lookup(r)!==void 0)return r;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 rR(s,e){return s.replace(/\{(\w+)\}/g,(t,i)=>{let n=e[i];return n===void 0?t:String(n)})}function Zu(s){return s.trim().replace(/_/g,"-").toLowerCase()}var Vo="Quest",sR={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:s=>{let e=Date.now(),t=null,i=[...Object.values(s.PointsTracks??{}).map(n=>n?.CycleEndUtc),...Object.values(s.State?.Cycles??{}).map(n=>n?.CycleEndUtc)];for(let n of i){let r=Date.parse(n??"");!Number.isNaN(r)&&r>e&&(t===null||r<t)&&(t=r);}return t}},Hn=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let n=e.cache.configSection(Vo)?.Cycles;if(!n)return false;let r=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(n)){let c=Date.parse(r[o]?.CycleEndUtc??"");if(Number.isNaN(c)){if(t===0)return true}else if(c<=i&&t<c)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true,{forceRefresh:true});return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(Vo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.quest.getQuestDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Vo,n.data),this.ctx.emitter.emit("quest:definitionsLoaded",n.data)),n}getUserQuestState(e=true,t){return this.ctx.cache.read(sR,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let n=i.data.State??{};this.ctx.data.user.applyQuest(n),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",n);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return a;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 i=e.trim();if(!i)return u("client","QuestID is required.");if(!this.ctx.auth.context)return a;let n=t&&t.trim().length>0?t.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:n,RelatedEntityID:`quest_claim_${n??""}_${i}_${G()}`},o=await this.ctx.api.quest.claimQuestReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchQuestStatus(c.QuestID,c.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",c);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return u("client","quests is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||(this.ctx.data.user.patchQuestStatus(r.Data.QuestID,r.Data.CycleID,"Claimed"),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return u("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:n,RelatedEntityID:`milestone_claim_${i}_${n}_${G()}`},o=await this.ctx.api.quest.claimMilestoneReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchMilestoneClaimed(c.CycleID,c.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",c);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||(this.ctx.data.user.patchMilestoneClaimed(r.Data.CycleID,r.Data.MilestoneID),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return u("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:n,RelatedEntityID:`group_completion_${i}_${n}_${G()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchGroupCompletionClaimed(c.CycleID,c.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",c);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return u("client","MetricID is required.");if(t<0)return u("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},r=await this.ctx.api.quest.addQuestProgress(n);return r.ok&&(this.ctx.data.user.patchQuestProgressUpdates(r.data.Updates),this.ctx.emitter.emit("quest:progressAdded",r.data)),r}};var Yu=zod.z.object({}).passthrough().transform(s=>s);var oR=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),aR=zod.z.object({Schedule:zod.z.array(oR).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),lR=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:p.nullish(),NextBonusStartUtc:p.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),uR=zod.z.object({Milestones:Q.nullish()}).passthrough(),No=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:Jt.nullish(),TokenSources:zod.z.array(ot).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:uR.nullish(),BonusWindow:aR.nullish()}).passthrough(),cR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:No.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),pR=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:Re.nullish(),Content:No.nullish(),Events:zod.z.array(cR).nullish(),Gate:Z.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),dR=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),hR=zod.z.object({Milestones:zod.z.record(zod.z.string(),fi).nullish()}).passthrough(),$n=zod.z.object({Definitions:zod.z.record(zod.z.string(),pR).nullish(),Settings:dR.nullish(),Presets:hR.nullish()}).passthrough(),mR=zod.z.object({Type:Oi,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:No.nullish(),Progress:Yu.nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:_e.nullish(),BonusWindow:lR.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),Jn=zod.z.object({ActiveEvents:zod.z.array(mR).nullish()}).passthrough(),Xu=zod.z.object({Tokens:zod.z.record(zod.z.string(),Yu).nullish()}),jo=zod.z.object({Type:Oi.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Wo=zod.z.object({Type:Oi.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:M.nullish(),Inventory:K.nullish()}),fR=zod.z.object({Type:Oi.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Ko=zod.z.array(we(Wo)),ec=zod.z.array(we(jo)),tc=zod.z.array(we(fR)),ut={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var ic="TimedEvent",nc={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:s=>{let e=null;for(let t of s.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Zn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(nc,{schema:Jn,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(nc,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return a;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(ic,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.timedEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ic,n.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",n.data)),n}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return a;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,i,n,r,o,c=1){if(!t)return u("client","LteID is required.");if(!i)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:n,AmountOverride:r,SourceParams:o,RollMultiplier:c},y=await this.ctx.api.timedEvent.grantTokens(h);return y.ok&&(this.ctx.data.user.applyResourceOperation(y.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",y.data)),y}async spendTokens(e,t,i){if(!t)return u("client","LteID is required.");if(i<=0)return u("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},r=await this.ctx.api.timedEvent.spendTokens(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",r.data)),r}async claimMilestone(e,t,i){if(!t||!i)return u("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},r=await this.ctx.api.timedEvent.claimMilestone(n);if(r.ok){let o=r.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return r}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return a;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return u("client","spends is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(r.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return u("client","grants is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(r.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let n=i.Data;n.Type&&n.LteID&&n.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(n.Type,n.LteID,n.MilestoneID,n.TokenEntityID),!t&&n.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(n.Rewards,n.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var gR=zod.z.object({UserID:zod.z.string(),Score:W.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:p.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:qe.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),Li=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:W.nullish(),CycleEndUtc:p.nullish(),TopUsers:zod.z.array(gR).nullish(),BracketID:zod.z.string().nullish()}),yR=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:p.nullish(),ClaimDeadlineUtc:p.nullish(),MilestoneTokensEarned:W.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Yn=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:W.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:W.nullish(),MilestoneTokensEarned:W.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(yR).nullish()}),Xn=zod.z.object({LeaderboardID:zod.z.string(),NewScore:W,CycleVersion:zod.z.number()}),er=zod.z.object({ServerTimeUtc:p,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),tr=zod.z.object({ServerTimeUtc:p,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:M.nullish(),Inventory:K.nullish()}),rc=zod.z.array(we(Li)),ir=zod.z.array(we(Yn)),sc=zod.z.array(we(er)),oc=zod.z.array(we(tr)),ac=zod.z.array(we(Xn)),RR=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:we(er).nullish(),Milestones:zod.z.array(we(tr)).nullish()}),lc=zod.z.array(RR),CR=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:we(Li).nullish(),Progress:we(Yn).nullish()}),uc=zod.z.array(CR),SR=zod.z.string(),cc=zod.z.object({Rank:zod.z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:mo.nullish()}).passthrough(),xR=zod.z.object({RankRewards:zod.z.array(cc).nullish()}).passthrough(),bR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),DR=zod.z.object({Milestones:Q.nullish(),RankRewards:Q.nullish()}).passthrough(),IR=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:SR.nullish(),Schedule:Re.nullish(),ChainEvents:zod.z.array(bR).nullish(),Gate:Z.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(cc).nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:DR.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(ot).nullish()}).passthrough(),PR=zod.z.object({Milestones:zod.z.record(zod.z.string(),fi).nullish(),RankRewards:zod.z.record(zod.z.string(),xR).nullish()}).passthrough(),nr=zod.z.object({Definitions:zod.z.record(zod.z.string(),IR).nullish(),Presets:PR.nullish()}).passthrough(),je={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 pc="Leaderboard",dc={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"]},rr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(dc,{schema:ir,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(pc,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.leaderboard.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(pc,n.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",n.data)),n}async getLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return u("client","LeaderboardID is required.");if(t<=0)return u("client","Score must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},n=await this.ctx.api.leaderboard.submitScore(i);if(n.ok){let r=n.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),r.NewScore,t,r.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",r);}return n}async submitScoreFromSource(e,t,i,n,r=1){if(!e)return u("client","LeaderboardID is required.");if(!t)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:n,RollMultiplier:r},c=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(c.ok){let h=c.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),h.NewScore,h.NewScore,h.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",h);}return c}async claimCycleReward(e){if(!e)return u("client","LeaderboardID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",n);}return i}async claimMilestone(e,t,i){if(!e||!t)return u("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},r=await this.ctx.api.leaderboard.claimMilestone(n);if(r.ok){let o=r.data;i||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 r}async getFriendsLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(u("client","leaderboardIDs is required.")):this.ctx.cache.read(dc,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}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 u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(n.Data.LeaderboardID)),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(n.Data.LeaderboardID),n.Data.MilestoneID),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return u("client","scores is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(n.Data.LeaderboardID),n.Data.NewScore,n.Data.NewScore,n.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let n of i.data){let r=this.cycleDocID(n.LeaderboardID);n.CycleReward?.Success&&n.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(r),n.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.CycleReward.Data.Resources,n.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of n.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(r,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",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let n of i.data)n.Progress?.Success&&n.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(n.LeaderboardID),n.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var Qo=zod.z.object({}).passthrough().transform(s=>s),sr=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>gc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:W.nullish(),UserState:Qo.nullish(),NextTier:zod.z.lazy(()=>fc).nullish()}).passthrough(),hc=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:W.nullish(),NewStatusTokens:W.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),Ho=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:M.nullish(),Inventory:K.nullish()}),mc=Ct(Ho);var fc=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:W.nullish(),TierReachedReward:H.nullish()}).passthrough(),gc=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:W.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(fc).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var vR=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Seasons:zod.z.array(gc).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:Z.nullish()}).passthrough(),or=zod.z.object({Chains:zod.z.record(zod.z.string(),vR).nullish()}).passthrough(),Ft={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var yc="Season",Rc={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:s=>{let e=Date.parse(s.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},ar=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Rc,{schema:sr,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(yc,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.season.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(yc,n.data),this.ctx.emitter.emit("season:definitionsLoaded",n.data)),n}getActiveSeason(e,t){return e?this.ctx.cache.read(Rc,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(u("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}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 u("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","Amount must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${G()}`},n=await this.ctx.api.season.grantStatusTokens(i);return n.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,n.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",n.data)),n}async claimTierReward(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","TierNumber must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${G()}`},n=await this.ctx.api.season.claimTierReward(i);if(n.ok){let r=n.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",r);}return n}async claimTierRewardsBatch(e,t){if(!e)return u("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return u("client","TierNumbers is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${G()}`},r=await this.ctx.api.season.claimTierRewardsBatch(n);if(r.ok){let o=r.data;for(let c of o.Items??[]){let h=c.Data?.TierNumber;c.Success&&typeof h=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,h);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return r}};var Cc="Premium",lr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Cc,e);if(t){let r={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",r),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.premium.getDefinitions(i);return n.ok&&n.data.Premium&&(this.ctx.data.config.patchSection(Cc,n.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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 u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},n=await this.ctx.api.premium.activateTrial(i);return n.ok&&(n.data.Premium&&this.ctx.data.user.applyPremium(n.data.Premium),this.ctx.emitter.emit("premium:trialActivated",n.data)),n}async purchaseItemOrCurrency(e,t,i="Default",n=1,r){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:n,CreditsConfirmationID:r,RelatedEntityID:`premium_purchase_${e}_${t}`},c=await this.ctx.api.premium.purchaseItemOrCurrency(o);if(c.ok&&!c.data.CreditsConfirmation){let h=c.data;h.Premium&&this.ctx.data.user.applyPremium(h.Premium),this.ctx.data.user.applyResourceOperation(h.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",h);}return c}async purchaseRealMoney(e,t,i,n,r,o,c,h){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!n||!r)return u("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return a;let y={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:n,ReceiptData:r,PurchaseToken:o,PackageName:c,AppStoreEnvironment:h,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(y);if(V.ok){let oe=V.data;oe.Premium&&this.ctx.data.user.applyPremium(oe.Premium),this.ctx.data.user.applyResourceOperation(oe.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",oe);}return V}};var ur=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:p.nullish()}),$o=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:W.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),ur).nullish(),UpdatedAt:p.nullish()}).passthrough(),Sc=zod.z.object({Characters:zod.z.record(zod.z.string(),$o).nullish()}),Jo=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),Zo=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),xc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),ur).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),bc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),TR=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Dc=zod.z.object({ServerTimeUtc:p,Characters:zod.z.record(zod.z.string(),TR).nullish(),Inventory:K.nullish()}),Yo=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:M.nullish()}),Ic=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:M.nullish(),Inventory:K.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:ur.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Pc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:ur.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),vc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),AR=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:p.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:ce.nullish()}),wR=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(AR).nullish()}),Tc=zod.z.object({ServerTimeUtc:p,Characters:zod.z.record(zod.z.string(),wR).nullish()}),Ac=Ct(Yo),wc=Ct(Zo),kc=Ct(Jo),Xo=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),zc=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:ce.nullish(),CostCurve:Ne.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Ne.nullish(),RankCurve:Ne.nullish(),Requirements:zod.z.array(Xo).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),kR=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Xo).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(),Mc=zod.z.object({Slots:zod.z.record(zod.z.string(),kR).nullish()}).passthrough(),Oc=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(),zR=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),MR=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:ce.nullish()}).passthrough(),OR=zod.z.object({Stats:Q.nullish(),Levels:Q.nullish(),Equipment:Q.nullish()}).passthrough(),Ec=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:Ne.nullish()}).passthrough(),ea="@skin";function ER(s){return !!s&&s.startsWith("@")}var UR=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),qR=zod.z.object({PriceOptions:ce.nullish(),Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),LR=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Xo).nullish()}).passthrough(),BR=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Oc.nullish(),Item:UR.nullish(),Sale:qR.nullish(),Requirements:LR.nullish()}).passthrough(),GR=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),BR).nullish()}).passthrough(),FR=zod.z.object({CharacterID:zod.z.string(),Identity:Oc.nullish(),Classification:zR.nullish(),Unlock:MR.nullish(),Presets:OR.nullish(),Equipment:Mc.nullish(),Stats:zod.z.record(zod.z.string(),zc).nullish(),RankLadder:Ec.nullish(),RankStatCurve:Ne.nullish(),StatMaxLevelCurve:Ne.nullish(),Skins:GR.nullish()}).passthrough(),_R=zod.z.object({Stats:zod.z.record(zod.z.string(),zc).nullish()}).passthrough(),VR=zod.z.object({RankLadder:Ec.nullish()}).passthrough(),NR=zod.z.object({Equipment:Mc.nullish()}).passthrough(),jR=zod.z.object({Stats:zod.z.record(zod.z.string(),_R).nullish(),Levels:zod.z.record(zod.z.string(),VR).nullish(),Equipment:zod.z.record(zod.z.string(),NR).nullish()}).passthrough(),cr=zod.z.object({Definitions:zod.z.record(zod.z.string(),FR).nullish(),Presets:jR.nullish()}).passthrough(),We={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"},WR="SKIN_ALREADY_OWNED";var ta="Character",pr=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(ta)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([n,r])=>r?.Unlock?.UnlockedByDefault===true&&!i[r.CharacterID??n])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(ta,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.character.getCharacterDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ta,n.data),this.ctx.emitter.emit("character:definitionsLoaded",n.data)),n}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${G()}`},n=await this.ctx.api.character.unlockCharacter(i);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},r.Power!=null&&(o.Power=r.Power),o.UpdatedAt=r.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",r);}return n}async upgradeStatLevel(e,t,i){if(!e||!t)return u("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${G()}`,SelectedOptionID:i?.selectedOptionID,CreditsConfirmationID:i?.creditsConfirmationID,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},r=await this.ctx.api.character.upgradeStatLevel(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;this.ctx.data.user.patchCharacter(o.CharacterID,c=>{c.StatLevels??={},c.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(c.Power=o.Power),c.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return r}async upgradeCharacterLevel(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${G()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},n=await this.ctx.api.character.upgradeCharacterLevel(i);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,o=>{o.Level=r.NewLevel,r.Power!=null&&(o.Power=r.Power),o.UpdatedAt=r.ServerTimeUtc,r.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",r);}return n}async equipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},n=await this.ctx.api.character.equipItems(i);return n.ok&&(this.applyEquipChangesLocally(e,n.data),this.ctx.emitter.emit("character:itemsEquipped",n.data)),n}async unequipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},n=await this.ctx.api.character.unequipItems(i);if(n.ok){let r=n.data;this.applyUnequipChangesLocally(e,r),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:r.ClearedSlotIDs??[],power:r.Power??null});}return n}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return a;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,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${G()}`},r=await this.ctx.api.character.unlockSkin(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.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 r}async equipSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},r=await this.ctx.api.character.equipSkin(n);if(r.ok){let o=r.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return r}async unequipSkin(e){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let n=i.data;n.Cleared&&(this.applyInventoryDelta(n.Inventory),this.applySkinLocally(n.CharacterID,null,n.Power,n.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",n);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):a}applySkinLocally(e,t,i,n){let r=this.ctx.data.user;r.patchCharacterEquipment(e,ea,t??null),r.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=n;});}async unlockCharactersBatch(e){if(!e||e.length===0)return u("client","characterIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level??=1,r.StatLevels??={},r.Equipment??={},n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level=n.NewLevel,n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(r.StatLevels??={},r.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.StatLevels??={},r.StatLevels[n.StatID]=n.StatLevel,n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[n,r]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,n,r);i.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let r of i)n.patchCharacterEquipment(e,r,null);n.patchCharacter(e,r=>{t.Power!=null&&(r.Power=t.Power),r.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,n]of Object.entries(e.Characters??{})){for(let r of n.ClearedSlotIDs??[])t.patchCharacterEquipment(i,r,null);t.patchCharacter(i,r=>{n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=e.ServerTimeUtc;});}}};var Uc="Match",dr=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,n,r,o){let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:n,TargetUserID:r,SelectedOptionID:o,RelatedEntityID:`pvp_create_${c.userID}_${G()}`},y=await this.ctx.api.match.createMatch(h);return y.ok&&(this.ctx.data.user.applyResourceOperation(y.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",y.data)),y}async updateMatch(e,t={}){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},n=await this.ctx.api.match.updateMatch(i);return n.ok&&this.ctx.emitter.emit("match:updated",n.data),n}async cancelMatch(e){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,n){let r=this.ctx.auth.context;if(!r)return a;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:n,RelatedEntityID:`pvp_battle_${e}_${G()}`},c=await this.ctx.api.match.instantBattle(o);if(c.ok){let h=c.data,y=this.ctx.data.config.itemDefinitions;if(h.Resources)this.ctx.data.user.applyResourceOperation(h.Resources,y);else if(h.ResourcesDual){let V=h.ResourcesDual;V.FromUserID===r.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,y):V.ToUserID===r.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,y);}this.ctx.emitter.emit("match:instantBattleCompleted",h);}return c}async saveStrategy(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let n=this.ctx.authedRequest();if(!n)return a;n.Page=e,n.PageSize=t,n.Statuses=i;let r=await this.ctx.api.match.getMyMatches(n);return r.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",r.data),r}async getAvailableMatches(e=0,t=20,i=false){let n=this.ctx.authedRequest();if(!n)return a;n.Page=e,n.PageSize=t,n.OnlyPublic=i;let r=await this.ctx.api.match.getAvailableMatches(n);return r.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",r.data),r}async getDefinitions(e){let t=this.ctx.cache.configSection(Uc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.match.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Uc,n.data),this.ctx.emitter.emit("match:definitionsLoaded",n.data)),n}};var qc="Craft",hr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(qc,e);if(t){let r={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.craft.getDefinitions(i);return n.ok&&n.data.CraftDefinitions&&(this.ctx.data.config.patchSection(qc,n.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",n.data.CraftDefinitions)),n}async craft(e,t,i=1,n,r,o){if(!e)return u("client","CraftID is required.");let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:n,InputInstanceIDs:r,CreditsConfirmationID:o,RelatedEntityID:`craft_${e}_${c.userID}_${G()}`},y=await this.ctx.api.craft.craft(h);return y.ok&&!y.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(y.data.Resources,y.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",y.data)),y}};var _t=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(_t),zod.z.record(zod.z.string(),_t)]));var Vt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Lc=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Xt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Bi(s){return s!==Xt.Pending&&s!==Xt.Running}var KR={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 QR(s){return s?/\b(AI_[A-Z_]+)\s*:/.exec(s)?.[1]??null:null}var HR=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),$R=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),mr=zod.z.object({CreditsConfirmation:fe.nullish(),GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Lc.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),_t).nullish(),Assets:zod.z.array(HR).nullish(),Error:$R.nullish(),Charge:M.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:M.nullish(),Context:zod.z.record(zod.z.string(),_t).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish()}),Bc=zod.z.object({Data:zod.z.array(mr).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),JR=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(),Di=zod.z.record(zod.z.string(),zod.z.string()),ZR=zod.z.object({Key:zod.z.string().nullish(),Role:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),Label:Di.nullish()}).passthrough(),YR=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:Di.nullish(),Placeholder:Di.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string().nullish(),Label:Di.nullish()}).passthrough()).nullish()}).passthrough(),XR=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:Di.nullish(),Description:Di.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(ZR).nullish(),Variables:zod.z.array(YR).nullish()}).passthrough(),eC=zod.z.object({Modality:Lc.nullish(),Async:zod.z.boolean().nullish(),Limits:Se.nullish(),PriceOptions:ce.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:H.nullish(),PromptVariables:zod.z.array(JR).nullish(),AllowFreePrompt:zod.z.boolean().nullish(),PlatformTemplateId:zod.z.string().nullish(),PlatformTemplate:XR.nullish(),FreePerDay:zod.z.number().nullish(),FreeLeftToday:zod.z.number().nullish()}).passthrough(),Gc=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),eC).nullish()}).passthrough(),Be={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"};var Fc="AI",tC=/^[A-Za-z0-9_-]{1,128}$/,iC=2e3,nC=5e3,rC=30*6e4;function sC(s,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(n),e?.removeEventListener("abort",i),t();},n=setTimeout(i,s);e?.addEventListener("abort",i,{once:true});})}var fr=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(Fc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.ai.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Fc,n.data),this.ctx.emitter.emit("ai:definitionsLoaded",n.data)),n}generateText(e,t,i){return this.generate(e,{Text:t},i,n=>this.ctx.api.ai.generateText(n))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,n=>this.ctx.api.ai.generateImage(n))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,n=>this.ctx.api.ai.editImage(n))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,n=>this.ctx.api.ai.generateVideo(n))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,n=>this.ctx.api.ai.generateAudio(n))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,n=>this.ctx.api.ai.generateMusic(n))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,i){return this.generate(e,{TemplateInputs:t},i,n=>this.ctx.api.ai.generateFromTemplate(n))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,n=>this.ctx.api.ai.generateThreeD(n))}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)):a}async getGeneration(e){if(!e)return u("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):a}isTerminal(e){return Bi(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let c=await this.getGeneration(e);if(!c.ok)return c;i=c.data;}else {if(!e?.GenerationID)return u("client","GenerationID is required.");i=e;}let n=Date.now()+(t.timeoutMs??rC),r=Math.max(1,t.intervalMs??iC),o=Math.max(r,t.maxIntervalMs??nC);for(;!Bi(i.Status);){if(t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");if(Date.now()+r>n)return u("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await sC(r,t.signal),t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");let c=await this.pollFor(i);if(r=Math.min(o,Math.round(r*1.5)),!c.ok){if(c.reason==="connection")continue;return c}i=c.data,Bi(i.Status)||t.onUpdate?.(i);}return N(i)}pollFor(e){switch(e.Modality){case Vt.Text:return this.getText(e.GenerationID);case Vt.Image:return this.getImage(e.GenerationID);case Vt.Audio:return this.getAudio(e.GenerationID);case Vt.Music:return this.getMusic(e.GenerationID);case Vt.Video:return this.getVideo(e.GenerationID);case Vt.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,n){if(!e)return u("client","FeatureKey is required.");let r=i?.relatedEntityID;if(r!==void 0&&!tC.test(r))return u("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,Variables:i?.variables,Context:i?.context,RelatedEntityID:r??G()},c=await n(o);return c.ok&&!c.data.CreditsConfirmation&&(await this.reconcileCharge(c.data,true),this.emitView(c.data)),c}async poll(e,t){if(!e)return u("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.GenerationID=e;let n=await t(i);return n.ok&&(await this.reconcileCharge(n.data,false),this.emitView(n.data)),n}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Xt.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===Xt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Xt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var ia="Collection",gr=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let i=e.cache.configSection(ia),n=Object.keys(i?.Collections??{});if(n.length===0||t)return false;let r=e.cache.configSection("Season");return Object.values(r?.Chains??{}).some(c=>(c?.Seasons??[]).some(h=>!!h?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==n[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ia,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.collection.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ia,n.data),this.ctx.emitter.emit("collection:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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,i=1,n){let r=this.ctx.auth.context;if(!r)return a;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${r.userID}_${G()}`},c=await this.ctx.api.collection.openPack(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",c.data)),c}async openCollectionChest(e,t,i=1){let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${n.userID}_${G()}`},o=await this.ctx.api.collection.openCollectionChest(r);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 i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${G()}`},r=await this.ctx.api.collection.useCollectibleJoker(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",r.data)),r}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${G()}`},r=await this.ctx.api.collection.claimSetReward(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",r.data)),r}async claimSetRewardsBatch(e){if(!e||e.length===0)return u("client","sets is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${G()}`},n=await this.ctx.api.collection.claimGrandPrize(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",n.data)),n}async sendTradeOffer(e,t,i,n,r,o=false){let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:n,RequestedCollectibleID:r,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${c.userID}_${n}_${G()}`},y=await this.ctx.api.collection.sendTradeOffer(h);return y.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",y.data)),y}async cancelTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${G()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${G()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${G()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var oC=zod.z.object({}).passthrough().transform(s=>s),aC={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},lC={Active:"Active",Left:"Left",Replaced:"Replaced"},uC=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),cC=zod.z.object({UserID:zod.z.string().nullish(),PublicData:qe.nullish(),BuildObjectsProgress:uC.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:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),pC=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(),dC=zod.z.object({Objects:zod.z.array(pC).nullish()}).passthrough(),_c=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(cC).nullish(),BuildObjectsState:dC.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:zod.z.number().nullish()}).passthrough(),Vc=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>Nc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),hC=zod.z.string(),na=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(),mC=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:H.nullish()}).passthrough(),fC=zod.z.object({Objects:zod.z.array(mC).nullish(),PriceOptions:ce.nullish(),SpinnerTable:zod.z.array(na).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),Nc=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:hC.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:fC.nullish(),GrandPrize:H.nullish()}).passthrough(),gC=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Events:zod.z.array(Nc).nullish(),Gate:Z.nullish()}).passthrough(),yr=zod.z.object({ServerTimeUtc:p.nullish(),UserState:oC.nullish(),ActiveGroup:_c.nullish()}),ra=zod.z.object({ServerTimeUtc:p.nullish(),Group:_c.nullish(),SecondsRemaining:W.nullish()}),jc=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Resources:M.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:na.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(na).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),sa=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Wc=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Rr=zod.z.object({Chains:zod.z.record(zod.z.string(),gC).nullish()}).passthrough(),gt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Kc="CoopEvent",Qc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},Cr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Qc,{schema:yr,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Kc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.coopEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Kc,n.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",n.data)),n}async getActiveEvent(e){if(!e)return u("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(Qc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return a;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 u("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return u("client","CoopChainID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let n=i.data.Group;n&&this.ctx.data.user.patchCoopEventActiveGroup(n.GroupID??null,n.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,n,r){if(!e||!t)return u("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:n,CreditsConfirmationID:r,RelatedEntityID:G()},c=await this.ctx.api.coopEvent.spin(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(c.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",c.data)),c}async claimObjectReward(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var yC={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},RC={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},CC=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:p.nullish(),CompletedAtUtc:p.nullish(),LastExecutedAtUtc:p.nullish(),NextAvailableAtUtc:p.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),SC=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),Hc=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:p.nullish(),ExhaustedAtUtc:p.nullish(),ExpiredAtUtc:p.nullish(),DismissedAtUtc:p.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:p.nullish(),Nodes:zod.z.record(zod.z.string(),CC).nullish(),Tracks:zod.z.record(zod.z.string(),SC).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),xC=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:p.nullish(),ActiveOfferExpiresAtUtc:p.nullish(),ActiveOffer:Hc.nullish(),NextCycleStartsAtUtc:p.nullish(),LastUpdatedUtc:p.nullish(),DismissSkipAvailableAtUtc:p.nullish(),LastDismissedAtUtc:p.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),bC=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),DC=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:p.nullish(),LastActivatedAtUtc:p.nullish(),LastExhaustedAtUtc:p.nullish(),NodeCounts:zod.z.record(zod.z.string(),bC).nullish()}).passthrough(),IC=zod.z.object({Slots:zod.z.record(zod.z.string(),xC).nullish(),OfferHistory:zod.z.record(zod.z.string(),DC).nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),PC={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},vC={Eq:"Eq",Gte:"Gte",Lte:"Lte"},TC=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),Sr=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(),$c=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),Jc=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),AC=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Behaviour:Q.nullish()}).passthrough(),wC=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:Sr.nullish(),Availability:$c.nullish(),Behaviour:Jc.nullish(),Queue:zod.z.array(TC).nullish(),Presets:AC.nullish()}).passthrough(),kC=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),zC=zod.z.object({RewardedVideo:kC.nullish()}).passthrough(),MC=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),OC=zod.z.object({Identity:Q.nullish(),Graph:Q.nullish(),Milestones:Q.nullish()}).passthrough(),EC=zod.z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish()}).passthrough(),UC=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),qC=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(),LC=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(MC).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),Zc=zod.z.object({Options:ce.nullish()}).passthrough(),Yc=zod.z.object({Grants:H.nullish(),TrackChanges:zod.z.array(UC).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),BC=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:Sr.nullish(),Pricing:Zc.nullish(),Reward:Yc.nullish(),Action:zC.nullish(),UnlockRules:LC.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:Se.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:EC.nullish()}).passthrough(),Xc=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(BC).nullish(),Tracks:zod.z.array(qC).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),ep=zod.z.object({Milestones:zod.z.record(zod.z.string(),_e).nullish(),ClaimMode:zod.z.string().nullish(),Token:Jt.nullish()}).passthrough(),tp=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:Sr.nullish(),Graph:Xc.nullish(),Milestones:ep.nullish(),Presets:OC.nullish()}).passthrough(),GC=zod.z.object({Identity:zod.z.record(zod.z.string(),Sr).nullish(),Availability:zod.z.record(zod.z.string(),$c).nullish(),Behaviour:zod.z.record(zod.z.string(),Jc).nullish(),Graph:zod.z.record(zod.z.string(),Xc).nullish(),Milestones:zod.z.record(zod.z.string(),ep).nullish(),Pricing:zod.z.record(zod.z.string(),Zc).nullish(),Reward:zod.z.record(zod.z.string(),Yc).nullish()}).passthrough(),oa=zod.z.object({Slots:zod.z.record(zod.z.string(),wC).nullish(),Offers:zod.z.record(zod.z.string(),tp).nullish(),Presets:GC.nullish()}).passthrough(),ip=zod.z.object({DealOfferDefinitions:oa.nullish()}),np=zod.z.object({DealOffers:IC.nullish()}),FC=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(),_C=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:tp.nullish(),ActivationState:Hc.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:p.nullish(),Cost:vt.nullish(),Milestone:FC.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),xr=zod.z.object({Slots:zod.z.array(_C).nullish()}),rp=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.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:M.nullish(),Inventory:K.nullish()}),sp=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),op=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),ap=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),lp=zod.z.object({ServerTimeUtc:p.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:M.nullish(),Inventory:K.nullish()}),xt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var VC="DealOffer",up={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},br=class{constructor(e){this.ctx=e;e.cache.bindLoginView(up,{schema:xr,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(VC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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(up,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return a;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 u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${G()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,n){if(!e||!t)return u("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return a;let r=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:r??`deal_exec_${e}_${t}_${G()}`},c=await this.ctx.api.dealOffer.executeNode(o);return c.ok&&!c.data.CreditsConfirmation&&(c.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",c.data)),c}async recordShow(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${G()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return u("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${G()}`},n=await this.ctx.api.dealOffer.claimMilestone(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",n.data)),n}async claimMilestonesBatch(e,t){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${G()}`},r=await this.ctx.api.dealOffer.claimMilestonesBatch(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",r.data)),r}};var cp="Referral",Dr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(cp,e);if(t){let r={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",r),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.referral.getDefinitions(i);return n.ok&&n.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(cp,n.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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=$t.parseReferralCode(e)?.toUpperCase();if(!t)return u("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},r=await this.ctx.api.referral.activateReferralCode(n);if(r.ok){let o=r.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 r}async claimInviteReward(e){let t=e.trim();if(!t)return u("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},r=await this.ctx.api.referral.claimInviteReward(n);if(r.ok){let o=r.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 r}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return u("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},r=await this.ctx.api.referral.claimInviteRewardsBatch(n);if(r.ok){let o=r.data;for(let c of o.Items??[])c.Success&&c.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(c.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return r}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return a;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 NC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},pp=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),jC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},WC=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),KC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},QC=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),nt={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},HC={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"},$C=100,JC=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),dp=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(),ZC=zod.z.object({Texts:zod.z.record(zod.z.string(),JC).nullish(),Category:pp.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:dp.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),YC=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:pe.nullish(),Cost:pe.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:p.nullish(),SenderGate:Z.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),XC=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(),eS=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(XC).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:p.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:pe.nullish(),SenderGate:Z.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),hp=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(),ZC).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),YC).nullish(),Transfer:eS.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(),tS=zod.z.object({MessageID:zod.z.string(),Source:WC,Category:pp,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:dp.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:H.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:p,ExpiresAt:p.nullish(),ReadAt:p.nullish(),ClaimedAt:p.nullish()}).passthrough(),iS=zod.z.object({MessageID:zod.z.string(),Module:QC,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:H.nullish()}).passthrough(),aa=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),mp=zod.z.object({ServerTimeUtc:p.nullish(),Messages:zod.z.array(tS).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(iS).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),Ir=zod.z.object({ServerTimeUtc:p.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),la=zod.z.object({ServerTimeUtc:p.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(aa).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),nS=zod.z.object({MessageID:zod.z.string(),Rewards:pe.nullish()}).passthrough(),Pr=zod.z.object({ServerTimeUtc:p.nullish(),Claimed:zod.z.array(nS).default([]),Failed:zod.z.array(aa).default([]),Resources:M.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),fp=zod.z.object({ServerTimeUtc:p.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(aa).default([]),Resources:M.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish()}).passthrough(),gp=zod.z.object({ServerTimeUtc:p.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish(),RecipientReceives:pe.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),yp=zod.z.object({ServerTimeUtc:p.nullish(),ResetsAt:p.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:p.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:p.nullish()}).passthrough().nullish()}).passthrough();var ua="Mailbox",ca={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},vr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ca,{schema:Ir,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(ca,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(ua)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(ua,e);if(t)return N(t);let i=this.request();if(!i)return a;let n=await this.ctx.api.mailbox.getDefinitions(i);return n.ok&&this.ctx.data.config.patchSection(ua,n.data),n}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 a;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(ca,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return a;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 a;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return u("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):a}async claimRewards(e){let t=(e??[]).map(n=>n?.trim()).filter(Boolean);if(t.length===0)return u("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):a}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):a}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 i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return a;let n=await this.ctx.api.mailbox.deleteMessages(i);return n.ok&&this.emitCounters(n.data),n}async sendGift(e,t){if(!e?.trim())return u("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return u("client","Recipients are required.");let n=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!n)return a;let r=await this.ctx.api.mailbox.sendGift(n);return r.ok&&(r.data.Resources&&this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",r.data)),r}async sendTransfer(e,t,i){if(!e?.trim())return u("client","RecipientUserID is required.");if(!i?.requestID?.trim())return u("client","requestID is required.");let n=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!n)return a;let r=await this.ctx.api.mailbox.sendTransfer(n);return r.ok&&(r.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(r.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",r.data)),r}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):a}};var Tr={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},pa="idos-app",Rp=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()}),Cp=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:M.nullish()});var da={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},rS=5*6e4;function Ar(){return Yt()}async function ha(s){let e=await wt(da.request,da.response,{titleID:s.titleID,userID:s.userID,requestID:s.requestID,placementID:s.placementID,adUnitID:s.adUnitID??null},{answerTimeoutMs:rS});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var sS=new Set(["CANCELLED","DECLINED","CLOSED"]),oS=45e3,aS=s=>new Promise(e=>setTimeout(e,s)),wr=class{constructor(e){this.ctx=e;}ctx;get available(){return Ar()}async showRewarded(e){if(!Ar())return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let i=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!i.ok)return {status:"unavailable",reason:i.error};let n=i.data;if(!n.Allowed)return {status:"denied",reason:n.DenyReason??void 0,retryAfterSeconds:n.RetryAfterSeconds??void 0};if(n.ProviderID!==pa||!n.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let r=await ha({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:n.RequestID,placementID:e,adUnitID:n.AdUnitID});return r.ok?{...await this.awaitReward(n.RequestID,r.via),requestID:n.RequestID}:{status:sS.has(r.error??"")?"cancelled":"unavailable",reason:r.error}}async awaitReward(e,t){let i=Date.now()+oS;for(;;){let n=this.ctx.authedRequest();if(!n)return {status:"pending",via:t};let r=await this.ctx.api.advertising.completeView({...n,RequestID:e});if(r.ok&&r.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:r.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((r.ok?r.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>i)return {status:"pending",via:t,reason:r.ok?void 0:r.error};await aS(o);}}};var lS={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},uS={Title:"Title",Platform:"Platform"},Sp=zod.z.object({UserID:zod.z.string(),PublicData:qe.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),Gi=zod.z.object({Friends:zod.z.array(Sp).nullish()}),cS=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),Fi=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:Sp.nullish(),Counters:cS.nullish()}),pS={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},dS={Like:"Like",Favorite:"Favorite"},hS={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},mS={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},fS={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},gS=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),yS=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(gS).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),OccurredAt:p.nullish(),OwnerImpact:M.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),xp=zod.z.object({Items:zod.z.array(yS).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:p.nullish()}).passthrough(),_i=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:p.nullish()}).passthrough(),RS=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(),Nt=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:RS.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),bp=zod.z.object({Items:zod.z.array(Nt).nullish()}).passthrough(),ma={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},CS=zod.z.object({UserID:zod.z.string(),PublicData:qe.nullish(),Mutual:zod.z.boolean().nullish(),Since:p.nullish()}).passthrough(),kr=zod.z.object({Items:zod.z.array(CS).nullish(),...ma}).passthrough(),SS=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:p.nullish()}).passthrough(),Dp=zod.z.object({Items:zod.z.array(SS).nullish(),...ma}).passthrough(),zr=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:qe.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:p.nullish(),EditedAt:p.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Ip=zod.z.object({Items:zod.z.array(zr).nullish(),...ma,TotalCount:zod.z.number().nullish()}).passthrough(),Pp=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),vp=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),Tp=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(),xS="FRIENDS_FROM_PLATFORM",bS={Off:"Off",Default:"Default",Always:"Always"},DS={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Ap=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(),xe={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"};var fa={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Mr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fa,{schema:_i,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return a;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 a;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 a;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 a;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return u("client","TargetUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return u("client","FriendUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return a;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(fa,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return a;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 a;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(fa,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 i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):a}async getEntityStates(e,t){if(!t?.length)return u("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):a}async addComment(e,t,i,n){let r=this.targetRequest(e,t);if("ok"in r)return r;if(!i?.trim())return u("client","Text is required.");r.Text=i,r.ParentCommentID=n;let o=await this.ctx.api.social.addComment(r);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return u("client","CommentID is required.");if(!t?.trim())return u("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return a;i.CommentID=e,i.Text=t;let n=await this.ctx.api.social.editComment(i);return n.ok&&this.ctx.emitter.emit("social:commentEdited",n.data),n}async deleteComment(e){if(!e)return u("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let n=this.targetRequest(e,t);return "ok"in n?n:(n.ParentCommentID=i.parentCommentID,this.applyPage(n,i.cursor,i.limit),this.ctx.api.social.getComments(n))}async report(e,t,i,n){let r=this.targetRequest(e,t);if("ok"in r)return r;if(!i)return u("client","ReportReason is required.");r.ReportReason=i,r.ReportComment=n;let o=await this.ctx.api.social.report(r);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,n){let r=this.targetRequest(t,i);if("ok"in r)return r;r.ReactionKind=n;let o=await this.ctx.api.social[e](r);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let n=this.ctx.authedRequest();return n?(this.applyPage(n,t,i),this.ctx.api.social[e](n)):a}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return u("client","EntityType is required.");if(!t)return u("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):a}};var wp="TimedBoost";function IS(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var Or=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(wp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.timedBoost.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(wp,n.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",n.data)),n}async getActive(){let e=this.ctx.authedRequest();if(!e)return a;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 a;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 i=e.trim();if(!IS(i))return u("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${i}_${G()}`},r=await this.ctx.api.timedBoost.activate(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;if(o.ActivatedBoost){let c=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,c);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return r}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return a;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 Et={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},PS={Client:"Client",Server:"Server",System:"System"},vS=zod.z.enum(["Client","Server","System"]).catch("Client"),TS=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:p.nullish(),Version:zod.z.number().nullish(),LastWriter:vS.nullish(),ExpiresAt:p.nullish()}).passthrough(),Er=zod.z.record(zod.z.string(),TS),kp=zod.z.object({Version:zod.z.number().nullish(),Private:Er.nullish(),Public:Er.nullish(),ReadOnly:Er.nullish()}),ga=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Er.nullish()}),ya=zod.z.object({ServerTimeUtc:p.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:p.nullish()}),AS=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:p.nullish()}),zp=zod.z.object({ServerTimeUtc:p.nullish(),Results:zod.z.array(AS).nullish()}),Mp=zod.z.object({ServerTimeUtc:p.nullish(),DeletedCount:zod.z.number().nullish()}),Op=zod.z.object({Results:zod.z.array(ga).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),wS={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},kS=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),zS=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:kS.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Ur=zod.z.object({Keys:zod.z.record(zod.z.string(),zS).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(),yt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var MS="UserCustomData";function Ep(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var qr=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(MS,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return a;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 u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TargetUserID=t;let n=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return n.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",n.data),n}async setPrivateData(e,t){return this.setData(e,t,Et.Private)}async setPublicData(e,t){return this.setData(e,t,Et.Public)}async setData(e,t,i){let n=e.trim();if(!Ep(n))return u("client",'KeyID is required and must not contain "." or "$".');if(t==null)return u("client","Value is required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Value:t},c=await(i===Et.Private?this.ctx.api.userCustomData.setPrivateData(r):this.ctx.api.userCustomData.setPublicData(r));if(c.ok){let h=c.data;this.ctx.data.user.patchUserCustomDataKey(i,h.KeyID,t,h.Version??0,h.ExpiresAt),this.ctx.emitter.emit(i===Et.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",h);}return c}async deleteKey(e,t){let i=e.trim();if(!Ep(i))return u("client",'KeyID is required and must not contain "." or "$".');if(t!==Et.Private&&t!==Et.Public)return u("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},r=await this.ctx.api.userCustomData.deleteKey(n);return r.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),r}async batchSet(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let n of i.data.Results??[]){let r=n.Bucket??Et.Private,o=e.find(c=>c.Bucket===r&&c.KeyID===n.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(r,n.KeyID,o.Value,n.Version??0,n.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let n of e)this.ctx.data.user.removeUserCustomDataKey(n.Bucket,n.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return u("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var OS="TitleCustomDataDefinitions",Up=50;function ES(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}function Ra(s){if(s.ExpiresAt==null)return false;let e=Date.parse(s.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function US(s){let e={};for(let[t,i]of Object.entries(s))Ra(i)||(e[t]=i);return e}var Lr=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(OS,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return a;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(r=>r.trim()).filter(r=>r.length>0);if(!t.length)return u("client","At least one KeyID is required.");if(t.some(r=>!ES(r)))return u("client",'KeyID must not contain "." or "$".');if(t.length>Up)return u("client",`At most ${Up} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return a;i.KeyIDs=t;let n=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return n.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",n.data),n}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Ra(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Ra(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=US(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 Br=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return a;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 a;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 a;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 a;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var qS=15,LS="GameLoop",qp="BoardDefinition",Gr=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 a;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(LS,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(qp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),N(i);let n=this.ctx.authedRequest();if(!n)return a;let r=await this.ctx.api.gameLoop.getBoardDefinition(n,e);return r.ok&&(this.ctx.data.config.patchSection(qp,r.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",r.data)),r}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return u("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return a;i.StageLevel=e;let n=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return n.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",n.data),n}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return u("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopRoll(i);if(n.ok){let r=n.data,o=pu(new Date,qS);this.ctx.data.user.patchBoardState(c=>{c.Position=r.NewPosition,c.CyclesCompleted=(c.CyclesCompleted??0)+(r.CyclesCompletedDelta??0),c.LastRollAtUtc=new Date().toISOString(),r.ActionRequired&&r.ActionData?c.Pending={Type:r.ActionRequired,TargetUserID:r.ActionData.TargetUserID,TargetPublicData:r.ActionData.PublicData,TargetBuildingStates:r.ActionData.TargetBuildingStates??void 0,TargetHasShield:r.ActionData.TargetHasShield??void 0,RollMultiplier:r.UsedMultiplier??1,ExpiresAtUtc:o}:r.SpecialModeOffer&&(c.Pending={Type:"SPECIAL",RollMultiplier:r.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:r.SpecialModeOffer.ModeID??void 0,Choices:r.SpecialModeOffer.Choices??void 0}});}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),r.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",r);}return n}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopAttack(i);if(n.ok){let r=n.data;this.ctx.data.user.clearBoardPending(),r.IsBotTarget&&r.Operation?this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs):!r.IsBotTarget&&r.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(r.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",r);}else await this.getUserBoardState();return n}async boardLoopRaid(e,t){if(e<0||e>11)return u("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${G()}`},r=await this.ctx.api.gameLoop.boardLoopRaid(n);if(r.ok){let o=r.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 r}async boardLoopRaidFast(e){if(!e.length)return u("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(n.ok){let r=n.data;r.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(r)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",r);}else await this.getUserBoardState();return n}async boardLoopBuild(e){if(e<0)return u("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopBuild(i);if(n.ok){let r=n.data;r.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(r.BuiltIndex,o=>{r.NewLevel!=null&&(o.Level=r.NewLevel),o.IsDamaged=false,r.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",r);}return n}async boardSpecialChoose(e,t,i){if(!e)return u("client","choiceID must not be empty.");let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:i,RelatedEntityID:`special_choose_${n.userID}_${G()}`},o=await this.ctx.api.gameLoop.boardSpecialChoose(r);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;c.Mode==="Instant"||c.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(y=>{y.ChoiceID=e,y.ChosenMode=c.Mode??"Timed",y.StartedAtUtc=c.StartedAtUtc??null,y.DurationSeconds=c.DurationSeconds??null,y.AdViewsUsed=0;}),c.Operation&&this.ctx.data.user.applyResourcesWithDelta(c.Operation,c.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",c);}return o}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(n.ok){let r=n.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=r.AdViewsUsed??0,o.AccumulatedMultiplier=r.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",r);}return n}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${G()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},n=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(n.ok){let r=n.data;this.ctx.data.user.clearBoardPending(),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",r);}return n}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return a;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 a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return u("client","milestoneID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},n=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",n.data)),n}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}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 Fr=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,n){let r=e.trim();if(!r)return u("client","FunctionName is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:r,FunctionParameter:t,RevisionSelection:i,SpecificRevision:n},c=await this.ctx.api.cloudCode.execute(o);return c.ok&&this.ctx.emitter.emit("cloudCode:executed",c.data),c}};var Lp=zod.z.object({ServerTimeUtc:p,SourceType:hi,SourceID:zod.z.string(),TargetType:hi,TargetID:zod.z.string(),SourceSpent:W,FeeAmount:W,RateApplied:Y,TargetCredited:W}),Bp=zod.z.object({ServerTimeUtc:p,SourceType:hi,SourceID:zod.z.string(),TargetType:hi,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),Gp=zod.z.object({ServerTimeUtc:p,SpendID:zod.z.string(),Resources:M.nullish()}),Vi={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},BS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},Fp=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),GS={Automatic:"Automatic",Manual:"Manual"},FS=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),_S=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.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(),VS=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),NS=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),jS=zod.z.object({TargetCurrencyType:hi.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),_p=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:FS.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(jS).nullish()}).passthrough(),Vp=zod.z.object({CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough(),WS=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:_S.nullish(),Recharge:VS.nullish(),Conversion:_p.nullish(),Permissions:NS.nullish(),Audit:Vp.nullish(),Status:Fp.nullish()}).passthrough(),KS=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),QS=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),HS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),$S=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(),Ca=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:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:zod.z.array(KS).nullish(),Limits:QS.nullish(),Permissions:HS.nullish(),Conversion:_p.nullish(),Audit:Vp.nullish(),Status:Fp.nullish(),ServerGrantPolicy:$S.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),JS=zod.z.object({SpendID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),PriceOptions:zod.z.record(zod.z.string(),An).nullish()}).passthrough(),_r=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),WS).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),Ca).nullish(),Spends:zod.z.record(zod.z.string(),JS).nullish()}).passthrough();var ZS={EVM:"EVM",Solana:"Solana"},YS=zod.z.enum(["EVM","Solana"]).catch("EVM"),XS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},ex=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),tx={Token:"Token",Nft:"Nft"},Np=zod.z.enum(["Token","Nft"]).catch("Token"),ix={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},nx=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),rx={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},sx=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),ox={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Sa=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),jp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Vr(s){let e=s?.trim();return e||jp.GameTopUp}var ax={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},Wp=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),lx=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(),Kp=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),ux=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:YS.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:Kp.nullish(),NftCollections:zod.z.array(lx).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(),cx=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Kp.nullish()}).passthrough(),px=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),dx={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},hx=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Qp=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:hx.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),mx=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),fx={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Ni=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),gx=zod.z.object({Mode:Ni.nullish(),TokenGates:zod.z.array(Qp).nullish()}).passthrough(),xa=zod.z.object({SystemState:cx.nullish(),Networks:zod.z.record(zod.z.string(),ux).nullish(),AccountSafety:px.nullish(),WalletLogin:mx.nullish(),PlayAccess:gx.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),yx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:p.nullish(),LastUsedAt:p.nullish(),LinkType:ex.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),Hp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:Np.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),Rx=zod.z.object({Status:nx.nullish(),Tier:sx.nullish(),VerifiedAt:p.nullish(),ExpiresAt:p.nullish(),RejectedAt:p.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),Cx=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),Sx=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:zod.z.record(zod.z.string(),Cx).nullish()}).passthrough(),xx=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:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),bx=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(),xx).nullish()}).passthrough(),Dx=zod.z.object({Tokens:Sx.nullish(),Nfts:bx.nullish()}).passthrough(),ba=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),jt=zod.z.object({Granted:zod.z.boolean(),Mode:Ni.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:p.nullish(),Balances:zod.z.array(ba).nullish()}).passthrough(),Ix=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:p.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:p.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(ba).nullish()}).passthrough(),Px=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),$p=zod.z.object({Mode:Ni.nullish(),TokenGates:zod.z.array(Qp).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(Px).nullish(),Status:jt.nullish()}).passthrough(),vx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:p.nullish(),LoggedInAt:p.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(ba).nullish()}).passthrough(),Tx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:p.nullish()}).passthrough(),Ax=zod.z.object({Version:zod.z.number().nullish(),Stats:Dx.nullish(),LinkedWallets:zod.z.record(zod.z.string(),yx).nullish(),LastWalletLogin:vx.nullish(),PlayAccess:Ix.nullish(),PendingWithdrawals:zod.z.array(Hp).nullish(),Kyc:Rx.nullish(),FirstActivityAt:p.nullish(),LastActivityAt:p.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(Tx).nullish()}).passthrough(),wx=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:p}).passthrough(),Ii=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),wx).nullish(),PendingAdded:Hp.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),kx=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough().transform(s=>s),zx=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.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:Wp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Sa.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.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:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:p.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:p.nullish(),RefundCheckedAt:p.nullish()}).passthrough(),Mx=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.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:Wp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Sa.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.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:p.nullish()}).passthrough(),Jp=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Da=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(Jp).nullish(),Signature:zod.z.string().nullish()}).passthrough(),Ia=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(Jp).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(),Zp=zod.z.object({Blockchain:xa.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),Ca).nullish()}).passthrough(),Yp=zod.z.object({State:Ax.nullish(),CryptoBalances:zod.z.record(zod.z.string(),kx).nullish()}).passthrough(),Xp=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:Ii.nullish()}).passthrough(),ed=zod.z.object({ServerTimeUtc:p.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:M.nullish(),Inventory:K.nullish()}).passthrough(),td=zod.z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:p.nullish(),EvmSignature:Da.nullish(),SolanaSignature:Ia.nullish(),StateDelta:Ii.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),id=zod.z.object({ServerTimeUtc:p.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:p.nullish(),Resources:M.nullish(),EvmSignature:Da.nullish(),SolanaSignature:Ia.nullish(),StateDelta:Ii.nullish(),Inventory:K.nullish()}).passthrough(),nd=zod.z.object({TokenTransactions:zod.z.array(zx).nullish(),NFTTransactions:zod.z.array(Mx).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Pa=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:zod.z.string().nullish()}).passthrough(),rd=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:Np.nullish(),EvmSignature:Da.nullish(),SolanaSignature:Ia.nullish()}).passthrough(),sd=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:Sa.nullish(),StateDelta:Ii.nullish()}).passthrough(),Je={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 Ox="Blockchain",od="Blockchain:Definitions",Nr=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(od,e);if(t)return N(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return a;let n=this.ctx.api.blockchain.getDefinitions(i).then(r=>(r.ok&&(this.ctx.data.config.patchSection(Ox,r.data.Blockchain),this.ctx.data.config.patchSection(od,r.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",r.data)),r)).finally(()=>{this.definitionsInflight===n&&(this.definitionsInflight=null);});return this.definitionsInflight=n,n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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 u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositToken(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",n.data)),n}async depositNFT(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositNFT(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",n.data)),n}async requestTokenWithdrawal(e,t,i,n,r){if(!e)return u("client","CurrencyID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!n)return u("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return a;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=n,o.Category=Vr(r);let c=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return c.ok&&(this.ctx.data.user.applyBlockchainStateDelta(c.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",c.data)),c}async requestNFTWithdrawal(e,t,i,n,r,o,c){if(!e)return u("client","ItemID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!n)return u("client","Amount is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.NetworkID=t,h.WalletAddress=i,h.Amount=n,h.Category=Vr(r),o!==void 0&&(h.Level=o),c&&(h.ItemInstanceID=c);let y=await this.ctx.api.blockchain.requestNFTWithdrawal(h);return y.ok&&(this.ctx.data.user.applyBlockchainStateDelta(y.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(y.data.Resources,y.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",y.data)),y}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return a;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return u("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return u("client","TitleTransactionID is required.");if(!t)return u("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TitleTransactionID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.confirmWithdrawal(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",n.data)),n}async donateToDeveloper(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToDeveloper(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",n.data),n}async donateToUsersPool(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToUsersPool(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",n.data),n}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return a;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 a;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var Ex={Head:"Head",Torso:"Torso",Legs:"Legs"},jr=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),Ux={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},va=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),ld=zod.z.object({AttackTarget:jr,DefenseTarget:jr});var qx=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),Lx=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:jr.nullish(),DefenseZone:jr.nullish(),HitType:qx.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),Bx=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(),Gx=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:p,ExpiresAt:p.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),ad=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:$o.nullish(),BattleStrategy:zod.z.array(ld).nullish(),UnstackableItems:zod.z.record(zod.z.string(),Gx).nullish(),Stats:Bx.nullish()}).passthrough(),Fx=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:pe.nullish(),NetReward:pe.nullish(),BattleLog:zod.z.array(Lx).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:ad.nullish(),P2BattleProfile:ad.nullish()}).passthrough(),ud=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:p.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(ld).nullish(),TargetUserID:zod.z.string().nullish(),Entry:pe.nullish(),CreationCostPaid:pe.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:p.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:p.nullish(),Status:va.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:p.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:p.nullish()}).passthrough(),cd=zod.z.object({Status:va,MatchID:zod.z.string(),Entry:pe.nullish(),Resources:M.nullish()}),pd=zod.z.object({Match:ud.nullish()}),dd=zod.z.object({MatchID:zod.z.string(),Status:va,Resources:M.nullish()}),hd=zod.z.object({Battle:Fx.nullish(),Resources:M.nullish(),ResourcesDual:Tt.nullish()}),Ta=zod.z.object({Matches:zod.z.array(ud).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),bt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var _x=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var Vx=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),Nx=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(),jx=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),Wx=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:jx.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),Kx=zod.z.object({Kind:Vx.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Ne.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),Qx=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(Kx).nullish()}).passthrough(),ei=zod.z.object({Terms:zod.z.array(Qx).nullish()}).passthrough(),Hx=zod.z.object({Health:ei.nullish(),Damage:ei.nullish(),Armor:ei.nullish(),AttackSpeed:ei.nullish(),CritChance:ei.nullish(),CritDamage:ei.nullish(),Dodge:ei.nullish()}).passthrough(),md=zod.z.object({StatMapping:Nx.nullish(),Combat:Wx.nullish(),Formula:Hx.nullish()}).passthrough(),$x=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),ji=zod.z.object({Kind:_x.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:en.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),fd=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(ji).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),gd=zod.z.object({PriceOptions:ce.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:Se.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),Jx=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:$x.nullish(),Entry:fd.nullish(),Creation:gd.nullish(),Settings:md.nullish()}).passthrough(),Zx=zod.z.object({Rules:zod.z.record(zod.z.string(),Jx).nullish(),Defaults:md.nullish(),EntryDefaults:fd.nullish(),CreationDefaults:gd.nullish()}).passthrough(),Aa=zod.z.object({InstantBattle:Zx.nullish()}).passthrough(),yd=Aa;var Yx={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},wa=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),Xx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},ka=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),eb={Burn:"Burn",Ledger:"Ledger"},tb=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Kr={Item:"Item",VirtualCurrency:"VirtualCurrency"},za=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),ib=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:W.nullish()}).passthrough(),Qr=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(ji).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Ma=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:W.nullish(),Sink:tb.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),ib).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),nb=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(),rb=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:Se.nullish(),BuyLimits:Se.nullish(),ListingFeeOptions:ce.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),sb=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:W.nullish(),BidLimits:Se.nullish()}).passthrough(),ob=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:Se.nullish(),FillLimits:Se.nullish()}).passthrough(),ab=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:Se.nullish()}).passthrough(),lb=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Oa=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:Re.nullish(),PricePolicy:Qr.nullish(),Commission:Ma.nullish(),Tradability:nb.nullish(),Listings:rb.nullish(),Auctions:sb.nullish(),BuyOrders:ob.nullish(),DirectTrades:ab.nullish(),Matching:lb.nullish()}).passthrough(),Rd=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:W.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:p.nullish()}).passthrough(),ub=zod.z.object({BidAxisType:mi.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:W.nullish(),CurrentBid:W.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(Rd).nullish()}).passthrough(),Wr=zod.z.object({LastAt:p.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),cb=zod.z.object({Create:Wr.nullish(),Buy:Wr.nullish(),Sell:Wr.nullish(),Bid:Wr.nullish()}).passthrough(),pb=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),db=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:p,ExpiresAt:p.nullish(),EquippedSlot:pb.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),Ut=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:wa.nullish(),Status:ka.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:qe.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:za.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:W.nullish(),GoodsInstances:zod.z.array(db).nullish(),Price:pe.nullish(),Auction:ub.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),hb=zod.z.object({GoodsType:za.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(wa,W).nullish()}).passthrough(),Cd=zod.z.object({Definitions:Oa.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),Ea=zod.z.object({Offers:zod.z.array(Ut).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Sd=zod.z.object({Groups:zod.z.array(hb).nullish()}).passthrough(),xd=zod.z.object({Offer:Ut.nullish()}).passthrough(),ct=zod.z.object({OfferID:zod.z.string().nullish(),Status:ka.nullish(),Settlement:Tt.nullish(),Resources:M.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Wi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:Ut.nullish(),Resources:M.nullish(),Matched:zod.z.boolean().nullish(),Settlement:ct.nullish()}).passthrough(),bd=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:W.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:p.nullish(),Resources:M.nullish()}).passthrough(),Hr=zod.z.object({MyOffers:zod.z.array(Ut).nullish(),MyBids:zod.z.array(Ut).nullish(),MyBuyOrders:zod.z.array(Ut).nullish(),IncomingTrades:zod.z.array(Ut).nullish(),OutgoingTrades:zod.z.array(Ut).nullish(),Claimables:zod.z.array(Ut).nullish(),DrainedRefunds:zod.z.array(Rd).nullish(),Limits:cb.nullish()}).passthrough(),mb=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:wa.nullish(),FinalStatus:ka.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:za.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:W.nullish(),PricePaid:pe.nullish(),CommissionTaken:pe.nullish(),CompletedAt:p.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),Dd=zod.z.object({Entries:zod.z.array(mb).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Oe={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 fb="Marketplace",Id={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"]},$r=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Id,{schema:Hr,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(fb,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return a;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,i,n=20){if(!e)return u("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return a;r.ItemID=e,r.OfferTypeFilter=t,r.ContinuationToken=i,r.PageSize=n;let o=await this.ctx.api.marketplace.getOffersByItem(r);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let n=this.ctx.authedRequest();if(!n)return a;n.ItemID=e,n.ContinuationToken=t,n.PageSize=i;let r=await this.ctx.api.marketplace.getBuyOrders(n);return r.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",r.data),r}getMyState(e,t){return this.ctx.cache.read(Id,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let n=this.ctx.authedRequest();if(!n)return a;i&&(n.HistoryFilter=i),n.ContinuationToken=e,n.PageSize=t;let r=await this.ctx.api.marketplace.getHistory(n);return r.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",r.data),r}async createListing(e,t,i,n,r,o,c){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!n)return u("client","PriceBundle is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.PriceBundle=n,h.DurationHours=r,h.ItemInstanceIDs=o,h.SelectedOptionID=c;let y=await this.ctx.api.marketplace.createListing(h);return this.applyCreateOfferResult(y,"marketplace:listingCreated"),y}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let n=this.ctx.authedRequest();if(!n)return a;let r=this.applyGoodsSelector(n,i);if(r)return r;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let n=this.ctx.authedRequest();if(!n)return a;let r=this.applyGoodsSelector(n,i);if(r)return r;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,n,r,o,c={}){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.BidAxisType=n,h.BidCurrencyID=c.bidCurrencyID,h.BidCatalogID=c.bidCatalogID,h.BidItemID=c.bidItemID,h.StartingBid=r,h.DurationHours=o,h.ItemInstanceIDs=c.itemInstanceIDs,h.SelectedOptionID=c.selectedOptionID;let y=await this.ctx.api.marketplace.createAuction(h);return this.applyCreateOfferResult(y,"marketplace:auctionCreated"),y}async placeBid(e,t){if(!e)return u("client","OfferID is required.");if(!t||t<=0)return u("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.BidAmount=t;let n=await this.ctx.api.marketplace.placeBid(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",n.data)),n}async claimAuction(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,n,r){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!n)return u("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return a;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=n,o.DurationHours=r;let c=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(c,"marketplace:buyOrderCreated"),c}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,n,r){if(!e)return u("client","TargetUserID is required.");if(!t)return u("client","CatalogID is required.");if(!i)return u("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return a;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=n,o.RequestedBundle=r;let c=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(c,"marketplace:directTradeCreated"),c}async respondDirectTrade(e,t){if(!e)return u("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.Accept=t;let n=await this.ctx.api.marketplace.respondDirectTrade(i);return n.ok&&(t&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",n.data)),n}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 a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return u("client","OfferID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.OfferID=e;let r=await t(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,r.data)),r}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=Kr.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Kr.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):u("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var Jr=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return u("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let n=await this.ctx.api.multiplayer.createRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",n.data),n}async joinRoom(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.JoinCode=t;let n=await this.ctx.api.multiplayer.joinRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",n.data),n}async leaveRoom(e,t={}){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let n=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",n.data),n}async claimHost(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.TargetUserID=t,n.Ban=i;let r=await this.ctx.api.multiplayer.kickMember(n);return r.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",r.data),r}async unbanMember(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.TargetUserID=t;let n=await this.ctx.api.multiplayer.unbanMember(i);return n.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",n.data),n}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return a;i.Page=e,i.PageSize=t;let n=await this.ctx.api.multiplayer.listRooms(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",n.data),n}async getRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.LastSeq=t;let n=await this.ctx.api.multiplayer.poll(i);return n.ok&&this.ctx.emitter.emit("multiplayer:polled",n.data),n}async sendSignal(e,t,i,n){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");if(!i)return u("client","SignalKind is required.");let r=this.ctx.authedRequest();if(!r)return a;r.RoomID=e,r.TargetUserID=t,r.SignalKind=i,r.Payload=n;let o=await this.ctx.api.multiplayer.sendSignal(r);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.ChatText=t;let n=await this.ctx.api.multiplayer.sendChat(i);return n.ok&&this.ctx.emitter.emit("multiplayer:chatSent",n.data),n}async setMemberState(e,t,i){if(!e)return u("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.Ready=t,n.MemberState=i;let r=await this.ctx.api.multiplayer.setMemberState(n);return r.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",r.data),r}};var Pd=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Zr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;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)):a}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 u("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):a}async getCreatorProfile(e,t,i){if(!e)return u("client","CreatorUserID is required.");let n=this.ctx.authedRequest();return n?(n.CreatorUserID=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getCreatorProfile(n)):a}async publish(e){if(!e.files||e.files.length===0)return u("client","At least one file is required.");let t=new Map,i=e.files.map((h,y)=>{if("sourceAssetUrl"in h)return {Role:h.role,ContentType:h.contentType,SourceAssetUrl:h.sourceAssetUrl};let V=vd(h.data,h.contentType);return t.set(y,V),{Role:h.role,ContentType:h.contentType,Size:V.size}}),n=e.thumbnail?vd(e.thumbnail.data,e.thumbnail.contentType):null,r=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&n?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:n.size}:void 0});if(!r.ok)return r;let o=r.data.Uploads??[];for(let h=0;h<o.length;h++){let y=o[h];if(!y||y.ServerCopy||!y.Url)continue;let V=t.get(h);if(!V)return u("client",`No bytes for file #${h+1}.`);let oe=await this.putBytes(y.Url,V,y.ContentType??V.type);if(!oe.ok)return oe}let c=r.data.ThumbnailUpload;if(c?.Url&&n){let h=await this.putBytes(c.Url,n,c.ContentType??n.type);if(!h.ok)return h}return this.ctx.credits.pay(h=>this.publishUploaded({CreditsConfirmationID:h,ContentID:r.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}):a}async publishUploaded(e){if(!e.ContentID)return u("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return a;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&!i.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let n=await this.ctx.api.workshop.updateContent(i);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let n=this.ctx.authedRequest();return n?(n.ContentType=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getMyContent(n)):a}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let n=await this.ctx.api.workshop.acquire(i);return n.ok&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",n.data)),n}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 i=[];for(let n of t.data.Files??[])if(n.Url)try{let r=await this.ctx.fetchImpl(n.Url);if(!r.ok)return u("connection",`Download failed (HTTP ${r.status}).`);i.push({role:n.Role??"main",contentType:n.ContentType??"application/octet-stream",data:await r.arrayBuffer()});}catch(r){return u("connection",`Download failed: ${r instanceof Error?r.message:String(r)}${Pd}`)}return N({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):a}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):a}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?N(!0):u("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return u("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}${Pd}`)}}contentRequest(e){if(!e)return u("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):a}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function vd(s,e){return s instanceof Blob?s:typeof s=="string"?new Blob([new TextEncoder().encode(s)],{type:e}):s instanceof Uint8Array?new Blob([s.slice().buffer],{type:e}):new Blob([s],{type:e})}var gb={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},yb=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Rb={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Td=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),Cb={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Ad=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),Sb={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},xb=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),bb={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},Db=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),Ib={Count:"Count",Sum:"Sum"},Pb=zod.z.enum(["Count","Sum"]).catch("Count"),vb={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},Tb=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),Ab={Strict:"Strict",Loose:"Loose"},wb=zod.z.enum(["Strict","Loose"]).catch("Strict"),kb=zod.z.object({Kind:Db,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),zb=zod.z.object({Type:Td,ItemType:Td.nullish(),Ref:kb.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:Ad.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()}),Mb=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Yr=zod.z.object({Mode:xb,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),Ob=zod.z.object({Read:zod.z.array(Yr).nullish(),Create:zod.z.array(Yr).nullish(),Update:zod.z.array(Yr).nullish(),Delete:zod.z.array(Yr).nullish()}),Ua=zod.z.object({Cost:pe.nullish(),Grant:pe.nullish()}),Eb=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()}),Ub=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:yb,Mode:wb.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),zb).nullish(),SortKeys:zod.z.array(Mb).nullish(),Access:Ob.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:Tb.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:Pb,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:Ad.optional()})).nullish(),Economy:zod.z.object({OnCreate:Ua.nullish(),OnUpdate:Ua.nullish(),OnDelete:Ua.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:zod.z.array(Eb).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()}),wd=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),Ub).default({})}),qb=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),kd=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),Pi=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(),qb).nullish()}),qa=zod.z.object({Item:Pi}),zd=zod.z.object({Items:zod.z.array(Pi).default([]),Missing:zod.z.array(zod.z.string()).default([])}),La=zod.z.object({Items:zod.z.array(Pi).default([]),NextCursor:zod.z.string().nullish()}),Md=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),Ba=zod.z.object({Item:Pi,AlreadyExists:zod.z.boolean().optional(),Economy:M.nullish()}),Od=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:M.nullish()}),Ed=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),Ud=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:Pi.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),qd=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),Ld=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),Bd=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({})}),Gd=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(Pi).default([])}),Lb={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 Bb=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Vd=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Fa=100,Fd=25,_d=100;function Gb(s,e,t){return {Field:s,Op:e,Value:t}}var Xr=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(a)}get(e,t,i={}){let n=rt(e)??Ki(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.get({...r,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let n=rt(e);if(n)return Promise.resolve(n);let r=[...new Set(t.filter(o=>Vd.test(o)))];return r.length?r.length>_d?Promise.resolve(u("client",`At most ${_d} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:r,Expand:i.expand})):Promise.resolve(u("client","At least one valid item id is required."))}query(e,t={},i={}){let n=rt(e)??Ga(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.query({...r,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let n=Math.max(1,i.maxItems??500),r=[],o=t.Cursor;for(;;){let c=await this.query(e,{...t,Cursor:o,Limit:t.Limit??Fa},i);if(!c.ok)return c;if(r.push(...c.data.Items),o=c.data.NextCursor??void 0,!o||r.length>=n)return N(r.slice(0,n))}}count(e,t={}){let i=rt(e)??Ga(t);return i?Promise.resolve(i):this.call(n=>this.ctx.api.dataCollections.count({...n,Collection:e,Query:t}))}create(e,t,i={}){let n=rt(e)??(i.itemID?Ki(i.itemID):null);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.create({...r,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,n={}){let r=rt(e)??Ki(t);return r?Promise.resolve(r):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:n.expectedVersion}))}set(e,t,i,n={}){return this.update(e,t,{Set:i},n)}increment(e,t,i,n=1){return this.update(e,t,{Inc:{[i]:n}})}delete(e,t,i={}){let n=rt(e)??Ki(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.delete({...r,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(u("client","Operations are empty."));if(e.length>Fd)return Promise.resolve(u("client",`At most ${Fd} operations per batch.`));let t=e.map(i=>rt(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let n=rt(e);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.getCounter({...r,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,n){let r=rt(e);return r?Promise.resolve(r):t?n>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:n})):Promise.resolve(u("client","File size must be positive.")):Promise.resolve(u("client","Field is required."))}async uploadFile(e,t,i,n={}){let r=n.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,r,i.size);if(!o.ok)return o;let c=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||r);return c.ok?o:c}async getPublicViews(e){let t=rt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return N(i);let n=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return n.ok&&this.publicViews.set(e,n.data),n}async readPublicView(e,t,i={}){let n=await this.getPublicViews(e);if(!n.ok)return n;let r=n.data.Views[t];if(!r)return u("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(r,Bd);if(!o.ok)return o;let c=o.data.Partitions[i.partition??""],h=Math.max(1,i.page??1);if(!c||h>c.Pages)return N({pointer:o.data,page:{Page:h,HasMore:false,Items:[]}});let y=await this.fetchJson(`${o.data.BaseUrl}${c.Segment}/page-${h}.json`,Gd);return y.ok?N({pointer:o.data,page:y.data}):y}getPublic(e,t){let i=rt(e)??Ki(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=rt(e)??Ga(t);return i?Promise.resolve(i):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(a)}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?N(!0):u("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return u("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return u("connection","Internet Connection Error")}if(!i.ok)return u("server",`CDN answered ${i.status}.`);let n;try{n=await i.json();}catch{return u("server","CDN answer is not JSON.")}let r=t.safeParse(n);return r.success?N(r.data):u("server","CDN answer has an unexpected shape.")}};function rt(s){return Bb.test(s??"")?null:u("client",`Collection id '${s}' is invalid (letters, digits, '_', '-', ':').`)}function Ki(s){return Vd.test(s??"")?null:u("client",`Item id '${s}' is invalid.`)}function Ga(s){return s.Limit!=null&&(s.Limit<1||s.Limit>Fa)?u("client",`Limit must be 1..${Fa}.`):(s.Where?.length??0)>8?u("client","At most 8 filters per query."):null}var _a={Open:"Open",Declared:"Declared"},Fb=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),_b=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),Nd=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Fb).nullish(),Dimensions:zod.z.array(_b).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),Wt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Dt={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},es=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Vb={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},Nb=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),jd=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(Nb).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Va={LogEvents:"LogEvents"};function Wd(s,e=0){let t=s??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let c=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:c==="iPad"?"tablet":"phone",deviceModel:c}}let n=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(n){let c=(n[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:n[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:c&&c!=="K"&&c!=="wv"?c:void 0}}let r=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(r)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(r[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 Kd(s){let e=typeof navigator>"u"?void 0:navigator,t=Wd(e?.userAgent??"",e?.maxTouchPoints??0),i={};s.appVersion&&(i.AppVersion=s.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let n=s.locale||e?.language;return n&&(i.Language=n),i}var jb=25,Wb=3e4,Qd=1800*1e3,Hd=500,Kb=5,Qb=1e3,Hb=3600*1e3,$d="idos_analytics_queue",Na="idos_analytics_pending",ja="idos_analytics_opt_out",Jd="idos_analytics_first_open",Zd="idos_analytics_last_activity",Yd="idos_analytics_last_context",Xd="idos_analytics_owner",ts=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!es.test(e)?u("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):$b(e)?u("client",`Event name "${e}" uses a reserved prefix (${Dt.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return u("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Wt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return N(null);if(this.config()?.Enabled===false)return this.clear(),N(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return N(null);this.pending={BatchID:G(),Events:this.queue.splice(0,Dt.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=Kb)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(ja);return}this.write(ja,"1"),this.clear();}get isEnabled(){return this.read(ja)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(Xd);e&&t&&t!==e&&this.clear(),e&&this.write(Xd,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Wb),typeof window<"u"&&(window.addEventListener("visibilitychange",this.onVisibilityChange),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,typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),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(Zd)??"0");this.read(Jd)||(this.write(Jd,new Date().toISOString()),this.enqueue(Wt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Yd);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Wt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Wt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Yd,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Qd)&&this.enqueue(Wt.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=Qd&&this.enqueue(Wt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,n){if(!this.isEnabled||this.disabledByServer)return N(null);let r=this.config();if(r?.Enabled===false)return N(null);if(n&&r?.AutomaticEvents===false)return N(null);if(r?.Events?.[e]?.Blocked)return u("client",`Event "${e}" is blocked by the title.`);if(!n&&r?.EventNaming?.toLowerCase()===_a.Declared.toLowerCase()&&!r.Events?.[e])return u("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return u("client","value must be a finite number.");let o=Jb(t);if(o.error)return u("client",o.error);this.restore();let c={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(c.Params=o.params),i!==void 0&&(c.Value=i),this.queue.push(c),this.queue.length>Hd&&this.queue.splice(0,this.queue.length-Hd),this.touch(),this.persist(),this.started&&this.queue.length>=jb&&this.flush(),N(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},Qb));}dropStale(){let e=Date.now()-(Dt.maxEventAgeMs-Hb);this.queue=this.queue.filter(t=>{let i=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(i)||i>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=Kd({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson($d);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(Na);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson($d,this.queue),this.pending?this.writeJson(Na,this.pending):this.remove(Na);}touch(){this.write(Zd,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.platform.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.platform.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.platform.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 $b(s){let e=s.toLowerCase();return Dt.reservedPrefixes.some(t=>e.startsWith(t))}function Jb(s){if(!s)return {};let e=Object.keys(s);if(e.length===0)return {};if(e.length>Dt.maxParams)return {error:`Too many parameters: ${e.length}, max ${Dt.maxParams}.`};let t={};for(let i of e){if(!es.test(i))return {error:`Invalid parameter name "${i}".`};let n=s[i];typeof n=="string"?t[i]=n.length>Dt.maxStringValueLength?n.slice(0,Dt.maxStringValueLength):n:typeof n=="number"?Number.isFinite(n)&&(t[i]=n):typeof n=="boolean"&&(t[i]=n);}return {params:t}}var Zb="idos_experiments",is=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 a;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}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,i){let n=this.getParams(e)[t];if(n===void 0)return i;if(typeof i=="number"){let r=Number(n);return n.trim()!==""&&Number.isFinite(r)?r:i}if(typeof i=="boolean"){let r=n.trim().toLowerCase();return r==="true"||r==="1"?true:r==="false"||r==="0"?false:i}return n}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 n of e.Experiments??[])n?.ExperimentID&&t.set(n.ExperimentID,n);let i=[];for(let[n,r]of t){let o=this.views.get(n);(!o||o.VariantID!==r.VariantID||o.Status!==r.Status)&&i.push(r);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}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.platform.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.platform.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${Zb}:${this.ctx.settings.titleID}`}};function Kt(s,e,t,i){let r=`api/v2/${s&&s.length>0?s:"0"}/Client/${e}/${t}`;return i==null?r:`${r}/${i}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Kt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,n){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...n,ticket:t.ClientSessionTicket})}};var ns=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Va.LogEvents,e,jd,{silent:true})}};var Yb=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(),Xb={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},eD=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),tD=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:Re.nullish(),Gate:Z.nullish(),Variants:zod.z.array(Yb).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(eD).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),eh=zod.z.object({Experiments:zod.z.record(zod.z.string(),tD).nullish()}).passthrough(),iD={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},nD=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(),th=zod.z.object({Experiments:zod.z.array(nD).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),Wa={GetExperiments:"GetExperiments"};var rs=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Wa.GetExperiments,e,th)}};var ih=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:p.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:p,PlayAccess:jt.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:p.nullish()}),nh=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:p,RefreshToken:zod.z.string(),RefreshTokenExpiration:p.nullish(),PlayAccess:jt.nullish()}),rD=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),rh=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:Ni.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:rD.nullish()}).passthrough(),sh=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:p.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:jt.nullish()}).passthrough(),oh=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:p.nullish(),PlayAccess:jt.nullish()}).passthrough(),ah=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Ge=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:p.nullish()}),lh=zod.z.object({Message:zod.z.string(),ExpiresAt:p}),Le={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 ss=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Kt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,ih,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Le.RefreshSession),e,nh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Le.GetAuthOptions),e,rh,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Kt(this.ctx.settings.titleID,"Authentication",Le.LinkWallet,e.UserID??""),e,sh,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Kt(this.ctx.settings.titleID,"Authentication",Le.UnlinkWallet,e.UserID??""),e,oh,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Le.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Le.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Le.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Le.LoginWithGoogle,e)}loginWithApple(e){return this.login(Le.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Le.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(Le.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Le.RegisterWithEmail),e,ah,{ticket:null})}confirmEmailRegistration(e){return this.login(Le.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Le.ResendVerificationCode),e,Ge,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Le.RequestWalletChallenge),e,lh,{ticket:null})}loginWithWallet(e){return this.login(Le.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Le.ForgotPassword),e,Ge,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Le.ResetPassword),e,Ge,{ticket:null})}};var sD={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},uh=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),oD=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),ch=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),oD).nullish(),MissingKeyMode:uh.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),aD=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),ph=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:aD.nullish()}).passthrough(),os={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},lD=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),dh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:uh.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(lD).nullish()}).passthrough(),hh=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 Ka=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:ph.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()}).passthrough().transform(s=>s),mh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(s=>s),fh=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(s=>s),gh=zod.z.object({}).passthrough().transform(s=>s),yh=zod.z.object({}).passthrough().transform(s=>s),Rh=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:p.nullish(),LastActiveAt:p.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(),Ch=zod.z.object({Username:zod.z.string()}),pt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var as=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(pt.GetClientState,e,Ka)}getClientStateExcept(e){return this.send(pt.GetClientStateExcept,e,Ka)}getStateVersions(e){return this.send(pt.GetStateVersions,e,mh)}getUserState(e){return this.send(pt.GetUserState,e,fh)}getInventory(e){return this.send(pt.GetInventory,e,gh)}getEventTokens(e){return this.send(pt.GetEventTokens,e,yh)}getUsageTime(e){return this.send(pt.GetUsageTime,e,Rh)}addUsageTime(e){return this.send(pt.AddUsageTime,e,Ge,{silent:true})}deleteUserAccount(e){return this.send(pt.DeleteUserAccount,e,Ge)}changeUsername(e){return this.send(pt.ChangeUsername,e,Ch)}};var ls=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(Vi.Convert,e,Lp)}spend(e){return this.send(Vi.Spend,e,Gp)}cryptoConvert(e){return this.send(Vi.CryptoConvert,e,Bp)}};var uD=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),Qa=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:M.nullish(),FodderConsumed:zod.z.array(uD).nullish()}),Sh=zod.z.array(we(Qa)),us={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},cD={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},pD=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),dD={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},hD=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),mD=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),fD=zod.z.object({Networks:zod.z.record(zod.z.string(),mD).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),gD=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(),yD=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(),RD=zod.z.object({ValuationMode:pD.nullish(),WeightCurve:Ne.nullish(),Selection:hD.nullish()}).passthrough(),CD=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:Ne.nullish(),FlatBonusCurve:Ne.nullish(),PercentBonusCurve:Ne.nullish(),PowerCurve:Ne.nullish(),Fodder:RD.nullish()}).passthrough(),SD=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),xD=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:fD.nullish(),Stats:gD.nullish(),Equipment:yD.nullish(),Upgrade:CD.nullish(),Metadata:SD.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),bD=zod.z.object({Items:zod.z.record(zod.z.string(),xD).nullish()}).passthrough(),cs=zod.z.object({Catalogs:zod.z.record(zod.z.string(),bD).nullish()}).passthrough();function Pe(s){return zod.z.unknown().transform((e,t)=>{let i=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(i!=null){let r=fe.safeParse(i);return r.success?{...e,CreditsConfirmation:r.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${r.error.message}`}),zod.z.NEVER)}let n=s.safeParse(e);return n.success?n.data:(t.addIssue({code:"custom",message:n.error.message}),zod.z.NEVER)})}var ps=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(us.UpgradeLevel,e,Pe(Qa))}upgradeLevelsBatch(e){return this.send(us.UpgradeLevelsBatch,e,Sh)}};var ds=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(zt.Purchase,e,Oo)}purchaseBatch(e){return this.send(zt.PurchaseBatch,e,bu)}getDefinitions(e){return this.send(zt.GetDefinitions,e,kn)}getUserState(e){return this.send(zt.GetUserState,e,Du)}getStorefront(e){return this.send(zt.GetStorefront,e,zn)}getCreditsConfirmation(e){return this.send(zt.GetCreditsConfirmation,e,fe)}getCreditsBalance(e){return this.send(zt.GetCreditsBalance,e,xu)}};var DD={Apple:"Apple",Google:"Google"},hs=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(),ms=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),hs).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(s=>s),ID=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:ce.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$a=zod.z.object({Definitions:zod.z.record(zod.z.string(),ID).nullish()}).passthrough(),xh=zod.z.object({Premium:$a.nullish()}),bh=zod.z.object({ServerTimeUtc:p.nullish(),Premium:ms.nullish()}),fs=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),Premium:ms.nullish(),Subscription:hs.nullish(),Resources:M.nullish()}),ti={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var PD={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},vD=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Dh=zod.z.object({StartUtc:p.nullish(),EndUtc:p.nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Ja=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),TD=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),AD=zod.z.object({Rewards:Q.nullish(),Rules:Q.nullish(),Refund:Q.nullish()}).passthrough(),wD=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:vD.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:Dh.nullish(),Refund:Ja.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:TD.nullish(),Presets:AD.nullish()}).passthrough(),kD=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(),zD=zod.z.object({Rewards:H.nullish()}).passthrough(),MD=zod.z.object({Rules:Dh.nullish()}).passthrough(),OD=zod.z.object({Refund:Ja.nullish()}).passthrough(),ED=zod.z.object({Rewards:zod.z.record(zod.z.string(),zD).nullish(),Rules:zod.z.record(zod.z.string(),MD).nullish(),Refund:zod.z.record(zod.z.string(),OD).nullish()}).passthrough(),UD=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(),qD=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),wD).nullish(),Stores:zod.z.record(zod.z.string(),kD).nullish(),Presets:ED.nullish(),Validation:UD.nullish(),Refund:Ja.nullish()}).passthrough(),Ih=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:p.nullish(),LastPurchasedAt:p.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(),Ph=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:p.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:p.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:p.nullish()}).passthrough(),LD=zod.z.object({Products:zod.z.record(zod.z.string(),Ih).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Ph).nullish(),LastRefundCheckAt:p.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:p.nullish(),LastPurchaseAt:p.nullish()}).passthrough(),BD=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(),vh=zod.z.object({ServerTimeUtc:p,Purchase:qD.nullish(),Availability:zod.z.array(BD).nullish()}),Th=zod.z.object({ServerTimeUtc:p,Purchase:LD.nullish()}),GD={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},FD=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Za=zod.z.object({ServerTimeUtc:p,Store:Xi.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:FD.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish(),ProductState:Ih.nullish(),Premium:ms.nullish(),Subscription:hs.nullish(),SubscriptionMirror:Ph.nullish()}).passthrough(),Ah=zod.z.object({ServerTimeUtc:p,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:p.nullish()}).passthrough(),wh=Ct(Za),ii={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var gs=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(ii.GetDefinitions,e,vh)}getUserState(e){return this.send(ii.GetUserState,e,Th)}validatePurchase(e){return this.send(ii.ValidatePurchase,e,Za)}validatePurchasesBatch(e){return this.send(ii.ValidatePurchasesBatch,e,wh)}createTelegramInvoice(e){return this.send(ii.CreateTelegramInvoice,e,Ah)}};var _D=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),kh=zod.z.object({Reward:H.nullish(),Weight:zod.z.number().nullish(),AmountRange:_D.nullish()}).passthrough(),vi=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(kh).nullish()}).passthrough(),Ti=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(kh).nullish()}).passthrough(),VD=zod.z.object({RewardSlots:zod.z.array(vi).nullish()}).passthrough(),ND=zod.z.object({PityRules:zod.z.array(Ti).nullish()}).passthrough(),ys=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),VD).nullish(),PityPresets:zod.z.record(zod.z.string(),ND).nullish()}).passthrough();var jD=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),zh=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish(),Results:zod.z.array(M).nullish(),TriggeredPity:zod.z.array(jD).nullish()}),WD=zod.z.object({RewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),KD=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:W.nullish()}).passthrough(),QD=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ce.nullish(),RewardSlots:zod.z.array(vi).nullish(),PityRules:zod.z.array(Ti).nullish(),Presets:WD.nullish(),RewardMultiplier:tn.nullish(),SupplyLimits:zod.z.array(KD).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),HD=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Ya=zod.z.object({Definitions:zod.z.record(zod.z.string(),QD).nullish(),RewardPools:ys.nullish(),Settings:HD.nullish()}).passthrough(),Mh=zod.z.object({LootboxDefinitions:Ya.nullish()}),Rs={GetDefinitions:"GetDefinitions",Open:"Open"};var Cs=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(Rs.GetDefinitions,e,Mh)}open(e){return this.send(Rs.Open,e,Pe(zh))}};var $D=zod.z.object({}).passthrough().transform(s=>s),JD=zod.z.object({}).passthrough().transform(s=>s),ZD=zod.z.object({}).passthrough().transform(s=>s),YD=zod.z.object({}).passthrough().transform(s=>s),XD=zod.z.object({}).passthrough().transform(s=>s),eI=zod.z.object({}).passthrough().transform(s=>s),Oh=zod.z.object({ServerTimeUtc:p,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:$D,Resources:M.nullish(),Inventory:K.nullish()}),Eh=zod.z.object({ServerTimeUtc:p,AccrualID:zod.z.string(),AccruedSeconds:W.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:JD,Resources:M.nullish(),Inventory:K.nullish()}),Uh=zod.z.object({ServerTimeUtc:p,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:ZD,Resources:M.nullish(),Inventory:K.nullish()}),qh=zod.z.object({ServerTimeUtc:p,ClaimID:zod.z.string(),ClaimState:YD,Resources:M.nullish(),Inventory:K.nullish()}),tI={None:"None",Ad:"Ad",Vip:"Vip"},Lh=zod.z.object({ServerTimeUtc:p,WindowID:zod.z.string(),Boost:zod.z.string().nullish(),BaseAmount:W.nullish(),Multiplier:zod.z.number().nullish(),Granted:W.nullish(),WindowState:XD,Resources:M.nullish(),Inventory:K.nullish()}),Bh=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:W.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),iI=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),nI=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:H.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Qi=zod.z.object({Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Xa=zod.z.object({Availability:Q.nullish()}).passthrough(),rI=zod.z.object({Availability:zod.z.record(zod.z.string(),Qi).nullish()}).passthrough(),sI=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(nI).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:Qi.nullish(),Presets:Xa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),oI=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),aI=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(oI).nullish()}).passthrough(),lI=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Qi.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),uI=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:aI.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:lI.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),cI=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:H.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),pI=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(cI).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Qi.nullish(),Presets:Xa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),dI=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(),hI=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:H.nullish(),PremiumLimitOverrides:zod.z.array(dI).nullish(),Availability:Qi.nullish(),Presets:Xa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),mI=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(),el=zod.z.object({TierRewards:iI.nullish(),MilestoneRewardMultiplier:tn.nullish(),DailyCalendars:zod.z.record(zod.z.string(),sI).nullish(),IdleAccruals:zod.z.record(zod.z.string(),uI).nullish(),Comebacks:zod.z.record(zod.z.string(),pI).nullish(),Claims:zod.z.record(zod.z.string(),hI).nullish(),Windows:zod.z.record(zod.z.string(),mI).nullish(),Presets:rI.nullish()}).passthrough(),Gh=zod.z.object({RewardDefinitions:el.nullish()}),Fh=zod.z.object({Rewards:eI.nullish()}),It={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var Ss=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(It.GetRewardDefinitions,e,Gh)}getUserRewardsState(e){return this.send(It.GetUserRewardsState,e,Fh)}getMilestoneRewardMultiplier(e){return this.send(It.GetMilestoneRewardMultiplier,e,Bh)}claimDailyReward(e){return this.send(It.ClaimDailyReward,e,Oh)}collectIdleAccrual(e){return this.send(It.CollectIdleAccrual,e,Eh)}claimComebackReward(e){return this.send(It.ClaimComebackReward,e,Uh)}claimReward(e){return this.send(It.ClaimReward,e,qh)}claimRewardWindow(e){return this.send(It.ClaimRewardWindow,e,Lh)}};var xs=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(at.GetTutorialDefinitions,e,Xl)}getUserTutorialState(e){return this.send(at.GetUserTutorialState,e,sn)}startFlow(e){return this.send(at.StartFlow,e,Lt)}reportStepShown(e){return this.send(at.ReportStepShown,e,Lt)}completeStep(e){return this.send(at.CompleteStep,e,Lt)}completeStepsBatch(e){return this.send(at.CompleteStepsBatch,e,iu)}skipStep(e){return this.send(at.SkipStep,e,Lt)}skipFlow(e){return this.send(at.SkipFlow,e,Lt)}claimFlowReward(e){return this.send(at.ClaimFlowReward,e,tu)}resetFlow(e){return this.send(at.ResetFlow,e,Lt)}};var fI={Open:"Open",Application:"Application"},gI=zod.z.enum(["Open","Application"]).catch("Open"),yI={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},_h=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),RI={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},tl=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),CI={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var ni={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},SI=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(),Vh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:gI.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:_h.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(SI).nullish()}).passthrough(),xI=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(),bI=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:tl.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(),xI).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),DI=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:tl.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),Nh=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(bI).nullish(),Payouts:zod.z.array(DI).nullish()}).passthrough(),jh=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:tl.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),II=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),PI=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(II).nullish()}).passthrough(),vI=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(),Wh=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:_h.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(vI).nullish()}).passthrough(),TI=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),AI=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(TI).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(),Kh=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:PI.nullish(),SolanaSignature:AI.nullish(),StateDelta:Ii.nullish()}).passthrough();var bs=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(ni.GetCommunityMarketingState,e,Vh)}getEarnings(e){return this.send(ni.GetEarnings,e,Nh)}claim(e){return this.send(ni.Claim,e,jh)}checkJoinEligibility(e){return this.send(ni.CheckJoinEligibility,e,Wh)}withdrawCryptoReward(e){return this.send(ni.WithdrawCryptoReward,e,Kh)}};var Ds=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send($e.GetChatDefinitions,e,Gu)}getChannels(e){return this.send($e.GetChannels,e,Nn)}poll(e){return this.send($e.Poll,e,Fu)}getHistory(e){return this.send($e.GetHistory,e,_u)}getConversations(e){return this.send($e.GetConversations,e,ju)}sendMessage(e){return this.send($e.SendMessage,e,Vu)}openDirectChannel(e){return this.send($e.OpenDirectChannel,e,Nu)}markRead(e){return this.send($e.MarkRead,e,xi)}joinChannel(e){return this.send($e.JoinChannel,e,xi)}leaveChannel(e){return this.send($e.LeaveChannel,e,xi)}reportMessage(e){return this.send($e.ReportMessage,e,Wu)}ignoreUser(e){return this.send($e.IgnoreUser,e,xi)}unignoreUser(e){return this.send($e.UnignoreUser,e,xi)}};var Is=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(bi.GetPushConfig,e,Hu)}subscribePush(e){return this.send(bi.SubscribePush,e,_o)}unsubscribePush(e){return this.send(bi.UnsubscribePush,e,Ge)}getPushSubscriptions(e){return this.send(bi.GetPushSubscriptions,e,$u)}};var Ps=class extends B{constructor(e){super(e,"Localization");}send(e,t,i,n){let r=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${r}:${t.Locale}`:r,...n})}getLocalizationManifest(e){return this.send(os.GetLocalizationManifest,e,dh)}getLocalizationTable(e){return this.send(os.GetLocalizationTable,e,hh)}};var vs=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(ft.GetQuestDefinitions,e,rn)}getUserQuestState(e){return this.send(ft.GetUserQuestState,e,_l)}refreshQuestCycles(e){return this.send(ft.RefreshQuestCycles,e,Ge)}claimQuestReward(e){return this.send(ft.ClaimQuestReward,e,go)}claimQuestRewardsBatch(e){return this.send(ft.ClaimQuestRewardsBatch,e,jl)}claimMilestoneReward(e){return this.send(ft.ClaimMilestoneReward,e,yo)}claimMilestoneRewardsBatch(e){return this.send(ft.ClaimMilestoneRewardsBatch,e,Wl)}claimGroupCompletionReward(e){return this.send(ft.ClaimGroupCompletionReward,e,Vl)}addQuestProgress(e){return this.send(ft.AddQuestProgress,e,Nl)}};var Ts=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ut.GetActiveEvents,e,Jn)}getDefinitions(e){return this.send(ut.GetDefinitions,e,$n)}getUserLteState(e){return this.send(ut.GetUserLteState,e,Xu)}grantTokens(e){return this.send(ut.GrantTokens,e,M)}spendTokens(e){return this.send(ut.SpendTokens,e,jo)}claimMilestone(e){return this.send(ut.ClaimMilestone,e,Wo)}claimMilestonesBatch(e){return this.send(ut.ClaimMilestonesBatch,e,Ko)}claimAllMilestones(e){return this.send(ut.ClaimAllMilestones,e,Ko)}spendTokensBatch(e){return this.send(ut.SpendTokensBatch,e,ec)}grantTokensBatch(e){return this.send(ut.GrantTokensBatch,e,tc)}};var As=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(je.GetDefinitions,e,nr)}getLeaderboard(e){return this.send(je.GetLeaderboard,e,Li)}getMyProgress(e){return this.send(je.GetMyProgress,e,Yn)}submitScore(e){return this.send(je.SubmitScore,e,Xn)}submitScoreFromSource(e){return this.send(je.SubmitScoreFromSource,e,Xn)}claimCycleReward(e){return this.send(je.ClaimCycleReward,e,er)}claimMilestone(e){return this.send(je.ClaimMilestone,e,tr)}getFriendsLeaderboard(e){return this.send(je.GetFriendsLeaderboard,e,Li)}getLeaderboardsBatch(e){return this.send(je.GetLeaderboardsBatch,e,rc)}getProgressBatch(e){return this.send(je.GetProgressBatch,e,ir)}claimCycleRewardsBatch(e){return this.send(je.ClaimCycleRewardsBatch,e,sc)}claimMilestonesBatch(e){return this.send(je.ClaimMilestonesBatch,e,oc)}submitScoresBatch(e){return this.send(je.SubmitScoresBatch,e,ac)}claimAllRewardsBatch(e){return this.send(je.ClaimAllRewardsBatch,e,lc)}getOverviewBatch(e){return this.send(je.GetOverviewBatch,e,uc)}};var ws=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Ft.GetDefinitions,e,or)}getActiveSeason(e){return this.send(Ft.GetActiveSeason,e,sr)}getUserState(e){return this.send(Ft.GetUserState,e,Qo)}grantStatusTokens(e){return this.send(Ft.GrantStatusTokens,e,hc)}claimTierReward(e){return this.send(Ft.ClaimTierReward,e,Ho)}claimTierRewardsBatch(e){return this.send(Ft.ClaimTierRewardsBatch,e,mc)}};var ks=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(ti.GetDefinitions,e,xh)}getUserState(e){return this.send(ti.GetUserState,e,bh)}activateTrial(e){return this.send(ti.ActivateTrial,e,fs)}purchaseItemOrCurrency(e){return this.send(ti.PurchaseWithResources,e,Pe(fs))}purchaseRealMoney(e){return this.send(ti.PurchaseRealMoney,e,fs)}};var zs=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(We.GetCharacterDefinitions,e,cr)}getUserCharacters(e){return this.send(We.GetUserCharacters,e,Sc)}unlockCharacter(e){return this.send(We.UnlockCharacter,e,Pe(Yo))}upgradeStatLevel(e){return this.send(We.UpgradeStatLevel,e,Pe(Jo))}upgradeCharacterLevel(e){return this.send(We.UpgradeCharacterLevel,e,Pe(Zo))}equipItems(e){return this.send(We.EquipItems,e,xc)}unequipItems(e){return this.send(We.UnequipItems,e,bc)}unequipAllCharacters(e){return this.send(We.UnequipAllCharacters,e,Dc)}unlockCharactersBatch(e){return this.send(We.UnlockCharactersBatch,e,Ac)}upgradeCharacterLevelsBatch(e){return this.send(We.UpgradeCharacterLevelsBatch,e,wc)}upgradeStatLevelsBatch(e){return this.send(We.UpgradeStatLevelsBatch,e,kc)}unlockSkin(e){return this.send(We.UnlockSkin,e,Pe(Ic))}equipSkin(e){return this.send(We.EquipSkin,e,Pc)}unequipSkin(e){return this.send(We.UnequipSkin,e,vc)}getCharacterSkins(e){return this.send(We.GetCharacterSkins,e,Tc)}};var Ms=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(bt.CreateMatch,e,cd)}updateMatch(e){return this.send(bt.UpdateMatch,e,pd)}cancelMatch(e){return this.send(bt.CancelMatch,e,dd)}instantBattle(e){return this.send(bt.InstantBattle,e,hd)}saveStrategy(e){return this.send(bt.SaveStrategy,e,Ge)}getMyMatches(e){return this.send(bt.GetMyMatches,e,Ta)}getAvailableMatches(e){return this.send(bt.GetAvailableMatches,e,Ta)}getDefinitions(e){return this.send(bt.GetDefinitions,e,yd)}};var wI={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Qh=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),kI={None:"None",Min:"Min",Average:"Average",Max:"Max"},zI=zod.z.enum(["None","Min","Average","Max"]).catch("None"),MI={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},OI=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),EI={Clamp:"Clamp",Reject:"Reject"},UI=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),qI=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),LI=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:ho.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(qI).nullish()}),Hh=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,Type:Qh.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:M.nullish(),Inventory:K.nullish(),Results:zod.z.array(LI).nullish()}),BI=zod.z.object({CraftID:zod.z.string().nullish(),Type:Qh.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:ce.nullish(),OutputLevelMode:zI.nullish(),InputSelection:OI.nullish(),OutputLevelOverflow:UI.nullish()}).passthrough(),il=zod.z.object({Definitions:zod.z.record(zod.z.string(),BI).nullish()}).passthrough(),$h=zod.z.object({ServerTimeUtc:p.nullish(),CraftDefinitions:il.nullish()}),Os={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Es=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Os.GetDefinitions,e,$h)}craft(e){return this.send(Os.Craft,e,Pe(Hh))}};var GI=2e5,Us=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,Pe(mr),{timeoutMs:GI,autoRetry:false})}readGeneration(e,t){return this.send(e,t,mr,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Be.GetDefinitions,e,Gc)}generateText(e){return this.generate(Be.GenerateText,e)}getText(e){return this.readGeneration(Be.GetText,e)}generateImage(e){return this.generate(Be.GenerateImage,e)}editImage(e){return this.generate(Be.EditImage,e)}getImage(e){return this.readGeneration(Be.GetImage,e)}generateVideo(e){return this.generate(Be.GenerateVideo,e)}getVideo(e){return this.readGeneration(Be.GetVideo,e)}generateAudio(e){return this.generate(Be.GenerateAudio,e)}getAudio(e){return this.readGeneration(Be.GetAudio,e)}generateMusic(e){return this.generate(Be.GenerateMusic,e)}getMusic(e){return this.readGeneration(Be.GetMusic,e)}generateFromTemplate(e){return this.generate(Be.GenerateFromTemplate,e)}generateThreeD(e){return this.generate(Be.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Be.GetThreeD,e)}listGenerations(e){return this.send(Be.ListGenerations,e,Bc)}getGeneration(e){return this.readGeneration(Be.GetGeneration,e)}};var FI={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},_I=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),Jh=zod.z.object({}).passthrough().transform(s=>s),Ai=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()}),Zh=zod.z.object({GrantedCollectibles:zod.z.array(Ai).nullish(),DuplicateCollectibles:zod.z.array(Ai).nullish(),CollectionCurrencyEarned:W.nullish()}),Yh=zod.z.object({CreditsConfirmation:fe.nullish(),OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(Zh).nullish(),GrantedCollectibles:zod.z.array(Ai).nullish(),DuplicateCollectibles:zod.z.array(Ai).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Xh=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(Zh).nullish(),GrantedCollectibles:zod.z.array(Ai).nullish(),DuplicateCollectibles:zod.z.array(Ai).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),em=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),nl=zod.z.object({SetID:zod.z.string(),Resources:M.nullish(),Inventory:K.nullish()}),tm=zod.z.array(we(nl)),im=zod.z.object({Resources:M.nullish(),Inventory:K.nullish()}),VI=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:qe.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:_I.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RespondedAtUtc:p.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),nm=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:p.nullish(),Resources:M.nullish()}),rm=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),sm=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()}),om=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),rl=zod.z.object({Offers:zod.z.array(VI).nullish()}),NI=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(),jI=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(NI).nullish(),SetCompletionReward:H.nullish()}).passthrough(),WI=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(jI).nullish(),GrandPrize:H.nullish()}).passthrough(),am=zod.z.object({BonusRewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),KI=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:ce.nullish(),BonusRewardSlots:zod.z.array(vi).nullish(),PityRules:zod.z.array(Ti).nullish(),Presets:am.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(),QI=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),HI=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(vi).nullish(),PityRules:zod.z.array(Ti).nullish(),Presets:am.nullish(),Tier:zod.z.number().nullish()}).passthrough(),$I=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),JI=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),qs=zod.z.object({Collections:zod.z.record(zod.z.string(),WI).nullish(),PackTypes:zod.z.record(zod.z.string(),KI).nullish(),CollectionChests:zod.z.array(HI).nullish(),DuplicateConversions:zod.z.array(QI).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array($I).nullish(),RewardPools:ys.nullish(),Settings:JI.nullish()}).passthrough(),Ke={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 Ls=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ke.GetDefinitions,e,qs)}getUserState(e){return this.send(Ke.GetUserState,e,Jh)}openPack(e){return this.send(Ke.OpenPack,e,Pe(Yh))}openCollectionChest(e){return this.send(Ke.OpenCollectionChest,e,Xh)}useCollectibleJoker(e){return this.send(Ke.UseCollectibleJoker,e,em)}claimSetReward(e){return this.send(Ke.ClaimSetReward,e,nl)}claimSetRewardsBatch(e){return this.send(Ke.ClaimSetRewardsBatch,e,tm)}claimGrandPrize(e){return this.send(Ke.ClaimGrandPrize,e,im)}sendTradeOffer(e){return this.send(Ke.SendTradeOffer,e,nm)}cancelTradeOffer(e){return this.send(Ke.CancelTradeOffer,e,rm)}acceptTradeOffer(e){return this.send(Ke.AcceptTradeOffer,e,sm)}declineTradeOffer(e){return this.send(Ke.DeclineTradeOffer,e,om)}getMyTradeOffers(e){return this.send(Ke.GetMyTradeOffers,e,rl)}getIncomingTradeOffers(e){return this.send(Ke.GetIncomingTradeOffers,e,rl)}};var Bs=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(gt.GetDefinitions,e,Rr)}getActiveEvent(e){return this.send(gt.GetActiveEvent,e,Vc)}getUserState(e){return this.send(gt.GetUserState,e,yr)}getGroupState(e){return this.send(gt.GetGroupState,e,ra)}joinOrCreateGroup(e){return this.send(gt.JoinOrCreateGroup,e,ra)}spin(e){return this.send(gt.Spin,e,Pe(jc))}claimObjectReward(e){return this.send(gt.ClaimObjectReward,e,sa)}claimGrandPrize(e){return this.send(gt.ClaimGrandPrize,e,sa)}leaveGroup(e){return this.send(gt.LeaveGroup,e,Wc)}};var Gs=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(xt.GetDefinition,e,ip)}getUserState(e){return this.send(xt.GetUserState,e,np)}getActiveDeals(e){return this.send(xt.GetActiveDeals,e,xr)}dismissDeal(e){return this.send(xt.DismissDeal,e,sp)}executeNode(e){return this.send(xt.ExecuteNode,e,Pe(rp))}recordShow(e){return this.send(xt.RecordShow,e,op)}claimMilestone(e){return this.send(xt.ClaimMilestone,e,ap)}claimMilestonesBatch(e){return this.send(xt.ClaimMilestonesBatch,e,lp)}};var ZI=zod.z.object({}).passthrough().transform(s=>s),YI=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:Se.nullish()}).passthrough(),sl=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:zod.z.record(zod.z.string(),_e).nullish(),SpendRewards:zod.z.array(YI).nullish(),Qualification:zod.z.object({}).passthrough().transform(s=>s).nullish()}).passthrough(),ol=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(),lm=zod.z.object({ReferralDefinitions:sl.nullish()}).passthrough(),um=zod.z.object({Referral:ZI.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:ol.nullish()}).passthrough(),cm=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:ol.nullish()}).passthrough(),pm=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),QualificationPending:zod.z.boolean().nullish(),Qualification:ol.nullish()}).passthrough(),al=zod.z.object({RewardID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}).passthrough(),dm=Ct(al),Qt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var Fs=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Qt.GetDefinitions,e,lm)}getUserState(e){return this.send(Qt.GetUserState,e,um)}activateReferralCode(e){return this.send(Qt.ActivateReferralCode,e,pm)}claimInviteReward(e){return this.send(Qt.ClaimInviteReward,e,al)}claimInviteRewardsBatch(e){return this.send(Qt.ClaimInviteRewardsBatch,e,dm)}checkQualification(e){return this.send(Qt.CheckQualification,e,cm)}};var _s=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(nt.GetDefinitions,e,hp)}getMessages(e){return this.send(nt.GetMessages,e,mp)}getUnreadCount(e){return this.send(nt.GetUnreadCount,e,Ir)}readMessages(e){return this.send(nt.ReadMessages,e,la)}claimReward(e){return this.send(nt.ClaimReward,e,Pr)}claimRewardsBatch(e){return this.send(nt.ClaimRewardsBatch,e,Pr)}claimAll(e){return this.send(nt.ClaimAll,e,Pr)}deleteMessages(e){return this.send(nt.DeleteMessages,e,la)}sendGift(e){return this.send(nt.SendGift,e,fp)}sendTransfer(e){return this.send(nt.SendTransfer,e,gp)}getGiftStatus(e){return this.send(nt.GetGiftStatus,e,yp)}};var Vs=class extends B{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Tr.RequestAdPermit,e,Rp)}completeView(e){return this.send(Tr.CompleteView,e,Cp)}};var Ns=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(xe.GetFriendsList,e,Gi)}getIncomingRequests(e){return this.send(xe.GetIncomingRequests,e,Gi)}getOutgoingRequests(e){return this.send(xe.GetOutgoingRequests,e,Gi)}getRecommendedFriends(e){return this.send(xe.GetRecommendedFriends,e,Gi)}sendFriendRequest(e){return this.send(xe.SendFriendRequest,e,Fi)}acceptFriendRequest(e){return this.send(xe.AcceptFriendRequest,e,Fi)}declineFriendRequest(e){return this.send(xe.DeclineFriendRequest,e,Fi)}removeFriend(e){return this.send(xe.RemoveFriend,e,Fi)}getInbox(e){return this.send(xe.GetInbox,e,xp)}markInboxSeen(e){return this.send(xe.MarkInboxSeen,e,_i)}getInboxUnread(e){return this.send(xe.GetInboxUnread,e,_i)}follow(e){return this.send(xe.Follow,e,Nt)}unfollow(e){return this.send(xe.Unfollow,e,Nt)}getFollowers(e){return this.send(xe.GetFollowers,e,kr)}getFollowing(e){return this.send(xe.GetFollowing,e,kr)}block(e){return this.send(xe.Block,e,Nt)}unblock(e){return this.send(xe.Unblock,e,Nt)}getBlocked(e){return this.send(xe.GetBlocked,e,kr)}react(e){return this.send(xe.React,e,Nt)}unreact(e){return this.send(xe.Unreact,e,Nt)}getMyReactions(e){return this.send(xe.GetMyReactions,e,Dp)}getEntityStates(e){return this.send(xe.GetEntityStates,e,bp)}addComment(e){return this.send(xe.AddComment,e,zr)}editComment(e){return this.send(xe.EditComment,e,zr)}deleteComment(e){return this.send(xe.DeleteComment,e,Pp)}getComments(e){return this.send(xe.GetComments,e,Ip)}report(e){return this.send(xe.Report,e,vp)}};var XI={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var ri=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),eP=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:ce.nullish(),Effect:ri.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(),js=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),ll=zod.z.object({Availability:Q.nullish(),Effects:Q.nullish()}).passthrough(),tP=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(ri).nullish(),Availability:js.nullish(),Presets:ll.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),iP=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(ri).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),nP=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(iP).nullish(),Availability:js.nullish(),Presets:ll.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rP=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(ot).nullish(),Effects:zod.z.array(ri).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:js.nullish(),Presets:ll.nullish()}).passthrough(),sP=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),oP=zod.z.object({Effects:zod.z.array(ri).nullish()}).passthrough(),aP=zod.z.object({Availability:zod.z.record(zod.z.string(),js).nullish(),Effects:zod.z.record(zod.z.string(),oP).nullish()}).passthrough(),lP=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),sP).nullish()}).passthrough(),Ws=zod.z.object({Definitions:zod.z.record(zod.z.string(),eP).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),tP).nullish(),BoostChains:zod.z.record(zod.z.string(),nP).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),rP).nullish(),Settings:lP.nullish(),Presets:aP.nullish()}).passthrough(),hm=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:ri.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:p.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:p.nullish()}).passthrough();var mm=zod.z.object({ServerTimeUtc:p.nullish(),Active:zod.z.record(zod.z.string(),hm).nullish()}),fm=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:hm.nullish(),Resources:M.nullish()}),uP={Scheduled:"Scheduled",Chain:"Chain"},cP=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:p.nullish(),EndUtc:p.nullish(),Effects:zod.z.array(ri).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),gm=zod.z.object({ServerTimeUtc:p.nullish(),Windows:zod.z.array(cP).nullish()}),si={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Ks=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(si.GetDefinitions,e,Ws)}getActive(e){return this.send(si.GetActive,e,mm)}getActiveWindows(e){return this.send(si.GetActiveWindows,e,gm)}activate(e){return this.send(si.Activate,e,Pe(fm))}cleanupExpired(e){return this.send(si.CleanupExpired,e,Ge)}};var Qs=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(yt.GetUserCustomDataDefinitions,e,Ur)}getMyUserCustomData(e){return this.send(yt.GetMyUserCustomData,e,kp)}getPublicUserCustomDataOf(e){return this.send(yt.GetPublicUserCustomDataOf,e,ga)}setPrivateData(e){return this.send(yt.SetPrivateData,e,ya)}setPublicData(e){return this.send(yt.SetPublicData,e,ya)}deleteKey(e){return this.send(yt.DeleteKey,e,Ge)}batchSet(e){return this.send(yt.BatchSet,e,zp)}batchDelete(e){return this.send(yt.BatchDelete,e,Mp)}batchGetPublicUserCustomDataOf(e){return this.send(yt.BatchGetPublicUserCustomDataOf,e,Op)}};var pP={Static:"Static",Runtime:"Runtime"},dP={Public:"Public",Private:"Private"},hP=zod.z.enum(["Client","Server","System"]).catch("Client"),mP=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),fP=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:p.nullish(),Version:zod.z.number().nullish(),LastWriter:hP.nullish(),ExpiresAt:p.nullish()}).passthrough(),ym=zod.z.record(zod.z.string(),fP),ul=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:ym.nullish(),Runtime:ym.nullish(),NotModified:zod.z.boolean().nullish()}),gP=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:mP.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Hs=zod.z.object({Keys:zod.z.record(zod.z.string(),gP).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(),Hi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var $s=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Hi.GetTitleCustomDataDefinitions,e,Hs)}getPublicTitleData(e){return this.send(Hi.GetPublicTitleData,e,ul)}getPublicTitleDataKeys(e){return this.send(Hi.GetPublicTitleDataKeys,e,ul)}};var Rm=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 yP={Fast:"Fast",Sequential:"Sequential"},RP={Instant:"Instant",Timed:"Timed"};var CP={Hit:"Hit",Blocked:"Blocked"},SP=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),xP=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:H.nullish()}).passthrough();var bP=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:H.nullish()}).passthrough(),DP=zod.z.object({Reward:H.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(bP).nullish(),Rate:DP.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 Cm=zod.z.object({}).passthrough().transform(s=>s),Sm=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Qe=zod.z.object({Operation:M.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),IP=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),PP=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(),vP=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:pe.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(),TP=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:pe.nullish()}).passthrough(),xm=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:H.nullish()}).passthrough(),AP=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(),wP=zod.z.object({Tiles:zod.z.record(zod.z.string(),AP).nullish()}).passthrough(),kP=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Qe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),zP=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(kP).nullish(),GuaranteedBonus:Qe.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),MP=zod.z.object({Variants:zod.z.array(zP).nullish()}).passthrough(),OP=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:Qe.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),EP=zod.z.object({Outcomes:zod.z.array(OP).nullish()}).passthrough(),bm=zod.z.object({PerAdMultiplierRange:Sm.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),UP=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Qe.nullish()}).passthrough(),qP=zod.z.object({Tiers:zod.z.array(UP).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Qe.nullish()}).passthrough(),LP=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Qe.nullish()}).passthrough(),BP=zod.z.object({Reward:Qe.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),GP=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(LP).nullish(),Rate:BP.nullish()}).passthrough(),Dm=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),GP).nullish()}).passthrough(),FP=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ce.nullish(),Multipliers:bm.nullish(),Gradation:qP.nullish(),RunStats:Dm.nullish()}).passthrough(),_P=zod.z.object({Choices:zod.z.array(FP).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),VP=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Qe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),NP=zod.z.object({OnPassStart:Qe.nullish(),OnTileLanding:zod.z.record(zod.z.string(),Qe).nullish(),OnAttack:zod.z.record(zod.z.string(),Qe).nullish(),OnRaid:zod.z.record(zod.z.string(),Qe).nullish(),OnBuild:Qe.nullish(),OnStageComplete:Qe.nullish(),OnAttackBonusDrops:zod.z.array(VP).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),EP).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),_P).nullish()}).passthrough(),Im=zod.z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(xm).nullish(),HeistGridBonusConfig:MP.nullish(),StageOperations:NP.nullish(),TileLandingMultiplier:Sm.nullish(),EconomyOverride:TP.nullish()}).passthrough(),jP=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(xm).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:Im.nullish()}).passthrough(),WP=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(),KP=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(),Js=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(),wP).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),Im).nullish(),StagesByLevel:zod.z.record(zod.z.string(),jP).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:vP.nullish(),Dice:IP.nullish(),Bots:PP.nullish(),Targeting:WP.nullish(),BotRaids:KP.nullish()}).passthrough(),QP=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:p.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(),_e).nullish(),GrandPrize:H.nullish()}).passthrough(),Zs=zod.z.object({Board:Js.nullish(),CommunityChest:QP.nullish()}).passthrough(),Pm=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),pe).nullish()}).passthrough(),HP=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:qe.nullish(),TargetBuildingStates:zod.z.array(SP).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:Pm.nullish()}).passthrough(),$P=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ce.nullish(),Multipliers:bm.nullish(),RunStats:Dm.nullish()}).passthrough(),JP=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array($P).nullish()}).passthrough(),ZP=zod.z.object({GroupID:zod.z.string().nullish(),Delta:W.nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),vm=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:W.nullish(),LandedTileType:zod.z.string().nullish(),Operation:M.nullish(),Inventory:K.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:HP.nullish(),SpecialModeOffer:JP.nullish(),CommunityChestContribution:ZP.nullish()}).passthrough(),Tm=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:Tt.nullish()}).passthrough(),cl=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:H.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(xP).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:Tt.nullish(),RaidRewardPreview:Pm.nullish()}).passthrough(),Am=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish()}).passthrough(),wm=zod.z.object({CreditsConfirmation:fe.nullish(),Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:M.nullish(),Inventory:K.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish()}).passthrough(),km=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),YP=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),zm=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:M.nullish(),Inventory:K.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(YP).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),XP={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Mm=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),ev={Active:"Active",Left:"Left",Replaced:"Replaced"},tv=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),iv=zod.z.object({CurrentProgress:W.nullish(),MaxProgress:W.nullish()}).passthrough(),nv=zod.z.object({UserID:zod.z.string().nullish(),PublicData:qe.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:W.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),Bl).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:tv.nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.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(nv).nullish(),SharedProgress:iv.nullish(),Status:Mm.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:zod.z.number().nullish()}).passthrough(),rv=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:Mm.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:p.nullish()}).passthrough(),sv=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(rv).nullish()}).passthrough(),Em=zod.z.object({ServerTimeUtc:p.nullish(),UserState:sv.nullish(),ActiveGroup:Om.nullish(),SecondsRemaining:W.nullish()}),Um=zod.z.object({ServerTimeUtc:p.nullish(),Group:Om.nullish(),SecondsRemaining:W.nullish()}),pl=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),qm=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Fe={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var ov={Mesh:"Mesh",Host:"Host"},dl=zod.z.enum(["Mesh","Host"]).catch("Mesh"),av={ServerRelay:"ServerRelay",P2P:"P2P"},hl=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),lv={Public:"Public",Private:"Private"},uv=zod.z.enum(["Public","Private"]).catch("Public"),cv={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},pv=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Lm=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),dv=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Bm=zod.z.object({SystemState:dv.nullish(),DefaultTopology:dl.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:hl.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(Lm).nullish()}).passthrough(),hv=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(),mv=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:dl.nullish(),ChatMode:hl.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(),fv=zod.z.object({Seq:zod.z.number().nullish(),Type:pv.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(),$i=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:dl.nullish(),ChatMode:hl.nullish(),Visibility:uv.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(hv).nullish(),IceServers:zod.z.array(Lm).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Gm=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),Fm=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),ml=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),_m=zod.z.object({Rooms:zod.z.array(mv).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Vm=zod.z.object({Envelopes:zod.z.array(fv).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Ys=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),Ze={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 fl=zod.z.object({TitleCustomData:Hs.nullish(),Character:cr.nullish(),Item:cs.nullish(),Currency:_r.nullish(),Store:kn.nullish(),Lootbox:Ya.nullish(),Quest:rn.nullish(),TimedEvent:$n.nullish(),Leaderboard:nr.nullish(),Season:or.nullish(),Reward:el.nullish(),Collection:qs.nullish(),Craft:il.nullish(),DealOffer:oa.nullish(),Premium:$a.nullish(),TimedBoost:Ws.nullish(),CoopEvent:Rr.nullish(),GameLoop:Zs.nullish(),Match:Aa.nullish(),Experiment:eh.nullish(),Blockchain:xa.nullish(),Marketplace:Oa.nullish(),Multiplayer:Bm.nullish(),UserCustomData:Ur.nullish(),Referral:sl.nullish(),Localization:ch.nullish(),Analytics:Nd.nullish(),Social:Tp.nullish(),PlatformBridge:Ap.nullish(),GameSpec:zod.z.string().nullish(),Look:Rm.nullish()}).passthrough();var oi={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Xs=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(oi.GetTitlePublicConfiguration,e,fl)}getTitlePublicConfigurationExcept(e){return this.send(oi.GetTitlePublicConfigurationExcept,e,fl)}getCurrencyDefinitions(e){return this.send(oi.GetCurrencyDefinitions,e,_r)}getItemDefinitions(e){return this.send(oi.GetItemDefinitions,e,cs)}getServerTime(e){return this.send(oi.GetServerTime,e,Ge)}};var eo=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Fe.GetGameLoops,e,Zs)}getBoardDefinition(e,t=false){return this.send(Fe.GetBoardDefinition,e,Js,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Fe.GetBoardDefinitionForLevel,e,Js,{silent:t})}getUserBoardState(e){return this.send(Fe.GetUserBoardState,e,Cm)}boardLoopRoll(e){return this.send(Fe.BoardLoopRoll,e,vm)}boardLoopAttack(e){return this.send(Fe.BoardLoopAttack,e,Tm)}boardLoopRaid(e){return this.send(Fe.BoardLoopRaid,e,cl)}boardLoopRaidFast(e){return this.send(Fe.BoardLoopRaidFast,e,cl)}boardLoopBuild(e){return this.send(Fe.BoardLoopBuild,e,Am)}boardSpecialChoose(e){return this.send(Fe.BoardSpecialChoose,e,Pe(wm))}boardSpecialApplyMultiplier(e){return this.send(Fe.BoardSpecialApplyMultiplier,e,km)}boardSpecialClaim(e){return this.send(Fe.BoardSpecialClaim,e,zm)}getCommunityChestState(e){return this.send(Fe.GetCommunityChestState,e,Em)}joinOrCreateCommunityChest(e){return this.send(Fe.JoinOrCreateCommunityChest,e,Um)}claimCommunityChestMilestone(e){return this.send(Fe.ClaimCommunityChestMilestone,e,pl)}claimCommunityChestGrandPrize(e){return this.send(Fe.ClaimCommunityChestGrandPrize,e,pl)}leaveCommunityChest(e){return this.send(Fe.LeaveCommunityChest,e,qm)}};var gv={Live:"Live",Latest:"Latest",Specific:"Specific"},yv={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},Rv=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),Cv={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"},Sv=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),xv=zod.z.object({Level:Rv,Message:zod.z.string().nullish(),Data:_t.nullish()}),bv=zod.z.object({Error:Sv,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),jm=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:_t.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(xv).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:bv.nullish()}),gl={Execute:"Execute"};var to=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(gl.Execute,e,jm)}};var io=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Je.GetDefinitions,e,Zp)}getUserState(e){return this.send(Je.GetUserState,e,Yp)}depositToken(e){return this.send(Je.DepositToken,e,Xp)}depositNFT(e){return this.send(Je.DepositNFT,e,ed)}requestTokenWithdrawal(e){return this.send(Je.RequestTokenWithdrawal,e,td)}requestNFTWithdrawal(e){return this.send(Je.RequestNFTWithdrawal,e,id)}getTransactionHistory(e){return this.send(Je.GetTransactionHistory,e,nd)}retryWithdrawal(e){return this.send(Je.RetryWithdrawal,e,rd)}confirmWithdrawal(e){return this.send(Je.ConfirmWithdrawal,e,sd)}donateToDeveloper(e){return this.send(Je.DonateToDeveloper,e,Pa)}donateToUsersPool(e){return this.send(Je.DonateToUsersPool,e,Pa)}getPlayAccess(e){return this.send(Je.GetPlayAccess,e,$p)}confirmPlayAccess(e){return this.send(Je.ConfirmPlayAccess,e,jt)}};var no=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Oe.GetDefinitions,e,Cd)}getGroupedOffers(e){return this.send(Oe.GetGroupedOffers,e,Sd)}getOffersByItem(e){return this.send(Oe.GetOffersByItem,e,Ea)}getOffer(e){return this.send(Oe.GetOffer,e,xd)}getBuyOrders(e){return this.send(Oe.GetBuyOrders,e,Ea)}getMyState(e){return this.send(Oe.GetMyState,e,Hr)}getHistory(e){return this.send(Oe.GetHistory,e,Dd)}createListing(e){return this.send(Oe.CreateListing,e,Wi)}cancelListing(e){return this.send(Oe.CancelListing,e,ct)}buy(e){return this.send(Oe.Buy,e,ct)}marketBuy(e){return this.send(Oe.MarketBuy,e,ct)}marketSell(e){return this.send(Oe.MarketSell,e,ct)}createAuction(e){return this.send(Oe.CreateAuction,e,Wi)}placeBid(e){return this.send(Oe.PlaceBid,e,bd)}claimAuction(e){return this.send(Oe.ClaimAuction,e,ct)}createBuyOrder(e){return this.send(Oe.CreateBuyOrder,e,Wi)}cancelBuyOrder(e){return this.send(Oe.CancelBuyOrder,e,ct)}fillBuyOrder(e){return this.send(Oe.FillBuyOrder,e,ct)}createDirectTrade(e){return this.send(Oe.CreateDirectTrade,e,Wi)}respondDirectTrade(e){return this.send(Oe.RespondDirectTrade,e,ct)}cancelDirectTrade(e){return this.send(Oe.CancelDirectTrade,e,ct)}claimBack(e){return this.send(Oe.ClaimBack,e,ct)}};var ro=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(Ze.CreateRoom,e,$i)}joinRoom(e){return this.send(Ze.JoinRoom,e,$i)}leaveRoom(e,t=false){return this.send(Ze.LeaveRoom,e,ml,{keepalive:t})}listRooms(e){return this.send(Ze.ListRooms,e,_m)}getRoom(e){return this.send(Ze.GetRoom,e,$i)}closeRoom(e){return this.send(Ze.CloseRoom,e,ml)}poll(e){return this.send(Ze.Poll,e,Vm)}sendSignal(e){return this.send(Ze.SendSignal,e,Ys,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(Ze.ClaimHost,e,$i)}kickMember(e){return this.send(Ze.KickMember,e,Gm)}unbanMember(e){return this.send(Ze.UnbanMember,e,Fm)}sendChat(e){return this.send(Ze.SendChat,e,Ys)}setMemberState(e){return this.send(Ze.SetMemberState,e,Ys)}};var Dv={Free:"Free",Price:"Price",Holding:"Holding"},yl=zod.z.enum(["Free","Price","Holding"]).catch("Free"),Iv={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},Pv=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),vv={All:"All",Any:"Any"},Tv=zod.z.enum(["All","Any"]).catch("All"),Av={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},wv=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),kv={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},zv=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),Mv={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Km=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),Ov={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},Ev={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},Uv=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),qv=zod.z.object({Type:mi.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(),Lv=zod.z.object({Requirements:zod.z.array(qv).nullish(),Match:Tv.nullish(),Mode:Pv.nullish()}).passthrough(),Bv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:yl.nullish(),Price:pe.nullish(),Holding:Lv.nullish()}).passthrough(),Gv=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(),Fv=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),Gv).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(yl).nullish(),PricePolicy:Qr.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ce.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),_v=zod.z.object({Allowed:zod.z.array(ji).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),Vv=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),Nv=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(),jv=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:Re.nullish(),Gate:Z.nullish(),Order:zod.z.number().nullish()}).passthrough(),Wv=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:Re.nullish(),ContentTypes:zod.z.record(zod.z.string(),Fv).nullish(),PricePolicy:Qr.nullish(),Commission:Ma.nullish(),HoldingPolicy:_v.nullish(),Moderation:Vv.nullish(),Limits:Nv.nullish(),Featured:zod.z.array(jv).nullish()}).passthrough(),Kv=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(),ai=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:qe.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:wv.nullish(),Access:zod.z.array(Bv).nullish(),Status:zv.nullish(),ModerationNote:zod.z.string().nullish(),Stats:Kv.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),PublishedAt:p.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),Qv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:yl.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),Qm=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(),Hm=zod.z.object({Definitions:Wv.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(Qm).nullish()}).passthrough(),so=zod.z.object({Items:zod.z.array(ai).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),$m=zod.z.object({Content:ai.nullish(),AccessState:zod.z.array(Qv).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Jm=zod.z.object({Collection:Qm.nullish(),Items:zod.z.array(ai).nullish()}).passthrough(),Zm=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:qe.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(ai).nullish()}).passthrough(),Wm=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(),Ym=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(Wm).nullish(),ThumbnailUpload:Wm.nullish(),ExpiresAt:p.nullish()}).passthrough(),Xm=zod.z.object({CreditsConfirmation:fe.nullish(),Content:ai.nullish(),Resources:M.nullish()}).passthrough(),Rl=zod.z.object({Content:ai.nullish()}).passthrough(),ef=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Km.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:Tt.nullish(),Resources:M.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Hv=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),tf=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:Uv.nullish(),Files:zod.z.array(Hv).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:p.nullish()}).passthrough(),$v=zod.z.object({ContentID:zod.z.string().nullish(),Source:Km.nullish(),OptionID:zod.z.string().nullish(),PricePaid:pe.nullish(),AcquiredAt:p.nullish(),Content:ai.nullish()}).passthrough(),nf=zod.z.object({Licenses:zod.z.array($v).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),He={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 oo=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(He.GetDefinitions,e,Hm)}browse(e){return this.send(He.Browse,e,so)}getContent(e){return this.send(He.GetContent,e,$m)}getCollection(e){return this.send(He.GetCollection,e,Jm)}getCreatorProfile(e){return this.send(He.GetCreatorProfile,e,Zm)}beginUpload(e){return this.send(He.BeginUpload,e,Ym)}publish(e){return this.send(He.Publish,e,Pe(Xm))}updateContent(e){return this.send(He.UpdateContent,e,Rl)}unpublish(e){return this.send(He.Unpublish,e,Rl)}getMyContent(e){return this.send(He.GetMyContent,e,so)}acquire(e){return this.send(He.Acquire,e,ef)}getDownload(e){return this.send(He.GetDownload,e,tf)}getMyLicenses(e){return this.send(He.GetMyLicenses,e,nf)}getMyFavorites(e){return this.send(He.GetMyFavorites,e,so)}};var ao=class extends B{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,n){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${n}`})}sendPublic(e,t,i,n){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${n}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,wd,"defs")}get(e){return this.sendKeyed("Get",e,qa,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,zd,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,La,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Md,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,Ba,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,Ba,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Od,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,Ud,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Ed,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,qd,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,kd,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Ld,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,qa,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,La,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var lo=class{settings;emitter;platform;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;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.settings=Dl(e),this.emitter=new zi,this.platform=e.platform??new pi,this.clientPlatform=e.clientPlatform??ql(),this.acquisition=new $t(this.platform),this.acquisition.capture(),this.playtime=new Mi(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new pn({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 fn(this.emitter),this.cache=new yn(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:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new Rn(this.platform.storage,this.settings.titleID),this.api={authentication:new ss(this),user:new as(this),currency:new ls(this),item:new ps(this),store:new ds(this),purchase:new gs(this),lootbox:new Cs(this),reward:new Ss(this),quest:new vs(this),tutorial:new xs(this),communityMarketing:new bs(this),chat:new Ds(this),push:new Is(this),localization:new Ps(this),timedEvent:new Ts(this),leaderboard:new As(this),season:new ws(this),premium:new ks(this),character:new zs(this),match:new Ms(this),craft:new Es(this),ai:new Us(this),collection:new Ls(this),coopEvent:new Bs(this),dealOffer:new Gs(this),referral:new Fs(this),mailbox:new _s(this),advertising:new Vs(this),social:new Ns(this),timedBoost:new Ks(this),userCustomData:new Qs(this),titleCustomData:new $s(this),title:new Xs(this),gameLoop:new eo(this),cloudCode:new to(this),blockchain:new io(this),marketplace:new no(this),multiplayer:new ro(this),workshop:new oo(this),dataCollections:new ao(this),analytics:new ns(this),experiment:new rs(this)},this.userService=new In(this),this.cache.attachState(this.userService),this.auth=new Sn(this),this.currency=new vn(this),this.item=new Tn(this),this.store=new Mn(this),this.credits=new On(this),this.purchase=new En(this),this.checkout=new Un(this),this.lootbox=new qn(this),this.reward=new Bn(this),this.quest=new Hn(this),this.tutorial=new Fn(this),this.communityMarketing=new _n(this),this.chat=new jn(this),this.push=new Wn(this),this.localization=new Qn(this),this.timedEvent=new Zn(this),this.leaderboard=new rr(this),this.season=new ar(this),this.premium=new lr(this),this.character=new pr(this),this.match=new dr(this),this.craft=new hr(this),this.ai=new fr(this),this.collection=new gr(this),this.coopEvent=new Cr(this),this.dealOffer=new br(this),this.referral=new Dr(this),this.mailbox=new vr(this),this.ads=new wr(this),this.social=new Mr(this),this.timedBoost=new Or(this),this.userCustomData=new qr(this),this.titleCustomData=new Lr(this),this.title=new Br(this),this.gameLoop=new Gr(this),this.cloudCode=new Fr(this),this.blockchain=new Nr(this),this.marketplace=new $r(this),this.multiplayer=new Jr(this),this.workshop=new Zr(this),this.dataCollections=new Xr(this),this.analytics=new ts(this),this.experiments=new is(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.platform.getFullURL(),RelatedEntityID:G()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var uo=class{ctx;constructor(e){this.ctx=new lo(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let n=this.ctx.buildAuthedBaseRequest(),r=Kt(this.ctx.settings.titleID,e,t,n.UserID??"");return this.ctx.transport.post(r,{...n,...i},zod.z.unknown(),{ticket:n.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 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 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 platform(){return this.ctx.platform}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 Zv(s){return new uo(s)}var rf="idos_sso",sf="state",Cl="idos:sso:state",Yv="https://idosgames.com/sso/",Xv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],eT=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function tT(){if(typeof window>"u")return false;let{origin:s}=window.location;return Xv.includes(s)||eT.test(s)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function iT(){if(typeof window>"u")return null;let s=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!s)return null;let e=new URLSearchParams(s),t=e.get(rf);if(!t)return null;let i=e.get(sf)??"",n=aT();return uT(e),lT(),n&&i!==n?null:{code:t,state:i}}function nT(s){if(typeof window>"u")return;let e=s.returnTo??rT(),t=sT();oT(t);let i=new URL(s.ssoUrl??Yv);i.searchParams.set("title",s.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function rT(){let{origin:s,pathname:e,search:t}=window.location;return `${s}${e}${t}`}function sT(){let s=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(s);else for(let e=0;e<s.length;e++)s[e]=Math.floor(Math.random()*256);return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}function oT(s){try{window.sessionStorage.setItem(Cl,s);}catch{}}function aT(){try{return window.sessionStorage.getItem(Cl)}catch{return null}}function lT(){try{window.sessionStorage.removeItem(Cl);}catch{}}function uT(s){s.delete(rf),s.delete(sf);let e=s.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var cT={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 pT(s,e="Something went wrong. Please try again."){return s?cT[s]??s:e}function dT(s,e){return !!s?.Claims?.[e]?.ClaimedAt}function hT(s){let e=s?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function mT(s,e){return s?.Claims?.[e]?.PremiumTiers??[]}function af(s,e,t,i=1){if(!s)return e;let n=s.Base??e,r=Math.max(0,t-i),o;switch(s.Shape??"Flat"){case "PerStep":o=n+(s.PerStep??0)*r;break;case "PerStepRate":o=n*(1+(s.PerStepRate??0)*r);break;case "Geometric":o=n*Math.pow(1+(s.GrowthRate??0),r);break;case "Table":o=n*of(s,t,1);break;case "TableAbsolute":o=of(s,t,n);break;default:o=n;break}return Number.isNaN(o)?n:(s.MinResult!=null&&o<s.MinResult&&(o=s.MinResult),s.MaxResult!=null&&o>s.MaxResult&&(o=s.MaxResult),o)}function fT(s,e,t=1){return af(s,1,e,t)}function gT(s){if(!s)return false;switch(s.Shape??"Flat"){case "PerStep":return (s.PerStep??0)!==0;case "PerStepRate":return (s.PerStepRate??0)!==0;case "Geometric":return (s.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return lf(s.Points).length>0;default:return s.MinResult!=null||s.MaxResult!=null}}function yT(s){if(Number.isNaN(s)||s<=0)return 0;if(!Number.isFinite(s))return Number.MAX_SAFE_INTEGER;let e=Math.round(s);return Math.abs(s-e)<=1e-9*Math.max(1,Math.abs(s))?e:Math.ceil(s)}function lf(s){if(!s)return [];let e=[];for(let t of s)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function of(s,e,t){let i=lf(s.Points);if(i.length===0)return t;let n=null,r=null,o=null;for(let c of i)(o===null||c.AtStep>o.AtStep)&&(o=c),c.AtStep<=e&&(n===null||c.AtStep>=n.AtStep)&&(n=c),c.AtStep>e&&(r===null||c.AtStep<r.AtStep)&&(r=c);if(n===null)return t;if(r===null){let c=s.TailGrowthRate??0;return c===0?o.Value:o.Value*Math.pow(1+c,e-o.AtStep)}switch(s.Interpolation??"Step"){case "Linear":{let c=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value+c*(r.Value-n.Value)}case "Geometric":{if(n.Value<=0||r.Value<=0){let h=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value+h*(r.Value-n.Value)}let c=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value*Math.pow(r.Value/n.Value,c)}default:return n.Value}}var RT={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Sl=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),CT={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},ST=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),xT=zod.z.object({PlacementID:zod.z.string().nullish(),Type:Sl.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(),bT=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(),DT=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),IT=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:ST.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),PT=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),vT=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),TT=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(),AT=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(),wT=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),kT=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:Sl.nullish()}).passthrough(),zT={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},MT=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),OT=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:MT.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(),kT).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),xT).nullish(),Providers:zod.z.record(zod.z.string(),OT).nullish(),RewardedVideo:bT.nullish(),Interstitial:DT.nullish(),Banner:IT.nullish(),AppOpen:PT.nullish(),FrequencyCapping:vT.nullish(),PremiumAdReductions:zod.z.array(TT).nullish(),Consent:AT.nullish(),Verification:wT.nullish()}).passthrough();var ET=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),UT=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:p.nullish(),LastCompletedAt:p.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),qT=zod.z.object({Date:p.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(),LT=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:p.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),BT=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:p.nullish(),ConsentRevokedAt:p.nullish()}).passthrough(),GT=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:Sl.nullish(),IssuedAt:p.nullish(),ExpiresAt:p.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),FT=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:p.nullish()}).passthrough();zod.z.object({Credits:ET.nullish(),Placements:zod.z.record(zod.z.string(),UT).nullish(),Daily:qT.nullish(),Session:LT.nullish(),LastImpressionAt:p.nullish(),LastInterstitialAt:p.nullish(),LastRewardedAt:p.nullish(),LastAppOpenAt:p.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:p.nullish(),Consent:BT.nullish(),PendingRequests:zod.z.record(zod.z.string(),GT).nullish(),FraudFlags:FT.nullish(),UpdatedAt:p.nullish()}).passthrough();var uf="idos_device_id",co=class{storage;constructor(e=new ui){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(uf);return e||(e="noop-device",this.storage.setString(uf,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};
|
|
2
|
-
exports.AIAction=
|
|
1
|
+
'use strict';var zod=require('zod'),Yt=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Yt__default=/*#__PURE__*/_interopDefault(Yt);var zi=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,n=>{i(),t(n);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let n of [...i])n(t);}removeAllListeners(){this.listeners.clear();}};function pf(){let s=new Map;return {get:e=>s.get(e)??null,set:(e,t)=>{s.set(e,t);},remove:e=>{s.delete(e);}}}function xl(){return df()??pf()}function df(){try{let s=globalThis.localStorage;if(!s)return null;let e="__idos_probe__";return s.setItem(e,"1"),s.removeItem(e),{get:t=>{try{return s.getItem(t)}catch{return null}},set:(t,i)=>{try{s.setItem(t,i);}catch{try{s.removeItem(t);}catch{}}},remove:t=>{try{s.removeItem(t);}catch{}}}}catch{return null}}var bl="https://api.idosgames.com";function Dl(s){return {titleID:s.titleID,titleTemplateID:s.titleTemplateID??"default",buildKey:s.buildKey??"",baseUrl:(s.baseUrl??bl).replace(/\/+$/,""),devBuild:s.devBuild??false,debugLogging:s.debugLogging??false,configStorage:s.configStorage??xl(),locale:s.locale??hf(),appVersion:s.appVersion??""}}function hf(){try{return globalThis.navigator?.language??""}catch{return ""}}var ui=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{}}},ci=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);}};function pi(){return globalThis.Telegram?.WebApp??null}function G(){return crypto.randomUUID()}var Pl="idos_device_id",di=class{storage;constructor(e=new ui){this.storage=e;}getPlatform(){return pi()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=pi()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=pi()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(Pl);return e||(e=G(),this.storage.setString(Pl,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let t=pi();if(t?.openTelegramLink){t.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let t=pi();if(t?.openInvoice){t.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let t=globalThis;typeof t.showAd=="function"&&await t.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var po="idos_acq",Il=["gclid","fbclid","ttclid","msclkid","yclid"],mf=["ref","r"],ff=["ref_","ref-","ref=","r_","r-"];var Jt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();gf(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},n=Cf(this.platform.getDeviceModel());return n&&(i.OsVersion=n),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(po);}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 i=Al(Tl(t));if(i)return i}return Ji(t)}readFromEnvironment(){let e={},t=Tl(this.platform.getFullURL());$t(e,"UtmSource",t.get("utm_source")),$t(e,"UtmMedium",t.get("utm_medium")),$t(e,"UtmCampaign",t.get("utm_campaign")),$t(e,"UtmTerm",t.get("utm_term")),$t(e,"UtmContent",t.get("utm_content")),$t(e,"ClaimToken",t.get("idos_click"));for(let y of Il){let V=t.get(y);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",n=Rf(i);if(n){for(let y of yf)$t(e,y,n.get(wl[y])??null);for(let y of Il){let V=n.get(y);if(V){e.ClickID=V;break}}}let r=Ji(n?n.get("ref")??n.get("r")??"":i),o=Al(t),c=r||o;c&&(e.ReferralCode=c,e.ChannelHint=r?"telegram":"query");let h=this.platform.getReferrer?.();return h&&(e.Referrer=h),e}read(){try{let e=this.platform.storage.getString(po);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.platform.storage.setString(po,JSON.stringify(e));}catch{}}};function gf(s){return !!(s.UtmSource||s.UtmMedium||s.UtmCampaign||s.ClickID||s.Referrer||s.ReferralCode||s.ClaimToken)}function $t(s,e,t){t&&(s[e]=t);}var vl="a1_",wl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},yf=Object.keys(wl);function Rf(s){let e=(s||"").trim();if(!e.startsWith(vl))return null;let t=e.slice(vl.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(i+"=".repeat((4-i.length%4)%4)),r=Uint8Array.from(n,h=>h.charCodeAt(0)),o=new TextDecoder().decode(r),c=new URLSearchParams(o);return [...c.keys()].length>0?c:null}catch{return null}}function Tl(s){try{let e=s.indexOf("?");return new URLSearchParams(e>=0?s.slice(e):"")}catch{return new URLSearchParams}}function Al(s){for(let e of mf){let t=s.get(e);if(t)return Ji(t)}return null}function Ji(s){let e=(s||"").trim();if(!e)return null;for(let t of ff)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Cf(s){let e=s||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var kl="idos_usage_pending",zl="idos_usage_session",Ml="idos_usage_closed_session",Ol="idos_usage_new_session",El="idos_usage_last_activity",Mi=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;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=typeof document<"u"&&document.visibilityState==="hidden",this.timer=setInterval(()=>this.tick(),200*1e3),window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide)),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){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,i=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,i,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(kl),this.currentSessionSeconds=this.readNumber(zl),this.pendingClosedSessionSeconds=this.readNumber(Ml),this.isNewSessionPending=this.readNumber(Ol)!==0;let e=this.readNumber(El);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(kl,this.pendingSeconds),this.writeNumber(zl,this.currentSessionSeconds),this.writeNumber(Ml,this.pendingClosedSessionSeconds),this.writeNumber(Ol,this.isNewSessionPending?1:0),this.writeNumber(El,Date.now());}readNumber(e){let t=this.ctx.platform.storage.getString(e),i=t?Number(t):0;return Number.isFinite(i)&&i>0?i:0}writeNumber(e,t){try{this.ctx.platform.storage.setString(e,String(Math.floor(t)));}catch{}}};var ht={Virtual:"Virtual",Crypto:"Crypto"},mi=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),Zi={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},fi=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),Ct={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Yi=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),Sf={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Xi=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),xf={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},en=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),bf={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},Oi=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),ze={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function ql(){let s=globalThis,e=s.Capacitor?.getPlatform?.();if(e)return Ul(e);let t=s.cordova?.platformId;return t?Ul(t):s.navigator?.userAgent??""?Ct.Web:Ct.Unknown}function Ul(s){let e=s.toLowerCase();return e==="android"?Ct.Android:e==="ios"?Ct.Ios:e==="web"?Ct.Web:Ct.Unknown}function N(s){return {ok:true,data:s}}function u(s,e){return {ok:false,reason:s,error:e}}var a=u("unauthorized","Not logged in.");function Df(s){return s.ok}function Pf(s){return !s.ok}var W=zod.z.union([zod.z.number(),zod.z.string()]).transform((s,e)=>{let t=typeof s=="string"?Number(s):s;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(s)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((s,e)=>{let t=typeof s=="number"?String(s):s.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(s)}`}),zod.z.NEVER):t}),p=zod.z.string();var ho=zod.z.object({Type:fi.nullish(),CurrencyID:zod.z.string().nullish(),Amount:W.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),If=zod.z.object({Type:en.nullish(),EntityID:zod.z.string()}),vf=zod.z.object({Address:If.nullish(),Amount:W.nullish(),Source:zod.z.string().nullish()}),pe=zod.z.object({Entries:zod.z.array(ho).nullish(),EventTokens:zod.z.array(vf).nullish()}),Ll=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:pe.nullish()}),H=zod.z.object({Standard:pe.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Ll).nullish()}),Tt=zod.z.object({Standard:pe.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Ll).nullish()}),O=zod.z.object({Grant:H.nullish(),Consume:Tt.nullish()}),At=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:pe.nullish()});var Tf=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Af={Completed:"Completed",Started:"Started",StepReached:"StepReached"},wf=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(),Z=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:Tf.nullish(),Tutorial:wf.nullish(),Platforms:zod.z.array(Yi).nullish()}).passthrough();var Se=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 kf=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),zf=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Mf=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 Of=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 ot=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:Se.nullish()}).passthrough(),Re=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:zf.nullish(),Chain:Mf.nullish(),Cyclic:Of.nullish(),ActivationTriggers:zod.z.array(ot).nullish(),Relative:kf.nullish()}).passthrough();var Ef={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},Uf=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),qf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Lf=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),Bf=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Ne=zod.z.object({Base:zod.z.number().nullish(),Shape:Uf.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(Bf).nullish(),Interpolation:Lf.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var Gf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:H.nullish()}).passthrough(),Ff=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),mo=zod.z.object({Bundles:zod.z.array(Gf).nullish(),Multipliers:zod.z.array(Ff).nullish()}).passthrough();var _f=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),tn=zod.z.object({Source:_f.nullish(),SourceKey:zod.z.string().nullish(),Curve:Ne.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:pe.nullish(),ExcludeRewards:pe.nullish()}).passthrough(),Bl=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),_e=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:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:mo.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),gi=zod.z.object({Milestones:zod.z.record(zod.z.string(),_e).nullish()}).passthrough();var Q=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var Vf=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Zt=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:Vf.nullish()}).passthrough();var Nf=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),Gl=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:p,ExpiresAt:p.nullish(),EquippedSlot:Nf.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),K=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),Gl).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var we=s=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:s.nullish()}),St=s=>zod.z.object({ServerTimeUtc:p,Items:zod.z.array(we(s)),Resources:O.nullish(),Inventory:K.nullish()});var jf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Fl=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Wf=zod.z.object({}).passthrough().transform(s=>s),Kf=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:p.nullish(),CycleEndUtc:p.nullish(),PointsTotalEarned:W.nullish(),PointsCurrent:W.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),fo=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:W.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:Fl}),_l=zod.z.object({State:Wf.nullish(),PointsTracks:zod.z.record(zod.z.string(),Kf).nullish()}),go=zod.z.object({ServerTimeUtc:p,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:Fl.nullish(),Resources:O.nullish(),Inventory:K.nullish()}),yo=zod.z.object({ServerTimeUtc:p,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:W.nullish(),Resources:O.nullish(),Inventory:K.nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Vl=zod.z.object({ServerTimeUtc:p,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()}),Nl=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(fo).nullish()}),jl=zod.z.array(we(go)),Wl=zod.z.array(we(yo)),Qf={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Hf=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),$f={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Jf=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),Kl=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:Hf.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(ot).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),Ro=zod.z.object({Milestones:Q.nullish(),Linking:Q.nullish(),Availability:Q.nullish(),Reward:Q.nullish(),Objectives:Q.nullish()}).passthrough(),Zf=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(),Ql=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:Jf.nullish()}).passthrough(),Hl=zod.z.object({Schedule:Re.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),$l=zod.z.object({Grant:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Yf=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Zf.nullish(),Linking:Ql.nullish(),Availability:Hl.nullish(),Objectives:zod.z.record(zod.z.string(),Kl).nullish(),Reward:$l.nullish(),Presets:Ro.nullish()}).passthrough(),Xf=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),eg=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:Z.nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:Ro.nullish(),PointsToken:Zt.nullish()}).passthrough(),tg=zod.z.object({Milestones:zod.z.record(zod.z.string(),gi).nullish(),Linking:zod.z.record(zod.z.string(),Ql).nullish(),Availability:zod.z.record(zod.z.string(),Hl).nullish(),Reward:zod.z.record(zod.z.string(),$l).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Kl)).nullish()}).passthrough(),ig=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Gate:Z.nullish(),PointsToken:Zt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),Xf).nullish(),Phases:zod.z.record(zod.z.string(),eg).nullish(),Presets:Ro.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rn=zod.z.object({Cycles:zod.z.record(zod.z.string(),ig).nullish(),Quests:zod.z.record(zod.z.string(),Yf).nullish(),Presets:tg.nullish()}).passthrough(),ft={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var ng={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},rg=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),sg={Never:"Never",OnRequest:"OnRequest",Always:"Always"},og=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),ag={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},lg=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),ug={GameLoop:"GameLoop"},cg={Raid:"Raid",Attack:"Attack"},pg=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(),dg=zod.z.object({Mode:rg.nullish(),Triggers:zod.z.array(ot).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),hg=zod.z.object({Grant:H.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),mg=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(),fg=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:mg.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),gg=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),Co=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:pg.nullish(),Completion:dg.nullish(),Effects:hg.nullish(),Script:fg.nullish(),Policy:gg.nullish()}).passthrough(),yg=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(),Jl=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:ot.nullish()}).passthrough(),Zl=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:og.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Yl=zod.z.object({Grant:H.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),Rg=zod.z.object({Availability:Q.nullish(),Policy:Q.nullish(),Reward:Q.nullish(),Steps:Q.nullish()}).passthrough(),Cg=zod.z.object({FlowID:zod.z.string().nullish(),Identity:yg.nullish(),Availability:Jl.nullish(),Policy:Zl.nullish(),Steps:zod.z.record(zod.z.string(),Co).nullish(),Reward:Yl.nullish(),Presets:Rg.nullish()}).passthrough(),Sg=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(),xg=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:Sg.nullish()}).passthrough(),bg=zod.z.object({Availability:zod.z.record(zod.z.string(),Jl).nullish(),Policy:zod.z.record(zod.z.string(),Zl).nullish(),Reward:zod.z.record(zod.z.string(),Yl).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Co)).nullish()}).passthrough(),Xl=zod.z.object({Flows:zod.z.record(zod.z.string(),Cg).nullish(),Settings:xg.nullish(),Presets:bg.nullish()}).passthrough(),Dg=zod.z.object({}).passthrough().transform(s=>s),eu=zod.z.object({FlowID:zod.z.string(),Status:lg,CurrentStepID:zod.z.string().nullish(),CurrentStep:Co.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(),sn=zod.z.object({State:Dg.nullish(),Flows:zod.z.array(eu).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Bt=zod.z.object({Flow:eu.nullish()}).passthrough(),tu=zod.z.object({FlowID:zod.z.string().nullish(),Granted:O.nullish()}).passthrough(),iu=zod.z.array(we(Bt)),nu=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),at={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function on(s){return Array.isArray(s)?s.filter(e=>e!==null).map(on):s!==null&&typeof s=="object"?Object.fromEntries(Object.entries(s).filter(([,e])=>e!==null).map(([e,t])=>[e,on(t)])):s}var an=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(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var ln=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function ru(s){return s===429||s>=500&&s<=599}function un(s,e=Math.random){let t=Math.min(500*Math.pow(2,s-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Gt(s){return new Promise(e=>setTimeout(e,s))}var su=15e3;async function ou(s){try{let t=JSON.parse(await s.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(s.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function au(s,e=Math.random){return s+10+Math.min(250,s*.2)*e()}function lu(s,e=Math.random){let t=s<=1?1500:s===2?4e3:6e3;return t+t*.1*e()}var So=15,uu=1e3,cn=class{constructor(e=So,t=()=>Date.now(),i=Gt){this.perSecond=e;this.now=t;this.wait=i;}perSecond;now;wait;starts=[];async take(){if(this.perSecond>0)for(;;){let e=this.now();for(;this.starts.length>0&&e-this.starts[0]>=uu;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(uu-(e-this.starts[0])+5);}}};var Pg=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function Ri(s){if(!s)return null;let e=Pg.exec(s);if(!e)return null;let[,t,i,n]=e;if(!t||i===void 0||n===void 0)return null;let r=new Yt__default.default(i),o=new Yt__default.default(n),c=o.minus(Yt__default.default.max(r,0));return c.lte(0)?null:{currencyID:t,required:o.toNumber(),available:r.toNumber(),missing:c.toNumber(),missingAmount:c.toFixed()}}var Ig=12e3,vg=new Set(["RelatedEntityID"]);function Tg(s,e){if(e===null||typeof e!="object"||Array.isArray(e))return s;let t={};for(let[i,n]of Object.entries(e))vg.has(i)||(t[i]=n);try{return `${s}|${JSON.stringify(t)}`}catch{return s}}var Ag=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(fo).nullish(),TutorialProgress:zod.z.array(nu).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),pn=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new ln;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 an(e.throttleMs),this.pacer=new cn(e.maxRequestsPerSecond??So),this.clientPlatform=e.clientPlatform??Ct.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,n={}){let r=n.throttleKey??Tg(e,t);if(!this.throttler.tryAcquire(r))return u("throttled","Throttled");if(!this.inflight.add(r))return u("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,c=JSON.stringify(t),h=n.ticket??null,y=n.silent??!1,V=n.timeoutMs??Ig,oe=n.autoRetry??!0,be=!1,ue=!1,ge=0;for(;;){let vt;n.keepalive||await this.pacer.take();try{vt=await this.doFetch(o,c,h,V,n.keepalive??!1);}catch{if(oe&&ge<3){ge++,await Gt(un(ge));continue}return this.connectionFailure("Internet Connection Error",y)}let Xe=vt.status;if(Xe>=200&&Xe<300){let se=!ue&&this.cryptoTopUpHandler!==null,Ae=await this.parseSuccess(vt,i,y,e,se);if(!Ae.ok&&se){let de=Ri(Ae.error);if(de){if(ue=!0,await this.runTopUp(de))continue;y||this.emitter.emit("error:global",Ae.error);}}return Ae}if(Xe===401){if(!be&&this.sessionRefreshHandler){be=!0;let se=null;try{se=await this.sessionRefreshHandler();}catch{se=null;}if(se){h=se;continue}}return this.emitter.emit("auth:unauthorized",void 0),u("unauthorized","Unauthorized")}if(ru(Xe)){let se=Xe===429?await ou(vt):null;if(se!==null&&se>su)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(se/1e3)} s`,y);if(oe&&ge<3){ge++,await Gt(se!==null?au(se):Xe===429?lu(ge):un(ge));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Xe})`,y)}let wi="";try{wi=await vt.text();}catch{}if(Xe===409&&/operation in progress/i.test(wi)&&oe&&ge<3){ge++,await Gt(un(ge));continue}return this.handleWebError(wi,Xe,y)}}finally{this.inflight.remove(r),this.lowerBusy();}}async doFetch(e,t,i,n,r=false){let o=new AbortController,c=setTimeout(()=>{o.abort();},n);try{let h={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(h.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:h,signal:o.signal,...r?{keepalive:!0}:{}})}finally{clearTimeout(c);}}async parseSuccess(e,t,i,n,r=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",i)}let c;try{c=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",i)}let h=Ag.safeParse(c);if(!h.success)return this.globalError("Malformed response envelope",i);if(!h.data.Success){let ue=h.data.Error??"Server returned Success=false",ge=r&&Ri(ue);return !i&&!ge&&this.emitter.emit("error:global",ue),u("server",ue)}let y=h.data.StateVersions;y&&Object.keys(y).length>0&&this.emitter.emit("user:stateVersions",{epoch:h.data.StateEpoch??null,versions:y});let V=h.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);let oe=h.data.TutorialProgress;oe&&oe.length>0&&this.emitter.emit("tutorial:systemProgress",oe);let be=t.safeParse(h.data.Data);if(!be.success){let ue=t.safeParse(on(h.data.Data));ue.success&&(be=ue);}if(!be.success){let ue=`Validation error (${n}): ${be.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",ue),i||this.emitter.emit("error:global",ue),u("validation",ue)}return N(be.data)}handleWebError(e,t,i){let n=`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),u("server","PLAY_ACCESS_REQUIRED");n=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{n=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",n),u("server",n)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),u("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),u("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 Ci(s){return (typeof s=="string"?s:s.toISOString()).slice(0,10)}function Ei(s){return `${Ci(s)}T00:00:00.000Z`}function cu(s){let e=new Date(s);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function pu(s,e){return new Date(s.getTime()+e*6e4).toISOString()}function Do(s,e,t,i){let n={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return n;s.InventoryV2??={};let r=s.InventoryV2,o=i.toISOString(),c=new Map,h=new Map,y=new Map,V=new Map,oe=new Map,be=new Map,ue=new Map,ge=new Map,vt=e.Grant?.PremiumTiers??[],Xe=vt.length;for(let se=0;;se++){let Ae,de;if(se===0)Ae=e.Grant?.Standard?.Entries,de=false;else if(se-1<Xe)Ae=vt[se-1]?.Resources?.Entries,de=false;else if(se===1+Xe)Ae=e.Consume?.Standard?.Entries,de=true;else break;if(Ae)for(let ce of Ae){if(ce.Type==null)continue;let he=Math.max(0,ce.Amount??0);if(!(he<=0))switch(ce.Type){case "VirtualCurrency":{if(!ce.CurrencyID)continue;let me=de?h:c;me.set(ce.CurrencyID,(me.get(ce.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!ce.CurrencyID)continue;let me=de?V:y;me.set(ce.CurrencyID,(me.get(ce.CurrencyID)??new Yt__default.default(0)).plus(he));break}case "Item":{if(!ce.ItemID)continue;let me=kg(t,ce.CatalogID,ce.ItemID),Pe=(me?me.IsStackable??true:true)?de?be:oe:de?ge:ue;Pe.set(ce.ItemID,(Pe.get(ce.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(n.vcChanged=c.size>0||h.size>0,n.vcChanged){r.VirtualCurrencies??={};for(let se of new Set([...c.keys(),...h.keys()])){let Ae=c.get(se)??0,de=h.get(se)??0,ce=Ae-de,he=r.VirtualCurrencies[se];he?(he.Amount+=ce,he.UpdatedAt=o,he.Daily&&Ci(he.Daily.PeriodStartUtc)===Ci(i)?(he.Daily.Earned+=Ae,he.Daily.Spent+=de):he.Daily={PeriodStartUtc:Ei(i),Earned:Ae,Spent:de}):r.VirtualCurrencies[se]={Amount:ce,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:Ei(i),Earned:Ae,Spent:de}};}}if(n.ccChanged=y.size>0||V.size>0,n.ccChanged){r.CryptoCurrencies??={};for(let se of new Set([...y.keys(),...V.keys()])){let Ae=y.get(se)??new Yt__default.default(0),de=V.get(se)??new Yt__default.default(0),ce=Ae.minus(de),he=r.CryptoCurrencies[se];he?(he.Amount=new Yt__default.default(he.Amount).plus(ce).toString(),he.UpdatedAt=o):r.CryptoCurrencies[se]={Amount:ce.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(n.itemsChanged=oe.size>0||be.size>0||ue.size>0||ge.size>0,n.itemsChanged){r.Items??={},r.UnstackableItems??={};let se=r.UnstackableItems,Ae=new Set([...oe.keys(),...be.keys(),...ue.keys(),...ge.keys()]);for(let de of Ae){let ce=(oe.get(de)??0)-(be.get(de)??0),he=(ue.get(de)??0)-(ge.get(de)??0),me=ce+he,st=r.Items[de];st?(ce!==0&&(st.StackableAmount+=ce),he!==0&&(st.UnstackableAmount+=he),me!==0&&(st.TotalAmount+=me)):r.Items[de]={StackableAmount:Math.max(0,ce),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,me)};}for(let[de,ce]of ge){if(ce<=0)continue;let he=Object.values(se).filter(me=>me.ItemID===de&&me.EquippedSlot==null&&(me.ExpiresAt==null||new Date(me.ExpiresAt)>i)).sort(wg).slice(0,ce).map(me=>me.ItemInstanceID);for(let me of he)delete se[me];}for(let[de,ce]of ue){let he=zg(t,de);for(let me=0;me<ce;me++){let st=G();se[st]={ItemInstanceID:st,ItemID:de,CatalogID:he,RemainingUses:1,AcquiredAt:o};}}}s.EventToken??={};let wi=s.EventToken;for(let se=0;;se++){let Ae,de;if(se===0)Ae=e.Grant?.Standard?.EventTokens,de=false;else if(se-1<Xe)Ae=vt[se-1]?.Resources?.EventTokens,de=false;else if(se===1+Xe)Ae=e.Consume?.Standard?.EventTokens,de=true;else break;if(!(!Ae||Ae.length===0))for(let ce of Ae){let he=ce.Address;if(!he||he.Type==null)continue;let me=ce.Amount??0;if(me<=0)continue;let st=Mg(wi,he.Type);if(!st)continue;let Pe=st[he.EntityID];Pe||(Pe={},st[he.EntityID]=Pe),Pe.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Pe.Daily??={Date:Ei(i),TotalEarned:0},Pe.Meta??={};let ki=ce.Source&&ce.Source.length>0?ce.Source:"CustomAction";de?(Pe.Balance.Current-=me,Pe.Balance.TotalSpent+=me):(Pe.Balance.Current+=me,Pe.Balance.TotalEarned+=me,Ci(Pe.Daily.Date)!==Ci(i)&&(Pe.Daily={Date:Ei(i),TotalEarned:0}),Pe.Daily.TotalEarned+=me,Pe.Daily.EarnedBySource??={},Pe.Daily.EarnedBySource[ki]=(Pe.Daily.EarnedBySource[ki]??0)+me,Pe.Daily.TriggersBySource??={},Pe.Daily.TriggersBySource[ki]=(Pe.Daily.TriggersBySource[ki]??0)+1,Pe.Daily.LastTriggerBySource??={},Pe.Daily.LastTriggerBySource[ki]=o,Pe.Meta.JoinedAtUtc||(Pe.Meta.JoinedAtUtc=o),Pe.Meta.LastEarnedAtUtc=o),n.tokensChanged=true;}}return n}function wg(s,e){return s.AcquiredAt!==e.AcquiredAt?s.AcquiredAt<e.AcquiredAt?-1:1:s.ItemInstanceID===e.ItemInstanceID?0:s.ItemInstanceID<e.ItemInstanceID?-1:1}function kg(s,e,t){let i=s?.Catalogs;if(i){if(e){let n=i[e]?.Items?.[t];if(n)return n}for(let n of Object.values(i)){let r=n.Items?.[t];if(r)return r}}}function zg(s,e){let t=s?.Catalogs;if(t){for(let[i,n]of Object.entries(t))if(n.Items&&e in n.Items)return i}}function Mg(s,e){switch(e){case "TimedEvent":return s.TimedEvent??={};case "Quest":return s.Quest??={};case "Leaderboard":return s.Leaderboard??={};case "CoopEvent":return s.CoopEvent??={};case "Season":return s.Season??={};default:return null}}function du(s,e,t){let i={drop:[],restore:{}};if(!t)return i;let n=t.ChangedInstances??{},r=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let h of Object.values(n))h?.ItemID&&o.add(h.ItemID);for(let h of r){let y=s[h]?.ItemID;y&&o.add(y);}if(o.size===0)return i;let c=h=>r.has(h)||h in n;if(e){for(let[h,y]of Object.entries(e))h in s||c(h)||y&&o.has(y.ItemID)&&i.drop.push(h);for(let[h,y]of Object.entries(s))h in e||c(h)||y&&o.has(y.ItemID)&&(i.restore[h]=y);}return i}function Po(s,e){return s===e||s.startsWith(`${e}:`)}var hn=class s{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 i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){s.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 i of t)this.currentState[i]=e[i];s.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){s.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,i=new Date){if(!this.currentState)return;let n=Do(this.currentState,e,t,i);this.emitResourceChanges(n,false);}applyResourcesWithDelta(e,t,i,n=new Date){if(!this.currentState)return;let r=this.currentState,o={...r.InventoryV2?.UnstackableItems??{}},c=Do(r,e,i,n),h=du(o,r.InventoryV2?.UnstackableItems,t),y=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],oe=h.drop.length>0||Object.keys(h.restore).length>0||y.length>0||V.length>0;if(oe){r.InventoryV2??={},r.InventoryV2.UnstackableItems??={};let be=r.InventoryV2.UnstackableItems;for(let ue of h.drop)delete be[ue];for(let[ue,ge]of Object.entries(h.restore))be[ue]=ge;for(let[ue,ge]of y)be[ue]=ge;for(let ue of V)delete be[ue];}this.emitResourceChanges(c,oe);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,n){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let r=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof Yt__default.default?t:new Yt__default.default(t),c=n===void 0?new Yt__default.default(0):n instanceof Yt__default.default?n:new Yt__default.default(n),h=i??new Date().toISOString(),y=r[e];y?(y.Amount=new Yt__default.default(y.Amount).plus(o).toString(),c.isZero()||(y.Frozen=new Yt__default.default(y.Frozen??0).plus(c).toString()),y.UpdatedAt=h):r[e]={Amount:o.toString(),Frozen:c.toString(),CreatedAt:h,UpdatedAt:h},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,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let n=this.currentState.Store.Purchases,r=n[e];r||(r={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},n[e]=r),r.TotalPurchases+=t,r.LastPurchasedAt=i,i>=r.DailyResetUtc?(r.DailyPurchases=t,r.DailyResetUtc=cu(i)):r.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let n=this.currentState.Lootbox??={};if(n.Pity??={},t){let r=new Date().toISOString();for(let o of t)o.RuleID&&(n.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:r});}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,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let n=this.currentState.Quest;if(t){n.Cycles??={};let r=n.Cycles[t];if(!r)return;r.Quests??={};let o=r.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {n.PermanentQuests??={};let r=n.PermanentQuests[e]??={QuestID:e,Status:i};r.Status=i,i==="Claimed"&&(r.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 i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.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 i of Object.values(e)){if(!i.CycleID)continue;let n=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,r=t[n]??={};r.Balance??={Current:0,TotalEarned:0,TotalSpent:0},r.Balance.Current=i.PointsCurrent??0,r.Balance.TotalEarned=i.PointsTotalEarned??0,r.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(r.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 i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.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 i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.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 i of e){if(!i.FlowID||!i.StepID)continue;let n=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};n.Steps??={};let r=n.Steps[i.StepID]??={StepID:i.StepID};r.Progress=i.Progress,i.Completed&&(r.CompletedAtUtc??=new Date().toISOString(),n.CurrentStepID===i.StepID&&(n.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 i of e){if(!i.QuestID)continue;let n;if(!i.CycleID)t.PermanentQuests??={},n=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let r=t.Cycles[i.CycleID];if(!r)continue;r.Quests??={},n=r.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(n.Status=i.Status,i.ObjectiveID){n.Objectives??={};let r=n.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};r.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(r.Completed=true,r.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(n.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[i,n]of Object.entries(t))if(Po(i,e)&&n)return n;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,i,n){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[r,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((n?r!==n:!Po(r,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,n),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,n){let r=this.activeEventsCache?.ActiveEvents;if(r)for(let o of r)o.Type!==e||o.TimedEventID!==t||n&&o.TokenEntityID&&o.TokenEntityID!==n||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,n){if(!e)return;let r=this.ensureLeaderboardProgress(e);(r.ScoreCycleVersion??0)<n&&(r.ScoreEarnedThisCycle=0,r.ClaimedMilestoneIDs=[],r.BracketID=null),r.CurrentScore=t,r.ScoreEarnedThisCycle=(r.ScoreEarnedThisCycle??0)+i,r.ScoreCycleVersion=n,r.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 i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.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,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}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 i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.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,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}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 i=this.currentState?.Character?.Characters;if(!i)return;let n=false;for(let r of Object.values(i))for(let o of Object.values(r.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,n=true);n&&(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);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,n=i[e];n||(n={CharacterID:e},i[e]=n),t(n),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let n=this.currentState?.Character?.Characters?.[e];n&&(n.Equipment??={},i===null?delete n.Equipment[t]:n.Equipment[t]=i,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,i=false;for(let[n,r]of Object.entries(e.ChangedInstances??{}))t[n]=r,i=true;for(let n of e.RemovedInstanceIDs??[])n in t&&(delete t[n],i=true);i&&(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,i){this.currentState??={};let n=this.currentState.CoopEvent??={MyObjectIndex:-1};n.ActiveGroupID=e,n.ActiveCoopEventID=t,n.MyObjectIndex=i,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(i=>i!==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(i=>i!==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(i=>i!==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(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(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 i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let n of Object.keys(i)){let r=i[n];r&&r.BoostID===e.BoostID&&n!==e.InstanceID&&delete i[n];}i[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,i,n,r){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,c={Value:i,UpdatedAt:new Date().toISOString(),Version:n,LastWriter:"Client",ExpiresAt:r??null};if(e==="Private")o.Private??={},o.Private[t]=c;else if(e==="Public")o.Public??={},o.Public[t]=c;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 i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.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 i=this.ensureBoard();i.BuildingStates??=[];let n=i.BuildingStates.find(r=>r.SlotIndex===e);n||(n={SlotIndex:e},i.BuildingStates.push(n)),t(n),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let n=this.ensureBoard().Pending;n&&(e&&(n.RaidLayout=e),t>=0&&(n.OpenedIndices??=[],n.OpenedIndices.includes(t)||n.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.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 n of Object.values(e.CryptoBalances??{}))n?.CurrencyID&&this.patchCryptoCurrencyDelta(n.CurrencyID,n.AmountDelta,n.UpdatedAt,n.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let n=this.currentState.Blockchain??={},r=n.PendingWithdrawals??[];t.size>0&&(r=r.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!r.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(r=[...r,i]),n.PendingWithdrawals=r;}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 mn=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,i]of Object.entries(e))this.sections.has(t)||this.sections.set(t,i);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let i=this.config?.[e];return i??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 fn=class{user;config;constructor(e){this.user=new hn(e),this.config=new mn;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Og(s){return s}var Eg=0,Ug=1500,qg=3,yn=class{constructor(e,t,i=null,n="",r="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=n;this.loginMode=r;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 N(void 0);let i=Date.now(),n=[],r=[];for(let h of new Set(e)){let y=this.rules.get(h);if(y&&(t?.force||y.needsServer(i))){n.push(this.runRule(h,y));continue}(t?.force||!this.state.isStateFresh(h,t?.maxAgeMs))&&r.push(h);}let c=(await Promise.all([...n,r.length>0?this.queueSlice(r):Promise.resolve(N(void 0))])).find(h=>!h.ok);return c&&!c.ok?c:N(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let n=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,n),n}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},Eg),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 i;this.batchRunning=new Promise(n=>i=n);try{let n=this.state?await this.state.readStateSlice(e):N(void 0),r=n.ok?N(void 0):n;for(let o of t)o(r);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let n=gn(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let y=this.fresh(n,i?.maxAgeMs);if(y)return N(y.data);let V=this.loginFailures.get(n);if(V)return this.loginFailures.delete(n),V;let oe=this.inflight.get(n);if(oe)return oe}let r=this.generation.get(n)??0,o=Date.now(),h=t().then(y=>{if(!y.ok)return y;let V=Date.now();if((this.generation.get(n)??0)===r)return this.entries.set(n,{data:y.data,storedAt:V,expiresAt:Io(e,y.data,V)}),y;let oe=this.entries.get(n);if(oe&&oe.storedAt>=o)return y;let be=Io(e,y.data,V);return this.entries.set(n,{data:y.data,storedAt:V,expiresAt:Math.min(be??1/0,V+Ug)}),y}).finally(()=>{this.inflight.get(n)===h&&this.inflight.delete(n);});return this.inflight.set(n,h),h}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,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let n=t.Key?t.Key:void 0,r=gn(i.view,n);if(!t.Success){this.loginFailures.set(r,u("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(r),i.apply(o.data,n),this.put(i.view,o.data,n));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let n=e.login;this.loadUsed().then(()=>{let r=hu({Name:n,Key:t});this.used.get(r)?.n!==this.session&&(this.used.set(r,{Name:n,Key:t??"",...i,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>qg||this.used.set(hu(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()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(n=>n&&typeof n.Name=="string"&&typeof n.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(gn(e,t))?.data}put(e,t,i){this.register(e);let n=gn(e,i);this.bump(n);let r=Date.now();this.entries.set(n,{data:t,storedAt:r,expiresAt:Io(e,t,r)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let n of [...this.entries.keys(),...this.inflight.keys()])(n===i||n.startsWith(`${i}|`))&&this.drop(n);this.drop(i);}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,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let n=Date.now();if(!(i.expiresAt!==null&&n>=i.expiresAt)&&!(t!==void 0&&n-i.storedAt>t))return i}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 i of this.views.values())i.dependsOn?.some(n=>t.has(n))&&this.invalidate(i);}};function gn(s,e){return e===void 0?s.key:`${s.key}|${e}`}function hu(s){return s.Key?`${s.Name}|${s.Key}`:s.Name}function Io(s,e,t){let i=s.expiresAt?.(e)??null,n=s.ttlMs!==void 0?t+s.ttlMs:null;return i!==null&&n!==null?Math.min(i,n):i??n}var Rn=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 Lg(e)?e:ze.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 Lg(s){return s!==null&&Object.values(ze).includes(s)}var wt=["https://idosgames.com","https://www.idosgames.com"],Cn="https://platform.idosgames.com",mu=/^[a-z0-9]{8}-preview\.idos\.games$/;function vo(s){return s==="localhost"||s==="127.0.0.1"||s==="[::1]"||s.endsWith(".localhost")}function To(){if(typeof window>"u")return false;let s=window.location.hostname.toLowerCase();return mu.test(s)?true:vo(s)&&globalThis.__IDOS_PREVIEW__!=null}function Ui(s){if(typeof window<"u"&&mu.test(window.location.hostname.toLowerCase()))return s===Cn;if(wt.includes(s))return true;if(typeof window>"u"||!vo(window.location.hostname))return false;try{return vo(new URL(s).hostname)}catch{return false}}var fu="IDOS_PLATFORM_WALLET_ACK",gu="PLATFORM_WALLET_UNAVAILABLE",Bg=5e3,Gg=18e4;function Fg(){if(Ui(Cn))return [Cn];let s=[...wt],e=window.location.ancestorOrigins?.[0];return e&&!s.includes(e)&&Ui(e)&&s.push(e),s}function _g(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function kt(s,e,t,i={}){let n={ok:false,error:gu,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(n);let r=window.parent;if(!r)return Promise.resolve(n);let o=_g(),c=i.answerTimeoutMs??Gg;return new Promise(h=>{let y=false,V,oe=ue=>{y||(y=true,window.removeEventListener("message",be),clearTimeout(V),h(ue));},be=ue=>{if(!Ui(ue.origin))return;let ge=ue.data;if(!(!ge||ge.requestId!==o)){if(ge.type===fu){clearTimeout(V),V=setTimeout(()=>oe({ok:false,error:"TIMEOUT",data:{}}),c);return}ge.type===e&&oe({ok:ge.ok===true,error:typeof ge.error=="string"?ge.error:void 0,data:ge});}};V=setTimeout(()=>oe(n),Bg),window.addEventListener("message",be);for(let ue of Fg())try{r.postMessage({type:s,requestId:o,...t},ue);}catch{}})}var Ao={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},Vg=30*6e4,wo="idos:platformSignIn:declined:";function Ng(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(To())return false;let s=window.location.ancestorOrigins?.[0];if(s&&!wt.includes(s))try{let e=new URL(s).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}function jg(){if(typeof window>"u"||!To())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function ko(s){let e=await kt(Ao.request,Ao.response,{titleID:s,supports:["pgs"]},{answerTimeoutMs:Vg}),t=e.data.ticket;if(e.ok&&typeof t=="string"&&t.length>0)return {ticket:t};let i=e.data.code;return e.ok&&typeof i=="string"&&i.length>0?{code:i}:{error:e.error??"no_code"}}function Wg(s){try{window.localStorage.setItem(wo+s,"1");}catch{}}function Kg(s){try{window.localStorage.removeItem(wo+s);}catch{}}function Qg(s){try{return window.localStorage.getItem(wo+s)==="1"}catch{return false}}var Hg=8,$g=100,Jg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,yu=["GameLoop"];function Zg(s){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(s)}var Sn=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=ze.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,i){let n=this.authContext;if(!n)return a;let r=this.baseRequest();r.UserID=n.userID,r.ClientSessionTicket=n.clientSessionTicket,r.WalletAddress=e,r.NetworkID=t,i&&(r.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(r);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return a;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let n=await this.ctx.api.authentication.unlinkWallet(i);return n.ok&&n.data.PlayAccess&&this.setPlayAccess(n.data.PlayAccess),n}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.platform.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.platform.getDeviceID(),e.Device=this.ctx.platform.getDeviceModel(),e.Platform=this.ctx.platform.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(ze.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return u("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let n=await this.ctx.api.authentication.loginWithEmail(i);if(!n.ok)return n;this.applyAuthContext(n.data);let r=await this.fetchAndApplyClientState(ze.Email);return r.ok&&this.keepEmailCredentials(e,t),r}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.platform.getDeviceID(),i.Device=this.ctx.platform.getDeviceModel(),i.Platform=this.ctx.platform.getPlatform();let n=await this.ctx.api.authentication.registerWithEmail(i);return n.ok?(this.pendingRegistration={email:e,password:t},N({codeTtlMinutes:n.data.CodeTtlMinutes??0,resendCooldownSeconds:n.data.ResendCooldownSeconds??0})):n}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let n=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!n.ok)return n;this.applyAuthContext(n.data);let r=await this.fetchAndApplyClientState(ze.Email);return r.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,r}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?N(void 0):i}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let i=await this.ctx.api.authentication.loginWithGoogle(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.Google)):i}async loginWithApple(e,t){if(!e?.trim())return u("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let n=await this.ctx.api.authentication.loginWithApple(i);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(ze.Apple)):n}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.WalletAddress=e,n.NetworkID=t,n.WalletSignature=i,n.Platform=this.ctx.platform.getPlatform(),n.Device=this.ctx.platform.getDeviceModel(),n.DeviceID=this.ctx.platform.getDeviceID();let r=await this.ctx.api.authentication.loginWithWallet(n);return r.ok?(this.applyAuthContext(r.data),this.fetchAndApplyClientState(ze.Wallet)):r}async loginWithSsoCode(e){if(!e)return u("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.platform.getDeviceID(),t.Device=this.ctx.platform.getDeviceModel(),t.Platform=this.ctx.platform.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ze.iDosGames)):i}async loginWithPlatformGameTicket(e){if(!e)return u("client","Platform game ticket is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.PlatformGameTicket=e;let i=await this.ctx.api.authentication.resolvePlatformGameSession(t);return i.ok?(this.applyAuthContext(i.data),this.platformGameSession=true,this.fetchAndApplyClientState(ze.iDosGames)):i}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,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.Email=e,n.ResetToken=t,n.Password=i,this.ctx.api.authentication.resetPassword(n)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==ze.None?e:ze.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 i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let n=await this.ctx.api.authentication.refreshSession(i);return n.ok?(this.applyRefresh(n.data),"ok"):(Zg(n.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,i){switch(e){case ze.Email:return this.loginWithEmail(t,i);case ze.Device:case ze.None:return this.loginWithDeviceID();case ze.Telegram:return this.loginWithTelegram();default:return Promise.resolve(u("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 ko(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let n=await this.ctx.api.authentication.resolvePlatformGameSession(i);return n.ok?(this.applyAuthContext(n.data),this.platformGameSession=!0,n.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!==ze.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===ze.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&&Jg.test(e)}static isValidPasswordLength(e){return e.length>=Hg&&e.length<=$g}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=ze.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){let t=await this.ctx.userService.getClientStateExcept(yu,yu);return t.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)),t}};var Yg="idos:cfg",Si=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Ru(t)}`:e&&e.length>0?`f:${Ru(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${Yg}:${this.titleId}:${e}`}};function Ru(s){return [...s].map(e=>e.toLowerCase()).sort().join(",")}var Cu="idos:loc",xi=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 i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(n)),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 i={};for(let[n,r]of Object.entries(t))typeof r=="number"&&r>0&&(i[n]=r);return i}catch{return {}}}async noteVersion(e,t){let i=await this.readVersions();i[e]!==t&&(i[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(i)));}keyOf(e){return `${Cu}:${this.titleId}:${e}`}versionsKey(){return `${Cu}:${this.titleId}:versions`}};var Xg="idos:sec",xn=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 i=JSON.parse(t);return !i||typeof i!="object"||i.v!==e||!i.s||typeof i.s!="object"?{}:i.s}catch{return {}}}async write(e,t){try{let i={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(i));}catch{}}keyOf(){return `${Xg}:${this.titleId}`}};var ey="idos:state",bn=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 i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,n){if(!(!e||!t))try{let r={e:t,v:i,s:n};await this.storage.set(this.keyOf(e),JSON.stringify(r));}catch{}}keyOf(e){return `${ey}:${this.titleId}:${e}`}};function ty(s,e){if(!s)return;let t=new Set((e??[]).map(n=>n.trim().toLowerCase()));if(t.size===0)return s;let i={};for(let[n,r]of Object.entries(s))t.has(n.toLowerCase())||(i[n]=r);return i}function zo(s,e,t,i){let n={...s??{}};if(!e||!t||!i)return n;for(let[r,o]of Object.entries(t))i[r]===o&&r in e&&(n[r]=e[r]);return n}function iy(s){return {...s??{}}}function Mo(s){return typeof s.StateEpoch=="string"&&s.StateEpoch.length>0?s.StateEpoch:null}var Dn=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,i=Date.now()){if(this.versions[e]===void 0)return false;let n=this.confirmedAt[e];return n===void 0?false:t===void 0||i-n<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=ty(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 r=Object.keys(this.versions);this.reset(e),this.notify(r);}return}let i=Date.now(),n=[];for(let[r,o]of Object.entries(t)){let c=this.versions[r];c!==o&&(c!==void 0&&o===c+1?(this.versions[r]=o,this.confirmedAt[r]=i):(delete this.versions[r],delete this.confirmedAt[r]),n.push(r),this.dirty=true);}this.notify(n);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=iy(t);let n=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=n;this.dirty=true;let r=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&r.add(o);this.notify([...r]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),n=[];for(let[r,o]of Object.entries(t??{}))this.versions[r]!==o&&n.push(r),this.versions[r]=o,this.confirmedAt[r]=i;this.dirty=true,this.notify(n);}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 Su=u("server","Title configuration is unavailable (CDN and API both failed)."),Pn=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.platform.getFullURL(),RelatedEntityID:G()}:null}get configCache(){return this.cache??=new Si(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new xi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new xn(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new Dn(new bn(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}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 a;let t=Si.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let n=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let r=await this.ctx.api.user.getClientState(e);if(!r.ok)return r;let o=await this.resolveTitleConfig(r.data,t,i,{Fields:e.TitleFields});return o==null?Su:(this.finishStateHandshake(r.data,n),await this.restoreSections(r.data.TitleConfigVersion,o),await this.applyClientState(r.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(r.data.Views),await this.applyLocalization(r.data.Localization),await this.flushState(n),r)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let n=this.stateStore.versionsFor(t);if(n){e.KnownStateVersions=n;let r=this.stateStore.currentEpoch;r&&(e.KnownStateEpoch=r);}return {userId:i,cached:this.stateStore.cachedState,sent:n}}finishStateHandshake(e,t){let i=zo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let n=Mo(e);!n||!t.userId||this.stateStore.afterFullRead(n,e.StateVersions);}async resolveTitleConfig(e,t,i,n){let r=e.TitleConfigVersion;if(i&&r&&i.v===r)return i.c;if(e.TitleConfigUrl){let c=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(c!=null)return r&&await this.configCache.write(t,r,c),c}let o=await this.fetchConfigFromApi(n);return o!=null?(r&&await this.configCache.write(t,r,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},n=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return n.ok?n.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return a;i.ExcludeFields=e,i.ExcludeTitleFields=t;let n=Si.scopeOf(null,t??[]),r=await this.configCache.read(n);r&&(i.KnownTitleConfigVersion=r.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let c=await this.ctx.api.user.getClientStateExcept(i);if(!c.ok)return c;let h=await this.resolveTitleConfig(c.data,n,r,{ExcludeFields:t??[]});return h==null?Su:(this.finishStateHandshake(c.data,o),await this.restoreSections(c.data.TitleConfigVersion,h),await this.applyClientState(c.data,h,e,t),this.ctx.cache.acceptLoginViews(c.data.Views),await this.applyLocalization(c.data.Localization),await this.flushState(o),c)}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 i=t,n={};for(let[r,o]of Object.entries(await this.sectionCache.read(e)))i[r]==null&&(n[r]=o);this.ctx.data.config.restoreSections(n),this.ctx.data.config.setSectionSink((r,o)=>{i[r]!=null||o==null||(n[r]=o,this.sectionCache.write(e,n));});}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 i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}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}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let n=await this.localizationCache.read(t);if(i<=0)return n?.t??null;if(n&&n.v===i)return n.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let r=await this.fetchLocalizationFromApi(t,n?.v??0);return r??n?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let n=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!n.ok)return null;let r=n.data;if(r.NotModified)return null;let o=r.Entries??{},c=r.Version??0,h=r.Locale??e;return c>0&&await this.localizationCache.write(h,c,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):a}async getUserState(e){let t=this.baseRequest();if(!t)return a;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),n=await this.ctx.api.user.getUserState(t);if(!n.ok)return n;let r=zo(n.data.User,i.cached,i.sent,n.data.StateVersions);n.data.User=r;let o=i.sent??{},c=Object.entries(n.data.StateVersions??{}).filter(([y,V])=>o[y]!==V||this.ctx.data.user.state?.[y]===void 0).map(([y])=>y);this.ctx.data.user.applyUserStateContainers(r,c);let h=Mo(n.data);return h&&(this.stateStore.afterSliceRead(h,n.data.StateVersions),await this.flushState(i)),n}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 a;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 a;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 a;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,i){let n=this.baseRequest();if(!n)return a;n.UsageTime=e,n.IsNewSession=t,n.SessionDurationSeconds=i;let r=await this.ctx.api.user.addUsageTime(n);return r.ok&&this.ctx.emitter.emit("user:usageTimeAdded",r.data),r}async deleteUserAccount(){let e=this.baseRequest();if(!e)return a;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 a;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,n){let r=i?.includes("GameLoop")===true,o=n?.includes("GameLoop")===true,c=r?this.ctx.data.user.state?.GameLoop:void 0,h=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let y=this.ctx.data.user.state;r&&y&&y.GameLoop==null&&(y.GameLoop=c);let V=this.ctx.data.config.titlePublicConfiguration;o&&V&&V.GameLoop==null&&(V.GameLoop=h),this.ctx.emitter.emit("user:clientStateReceived",e);}};var vn=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return u("client","SpendID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${G()}`},n=await this.ctx.api.currency.spend(i);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",n.data)),n}async convert(e,t,i,n,r,o){if(!t)return u("client","SourceID is required.");if(!n)return u("client","TargetID is required.");if(r<=0)return u("client","Amount must be positive.");if(e===i&&t===n)return u("client","Source and target must differ.");if(e===ht.Crypto||i===ht.Crypto)return u("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return a;let c={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:String(Math.trunc(r)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${n}_${G()}`},h=await this.ctx.api.currency.convert(c);if(h.ok){let y=h.data,V={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:y.SourceID,Amount:y.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:y.TargetID,Amount:y.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",y);}return h}async cryptoConvert(e,t,i,n,r,o){let c=r instanceof Yt__default.default?r:new Yt__default.default(r);if(!t)return u("client","SourceID is required.");if(!n)return u("client","TargetID is required.");if(c.lte(0))return u("client","SourceAmount must be a positive decimal.");if(e===i&&t===n)return u("client","Source and target must differ.");if(e===ht.Virtual&&i===ht.Virtual)return u("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ht.Virtual&&!c.isInteger())return u("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:c.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${n}_${G()}`},y=await this.ctx.api.currency.cryptoConvert(h);if(y.ok){let V=y.data,oe=[],be=[];if(V.SourceType===ht.Virtual&&oe.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===ht.Virtual&&be.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),oe.length>0||be.length>0){let ue={Consume:oe.length>0?{Standard:{Entries:oe}}:null,Grant:be.length>0?{Standard:{Entries:be}}:null};this.ctx.data.user.applyResourceOperation(ue,this.ctx.data.config.itemDefinitions);}V.SourceType===ht.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new Yt__default.default(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===ht.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new Yt__default.default(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return y}};var Tn=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i,n){let r=e.trim();if(!r)return u("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:r,SelectedOptionID:i,CreditsConfirmationID:n,RelatedEntityID:`upgrade_item_${r}_${G()}`};t&&t.length>0&&(o.FodderInstanceIDs=[...t]);let c=await this.ctx.api.item.upgradeLevel(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(c.data.ItemInstanceID??r,c.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",c.data)),c}async upgradeLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let n of i.data)n.Success&&n.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(n.Data.ItemInstanceID,n.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var An=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:Tt.nullish(),AllowedPlatforms:zod.z.array(Yi).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ae=zod.z.record(zod.z.string(),An),ny=zod.z.object({Store:Xi,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var qi={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},fe=zod.z.object({ConfirmationID:zod.z.string(),Url:zod.z.string(),Status:zod.z.string(),PriceCredits:zod.z.number(),ExpiresAt:p}).passthrough(),xu=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),ry={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"},Oo=zod.z.object({ServerTimeUtc:p,OfferID:zod.z.string(),Count:zod.z.number(),Resources:O.nullish(),Inventory:K.nullish(),CreditsConfirmation:fe.nullish()}),bu=zod.z.array(we(Oo)),sy=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:p,LastPurchasedAt:p}),oy=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:p}),Du=zod.z.object({Purchases:zod.z.record(zod.z.string(),sy).nullish(),Rotations:zod.z.record(zod.z.string(),oy).nullish()}).passthrough().transform(s=>s),zt=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(),wn=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),ay={Fixed:"Fixed",Title:"Title",Player:"Player"},ly=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:Z.nullish()}).passthrough(),Pu=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(ly).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),uy=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Rotation:Q.nullish()}).passthrough(),cy=zod.z.object({SlotID:zod.z.string().nullish(),Identity:zt.nullish(),Availability:wn.nullish(),Rotation:Pu.nullish(),Presets:uy.nullish()}).passthrough(),py=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish()}).passthrough(),dy=zod.z.object({SectionID:zod.z.string().nullish(),Identity:zt.nullish(),Availability:wn.nullish(),Slots:zod.z.record(zod.z.string(),cy).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:py.nullish()}).passthrough(),Iu=zod.z.object({Sections:zod.z.record(zod.z.string(),dy).nullish()}).passthrough(),hy=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Layout:Q.nullish()}).passthrough(),my=zod.z.object({StoreID:zod.z.string().nullish(),Identity:zt.nullish(),Availability:wn.nullish(),Layout:Iu.nullish(),Presets:hy.nullish()}).passthrough(),vu=zod.z.object({Options:ae.nullish(),CompareAt:zod.z.record(zod.z.string(),Tt).nullish()}).passthrough(),Tu=zod.z.object({Grant:H.nullish()}).passthrough(),Au=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),fy=zod.z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish(),Availability:Q.nullish()}).passthrough(),gy=zod.z.object({OfferID:zod.z.string().nullish(),Identity:zt.nullish(),Pricing:vu.nullish(),Reward:Tu.nullish(),Availability:Au.nullish(),Presets:fy.nullish()}).passthrough(),yy=zod.z.object({Identity:zod.z.record(zod.z.string(),zt).nullish(),Availability:zod.z.record(zod.z.string(),wn).nullish(),Layout:zod.z.record(zod.z.string(),Iu).nullish(),Rotation:zod.z.record(zod.z.string(),Pu).nullish(),Pricing:zod.z.record(zod.z.string(),vu).nullish(),Reward:zod.z.record(zod.z.string(),Tu).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Au).nullish()}).passthrough(),kn=zod.z.object({Stores:zod.z.record(zod.z.string(),my).nullish(),StoreOffers:zod.z.record(zod.z.string(),gy).nullish(),Presets:yy.nullish()}).passthrough(),Ry=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:p.nullish()}).passthrough(),Cy=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:Tt.nullish(),CompareAtCost:Tt.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(),Sy=zod.z.object({OfferID:zod.z.string(),Identity:zt.nullish(),PriceOptions:zod.z.array(Cy).nullish(),Rewards:H.nullish(),State:Ry.nullish()}).passthrough(),xy=zod.z.object({SlotID:zod.z.string(),Identity:zt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:p.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:Sy.nullish()}).passthrough(),by=zod.z.object({SectionID:zod.z.string(),Identity:zt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(xy).nullish()}).passthrough(),Dy=zod.z.object({StoreID:zod.z.string(),Identity:zt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:p.nullish(),Sections:zod.z.array(by).nullish()}).passthrough(),zn=zod.z.object({ServerTimeUtc:p,Stores:zod.z.array(Dy).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Mt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},Py="OFFER_NOT_IN_ROTATION";var wu="Store",ku={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:s=>{let e=null;for(let t of s.Stores??[])for(let i of t.Sections??[])for(let n of i.Slots??[]){let r=Date.parse(n.RefreshesAtUtc??"");!Number.isNaN(r)&&(e===null||r<e)&&(e=r);}return e}},Mn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ku,{schema:zn,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return u("client","OfferID is required.");if(t<1)return u("client","Count must be at least 1.");let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`store_buy_${e}_${n.userID}_${G()}`},o=await this.ctx.api.store.purchase(r);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;this.ctx.data.user.patchStorePurchase(e,t,c.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",c);}return o}async purchaseWithCredits(e,t=1,i={}){return await this.ctx.credits.pay(n=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:n}),{onConfirmation:i.onConfirmation,signal:i.signal,pollMs:i.pollMs})}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):a}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):a}async purchaseBatch(e){if(!e||e.length===0)return u("client","purchases is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||!r.Data.OfferID||(this.ctx.data.user.patchStorePurchase(r.Data.OfferID,r.Data.Count,r.Data.ServerTimeUtc),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(wu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.store.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(wu,n.data),this.ctx.emitter.emit("store:definitionsLoaded",n.data)),n}getStorefront(e){return this.ctx.cache.read(ku,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return a;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 i of t.Sections??[])for(let n of i.Slots??[]){let r=n.RefreshesAtUtc;r&&(e===null||Date.parse(r)<Date.parse(e))&&(e=r);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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 Eo={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},Iy=15*6e4,vy=/^[a-z0-9]{8}-preview\.idos\.games$/;function Xt(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !vy.test(window.location.hostname.toLowerCase())}async function Uo(s){let e=await kt(Eo.request,Eo.response,{titleID:s.titleID,userID:s.userID,currencyID:s.currencyID,amount:s.amount},{answerTimeoutMs:Iy});return e.ok?{ok:true}:{ok:false,error:e.error}}var qo={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},Ty=10*6e4;function Ay(){let s=globalThis.navigator?.userAgent??"";if(!/\biDosGamesApp\/(?:player|studio)\//.test(s))return true;let e=/\biDosGamesPlatform\/(ios|android)\b/.exec(s);return (e?e[1]:/\bAndroid\b/.test(s)?"android":"ios")!=="ios"}function Lo(){return Xt()}async function Bo(s){let e=await kt(qo.request,qo.response,{titleID:s.titleID,confirmationID:s.confirmationID},{answerTimeoutMs:Ty});return e.ok?{ok:true}:{ok:false,error:e.error}}var On=class{constructor(e){this.ctx=e;}ctx;async pay(e,t={}){let i=await e(void 0);if(!i.ok||!i.data.CreditsConfirmation)return i;let n=i.data.CreditsConfirmation,r=()=>e(n.ConfirmationID);if(Lo()){let h=await Bo({titleID:this.ctx.settings.titleID,confirmationID:n.ConfirmationID});if(h.ok)return await r();if(h.error==="DECLINED")return u("server","CREDITS_CONFIRMATION_DECLINED");if(h.error==="NOT_ENOUGH_CREDITS")return u("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(n);let o=Math.max(1e3,t.pollMs??2500),c=Date.parse(n.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return u("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>c)return u("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(V=>setTimeout(V,o));let h=await this.ctx.store.getCreditsConfirmation(n.ConfirmationID);if(!h.ok)continue;let y=h.data.Status;if(y!==qi.Pending)return y===qi.Declined?u("server","CREDITS_CONFIRMATION_DECLINED"):y===qi.Expired?u("server","CREDITS_CONFIRMATION_EXPIRED"):await r()}}};var En=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?N(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return u("client","Receipt is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},r=await this.ctx.api.purchase.validatePurchase(n);return r.ok&&this.applyValidation(r.data),r}async buyWithTelegramStars(e,t){if(!e)return u("client","productID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},n=await this.ctx.api.purchase.createTelegramInvoice(i);return n.ok&&t?.open!==false&&this.ctx.platform.openInvoice(n.data.InvoiceLink),n}async validatePurchasesBatch(e){if(!e||e.length===0)return u("client","receipts is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let n of i.data.Items)n.Success&&n.Data&&this.applyValidation(n.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var zu=3,wy=700,Un=class{constructor(e){this.ctx=e;Xt()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return Ri(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await Uo({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return i.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:i.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=zu;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===zu)break;await Gt(wy);}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,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.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 i of t)if(i?.Type===Zi.Purchase&&i.ProductID)return i.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t){if(i?.Type!==Zi.CryptoCurrency||!i.CurrencyID)continue;let n=Number(i.Amount??0);if(!(n>0))continue;let r=this.cryptoBalance(i.CurrencyID);return r>=n?null:{currencyID:i.CurrencyID,required:n,available:r,missing:n-r}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var Mu="Lootbox",qn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Mu,e);if(t){let r={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.lootbox.getDefinitions(i);if(n.ok){let r=n.data.LootboxDefinitions;r&&(this.ctx.data.config.patchSection(Mu,r),this.ctx.emitter.emit("lootbox:definitionsLoaded",r));}return n}async open(e,t,i,n,r){if(!e)return u("client","LootboxID is required.");if(t<1)return u("client","Count must be at least 1.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:n,CreditsConfirmationID:r,RelatedEntityID:`lootbox_${e}_${i??"default"}_${G()}`},c=await this.ctx.api.lootbox.open(o);if(c.ok&&!c.data.CreditsConfirmation){let h=c.data;h.TriggeredPity&&h.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,h.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(h.Resources,h.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",h);}return c}};var Go="Reward";function Ln(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var Bn=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(Go)?.Comebacks??{}).some(i=>i?.TrackPresenceOnRead===true),refresh:async()=>{let i=await this.getUserRewardsState();return i.ok&&(t=true),i}});}ctx;multiplier=1;multiplierEnabled=false;get milestoneRewardMultiplier(){return this.multiplier}get milestoneRewardMultiplierEnabled(){return this.multiplierEnabled}async getRewardDefinitions(e){let t=this.ctx.cache.configSection(Go,e);if(t){let r={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.reward.getRewardDefinitions(i);if(n.ok){let r=n.data.RewardDefinitions;r&&(this.ctx.data.config.patchSection(Go,r),this.ctx.emitter.emit("reward:definitionsLoaded",r));}return n}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return a;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 a;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${G()}`},n=await this.ctx.api.reward.claimDailyReward(i);if(n.ok){let r=n.data;this.ctx.data.user.patchDailyCalendarState(r.CalendarID,r.DailyState),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",r);}return n}async collectIdleAccrual(e){if(!Ln(e))return u("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${G()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let n=i.data;this.ctx.data.user.patchIdleAccrualState(n.AccrualID,n.IdleState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",n);}return i}async claimComebackReward(e){if(!Ln(e))return u("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchComebackState(n.ComebackID,n.ComebackState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",n);}return i}async claimReward(e){if(!Ln(e))return u("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchClaimRewardState(n.ClaimID,n.ClaimState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",n);}return i}async claimRewardWindow(e,t,i={}){if(!Ln(e))return u("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return u("client","Amount must be a positive number.");let n=i.boost??"None";if(n==="Ad"&&!i.adRequestID)return u("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:n,...i.adRequestID?{AdRequestID:i.adRequestID}:{},RelatedEntityID:i.roundID??`reward_window_${e}_${G()}`},o=await this.ctx.api.reward.claimRewardWindow(r);if(o.ok){let c=o.data;this.ctx.data.user.patchRewardWindowState(c.WindowID,c.WindowState),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:windowClaimed",c);}return o}};var Gn="Tutorial",Ou={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"]},Fn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ou,{schema:sn,apply:i=>this.applyUserTutorialState(i)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(Gn)?.Flows??{}).length>0,refresh:async()=>{let i=await this.getUserTutorialState();return i.ok&&(t=true),i}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(Gn,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.tutorial.getTutorialDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Gn,n.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",n.data)),n}getUserTutorialState(e=true,t){return this.ctx.cache.read(Ou,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}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,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${G()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return u("client","FlowID is required.");if(!t||t.length===0)return u("client","stepIDs is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${G()}`},r=await this.ctx.api.tutorial.completeStepsBatch(n);return r.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",r.data)),r}async skipStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.skipStep(i))}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 u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${G()}`},n=await this.ctx.api.tutorial.claimFlowReward(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",n.data)),n}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let n=e?.trim();if(!n)return u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),FlowID:n},o=await t(r);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,n){let r=e?.trim(),o=t?.trim();if(!r)return u("client","FlowID is required.");if(!o)return u("client","StepID is required.");if(!this.ctx.auth.context)return a;let c={...this.ctx.buildAuthedBaseRequest(),FlowID:r,StepID:o};n?.relatedEntityID&&(c.RelatedEntityID=n.relatedEntityID);let h=this.ctx.data.user.state?.Tutorial?.Flows?.[r]?.RewardClaimed===true,y=await i(c);return y.ok&&(this.applyFlowView(y.data),this.mayHavePaid(r,o,h,y.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",y.data)),y}mayHavePaid(e,t,i,n){return !i&&n.Flow?.RewardClaimed===true?true:n.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Gn)?.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 _n=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return a;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 a;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return u("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return u("client","campaignID is required.");if(!t)return u("client","walletAddress is required.");let n=this.ctx.authedRequest();if(!n)return a;n.CampaignID=e,n.WalletAddress=t,i&&(n.Amount=i);let r=await this.ctx.api.communityMarketing.withdrawCryptoReward(n);return r.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",r.data),r}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var qe=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 ky={Global:"Global",Announcement:"Announcement",Group:"Group"},Uu=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),zy={None:"None",Language:"Language",Region:"Region"},My=zod.z.enum(["None","Language","Region"]).catch("None"),Oy={Anyone:"Anyone",Friends:"Friends"},Ey=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),Uy={Reject:"Reject",Mask:"Mask"},qy=zod.z.enum(["Reject","Mask"]).catch("Reject"),Ly={Player:"Player",Publisher:"Publisher",System:"System"},By=zod.z.enum(["Player","Publisher","System"]).catch("Player"),Gy={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Fy=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),qu=zod.z.object({Gate:Z.nullish(),Schedule:Re.nullish()}).passthrough(),Lu=zod.z.object({Gate:Z.nullish(),Limits:Se.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Bu=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),_y=zod.z.object({Availability:Q.nullish(),Write:Q.nullish(),Retention:Q.nullish()}).passthrough(),Vy=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:Fy.nullish(),Type:Uu.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:My.nullish(),Capacity:zod.z.number().nullish(),Availability:qu.nullish(),Write:Lu.nullish(),Retention:Bu.nullish(),Presets:_y.nullish()}).passthrough(),Ny=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:Ey.nullish(),Limits:Se.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),jy=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:qy.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Se.nullish()}).passthrough(),Wy=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),Ky=zod.z.object({Availability:zod.z.record(zod.z.string(),qu).nullish(),Write:zod.z.record(zod.z.string(),Lu).nullish(),Retention:zod.z.record(zod.z.string(),Bu).nullish()}).passthrough(),Gu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),Vy).nullish(),Direct:Ny.nullish(),Moderation:jy.nullish(),Polling:Wy.nullish(),Presets:Ky.nullish()}).passthrough(),Qy=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),Eu=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(),Qy).nullish(),Limits:zod.z.record(zod.z.string(),Eu).nullish(),ReportLimits:Eu.nullish()}).passthrough();var Fo=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),Vn=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:qe.nullish(),AuthorType:By.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),Hy=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:Uu.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(),Nn=zod.z.object({Channels:zod.z.array(Hy).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),$y=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Vn).nullish(),NextCursor:Fo.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Fu=zod.z.object({Rooms:zod.z.array($y).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),_u=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Vn).nullish(),NextBefore:Fo.nullish()}).passthrough(),Vu=zod.z.object({Message:Vn.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),Nu=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:qe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Jy=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:qe.nullish(),LastMessage:Vn.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),ju=zod.z.object({Conversations:zod.z.array(Jy).nullish()}).passthrough(),bi=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:Fo.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),Wu=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),$e={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 Ku="Chat",Qu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},jn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Qu,{schema:Nn,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(Ku,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.chat.getChatDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Ku,n.data),this.ctx.emitter.emit("chat:definitionsLoaded",n.data)),n}getChannels(e,t){return this.ctx.cache.read(Qu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let n of i.data.Rooms??[])n.NextCursor&&n.RoomID&&this.cursors.set(n.RoomID,n.NextCursor),n.Messages&&n.Messages.length>0&&this.ctx.emitter.emit("chat:messages",n);return i}async getHistory(e,t,i){let n=this.ctx.authedRequest();return n?(n.RoomID=e,t&&(n.Before=t),i&&(n.Limit=i),this.ctx.api.chat.getHistory(n)):a}async sendMessage(e,t,i){let n=this.ctx.authedRequest();if(!n)return a;n.ChannelID=e,n.Text=t,i&&(n.Locale=i);let r=await this.ctx.api.chat.sendMessage(n);return r.ok&&this.ctx.emitter.emit("chat:sent",r.data),r}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Text=t;let n=await this.ctx.api.chat.sendMessage(i);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):a}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):a}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let n=await this.ctx.api.chat.markRead(i);return n.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),n}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):a}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):a}async reportMessage(e,t,i,n){let r=this.ctx.authedRequest();return r?(r.RoomID=e,r.MessageID=t,r.Reason=i,n&&(r.Comment=n),this.ctx.api.chat.reportMessage(r)):a}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):a}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):a}resetCursors(){this.cursors.clear();}};var Zy={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},Yy=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),Xy={Player:"player",Title:"title",Creator:"creator"},Di={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Hu=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),eR=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),_o=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:Yy.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(eR).nullish()}).passthrough(),$u=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(_o).nullish()}).passthrough(),Ot={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var tR="IDOS_PLATFORM_PUSH_REQUEST",iR="IDOS_PLATFORM_PUSH_RESPONSE",nR=12e4;function Ju(s){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(i=>{let n=false,r=h=>{n||(n=true,window.removeEventListener("message",o),clearTimeout(c),i(h));},o=h=>{let y=h?.data;!y||y.type!==iR||y.requestId!==t||wt.includes(h.origin)&&r(y.ok===true);},c=setTimeout(()=>r(false),nR);window.addEventListener("message",o);for(let h of wt)try{e.postMessage({type:tR,requestId:t,titleID:s},h);}catch{}})}var Wn=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 i=await this.ctx.api.push.getPushConfig(t),n=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=n,i.ok&&this.ctx.emitter.emit("push:configLoaded",n),n}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return Ot.Unsupported;if(this.isEmbedded())return Ot.Embedded;if(!this.isSupported())return Ot.Unsupported;let t=Notification.permission;return t==="denied"?Ot.Blocked:t!=="granted"?Ot.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?Ot.Subscribed:Ot.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return u("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Ju(this.ctx.settings.titleID)?N({Where:"portal",Subscription:null}):u("client","The portal did not complete the subscription.");if(!this.isSupported())return u("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return u("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let n=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await n.pushManager.getSubscription()??await n.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:rR(t.PublicKey)}),c=this.ctx.authedRequest();if(!c)return a;let h=o.toJSON();c.PushEndpoint=h.endpoint,c.PushP256dh=h.keys?.p256dh,c.PushAuth=h.keys?.auth,c.PushTransport="WebPush",c.PushLocale=e.locale??navigator.language,c.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let y=await this.ctx.api.push.subscribePush(c);return y.ok?(this.ctx.emitter.emit("push:subscribed",y.data),N({Where:"game",Subscription:y.data})):y}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return a;if(this.isSupported()){let n=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();n&&(e.PushEndpoint=n.endpoint,await n.unsubscribe());}if(!e.PushEndpoint)return u("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):a}async unsubscribeByHash(e){if(!e)return u("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return a;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function rR(s){let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),n=new Uint8Array(i);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return i}var Kn=Object.freeze({}),Qn=class{constructor(e){this.ctx=e;}ctx;table={...Kn};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new xi(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,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),n=this.lookup(i)??this.lookup(e);return n===void 0?this.onMissing(e):t?sR(n,t):n}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Kn},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return a;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:n,table:r,fallbackLocale:o}=i.data,c=null;if(o){let h=await this.loadTableFromApi(o);h.ok&&(c=h.data.table);}return this.table=r,this.fallbackTable=c,this.currentFallbackLocale=o,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:o,entryCount:Object.keys(r).length}),{ok:true,data:n}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):a}reset(){this.table={...Kn},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:G()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return a;t.Locale=e;let i=await this.cache.read(Zu(e));i&&(t.KnownVersion=i.v);let n=await this.ctx.api.localization.getLocalizationTable(t);if(!n.ok)return n;let r=n.data,o=r.Locale??Zu(e),c=r.Version??0;if(r.NotModified){let y=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:y?.t??{...Kn},fallbackLocale:r.FallbackLocale??null}}}let h=r.Entries??{};return c>0&&await this.cache.write(o,c,h),{ok:true,data:{locale:o,table:h,fallbackLocale:r.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let n=this.pluralCategory(i),r=`${e}.${n}`;if(this.lookup(r)!==void 0)return r;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 sR(s,e){return s.replace(/\{(\w+)\}/g,(t,i)=>{let n=e[i];return n===void 0?t:String(n)})}function Zu(s){return s.trim().replace(/_/g,"-").toLowerCase()}var Vo="Quest",oR={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:s=>{let e=Date.now(),t=null,i=[...Object.values(s.PointsTracks??{}).map(n=>n?.CycleEndUtc),...Object.values(s.State?.Cycles??{}).map(n=>n?.CycleEndUtc)];for(let n of i){let r=Date.parse(n??"");!Number.isNaN(r)&&r>e&&(t===null||r<t)&&(t=r);}return t}},Hn=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let n=e.cache.configSection(Vo)?.Cycles;if(!n)return false;let r=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(n)){let c=Date.parse(r[o]?.CycleEndUtc??"");if(Number.isNaN(c)){if(t===0)return true}else if(c<=i&&t<c)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true,{forceRefresh:true});return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(Vo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.quest.getQuestDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Vo,n.data),this.ctx.emitter.emit("quest:definitionsLoaded",n.data)),n}getUserQuestState(e=true,t){return this.ctx.cache.read(oR,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let n=i.data.State??{};this.ctx.data.user.applyQuest(n),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",n);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return a;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 i=e.trim();if(!i)return u("client","QuestID is required.");if(!this.ctx.auth.context)return a;let n=t&&t.trim().length>0?t.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:n,RelatedEntityID:`quest_claim_${n??""}_${i}_${G()}`},o=await this.ctx.api.quest.claimQuestReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchQuestStatus(c.QuestID,c.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",c);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return u("client","quests is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||(this.ctx.data.user.patchQuestStatus(r.Data.QuestID,r.Data.CycleID,"Claimed"),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return u("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:n,RelatedEntityID:`milestone_claim_${i}_${n}_${G()}`},o=await this.ctx.api.quest.claimMilestoneReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchMilestoneClaimed(c.CycleID,c.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",c);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!r.Success||!r.Data||(this.ctx.data.user.patchMilestoneClaimed(r.Data.CycleID,r.Data.MilestoneID),!n&&r.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return u("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:n,RelatedEntityID:`group_completion_${i}_${n}_${G()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(r);if(o.ok){let c=o.data;this.ctx.data.user.patchGroupCompletionClaimed(c.CycleID,c.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",c);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return u("client","MetricID is required.");if(t<0)return u("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},r=await this.ctx.api.quest.addQuestProgress(n);return r.ok&&(this.ctx.data.user.patchQuestProgressUpdates(r.data.Updates),this.ctx.emitter.emit("quest:progressAdded",r.data)),r}};var Yu=zod.z.object({}).passthrough().transform(s=>s);var aR=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),lR=zod.z.object({Schedule:zod.z.array(aR).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),uR=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:p.nullish(),NextBonusStartUtc:p.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),cR=zod.z.object({Milestones:Q.nullish()}).passthrough(),No=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:Zt.nullish(),TokenSources:zod.z.array(ot).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:cR.nullish(),BonusWindow:lR.nullish()}).passthrough(),pR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:No.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),dR=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:Re.nullish(),Content:No.nullish(),Events:zod.z.array(pR).nullish(),Gate:Z.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),hR=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),mR=zod.z.object({Milestones:zod.z.record(zod.z.string(),gi).nullish()}).passthrough(),$n=zod.z.object({Definitions:zod.z.record(zod.z.string(),dR).nullish(),Settings:hR.nullish(),Presets:mR.nullish()}).passthrough(),fR=zod.z.object({Type:Oi,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:No.nullish(),Progress:Yu.nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:_e.nullish(),BonusWindow:uR.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),Jn=zod.z.object({ActiveEvents:zod.z.array(fR).nullish()}).passthrough(),Xu=zod.z.object({Tokens:zod.z.record(zod.z.string(),Yu).nullish()}),jo=zod.z.object({Type:Oi.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),Wo=zod.z.object({Type:Oi.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}),gR=zod.z.object({Type:Oi.nullish(),LteID:zod.z.string().nullish(),Resources:O.nullish()}),Ko=zod.z.array(we(Wo)),ec=zod.z.array(we(jo)),tc=zod.z.array(we(gR)),ut={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var ic="TimedEvent",nc={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:s=>{let e=null;for(let t of s.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Zn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(nc,{schema:Jn,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(nc,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return a;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(ic,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.timedEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ic,n.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",n.data)),n}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return a;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,i,n,r,o,c=1){if(!t)return u("client","LteID is required.");if(!i)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:n,AmountOverride:r,SourceParams:o,RollMultiplier:c},y=await this.ctx.api.timedEvent.grantTokens(h);return y.ok&&(this.ctx.data.user.applyResourceOperation(y.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",y.data)),y}async spendTokens(e,t,i){if(!t)return u("client","LteID is required.");if(i<=0)return u("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},r=await this.ctx.api.timedEvent.spendTokens(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",r.data)),r}async claimMilestone(e,t,i){if(!t||!i)return u("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},r=await this.ctx.api.timedEvent.claimMilestone(n);if(r.ok){let o=r.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return r}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return a;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return u("client","spends is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(r.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return u("client","grants is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(r.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let n=i.Data;n.Type&&n.LteID&&n.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(n.Type,n.LteID,n.MilestoneID,n.TokenEntityID),!t&&n.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(n.Rewards,n.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var yR=zod.z.object({UserID:zod.z.string(),Score:W.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:p.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:qe.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),Li=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:W.nullish(),CycleEndUtc:p.nullish(),TopUsers:zod.z.array(yR).nullish(),BracketID:zod.z.string().nullish()}),RR=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:p.nullish(),ClaimDeadlineUtc:p.nullish(),MilestoneTokensEarned:W.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Yn=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:W.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:W.nullish(),MilestoneTokensEarned:W.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:_e.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(RR).nullish()}),Xn=zod.z.object({LeaderboardID:zod.z.string(),NewScore:W,CycleVersion:zod.z.number()}),er=zod.z.object({ServerTimeUtc:p,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),tr=zod.z.object({ServerTimeUtc:p,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish()}),rc=zod.z.array(we(Li)),ir=zod.z.array(we(Yn)),sc=zod.z.array(we(er)),oc=zod.z.array(we(tr)),ac=zod.z.array(we(Xn)),CR=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:we(er).nullish(),Milestones:zod.z.array(we(tr)).nullish()}),lc=zod.z.array(CR),SR=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:we(Li).nullish(),Progress:we(Yn).nullish()}),uc=zod.z.array(SR),xR=zod.z.string(),cc=zod.z.object({Rank:zod.z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:mo.nullish()}).passthrough(),bR=zod.z.object({RankRewards:zod.z.array(cc).nullish()}).passthrough(),DR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),PR=zod.z.object({Milestones:Q.nullish(),RankRewards:Q.nullish()}).passthrough(),IR=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:xR.nullish(),Schedule:Re.nullish(),ChainEvents:zod.z.array(DR).nullish(),Gate:Z.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(cc).nullish(),Milestones:zod.z.record(zod.z.string(),_e).nullish(),Presets:PR.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(ot).nullish()}).passthrough(),vR=zod.z.object({Milestones:zod.z.record(zod.z.string(),gi).nullish(),RankRewards:zod.z.record(zod.z.string(),bR).nullish()}).passthrough(),nr=zod.z.object({Definitions:zod.z.record(zod.z.string(),IR).nullish(),Presets:vR.nullish()}).passthrough(),je={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 pc="Leaderboard",dc={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"]},rr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(dc,{schema:ir,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(pc,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.leaderboard.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(pc,n.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",n.data)),n}async getLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return u("client","LeaderboardID is required.");if(t<=0)return u("client","Score must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},n=await this.ctx.api.leaderboard.submitScore(i);if(n.ok){let r=n.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),r.NewScore,t,r.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",r);}return n}async submitScoreFromSource(e,t,i,n,r=1){if(!e)return u("client","LeaderboardID is required.");if(!t)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:n,RollMultiplier:r},c=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(c.ok){let h=c.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),h.NewScore,h.NewScore,h.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",h);}return c}async claimCycleReward(e){if(!e)return u("client","LeaderboardID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",n);}return i}async claimMilestone(e,t,i){if(!e||!t)return u("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},r=await this.ctx.api.leaderboard.claimMilestone(n);if(r.ok){let o=r.data;i||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 r}async getFriendsLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(u("client","leaderboardIDs is required.")):this.ctx.cache.read(dc,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}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 u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(n.Data.LeaderboardID)),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(n.Data.LeaderboardID),n.Data.MilestoneID),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return u("client","scores is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(n.Data.LeaderboardID),n.Data.NewScore,n.Data.NewScore,n.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let n of i.data){let r=this.cycleDocID(n.LeaderboardID);n.CycleReward?.Success&&n.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(r),n.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.CycleReward.Data.Resources,n.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of n.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(r,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",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let n of i.data)n.Progress?.Success&&n.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(n.LeaderboardID),n.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var Qo=zod.z.object({}).passthrough().transform(s=>s),sr=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>gc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:W.nullish(),UserState:Qo.nullish(),NextTier:zod.z.lazy(()=>fc).nullish()}).passthrough(),hc=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:W.nullish(),NewStatusTokens:W.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),Ho=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:O.nullish(),Inventory:K.nullish()}),mc=St(Ho);var fc=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:W.nullish(),TierReachedReward:H.nullish()}).passthrough(),gc=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:W.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(fc).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var TR=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Seasons:zod.z.array(gc).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:Z.nullish()}).passthrough(),or=zod.z.object({Chains:zod.z.record(zod.z.string(),TR).nullish()}).passthrough(),_t={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var yc="Season",Rc={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:s=>{let e=Date.parse(s.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},ar=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Rc,{schema:sr,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(yc,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.season.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(yc,n.data),this.ctx.emitter.emit("season:definitionsLoaded",n.data)),n}getActiveSeason(e,t){return e?this.ctx.cache.read(Rc,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(u("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}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 u("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","Amount must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${G()}`},n=await this.ctx.api.season.grantStatusTokens(i);return n.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,n.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",n.data)),n}async claimTierReward(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","TierNumber must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${G()}`},n=await this.ctx.api.season.claimTierReward(i);if(n.ok){let r=n.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",r);}return n}async claimTierRewardsBatch(e,t){if(!e)return u("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return u("client","TierNumbers is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${G()}`},r=await this.ctx.api.season.claimTierRewardsBatch(n);if(r.ok){let o=r.data;for(let c of o.Items??[]){let h=c.Data?.TierNumber;c.Success&&typeof h=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,h);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return r}};var Cc="Premium",lr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Cc,e);if(t){let r={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",r),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.premium.getDefinitions(i);return n.ok&&n.data.Premium&&(this.ctx.data.config.patchSection(Cc,n.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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 u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},n=await this.ctx.api.premium.activateTrial(i);return n.ok&&(n.data.Premium&&this.ctx.data.user.applyPremium(n.data.Premium),this.ctx.emitter.emit("premium:trialActivated",n.data)),n}async purchaseItemOrCurrency(e,t,i="Default",n=1,r){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:n,CreditsConfirmationID:r,RelatedEntityID:`premium_purchase_${e}_${t}`},c=await this.ctx.api.premium.purchaseItemOrCurrency(o);if(c.ok&&!c.data.CreditsConfirmation){let h=c.data;h.Premium&&this.ctx.data.user.applyPremium(h.Premium),this.ctx.data.user.applyResourceOperation(h.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",h);}return c}async purchaseRealMoney(e,t,i,n,r,o,c,h){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!n||!r)return u("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return a;let y={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:n,ReceiptData:r,PurchaseToken:o,PackageName:c,AppStoreEnvironment:h,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(y);if(V.ok){let oe=V.data;oe.Premium&&this.ctx.data.user.applyPremium(oe.Premium),this.ctx.data.user.applyResourceOperation(oe.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",oe);}return V}};var ur=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:p.nullish()}),$o=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:W.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),ur).nullish(),UpdatedAt:p.nullish()}).passthrough(),Sc=zod.z.object({Characters:zod.z.record(zod.z.string(),$o).nullish()}),Jo=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Zo=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:O.nullish()}),xc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),ur).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),bc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),AR=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Dc=zod.z.object({ServerTimeUtc:p,Characters:zod.z.record(zod.z.string(),AR).nullish(),Inventory:K.nullish()}),Yo=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:O.nullish()}),Pc=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,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:ur.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Ic=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:ur.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),vc=zod.z.object({ServerTimeUtc:p,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),wR=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:p.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:ae.nullish()}),kR=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(wR).nullish()}),Tc=zod.z.object({ServerTimeUtc:p,Characters:zod.z.record(zod.z.string(),kR).nullish()}),Ac=St(Yo),wc=St(Zo),kc=St(Jo),Xo=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),zc=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:ae.nullish(),CostCurve:Ne.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Ne.nullish(),RankCurve:Ne.nullish(),Requirements:zod.z.array(Xo).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),zR=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Xo).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(),Mc=zod.z.object({Slots:zod.z.record(zod.z.string(),zR).nullish()}).passthrough(),Oc=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(),MR=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),OR=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:ae.nullish()}).passthrough(),ER=zod.z.object({Stats:Q.nullish(),Levels:Q.nullish(),Equipment:Q.nullish()}).passthrough(),Ec=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:ae.nullish(),CostCurve:Ne.nullish()}).passthrough(),ea="@skin";function UR(s){return !!s&&s.startsWith("@")}var qR=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),LR=zod.z.object({PriceOptions:ae.nullish(),Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),BR=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Xo).nullish()}).passthrough(),GR=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Oc.nullish(),Item:qR.nullish(),Sale:LR.nullish(),Requirements:BR.nullish()}).passthrough(),FR=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),GR).nullish()}).passthrough(),_R=zod.z.object({CharacterID:zod.z.string(),Identity:Oc.nullish(),Classification:MR.nullish(),Unlock:OR.nullish(),Presets:ER.nullish(),Equipment:Mc.nullish(),Stats:zod.z.record(zod.z.string(),zc).nullish(),RankLadder:Ec.nullish(),RankStatCurve:Ne.nullish(),StatMaxLevelCurve:Ne.nullish(),Skins:FR.nullish()}).passthrough(),VR=zod.z.object({Stats:zod.z.record(zod.z.string(),zc).nullish()}).passthrough(),NR=zod.z.object({RankLadder:Ec.nullish()}).passthrough(),jR=zod.z.object({Equipment:Mc.nullish()}).passthrough(),WR=zod.z.object({Stats:zod.z.record(zod.z.string(),VR).nullish(),Levels:zod.z.record(zod.z.string(),NR).nullish(),Equipment:zod.z.record(zod.z.string(),jR).nullish()}).passthrough(),cr=zod.z.object({Definitions:zod.z.record(zod.z.string(),_R).nullish(),Presets:WR.nullish()}).passthrough(),We={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"},KR="SKIN_ALREADY_OWNED";var ta="Character",pr=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(ta)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([n,r])=>r?.Unlock?.UnlockedByDefault===true&&!i[r.CharacterID??n])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(ta,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.character.getCharacterDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ta,n.data),this.ctx.emitter.emit("character:definitionsLoaded",n.data)),n}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${G()}`},n=await this.ctx.api.character.unlockCharacter(i);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},r.Power!=null&&(o.Power=r.Power),o.UpdatedAt=r.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",r);}return n}async upgradeStatLevel(e,t,i){if(!e||!t)return u("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${G()}`,SelectedOptionID:i?.selectedOptionID,CreditsConfirmationID:i?.creditsConfirmationID,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},r=await this.ctx.api.character.upgradeStatLevel(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;this.ctx.data.user.patchCharacter(o.CharacterID,c=>{c.StatLevels??={},c.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(c.Power=o.Power),c.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return r}async upgradeCharacterLevel(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${G()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},n=await this.ctx.api.character.upgradeCharacterLevel(i);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,o=>{o.Level=r.NewLevel,r.Power!=null&&(o.Power=r.Power),o.UpdatedAt=r.ServerTimeUtc,r.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",r);}return n}async equipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},n=await this.ctx.api.character.equipItems(i);return n.ok&&(this.applyEquipChangesLocally(e,n.data),this.ctx.emitter.emit("character:itemsEquipped",n.data)),n}async unequipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},n=await this.ctx.api.character.unequipItems(i);if(n.ok){let r=n.data;this.applyUnequipChangesLocally(e,r),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:r.ClearedSlotIDs??[],power:r.Power??null});}return n}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return a;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,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,CreditsConfirmationID:i?.creditsConfirmationID,RelatedEntityID:`unlock_skin_${e}_${t}_${G()}`},r=await this.ctx.api.character.unlockSkin(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.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 r}async equipSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},r=await this.ctx.api.character.equipSkin(n);if(r.ok){let o=r.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return r}async unequipSkin(e){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let n=i.data;n.Cleared&&(this.applyInventoryDelta(n.Inventory),this.applySkinLocally(n.CharacterID,null,n.Power,n.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",n);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):a}applySkinLocally(e,t,i,n){let r=this.ctx.data.user;r.patchCharacterEquipment(e,ea,t??null),r.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=n;});}async unlockCharactersBatch(e){if(!e||e.length===0)return u("client","characterIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level??=1,r.StatLevels??={},r.Equipment??={},n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level=n.NewLevel,n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(r.StatLevels??={},r.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.StatLevels??={},r.StatLevels[n.StatID]=n.StatLevel,n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[n,r]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,n,r);i.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let r of i)n.patchCharacterEquipment(e,r,null);n.patchCharacter(e,r=>{t.Power!=null&&(r.Power=t.Power),r.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,n]of Object.entries(e.Characters??{})){for(let r of n.ClearedSlotIDs??[])t.patchCharacterEquipment(i,r,null);t.patchCharacter(i,r=>{n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=e.ServerTimeUtc;});}}};var Uc="Match",dr=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,n,r,o){let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:n,TargetUserID:r,SelectedOptionID:o,RelatedEntityID:`pvp_create_${c.userID}_${G()}`},y=await this.ctx.api.match.createMatch(h);return y.ok&&(this.ctx.data.user.applyResourceOperation(y.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",y.data)),y}async updateMatch(e,t={}){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},n=await this.ctx.api.match.updateMatch(i);return n.ok&&this.ctx.emitter.emit("match:updated",n.data),n}async cancelMatch(e){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,n){let r=this.ctx.auth.context;if(!r)return a;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:n,RelatedEntityID:`pvp_battle_${e}_${G()}`},c=await this.ctx.api.match.instantBattle(o);if(c.ok){let h=c.data,y=this.ctx.data.config.itemDefinitions;if(h.Resources)this.ctx.data.user.applyResourceOperation(h.Resources,y);else if(h.ResourcesDual){let V=h.ResourcesDual;V.FromUserID===r.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,y):V.ToUserID===r.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,y);}this.ctx.emitter.emit("match:instantBattleCompleted",h);}return c}async saveStrategy(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let n=this.ctx.authedRequest();if(!n)return a;n.Page=e,n.PageSize=t,n.Statuses=i;let r=await this.ctx.api.match.getMyMatches(n);return r.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",r.data),r}async getAvailableMatches(e=0,t=20,i=false){let n=this.ctx.authedRequest();if(!n)return a;n.Page=e,n.PageSize=t,n.OnlyPublic=i;let r=await this.ctx.api.match.getAvailableMatches(n);return r.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",r.data),r}async getDefinitions(e){let t=this.ctx.cache.configSection(Uc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.match.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Uc,n.data),this.ctx.emitter.emit("match:definitionsLoaded",n.data)),n}};var qc="Craft",hr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(qc,e);if(t){let r={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.craft.getDefinitions(i);return n.ok&&n.data.CraftDefinitions&&(this.ctx.data.config.patchSection(qc,n.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",n.data.CraftDefinitions)),n}async craft(e,t,i=1,n,r,o){if(!e)return u("client","CraftID is required.");let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:n,InputInstanceIDs:r,CreditsConfirmationID:o,RelatedEntityID:`craft_${e}_${c.userID}_${G()}`},y=await this.ctx.api.craft.craft(h);return y.ok&&!y.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(y.data.Resources,y.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",y.data)),y}};var Vt=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(Vt),zod.z.record(zod.z.string(),Vt)]));var Nt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Lc=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),ei={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Bi(s){return s!==ei.Pending&&s!==ei.Running}var QR={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 HR(s){return s?/\b(AI_[A-Z_]+)\s*:/.exec(s)?.[1]??null:null}var $R=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),JR=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),mr=zod.z.object({CreditsConfirmation:fe.nullish(),GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Lc.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),Vt).nullish(),Assets:zod.z.array($R).nullish(),Error:JR.nullish(),Charge:O.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:O.nullish(),Context:zod.z.record(zod.z.string(),Vt).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish()}),Bc=zod.z.object({Data:zod.z.array(mr).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),ZR=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(),gt=zod.z.record(zod.z.string(),zod.z.string()),YR=zod.z.object({Key:zod.z.string().nullish(),Role:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),Label:gt.nullish()}).passthrough(),XR=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:gt.nullish(),Placeholder:gt.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string().nullish(),Label:gt.nullish()}).passthrough()).nullish()}).passthrough(),eC=zod.z.object({Key:zod.z.string(),Kind:zod.z.string().nullish(),Name:gt.nullish(),Hint:gt.nullish(),Unit:gt.nullish(),Choices:zod.z.array(zod.z.object({Value:zod.z.string(),Name:gt.nullish(),Group:zod.z.string().nullish()}).passthrough()).nullish(),Groups:zod.z.array(zod.z.object({Key:zod.z.string(),Name:gt.nullish()}).passthrough()).nullish(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),Step:zod.z.number().nullish()}).passthrough(),Gc=zod.z.object({PriceOptions:ae.nullish()}).passthrough(),tC=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:gt.nullish(),Description:gt.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(YR).nullish(),Variables:zod.z.array(XR).nullish(),Settings:zod.z.array(eC).nullish()}).passthrough(),iC=zod.z.object({Modality:Lc.nullish(),Async:zod.z.boolean().nullish(),Limits:Se.nullish(),PriceOptions:ae.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:H.nullish(),PromptVariables:zod.z.array(ZR).nullish(),AllowFreePrompt:zod.z.boolean().nullish(),PlatformTemplateId:zod.z.string().nullish(),PlatformTemplate:tC.nullish(),FreePerDay:zod.z.number().nullish(),FreeLeftToday:zod.z.number().nullish()}).passthrough(),Fc=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),iC).nullish()}).passthrough(),Le={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 _c="AI",nC=/^[A-Za-z0-9_-]{1,128}$/,rC=2e3,sC=5e3,oC=30*6e4;function aC(s,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(n),e?.removeEventListener("abort",i),t();},n=setTimeout(i,s);e?.addEventListener("abort",i,{once:true});})}var fr=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(_c,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.ai.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(_c,n.data),this.ctx.emitter.emit("ai:definitionsLoaded",n.data)),n}generateText(e,t,i){return this.generate(e,{Text:t},i,n=>this.ctx.api.ai.generateText(n))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,n=>this.ctx.api.ai.generateImage(n))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,n=>this.ctx.api.ai.editImage(n))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,n=>this.ctx.api.ai.generateVideo(n))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,n=>this.ctx.api.ai.generateAudio(n))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,n=>this.ctx.api.ai.generateMusic(n))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,i){return this.generate(e,{TemplateInputs:t},i,n=>this.ctx.api.ai.generateFromTemplate(n))}async estimateTemplatePrice(e,t,i){return e?this.ctx.auth.context?this.ctx.api.ai.estimateTemplatePrice({...this.ctx.buildAuthedBaseRequest(),FeatureKey:e,Params:t,Variables:i}):a:u("client","FeatureKey is required.")}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,n=>this.ctx.api.ai.generateThreeD(n))}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)):a}async getGeneration(e){if(!e)return u("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):a}isTerminal(e){return Bi(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let c=await this.getGeneration(e);if(!c.ok)return c;i=c.data;}else {if(!e?.GenerationID)return u("client","GenerationID is required.");i=e;}let n=Date.now()+(t.timeoutMs??oC),r=Math.max(1,t.intervalMs??rC),o=Math.max(r,t.maxIntervalMs??sC);for(;!Bi(i.Status);){if(t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");if(Date.now()+r>n)return u("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await aC(r,t.signal),t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");let c=await this.pollFor(i);if(r=Math.min(o,Math.round(r*1.5)),!c.ok){if(c.reason==="connection")continue;return c}i=c.data,Bi(i.Status)||t.onUpdate?.(i);}return N(i)}pollFor(e){switch(e.Modality){case Nt.Text:return this.getText(e.GenerationID);case Nt.Image:return this.getImage(e.GenerationID);case Nt.Audio:return this.getAudio(e.GenerationID);case Nt.Music:return this.getMusic(e.GenerationID);case Nt.Video:return this.getVideo(e.GenerationID);case Nt.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,n){if(!e)return u("client","FeatureKey is required.");let r=i?.relatedEntityID;if(r!==void 0&&!nC.test(r))return u("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,CreditsConfirmationID:i?.creditsConfirmationID,Variables:i?.variables,Params:i?.params,Context:i?.context,RelatedEntityID:r??G()},c=await n(o);return c.ok&&!c.data.CreditsConfirmation&&(await this.reconcileCharge(c.data,true),this.emitView(c.data)),c}async poll(e,t){if(!e)return u("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.GenerationID=e;let n=await t(i);return n.ok&&(await this.reconcileCharge(n.data,false),this.emitView(n.data)),n}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===ei.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===ei.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===ei.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var ia="Collection",gr=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let i=e.cache.configSection(ia),n=Object.keys(i?.Collections??{});if(n.length===0||t)return false;let r=e.cache.configSection("Season");return Object.values(r?.Chains??{}).some(c=>(c?.Seasons??[]).some(h=>!!h?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==n[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ia,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.collection.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(ia,n.data),this.ctx.emitter.emit("collection:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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,i=1,n){let r=this.ctx.auth.context;if(!r)return a;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${r.userID}_${G()}`},c=await this.ctx.api.collection.openPack(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",c.data)),c}async openCollectionChest(e,t,i=1){let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${n.userID}_${G()}`},o=await this.ctx.api.collection.openCollectionChest(r);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 i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${G()}`},r=await this.ctx.api.collection.useCollectibleJoker(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",r.data)),r}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${G()}`},r=await this.ctx.api.collection.claimSetReward(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",r.data)),r}async claimSetRewardsBatch(e){if(!e||e.length===0)return u("client","sets is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let n=false;for(let r of i.data)!n&&r.Success&&r.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${G()}`},n=await this.ctx.api.collection.claimGrandPrize(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",n.data)),n}async sendTradeOffer(e,t,i,n,r,o=false){let c=this.ctx.auth.context;if(!c)return a;let h={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:n,RequestedCollectibleID:r,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${c.userID}_${n}_${G()}`},y=await this.ctx.api.collection.sendTradeOffer(h);return y.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",y.data)),y}async cancelTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${G()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${G()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${G()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var lC=zod.z.object({}).passthrough().transform(s=>s),uC={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},cC={Active:"Active",Left:"Left",Replaced:"Replaced"},pC=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),dC=zod.z.object({UserID:zod.z.string().nullish(),PublicData:qe.nullish(),BuildObjectsProgress:pC.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:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),hC=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(),mC=zod.z.object({Objects:zod.z.array(hC).nullish()}).passthrough(),Vc=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(dC).nullish(),BuildObjectsState:mC.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:zod.z.number().nullish()}).passthrough(),Nc=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>jc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),fC=zod.z.string(),na=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(),gC=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:H.nullish()}).passthrough(),yC=zod.z.object({Objects:zod.z.array(gC).nullish(),PriceOptions:ae.nullish(),SpinnerTable:zod.z.array(na).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),jc=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:fC.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:yC.nullish(),GrandPrize:H.nullish()}).passthrough(),RC=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:Re.nullish(),Events:zod.z.array(jc).nullish(),Gate:Z.nullish()}).passthrough(),yr=zod.z.object({ServerTimeUtc:p.nullish(),UserState:lC.nullish(),ActiveGroup:Vc.nullish()}),ra=zod.z.object({ServerTimeUtc:p.nullish(),Group:Vc.nullish(),SecondsRemaining:W.nullish()}),Wc=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Resources:O.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:na.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(na).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),sa=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Kc=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Rr=zod.z.object({Chains:zod.z.record(zod.z.string(),RC).nullish()}).passthrough(),yt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Qc="CoopEvent",Hc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},Cr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Hc,{schema:yr,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Qc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.coopEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Qc,n.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",n.data)),n}async getActiveEvent(e){if(!e)return u("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(Hc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return a;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 u("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return u("client","CoopChainID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let n=i.data.Group;n&&this.ctx.data.user.patchCoopEventActiveGroup(n.GroupID??null,n.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,n,r){if(!e||!t)return u("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:n,CreditsConfirmationID:r,RelatedEntityID:G()},c=await this.ctx.api.coopEvent.spin(o);return c.ok&&!c.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(c.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",c.data)),c}async claimObjectReward(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var CC={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},SC={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},xC=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:p.nullish(),CompletedAtUtc:p.nullish(),LastExecutedAtUtc:p.nullish(),NextAvailableAtUtc:p.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),bC=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),$c=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:p.nullish(),ExhaustedAtUtc:p.nullish(),ExpiredAtUtc:p.nullish(),DismissedAtUtc:p.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:p.nullish(),Nodes:zod.z.record(zod.z.string(),xC).nullish(),Tracks:zod.z.record(zod.z.string(),bC).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),DC=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:p.nullish(),ActiveOfferExpiresAtUtc:p.nullish(),ActiveOffer:$c.nullish(),NextCycleStartsAtUtc:p.nullish(),LastUpdatedUtc:p.nullish(),DismissSkipAvailableAtUtc:p.nullish(),LastDismissedAtUtc:p.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),PC=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),IC=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:p.nullish(),LastActivatedAtUtc:p.nullish(),LastExhaustedAtUtc:p.nullish(),NodeCounts:zod.z.record(zod.z.string(),PC).nullish()}).passthrough(),vC=zod.z.object({Slots:zod.z.record(zod.z.string(),DC).nullish(),OfferHistory:zod.z.record(zod.z.string(),IC).nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),TC={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},AC={Eq:"Eq",Gte:"Gte",Lte:"Lte"},wC=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),Sr=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(),Jc=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),Zc=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),kC=zod.z.object({Identity:Q.nullish(),Availability:Q.nullish(),Behaviour:Q.nullish()}).passthrough(),zC=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:Sr.nullish(),Availability:Jc.nullish(),Behaviour:Zc.nullish(),Queue:zod.z.array(wC).nullish(),Presets:kC.nullish()}).passthrough(),MC=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),OC=zod.z.object({RewardedVideo:MC.nullish()}).passthrough(),EC=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),UC=zod.z.object({Identity:Q.nullish(),Graph:Q.nullish(),Milestones:Q.nullish()}).passthrough(),qC=zod.z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish()}).passthrough(),LC=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),BC=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(),GC=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(EC).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),Yc=zod.z.object({Options:ae.nullish()}).passthrough(),Xc=zod.z.object({Grants:H.nullish(),TrackChanges:zod.z.array(LC).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),FC=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:Sr.nullish(),Pricing:Yc.nullish(),Reward:Xc.nullish(),Action:OC.nullish(),UnlockRules:GC.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:Se.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:qC.nullish()}).passthrough(),ep=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(FC).nullish(),Tracks:zod.z.array(BC).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),tp=zod.z.object({Milestones:zod.z.record(zod.z.string(),_e).nullish(),ClaimMode:zod.z.string().nullish(),Token:Zt.nullish()}).passthrough(),ip=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:Sr.nullish(),Graph:ep.nullish(),Milestones:tp.nullish(),Presets:UC.nullish()}).passthrough(),_C=zod.z.object({Identity:zod.z.record(zod.z.string(),Sr).nullish(),Availability:zod.z.record(zod.z.string(),Jc).nullish(),Behaviour:zod.z.record(zod.z.string(),Zc).nullish(),Graph:zod.z.record(zod.z.string(),ep).nullish(),Milestones:zod.z.record(zod.z.string(),tp).nullish(),Pricing:zod.z.record(zod.z.string(),Yc).nullish(),Reward:zod.z.record(zod.z.string(),Xc).nullish()}).passthrough(),oa=zod.z.object({Slots:zod.z.record(zod.z.string(),zC).nullish(),Offers:zod.z.record(zod.z.string(),ip).nullish(),Presets:_C.nullish()}).passthrough(),np=zod.z.object({DealOfferDefinitions:oa.nullish()}),rp=zod.z.object({DealOffers:vC.nullish()}),VC=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(),NC=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:ip.nullish(),ActivationState:$c.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:p.nullish(),Cost:Tt.nullish(),Milestone:VC.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),xr=zod.z.object({Slots:zod.z.array(NC).nullish()}),sp=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.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()}),op=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),ap=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),Resources:O.nullish()}),lp=zod.z.object({ServerTimeUtc:p.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),up=zod.z.object({ServerTimeUtc:p.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()}),bt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var jC="DealOffer",cp={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},br=class{constructor(e){this.ctx=e;e.cache.bindLoginView(cp,{schema:xr,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(jC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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(cp,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return a;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 u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${G()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,n){if(!e||!t)return u("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return a;let r=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,CreditsConfirmationID:n?.creditsConfirmationID,RelatedEntityID:r??`deal_exec_${e}_${t}_${G()}`},c=await this.ctx.api.dealOffer.executeNode(o);return c.ok&&!c.data.CreditsConfirmation&&(c.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",c.data)),c}async recordShow(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${G()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return u("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${G()}`},n=await this.ctx.api.dealOffer.claimMilestone(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",n.data)),n}async claimMilestonesBatch(e,t){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${G()}`},r=await this.ctx.api.dealOffer.claimMilestonesBatch(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",r.data)),r}};var pp="Referral",Dr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(pp,e);if(t){let r={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",r),N(r)}let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.referral.getDefinitions(i);return n.ok&&n.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(pp,n.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",n.data)),n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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=Jt.parseReferralCode(e)?.toUpperCase();if(!t)return u("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},r=await this.ctx.api.referral.activateReferralCode(n);if(r.ok){let o=r.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 r}async claimInviteReward(e){let t=e.trim();if(!t)return u("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},r=await this.ctx.api.referral.claimInviteReward(n);if(r.ok){let o=r.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 r}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return u("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},r=await this.ctx.api.referral.claimInviteRewardsBatch(n);if(r.ok){let o=r.data;for(let c of o.Items??[])c.Success&&c.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(c.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return r}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return a;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 WC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},dp=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),KC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},QC=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),HC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},$C=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),nt={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},JC={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"},ZC=100,YC=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),hp=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(),XC=zod.z.object({Texts:zod.z.record(zod.z.string(),YC).nullish(),Category:dp.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:hp.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),eS=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:pe.nullish(),Cost:pe.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:p.nullish(),SenderGate:Z.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),tS=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(),iS=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(tS).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:p.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:pe.nullish(),SenderGate:Z.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),mp=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(),XC).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),eS).nullish(),Transfer:iS.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(),nS=zod.z.object({MessageID:zod.z.string(),Source:QC,Category:dp,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:hp.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:H.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:p,ExpiresAt:p.nullish(),ReadAt:p.nullish(),ClaimedAt:p.nullish()}).passthrough(),rS=zod.z.object({MessageID:zod.z.string(),Module:$C,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:H.nullish()}).passthrough(),aa=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),fp=zod.z.object({ServerTimeUtc:p.nullish(),Messages:zod.z.array(nS).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(rS).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),Pr=zod.z.object({ServerTimeUtc:p.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),la=zod.z.object({ServerTimeUtc:p.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(aa).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),sS=zod.z.object({MessageID:zod.z.string(),Rewards:pe.nullish()}).passthrough(),Ir=zod.z.object({ServerTimeUtc:p.nullish(),Claimed:zod.z.array(sS).default([]),Failed:zod.z.array(aa).default([]),Resources:O.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),gp=zod.z.object({ServerTimeUtc:p.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(aa).default([]),Resources:O.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish()}).passthrough(),yp=zod.z.object({ServerTimeUtc:p.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish(),RecipientReceives:pe.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:p.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),Rp=zod.z.object({ServerTimeUtc:p.nullish(),ResetsAt:p.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:p.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:p.nullish()}).passthrough().nullish()}).passthrough();var ua="Mailbox",ca={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},vr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ca,{schema:Pr,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(ca,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(ua)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(ua,e);if(t)return N(t);let i=this.request();if(!i)return a;let n=await this.ctx.api.mailbox.getDefinitions(i);return n.ok&&this.ctx.data.config.patchSection(ua,n.data),n}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 a;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(ca,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return a;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 a;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return u("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):a}async claimRewards(e){let t=(e??[]).map(n=>n?.trim()).filter(Boolean);if(t.length===0)return u("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):a}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):a}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 i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return a;let n=await this.ctx.api.mailbox.deleteMessages(i);return n.ok&&this.emitCounters(n.data),n}async sendGift(e,t){if(!e?.trim())return u("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return u("client","Recipients are required.");let n=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!n)return a;let r=await this.ctx.api.mailbox.sendGift(n);return r.ok&&(r.data.Resources&&this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",r.data)),r}async sendTransfer(e,t,i){if(!e?.trim())return u("client","RecipientUserID is required.");if(!i?.requestID?.trim())return u("client","requestID is required.");let n=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!n)return a;let r=await this.ctx.api.mailbox.sendTransfer(n);return r.ok&&(r.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(r.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",r.data)),r}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):a}};var Tr={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},pa="idos-app",Cp=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()}),Sp=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 da={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},oS=5*6e4;function Ar(){return Xt()}async function ha(s){let e=await kt(da.request,da.response,{titleID:s.titleID,userID:s.userID,requestID:s.requestID,placementID:s.placementID,adUnitID:s.adUnitID??null},{answerTimeoutMs:oS});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var aS=new Set(["CANCELLED","DECLINED","CLOSED"]),lS=45e3,uS=s=>new Promise(e=>setTimeout(e,s)),wr=class{constructor(e){this.ctx=e;}ctx;get available(){return Ar()}async showRewarded(e){if(!Ar())return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let i=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!i.ok)return {status:"unavailable",reason:i.error};let n=i.data;if(!n.Allowed)return {status:"denied",reason:n.DenyReason??void 0,retryAfterSeconds:n.RetryAfterSeconds??void 0};if(n.ProviderID!==pa||!n.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let r=await ha({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:n.RequestID,placementID:e,adUnitID:n.AdUnitID});return r.ok?{...await this.awaitReward(n.RequestID,r.via),requestID:n.RequestID}:{status:aS.has(r.error??"")?"cancelled":"unavailable",reason:r.error}}async awaitReward(e,t){let i=Date.now()+lS;for(;;){let n=this.ctx.authedRequest();if(!n)return {status:"pending",via:t};let r=await this.ctx.api.advertising.completeView({...n,RequestID:e});if(r.ok&&r.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:r.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((r.ok?r.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>i)return {status:"pending",via:t,reason:r.ok?void 0:r.error};await uS(o);}}};var cS={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},pS={Title:"Title",Platform:"Platform"},xp=zod.z.object({UserID:zod.z.string(),PublicData:qe.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),Gi=zod.z.object({Friends:zod.z.array(xp).nullish()}),dS=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),Fi=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:xp.nullish(),Counters:dS.nullish()}),hS={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},mS={Like:"Like",Favorite:"Favorite"},fS={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},gS={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},yS={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},RS=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),CS=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(RS).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),OccurredAt:p.nullish(),OwnerImpact:O.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),bp=zod.z.object({Items:zod.z.array(CS).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:p.nullish()}).passthrough(),_i=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:p.nullish()}).passthrough(),SS=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(),jt=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:SS.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),Dp=zod.z.object({Items:zod.z.array(jt).nullish()}).passthrough(),ma={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},xS=zod.z.object({UserID:zod.z.string(),PublicData:qe.nullish(),Mutual:zod.z.boolean().nullish(),Since:p.nullish()}).passthrough(),kr=zod.z.object({Items:zod.z.array(xS).nullish(),...ma}).passthrough(),bS=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:p.nullish()}).passthrough(),Pp=zod.z.object({Items:zod.z.array(bS).nullish(),...ma}).passthrough(),zr=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:qe.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:p.nullish(),EditedAt:p.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Ip=zod.z.object({Items:zod.z.array(zr).nullish(),...ma,TotalCount:zod.z.number().nullish()}).passthrough(),vp=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),Tp=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),Ap=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(),DS="FRIENDS_FROM_PLATFORM",PS={Off:"Off",Default:"Default",Always:"Always"},IS={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},wp=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(),xe={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"};var fa={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Mr=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fa,{schema:_i,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return a;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 a;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 a;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 a;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return u("client","TargetUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return u("client","FriendUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return a;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(fa,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return a;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 a;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(fa,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 i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):a}async getEntityStates(e,t){if(!t?.length)return u("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):a}async addComment(e,t,i,n){let r=this.targetRequest(e,t);if("ok"in r)return r;if(!i?.trim())return u("client","Text is required.");r.Text=i,r.ParentCommentID=n;let o=await this.ctx.api.social.addComment(r);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return u("client","CommentID is required.");if(!t?.trim())return u("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return a;i.CommentID=e,i.Text=t;let n=await this.ctx.api.social.editComment(i);return n.ok&&this.ctx.emitter.emit("social:commentEdited",n.data),n}async deleteComment(e){if(!e)return u("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let n=this.targetRequest(e,t);return "ok"in n?n:(n.ParentCommentID=i.parentCommentID,this.applyPage(n,i.cursor,i.limit),this.ctx.api.social.getComments(n))}async report(e,t,i,n){let r=this.targetRequest(e,t);if("ok"in r)return r;if(!i)return u("client","ReportReason is required.");r.ReportReason=i,r.ReportComment=n;let o=await this.ctx.api.social.report(r);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,n){let r=this.targetRequest(t,i);if("ok"in r)return r;r.ReactionKind=n;let o=await this.ctx.api.social[e](r);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let n=this.ctx.authedRequest();return n?(this.applyPage(n,t,i),this.ctx.api.social[e](n)):a}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return u("client","EntityType is required.");if(!t)return u("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):a}};var kp="TimedBoost";function vS(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var Or=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(kp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),N(t);let i=this.ctx.authedRequest();if(!i)return a;let n=await this.ctx.api.timedBoost.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(kp,n.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",n.data)),n}async getActive(){let e=this.ctx.authedRequest();if(!e)return a;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 a;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 i=e.trim();if(!vS(i))return u("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${i}_${G()}`},r=await this.ctx.api.timedBoost.activate(n);if(r.ok&&!r.data.CreditsConfirmation){let o=r.data;if(o.ActivatedBoost){let c=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,c);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return r}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return a;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 Ut={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},TS={Client:"Client",Server:"Server",System:"System"},AS=zod.z.enum(["Client","Server","System"]).catch("Client"),wS=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:p.nullish(),Version:zod.z.number().nullish(),LastWriter:AS.nullish(),ExpiresAt:p.nullish()}).passthrough(),Er=zod.z.record(zod.z.string(),wS),zp=zod.z.object({Version:zod.z.number().nullish(),Private:Er.nullish(),Public:Er.nullish(),ReadOnly:Er.nullish()}),ga=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:Er.nullish()}),ya=zod.z.object({ServerTimeUtc:p.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:p.nullish()}),kS=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:p.nullish()}),Mp=zod.z.object({ServerTimeUtc:p.nullish(),Results:zod.z.array(kS).nullish()}),Op=zod.z.object({ServerTimeUtc:p.nullish(),DeletedCount:zod.z.number().nullish()}),Ep=zod.z.object({Results:zod.z.array(ga).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),zS={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},MS=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),OS=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:MS.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Ur=zod.z.object({Keys:zod.z.record(zod.z.string(),OS).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(),Rt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var ES="UserCustomData";function Up(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}var qr=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(ES,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return a;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 u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TargetUserID=t;let n=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return n.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",n.data),n}async setPrivateData(e,t){return this.setData(e,t,Ut.Private)}async setPublicData(e,t){return this.setData(e,t,Ut.Public)}async setData(e,t,i){let n=e.trim();if(!Up(n))return u("client",'KeyID is required and must not contain "." or "$".');if(t==null)return u("client","Value is required.");if(!this.ctx.auth.context)return a;let r={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Value:t},c=await(i===Ut.Private?this.ctx.api.userCustomData.setPrivateData(r):this.ctx.api.userCustomData.setPublicData(r));if(c.ok){let h=c.data;this.ctx.data.user.patchUserCustomDataKey(i,h.KeyID,t,h.Version??0,h.ExpiresAt),this.ctx.emitter.emit(i===Ut.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",h);}return c}async deleteKey(e,t){let i=e.trim();if(!Up(i))return u("client",'KeyID is required and must not contain "." or "$".');if(t!==Ut.Private&&t!==Ut.Public)return u("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},r=await this.ctx.api.userCustomData.deleteKey(n);return r.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),r}async batchSet(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let n of i.data.Results??[]){let r=n.Bucket??Ut.Private,o=e.find(c=>c.Bucket===r&&c.KeyID===n.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(r,n.KeyID,o.Value,n.Version??0,n.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let n of e)this.ctx.data.user.removeUserCustomDataKey(n.Bucket,n.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return u("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var US="TitleCustomDataDefinitions",qp=50;function qS(s){return s.length>0&&!s.includes(".")&&!s.includes("$")}function Ra(s){if(s.ExpiresAt==null)return false;let e=Date.parse(s.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function LS(s){let e={};for(let[t,i]of Object.entries(s))Ra(i)||(e[t]=i);return e}var Lr=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(US,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return a;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(r=>r.trim()).filter(r=>r.length>0);if(!t.length)return u("client","At least one KeyID is required.");if(t.some(r=>!qS(r)))return u("client",'KeyID must not contain "." or "$".');if(t.length>qp)return u("client",`At most ${qp} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return a;i.KeyIDs=t;let n=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return n.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",n.data),n}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Ra(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Ra(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=LS(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 Br=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return a;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 a;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 a;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 a;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var BS=15,GS="GameLoop",Lp="BoardDefinition",Gr=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 a;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(GS,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(Lp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),N(i);let n=this.ctx.authedRequest();if(!n)return a;let r=await this.ctx.api.gameLoop.getBoardDefinition(n,e);return r.ok&&(this.ctx.data.config.patchSection(Lp,r.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",r.data)),r}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return u("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return a;i.StageLevel=e;let n=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return n.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",n.data),n}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return u("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopRoll(i);if(n.ok){let r=n.data,o=pu(new Date,BS);this.ctx.data.user.patchBoardState(c=>{c.Position=r.NewPosition,c.CyclesCompleted=(c.CyclesCompleted??0)+(r.CyclesCompletedDelta??0),c.LastRollAtUtc=new Date().toISOString(),r.ActionRequired&&r.ActionData?c.Pending={Type:r.ActionRequired,TargetUserID:r.ActionData.TargetUserID,TargetPublicData:r.ActionData.PublicData,TargetBuildingStates:r.ActionData.TargetBuildingStates??void 0,TargetHasShield:r.ActionData.TargetHasShield??void 0,RollMultiplier:r.UsedMultiplier??1,ExpiresAtUtc:o}:r.SpecialModeOffer&&(c.Pending={Type:"SPECIAL",RollMultiplier:r.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:r.SpecialModeOffer.ModeID??void 0,Choices:r.SpecialModeOffer.Choices??void 0}});}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),r.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",r);}return n}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopAttack(i);if(n.ok){let r=n.data;this.ctx.data.user.clearBoardPending(),r.IsBotTarget&&r.Operation?this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs):!r.IsBotTarget&&r.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(r.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",r);}else await this.getUserBoardState();return n}async boardLoopRaid(e,t){if(e<0||e>11)return u("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return a;let n={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${G()}`},r=await this.ctx.api.gameLoop.boardLoopRaid(n);if(r.ok){let o=r.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 r}async boardLoopRaidFast(e){if(!e.length)return u("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(n.ok){let r=n.data;r.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(r)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",r);}else await this.getUserBoardState();return n}async boardLoopBuild(e){if(e<0)return u("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopBuild(i);if(n.ok){let r=n.data;r.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(r.BuiltIndex,o=>{r.NewLevel!=null&&(o.Level=r.NewLevel),o.IsDamaged=false,r.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",r);}return n}async boardSpecialChoose(e,t,i){if(!e)return u("client","choiceID must not be empty.");let n=this.ctx.auth.context;if(!n)return a;let r={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:i,RelatedEntityID:`special_choose_${n.userID}_${G()}`},o=await this.ctx.api.gameLoop.boardSpecialChoose(r);if(o.ok&&!o.data.CreditsConfirmation){let c=o.data;c.Mode==="Instant"||c.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(y=>{y.ChoiceID=e,y.ChosenMode=c.Mode??"Timed",y.StartedAtUtc=c.StartedAtUtc??null,y.DurationSeconds=c.DurationSeconds??null,y.AdViewsUsed=0;}),c.Operation&&this.ctx.data.user.applyResourcesWithDelta(c.Operation,c.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",c);}return o}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(n.ok){let r=n.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=r.AdViewsUsed??0,o.AccumulatedMultiplier=r.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",r);}return n}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${G()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},n=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(n.ok){let r=n.data;this.ctx.data.user.clearBoardPending(),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",r);}return n}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return a;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 a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return u("client","milestoneID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},n=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",n.data)),n}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}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 Fr=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,n){let r=e.trim();if(!r)return u("client","FunctionName is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:r,FunctionParameter:t,RevisionSelection:i,SpecificRevision:n},c=await this.ctx.api.cloudCode.execute(o);return c.ok&&this.ctx.emitter.emit("cloudCode:executed",c.data),c}};var Bp=zod.z.object({ServerTimeUtc:p,SourceType:mi,SourceID:zod.z.string(),TargetType:mi,TargetID:zod.z.string(),SourceSpent:W,FeeAmount:W,RateApplied:Y,TargetCredited:W}),Gp=zod.z.object({ServerTimeUtc:p,SourceType:mi,SourceID:zod.z.string(),TargetType:mi,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),Fp=zod.z.object({ServerTimeUtc:p,SpendID:zod.z.string(),Resources:O.nullish()}),Vi={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},FS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},_p=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),_S={Automatic:"Automatic",Manual:"Manual"},VS=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),NS=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.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(),jS=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),WS=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),KS=zod.z.object({TargetCurrencyType:mi.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),Vp=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:VS.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(KS).nullish()}).passthrough(),Np=zod.z.object({CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough(),QS=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:NS.nullish(),Recharge:jS.nullish(),Conversion:Vp.nullish(),Permissions:WS.nullish(),Audit:Np.nullish(),Status:_p.nullish()}).passthrough(),HS=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),$S=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),JS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),ZS=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(),Ca=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:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:zod.z.array(HS).nullish(),Limits:$S.nullish(),Permissions:JS.nullish(),Conversion:Vp.nullish(),Audit:Np.nullish(),Status:_p.nullish(),ServerGrantPolicy:ZS.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),YS=zod.z.object({SpendID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),PriceOptions:zod.z.record(zod.z.string(),An).nullish()}).passthrough(),_r=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),QS).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),Ca).nullish(),Spends:zod.z.record(zod.z.string(),YS).nullish()}).passthrough();var XS={EVM:"EVM",Solana:"Solana"},ex=zod.z.enum(["EVM","Solana"]).catch("EVM"),tx={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},ix=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),nx={Token:"Token",Nft:"Nft"},jp=zod.z.enum(["Token","Nft"]).catch("Token"),rx={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},sx=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),ox={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},ax=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),lx={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Sa=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),Wp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Vr(s){let e=s?.trim();return e||Wp.GameTopUp}var ux={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},Kp=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),cx=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(),Qp=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),px=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:ex.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:Qp.nullish(),NftCollections:zod.z.array(cx).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(),dx=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Qp.nullish()}).passthrough(),hx=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),mx={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},fx=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Hp=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:fx.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),gx=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),yx={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Ni=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),Rx=zod.z.object({Mode:Ni.nullish(),TokenGates:zod.z.array(Hp).nullish()}).passthrough(),xa=zod.z.object({SystemState:dx.nullish(),Networks:zod.z.record(zod.z.string(),px).nullish(),AccountSafety:hx.nullish(),WalletLogin:gx.nullish(),PlayAccess:Rx.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),Cx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:p.nullish(),LastUsedAt:p.nullish(),LinkType:ix.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),$p=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:jp.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),Sx=zod.z.object({Status:sx.nullish(),Tier:ax.nullish(),VerifiedAt:p.nullish(),ExpiresAt:p.nullish(),RejectedAt:p.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),xx=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),bx=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:zod.z.record(zod.z.string(),xx).nullish()}).passthrough(),Dx=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:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),Px=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(),Dx).nullish()}).passthrough(),Ix=zod.z.object({Tokens:bx.nullish(),Nfts:Px.nullish()}).passthrough(),ba=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Wt=zod.z.object({Granted:zod.z.boolean(),Mode:Ni.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:p.nullish(),Balances:zod.z.array(ba).nullish()}).passthrough(),vx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:p.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:p.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(ba).nullish()}).passthrough(),Tx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),Jp=zod.z.object({Mode:Ni.nullish(),TokenGates:zod.z.array(Hp).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(Tx).nullish(),Status:Wt.nullish()}).passthrough(),Ax=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:p.nullish(),LoggedInAt:p.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(ba).nullish()}).passthrough(),wx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:p.nullish()}).passthrough(),kx=zod.z.object({Version:zod.z.number().nullish(),Stats:Ix.nullish(),LinkedWallets:zod.z.record(zod.z.string(),Cx).nullish(),LastWalletLogin:Ax.nullish(),PlayAccess:vx.nullish(),PendingWithdrawals:zod.z.array($p).nullish(),Kyc:Sx.nullish(),FirstActivityAt:p.nullish(),LastActivityAt:p.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(wx).nullish()}).passthrough(),zx=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:p}).passthrough(),Pi=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),zx).nullish(),PendingAdded:$p.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Mx=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough().transform(s=>s),Ox=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.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:Kp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Sa.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.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:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:p.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:p.nullish(),RefundCheckedAt:p.nullish()}).passthrough(),Ex=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.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:Kp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Sa.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.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:p.nullish()}).passthrough(),Zp=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Da=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(Zp).nullish(),Signature:zod.z.string().nullish()}).passthrough(),Pa=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(Zp).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(),Yp=zod.z.object({Blockchain:xa.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),Ca).nullish()}).passthrough(),Xp=zod.z.object({State:kx.nullish(),CryptoBalances:zod.z.record(zod.z.string(),Mx).nullish()}).passthrough(),ed=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:Pi.nullish()}).passthrough(),td=zod.z.object({ServerTimeUtc:p.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(),id=zod.z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:p.nullish(),EvmSignature:Da.nullish(),SolanaSignature:Pa.nullish(),StateDelta:Pi.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),nd=zod.z.object({ServerTimeUtc:p.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:p.nullish(),Resources:O.nullish(),EvmSignature:Da.nullish(),SolanaSignature:Pa.nullish(),StateDelta:Pi.nullish(),Inventory:K.nullish()}).passthrough(),rd=zod.z.object({TokenTransactions:zod.z.array(Ox).nullish(),NFTTransactions:zod.z.array(Ex).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ia=zod.z.object({ServerTimeUtc:p.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:zod.z.string().nullish()}).passthrough(),sd=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:jp.nullish(),EvmSignature:Da.nullish(),SolanaSignature:Pa.nullish()}).passthrough(),od=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:Sa.nullish(),StateDelta:Pi.nullish()}).passthrough(),Je={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 Ux="Blockchain",ad="Blockchain:Definitions",Nr=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(ad,e);if(t)return N(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return a;let n=this.ctx.api.blockchain.getDefinitions(i).then(r=>(r.ok&&(this.ctx.data.config.patchSection(Ux,r.data.Blockchain),this.ctx.data.config.patchSection(ad,r.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",r.data)),r)).finally(()=>{this.definitionsInflight===n&&(this.definitionsInflight=null);});return this.definitionsInflight=n,n}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;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 u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositToken(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",n.data)),n}async depositNFT(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositNFT(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",n.data)),n}async requestTokenWithdrawal(e,t,i,n,r){if(!e)return u("client","CurrencyID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!n)return u("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return a;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=n,o.Category=Vr(r);let c=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return c.ok&&(this.ctx.data.user.applyBlockchainStateDelta(c.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",c.data)),c}async requestNFTWithdrawal(e,t,i,n,r,o,c){if(!e)return u("client","ItemID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!n)return u("client","Amount is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.NetworkID=t,h.WalletAddress=i,h.Amount=n,h.Category=Vr(r),o!==void 0&&(h.Level=o),c&&(h.ItemInstanceID=c);let y=await this.ctx.api.blockchain.requestNFTWithdrawal(h);return y.ok&&(this.ctx.data.user.applyBlockchainStateDelta(y.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(y.data.Resources,y.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",y.data)),y}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return a;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return u("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return u("client","TitleTransactionID is required.");if(!t)return u("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TitleTransactionID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.confirmWithdrawal(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",n.data)),n}async donateToDeveloper(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToDeveloper(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",n.data),n}async donateToUsersPool(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToUsersPool(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",n.data),n}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return a;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 a;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var qx={Head:"Head",Torso:"Torso",Legs:"Legs"},jr=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),Lx={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},va=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),ud=zod.z.object({AttackTarget:jr,DefenseTarget:jr});var Bx=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),Gx=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:jr.nullish(),DefenseZone:jr.nullish(),HitType:Bx.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),Fx=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(),_x=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:p,ExpiresAt:p.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),ld=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:$o.nullish(),BattleStrategy:zod.z.array(ud).nullish(),UnstackableItems:zod.z.record(zod.z.string(),_x).nullish(),Stats:Fx.nullish()}).passthrough(),Vx=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:pe.nullish(),NetReward:pe.nullish(),BattleLog:zod.z.array(Gx).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:ld.nullish(),P2BattleProfile:ld.nullish()}).passthrough(),cd=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:p.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(ud).nullish(),TargetUserID:zod.z.string().nullish(),Entry:pe.nullish(),CreationCostPaid:pe.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:p.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:p.nullish(),Status:va.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:p.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:p.nullish()}).passthrough(),pd=zod.z.object({Status:va,MatchID:zod.z.string(),Entry:pe.nullish(),Resources:O.nullish()}),dd=zod.z.object({Match:cd.nullish()}),hd=zod.z.object({MatchID:zod.z.string(),Status:va,Resources:O.nullish()}),md=zod.z.object({Battle:Vx.nullish(),Resources:O.nullish(),ResourcesDual:At.nullish()}),Ta=zod.z.object({Matches:zod.z.array(cd).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),Dt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var Nx=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var jx=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),Wx=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(),Kx=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),Qx=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:Kx.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),Hx=zod.z.object({Kind:jx.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Ne.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),$x=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(Hx).nullish()}).passthrough(),ti=zod.z.object({Terms:zod.z.array($x).nullish()}).passthrough(),Jx=zod.z.object({Health:ti.nullish(),Damage:ti.nullish(),Armor:ti.nullish(),AttackSpeed:ti.nullish(),CritChance:ti.nullish(),CritDamage:ti.nullish(),Dodge:ti.nullish()}).passthrough(),fd=zod.z.object({StatMapping:Wx.nullish(),Combat:Qx.nullish(),Formula:Jx.nullish()}).passthrough(),Zx=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),ji=zod.z.object({Kind:Nx.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:en.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),gd=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(ji).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),yd=zod.z.object({PriceOptions:ae.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:Se.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),Yx=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:Zx.nullish(),Entry:gd.nullish(),Creation:yd.nullish(),Settings:fd.nullish()}).passthrough(),Xx=zod.z.object({Rules:zod.z.record(zod.z.string(),Yx).nullish(),Defaults:fd.nullish(),EntryDefaults:gd.nullish(),CreationDefaults:yd.nullish()}).passthrough(),Aa=zod.z.object({InstantBattle:Xx.nullish()}).passthrough(),Rd=Aa;var eb={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},wa=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),tb={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},ka=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),ib={Burn:"Burn",Ledger:"Ledger"},nb=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Kr={Item:"Item",VirtualCurrency:"VirtualCurrency"},za=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),rb=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:W.nullish()}).passthrough(),Qr=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(ji).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Ma=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:W.nullish(),Sink:nb.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),rb).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),sb=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(),ob=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:Se.nullish(),BuyLimits:Se.nullish(),ListingFeeOptions:ae.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),ab=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:W.nullish(),BidLimits:Se.nullish()}).passthrough(),lb=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:Se.nullish(),FillLimits:Se.nullish()}).passthrough(),ub=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:Se.nullish()}).passthrough(),cb=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Oa=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:Re.nullish(),PricePolicy:Qr.nullish(),Commission:Ma.nullish(),Tradability:sb.nullish(),Listings:ob.nullish(),Auctions:ab.nullish(),BuyOrders:lb.nullish(),DirectTrades:ub.nullish(),Matching:cb.nullish()}).passthrough(),Cd=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:W.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:p.nullish()}).passthrough(),pb=zod.z.object({BidAxisType:fi.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:W.nullish(),CurrentBid:W.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(Cd).nullish()}).passthrough(),Wr=zod.z.object({LastAt:p.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),db=zod.z.object({Create:Wr.nullish(),Buy:Wr.nullish(),Sell:Wr.nullish(),Bid:Wr.nullish()}).passthrough(),hb=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),mb=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:p,ExpiresAt:p.nullish(),EquippedSlot:hb.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(s=>s),qt=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:wa.nullish(),Status:ka.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:qe.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:za.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:W.nullish(),GoodsInstances:zod.z.array(mb).nullish(),Price:pe.nullish(),Auction:pb.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),fb=zod.z.object({GoodsType:za.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(wa,W).nullish()}).passthrough(),Sd=zod.z.object({Definitions:Oa.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),Ea=zod.z.object({Offers:zod.z.array(qt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),xd=zod.z.object({Groups:zod.z.array(fb).nullish()}).passthrough(),bd=zod.z.object({Offer:qt.nullish()}).passthrough(),ct=zod.z.object({OfferID:zod.z.string().nullish(),Status:ka.nullish(),Settlement:At.nullish(),Resources:O.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Wi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:qt.nullish(),Resources:O.nullish(),Matched:zod.z.boolean().nullish(),Settlement:ct.nullish()}).passthrough(),Dd=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:W.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish()}).passthrough(),Hr=zod.z.object({MyOffers:zod.z.array(qt).nullish(),MyBids:zod.z.array(qt).nullish(),MyBuyOrders:zod.z.array(qt).nullish(),IncomingTrades:zod.z.array(qt).nullish(),OutgoingTrades:zod.z.array(qt).nullish(),Claimables:zod.z.array(qt).nullish(),DrainedRefunds:zod.z.array(Cd).nullish(),Limits:db.nullish()}).passthrough(),gb=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:wa.nullish(),FinalStatus:ka.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:za.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:W.nullish(),PricePaid:pe.nullish(),CommissionTaken:pe.nullish(),CompletedAt:p.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),Pd=zod.z.object({Entries:zod.z.array(gb).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Oe={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 yb="Marketplace",Id={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"]},$r=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Id,{schema:Hr,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(yb,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return a;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,i,n=20){if(!e)return u("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return a;r.ItemID=e,r.OfferTypeFilter=t,r.ContinuationToken=i,r.PageSize=n;let o=await this.ctx.api.marketplace.getOffersByItem(r);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let n=this.ctx.authedRequest();if(!n)return a;n.ItemID=e,n.ContinuationToken=t,n.PageSize=i;let r=await this.ctx.api.marketplace.getBuyOrders(n);return r.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",r.data),r}getMyState(e,t){return this.ctx.cache.read(Id,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let n=this.ctx.authedRequest();if(!n)return a;i&&(n.HistoryFilter=i),n.ContinuationToken=e,n.PageSize=t;let r=await this.ctx.api.marketplace.getHistory(n);return r.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",r.data),r}async createListing(e,t,i,n,r,o,c){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!n)return u("client","PriceBundle is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.PriceBundle=n,h.DurationHours=r,h.ItemInstanceIDs=o,h.SelectedOptionID=c;let y=await this.ctx.api.marketplace.createListing(h);return this.applyCreateOfferResult(y,"marketplace:listingCreated"),y}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let n=this.ctx.authedRequest();if(!n)return a;let r=this.applyGoodsSelector(n,i);if(r)return r;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let n=this.ctx.authedRequest();if(!n)return a;let r=this.applyGoodsSelector(n,i);if(r)return r;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,n,r,o,c={}){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.BidAxisType=n,h.BidCurrencyID=c.bidCurrencyID,h.BidCatalogID=c.bidCatalogID,h.BidItemID=c.bidItemID,h.StartingBid=r,h.DurationHours=o,h.ItemInstanceIDs=c.itemInstanceIDs,h.SelectedOptionID=c.selectedOptionID;let y=await this.ctx.api.marketplace.createAuction(h);return this.applyCreateOfferResult(y,"marketplace:auctionCreated"),y}async placeBid(e,t){if(!e)return u("client","OfferID is required.");if(!t||t<=0)return u("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.BidAmount=t;let n=await this.ctx.api.marketplace.placeBid(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",n.data)),n}async claimAuction(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,n,r){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!n)return u("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return a;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=n,o.DurationHours=r;let c=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(c,"marketplace:buyOrderCreated"),c}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,n,r){if(!e)return u("client","TargetUserID is required.");if(!t)return u("client","CatalogID is required.");if(!i)return u("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return a;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=n,o.RequestedBundle=r;let c=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(c,"marketplace:directTradeCreated"),c}async respondDirectTrade(e,t){if(!e)return u("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.Accept=t;let n=await this.ctx.api.marketplace.respondDirectTrade(i);return n.ok&&(t&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",n.data)),n}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 a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return u("client","OfferID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.OfferID=e;let r=await t(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,r.data)),r}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=Kr.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Kr.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):u("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var Jr=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return u("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let n=await this.ctx.api.multiplayer.createRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",n.data),n}async joinRoom(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.JoinCode=t;let n=await this.ctx.api.multiplayer.joinRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",n.data),n}async leaveRoom(e,t={}){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let n=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",n.data),n}async claimHost(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.TargetUserID=t,n.Ban=i;let r=await this.ctx.api.multiplayer.kickMember(n);return r.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",r.data),r}async unbanMember(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.TargetUserID=t;let n=await this.ctx.api.multiplayer.unbanMember(i);return n.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",n.data),n}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return a;i.Page=e,i.PageSize=t;let n=await this.ctx.api.multiplayer.listRooms(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",n.data),n}async getRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.LastSeq=t;let n=await this.ctx.api.multiplayer.poll(i);return n.ok&&this.ctx.emitter.emit("multiplayer:polled",n.data),n}async sendSignal(e,t,i,n){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");if(!i)return u("client","SignalKind is required.");let r=this.ctx.authedRequest();if(!r)return a;r.RoomID=e,r.TargetUserID=t,r.SignalKind=i,r.Payload=n;let o=await this.ctx.api.multiplayer.sendSignal(r);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.ChatText=t;let n=await this.ctx.api.multiplayer.sendChat(i);return n.ok&&this.ctx.emitter.emit("multiplayer:chatSent",n.data),n}async setMemberState(e,t,i){if(!e)return u("client","RoomID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.Ready=t,n.MemberState=i;let r=await this.ctx.api.multiplayer.setMemberState(n);return r.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",r.data),r}};var vd=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Zr=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;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)):a}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 u("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):a}async getCreatorProfile(e,t,i){if(!e)return u("client","CreatorUserID is required.");let n=this.ctx.authedRequest();return n?(n.CreatorUserID=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getCreatorProfile(n)):a}async publish(e){if(!e.files||e.files.length===0)return u("client","At least one file is required.");let t=new Map,i=e.files.map((h,y)=>{if("sourceAssetUrl"in h)return {Role:h.role,ContentType:h.contentType,SourceAssetUrl:h.sourceAssetUrl};let V=Td(h.data,h.contentType);return t.set(y,V),{Role:h.role,ContentType:h.contentType,Size:V.size}}),n=e.thumbnail?Td(e.thumbnail.data,e.thumbnail.contentType):null,r=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&n?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:n.size}:void 0});if(!r.ok)return r;let o=r.data.Uploads??[];for(let h=0;h<o.length;h++){let y=o[h];if(!y||y.ServerCopy||!y.Url)continue;let V=t.get(h);if(!V)return u("client",`No bytes for file #${h+1}.`);let oe=await this.putBytes(y.Url,V,y.ContentType??V.type);if(!oe.ok)return oe}let c=r.data.ThumbnailUpload;if(c?.Url&&n){let h=await this.putBytes(c.Url,n,c.ContentType??n.type);if(!h.ok)return h}return this.ctx.credits.pay(h=>this.publishUploaded({CreditsConfirmationID:h,ContentID:r.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}):a}async publishUploaded(e){if(!e.ContentID)return u("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return a;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&!i.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let n=await this.ctx.api.workshop.updateContent(i);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let n=this.ctx.authedRequest();return n?(n.ContentType=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getMyContent(n)):a}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let n=await this.ctx.api.workshop.acquire(i);return n.ok&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",n.data)),n}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 i=[];for(let n of t.data.Files??[])if(n.Url)try{let r=await this.ctx.fetchImpl(n.Url);if(!r.ok)return u("connection",`Download failed (HTTP ${r.status}).`);i.push({role:n.Role??"main",contentType:n.ContentType??"application/octet-stream",data:await r.arrayBuffer()});}catch(r){return u("connection",`Download failed: ${r instanceof Error?r.message:String(r)}${vd}`)}return N({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):a}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):a}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?N(!0):u("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return u("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}${vd}`)}}contentRequest(e){if(!e)return u("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):a}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function Td(s,e){return s instanceof Blob?s:typeof s=="string"?new Blob([new TextEncoder().encode(s)],{type:e}):s instanceof Uint8Array?new Blob([s.slice().buffer],{type:e}):new Blob([s],{type:e})}var Rb={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},Cb=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Sb={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Ad=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),xb={Everyone:"Everyone",Owner:"Owner",Server:"Server"},wd=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),bb={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},Db=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),Pb={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},Ib=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),vb={Count:"Count",Sum:"Sum"},Tb=zod.z.enum(["Count","Sum"]).catch("Count"),Ab={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},wb=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),kb={Strict:"Strict",Loose:"Loose"},zb=zod.z.enum(["Strict","Loose"]).catch("Strict"),Mb=zod.z.object({Kind:Ib,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),Ob=zod.z.object({Type:Ad,ItemType:Ad.nullish(),Ref:Mb.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:wd.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()}),Eb=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Yr=zod.z.object({Mode:Db,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),Ub=zod.z.object({Read:zod.z.array(Yr).nullish(),Create:zod.z.array(Yr).nullish(),Update:zod.z.array(Yr).nullish(),Delete:zod.z.array(Yr).nullish()}),Ua=zod.z.object({Cost:pe.nullish(),Grant:pe.nullish()}),qb=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()}),Lb=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:Cb,Mode:zb.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),Ob).nullish(),SortKeys:zod.z.array(Eb).nullish(),Access:Ub.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:wb.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:Tb,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:wd.optional()})).nullish(),Economy:zod.z.object({OnCreate:Ua.nullish(),OnUpdate:Ua.nullish(),OnDelete:Ua.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:zod.z.array(qb).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()}),kd=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),Lb).default({})}),Bb=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),zd=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),Ii=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(),Bb).nullish()}),qa=zod.z.object({Item:Ii}),Md=zod.z.object({Items:zod.z.array(Ii).default([]),Missing:zod.z.array(zod.z.string()).default([])}),La=zod.z.object({Items:zod.z.array(Ii).default([]),NextCursor:zod.z.string().nullish()}),Od=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),Ba=zod.z.object({Item:Ii,AlreadyExists:zod.z.boolean().optional(),Economy:O.nullish()}),Ed=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:O.nullish()}),Ud=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),qd=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:Ii.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),Ld=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),Bd=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),Gd=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({})}),Fd=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(Ii).default([])}),Gb={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 Fb=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Nd=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Fa=100,_d=25,Vd=100;function _b(s,e,t){return {Field:s,Op:e,Value:t}}var Xr=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(a)}get(e,t,i={}){let n=rt(e)??Ki(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.get({...r,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let n=rt(e);if(n)return Promise.resolve(n);let r=[...new Set(t.filter(o=>Nd.test(o)))];return r.length?r.length>Vd?Promise.resolve(u("client",`At most ${Vd} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:r,Expand:i.expand})):Promise.resolve(u("client","At least one valid item id is required."))}query(e,t={},i={}){let n=rt(e)??Ga(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.query({...r,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let n=Math.max(1,i.maxItems??500),r=[],o=t.Cursor;for(;;){let c=await this.query(e,{...t,Cursor:o,Limit:t.Limit??Fa},i);if(!c.ok)return c;if(r.push(...c.data.Items),o=c.data.NextCursor??void 0,!o||r.length>=n)return N(r.slice(0,n))}}count(e,t={}){let i=rt(e)??Ga(t);return i?Promise.resolve(i):this.call(n=>this.ctx.api.dataCollections.count({...n,Collection:e,Query:t}))}create(e,t,i={}){let n=rt(e)??(i.itemID?Ki(i.itemID):null);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.create({...r,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,n={}){let r=rt(e)??Ki(t);return r?Promise.resolve(r):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:n.expectedVersion}))}set(e,t,i,n={}){return this.update(e,t,{Set:i},n)}increment(e,t,i,n=1){return this.update(e,t,{Inc:{[i]:n}})}delete(e,t,i={}){let n=rt(e)??Ki(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.delete({...r,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(u("client","Operations are empty."));if(e.length>_d)return Promise.resolve(u("client",`At most ${_d} operations per batch.`));let t=e.map(i=>rt(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let n=rt(e);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.getCounter({...r,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,n){let r=rt(e);return r?Promise.resolve(r):t?n>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:n})):Promise.resolve(u("client","File size must be positive.")):Promise.resolve(u("client","Field is required."))}async uploadFile(e,t,i,n={}){let r=n.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,r,i.size);if(!o.ok)return o;let c=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||r);return c.ok?o:c}async getPublicViews(e){let t=rt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return N(i);let n=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return n.ok&&this.publicViews.set(e,n.data),n}async readPublicView(e,t,i={}){let n=await this.getPublicViews(e);if(!n.ok)return n;let r=n.data.Views[t];if(!r)return u("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(r,Gd);if(!o.ok)return o;let c=o.data.Partitions[i.partition??""],h=Math.max(1,i.page??1);if(!c||h>c.Pages)return N({pointer:o.data,page:{Page:h,HasMore:false,Items:[]}});let y=await this.fetchJson(`${o.data.BaseUrl}${c.Segment}/page-${h}.json`,Fd);return y.ok?N({pointer:o.data,page:y.data}):y}getPublic(e,t){let i=rt(e)??Ki(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=rt(e)??Ga(t);return i?Promise.resolve(i):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(a)}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?N(!0):u("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return u("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return u("connection","Internet Connection Error")}if(!i.ok)return u("server",`CDN answered ${i.status}.`);let n;try{n=await i.json();}catch{return u("server","CDN answer is not JSON.")}let r=t.safeParse(n);return r.success?N(r.data):u("server","CDN answer has an unexpected shape.")}};function rt(s){return Fb.test(s??"")?null:u("client",`Collection id '${s}' is invalid (letters, digits, '_', '-', ':').`)}function Ki(s){return Nd.test(s??"")?null:u("client",`Item id '${s}' is invalid.`)}function Ga(s){return s.Limit!=null&&(s.Limit<1||s.Limit>Fa)?u("client",`Limit must be 1..${Fa}.`):(s.Where?.length??0)>8?u("client","At most 8 filters per query."):null}var _a={Open:"Open",Declared:"Declared"},Vb=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),Nb=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),jd=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Vb).nullish(),Dimensions:zod.z.array(Nb).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),Kt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Pt={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},es=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,jb={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},Wb=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),Wd=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(Wb).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Va={LogEvents:"LogEvents"};function Kd(s,e=0){let t=s??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let c=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:c==="iPad"?"tablet":"phone",deviceModel:c}}let n=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(n){let c=(n[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:n[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:c&&c!=="K"&&c!=="wv"?c:void 0}}let r=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(r)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(r[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 Qd(s){let e=typeof navigator>"u"?void 0:navigator,t=Kd(e?.userAgent??"",e?.maxTouchPoints??0),i={};s.appVersion&&(i.AppVersion=s.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let n=s.locale||e?.language;return n&&(i.Language=n),i}var Kb=25,Qb=3e4,Hd=1800*1e3,$d=500,Hb=5,$b=1e3,Jb=3600*1e3,Jd="idos_analytics_queue",Na="idos_analytics_pending",ja="idos_analytics_opt_out",Zd="idos_analytics_first_open",Yd="idos_analytics_last_activity",Xd="idos_analytics_last_context",eh="idos_analytics_owner",ts=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!es.test(e)?u("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Zb(e)?u("client",`Event name "${e}" uses a reserved prefix (${Pt.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return u("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Kt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return N(null);if(this.config()?.Enabled===false)return this.clear(),N(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return N(null);this.pending={BatchID:G(),Events:this.queue.splice(0,Pt.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=Hb)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(ja);return}this.write(ja,"1"),this.clear();}get isEnabled(){return this.read(ja)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(eh);e&&t&&t!==e&&this.clear(),e&&this.write(eh,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Qb),typeof window<"u"&&(window.addEventListener("visibilitychange",this.onVisibilityChange),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,typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),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(Yd)??"0");this.read(Zd)||(this.write(Zd,new Date().toISOString()),this.enqueue(Kt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Xd);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Kt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Kt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Xd,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Hd)&&this.enqueue(Kt.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=Hd&&this.enqueue(Kt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,n){if(!this.isEnabled||this.disabledByServer)return N(null);let r=this.config();if(r?.Enabled===false)return N(null);if(n&&r?.AutomaticEvents===false)return N(null);if(r?.Events?.[e]?.Blocked)return u("client",`Event "${e}" is blocked by the title.`);if(!n&&r?.EventNaming?.toLowerCase()===_a.Declared.toLowerCase()&&!r.Events?.[e])return u("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return u("client","value must be a finite number.");let o=Yb(t);if(o.error)return u("client",o.error);this.restore();let c={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(c.Params=o.params),i!==void 0&&(c.Value=i),this.queue.push(c),this.queue.length>$d&&this.queue.splice(0,this.queue.length-$d),this.touch(),this.persist(),this.started&&this.queue.length>=Kb&&this.flush(),N(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},$b));}dropStale(){let e=Date.now()-(Pt.maxEventAgeMs-Jb);this.queue=this.queue.filter(t=>{let i=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(i)||i>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=Qd({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(Jd);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(Na);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(Jd,this.queue),this.pending?this.writeJson(Na,this.pending):this.remove(Na);}touch(){this.write(Yd,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.platform.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.platform.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.platform.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 Zb(s){let e=s.toLowerCase();return Pt.reservedPrefixes.some(t=>e.startsWith(t))}function Yb(s){if(!s)return {};let e=Object.keys(s);if(e.length===0)return {};if(e.length>Pt.maxParams)return {error:`Too many parameters: ${e.length}, max ${Pt.maxParams}.`};let t={};for(let i of e){if(!es.test(i))return {error:`Invalid parameter name "${i}".`};let n=s[i];typeof n=="string"?t[i]=n.length>Pt.maxStringValueLength?n.slice(0,Pt.maxStringValueLength):n:typeof n=="number"?Number.isFinite(n)&&(t[i]=n):typeof n=="boolean"&&(t[i]=n);}return {params:t}}var Xb="idos_experiments",is=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 a;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}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,i){let n=this.getParams(e)[t];if(n===void 0)return i;if(typeof i=="number"){let r=Number(n);return n.trim()!==""&&Number.isFinite(r)?r:i}if(typeof i=="boolean"){let r=n.trim().toLowerCase();return r==="true"||r==="1"?true:r==="false"||r==="0"?false:i}return n}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 n of e.Experiments??[])n?.ExperimentID&&t.set(n.ExperimentID,n);let i=[];for(let[n,r]of t){let o=this.views.get(n);(!o||o.VariantID!==r.VariantID||o.Status!==r.Status)&&i.push(r);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}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.platform.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.platform.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${Xb}:${this.ctx.settings.titleID}`}};function Qt(s,e,t,i){let r=`api/v2/${s&&s.length>0?s:"0"}/Client/${e}/${t}`;return i==null?r:`${r}/${i}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Qt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,n){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...n,ticket:t.ClientSessionTicket})}};var ns=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Va.LogEvents,e,Wd,{silent:true})}};var eD=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(),tD={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},iD=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),nD=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:Re.nullish(),Gate:Z.nullish(),Variants:zod.z.array(eD).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(iD).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),th=zod.z.object({Experiments:zod.z.record(zod.z.string(),nD).nullish()}).passthrough(),rD={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},sD=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(),ih=zod.z.object({Experiments:zod.z.array(sD).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),Wa={GetExperiments:"GetExperiments"};var rs=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Wa.GetExperiments,e,ih)}};var nh=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:p.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:p,PlayAccess:Wt.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:p.nullish()}),rh=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:p,RefreshToken:zod.z.string(),RefreshTokenExpiration:p.nullish(),PlayAccess:Wt.nullish()}),oD=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),sh=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:Ni.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:oD.nullish()}).passthrough(),oh=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:p.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:Wt.nullish()}).passthrough(),ah=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:p.nullish(),PlayAccess:Wt.nullish()}).passthrough(),lh=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Ge=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:p.nullish()}),uh=zod.z.object({Message:zod.z.string(),ExpiresAt:p}),Be={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 ss=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Qt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,nh,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Be.RefreshSession),e,rh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Be.GetAuthOptions),e,sh,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Qt(this.ctx.settings.titleID,"Authentication",Be.LinkWallet,e.UserID??""),e,oh,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Qt(this.ctx.settings.titleID,"Authentication",Be.UnlinkWallet,e.UserID??""),e,ah,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Be.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Be.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Be.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Be.LoginWithGoogle,e)}loginWithApple(e){return this.login(Be.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Be.LoginWithSsoCode,e)}resolvePlatformGameSession(e){return this.login(Be.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Be.RegisterWithEmail),e,lh,{ticket:null})}confirmEmailRegistration(e){return this.login(Be.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Be.ResendVerificationCode),e,Ge,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Be.RequestWalletChallenge),e,uh,{ticket:null})}loginWithWallet(e){return this.login(Be.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Be.ForgotPassword),e,Ge,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Be.ResetPassword),e,Ge,{ticket:null})}};var aD={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},ch=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),lD=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),ph=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),lD).nullish(),MissingKeyMode:ch.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),uD=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),dh=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:uD.nullish()}).passthrough(),os={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},cD=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),hh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:ch.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(cD).nullish()}).passthrough(),mh=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 Ka=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:dh.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()}).passthrough().transform(s=>s),fh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(s=>s),gh=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(s=>s),yh=zod.z.object({}).passthrough().transform(s=>s),Rh=zod.z.object({}).passthrough().transform(s=>s),Ch=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:p.nullish(),LastActiveAt:p.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(),Sh=zod.z.object({Username:zod.z.string()}),pt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var as=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(pt.GetClientState,e,Ka)}getClientStateExcept(e){return this.send(pt.GetClientStateExcept,e,Ka)}getStateVersions(e){return this.send(pt.GetStateVersions,e,fh)}getUserState(e){return this.send(pt.GetUserState,e,gh)}getInventory(e){return this.send(pt.GetInventory,e,yh)}getEventTokens(e){return this.send(pt.GetEventTokens,e,Rh)}getUsageTime(e){return this.send(pt.GetUsageTime,e,Ch)}addUsageTime(e){return this.send(pt.AddUsageTime,e,Ge,{silent:true})}deleteUserAccount(e){return this.send(pt.DeleteUserAccount,e,Ge)}changeUsername(e){return this.send(pt.ChangeUsername,e,Sh)}};var ls=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(Vi.Convert,e,Bp)}spend(e){return this.send(Vi.Spend,e,Fp)}cryptoConvert(e){return this.send(Vi.CryptoConvert,e,Gp)}};var pD=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),Qa=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:O.nullish(),FodderConsumed:zod.z.array(pD).nullish()}),xh=zod.z.array(we(Qa)),us={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},dD={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},hD=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),mD={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},fD=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),gD=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),yD=zod.z.object({Networks:zod.z.record(zod.z.string(),gD).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),RD=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(),CD=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(),SD=zod.z.object({ValuationMode:hD.nullish(),WeightCurve:Ne.nullish(),Selection:fD.nullish()}).passthrough(),xD=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:ae.nullish(),CostCurve:Ne.nullish(),FlatBonusCurve:Ne.nullish(),PercentBonusCurve:Ne.nullish(),PowerCurve:Ne.nullish(),Fodder:SD.nullish()}).passthrough(),bD=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),DD=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:yD.nullish(),Stats:RD.nullish(),Equipment:CD.nullish(),Upgrade:xD.nullish(),Metadata:bD.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),PD=zod.z.object({Items:zod.z.record(zod.z.string(),DD).nullish()}).passthrough(),cs=zod.z.object({Catalogs:zod.z.record(zod.z.string(),PD).nullish()}).passthrough();function Ie(s){return zod.z.unknown().transform((e,t)=>{let i=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(i!=null){let r=fe.safeParse(i);return r.success?{...e,CreditsConfirmation:r.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${r.error.message}`}),zod.z.NEVER)}let n=s.safeParse(e);return n.success?n.data:(t.addIssue({code:"custom",message:n.error.message}),zod.z.NEVER)})}var ps=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(us.UpgradeLevel,e,Ie(Qa))}upgradeLevelsBatch(e){return this.send(us.UpgradeLevelsBatch,e,xh)}};var ds=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(Mt.Purchase,e,Oo)}purchaseBatch(e){return this.send(Mt.PurchaseBatch,e,bu)}getDefinitions(e){return this.send(Mt.GetDefinitions,e,kn)}getUserState(e){return this.send(Mt.GetUserState,e,Du)}getStorefront(e){return this.send(Mt.GetStorefront,e,zn)}getCreditsConfirmation(e){return this.send(Mt.GetCreditsConfirmation,e,fe)}getCreditsBalance(e){return this.send(Mt.GetCreditsBalance,e,xu)}};var ID={Apple:"Apple",Google:"Google"},hs=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(),ms=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),hs).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(s=>s),vD=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:ae.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$a=zod.z.object({Definitions:zod.z.record(zod.z.string(),vD).nullish()}).passthrough(),bh=zod.z.object({Premium:$a.nullish()}),Dh=zod.z.object({ServerTimeUtc:p.nullish(),Premium:ms.nullish()}),fs=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),Premium:ms.nullish(),Subscription:hs.nullish(),Resources:O.nullish()}),ii={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var TD={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},AD=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Ph=zod.z.object({StartUtc:p.nullish(),EndUtc:p.nullish(),Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Ja=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),wD=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),kD=zod.z.object({Rewards:Q.nullish(),Rules:Q.nullish(),Refund:Q.nullish()}).passthrough(),zD=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:AD.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:Ph.nullish(),Refund:Ja.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:wD.nullish(),Presets:kD.nullish()}).passthrough(),MD=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(),OD=zod.z.object({Rewards:H.nullish()}).passthrough(),ED=zod.z.object({Rules:Ph.nullish()}).passthrough(),UD=zod.z.object({Refund:Ja.nullish()}).passthrough(),qD=zod.z.object({Rewards:zod.z.record(zod.z.string(),OD).nullish(),Rules:zod.z.record(zod.z.string(),ED).nullish(),Refund:zod.z.record(zod.z.string(),UD).nullish()}).passthrough(),LD=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(),BD=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),zD).nullish(),Stores:zod.z.record(zod.z.string(),MD).nullish(),Presets:qD.nullish(),Validation:LD.nullish(),Refund:Ja.nullish()}).passthrough(),Ih=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:p.nullish(),LastPurchasedAt:p.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(),vh=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:p.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:p.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:p.nullish()}).passthrough(),GD=zod.z.object({Products:zod.z.record(zod.z.string(),Ih).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),vh).nullish(),LastRefundCheckAt:p.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:p.nullish(),LastPurchaseAt:p.nullish()}).passthrough(),FD=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(),Th=zod.z.object({ServerTimeUtc:p,Purchase:BD.nullish(),Availability:zod.z.array(FD).nullish()}),Ah=zod.z.object({ServerTimeUtc:p,Purchase:GD.nullish()}),_D={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},VD=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Za=zod.z.object({ServerTimeUtc:p,Store:Xi.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:VD.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish(),ProductState:Ih.nullish(),Premium:ms.nullish(),Subscription:hs.nullish(),SubscriptionMirror:vh.nullish()}).passthrough(),wh=zod.z.object({ServerTimeUtc:p,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:p.nullish()}).passthrough(),kh=St(Za),ni={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var gs=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(ni.GetDefinitions,e,Th)}getUserState(e){return this.send(ni.GetUserState,e,Ah)}validatePurchase(e){return this.send(ni.ValidatePurchase,e,Za)}validatePurchasesBatch(e){return this.send(ni.ValidatePurchasesBatch,e,kh)}createTelegramInvoice(e){return this.send(ni.CreateTelegramInvoice,e,wh)}};var ND=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),zh=zod.z.object({Reward:H.nullish(),Weight:zod.z.number().nullish(),AmountRange:ND.nullish()}).passthrough(),vi=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(zh).nullish()}).passthrough(),Ti=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(zh).nullish()}).passthrough(),jD=zod.z.object({RewardSlots:zod.z.array(vi).nullish()}).passthrough(),WD=zod.z.object({PityRules:zod.z.array(Ti).nullish()}).passthrough(),ys=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),jD).nullish(),PityPresets:zod.z.record(zod.z.string(),WD).nullish()}).passthrough();var KD=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),Mh=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,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(KD).nullish()}),QD=zod.z.object({RewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),HD=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:W.nullish()}).passthrough(),$D=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ae.nullish(),RewardSlots:zod.z.array(vi).nullish(),PityRules:zod.z.array(Ti).nullish(),Presets:QD.nullish(),RewardMultiplier:tn.nullish(),SupplyLimits:zod.z.array(HD).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),JD=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Ya=zod.z.object({Definitions:zod.z.record(zod.z.string(),$D).nullish(),RewardPools:ys.nullish(),Settings:JD.nullish()}).passthrough(),Oh=zod.z.object({LootboxDefinitions:Ya.nullish()}),Rs={GetDefinitions:"GetDefinitions",Open:"Open"};var Cs=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(Rs.GetDefinitions,e,Oh)}open(e){return this.send(Rs.Open,e,Ie(Mh))}};var ZD=zod.z.object({}).passthrough().transform(s=>s),YD=zod.z.object({}).passthrough().transform(s=>s),XD=zod.z.object({}).passthrough().transform(s=>s),eP=zod.z.object({}).passthrough().transform(s=>s),tP=zod.z.object({}).passthrough().transform(s=>s),iP=zod.z.object({}).passthrough().transform(s=>s),Eh=zod.z.object({ServerTimeUtc:p,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:ZD,Resources:O.nullish(),Inventory:K.nullish()}),Uh=zod.z.object({ServerTimeUtc:p,AccrualID:zod.z.string(),AccruedSeconds:W.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:YD,Resources:O.nullish(),Inventory:K.nullish()}),qh=zod.z.object({ServerTimeUtc:p,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:XD,Resources:O.nullish(),Inventory:K.nullish()}),Lh=zod.z.object({ServerTimeUtc:p,ClaimID:zod.z.string(),ClaimState:eP,Resources:O.nullish(),Inventory:K.nullish()}),nP={None:"None",Ad:"Ad",Vip:"Vip"},Bh=zod.z.object({ServerTimeUtc:p,WindowID:zod.z.string(),Boost:zod.z.string().nullish(),BaseAmount:W.nullish(),Multiplier:zod.z.number().nullish(),Granted:W.nullish(),WindowState:tP,Resources:O.nullish(),Inventory:K.nullish()}),Gh=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:W.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),rP=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),sP=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:H.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Qi=zod.z.object({Gate:Z.nullish(),Limits:Se.nullish()}).passthrough(),Xa=zod.z.object({Availability:Q.nullish()}).passthrough(),oP=zod.z.object({Availability:zod.z.record(zod.z.string(),Qi).nullish()}).passthrough(),aP=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(sP).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:Qi.nullish(),Presets:Xa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),lP=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),uP=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(lP).nullish()}).passthrough(),cP=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Qi.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),pP=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:uP.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:cP.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),dP=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:H.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),hP=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(dP).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Qi.nullish(),Presets:Xa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),mP=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(),fP=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:H.nullish(),PremiumLimitOverrides:zod.z.array(mP).nullish(),Availability:Qi.nullish(),Presets:Xa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),gP=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(),el=zod.z.object({TierRewards:rP.nullish(),MilestoneRewardMultiplier:tn.nullish(),DailyCalendars:zod.z.record(zod.z.string(),aP).nullish(),IdleAccruals:zod.z.record(zod.z.string(),pP).nullish(),Comebacks:zod.z.record(zod.z.string(),hP).nullish(),Claims:zod.z.record(zod.z.string(),fP).nullish(),Windows:zod.z.record(zod.z.string(),gP).nullish(),Presets:oP.nullish()}).passthrough(),Fh=zod.z.object({RewardDefinitions:el.nullish()}),_h=zod.z.object({Rewards:iP.nullish()}),It={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var Ss=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(It.GetRewardDefinitions,e,Fh)}getUserRewardsState(e){return this.send(It.GetUserRewardsState,e,_h)}getMilestoneRewardMultiplier(e){return this.send(It.GetMilestoneRewardMultiplier,e,Gh)}claimDailyReward(e){return this.send(It.ClaimDailyReward,e,Eh)}collectIdleAccrual(e){return this.send(It.CollectIdleAccrual,e,Uh)}claimComebackReward(e){return this.send(It.ClaimComebackReward,e,qh)}claimReward(e){return this.send(It.ClaimReward,e,Lh)}claimRewardWindow(e){return this.send(It.ClaimRewardWindow,e,Bh)}};var xs=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(at.GetTutorialDefinitions,e,Xl)}getUserTutorialState(e){return this.send(at.GetUserTutorialState,e,sn)}startFlow(e){return this.send(at.StartFlow,e,Bt)}reportStepShown(e){return this.send(at.ReportStepShown,e,Bt)}completeStep(e){return this.send(at.CompleteStep,e,Bt)}completeStepsBatch(e){return this.send(at.CompleteStepsBatch,e,iu)}skipStep(e){return this.send(at.SkipStep,e,Bt)}skipFlow(e){return this.send(at.SkipFlow,e,Bt)}claimFlowReward(e){return this.send(at.ClaimFlowReward,e,tu)}resetFlow(e){return this.send(at.ResetFlow,e,Bt)}};var yP={Open:"Open",Application:"Application"},RP=zod.z.enum(["Open","Application"]).catch("Open"),CP={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Vh=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),SP={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},tl=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),xP={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var ri={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},bP=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(),Nh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:RP.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:Vh.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(bP).nullish()}).passthrough(),DP=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(),PP=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:tl.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(),DP).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),IP=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:tl.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),jh=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(PP).nullish(),Payouts:zod.z.array(IP).nullish()}).passthrough(),Wh=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:tl.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),vP=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),TP=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(vP).nullish()}).passthrough(),AP=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(),Kh=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:Vh.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(AP).nullish()}).passthrough(),wP=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),kP=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(wP).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(),Qh=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:TP.nullish(),SolanaSignature:kP.nullish(),StateDelta:Pi.nullish()}).passthrough();var bs=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(ri.GetCommunityMarketingState,e,Nh)}getEarnings(e){return this.send(ri.GetEarnings,e,jh)}claim(e){return this.send(ri.Claim,e,Wh)}checkJoinEligibility(e){return this.send(ri.CheckJoinEligibility,e,Kh)}withdrawCryptoReward(e){return this.send(ri.WithdrawCryptoReward,e,Qh)}};var Ds=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send($e.GetChatDefinitions,e,Gu)}getChannels(e){return this.send($e.GetChannels,e,Nn)}poll(e){return this.send($e.Poll,e,Fu)}getHistory(e){return this.send($e.GetHistory,e,_u)}getConversations(e){return this.send($e.GetConversations,e,ju)}sendMessage(e){return this.send($e.SendMessage,e,Vu)}openDirectChannel(e){return this.send($e.OpenDirectChannel,e,Nu)}markRead(e){return this.send($e.MarkRead,e,bi)}joinChannel(e){return this.send($e.JoinChannel,e,bi)}leaveChannel(e){return this.send($e.LeaveChannel,e,bi)}reportMessage(e){return this.send($e.ReportMessage,e,Wu)}ignoreUser(e){return this.send($e.IgnoreUser,e,bi)}unignoreUser(e){return this.send($e.UnignoreUser,e,bi)}};var Ps=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(Di.GetPushConfig,e,Hu)}subscribePush(e){return this.send(Di.SubscribePush,e,_o)}unsubscribePush(e){return this.send(Di.UnsubscribePush,e,Ge)}getPushSubscriptions(e){return this.send(Di.GetPushSubscriptions,e,$u)}};var Is=class extends B{constructor(e){super(e,"Localization");}send(e,t,i,n){let r=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${r}:${t.Locale}`:r,...n})}getLocalizationManifest(e){return this.send(os.GetLocalizationManifest,e,hh)}getLocalizationTable(e){return this.send(os.GetLocalizationTable,e,mh)}};var vs=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(ft.GetQuestDefinitions,e,rn)}getUserQuestState(e){return this.send(ft.GetUserQuestState,e,_l)}refreshQuestCycles(e){return this.send(ft.RefreshQuestCycles,e,Ge)}claimQuestReward(e){return this.send(ft.ClaimQuestReward,e,go)}claimQuestRewardsBatch(e){return this.send(ft.ClaimQuestRewardsBatch,e,jl)}claimMilestoneReward(e){return this.send(ft.ClaimMilestoneReward,e,yo)}claimMilestoneRewardsBatch(e){return this.send(ft.ClaimMilestoneRewardsBatch,e,Wl)}claimGroupCompletionReward(e){return this.send(ft.ClaimGroupCompletionReward,e,Vl)}addQuestProgress(e){return this.send(ft.AddQuestProgress,e,Nl)}};var Ts=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ut.GetActiveEvents,e,Jn)}getDefinitions(e){return this.send(ut.GetDefinitions,e,$n)}getUserLteState(e){return this.send(ut.GetUserLteState,e,Xu)}grantTokens(e){return this.send(ut.GrantTokens,e,O)}spendTokens(e){return this.send(ut.SpendTokens,e,jo)}claimMilestone(e){return this.send(ut.ClaimMilestone,e,Wo)}claimMilestonesBatch(e){return this.send(ut.ClaimMilestonesBatch,e,Ko)}claimAllMilestones(e){return this.send(ut.ClaimAllMilestones,e,Ko)}spendTokensBatch(e){return this.send(ut.SpendTokensBatch,e,ec)}grantTokensBatch(e){return this.send(ut.GrantTokensBatch,e,tc)}};var As=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(je.GetDefinitions,e,nr)}getLeaderboard(e){return this.send(je.GetLeaderboard,e,Li)}getMyProgress(e){return this.send(je.GetMyProgress,e,Yn)}submitScore(e){return this.send(je.SubmitScore,e,Xn)}submitScoreFromSource(e){return this.send(je.SubmitScoreFromSource,e,Xn)}claimCycleReward(e){return this.send(je.ClaimCycleReward,e,er)}claimMilestone(e){return this.send(je.ClaimMilestone,e,tr)}getFriendsLeaderboard(e){return this.send(je.GetFriendsLeaderboard,e,Li)}getLeaderboardsBatch(e){return this.send(je.GetLeaderboardsBatch,e,rc)}getProgressBatch(e){return this.send(je.GetProgressBatch,e,ir)}claimCycleRewardsBatch(e){return this.send(je.ClaimCycleRewardsBatch,e,sc)}claimMilestonesBatch(e){return this.send(je.ClaimMilestonesBatch,e,oc)}submitScoresBatch(e){return this.send(je.SubmitScoresBatch,e,ac)}claimAllRewardsBatch(e){return this.send(je.ClaimAllRewardsBatch,e,lc)}getOverviewBatch(e){return this.send(je.GetOverviewBatch,e,uc)}};var ws=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(_t.GetDefinitions,e,or)}getActiveSeason(e){return this.send(_t.GetActiveSeason,e,sr)}getUserState(e){return this.send(_t.GetUserState,e,Qo)}grantStatusTokens(e){return this.send(_t.GrantStatusTokens,e,hc)}claimTierReward(e){return this.send(_t.ClaimTierReward,e,Ho)}claimTierRewardsBatch(e){return this.send(_t.ClaimTierRewardsBatch,e,mc)}};var ks=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(ii.GetDefinitions,e,bh)}getUserState(e){return this.send(ii.GetUserState,e,Dh)}activateTrial(e){return this.send(ii.ActivateTrial,e,fs)}purchaseItemOrCurrency(e){return this.send(ii.PurchaseWithResources,e,Ie(fs))}purchaseRealMoney(e){return this.send(ii.PurchaseRealMoney,e,fs)}};var zs=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(We.GetCharacterDefinitions,e,cr)}getUserCharacters(e){return this.send(We.GetUserCharacters,e,Sc)}unlockCharacter(e){return this.send(We.UnlockCharacter,e,Ie(Yo))}upgradeStatLevel(e){return this.send(We.UpgradeStatLevel,e,Ie(Jo))}upgradeCharacterLevel(e){return this.send(We.UpgradeCharacterLevel,e,Ie(Zo))}equipItems(e){return this.send(We.EquipItems,e,xc)}unequipItems(e){return this.send(We.UnequipItems,e,bc)}unequipAllCharacters(e){return this.send(We.UnequipAllCharacters,e,Dc)}unlockCharactersBatch(e){return this.send(We.UnlockCharactersBatch,e,Ac)}upgradeCharacterLevelsBatch(e){return this.send(We.UpgradeCharacterLevelsBatch,e,wc)}upgradeStatLevelsBatch(e){return this.send(We.UpgradeStatLevelsBatch,e,kc)}unlockSkin(e){return this.send(We.UnlockSkin,e,Ie(Pc))}equipSkin(e){return this.send(We.EquipSkin,e,Ic)}unequipSkin(e){return this.send(We.UnequipSkin,e,vc)}getCharacterSkins(e){return this.send(We.GetCharacterSkins,e,Tc)}};var Ms=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(Dt.CreateMatch,e,pd)}updateMatch(e){return this.send(Dt.UpdateMatch,e,dd)}cancelMatch(e){return this.send(Dt.CancelMatch,e,hd)}instantBattle(e){return this.send(Dt.InstantBattle,e,md)}saveStrategy(e){return this.send(Dt.SaveStrategy,e,Ge)}getMyMatches(e){return this.send(Dt.GetMyMatches,e,Ta)}getAvailableMatches(e){return this.send(Dt.GetAvailableMatches,e,Ta)}getDefinitions(e){return this.send(Dt.GetDefinitions,e,Rd)}};var zP={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Hh=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),MP={None:"None",Min:"Min",Average:"Average",Max:"Max"},OP=zod.z.enum(["None","Min","Average","Max"]).catch("None"),EP={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},UP=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),qP={Clamp:"Clamp",Reject:"Reject"},LP=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),BP=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),GP=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:ho.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(BP).nullish()}),$h=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p,Type:Hh.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(GP).nullish()}),FP=zod.z.object({CraftID:zod.z.string().nullish(),Type:Hh.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:ae.nullish(),OutputLevelMode:OP.nullish(),InputSelection:UP.nullish(),OutputLevelOverflow:LP.nullish()}).passthrough(),il=zod.z.object({Definitions:zod.z.record(zod.z.string(),FP).nullish()}).passthrough(),Jh=zod.z.object({ServerTimeUtc:p.nullish(),CraftDefinitions:il.nullish()}),Os={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Es=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Os.GetDefinitions,e,Jh)}craft(e){return this.send(Os.Craft,e,Ie($h))}};var _P=2e5,Us=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,Ie(mr),{timeoutMs:_P,autoRetry:false})}readGeneration(e,t){return this.send(e,t,mr,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Le.GetDefinitions,e,Fc)}generateText(e){return this.generate(Le.GenerateText,e)}getText(e){return this.readGeneration(Le.GetText,e)}generateImage(e){return this.generate(Le.GenerateImage,e)}editImage(e){return this.generate(Le.EditImage,e)}getImage(e){return this.readGeneration(Le.GetImage,e)}generateVideo(e){return this.generate(Le.GenerateVideo,e)}getVideo(e){return this.readGeneration(Le.GetVideo,e)}generateAudio(e){return this.generate(Le.GenerateAudio,e)}getAudio(e){return this.readGeneration(Le.GetAudio,e)}generateMusic(e){return this.generate(Le.GenerateMusic,e)}getMusic(e){return this.readGeneration(Le.GetMusic,e)}generateFromTemplate(e){return this.generate(Le.GenerateFromTemplate,e)}estimateTemplatePrice(e){return this.send(Le.EstimateTemplatePrice,e,Gc,{throttleKey:`AI:EstimateTemplatePrice:${e.FeatureKey??""}:${JSON.stringify(e.Params??{})}`})}generateThreeD(e){return this.generate(Le.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Le.GetThreeD,e)}listGenerations(e){return this.send(Le.ListGenerations,e,Bc)}getGeneration(e){return this.readGeneration(Le.GetGeneration,e)}};var VP={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},NP=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),Zh=zod.z.object({}).passthrough().transform(s=>s),Ai=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()}),Yh=zod.z.object({GrantedCollectibles:zod.z.array(Ai).nullish(),DuplicateCollectibles:zod.z.array(Ai).nullish(),CollectionCurrencyEarned:W.nullish()}),Xh=zod.z.object({CreditsConfirmation:fe.nullish(),OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(Yh).nullish(),GrantedCollectibles:zod.z.array(Ai).nullish(),DuplicateCollectibles:zod.z.array(Ai).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.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()}),em=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(Yh).nullish(),GrantedCollectibles:zod.z.array(Ai).nullish(),DuplicateCollectibles:zod.z.array(Ai).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),tm=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),nl=zod.z.object({SetID:zod.z.string(),Resources:O.nullish(),Inventory:K.nullish()}),im=zod.z.array(we(nl)),nm=zod.z.object({Resources:O.nullish(),Inventory:K.nullish()}),jP=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:qe.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:NP.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RespondedAtUtc:p.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),rm=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:p.nullish(),Resources:O.nullish()}),sm=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),om=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()}),am=zod.z.object({OfferID:zod.z.string(),Resources:O.nullish()}),rl=zod.z.object({Offers:zod.z.array(jP).nullish()}),WP=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(),KP=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(WP).nullish(),SetCompletionReward:H.nullish()}).passthrough(),QP=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(KP).nullish(),GrandPrize:H.nullish()}).passthrough(),lm=zod.z.object({BonusRewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),HP=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:ae.nullish(),BonusRewardSlots:zod.z.array(vi).nullish(),PityRules:zod.z.array(Ti).nullish(),Presets:lm.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(),$P=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),JP=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(vi).nullish(),PityRules:zod.z.array(Ti).nullish(),Presets:lm.nullish(),Tier:zod.z.number().nullish()}).passthrough(),ZP=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),YP=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),qs=zod.z.object({Collections:zod.z.record(zod.z.string(),QP).nullish(),PackTypes:zod.z.record(zod.z.string(),HP).nullish(),CollectionChests:zod.z.array(JP).nullish(),DuplicateConversions:zod.z.array($P).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(ZP).nullish(),RewardPools:ys.nullish(),Settings:YP.nullish()}).passthrough(),Ke={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 Ls=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ke.GetDefinitions,e,qs)}getUserState(e){return this.send(Ke.GetUserState,e,Zh)}openPack(e){return this.send(Ke.OpenPack,e,Ie(Xh))}openCollectionChest(e){return this.send(Ke.OpenCollectionChest,e,em)}useCollectibleJoker(e){return this.send(Ke.UseCollectibleJoker,e,tm)}claimSetReward(e){return this.send(Ke.ClaimSetReward,e,nl)}claimSetRewardsBatch(e){return this.send(Ke.ClaimSetRewardsBatch,e,im)}claimGrandPrize(e){return this.send(Ke.ClaimGrandPrize,e,nm)}sendTradeOffer(e){return this.send(Ke.SendTradeOffer,e,rm)}cancelTradeOffer(e){return this.send(Ke.CancelTradeOffer,e,sm)}acceptTradeOffer(e){return this.send(Ke.AcceptTradeOffer,e,om)}declineTradeOffer(e){return this.send(Ke.DeclineTradeOffer,e,am)}getMyTradeOffers(e){return this.send(Ke.GetMyTradeOffers,e,rl)}getIncomingTradeOffers(e){return this.send(Ke.GetIncomingTradeOffers,e,rl)}};var Bs=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(yt.GetDefinitions,e,Rr)}getActiveEvent(e){return this.send(yt.GetActiveEvent,e,Nc)}getUserState(e){return this.send(yt.GetUserState,e,yr)}getGroupState(e){return this.send(yt.GetGroupState,e,ra)}joinOrCreateGroup(e){return this.send(yt.JoinOrCreateGroup,e,ra)}spin(e){return this.send(yt.Spin,e,Ie(Wc))}claimObjectReward(e){return this.send(yt.ClaimObjectReward,e,sa)}claimGrandPrize(e){return this.send(yt.ClaimGrandPrize,e,sa)}leaveGroup(e){return this.send(yt.LeaveGroup,e,Kc)}};var Gs=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(bt.GetDefinition,e,np)}getUserState(e){return this.send(bt.GetUserState,e,rp)}getActiveDeals(e){return this.send(bt.GetActiveDeals,e,xr)}dismissDeal(e){return this.send(bt.DismissDeal,e,op)}executeNode(e){return this.send(bt.ExecuteNode,e,Ie(sp))}recordShow(e){return this.send(bt.RecordShow,e,ap)}claimMilestone(e){return this.send(bt.ClaimMilestone,e,lp)}claimMilestonesBatch(e){return this.send(bt.ClaimMilestonesBatch,e,up)}};var XP=zod.z.object({}).passthrough().transform(s=>s),eI=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:Se.nullish()}).passthrough(),sl=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:zod.z.record(zod.z.string(),_e).nullish(),SpendRewards:zod.z.array(eI).nullish(),Qualification:zod.z.object({}).passthrough().transform(s=>s).nullish()}).passthrough(),ol=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(),um=zod.z.object({ReferralDefinitions:sl.nullish()}).passthrough(),cm=zod.z.object({Referral:XP.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:ol.nullish()}).passthrough(),pm=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:ol.nullish()}).passthrough(),dm=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:ol.nullish()}).passthrough(),al=zod.z.object({RewardID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),hm=St(al),Ht={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var Fs=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Ht.GetDefinitions,e,um)}getUserState(e){return this.send(Ht.GetUserState,e,cm)}activateReferralCode(e){return this.send(Ht.ActivateReferralCode,e,dm)}claimInviteReward(e){return this.send(Ht.ClaimInviteReward,e,al)}claimInviteRewardsBatch(e){return this.send(Ht.ClaimInviteRewardsBatch,e,hm)}checkQualification(e){return this.send(Ht.CheckQualification,e,pm)}};var _s=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(nt.GetDefinitions,e,mp)}getMessages(e){return this.send(nt.GetMessages,e,fp)}getUnreadCount(e){return this.send(nt.GetUnreadCount,e,Pr)}readMessages(e){return this.send(nt.ReadMessages,e,la)}claimReward(e){return this.send(nt.ClaimReward,e,Ir)}claimRewardsBatch(e){return this.send(nt.ClaimRewardsBatch,e,Ir)}claimAll(e){return this.send(nt.ClaimAll,e,Ir)}deleteMessages(e){return this.send(nt.DeleteMessages,e,la)}sendGift(e){return this.send(nt.SendGift,e,gp)}sendTransfer(e){return this.send(nt.SendTransfer,e,yp)}getGiftStatus(e){return this.send(nt.GetGiftStatus,e,Rp)}};var Vs=class extends B{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Tr.RequestAdPermit,e,Cp)}completeView(e){return this.send(Tr.CompleteView,e,Sp)}};var Ns=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(xe.GetFriendsList,e,Gi)}getIncomingRequests(e){return this.send(xe.GetIncomingRequests,e,Gi)}getOutgoingRequests(e){return this.send(xe.GetOutgoingRequests,e,Gi)}getRecommendedFriends(e){return this.send(xe.GetRecommendedFriends,e,Gi)}sendFriendRequest(e){return this.send(xe.SendFriendRequest,e,Fi)}acceptFriendRequest(e){return this.send(xe.AcceptFriendRequest,e,Fi)}declineFriendRequest(e){return this.send(xe.DeclineFriendRequest,e,Fi)}removeFriend(e){return this.send(xe.RemoveFriend,e,Fi)}getInbox(e){return this.send(xe.GetInbox,e,bp)}markInboxSeen(e){return this.send(xe.MarkInboxSeen,e,_i)}getInboxUnread(e){return this.send(xe.GetInboxUnread,e,_i)}follow(e){return this.send(xe.Follow,e,jt)}unfollow(e){return this.send(xe.Unfollow,e,jt)}getFollowers(e){return this.send(xe.GetFollowers,e,kr)}getFollowing(e){return this.send(xe.GetFollowing,e,kr)}block(e){return this.send(xe.Block,e,jt)}unblock(e){return this.send(xe.Unblock,e,jt)}getBlocked(e){return this.send(xe.GetBlocked,e,kr)}react(e){return this.send(xe.React,e,jt)}unreact(e){return this.send(xe.Unreact,e,jt)}getMyReactions(e){return this.send(xe.GetMyReactions,e,Pp)}getEntityStates(e){return this.send(xe.GetEntityStates,e,Dp)}addComment(e){return this.send(xe.AddComment,e,zr)}editComment(e){return this.send(xe.EditComment,e,zr)}deleteComment(e){return this.send(xe.DeleteComment,e,vp)}getComments(e){return this.send(xe.GetComments,e,Ip)}report(e){return this.send(xe.Report,e,Tp)}};var tI={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var si=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),iI=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:ae.nullish(),Effect:si.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(),js=zod.z.object({Schedule:Re.nullish(),Gate:Z.nullish()}).passthrough(),ll=zod.z.object({Availability:Q.nullish(),Effects:Q.nullish()}).passthrough(),nI=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(si).nullish(),Availability:js.nullish(),Presets:ll.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),rI=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(si).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),sI=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(rI).nullish(),Availability:js.nullish(),Presets:ll.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),oI=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(ot).nullish(),Effects:zod.z.array(si).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:js.nullish(),Presets:ll.nullish()}).passthrough(),aI=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),lI=zod.z.object({Effects:zod.z.array(si).nullish()}).passthrough(),uI=zod.z.object({Availability:zod.z.record(zod.z.string(),js).nullish(),Effects:zod.z.record(zod.z.string(),lI).nullish()}).passthrough(),cI=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),aI).nullish()}).passthrough(),Ws=zod.z.object({Definitions:zod.z.record(zod.z.string(),iI).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),nI).nullish(),BoostChains:zod.z.record(zod.z.string(),sI).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),oI).nullish(),Settings:cI.nullish(),Presets:uI.nullish()}).passthrough(),mm=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:si.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:p.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:p.nullish()}).passthrough();var fm=zod.z.object({ServerTimeUtc:p.nullish(),Active:zod.z.record(zod.z.string(),mm).nullish()}),gm=zod.z.object({CreditsConfirmation:fe.nullish(),ServerTimeUtc:p.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:mm.nullish(),Resources:O.nullish()}),pI={Scheduled:"Scheduled",Chain:"Chain"},dI=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:p.nullish(),EndUtc:p.nullish(),Effects:zod.z.array(si).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ym=zod.z.object({ServerTimeUtc:p.nullish(),Windows:zod.z.array(dI).nullish()}),oi={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Ks=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(oi.GetDefinitions,e,Ws)}getActive(e){return this.send(oi.GetActive,e,fm)}getActiveWindows(e){return this.send(oi.GetActiveWindows,e,ym)}activate(e){return this.send(oi.Activate,e,Ie(gm))}cleanupExpired(e){return this.send(oi.CleanupExpired,e,Ge)}};var Qs=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(Rt.GetUserCustomDataDefinitions,e,Ur)}getMyUserCustomData(e){return this.send(Rt.GetMyUserCustomData,e,zp)}getPublicUserCustomDataOf(e){return this.send(Rt.GetPublicUserCustomDataOf,e,ga)}setPrivateData(e){return this.send(Rt.SetPrivateData,e,ya)}setPublicData(e){return this.send(Rt.SetPublicData,e,ya)}deleteKey(e){return this.send(Rt.DeleteKey,e,Ge)}batchSet(e){return this.send(Rt.BatchSet,e,Mp)}batchDelete(e){return this.send(Rt.BatchDelete,e,Op)}batchGetPublicUserCustomDataOf(e){return this.send(Rt.BatchGetPublicUserCustomDataOf,e,Ep)}};var hI={Static:"Static",Runtime:"Runtime"},mI={Public:"Public",Private:"Private"},fI=zod.z.enum(["Client","Server","System"]).catch("Client"),gI=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),yI=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:p.nullish(),Version:zod.z.number().nullish(),LastWriter:fI.nullish(),ExpiresAt:p.nullish()}).passthrough(),Rm=zod.z.record(zod.z.string(),yI),ul=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:Rm.nullish(),Runtime:Rm.nullish(),NotModified:zod.z.boolean().nullish()}),RI=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:gI.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Hs=zod.z.object({Keys:zod.z.record(zod.z.string(),RI).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(),Hi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var $s=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Hi.GetTitleCustomDataDefinitions,e,Hs)}getPublicTitleData(e){return this.send(Hi.GetPublicTitleData,e,ul)}getPublicTitleDataKeys(e){return this.send(Hi.GetPublicTitleDataKeys,e,ul)}};var Cm=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 CI={Fast:"Fast",Sequential:"Sequential"},SI={Instant:"Instant",Timed:"Timed"};var xI={Hit:"Hit",Blocked:"Blocked"},bI=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),DI=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:H.nullish()}).passthrough();var PI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:H.nullish()}).passthrough(),II=zod.z.object({Reward:H.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(PI).nullish(),Rate:II.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 Sm=zod.z.object({}).passthrough().transform(s=>s),xm=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Qe=zod.z.object({Operation:O.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),vI=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),TI=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(),AI=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:pe.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(),wI=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:pe.nullish()}).passthrough(),bm=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:H.nullish()}).passthrough(),kI=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(),zI=zod.z.object({Tiles:zod.z.record(zod.z.string(),kI).nullish()}).passthrough(),MI=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Qe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),OI=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:Qe.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),EI=zod.z.object({Variants:zod.z.array(OI).nullish()}).passthrough(),UI=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:Qe.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),qI=zod.z.object({Outcomes:zod.z.array(UI).nullish()}).passthrough(),Dm=zod.z.object({PerAdMultiplierRange:xm.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),LI=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Qe.nullish()}).passthrough(),BI=zod.z.object({Tiers:zod.z.array(LI).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Qe.nullish()}).passthrough(),GI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Qe.nullish()}).passthrough(),FI=zod.z.object({Reward:Qe.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),_I=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(GI).nullish(),Rate:FI.nullish()}).passthrough(),Pm=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),_I).nullish()}).passthrough(),VI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ae.nullish(),Multipliers:Dm.nullish(),Gradation:BI.nullish(),RunStats:Pm.nullish()}).passthrough(),NI=zod.z.object({Choices:zod.z.array(VI).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),jI=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Qe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),WI=zod.z.object({OnPassStart:Qe.nullish(),OnTileLanding:zod.z.record(zod.z.string(),Qe).nullish(),OnAttack:zod.z.record(zod.z.string(),Qe).nullish(),OnRaid:zod.z.record(zod.z.string(),Qe).nullish(),OnBuild:Qe.nullish(),OnStageComplete:Qe.nullish(),OnAttackBonusDrops:zod.z.array(jI).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),qI).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),NI).nullish()}).passthrough(),Im=zod.z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(bm).nullish(),HeistGridBonusConfig:EI.nullish(),StageOperations:WI.nullish(),TileLandingMultiplier:xm.nullish(),EconomyOverride:wI.nullish()}).passthrough(),KI=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(bm).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:Im.nullish()}).passthrough(),QI=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(),HI=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(),Js=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(),zI).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),Im).nullish(),StagesByLevel:zod.z.record(zod.z.string(),KI).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:AI.nullish(),Dice:vI.nullish(),Bots:TI.nullish(),Targeting:QI.nullish(),BotRaids:HI.nullish()}).passthrough(),$I=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:p.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(),_e).nullish(),GrandPrize:H.nullish()}).passthrough(),Zs=zod.z.object({Board:Js.nullish(),CommunityChest:$I.nullish()}).passthrough(),vm=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),pe).nullish()}).passthrough(),JI=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:qe.nullish(),TargetBuildingStates:zod.z.array(bI).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:vm.nullish()}).passthrough(),ZI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ae.nullish(),Multipliers:Dm.nullish(),RunStats:Pm.nullish()}).passthrough(),YI=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(ZI).nullish()}).passthrough(),XI=zod.z.object({GroupID:zod.z.string().nullish(),Delta:W.nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),Tm=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:W.nullish(),LandedTileType:zod.z.string().nullish(),Operation:O.nullish(),Inventory:K.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:JI.nullish(),SpecialModeOffer:YI.nullish(),CommunityChestContribution:XI.nullish()}).passthrough(),Am=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:At.nullish()}).passthrough(),cl=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:H.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(DI).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:At.nullish(),RaidRewardPreview:vm.nullish()}).passthrough(),wm=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(),km=zod.z.object({CreditsConfirmation:fe.nullish(),Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:O.nullish(),Inventory:K.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish()}).passthrough(),zm=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),ev=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),Mm=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(ev).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),tv={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Om=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),iv={Active:"Active",Left:"Left",Replaced:"Replaced"},nv=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),rv=zod.z.object({CurrentProgress:W.nullish(),MaxProgress:W.nullish()}).passthrough(),sv=zod.z.object({UserID:zod.z.string().nullish(),PublicData:qe.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:W.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),Bl).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:nv.nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),Em=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(sv).nullish(),SharedProgress:rv.nullish(),Status:Om.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:zod.z.number().nullish()}).passthrough(),ov=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:Om.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:p.nullish()}).passthrough(),av=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(ov).nullish()}).passthrough(),Um=zod.z.object({ServerTimeUtc:p.nullish(),UserState:av.nullish(),ActiveGroup:Em.nullish(),SecondsRemaining:W.nullish()}),qm=zod.z.object({ServerTimeUtc:p.nullish(),Group:Em.nullish(),SecondsRemaining:W.nullish()}),pl=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Lm=zod.z.object({ServerTimeUtc:p.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Fe={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var lv={Mesh:"Mesh",Host:"Host"},dl=zod.z.enum(["Mesh","Host"]).catch("Mesh"),uv={ServerRelay:"ServerRelay",P2P:"P2P"},hl=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),cv={Public:"Public",Private:"Private"},pv=zod.z.enum(["Public","Private"]).catch("Public"),dv={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},hv=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Bm=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),mv=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Gm=zod.z.object({SystemState:mv.nullish(),DefaultTopology:dl.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:hl.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(Bm).nullish()}).passthrough(),fv=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(),gv=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:dl.nullish(),ChatMode:hl.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(),yv=zod.z.object({Seq:zod.z.number().nullish(),Type:hv.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(),$i=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:dl.nullish(),ChatMode:hl.nullish(),Visibility:pv.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(fv).nullish(),IceServers:zod.z.array(Bm).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Fm=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),_m=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),ml=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),Vm=zod.z.object({Rooms:zod.z.array(gv).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Nm=zod.z.object({Envelopes:zod.z.array(yv).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Ys=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),Ze={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 fl=zod.z.object({TitleCustomData:Hs.nullish(),Character:cr.nullish(),Item:cs.nullish(),Currency:_r.nullish(),Store:kn.nullish(),Lootbox:Ya.nullish(),Quest:rn.nullish(),TimedEvent:$n.nullish(),Leaderboard:nr.nullish(),Season:or.nullish(),Reward:el.nullish(),Collection:qs.nullish(),Craft:il.nullish(),DealOffer:oa.nullish(),Premium:$a.nullish(),TimedBoost:Ws.nullish(),CoopEvent:Rr.nullish(),GameLoop:Zs.nullish(),Match:Aa.nullish(),Experiment:th.nullish(),Blockchain:xa.nullish(),Marketplace:Oa.nullish(),Multiplayer:Gm.nullish(),UserCustomData:Ur.nullish(),Referral:sl.nullish(),Localization:ph.nullish(),Analytics:jd.nullish(),Social:Ap.nullish(),PlatformBridge:wp.nullish(),GameSpec:zod.z.string().nullish(),Look:Cm.nullish()}).passthrough();var ai={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Xs=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(ai.GetTitlePublicConfiguration,e,fl)}getTitlePublicConfigurationExcept(e){return this.send(ai.GetTitlePublicConfigurationExcept,e,fl)}getCurrencyDefinitions(e){return this.send(ai.GetCurrencyDefinitions,e,_r)}getItemDefinitions(e){return this.send(ai.GetItemDefinitions,e,cs)}getServerTime(e){return this.send(ai.GetServerTime,e,Ge)}};var eo=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Fe.GetGameLoops,e,Zs)}getBoardDefinition(e,t=false){return this.send(Fe.GetBoardDefinition,e,Js,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Fe.GetBoardDefinitionForLevel,e,Js,{silent:t})}getUserBoardState(e){return this.send(Fe.GetUserBoardState,e,Sm)}boardLoopRoll(e){return this.send(Fe.BoardLoopRoll,e,Tm)}boardLoopAttack(e){return this.send(Fe.BoardLoopAttack,e,Am)}boardLoopRaid(e){return this.send(Fe.BoardLoopRaid,e,cl)}boardLoopRaidFast(e){return this.send(Fe.BoardLoopRaidFast,e,cl)}boardLoopBuild(e){return this.send(Fe.BoardLoopBuild,e,wm)}boardSpecialChoose(e){return this.send(Fe.BoardSpecialChoose,e,Ie(km))}boardSpecialApplyMultiplier(e){return this.send(Fe.BoardSpecialApplyMultiplier,e,zm)}boardSpecialClaim(e){return this.send(Fe.BoardSpecialClaim,e,Mm)}getCommunityChestState(e){return this.send(Fe.GetCommunityChestState,e,Um)}joinOrCreateCommunityChest(e){return this.send(Fe.JoinOrCreateCommunityChest,e,qm)}claimCommunityChestMilestone(e){return this.send(Fe.ClaimCommunityChestMilestone,e,pl)}claimCommunityChestGrandPrize(e){return this.send(Fe.ClaimCommunityChestGrandPrize,e,pl)}leaveCommunityChest(e){return this.send(Fe.LeaveCommunityChest,e,Lm)}};var Rv={Live:"Live",Latest:"Latest",Specific:"Specific"},Cv={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},Sv=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),xv={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"},bv=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),Dv=zod.z.object({Level:Sv,Message:zod.z.string().nullish(),Data:Vt.nullish()}),Pv=zod.z.object({Error:bv,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Wm=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:Vt.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(Dv).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:Pv.nullish()}),gl={Execute:"Execute"};var to=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(gl.Execute,e,Wm)}};var io=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Je.GetDefinitions,e,Yp)}getUserState(e){return this.send(Je.GetUserState,e,Xp)}depositToken(e){return this.send(Je.DepositToken,e,ed)}depositNFT(e){return this.send(Je.DepositNFT,e,td)}requestTokenWithdrawal(e){return this.send(Je.RequestTokenWithdrawal,e,id)}requestNFTWithdrawal(e){return this.send(Je.RequestNFTWithdrawal,e,nd)}getTransactionHistory(e){return this.send(Je.GetTransactionHistory,e,rd)}retryWithdrawal(e){return this.send(Je.RetryWithdrawal,e,sd)}confirmWithdrawal(e){return this.send(Je.ConfirmWithdrawal,e,od)}donateToDeveloper(e){return this.send(Je.DonateToDeveloper,e,Ia)}donateToUsersPool(e){return this.send(Je.DonateToUsersPool,e,Ia)}getPlayAccess(e){return this.send(Je.GetPlayAccess,e,Jp)}confirmPlayAccess(e){return this.send(Je.ConfirmPlayAccess,e,Wt)}};var no=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Oe.GetDefinitions,e,Sd)}getGroupedOffers(e){return this.send(Oe.GetGroupedOffers,e,xd)}getOffersByItem(e){return this.send(Oe.GetOffersByItem,e,Ea)}getOffer(e){return this.send(Oe.GetOffer,e,bd)}getBuyOrders(e){return this.send(Oe.GetBuyOrders,e,Ea)}getMyState(e){return this.send(Oe.GetMyState,e,Hr)}getHistory(e){return this.send(Oe.GetHistory,e,Pd)}createListing(e){return this.send(Oe.CreateListing,e,Wi)}cancelListing(e){return this.send(Oe.CancelListing,e,ct)}buy(e){return this.send(Oe.Buy,e,ct)}marketBuy(e){return this.send(Oe.MarketBuy,e,ct)}marketSell(e){return this.send(Oe.MarketSell,e,ct)}createAuction(e){return this.send(Oe.CreateAuction,e,Wi)}placeBid(e){return this.send(Oe.PlaceBid,e,Dd)}claimAuction(e){return this.send(Oe.ClaimAuction,e,ct)}createBuyOrder(e){return this.send(Oe.CreateBuyOrder,e,Wi)}cancelBuyOrder(e){return this.send(Oe.CancelBuyOrder,e,ct)}fillBuyOrder(e){return this.send(Oe.FillBuyOrder,e,ct)}createDirectTrade(e){return this.send(Oe.CreateDirectTrade,e,Wi)}respondDirectTrade(e){return this.send(Oe.RespondDirectTrade,e,ct)}cancelDirectTrade(e){return this.send(Oe.CancelDirectTrade,e,ct)}claimBack(e){return this.send(Oe.ClaimBack,e,ct)}};var ro=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(Ze.CreateRoom,e,$i)}joinRoom(e){return this.send(Ze.JoinRoom,e,$i)}leaveRoom(e,t=false){return this.send(Ze.LeaveRoom,e,ml,{keepalive:t})}listRooms(e){return this.send(Ze.ListRooms,e,Vm)}getRoom(e){return this.send(Ze.GetRoom,e,$i)}closeRoom(e){return this.send(Ze.CloseRoom,e,ml)}poll(e){return this.send(Ze.Poll,e,Nm)}sendSignal(e){return this.send(Ze.SendSignal,e,Ys,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(Ze.ClaimHost,e,$i)}kickMember(e){return this.send(Ze.KickMember,e,Fm)}unbanMember(e){return this.send(Ze.UnbanMember,e,_m)}sendChat(e){return this.send(Ze.SendChat,e,Ys)}setMemberState(e){return this.send(Ze.SetMemberState,e,Ys)}};var Iv={Free:"Free",Price:"Price",Holding:"Holding"},yl=zod.z.enum(["Free","Price","Holding"]).catch("Free"),vv={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},Tv=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),Av={All:"All",Any:"Any"},wv=zod.z.enum(["All","Any"]).catch("All"),kv={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},zv=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),Mv={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},Ov=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),Ev={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Qm=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),Uv={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},qv={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},Lv=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),Bv=zod.z.object({Type:fi.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(),Gv=zod.z.object({Requirements:zod.z.array(Bv).nullish(),Match:wv.nullish(),Mode:Tv.nullish()}).passthrough(),Fv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:yl.nullish(),Price:pe.nullish(),Holding:Gv.nullish()}).passthrough(),_v=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(),Vv=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),_v).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(yl).nullish(),PricePolicy:Qr.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ae.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),Nv=zod.z.object({Allowed:zod.z.array(ji).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),jv=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),Wv=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(),Kv=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:Re.nullish(),Gate:Z.nullish(),Order:zod.z.number().nullish()}).passthrough(),Qv=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:Re.nullish(),ContentTypes:zod.z.record(zod.z.string(),Vv).nullish(),PricePolicy:Qr.nullish(),Commission:Ma.nullish(),HoldingPolicy:Nv.nullish(),Moderation:jv.nullish(),Limits:Wv.nullish(),Featured:zod.z.array(Kv).nullish()}).passthrough(),Hv=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(),li=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:qe.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:zv.nullish(),Access:zod.z.array(Fv).nullish(),Status:Ov.nullish(),ModerationNote:zod.z.string().nullish(),Stats:Hv.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),PublishedAt:p.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),$v=zod.z.object({OptionID:zod.z.string().nullish(),Mode:yl.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),Hm=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(),$m=zod.z.object({Definitions:Qv.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(Hm).nullish()}).passthrough(),so=zod.z.object({Items:zod.z.array(li).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Jm=zod.z.object({Content:li.nullish(),AccessState:zod.z.array($v).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Zm=zod.z.object({Collection:Hm.nullish(),Items:zod.z.array(li).nullish()}).passthrough(),Ym=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:qe.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(li).nullish()}).passthrough(),Km=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(),Xm=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(Km).nullish(),ThumbnailUpload:Km.nullish(),ExpiresAt:p.nullish()}).passthrough(),ef=zod.z.object({CreditsConfirmation:fe.nullish(),Content:li.nullish(),Resources:O.nullish()}).passthrough(),Rl=zod.z.object({Content:li.nullish()}).passthrough(),tf=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Qm.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:At.nullish(),Resources:O.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Jv=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),nf=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:Lv.nullish(),Files:zod.z.array(Jv).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:p.nullish()}).passthrough(),Zv=zod.z.object({ContentID:zod.z.string().nullish(),Source:Qm.nullish(),OptionID:zod.z.string().nullish(),PricePaid:pe.nullish(),AcquiredAt:p.nullish(),Content:li.nullish()}).passthrough(),rf=zod.z.object({Licenses:zod.z.array(Zv).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),He={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 oo=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(He.GetDefinitions,e,$m)}browse(e){return this.send(He.Browse,e,so)}getContent(e){return this.send(He.GetContent,e,Jm)}getCollection(e){return this.send(He.GetCollection,e,Zm)}getCreatorProfile(e){return this.send(He.GetCreatorProfile,e,Ym)}beginUpload(e){return this.send(He.BeginUpload,e,Xm)}publish(e){return this.send(He.Publish,e,Ie(ef))}updateContent(e){return this.send(He.UpdateContent,e,Rl)}unpublish(e){return this.send(He.Unpublish,e,Rl)}getMyContent(e){return this.send(He.GetMyContent,e,so)}acquire(e){return this.send(He.Acquire,e,tf)}getDownload(e){return this.send(He.GetDownload,e,nf)}getMyLicenses(e){return this.send(He.GetMyLicenses,e,rf)}getMyFavorites(e){return this.send(He.GetMyFavorites,e,so)}};var ao=class extends B{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,n){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${n}`})}sendPublic(e,t,i,n){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${n}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,kd,"defs")}get(e){return this.sendKeyed("Get",e,qa,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Md,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,La,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Od,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,Ba,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,Ba,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Ed,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,qd,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Ud,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,Ld,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,zd,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Bd,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,qa,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,La,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var lo=class{settings;emitter;platform;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;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.settings=Dl(e),this.emitter=new zi,this.platform=e.platform??new di,this.clientPlatform=e.clientPlatform??ql(),this.acquisition=new Jt(this.platform),this.acquisition.capture(),this.playtime=new Mi(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new pn({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 fn(this.emitter),this.cache=new yn(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:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new Rn(this.platform.storage,this.settings.titleID),this.api={authentication:new ss(this),user:new as(this),currency:new ls(this),item:new ps(this),store:new ds(this),purchase:new gs(this),lootbox:new Cs(this),reward:new Ss(this),quest:new vs(this),tutorial:new xs(this),communityMarketing:new bs(this),chat:new Ds(this),push:new Ps(this),localization:new Is(this),timedEvent:new Ts(this),leaderboard:new As(this),season:new ws(this),premium:new ks(this),character:new zs(this),match:new Ms(this),craft:new Es(this),ai:new Us(this),collection:new Ls(this),coopEvent:new Bs(this),dealOffer:new Gs(this),referral:new Fs(this),mailbox:new _s(this),advertising:new Vs(this),social:new Ns(this),timedBoost:new Ks(this),userCustomData:new Qs(this),titleCustomData:new $s(this),title:new Xs(this),gameLoop:new eo(this),cloudCode:new to(this),blockchain:new io(this),marketplace:new no(this),multiplayer:new ro(this),workshop:new oo(this),dataCollections:new ao(this),analytics:new ns(this),experiment:new rs(this)},this.userService=new Pn(this),this.cache.attachState(this.userService),this.auth=new Sn(this),this.currency=new vn(this),this.item=new Tn(this),this.store=new Mn(this),this.credits=new On(this),this.purchase=new En(this),this.checkout=new Un(this),this.lootbox=new qn(this),this.reward=new Bn(this),this.quest=new Hn(this),this.tutorial=new Fn(this),this.communityMarketing=new _n(this),this.chat=new jn(this),this.push=new Wn(this),this.localization=new Qn(this),this.timedEvent=new Zn(this),this.leaderboard=new rr(this),this.season=new ar(this),this.premium=new lr(this),this.character=new pr(this),this.match=new dr(this),this.craft=new hr(this),this.ai=new fr(this),this.collection=new gr(this),this.coopEvent=new Cr(this),this.dealOffer=new br(this),this.referral=new Dr(this),this.mailbox=new vr(this),this.ads=new wr(this),this.social=new Mr(this),this.timedBoost=new Or(this),this.userCustomData=new qr(this),this.titleCustomData=new Lr(this),this.title=new Br(this),this.gameLoop=new Gr(this),this.cloudCode=new Fr(this),this.blockchain=new Nr(this),this.marketplace=new $r(this),this.multiplayer=new Jr(this),this.workshop=new Zr(this),this.dataCollections=new Xr(this),this.analytics=new ts(this),this.experiments=new is(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.platform.getFullURL(),RelatedEntityID:G()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var uo=class{ctx;constructor(e){this.ctx=new lo(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let n=this.ctx.buildAuthedBaseRequest(),r=Qt(this.ctx.settings.titleID,e,t,n.UserID??"");return this.ctx.transport.post(r,{...n,...i},zod.z.unknown(),{ticket:n.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 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 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 platform(){return this.ctx.platform}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 Xv(s){return new uo(s)}var sf="idos_sso",of="state",Cl="idos:sso:state",eT="https://idosgames.com/sso/",tT=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],iT=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function nT(){if(typeof window>"u")return false;let{origin:s}=window.location;return tT.includes(s)||iT.test(s)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function rT(){if(typeof window>"u")return null;let s=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!s)return null;let e=new URLSearchParams(s),t=e.get(sf);if(!t)return null;let i=e.get(of)??"",n=uT();return pT(e),cT(),n&&i!==n?null:{code:t,state:i}}function sT(s){if(typeof window>"u")return;let e=s.returnTo??oT(),t=aT();lT(t);let i=new URL(s.ssoUrl??eT);i.searchParams.set("title",s.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function oT(){let{origin:s,pathname:e,search:t}=window.location;return `${s}${e}${t}`}function aT(){let s=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(s);else for(let e=0;e<s.length;e++)s[e]=Math.floor(Math.random()*256);return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}function lT(s){try{window.sessionStorage.setItem(Cl,s);}catch{}}function uT(){try{return window.sessionStorage.getItem(Cl)}catch{return null}}function cT(){try{window.sessionStorage.removeItem(Cl);}catch{}}function pT(s){s.delete(sf),s.delete(of);let e=s.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var dT={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 hT(s,e="Something went wrong. Please try again."){return s?dT[s]??s:e}function mT(s,e){return !!s?.Claims?.[e]?.ClaimedAt}function fT(s){let e=s?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function gT(s,e){return s?.Claims?.[e]?.PremiumTiers??[]}function lf(s,e,t,i=1){if(!s)return e;let n=s.Base??e,r=Math.max(0,t-i),o;switch(s.Shape??"Flat"){case "PerStep":o=n+(s.PerStep??0)*r;break;case "PerStepRate":o=n*(1+(s.PerStepRate??0)*r);break;case "Geometric":o=n*Math.pow(1+(s.GrowthRate??0),r);break;case "Table":o=n*af(s,t,1);break;case "TableAbsolute":o=af(s,t,n);break;default:o=n;break}return Number.isNaN(o)?n:(s.MinResult!=null&&o<s.MinResult&&(o=s.MinResult),s.MaxResult!=null&&o>s.MaxResult&&(o=s.MaxResult),o)}function yT(s,e,t=1){return lf(s,1,e,t)}function RT(s){if(!s)return false;switch(s.Shape??"Flat"){case "PerStep":return (s.PerStep??0)!==0;case "PerStepRate":return (s.PerStepRate??0)!==0;case "Geometric":return (s.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return uf(s.Points).length>0;default:return s.MinResult!=null||s.MaxResult!=null}}function CT(s){if(Number.isNaN(s)||s<=0)return 0;if(!Number.isFinite(s))return Number.MAX_SAFE_INTEGER;let e=Math.round(s);return Math.abs(s-e)<=1e-9*Math.max(1,Math.abs(s))?e:Math.ceil(s)}function uf(s){if(!s)return [];let e=[];for(let t of s)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function af(s,e,t){let i=uf(s.Points);if(i.length===0)return t;let n=null,r=null,o=null;for(let c of i)(o===null||c.AtStep>o.AtStep)&&(o=c),c.AtStep<=e&&(n===null||c.AtStep>=n.AtStep)&&(n=c),c.AtStep>e&&(r===null||c.AtStep<r.AtStep)&&(r=c);if(n===null)return t;if(r===null){let c=s.TailGrowthRate??0;return c===0?o.Value:o.Value*Math.pow(1+c,e-o.AtStep)}switch(s.Interpolation??"Step"){case "Linear":{let c=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value+c*(r.Value-n.Value)}case "Geometric":{if(n.Value<=0||r.Value<=0){let h=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value+h*(r.Value-n.Value)}let c=(e-n.AtStep)/(r.AtStep-n.AtStep);return n.Value*Math.pow(r.Value/n.Value,c)}default:return n.Value}}var ST={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Sl=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),xT={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},bT=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),DT=zod.z.object({PlacementID:zod.z.string().nullish(),Type:Sl.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(),PT=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(),IT=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),vT=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:bT.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),TT=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),AT=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),wT=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(),kT=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(),zT=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),MT=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:Sl.nullish()}).passthrough(),OT={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},ET=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),UT=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:ET.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(),MT).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),DT).nullish(),Providers:zod.z.record(zod.z.string(),UT).nullish(),RewardedVideo:PT.nullish(),Interstitial:IT.nullish(),Banner:vT.nullish(),AppOpen:TT.nullish(),FrequencyCapping:AT.nullish(),PremiumAdReductions:zod.z.array(wT).nullish(),Consent:kT.nullish(),Verification:zT.nullish()}).passthrough();var qT=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),LT=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:p.nullish(),LastCompletedAt:p.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),BT=zod.z.object({Date:p.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(),GT=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:p.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),FT=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:p.nullish(),ConsentRevokedAt:p.nullish()}).passthrough(),_T=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:Sl.nullish(),IssuedAt:p.nullish(),ExpiresAt:p.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),VT=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:p.nullish()}).passthrough();zod.z.object({Credits:qT.nullish(),Placements:zod.z.record(zod.z.string(),LT).nullish(),Daily:BT.nullish(),Session:GT.nullish(),LastImpressionAt:p.nullish(),LastInterstitialAt:p.nullish(),LastRewardedAt:p.nullish(),LastAppOpenAt:p.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:p.nullish(),Consent:FT.nullish(),PendingRequests:zod.z.record(zod.z.string(),_T).nullish(),FraudFlags:VT.nullish(),UpdatedAt:p.nullish()}).passthrough();var cf="idos_device_id",co=class{storage;constructor(e=new ci){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(cf);return e||(e="noop-device",this.storage.setString(cf,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};
|
|
2
|
+
exports.AIAction=Le;exports.AIErrorCode=QR;exports.AIGenerationStatus=ei;exports.AIModality=Nt;exports.AcquisitionCapture=Jt;exports.AdProviderKind=OT;exports.AdType=ST;exports.AdvertisingAction=Tr;exports.AnalyticsAction=Va;exports.AnalyticsDropReason=jb;exports.AnalyticsEventNaming=_a;exports.AnalyticsLimits=Pt;exports.AttackOutcome=xI;exports.AuthType=ze;exports.AuthenticationAction=Be;exports.AutomaticEvent=Kt;exports.BannerPosition=xT;exports.BlockchainAction=Je;exports.BlockchainNetworkType=XS;exports.BlockchainOperationCategory=Wp;exports.BlockchainTransactionStatus=lx;exports.BlockchainTransactionType=nx;exports.BodyPart=qx;exports.BoostWindowKind=pI;exports.BrowserPlatformAdapter=di;exports.BrowserStorage=ui;exports.CharacterAction=We;exports.ChatAction=$e;exports.ChatAuthorType=Ly;exports.ChatBlockedTermAction=Uy;exports.ChatChannelType=ky;exports.ChatDirectAudience=Oy;exports.ChatPartitioning=zy;exports.ChatReportReason=Gy;exports.ClientPlatform=Ct;exports.CloudCodeAction=gl;exports.CloudCodeErrorCode=xv;exports.CloudCodeLogLevel=Cv;exports.CloudCodeRevisionSelection=Rv;exports.CollectionAction=Ke;exports.CommissionSink=ib;exports.CommunityChestMemberStatus=iv;exports.CommunityChestStatus=tv;exports.CommunityCreatorStatus=CP;exports.CommunityMarketingAction=ri;exports.CommunityMetricKind=xP;exports.CommunityParticipationMode=yP;exports.CommunityPayoutCurrencyKind=SP;exports.ConversionRateMode=_S;exports.CoopEventAction=yt;exports.CoopGroupStatus=uC;exports.CoopMemberStatus=cC;exports.CraftAction=Os;exports.CraftInputSelectionMode=EP;exports.CraftOutputLevelMode=MP;exports.CraftOutputLevelOverflow=qP;exports.CraftType=zP;exports.CreditsConfirmationStatus=qi;exports.CreditsError=ry;exports.CurrencyAction=Vi;exports.CurrencyStatus=FS;exports.CurrencyType=ht;exports.CurveInterpolation=qf;exports.CurveShape=Ef;exports.CustomDataBucket=Ut;exports.CustomDataValueType=zS;exports.CustomDataWriter=TS;exports.DEFAULT_BASE_URL=bl;exports.DataAccessMode=bb;exports.DataCollectionKind=Rb;exports.DataCollectionSchemaMode=kb;exports.DataCollectionsAction=Gb;exports.DataCounterKind=vb;exports.DataFieldType=Sb;exports.DataFieldVisibility=xb;exports.DataOwnerDeletedPolicy=Ab;exports.DataRefKind=Pb;exports.DealComparisonOperator=AC;exports.DealNodeRuntimeStatus=SC;exports.DealNodeType=TC;exports.DealOfferAction=bt;exports.DealOfferActivationStatus=CC;exports.EVENT_NAME_PATTERN=es;exports.EnvelopeType=dv;exports.EventTokenType=xf;exports.ExperimentAction=Wa;exports.ExperimentGoalKind=tD;exports.FRIENDS_FROM_PLATFORM=DS;exports.FodderSelectionMode=mD;exports.FodderValuationMode=dD;exports.FriendActionStatus=cS;exports.FriendSource=pS;exports.GameLoopAction=Fe;exports.IDosGamesClient=uo;exports.IapProductType=TD;exports.IapPurchaseStatus=_D;exports.IapStoreValues=Sf;exports.ItemAction=us;exports.KycStatus=rx;exports.KycTier=ox;exports.LeaderboardAction=je;exports.LocalizationAction=os;exports.LocalizationMissingKeyMode=aD;exports.LootboxAction=Rs;exports.MAILBOX_COUNTER_CAP=ZC;exports.MailboxAction=nt;exports.MailboxCategory=WC;exports.MailboxErrors=JC;exports.MailboxLetterSource=KC;exports.MailboxRewardModule=HC;exports.MarketGoodsType=Kr;exports.MarketOfferStatus=tb;exports.MarketOfferType=eb;exports.MarketplaceAction=Oe;exports.MatchAction=Dt;exports.MatchStatus=Lx;exports.MemoryStorage=ci;exports.MultiplayerAction=Ze;exports.MultiplayerChatMode=uv;exports.MultiplayerTopology=lv;exports.NoopPlatformAdapter=co;exports.OFFER_NOT_IN_ROTATION=Py;exports.PLATFORM_AD_MESSAGES=da;exports.PLATFORM_AD_PROVIDER=pa;exports.PLATFORM_BRIDGE_ACK=fu;exports.PLATFORM_CREDITS_CONFIRM_MESSAGES=qo;exports.PLATFORM_ORIGINS=wt;exports.PLATFORM_PAGE_UNAVAILABLE=gu;exports.PLATFORM_SIGN_IN_MESSAGES=Ao;exports.PLATFORM_TOPUP_MESSAGES=Eo;exports.PlatformFriendsMode=IS;exports.PlatformProfileMode=PS;exports.PlayAccessMode=yx;exports.PlayerExperimentStatus=rD;exports.PlaytimeTracker=Mi;exports.PremiumAction=ii;exports.PurchaseAction=ni;exports.PushAction=Di;exports.PushPermissionState=Ot;exports.PushTopic=Xy;exports.PushTransport=Zy;exports.QuestAction=ft;exports.QuestObjectiveSource=Qf;exports.QuestPrerequisiteMode=$f;exports.QuestStatus=jf;exports.RaidMode=CI;exports.ReferralAction=Ht;exports.ResourceEntryType=Zi;exports.RewardAction=It;exports.RewardWindowBoost=nP;exports.RoomVisibility=cv;exports.SKIN_ALREADY_OWNED=KR;exports.SKIN_SLOT=ea;exports.ScheduleMode=bf;exports.SeasonAction=_t;exports.SocialAction=xe;exports.SocialContentStatus=gS;exports.SocialEntityType=hS;exports.SocialInboxVerb=yS;exports.SocialReactionKind=mS;exports.SocialReportReason=fS;exports.SpecialChoiceMode=SI;exports.StoreAction=Mt;exports.StoreRotationMode=ay;exports.StoreType=ID;exports.TimedBoostAction=oi;exports.TimedBoostStackingPolicy=tI;exports.TimedEventAction=ut;exports.TitleAction=ai;exports.TitleCustomDataAction=Hi;exports.TitleDataBucket=mI;exports.TitleDataScope=hI;exports.TradeOfferStatus=VP;exports.TransactionDirection=ux;exports.TutorialAction=at;exports.TutorialBoardAction=cg;exports.TutorialFlowStatus=ag;exports.TutorialGateMode=Af;exports.TutorialRestartPolicy=sg;exports.TutorialScriptModule=ug;exports.TutorialStepCompletionMode=ng;exports.TypedEmitter=zi;exports.UserAction=pt;exports.UserCustomDataAction=Rt;exports.WalletGateBalanceSource=mx;exports.WalletLinkType=tx;exports.WorkshopAccessMode=Iv;exports.WorkshopAccessVia=qv;exports.WorkshopAction=He;exports.WorkshopContentStatus=Mv;exports.WorkshopHoldingMatch=Av;exports.WorkshopHoldingMode=vv;exports.WorkshopLicenseSource=Ev;exports.WorkshopSort=Uv;exports.WorkshopVisibility=kv;exports.askPlatformPage=kt;exports.authErrorText=hT;exports.beginSsoRedirect=sT;exports.canPayWithPlatformCredits=Ay;exports.canUsePlatformAds=Ar;exports.canUsePlatformCreditsConfirm=Lo;exports.canUsePlatformSignIn=Ng;exports.canUsePlatformTopUp=Xt;exports.canUsePreviewSignIn=jg;exports.claimedMilestoneIDs=fT;exports.clearPlatformSignInDeclined=Kg;exports.createIDosGamesClient=Xv;exports.cryptoShortfallFromError=Ri;exports.curveMultiplier=yT;exports.defineView=Og;exports.describeUserAgent=Kd;exports.evaluateCurve=lf;exports.grantedPremiumTiers=gT;exports.isAIGenerationTerminal=Bi;exports.isCurveConfigured=RT;exports.isFail=Pf;exports.isMilestoneClaimed=mT;exports.isOk=Df;exports.isPlatformParentOrigin=Ui;exports.isPlatformSignInDeclined=Qg;exports.isReservedSlot=UR;exports.isSsoAvailable=nT;exports.markPlatformSignInDeclined=Wg;exports.normalizeBlockchainCategory=Vr;exports.parseAIErrorCode=HR;exports.readSsoCodeFromUrl=rT;exports.requestPlatformAd=ha;exports.requestPlatformCreditsConfirm=Bo;exports.requestPlatformSignIn=ko;exports.requestPlatformTopUp=Uo;exports.roundAmount=CT;exports.where=_b;exports.zPaymentProof=ny;exports.zPriceOption=An;exports.zPriceOptions=ae;
|