@idosgames/core 0.26.4 → 0.26.6
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/GameHost-xACJW0x5.d.cts +406 -0
- package/dist/GameHost-xACJW0x5.d.ts +406 -0
- package/dist/{VoiceController-BBp83r66.d.cts → VoiceController-BMXi4MNo.d.ts} +91 -113
- package/dist/{VoiceController-ClaEESTz.d.ts → VoiceController-BWb8NTp2.d.cts} +91 -113
- package/dist/chunk-YZ32MQXQ.js +2 -0
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +11 -29
- package/dist/index.d.ts +11 -29
- package/dist/index.js +2 -2
- package/dist/platform/index.cjs +2 -2
- package/dist/platform/index.d.cts +449 -2
- package/dist/platform/index.d.ts +449 -2
- package/dist/platform/index.js +1 -1
- package/dist/realtime/index.d.cts +3 -3
- package/dist/realtime/index.d.ts +3 -3
- package/package.json +1 -1
- package/dist/PlatformAdapter-DU_8HalI.d.cts +0 -34
- package/dist/PlatformAdapter-DU_8HalI.d.ts +0 -34
- package/dist/chunk-4VTWZXB4.js +0 -2
- package/dist/index-BCY6F_tf.d.cts +0 -197
- package/dist/index-YNXpT5ol.d.ts +0 -197
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {s,j,e,d,n,w,x,t,f}from'./chunk-4VTWZXB4.js';export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,y as NoopPlatformAdapter,h as PLATFORM_BRIDGE_ACK,u as PLATFORM_CREDITS_CONFIRM_MESSAGES,f as PLATFORM_ORIGINS,i as PLATFORM_PAGE_UNAVAILABLE,k as PLATFORM_SIGN_IN_MESSAGES,r as PLATFORM_TOPUP_MESSAGES,j as askPlatformPage,v as canPayWithPlatformCredits,w as canUsePlatformCreditsConfirm,l as canUsePlatformSignIn,s as canUsePlatformTopUp,m as canUsePreviewSignIn,p as clearPlatformSignInDeclined,g as isPlatformParentOrigin,q as isPlatformSignInDeclined,o as markPlatformSignInDeclined,x as requestPlatformCreditsConfirm,n as requestPlatformSignIn,t as requestPlatformTopUp}from'./chunk-4VTWZXB4.js';import {b,a,c}from'./chunk-CS7ACWDY.js';export{e as isFail,d as isOk}from'./chunk-CS7ACWDY.js';import {z}from'zod';import Jt from'decimal.js';var Pi=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,s=>{i(),t(s);});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 s of [...i])s(t);}removeAllListeners(){this.listeners.clear();}};function df(){let r=new Map;return {get:e=>r.get(e)??null,set:(e,t)=>{r.set(e,t);},remove:e=>{r.delete(e);}}}function ul(){return hf()??df()}function hf(){try{let r=globalThis.localStorage;if(!r)return null;let e="__idos_probe__";return r.setItem(e,"1"),r.removeItem(e),{get:t=>{try{return r.getItem(t)}catch{return null}},set:(t,i)=>{try{r.setItem(t,i);}catch{try{r.removeItem(t);}catch{}}},remove:t=>{try{r.removeItem(t);}catch{}}}}catch{return null}}var cl="https://api.idosgames.com";function pl(r){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??cl).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??ul(),locale:r.locale??mf(),appVersion:r.appVersion??""}}function mf(){try{return globalThis.navigator?.language??""}catch{return ""}}var uo="idos_acq",dl=["gclid","fbclid","ttclid","msclkid","yclid"],ff=["ref","r"],gf=["ref_","ref-","ref=","r_","r-"];var Ht=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();yf(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=Sf(this.platform.getDeviceModel());return s&&(i.OsVersion=s),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(uo);}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=fl(ml(t));if(i)return i}return ji(t)}readFromEnvironment(){let e={},t=ml(this.platform.getFullURL());Qt(e,"UtmSource",t.get("utm_source")),Qt(e,"UtmMedium",t.get("utm_medium")),Qt(e,"UtmCampaign",t.get("utm_campaign")),Qt(e,"UtmTerm",t.get("utm_term")),Qt(e,"UtmContent",t.get("utm_content")),Qt(e,"ClaimToken",t.get("idos_click"));for(let R of dl){let _=t.get(R);if(_){e.ClickID=_;break}}let i=this.platform.getStartParameter()??"",s=Cf(i);if(s){for(let R of Rf)Qt(e,R,s.get(gl[R])??null);for(let R of dl){let _=s.get(R);if(_){e.ClickID=_;break}}}let n=ji(s?s.get("ref")??s.get("r")??"":i),o=fl(t),c=n||o;c&&(e.ReferralCode=c,e.ChannelHint=n?"telegram":"query");let h=this.platform.getReferrer?.();return h&&(e.Referrer=h),e}read(){try{let e=this.platform.storage.getString(uo);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(uo,JSON.stringify(e));}catch{}}};function yf(r){return !!(r.UtmSource||r.UtmMedium||r.UtmCampaign||r.ClickID||r.Referrer||r.ReferralCode||r.ClaimToken)}function Qt(r,e,t){t&&(r[e]=t);}var hl="a1_",gl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},Rf=Object.keys(gl);function Cf(r){let e=(r||"").trim();if(!e.startsWith(hl))return null;let t=e.slice(hl.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),n=Uint8Array.from(s,h=>h.charCodeAt(0)),o=new TextDecoder().decode(n),c=new URLSearchParams(o);return [...c.keys()].length>0?c:null}catch{return null}}function ml(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function fl(r){for(let e of ff){let t=r.get(e);if(t)return ji(t)}return null}function ji(r){let e=(r||"").trim();if(!e)return null;for(let t of gf)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Sf(r){let e=r||"",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 yl="idos_usage_pending",Rl="idos_usage_session",Cl="idos_usage_closed_session",Sl="idos_usage_new_session",xl="idos_usage_last_activity",vi=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(yl),this.currentSessionSeconds=this.readNumber(Rl),this.pendingClosedSessionSeconds=this.readNumber(Cl),this.isNewSessionPending=this.readNumber(Sl)!==0;let e=this.readNumber(xl);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(yl,this.pendingSeconds),this.writeNumber(Rl,this.currentSessionSeconds),this.writeNumber(Cl,this.pendingClosedSessionSeconds),this.writeNumber(Sl,this.isNewSessionPending?1:0),this.writeNumber(xl,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"},ai=z.enum(["Virtual","Crypto"]).catch("Virtual"),Wi={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},li=z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),Ct={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Ki=z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),xf={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Qi=z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),bf={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Hi=z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),Df={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},Ti=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 Dl(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return bl(e);let t=r.cordova?.platformId;return t?bl(t):r.navigator?.userAgent??""?Ct.Web:Ct.Unknown}function bl(r){let e=r.toLowerCase();return e==="android"?Ct.Android:e==="ios"?Ct.Ios:e==="web"?Ct.Web:Ct.Unknown}var W=z.union([z.number(),z.string()]).transform((r,e)=>{let t=typeof r=="string"?Number(r):r;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(r)}`}),z.NEVER)}),Y=z.union([z.number(),z.string()]).transform((r,e)=>{let t=typeof r=="number"?String(r):r.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid decimal: ${String(r)}`}),z.NEVER):t}),p=z.string();var co=z.object({Type:li.nullish(),CurrencyID:z.string().nullish(),Amount:W.nullish(),AmountUsd:z.number().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ProductID:z.string().nullish()}),If=z.object({Type:Hi.nullish(),EntityID:z.string()}),Pf=z.object({Address:If.nullish(),Amount:W.nullish(),Source:z.string().nullish()}),ue=z.object({Entries:z.array(co).nullish(),EventTokens:z.array(Pf).nullish()}),Il=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Resources:ue.nullish()}),H=z.object({Standard:ue.nullish(),PremiumBonuses:z.array(z.unknown()).nullish(),PremiumTiers:z.array(Il).nullish()}),Tt=z.object({Standard:ue.nullish(),PremiumDiscounts:z.array(z.unknown()).nullish(),PremiumTiers:z.array(Il).nullish()}),O=z.object({Grant:H.nullish(),Consume:Tt.nullish()}),At=z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),FromResult:O.nullish(),ToResult:O.nullish()});z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Transferred:ue.nullish()});var vf=z.object({ExperimentID:z.string().nullish(),Variants:z.array(z.string()).nullish()}).passthrough(),Tf={Completed:"Completed",Started:"Started",StepReached:"StepReached"},Af=z.object({FlowIDs:z.array(z.string()).nullish(),Mode:z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:z.string().nullish(),Negate:z.boolean().nullish(),SkippedCountsAsCompleted:z.boolean().nullish()}).passthrough(),Z=z.object({Segments:z.array(z.string()).nullish(),MinPremiumTier:z.number().nullish(),RequiredPremiumIDs:z.array(z.string()).nullish(),MinLevel:z.number().nullish(),MaxLevel:z.number().nullish(),Countries:z.array(z.string()).nullish(),RegisteredWithinDays:z.number().nullish(),ActiveWithinDays:z.number().nullish(),Experiment:vf.nullish(),Tutorial:Af.nullish(),Platforms:z.array(Ki).nullish()}).passthrough();var Ce=z.object({TotalCap:z.number().nullish(),DailyCap:z.number().nullish(),DailyWeightCap:z.number().nullish(),PerActivationCap:z.number().nullish(),CooldownSeconds:z.number().nullish(),MaxPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish()}).passthrough();var kf=z.object({OffsetSecondsFromParentStart:z.number().nullish(),DurationSeconds:z.number().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),zf=z.object({StartUtc:z.string().nullish(),EndUtc:z.string().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),wf=z.object({AnchorUtc:z.string().nullish(),MaxCycles:z.number().nullish(),PauseBetweenPhasesSec:z.number().nullish(),PauseBetweenCyclesSec:z.number().nullish()}).passthrough();z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();var Mf=z.object({Reset:z.string().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:z.string().nullish(),PauseBetweenCyclesSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();z.object({SourceType:z.string().nullish(),TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),Outcome:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough();var ot=z.object({SourceType:z.string().nullish(),BaseWeight:z.number().nullish(),ScaleWithRollMultiplier:z.boolean().nullish(),TileTypeFilter:z.array(z.string()).nullish(),TileIndexFilter:z.array(z.number()).nullish(),ChanceOutcomeFilter:z.array(z.string()).nullish(),OutcomeFilter:z.array(z.string()).nullish(),Params:z.record(z.string(),z.string()).nullish(),Limits:Ce.nullish()}).passthrough(),ge=z.object({Mode:z.string().nullish(),IsActive:z.boolean().nullish(),Scheduled:zf.nullish(),Chain:wf.nullish(),Cyclic:Mf.nullish(),ActivationTriggers:z.array(ot).nullish(),Relative:kf.nullish()}).passthrough();var Of={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},Ef=z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Uf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},qf=z.enum(["Step","Linear","Geometric"]).catch("Step"),Bf=z.object({AtStep:z.number().nullish(),Value:z.number().nullish()}).passthrough(),_e=z.object({Base:z.number().nullish(),Shape:Ef.nullish(),PerStep:z.number().nullish(),PerStepRate:z.number().nullish(),GrowthRate:z.number().nullish(),Points:z.array(Bf).nullish(),Interpolation:qf.nullish(),TailGrowthRate:z.number().nullish(),MinResult:z.number().nullish(),MaxResult:z.number().nullish()}).passthrough();var Lf=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Rewards:H.nullish()}).passthrough(),Gf=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Multiplier:z.number().nullish()}).passthrough(),po=z.object({Bundles:z.array(Lf).nullish(),Multipliers:z.array(Gf).nullish()}).passthrough();var Ff=z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),$i=z.object({Source:Ff.nullish(),SourceKey:z.string().nullish(),Curve:_e.nullish(),Anchor:z.number().nullish(),IncludeRewards:ue.nullish(),ExcludeRewards:ue.nullish()}).passthrough(),Pl=z.object({ClaimedAt:z.string().nullish(),PremiumTiers:z.array(z.string()).nullish(),Unlocked:z.boolean().nullish()}).passthrough(),Ve=z.object({MilestoneID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredProgress:z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:po.nullish(),SortOrder:z.number().nullish(),IsFeatured:z.boolean().nullish()}).passthrough(),ui=z.object({Milestones:z.record(z.string(),Ve).nullish()}).passthrough();var Q=z.object({PresetID:z.string().nullish(),Remove:z.array(z.string()).nullish()}).passthrough();var Vf=z.object({TargetCurrencyID:z.string().nullish(),Rate:z.number().nullish(),MaxConvertAmount:z.number().nullish()}).passthrough(),$t=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxBalance:z.number().nullish(),MaxPerGrant:z.number().nullish(),DailyEarnCap:z.number().nullish(),BurnOnEventEnd:z.boolean().nullish(),BurnConversion:Vf.nullish()}).passthrough();var Nf=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),vl=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:Nf.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(r=>r),K=z.object({ChangedInstances:z.record(z.string(),vl).nullish(),RemovedInstanceIDs:z.array(z.string()).nullish()});var Te=r=>z.object({Id:z.string(),Success:z.boolean(),Error:z.string().nullish(),Data:r.nullish()}),St=r=>z.object({ServerTimeUtc:p,Items:z.array(Te(r)),Resources:O.nullish(),Inventory:K.nullish()});var _f={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},Tl=z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),jf=z.object({}).passthrough().transform(r=>r),Wf=z.object({CycleID:z.string(),InstanceKey:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),CycleStartUtc:p.nullish(),CycleEndUtc:p.nullish(),PointsTotalEarned:W.nullish(),PointsCurrent:W.nullish(),ClaimedPointMilestoneIDs:z.array(z.string()).nullish(),NextMilestone:Ve.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),ho=z.object({QuestID:z.string(),CycleID:z.string().nullish(),ObjectiveID:z.string().nullish(),NewValue:W.nullish(),ObjectiveCompleted:z.boolean().nullish(),Status:Tl}),Al=z.object({State:jf.nullish(),PointsTracks:z.record(z.string(),Wf).nullish()}),mo=z.object({ServerTimeUtc:p,QuestID:z.string(),CycleID:z.string().nullish(),NewStatus:Tl.nullish(),Resources:O.nullish(),Inventory:K.nullish()}),fo=z.object({ServerTimeUtc:p,CycleID:z.string(),MilestoneID:z.string(),PointsTotalEarned:W.nullish(),Resources:O.nullish(),Inventory:K.nullish(),NextMilestone:Ve.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),kl=z.object({ServerTimeUtc:p,CycleID:z.string(),GroupCompletionID:z.string(),GroupID:z.string().nullish(),CompletedGroupQuests:z.number().nullish(),RequiredGroupQuests:z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),zl=z.object({MetricID:z.string(),Updates:z.array(ho).nullish()}),wl=z.array(Te(mo)),Ml=z.array(Te(fo)),Kf={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Qf=z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Hf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},$f=z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),Ol=z.object({ObjectiveID:z.string().nullish(),Source:Qf.nullish(),MaxProgressPerCall:z.number().nullish(),MetricID:z.string().nullish(),Triggers:z.array(ot).nullish(),TargetValue:z.number().nullish(),AggregationMethod:z.string().nullish()}).passthrough(),go=z.object({Milestones:Q.nullish(),Linking:Q.nullish(),Availability:Q.nullish(),Reward:Q.nullish(),Objectives:Q.nullish()}).passthrough(),Jf=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),El=z.object({CycleIDs:z.array(z.string()).nullish(),GroupID:z.string().nullish(),PhaseIDs:z.array(z.string()).nullish(),RequiredQuestIDs:z.array(z.string()).nullish(),PrerequisiteMode:$f.nullish()}).passthrough(),Ul=z.object({Schedule:ge.nullish(),AccrueProgressWhenLocked:z.boolean().nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),ql=z.object({Grant:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),Zf=z.object({QuestID:z.string().nullish(),Identity:Jf.nullish(),Linking:El.nullish(),Availability:Ul.nullish(),Objectives:z.record(z.string(),Ol).nullish(),Reward:ql.nullish(),Presets:go.nullish()}).passthrough(),Yf=z.object({CompletionID:z.string().nullish(),GroupID:z.string().nullish(),RequiredCompletedQuests:z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),Xf=z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Gate:Z.nullish(),Milestones:z.record(z.string(),Ve).nullish(),Presets:go.nullish(),PointsToken:$t.nullish()}).passthrough(),eg=z.object({Milestones:z.record(z.string(),ui).nullish(),Linking:z.record(z.string(),El).nullish(),Availability:z.record(z.string(),Ul).nullish(),Reward:z.record(z.string(),ql).nullish(),Objectives:z.record(z.string(),z.record(z.string(),Ol)).nullish()}).passthrough(),tg=z.object({CycleID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:ge.nullish(),Milestones:z.record(z.string(),Ve).nullish(),Gate:Z.nullish(),PointsToken:$t.nullish(),GroupCompletions:z.record(z.string(),Yf).nullish(),Phases:z.record(z.string(),Xf).nullish(),Presets:go.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Zi=z.object({Cycles:z.record(z.string(),tg).nullish(),Quests:z.record(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"},sg=z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),ng={Never:"Never",OnRequest:"OnRequest",Always:"Always"},rg=z.enum(["Never","OnRequest","Always"]).catch("Never"),og={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},ag=z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),lg={GameLoop:"GameLoop"},ug={Raid:"Raid",Attack:"Attack"},cg=z.object({Title:z.string().nullish(),TitleKey:z.string().nullish(),Body:z.string().nullish(),BodyKey:z.string().nullish(),AnchorID:z.string().nullish(),HighlightTarget:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),UiHint:z.record(z.string(),z.string()).nullish()}).passthrough(),pg=z.object({Mode:sg.nullish(),Triggers:z.array(ot).nullish(),TargetValue:z.number().nullish(),RequireAllTriggers:z.boolean().nullish()}).passthrough(),dg=z.object({Grant:H.nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),hg=z.object({TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),RandomActionType:z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),mg=z.object({Module:z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:hg.nullish(),MaxUses:z.number().nullish()}).passthrough(),fg=z.object({Skippable:z.boolean().nullish(),TimeoutSeconds:z.number().nullish()}).passthrough(),yo=z.object({StepID:z.string().nullish(),Order:z.number().nullish(),Identity:cg.nullish(),Completion:pg.nullish(),Effects:dg.nullish(),Script:mg.nullish(),Policy:fg.nullish()}).passthrough(),gg=z.object({DisplayName:z.string().nullish(),DisplayNameKey:z.string().nullish(),Description:z.string().nullish(),DescriptionKey:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Bl=z.object({Schedule:ge.nullish(),Gate:Z.nullish(),RequiredFlowIDs:z.array(z.string()).nullish(),AutoStart:z.boolean().nullish(),StartTrigger:ot.nullish()}).passthrough(),Ll=z.object({Skippable:z.boolean().nullish(),SkippableFromOrder:z.number().nullish(),RestartPolicy:rg.nullish(),ExpireAfterSeconds:z.number().nullish(),IsBlocking:z.boolean().nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),Gl=z.object({Grant:H.nullish(),AutoClaim:z.boolean().nullish()}).passthrough(),yg=z.object({Availability:Q.nullish(),Policy:Q.nullish(),Reward:Q.nullish(),Steps:Q.nullish()}).passthrough(),Rg=z.object({FlowID:z.string().nullish(),Identity:gg.nullish(),Availability:Bl.nullish(),Policy:Ll.nullish(),Steps:z.record(z.string(),yo).nullish(),Reward:Gl.nullish(),Presets:yg.nullish()}).passthrough(),Cg=z.object({BlockingFlowIDs:z.array(z.string()).nullish(),BlockedModules:z.array(z.string()).nullish(),BlockedActions:z.record(z.string(),z.array(z.string())).nullish(),BlockBeforeStart:z.boolean().nullish(),SkipLiftsBlock:z.boolean().nullish()}).passthrough(),Sg=z.object({IsEnabled:z.boolean().nullish(),MaxActiveFlows:z.number().nullish(),Blocking:Cg.nullish()}).passthrough(),xg=z.object({Availability:z.record(z.string(),Bl).nullish(),Policy:z.record(z.string(),Ll).nullish(),Reward:z.record(z.string(),Gl).nullish(),Steps:z.record(z.string(),z.record(z.string(),yo)).nullish()}).passthrough(),Fl=z.object({Flows:z.record(z.string(),Rg).nullish(),Settings:Sg.nullish(),Presets:xg.nullish()}).passthrough(),bg=z.object({}).passthrough().transform(r=>r),Vl=z.object({FlowID:z.string(),Status:ag,CurrentStepID:z.string().nullish(),CurrentStep:yo.nullish(),TotalSteps:z.number(),CompletedSteps:z.number(),CanSkip:z.boolean(),RewardClaimed:z.boolean(),RewardPending:z.boolean(),VariantID:z.string().nullish()}).passthrough(),Yi=z.object({State:bg.nullish(),Flows:z.array(Vl).nullish(),UnlockedFeatures:z.array(z.string()).nullish()}).passthrough(),qt=z.object({Flow:Vl.nullish()}).passthrough(),Nl=z.object({FlowID:z.string().nullish(),Granted:O.nullish()}).passthrough(),_l=z.array(Te(qt)),jl=z.object({FlowID:z.string(),StepID:z.string(),Progress:z.number(),Target:z.number(),Completed: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 Xi(r){return Array.isArray(r)?r.filter(e=>e!==null).map(Xi):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,Xi(t)])):r}var es=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 ts=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Wl(r){return r===429||r>=500&&r<=599}function is(r,e=Math.random){let t=Math.min(500*Math.pow(2,r-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Bt(r){return new Promise(e=>setTimeout(e,r))}var Kl=15e3;async function Ql(r){try{let t=JSON.parse(await r.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(r.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Hl(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function $l(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var Ro=15,Jl=1e3,ss=class{constructor(e=Ro,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]>=Jl;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(Jl-(e-this.starts[0])+5);}}};var Dg=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function pi(r){if(!r)return null;let e=Dg.exec(r);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new Jt(i),o=new Jt(s),c=o.minus(Jt.max(n,0));return c.lte(0)?null:{currencyID:t,required:o.toNumber(),available:n.toNumber(),missing:c.toNumber(),missingAmount:c.toFixed()}}var Ig=12e3,Pg=new Set(["RelatedEntityID"]);function vg(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[i,s]of Object.entries(e))Pg.has(i)||(t[i]=s);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var Tg=z.object({Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().optional(),QuestProgress:z.array(ho).nullish(),TutorialProgress:z.array(jl).nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish()}).passthrough(),ns=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new ts;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 es(e.throttleMs),this.pacer=new ss(e.maxRequestsPerSecond??Ro),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,s={}){let n=s.throttleKey??vg(e,t);if(!this.throttler.tryAcquire(n))return b("throttled","Throttled");if(!this.inflight.add(n))return b("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,c=JSON.stringify(t),h=s.ticket??null,R=s.silent??!1,_=s.timeoutMs??Ig,ce=s.autoRetry??!0,Ae=!1,Re=!1,Ue=0;for(;;){let vt;s.keepalive||await this.pacer.take();try{vt=await this.doFetch(o,c,h,_,s.keepalive??!1);}catch{if(ce&&Ue<3){Ue++,await Bt(is(Ue));continue}return this.connectionFailure("Internet Connection Error",R)}let Xe=vt.status;if(Xe>=200&&Xe<300){let re=!Re&&this.cryptoTopUpHandler!==null,ve=await this.parseSuccess(vt,i,R,e,re);if(!ve.ok&&re){let pe=pi(ve.error);if(pe){if(Re=!0,await this.runTopUp(pe))continue;R||this.emitter.emit("error:global",ve.error);}}return ve}if(Xe===401){if(!Ae&&this.sessionRefreshHandler){Ae=!0;let re=null;try{re=await this.sessionRefreshHandler();}catch{re=null;}if(re){h=re;continue}}return this.emitter.emit("auth:unauthorized",void 0),b("unauthorized","Unauthorized")}if(Wl(Xe)){let re=Xe===429?await Ql(vt):null;if(re!==null&&re>Kl)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(re/1e3)} s`,R);if(ce&&Ue<3){Ue++,await Bt(re!==null?Hl(re):Xe===429?$l(Ue):is(Ue));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Xe})`,R)}let bi="";try{bi=await vt.text();}catch{}if(Xe===409&&/operation in progress/i.test(bi)&&ce&&Ue<3){Ue++,await Bt(is(Ue));continue}return this.handleWebError(bi,Xe,R)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let o=new AbortController,c=setTimeout(()=>{o.abort();},s);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,...n?{keepalive:!0}:{}})}finally{clearTimeout(c);}}async parseSuccess(e,t,i,s,n=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 Re=h.data.Error??"Server returned Success=false",Ue=n&&pi(Re);return !i&&!Ue&&this.emitter.emit("error:global",Re),b("server",Re)}let R=h.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:h.data.StateEpoch??null,versions:R});let _=h.data.QuestProgress;_&&_.length>0&&this.emitter.emit("quest:systemProgress",_);let ce=h.data.TutorialProgress;ce&&ce.length>0&&this.emitter.emit("tutorial:systemProgress",ce);let Ae=t.safeParse(h.data.Data);if(!Ae.success){let Re=t.safeParse(Xi(h.data.Data));Re.success&&(Ae=Re);}if(!Ae.success){let Re=`Validation error (${s}): ${Ae.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",Re),i||this.emitter.emit("error:global",Re),b("validation",Re)}return a(Ae.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),b("server","PLAY_ACCESS_REQUIRED");s=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),b("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),b("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),b("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 di(r){return (typeof r=="string"?r:r.toISOString()).slice(0,10)}function Ai(r){return `${di(r)}T00:00:00.000Z`}function Zl(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Yl(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function xo(r,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;r.InventoryV2??={};let n=r.InventoryV2,o=i.toISOString(),c=new Map,h=new Map,R=new Map,_=new Map,ce=new Map,Ae=new Map,Re=new Map,Ue=new Map,vt=e.Grant?.PremiumTiers??[],Xe=vt.length;for(let re=0;;re++){let ve,pe;if(re===0)ve=e.Grant?.Standard?.Entries,pe=false;else if(re-1<Xe)ve=vt[re-1]?.Resources?.Entries,pe=false;else if(re===1+Xe)ve=e.Consume?.Standard?.Entries,pe=true;else break;if(ve)for(let le of ve){if(le.Type==null)continue;let de=Math.max(0,le.Amount??0);if(!(de<=0))switch(le.Type){case "VirtualCurrency":{if(!le.CurrencyID)continue;let he=pe?h:c;he.set(le.CurrencyID,(he.get(le.CurrencyID)??0)+de);break}case "CryptoCurrency":{if(!le.CurrencyID)continue;let he=pe?_:R;he.set(le.CurrencyID,(he.get(le.CurrencyID)??new Jt(0)).plus(de));break}case "Item":{if(!le.ItemID)continue;let he=kg(t,le.CatalogID,le.ItemID),be=(he?he.IsStackable??true:true)?pe?Ae:ce:pe?Ue:Re;be.set(le.ItemID,(be.get(le.ItemID)??0)+de);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=c.size>0||h.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let re of new Set([...c.keys(),...h.keys()])){let ve=c.get(re)??0,pe=h.get(re)??0,le=ve-pe,de=n.VirtualCurrencies[re];de?(de.Amount+=le,de.UpdatedAt=o,de.Daily&&di(de.Daily.PeriodStartUtc)===di(i)?(de.Daily.Earned+=ve,de.Daily.Spent+=pe):de.Daily={PeriodStartUtc:Ai(i),Earned:ve,Spent:pe}):n.VirtualCurrencies[re]={Amount:le,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:Ai(i),Earned:ve,Spent:pe}};}}if(s.ccChanged=R.size>0||_.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let re of new Set([...R.keys(),..._.keys()])){let ve=R.get(re)??new Jt(0),pe=_.get(re)??new Jt(0),le=ve.minus(pe),de=n.CryptoCurrencies[re];de?(de.Amount=new Jt(de.Amount).plus(le).toString(),de.UpdatedAt=o):n.CryptoCurrencies[re]={Amount:le.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(s.itemsChanged=ce.size>0||Ae.size>0||Re.size>0||Ue.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let re=n.UnstackableItems,ve=new Set([...ce.keys(),...Ae.keys(),...Re.keys(),...Ue.keys()]);for(let pe of ve){let le=(ce.get(pe)??0)-(Ae.get(pe)??0),de=(Re.get(pe)??0)-(Ue.get(pe)??0),he=le+de,rt=n.Items[pe];rt?(le!==0&&(rt.StackableAmount+=le),de!==0&&(rt.UnstackableAmount+=de),he!==0&&(rt.TotalAmount+=he)):n.Items[pe]={StackableAmount:Math.max(0,le),UnstackableAmount:Math.max(0,de),TotalAmount:Math.max(0,he)};}for(let[pe,le]of Ue){if(le<=0)continue;let de=Object.values(re).filter(he=>he.ItemID===pe&&he.EquippedSlot==null&&(he.ExpiresAt==null||new Date(he.ExpiresAt)>i)).sort(Ag).slice(0,le).map(he=>he.ItemInstanceID);for(let he of de)delete re[he];}for(let[pe,le]of Re){let de=zg(t,pe);for(let he=0;he<le;he++){let rt=d();re[rt]={ItemInstanceID:rt,ItemID:pe,CatalogID:de,RemainingUses:1,AcquiredAt:o};}}}r.EventToken??={};let bi=r.EventToken;for(let re=0;;re++){let ve,pe;if(re===0)ve=e.Grant?.Standard?.EventTokens,pe=false;else if(re-1<Xe)ve=vt[re-1]?.Resources?.EventTokens,pe=false;else if(re===1+Xe)ve=e.Consume?.Standard?.EventTokens,pe=true;else break;if(!(!ve||ve.length===0))for(let le of ve){let de=le.Address;if(!de||de.Type==null)continue;let he=le.Amount??0;if(he<=0)continue;let rt=wg(bi,de.Type);if(!rt)continue;let be=rt[de.EntityID];be||(be={},rt[de.EntityID]=be),be.Balance??={Current:0,TotalEarned:0,TotalSpent:0},be.Daily??={Date:Ai(i),TotalEarned:0},be.Meta??={};let Di=le.Source&&le.Source.length>0?le.Source:"CustomAction";pe?(be.Balance.Current-=he,be.Balance.TotalSpent+=he):(be.Balance.Current+=he,be.Balance.TotalEarned+=he,di(be.Daily.Date)!==di(i)&&(be.Daily={Date:Ai(i),TotalEarned:0}),be.Daily.TotalEarned+=he,be.Daily.EarnedBySource??={},be.Daily.EarnedBySource[Di]=(be.Daily.EarnedBySource[Di]??0)+he,be.Daily.TriggersBySource??={},be.Daily.TriggersBySource[Di]=(be.Daily.TriggersBySource[Di]??0)+1,be.Daily.LastTriggerBySource??={},be.Daily.LastTriggerBySource[Di]=o,be.Meta.JoinedAtUtc||(be.Meta.JoinedAtUtc=o),be.Meta.LastEarnedAtUtc=o),s.tokensChanged=true;}}return s}function Ag(r,e){return r.AcquiredAt!==e.AcquiredAt?r.AcquiredAt<e.AcquiredAt?-1:1:r.ItemInstanceID===e.ItemInstanceID?0:r.ItemInstanceID<e.ItemInstanceID?-1:1}function kg(r,e,t){let i=r?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let n=s.Items?.[t];if(n)return n}}}function zg(r,e){let t=r?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function wg(r,e){switch(e){case "TimedEvent":return r.TimedEvent??={};case "Quest":return r.Quest??={};case "Leaderboard":return r.Leaderboard??={};case "CoopEvent":return r.CoopEvent??={};case "Season":return r.Season??={};default:return null}}function Xl(r,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},n=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let h of Object.values(s))h?.ItemID&&o.add(h.ItemID);for(let h of n){let R=r[h]?.ItemID;R&&o.add(R);}if(o.size===0)return i;let c=h=>n.has(h)||h in s;if(e){for(let[h,R]of Object.entries(e))h in r||c(h)||R&&o.has(R.ItemID)&&i.drop.push(h);for(let[h,R]of Object.entries(r))h in e||c(h)||R&&o.has(R.ItemID)&&(i.restore[h]=R);}return i}function bo(r,e){return r===e||r.startsWith(`${e}:`)}var os=class r{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let 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){r.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];r.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){r.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let s=xo(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let n=this.currentState,o={...n.InventoryV2?.UnstackableItems??{}},c=xo(n,e,i,s),h=Xl(o,n.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),_=t?.RemovedInstanceIDs??[],ce=h.drop.length>0||Object.keys(h.restore).length>0||R.length>0||_.length>0;if(ce){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let Ae=n.InventoryV2.UnstackableItems;for(let Re of h.drop)delete Ae[Re];for(let[Re,Ue]of Object.entries(h.restore))Ae[Re]=Ue;for(let[Re,Ue]of R)Ae[Re]=Ue;for(let Re of _)delete Ae[Re];}this.emitResourceChanges(c,ce);}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,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof Jt?t:new Jt(t),c=s===void 0?new Jt(0):s instanceof Jt?s:new Jt(s),h=i??new Date().toISOString(),R=n[e];R?(R.Amount=new Jt(R.Amount).plus(o).toString(),c.isZero()||(R.Frozen=new Jt(R.Frozen??0).plus(c).toString()),R.UpdatedAt=h):n[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 s=this.currentState.Store.Purchases,n=s[e];n||(n={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=n),n.TotalPurchases+=t,n.LastPurchasedAt=i,i>=n.DailyResetUtc?(n.DailyPurchases=t,n.DailyResetUtc=Zl(i)):n.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 s=this.currentState.Lootbox??={};if(s.Pity??={},t){let n=new Date().toISOString();for(let o of t)o.RuleID&&(s.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:n});}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 s=this.currentState.Quest;if(t){s.Cycles??={};let n=s.Cycles[t];if(!n)return;n.Quests??={};let o=n.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let n=s.PermanentQuests[e]??={QuestID:e,Status:i};n.Status=i,i==="Claimed"&&(n.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 s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,n=t[s]??={};n.Balance??={Current:0,TotalEarned:0,TotalSpent:0},n.Balance.Current=i.PointsCurrent??0,n.Balance.TotalEarned=i.PointsTotalEarned??0,n.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(n.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 s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let n=s.Steps[i.StepID]??={StepID:i.StepID};n.Progress=i.Progress,i.Completed&&(n.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let n=t.Cycles[i.CycleID];if(!n)continue;n.Quests??={},s=n.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let n=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};n.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(n.Completed=true,n.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(bo(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[n,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((s?n!==s:!bo(n,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let n=this.activeEventsCache?.ActiveEvents;if(n)for(let o of n)o.Type!==e||o.TimedEventID!==t||s&&o.TokenEntityID&&o.TokenEntityID!==s||(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,s){if(!e)return;let n=this.ensureLeaderboardProgress(e);(n.ScoreCycleVersion??0)<s&&(n.ScoreEarnedThisCycle=0,n.ClaimedMilestoneIDs=[],n.BracketID=null),n.CurrentScore=t,n.ScoreEarnedThisCycle=(n.ScoreEarnedThisCycle??0)+i,n.ScoreCycleVersion=s,n.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 s=false;for(let n of Object.values(i))for(let o of Object.values(n.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.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[s,n]of Object.entries(e.ChangedInstances??{}))t[s]=n,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],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 s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.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 s of Object.keys(i)){let n=i[s];n&&n.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}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,s,n){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,c={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??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 s=i.BuildingStates.find(n=>n.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let 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 s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},n=s.PendingWithdrawals??[];t.size>0&&(n=n.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!n.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(n=[...n,i]),s.PendingWithdrawals=n;}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 as=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 ls=class{user;config;constructor(e){this.user=new os(e),this.config=new as;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Mg(r){return r}var Og=0,Eg=1500,Ug=3,cs=class{constructor(e,t,i=null,s="",n="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=s;this.loginMode=n;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 a(void 0);let i=Date.now(),s=[],n=[];for(let h of new Set(e)){let R=this.rules.get(h);if(R&&(t?.force||R.needsServer(i))){s.push(this.runRule(h,R));continue}(t?.force||!this.state.isStateFresh(h,t?.maxAgeMs))&&n.push(h);}let c=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(a(void 0))])).find(h=>!h.ok);return c&&!c.ok?c:a(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}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(s=>i=s);try{let s=this.state?await this.state.readStateSlice(e):a(void 0),n=s.ok?a(void 0):s;for(let o of t)o(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=us(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let R=this.fresh(s,i?.maxAgeMs);if(R)return a(R.data);let _=this.loginFailures.get(s);if(_)return this.loginFailures.delete(s),_;let ce=this.inflight.get(s);if(ce)return ce}let n=this.generation.get(s)??0,o=Date.now(),h=t().then(R=>{if(!R.ok)return R;let _=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:R.data,storedAt:_,expiresAt:Do(e,R.data,_)}),R;let ce=this.entries.get(s);if(ce&&ce.storedAt>=o)return R;let Ae=Do(e,R.data,_);return this.entries.set(s,{data:R.data,storedAt:_,expiresAt:Math.min(Ae??1/0,_+Eg)}),R}).finally(()=>{this.inflight.get(s)===h&&this.inflight.delete(s);});return this.inflight.set(s,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 s=t.Key?t.Key:void 0,n=us(i.view,s);if(!t.Success){this.loginFailures.set(n,b("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(n),i.apply(o.data,s),this.put(i.view,o.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let n=eu({Name:s,Key:t});this.used.get(n)?.n!==this.session&&(this.used.set(n,{Name:s,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(eu(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(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(us(e,t))?.data}put(e,t,i){this.register(e);let s=us(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:Do(e,t,n)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===i||s.startsWith(`${i}|`))&&this.drop(s);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 s=Date.now();if(!(i.expiresAt!==null&&s>=i.expiresAt)&&!(t!==void 0&&s-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(s=>t.has(s))&&this.invalidate(i);}};function us(r,e){return e===void 0?r.key:`${r.key}|${e}`}function eu(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function Do(r,e,t){let i=r.expiresAt?.(e)??null,s=r.ttlMs!==void 0?t+r.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var ps=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(r){return r!==null&&Object.values(ze).includes(r)}var Bg=8,Lg=100,Gg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,tu=["GameLoop"];function Fg(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var ds=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 s=this.authContext;if(!s)return c;let n=this.baseRequest();n.UserID=s.userID,n.ClientSessionTicket=s.clientSessionTicket,n.WalletAddress=e,n.NetworkID=t,i&&(n.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(n);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return c;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(i);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.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 b("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 s=await this.ctx.api.authentication.loginWithEmail(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(ze.Email);return n.ok&&this.keepEmailCredentials(e,t),n}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 s=await this.ctx.api.authentication.registerWithEmail(i);return s.ok?(this.pendingRegistration={email:e,password:t},a({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(ze.Email);return n.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,n}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?a(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 b("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 s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(ze.Apple)):s}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 s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=i,s.Platform=this.ctx.platform.getPlatform(),s.Device=this.ctx.platform.getDeviceModel(),s.DeviceID=this.ctx.platform.getDeviceID();let n=await this.ctx.api.authentication.loginWithWallet(s);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(ze.Wallet)):n}async loginWithSsoCode(e){if(!e)return b("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 b("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 s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=i,this.ctx.api.authentication.resetPassword(s)}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 s=await this.ctx.api.authentication.refreshSession(i);return s.ok?(this.applyRefresh(s.data),"ok"):(Fg(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,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(b("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 n(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let s=await this.ctx.api.authentication.resolvePlatformGameSession(i);return s.ok?(this.applyAuthContext(s.data),this.platformGameSession=!0,s.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==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&&Gg.test(e)}static isValidPasswordLength(e){return e.length>=Bg&&e.length<=Lg}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(tu,tu);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 Vg="idos:cfg",hi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${iu(t)}`:e&&e.length>0?`f:${iu(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 s={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${Vg}:${this.titleId}:${e}`}};function iu(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var su="idos:loc",mi=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 s={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[s,n]of Object.entries(t))typeof n=="number"&&n>0&&(i[s]=n);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 `${su}:${this.titleId}:${e}`}versionsKey(){return `${su}:${this.titleId}:versions`}};var Ng="idos:sec",hs=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 `${Ng}:${this.titleId}`}};var _g="idos:state",ms=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,s){if(!(!e||!t))try{let n={e:t,v:i,s};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}keyOf(e){return `${_g}:${this.titleId}:${e}`}};function jg(r,e){if(!r)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return r;let i={};for(let[s,n]of Object.entries(r))t.has(s.toLowerCase())||(i[s]=n);return i}function Io(r,e,t,i){let s={...r??{}};if(!e||!t||!i)return s;for(let[n,o]of Object.entries(t))i[n]===o&&n in e&&(s[n]=e[n]);return s}function Wg(r){return {...r??{}}}function Po(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.StateEpoch:null}var fs=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 s=this.confirmedAt[e];return s===void 0?false:t===void 0||i-s<=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=jg(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 n=Object.keys(this.versions);this.reset(e),this.notify(n);}return}let i=Date.now(),s=[];for(let[n,o]of Object.entries(t)){let c=this.versions[n];c!==o&&(c!==void 0&&o===c+1?(this.versions[n]=o,this.confirmedAt[n]=i):(delete this.versions[n],delete this.confirmedAt[n]),s.push(n),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=Wg(t);let s=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=s;this.dirty=true;let n=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&n.add(o);this.notify([...n]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[n,o]of Object.entries(t??{}))this.versions[n]!==o&&s.push(n),this.versions[n]=o,this.confirmedAt[n]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var nu=b("server","Title configuration is unavailable (CDN and API both failed)."),gs=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:d()}:null}get configCache(){return this.cache??=new hi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new mi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new hs(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new fs(new ms(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 c;let t=hi.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let n=await this.ctx.api.user.getClientState(e);if(!n.ok)return n;let o=await this.resolveTitleConfig(n.data,t,i,{Fields:e.TitleFields});return o==null?nu:(this.finishStateHandshake(n.data,s),await this.restoreSections(n.data.TitleConfigVersion,o),await this.applyClientState(n.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(n.data.Views),await this.applyLocalization(n.data.Localization),await this.flushState(s),n)}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 s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let n=this.stateStore.currentEpoch;n&&(e.KnownStateEpoch=n);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=Io(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=Po(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,i,s){let n=e.TitleConfigVersion;if(i&&n&&i.v===n)return i.c;if(e.TitleConfigUrl){let c=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(c!=null)return n&&await this.configCache.write(t,n,c),c}let o=await this.fetchConfigFromApi(s);return o!=null?(n&&await this.configCache.write(t,n,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},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return c;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=hi.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let c$1=await this.ctx.api.user.getClientStateExcept(i);if(!c$1.ok)return c$1;let h=await this.resolveTitleConfig(c$1.data,s,n,{ExcludeFields:t??[]});return h==null?nu:(this.finishStateHandshake(c$1.data,o),await this.restoreSections(c$1.data.TitleConfigVersion,h),await this.applyClientState(c$1.data,h,e,t),this.ctx.cache.acceptLoginViews(c$1.data.Views),await this.applyLocalization(c$1.data.Localization),await this.flushState(o),c$1)}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,s={};for(let[n,o]of Object.entries(await this.sectionCache.read(e)))i[n]==null&&(s[n]=o);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((n,o)=>{i[n]!=null||o==null||(s[n]=o,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let 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 s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let n=await this.fetchLocalizationFromApi(t,s?.v??0);return n??s?.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 s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let n=s.data;if(n.NotModified)return null;let o=n.Entries??{},c=n.Version??0,h=n.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)):c}async getUserState(e){let t=this.baseRequest();if(!t)return c;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let n=Io(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let o=i.sent??{},c$1=Object.entries(s.data.StateVersions??{}).filter(([R,_])=>o[R]!==_||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(n,c$1);let h=Po(s.data);return h&&(this.stateStore.afterSliceRead(h,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return c;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 c;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 c;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 s=this.baseRequest();if(!s)return c;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=i;let n=await this.ctx.api.user.addUsageTime(s);return n.ok&&this.ctx.emitter.emit("user:usageTimeAdded",n.data),n}async deleteUserAccount(){let e=this.baseRequest();if(!e)return c;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 c;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,s){let n=i?.includes("GameLoop")===true,o=s?.includes("GameLoop")===true,c=n?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 R=this.ctx.data.user.state;n&&R&&R.GameLoop==null&&(R.GameLoop=c);let _=this.ctx.data.config.titlePublicConfiguration;o&&_&&_.GameLoop==null&&(_.GameLoop=h),this.ctx.emitter.emit("user:clientStateReceived",e);}};var Rs=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return b("client","SpendID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${d()}`},s=await this.ctx.api.currency.spend(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",s.data)),s}async convert(e,t,i,s,n,o){if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(n<=0)return b("client","Amount must be positive.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===ht.Crypto||i===ht.Crypto)return b("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return c;let c$1={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(n)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${s}_${d()}`},h=await this.ctx.api.currency.convert(c$1);if(h.ok){let R=h.data,_={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.SourceID,Amount:R.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.TargetID,Amount:R.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(_,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return h}async cryptoConvert(e,t,i,s,n,o){let c$1=n instanceof Jt?n:new Jt(n);if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(c$1.lte(0))return b("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===ht.Virtual&&i===ht.Virtual)return b("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ht.Virtual&&!c$1.isInteger())return b("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return c;let h={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:c$1.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${s}_${d()}`},R=await this.ctx.api.currency.cryptoConvert(h);if(R.ok){let _=R.data,ce=[],Ae=[];if(_.SourceType===ht.Virtual&&ce.push({Type:"VirtualCurrency",CurrencyID:_.SourceID,Amount:Math.trunc(Number(_.SourceSpent))}),_.TargetType===ht.Virtual&&Ae.push({Type:"VirtualCurrency",CurrencyID:_.TargetID,Amount:Math.trunc(Number(_.TargetCredited))}),ce.length>0||Ae.length>0){let Re={Consume:ce.length>0?{Standard:{Entries:ce}}:null,Grant:Ae.length>0?{Standard:{Entries:Ae}}:null};this.ctx.data.user.applyResourceOperation(Re,this.ctx.data.config.itemDefinitions);}_.SourceType===ht.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(_.SourceID,new Jt(_.SourceSpent).negated(),_.ServerTimeUtc),_.TargetType===ht.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(_.TargetID,new Jt(_.TargetCredited),_.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",_);}return R}};var Cs=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i,s){let n=e.trim();if(!n)return b("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:n,SelectedOptionID:i,CreditsConfirmationID:s,RelatedEntityID:`upgrade_item_${n}_${d()}`};t&&t.length>0&&(o.FodderInstanceIDs=[...t]);let c$1=await this.ctx.api.item.upgradeLevel(o);return c$1.ok&&!c$1.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(c$1.data.ItemInstanceID??n,c$1.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",c$1.data)),c$1}async upgradeLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let s of i.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var Ss=z.object({OptionID:z.string().nullish(),Name:z.string().nullish(),Cost:Tt.nullish(),AllowedPlatforms:z.array(Ki).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),oe=z.record(z.string(),Ss),Kg=z.object({Store:Qi,Receipt:z.string(),Signature:z.string().nullish()}).passthrough();var ki={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},me=z.object({ConfirmationID:z.string(),Url:z.string(),Status:z.string(),PriceCredits:z.number(),ExpiresAt:p}).passthrough(),ru=z.object({Linked:z.boolean(),Credits:z.number(),TopUpUrl:z.string().nullish()}).passthrough(),Qg={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"},vo=z.object({ServerTimeUtc:p,OfferID:z.string(),Count:z.number(),Resources:O.nullish(),Inventory:K.nullish(),CreditsConfirmation:me.nullish()}),ou=z.array(Te(vo)),Hg=z.object({OfferID:z.string(),TotalPurchases:z.number(),DailyPurchases:z.number(),DailyResetUtc:p,LastPurchasedAt:p}),$g=z.object({SlotKey:z.string(),InstanceKey:z.string(),OfferID:z.string().nullish(),Purchases:z.number(),LastPurchasedAt:p}),au=z.object({Purchases:z.record(z.string(),Hg).nullish(),Rotations:z.record(z.string(),$g).nullish()}).passthrough().transform(r=>r),kt=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),xs=z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Jg={Fixed:"Fixed",Title:"Title",Player:"Player"},Zg=z.object({OfferID:z.string().nullish(),Weight:z.number().nullish(),Gate:Z.nullish()}).passthrough(),lu=z.object({Mode:z.string().nullish(),OfferID:z.string().nullish(),Pool:z.array(Zg).nullish(),Salt:z.string().nullish(),PerInstanceCap:z.number().nullish()}).passthrough(),Yg=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Rotation:Q.nullish()}).passthrough(),Xg=z.object({SlotID:z.string().nullish(),Identity:kt.nullish(),Availability:xs.nullish(),Rotation:lu.nullish(),Presets:Yg.nullish()}).passthrough(),ey=z.object({Identity:Q.nullish(),Availability:Q.nullish()}).passthrough(),ty=z.object({SectionID:z.string().nullish(),Identity:kt.nullish(),Availability:xs.nullish(),Slots:z.record(z.string(),Xg).nullish(),UniqueOffersInSection:z.boolean().nullish(),Presets:ey.nullish()}).passthrough(),uu=z.object({Sections:z.record(z.string(),ty).nullish()}).passthrough(),iy=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Layout:Q.nullish()}).passthrough(),sy=z.object({StoreID:z.string().nullish(),Identity:kt.nullish(),Availability:xs.nullish(),Layout:uu.nullish(),Presets:iy.nullish()}).passthrough(),cu=z.object({Options:oe.nullish(),CompareAt:z.record(z.string(),Tt).nullish()}).passthrough(),pu=z.object({Grant:H.nullish()}).passthrough(),du=z.object({Schedule:ge.nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),ny=z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish(),Availability:Q.nullish()}).passthrough(),ry=z.object({OfferID:z.string().nullish(),Identity:kt.nullish(),Pricing:cu.nullish(),Reward:pu.nullish(),Availability:du.nullish(),Presets:ny.nullish()}).passthrough(),oy=z.object({Identity:z.record(z.string(),kt).nullish(),Availability:z.record(z.string(),xs).nullish(),Layout:z.record(z.string(),uu).nullish(),Rotation:z.record(z.string(),lu).nullish(),Pricing:z.record(z.string(),cu).nullish(),Reward:z.record(z.string(),pu).nullish(),OfferAvailability:z.record(z.string(),du).nullish()}).passthrough(),bs=z.object({Stores:z.record(z.string(),sy).nullish(),StoreOffers:z.record(z.string(),ry).nullish(),Presets:oy.nullish()}).passthrough(),ay=z.object({PurchasedTotal:z.number(),PurchasedToday:z.number(),PurchasedThisRotation:z.number(),RemainingTotal:z.number().nullish(),RemainingToday:z.number().nullish(),IsFirstPurchaseAvailable:z.boolean(),SoldOut:z.boolean(),AvailableAtUtc:p.nullish()}).passthrough(),ly=z.object({OptionID:z.string(),Name:z.string().nullish(),Cost:Tt.nullish(),CompareAtCost:Tt.nullish(),DiscountPercent:z.number().nullish(),IsFree:z.boolean(),IsAdPaid:z.boolean(),IsStorePaid:z.boolean(),IsCreditsPaid:z.boolean().nullish(),CreditsPrice:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),uy=z.object({OfferID:z.string(),Identity:kt.nullish(),PriceOptions:z.array(ly).nullish(),Rewards:H.nullish(),State:ay.nullish()}).passthrough(),cy=z.object({SlotID:z.string(),Identity:kt.nullish(),SortOrder:z.number(),RotationMode:z.string().nullish(),RotationInstanceKey:z.string().nullish(),RefreshesAtUtc:p.nullish(),RemainingThisRotation:z.number().nullish(),Offer:uy.nullish()}).passthrough(),py=z.object({SectionID:z.string(),Identity:kt.nullish(),SortOrder:z.number(),Slots:z.array(cy).nullish()}).passthrough(),dy=z.object({StoreID:z.string(),Identity:kt.nullish(),SortOrder:z.number(),ScheduleInstanceKey:z.string().nullish(),ExpiresAtUtc:p.nullish(),Sections:z.array(py).nullish()}).passthrough(),Ds=z.object({ServerTimeUtc:p,Stores:z.array(dy).nullish(),AdCreditBalance:z.number()}).passthrough(),zt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},hy="OFFER_NOT_IN_ROTATION";var hu="Store",mu={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=null;for(let t of r.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},Is=class{constructor(e){this.ctx=e;e.cache.bindLoginView(mu,{schema:Ds,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return b("client","OfferID is required.");if(t<1)return b("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return c;let n={...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}_${s.userID}_${d()}`},o=await this.ctx.api.store.purchase(n);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(s=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:s}),{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}):c}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):c}async purchaseBatch(e){if(!e||e.length===0)return b("client","purchases is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||!n.Data.OfferID||(this.ctx.data.user.patchStorePurchase(n.Data.OfferID,n.Data.Count,n.Data.ServerTimeUtc),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(hu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(hu,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(mu,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return c;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 s of i.Slots??[]){let n=s.RefreshesAtUtc;n&&(e===null||Date.parse(n)<Date.parse(e))&&(e=n);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 Ps=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 s=i.data.CreditsConfirmation,n=()=>e(s.ConfirmationID);if(w()){let h=await x({titleID:this.ctx.settings.titleID,confirmationID:s.ConfirmationID});if(h.ok)return await n();if(h.error==="DECLINED")return b("server","CREDITS_CONFIRMATION_DECLINED");if(h.error==="NOT_ENOUGH_CREDITS")return b("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(s);let o=Math.max(1e3,t.pollMs??2500),c=Date.parse(s.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return b("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>c)return b("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(_=>setTimeout(_,o));let h=await this.ctx.store.getCreditsConfirmation(s.ConfirmationID);if(!h.ok)continue;let R=h.data.Status;if(R!==ki.Pending)return R===ki.Declined?b("server","CREDITS_CONFIRMATION_DECLINED"):R===ki.Expired?b("server","CREDITS_CONFIRMATION_EXPIRED"):await n()}}};var vs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return c;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return c;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?a(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return b("client","Receipt is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},n=await this.ctx.api.purchase.validatePurchase(s);return n.ok&&this.applyValidation(n.data),n}async buyWithTelegramStars(e,t){if(!e)return b("client","productID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(i);return s.ok&&t?.open!==false&&this.ctx.platform.openInvoice(s.data.InvoiceLink),s}async validatePurchasesBatch(e){if(!e||e.length===0)return b("client","receipts is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let s of i.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var fu=3,my=700,Ts=class{constructor(e){this.ctx=e;s()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return pi(e)}platformTopUp=async e=>{let t$1=this.ctx.auth.context?.userID;if(!t$1)return false;let i=await t({titleID:this.ctx.settings.titleID,userID:t$1,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<=fu;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===fu)break;await Bt(my);}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===Wi.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!==Wi.CryptoCurrency||!i.CurrencyID)continue;let s=Number(i.Amount??0);if(!(s>0))continue;let n=this.cryptoBalance(i.CurrencyID);return n>=s?null:{currencyID:i.CurrencyID,required:s,available:n,missing:s-n}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var gu="Lootbox",As=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(gu,e);if(t){let n={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection(gu,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s,n){if(!e)return b("client","LootboxID is required.");if(t<1)return b("client","Count must be at least 1.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,CreditsConfirmationID:n,RelatedEntityID:`lootbox_${e}_${i??"default"}_${d()}`},c$1=await this.ctx.api.lootbox.open(o);if(c$1.ok&&!c$1.data.CreditsConfirmation){let h=c$1.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$1}};var To="Reward";function ks(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var zs=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(To)?.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(To,e);if(t){let n={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(To,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 c;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${d()}`},s=await this.ctx.api.reward.claimDailyReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchDailyCalendarState(n.CalendarID,n.DailyState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",n);}return s}async collectIdleAccrual(e){if(!ks(e))return b("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${d()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let s=i.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return i}async claimComebackReward(e){if(!ks(e))return b("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${d()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return i}async claimReward(e){if(!ks(e))return b("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${d()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return i}async claimRewardWindow(e,t,i={}){if(!ks(e))return b("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return b("client","Amount must be a positive number.");let s=i.boost??"None";if(s==="Ad"&&!i.adRequestID)return b("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:s,...i.adRequestID?{AdRequestID:i.adRequestID}:{},RelatedEntityID:i.roundID??`reward_window_${e}_${d()}`},o=await this.ctx.api.reward.claimRewardWindow(n);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 ws="Tutorial",yu={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"]},Ms=class{constructor(e){this.ctx=e;e.cache.bindLoginView(yu,{schema:Yi,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(ws)?.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(ws,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ws,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(yu,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return c;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}_${d()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return b("client","FlowID is required.");if(!t||t.length===0)return b("client","stepIDs is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${d()}`},n=await this.ctx.api.tutorial.completeStepsBatch(s);return n.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",n.data)),n}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 b("client","FlowID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${d()}`},s=await this.ctx.api.tutorial.claimFlowReward(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let s=e?.trim();if(!s)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:s},o=await t(n);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,s){let n=e?.trim(),o=t?.trim();if(!n)return b("client","FlowID is required.");if(!o)return b("client","StepID is required.");if(!this.ctx.auth.context)return c;let c$1={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:o};s?.relatedEntityID&&(c$1.RelatedEntityID=s.relatedEntityID);let h=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,R=await i(c$1);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(n,o,h,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(ws)?.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 Os=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 b("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","campaignID is required.");if(!t)return b("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return c;s.CampaignID=e,s.WalletAddress=t,i&&(s.Amount=i);let n=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return n.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",n.data),n}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var qe=z.object({Username:z.string().nullish(),Country:z.string().nullish(),AvatarUrl:z.string().nullish(),Premium:z.boolean().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),BoardRank:z.number().nullish()}).passthrough();var fy={Global:"Global",Announcement:"Announcement",Group:"Group"},Cu=z.enum(["Global","Announcement","Group"]).catch("Global"),gy={None:"None",Language:"Language",Region:"Region"},yy=z.enum(["None","Language","Region"]).catch("None"),Ry={Anyone:"Anyone",Friends:"Friends"},Cy=z.enum(["Anyone","Friends"]).catch("Anyone"),Sy={Reject:"Reject",Mask:"Mask"},xy=z.enum(["Reject","Mask"]).catch("Reject"),by={Player:"Player",Publisher:"Publisher",System:"System"},Dy=z.enum(["Player","Publisher","System"]).catch("Player"),Iy={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Py=z.object({DisplayNameKey:z.string().nullish(),SortOrder:z.number().nullish(),IconPath:z.string().nullish(),JoinedByDefault:z.boolean().nullish()}).passthrough(),Su=z.object({Gate:Z.nullish(),Schedule:ge.nullish()}).passthrough(),xu=z.object({Gate:Z.nullish(),Limits:Ce.nullish(),MaxLength:z.number().nullish()}).passthrough(),bu=z.object({HotTailSize:z.number().nullish(),HistoryHours:z.number().nullish()}).passthrough(),vy=z.object({Availability:Q.nullish(),Write:Q.nullish(),Retention:Q.nullish()}).passthrough(),Ty=z.object({ChannelID:z.string().nullish(),Identity:Py.nullish(),Type:Cu.nullish(),GroupSource:z.string().nullish(),Partitioning:yy.nullish(),Capacity:z.number().nullish(),Availability:Su.nullish(),Write:xu.nullish(),Retention:bu.nullish(),Presets:vy.nullish()}).passthrough(),Ay=z.object({IsEnabled:z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:Cy.nullish(),Limits:Ce.nullish(),MaxLength:z.number().nullish(),HistoryHours:z.number().nullish(),MaxConversations:z.number().nullish()}).passthrough(),ky=z.object({BlockedTerms:z.array(z.string()).nullish(),BlockedTermAction:xy.nullish(),MaxIgnoreListSize:z.number().nullish(),ReportsEnabled:z.boolean().nullish(),ReportLimits:Ce.nullish()}).passthrough(),zy=z.object({MinIntervalSeconds:z.number().nullish(),MaxMessagesPerPoll:z.number().nullish(),MaxHistoryPageSize:z.number().nullish()}).passthrough(),wy=z.object({Availability:z.record(z.string(),Su).nullish(),Write:z.record(z.string(),xu).nullish(),Retention:z.record(z.string(),bu).nullish()}).passthrough(),Du=z.object({IsEnabled:z.boolean().nullish(),Channels:z.record(z.string(),Ty).nullish(),Direct:Ay.nullish(),Moderation:ky.nullish(),Polling:zy.nullish(),Presets:wy.nullish()}).passthrough(),My=z.object({LastReadAt:z.string().nullish(),LastReadMessageID:z.string().nullish(),Left:z.boolean().nullish()}).passthrough(),Ru=z.object({LastAt:z.string().nullish(),DailyCount:z.number().nullish(),DailyResetUtc:z.string().nullish(),TotalCount:z.number().nullish(),LastTextHash:z.string().nullish()}).passthrough();z.object({MutedUntil:z.string().nullish(),MuteReason:z.string().nullish(),Ignored:z.array(z.string()).nullish(),Channels:z.record(z.string(),My).nullish(),Limits:z.record(z.string(),Ru).nullish(),ReportLimits:Ru.nullish()}).passthrough();var Ao=z.object({RoomID:z.string().nullish(),SentAt:z.string().nullish(),MessageID:z.string().nullish()}).passthrough(),Es=z.object({RoomID:z.string().nullish(),ChannelID:z.string().nullish(),MessageID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderProfile:qe.nullish(),AuthorType:Dy.nullish(),Text:z.string().nullish(),SentAt:z.string().nullish()}).passthrough(),Oy=z.object({ChannelID:z.string().nullish(),RoomID:z.string().nullish(),DisplayNameKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),Type:Cu.nullish(),CanWrite:z.boolean().nullish(),WriteBlockedReason:z.string().nullish(),SlowModeSeconds:z.number().nullish(),MaxLength:z.number().nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),Us=z.object({Channels:z.array(Oy).nullish(),PollIntervalSeconds:z.number().nullish(),MutedUntil:z.string().nullish(),MuteReason:z.string().nullish()}).passthrough(),Ey=z.object({RoomID:z.string().nullish(),Messages:z.array(Es).nullish(),NextCursor:Ao.nullish(),UnreadCount:z.number().nullish(),ServedFromDatabase:z.boolean().nullish()}).passthrough(),Iu=z.object({Rooms:z.array(Ey).nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),Pu=z.object({RoomID:z.string().nullish(),Messages:z.array(Es).nullish(),NextBefore:Ao.nullish()}).passthrough(),vu=z.object({Message:Es.nullish(),Moderated:z.boolean().nullish()}).passthrough(),Tu=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:qe.nullish(),MaxLength:z.number().nullish()}).passthrough(),Uy=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:qe.nullish(),LastMessage:Es.nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),Au=z.object({Conversations:z.array(Uy).nullish()}).passthrough(),fi=z.object({Ignored:z.array(z.string()).nullish(),Cursor:Ao.nullish(),Joined:z.boolean().nullish()}).passthrough(),ku=z.object({ReportID:z.string().nullish(),AlreadyReported: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 zu="Chat",wu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},qs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(wu,{schema:Us,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(zu,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(zu,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(wu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return c;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 c;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 s of i.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return i}async getHistory(e,t,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),i&&(s.Limit=i),this.ctx.api.chat.getHistory(s)):c}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return c;s.ChannelID=e,s.Text=t,i&&(s.Locale=i);let n=await this.ctx.api.chat.sendMessage(s);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.Text=t;let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):c}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):c}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(i);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):c}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):c}async reportMessage(e,t,i,s){let n=this.ctx.authedRequest();return n?(n.RoomID=e,n.MessageID=t,n.Reason=i,s&&(n.Comment=s),this.ctx.api.chat.reportMessage(n)):c}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):c}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):c}resetCursors(){this.cursors.clear();}};var qy={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},By=z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),Ly={Player:"player",Title:"title",Creator:"creator"},gi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Mu=z.object({Configured:z.boolean().nullish(),PublicKey:z.string().nullish()}).passthrough(),Gy=z.object({TitleID:z.string().nullish(),Topic:z.string().nullish()}).passthrough(),ko=z.object({EndpointHash:z.string().nullish(),Transport:By.nullish(),Locale:z.string().nullish(),Topics:z.array(Gy).nullish()}).passthrough(),Ou=z.object({Configured:z.boolean().nullish(),Subscriptions:z.array(ko).nullish()}).passthrough(),wt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var Fy="IDOS_PLATFORM_PUSH_REQUEST",Vy="IDOS_PLATFORM_PUSH_RESPONSE",Ny=12e4;function Eu(r){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let s=false,n=h=>{s||(s=true,window.removeEventListener("message",o),clearTimeout(c),i(h));},o=h=>{let R=h?.data;!R||R.type!==Vy||R.requestId!==t||f.includes(h.origin)&&n(R.ok===true);},c=setTimeout(()=>n(false),Ny);window.addEventListener("message",o);for(let h of f)try{e.postMessage({type:Fy,requestId:t,titleID:r},h);}catch{}})}var Bs=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),s=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,i.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return wt.Unsupported;if(this.isEmbedded())return wt.Embedded;if(!this.isSupported())return wt.Unsupported;let t=Notification.permission;return t==="denied"?wt.Blocked:t!=="granted"?wt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?wt.Subscribed:wt.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return b("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Eu(this.ctx.settings.titleID)?a({Where:"portal",Subscription:null}):b("client","The portal did not complete the subscription.");if(!this.isSupported())return b("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return b("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:_y(t.PublicKey)}),c$1=this.ctx.authedRequest();if(!c$1)return c;let h=o.toJSON();c$1.PushEndpoint=h.endpoint,c$1.PushP256dh=h.keys?.p256dh,c$1.PushAuth=h.keys?.auth,c$1.PushTransport="WebPush",c$1.PushLocale=e.locale??navigator.language,c$1.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(c$1);return R.ok?(this.ctx.emitter.emit("push:subscribed",R.data),a({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return c;if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return b("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):c}async unsubscribeByHash(e){if(!e)return b("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return c;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 _y(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return i}var Ls=Object.freeze({}),Gs=class{constructor(e){this.ctx=e;}ctx;table={...Ls};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new mi(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),s=this.lookup(i)??this.lookup(e);return s===void 0?this.onMissing(e):t?jy(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Ls},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 c;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:o}=i.data,c$1=null;if(o){let h=await this.loadTableFromApi(o);h.ok&&(c$1=h.data.table);}return this.table=n,this.fallbackTable=c$1,this.currentFallbackLocale=o,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:o,entryCount:Object.keys(n).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):c}reset(){this.table={...Ls},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:d()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return c;t.Locale=e;let i=await this.cache.read(Uu(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let n=s.data,o=n.Locale??Uu(e),c$1=n.Version??0;if(n.NotModified){let R=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:R?.t??{...Ls},fallbackLocale:n.FallbackLocale??null}}}let h=n.Entries??{};return c$1>0&&await this.cache.write(o,c$1,h),{ok:true,data:{locale:o,table:h,fallbackLocale:n.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 s=this.pluralCategory(i),n=`${e}.${s}`;if(this.lookup(n)!==void 0)return n;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 jy(r,e){return r.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function Uu(r){return r.trim().replace(/_/g,"-").toLowerCase()}var zo="Quest",Wy={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:r=>{let e=Date.now(),t=null,i=[...Object.values(r.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(r.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let n=Date.parse(s??"");!Number.isNaN(n)&&n>e&&(t===null||n<t)&&(t=n);}return t}},Fs=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let s=e.cache.configSection(zo)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(s)){let c=Date.parse(n[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(zo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(zo,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(Wy,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return c;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let s=i.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","QuestID is required.");if(!this.ctx.auth.context)return c;let s=t&&t.trim().length>0?t.trim():void 0,n={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${d()}`},o=await this.ctx.api.quest.claimQuestReward(n);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 b("client","quests is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchQuestStatus(n.Data.QuestID,n.Data.CycleID,"Claimed"),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${d()}`},o=await this.ctx.api.quest.claimMilestoneReward(n);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 b("client","milestones is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchMilestoneClaimed(n.Data.CycleID,n.Data.MilestoneID),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${d()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(n);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 b("client","MetricID is required.");if(t<0)return b("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},n=await this.ctx.api.quest.addQuestProgress(s);return n.ok&&(this.ctx.data.user.patchQuestProgressUpdates(n.data.Updates),this.ctx.emitter.emit("quest:progressAdded",n.data)),n}};var qu=z.object({}).passthrough().transform(r=>r);var Ky=z.object({Order:z.number().nullish(),Type:z.string().nullish(),DurationSec:z.number().nullish(),BonusMultiplier:z.number().nullish()}).passthrough(),Qy=z.object({Schedule:z.array(Ky).nullish(),RepeatCycle:z.boolean().nullish(),MaxCycles:z.number().nullish()}).passthrough(),Hy=z.object({IsActive:z.boolean().nullish(),CurrentPhaseEndUtc:p.nullish(),NextBonusStartUtc:p.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentPhaseIndex:z.number().nullish(),ActiveBonusMultiplier:z.number().nullish()}).passthrough(),$y=z.object({Milestones:Q.nullish()}).passthrough(),wo=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Category:z.string().nullish(),Token:$t.nullish(),TokenSources:z.array(ot).nullish(),ClaimMode:z.string().nullish(),Milestones:z.record(z.string(),Ve).nullish(),Presets:$y.nullish(),BonusWindow:Qy.nullish()}).passthrough(),Jy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Content:wo.nullish(),ClaimGraceHours:z.number().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Zy=z.object({TimedEventID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:ge.nullish(),Content:wo.nullish(),Events:z.array(Jy).nullish(),Gate:Z.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Yy=z.object({MaxConcurrentEvents:z.number().nullish()}).passthrough(),Xy=z.object({Milestones:z.record(z.string(),ui).nullish()}).passthrough(),Vs=z.object({Definitions:z.record(z.string(),Zy).nullish(),Settings:Yy.nullish(),Presets:Xy.nullish()}).passthrough(),eR=z.object({Type:Ti,TimedEventID:z.string(),CurrentChainedEventID:z.string().nullish(),Content:wo.nullish(),Progress:qu.nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),NextMilestone:Ve.nullish(),BonusWindow:Hy.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentEventOrder:z.number().nullish(),TotalEventsInChain:z.number().nullish(),TokenEntityID:z.string().nullish()}).passthrough(),Ns=z.object({ActiveEvents:z.array(eR).nullish()}).passthrough(),Bu=z.object({Tokens:z.record(z.string(),qu).nullish()}),Mo=z.object({Type:Ti.nullish(),LteID:z.string().nullish(),Resources:O.nullish()}),Oo=z.object({Type:Ti.nullish(),LteID:z.string().nullish(),MilestoneID:z.string().nullish(),TokenEntityID:z.string().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}),tR=z.object({Type:Ti.nullish(),LteID:z.string().nullish(),Resources:O.nullish()}),Eo=z.array(Te(Oo)),Lu=z.array(Te(Mo)),Gu=z.array(Te(tR)),ut={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Fu="TimedEvent",Vu={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:r=>{let e=null;for(let t of r.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},_s=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Vu,{schema:Ns,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(Vu,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return c;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(Fu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Fu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return c;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,s,n,o,c$1=1){if(!t)return b("client","LteID is required.");if(!i)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c;let h={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:o,RollMultiplier:c$1},R=await this.ctx.api.timedEvent.grantTokens(h);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",R.data)),R}async spendTokens(e,t,i){if(!t)return b("client","LteID is required.");if(i<=0)return b("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},n=await this.ctx.api.timedEvent.spendTokens(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",n.data)),n}async claimMilestone(e,t,i){if(!t||!i)return b("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},n=await this.ctx.api.timedEvent.claimMilestone(s);if(n.ok){let o=n.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 n}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c;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 c;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 b("client","spends is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return b("client","grants is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=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 s=i.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var iR=z.object({UserID:z.string(),Score:W.nullish(),Rank:z.number().nullish(),LastScoreUpdateUtc:p.nullish(),IpHash:z.string().nullish(),PublicProfile:qe.nullish(),SeasonTierAtCycleEnd:z.number().nullish()}).passthrough(),zi=z.object({LeaderboardID:z.string(),CycleVersion:z.number().nullish(),TotalParticipants:W.nullish(),CycleEndUtc:p.nullish(),TopUsers:z.array(iR).nullish(),BracketID:z.string().nullish()}),sR=z.object({CycleKey:z.string().nullish(),CycleEndUtc:p.nullish(),ClaimDeadlineUtc:p.nullish(),MilestoneTokensEarned:W.nullish(),ClaimableMilestoneIDs:z.array(z.string()).nullish(),CycleIndex:z.number().nullish(),ChainedEventID:z.string().nullish()}).passthrough(),js=z.object({LeaderboardID:z.string(),CurrentScore:W.nullish(),LastKnownRank:z.number().nullish(),HasUnclaimedReward:z.boolean().nullish(),UnclaimedRewardRank:z.number().nullish(),ScoreEarnedThisCycle:W.nullish(),MilestoneTokensEarned:W.nullish(),TokenEntityID:z.string().nullish(),NextMilestone:Ve.nullish(),HasUnclaimedMilestone:z.boolean().nullish(),GrantedPremiumTiers:z.record(z.string(),z.array(z.string())).nullish(),ClaimableGraceCycles:z.array(sR).nullish()}),Ws=z.object({LeaderboardID:z.string(),NewScore:W,CycleVersion:z.number()}),Ks=z.object({ServerTimeUtc:p,LeaderboardID:z.string(),Rank:z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Qs=z.object({ServerTimeUtc:p,LeaderboardID:z.string(),MilestoneID:z.string(),Resources:O.nullish(),Inventory:K.nullish()}),Nu=z.array(Te(zi)),Hs=z.array(Te(js)),_u=z.array(Te(Ks)),ju=z.array(Te(Qs)),Wu=z.array(Te(Ws)),nR=z.object({LeaderboardID:z.string(),CycleReward:Te(Ks).nullish(),Milestones:z.array(Te(Qs)).nullish()}),Ku=z.array(nR),rR=z.object({LeaderboardID:z.string(),Leaderboard:Te(zi).nullish(),Progress:Te(js).nullish()}),Qu=z.array(rR),oR=z.string(),Hu=z.object({Rank:z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:po.nullish()}).passthrough(),aR=z.object({RankRewards:z.array(Hu).nullish()}).passthrough(),lR=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),uR=z.object({Milestones:Q.nullish(),RankRewards:Q.nullish()}).passthrough(),cR=z.object({LeaderboardID:z.string(),DisplayName:z.string().nullish(),ScoreDisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),IsEnabled:z.boolean().nullish(),ScoreAggregation:oR.nullish(),Schedule:ge.nullish(),ChainEvents:z.array(lR).nullish(),Gate:Z.nullish(),TopUsersLimit:z.number().nullish(),MinScoreToEnterTop:z.number().nullish(),BracketSize:z.number().nullish(),LinkedSeasonChainID:z.string().nullish(),RankRewards:z.array(Hu).nullish(),Milestones:z.record(z.string(),Ve).nullish(),Presets:uR.nullish(),MilestoneClaimMode:z.string().nullish(),MilestoneClaimGraceHours:z.number().nullish(),ScoreSources:z.array(ot).nullish()}).passthrough(),pR=z.object({Milestones:z.record(z.string(),ui).nullish(),RankRewards:z.record(z.string(),aR).nullish()}).passthrough(),$s=z.object({Definitions:z.record(z.string(),cR).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 $u="Leaderboard",Ju={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"]},Js=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ju,{schema:Hs,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection($u,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection($u,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","LeaderboardID is required.");if(t<=0)return b("client","Score must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(i);if(s.ok){let n=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),n.NewScore,t,n.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",n);}return s}async submitScoreFromSource(e,t,i,s,n=1){if(!e)return b("client","LeaderboardID is required.");if(!t)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},c$1=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(c$1.ok){let h=c$1.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),h.NewScore,h.NewScore,h.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",h);}return c$1}async claimCycleReward(e){if(!e)return b("client","LeaderboardID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return i}async claimMilestone(e,t,i){if(!e||!t)return b("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},n=await this.ctx.api.leaderboard.claimMilestone(s);if(n.ok){let o=n.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 n}async getFriendsLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c;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(b("client","leaderboardIDs is required.")):this.ctx.cache.read(Ju,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return b("client","scores is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let n=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(n),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of s.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(n,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 b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let s of i.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var Uo=z.object({}).passthrough().transform(r=>r),Zs=z.object({SeasonChainID:z.string(),CycleIndex:z.number().nullish(),Season:z.lazy(()=>ec).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:W.nullish(),UserState:Uo.nullish(),NextTier:z.lazy(()=>Xu).nullish()}).passthrough(),Zu=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),AmountGranted:W.nullish(),NewStatusTokens:W.nullish(),OldTier:z.number().nullish(),NewTier:z.number(),TierUp:z.boolean().nullish()}),qo=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),TierNumber:z.number(),Resources:O.nullish(),Inventory:K.nullish()}),Yu=St(qo);var Xu=z.object({Tier:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredTokens:W.nullish(),TierReachedReward:H.nullish()}).passthrough(),ec=z.object({SeasonID:z.string().nullish(),Order:z.number().nullish(),DurationSec:W.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(Xu).nullish(),LinkedCollectionID:z.string().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough();var dR=z.object({SeasonChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:ge.nullish(),Seasons:z.array(ec).nullish(),GrantTokensAccessMode:z.string().nullish(),Gate:Z.nullish()}).passthrough(),Ys=z.object({Chains:z.record(z.string(),dR).nullish()}).passthrough(),Gt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var tc="Season",ic={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=Date.parse(r.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Xs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ic,{schema:Zs,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(tc,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(tc,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(ic,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(b("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","SeasonChainID is required.");if(t<=0)return b("client","Amount must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${d()}`},s=await this.ctx.api.season.grantStatusTokens(i);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","TierNumber must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${d()}`},s=await this.ctx.api.season.claimTierReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",n);}return s}async claimTierRewardsBatch(e,t){if(!e)return b("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return b("client","TierNumbers is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${d()}`},n=await this.ctx.api.season.claimTierRewardsBatch(s);if(n.ok){let o=n.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 n}};var sc="Premium",en=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(sc,e);if(t){let n={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",n),a(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(sc,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(i);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,i="Default",s=1,n){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,CreditsConfirmationID:n,RelatedEntityID:`premium_purchase_${e}_${t}`},c$1=await this.ctx.api.premium.purchaseItemOrCurrency(o);if(c$1.ok&&!c$1.data.CreditsConfirmation){let h=c$1.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$1}async purchaseRealMoney(e,t,i,s,n,o,c$1,h){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!s||!n)return b("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return c;let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:o,PackageName:c$1,AppStoreEnvironment:h,RelatedEntityID:`premium_iap_${e}_${t}`},_=await this.ctx.api.premium.purchaseRealMoney(R);if(_.ok){let ce=_.data;ce.Premium&&this.ctx.data.user.applyPremium(ce.Premium),this.ctx.data.user.applyResourceOperation(ce.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",ce);}return _}};var tn=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ItemInstanceID:z.string().nullish(),Level:z.number().nullish(),EquippedAt:p.nullish()}),Bo=z.object({CharacterID:z.string(),Level:z.number().nullish(),Experience:W.nullish(),Power:z.number().nullish(),StatLevels:z.record(z.string(),z.number()).nullish(),Equipment:z.record(z.string(),tn).nullish(),UpdatedAt:p.nullish()}).passthrough(),nc=z.object({Characters:z.record(z.string(),Bo).nullish()}),Lo=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),StatID:z.string(),StatLevel:z.number(),Power:z.number().nullish(),Resources:O.nullish()}),Go=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),NewLevel:z.number(),Power:z.number().nullish(),Resources:O.nullish()}),rc=z.object({ServerTimeUtc:p,CharacterID:z.string(),Equipment:z.record(z.string(),tn).nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),oc=z.object({ServerTimeUtc:p,CharacterID:z.string(),ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),hR=z.object({ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish()}),ac=z.object({ServerTimeUtc:p,Characters:z.record(z.string(),hR).nullish(),Inventory:K.nullish()}),Fo=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),Power:z.number().nullish(),Resources:O.nullish()}),lc=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),SkinID:z.string(),Resources:O.nullish(),Inventory:K.nullish(),Equipped:z.boolean().nullish(),EquipError:z.string().nullish(),Equipment:tn.nullish(),Power:z.number().nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish()}),uc=z.object({ServerTimeUtc:p,CharacterID:z.string(),SkinID:z.string(),Equipped:tn.nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),cc=z.object({ServerTimeUtc:p,CharacterID:z.string(),Cleared:z.boolean().nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),mR=z.object({SkinID:z.string(),IsDefault:z.boolean().nullish(),Misconfigured:z.string().nullish(),Owned:z.boolean().nullish(),OwnedCopies:z.number().nullish(),IsWorn:z.boolean().nullish(),MeetsRequirements:z.boolean().nullish(),SoldDirectly:z.boolean().nullish(),OnSale:z.boolean().nullish(),SaleEndsAtUtc:p.nullish(),GateOpen:z.boolean().nullish(),Purchasable:z.boolean().nullish(),PriceOptions:oe.nullish()}),fR=z.object({CharacterID:z.string(),CharacterOpen:z.boolean().nullish(),DefaultSkinID:z.string().nullish(),WornSkinID:z.string().nullish(),Skins:z.array(mR).nullish()}),pc=z.object({ServerTimeUtc:p,Characters:z.record(z.string(),fR).nullish()}),dc=St(Fo),hc=St(Go),mc=St(Lo),Vo=z.object({RequiredStatID:z.string(),RequiredLevel:z.number()}).passthrough(),fc=z.object({StatID:z.string(),TypeID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),MaxLevel:z.number().nullish(),Weight:z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:_e.nullish(),BaseStatValue:z.number().nullish(),ValueCurve:_e.nullish(),RankCurve:_e.nullish(),Requirements:z.array(Vo).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),gR=z.object({SlotID:z.string(),MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Vo).nullish(),AllowedRarityIDs:z.array(z.string()).nullish(),AllowedItemTags:z.array(z.string()).nullish(),MinItemLevel:z.number().nullish(),MaxItemLevel:z.number().nullish()}).passthrough(),gc=z.object({Slots:z.record(z.string(),gR).nullish()}).passthrough(),yc=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Lore:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),yR=z.object({ClassID:z.string().nullish(),RarityID:z.string().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),RR=z.object({UnlockedByDefault:z.boolean().nullish(),PriceOptions:oe.nullish()}).passthrough(),CR=z.object({Stats:Q.nullish(),Levels:Q.nullish(),Equipment:Q.nullish()}).passthrough(),Rc=z.object({MaxRank:z.number().nullish(),FirstPaidRank:z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:_e.nullish()}).passthrough(),No="@skin";function SR(r){return !!r&&r.startsWith("@")}var xR=z.object({CatalogID:z.string().nullish(),ItemID:z.string()}).passthrough(),bR=z.object({PriceOptions:oe.nullish(),Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),DR=z.object({MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Vo).nullish()}).passthrough(),IR=z.object({SkinID:z.string().nullish(),Identity:yc.nullish(),Item:xR.nullish(),Sale:bR.nullish(),Requirements:DR.nullish()}).passthrough(),PR=z.object({DefaultSkinID:z.string().nullish(),Definitions:z.record(z.string(),IR).nullish()}).passthrough(),vR=z.object({CharacterID:z.string(),Identity:yc.nullish(),Classification:yR.nullish(),Unlock:RR.nullish(),Presets:CR.nullish(),Equipment:gc.nullish(),Stats:z.record(z.string(),fc).nullish(),RankLadder:Rc.nullish(),RankStatCurve:_e.nullish(),StatMaxLevelCurve:_e.nullish(),Skins:PR.nullish()}).passthrough(),TR=z.object({Stats:z.record(z.string(),fc).nullish()}).passthrough(),AR=z.object({RankLadder:Rc.nullish()}).passthrough(),kR=z.object({Equipment:gc.nullish()}).passthrough(),zR=z.object({Stats:z.record(z.string(),TR).nullish(),Levels:z.record(z.string(),AR).nullish(),Equipment:z.record(z.string(),kR).nullish()}).passthrough(),sn=z.object({Definitions:z.record(z.string(),vR).nullish(),Presets:zR.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 _o="Character",nn=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(_o)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,n])=>n?.Unlock?.UnlockedByDefault===true&&!i[n.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(_o,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(_o,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${d()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok&&!s.data.CreditsConfirmation){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",n);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return b("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${d()}`,SelectedOptionID:i?.selectedOptionID,CreditsConfirmationID:i?.creditsConfirmationID,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok&&!n.data.CreditsConfirmation){let o=n.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 n}async upgradeCharacterLevel(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${d()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok&&!s.data.CreditsConfirmation){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,o=>{o.Level=n.NewLevel,n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",n);}return s}async equipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(i);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(i);if(s.ok){let n=s.data;this.applyUnequipChangesLocally(e,n),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:n.ClearedSlotIDs??[],power:n.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c;let s={...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}_${d()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok&&!n.data.CreditsConfirmation){let o=n.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 n}async equipSkin(e,t,i){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},n=await this.ctx.api.character.equipSkin(s);if(n.ok){let o=n.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return n}async unequipSkin(e){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let s=i.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):c}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,No,t??null),n.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return b("client","characterIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level??=1,n.StatLevels??={},n.Equipment??={},s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level=s.NewLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(n.StatLevels??={},n.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.StatLevels??={},n.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.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[s,n]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,s,n);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let n of i)s.patchCharacterEquipment(e,n,null);s.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,s]of Object.entries(e.Characters??{})){for(let n of s.ClearedSlotIDs??[])t.patchCharacterEquipment(i,n,null);t.patchCharacter(i,n=>{s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=e.ServerTimeUtc;});}}};var Cc="Match",rn=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,o){let c$1=this.ctx.auth.context;if(!c$1)return c;let h={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:o,RelatedEntityID:`pvp_create_${c$1.userID}_${d()}`},R=await this.ctx.api.match.createMatch(h);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",R.data)),R}async updateMatch(e,t={}){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(i);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c;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,s){let n=this.ctx.auth.context;if(!n)return c;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${d()}`},c$1=await this.ctx.api.match.instantBattle(o);if(c$1.ok){let h=c$1.data,R=this.ctx.data.config.itemDefinitions;if(h.Resources)this.ctx.data.user.applyResourceOperation(h.Resources,R);else if(h.ResourcesDual){let _=h.ResourcesDual;_.FromUserID===n.userID&&_.FromResult?this.ctx.data.user.applyResourceOperation(_.FromResult,R):_.ToUserID===n.userID&&_.ToResult&&this.ctx.data.user.applyResourceOperation(_.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",h);}return c$1}async saveStrategy(e){if(!this.ctx.auth.context)return c;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 s=this.ctx.authedRequest();if(!s)return c;s.Page=e,s.PageSize=t,s.Statuses=i;let n=await this.ctx.api.match.getMyMatches(s);return n.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",n.data),n}async getAvailableMatches(e=0,t=20,i=false){let s=this.ctx.authedRequest();if(!s)return c;s.Page=e,s.PageSize=t,s.OnlyPublic=i;let n=await this.ctx.api.match.getAvailableMatches(s);return n.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",n.data),n}async getDefinitions(e){let t=this.ctx.cache.configSection(Cc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Cc,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var Sc="Craft",on=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Sc,e);if(t){let n={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(Sc,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n,o){if(!e)return b("client","CraftID is required.");let c$1=this.ctx.auth.context;if(!c$1)return c;let h={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,CreditsConfirmationID:o,RelatedEntityID:`craft_${e}_${c$1.userID}_${d()}`},R=await this.ctx.api.craft.craft(h);return R.ok&&!R.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",R.data)),R}};var Ft=z.lazy(()=>z.union([z.string(),z.number(),z.boolean(),z.null(),z.array(Ft),z.record(z.string(),Ft)]));var Vt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},xc=z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Zt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function wi(r){return r!==Zt.Pending&&r!==Zt.Running}var MR={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 OR(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var ER=z.object({Url:z.string().nullish(),ContentType:z.string().nullish(),Variant:z.string().nullish()}),UR=z.object({Code:z.string().nullish(),Message:z.string().nullish()}),an=z.object({CreditsConfirmation:me.nullish(),GenerationID:z.string(),FeatureKey:z.string().nullish(),Modality:xc.nullish(),Status:z.string(),Progress:z.number().nullish(),OutputText:z.string().nullish(),OutputJson:z.record(z.string(),Ft).nullish(),Assets:z.array(ER).nullish(),Error:UR.nullish(),Charge:O.nullish(),PlayerRefunded:z.boolean().nullish(),Reused:z.boolean().nullish(),Reward:O.nullish(),Context:z.record(z.string(),Ft).nullish(),PaymentSettled:z.boolean().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish()}),bc=z.object({Data:z.array(an).nullish(),Skip:z.number().nullish(),Limit:z.number().nullish()}),qR=z.object({Name:z.string().nullish(),Type:z.string().nullish(),Required:z.boolean().nullish(),MaxLength:z.number().nullish(),Enum:z.array(z.string()).nullish()}).passthrough(),gt=z.record(z.string(),z.string()),BR=z.object({Key:z.string().nullish(),Role:z.string().nullish(),Required:z.boolean().nullish(),Label:gt.nullish()}).passthrough(),LR=z.object({Name:z.string().nullish(),Type:z.string().nullish(),Required:z.boolean().nullish(),MaxLength:z.number().nullish(),Default:z.string().nullish(),Multiline:z.boolean().nullish(),Label:gt.nullish(),Placeholder:gt.nullish(),Choices:z.array(z.object({Value:z.string().nullish(),Label:gt.nullish()}).passthrough()).nullish()}).passthrough(),Dc=z.object({Key:z.string(),Kind:z.string().nullish(),Name:gt.nullish(),Hint:gt.nullish(),Unit:gt.nullish(),Choices:z.array(z.object({Value:z.string(),Name:gt.nullish(),Group:z.string().nullish()}).passthrough()).nullish(),Groups:z.array(z.object({Key:z.string(),Name:gt.nullish()}).passthrough()).nullish(),Default:z.string().nullish(),Min:z.number().nullish(),Max:z.number().nullish(),Step:z.number().nullish()}).passthrough(),Ic=z.object({PriceOptions:oe.nullish()}).passthrough(),GR=z.object({Id:z.string().nullish(),Kind:z.string().nullish(),Action:z.string().nullish(),IsTrend:z.boolean().nullish(),Category:z.string().nullish(),Order:z.number().nullish(),Name:gt.nullish(),Description:gt.nullish(),Preview:z.object({Url:z.string().nullish(),PosterUrl:z.string().nullish(),Type:z.string().nullish()}).passthrough().nullish(),Inputs:z.array(BR).nullish(),Variables:z.array(LR).nullish(),Settings:z.array(Dc).nullish()}).passthrough(),FR=z.object({Modality:xc.nullish(),Async:z.boolean().nullish(),Limits:Ce.nullish(),PriceOptions:oe.nullish(),Tags:z.array(z.string()).nullish(),HistoryMessages:z.number().nullish(),MaxTokens:z.number().nullish(),AllowImages:z.boolean().nullish(),MaxInputImages:z.number().nullish(),MaxInputImageBytes:z.number().nullish(),AllowedImageTypes:z.array(z.string()).nullish(),MaxImages:z.number().nullish(),AllowEdit:z.boolean().nullish(),AllowReferenceImage:z.boolean().nullish(),MaxPromptChars:z.number().nullish(),LockBehavior:z.boolean().nullish(),ImageSize:z.string().nullish(),VideoSize:z.string().nullish(),VideoSeconds:z.number().nullish(),Voice:z.string().nullish(),AudioFormat:z.string().nullish(),MusicFormat:z.string().nullish(),ThreeDOperation:z.string().nullish(),ThreeDAnimations:z.array(z.string()).nullish(),Reward:H.nullish(),PromptVariables:z.array(qR).nullish(),AllowFreePrompt:z.boolean().nullish(),PlatformTemplateId:z.string().nullish(),PlatformTemplate:GR.nullish(),Settings:z.array(Dc).nullish(),FreePerDay:z.number().nullish(),FreeLeftToday:z.number().nullish()}).passthrough(),Pc=z.object({Enabled:z.boolean().nullish(),Features:z.record(z.string(),FR).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",EstimateTemplatePrice:"EstimateTemplatePrice"};var vc="AI",VR=/^[A-Za-z0-9_-]{1,128}$/,NR=2e3,_R=5e3,jR=30*6e4;function WR(r,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,r);e?.addEventListener("abort",i,{once:true});})}var ln=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(vc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(vc,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,i){return this.generate(e,{Text:t},i,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,i){return this.generate(e,{TemplateInputs:t},i,s=>this.ctx.api.ai.generateFromTemplate(s))}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}):c:b("client","FeatureKey is required.")}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):c}async getGeneration(e){if(!e)return b("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):c}isTerminal(e){return wi(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 b("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??jR),n=Math.max(1,t.intervalMs??NR),o=Math.max(n,t.maxIntervalMs??_R);for(;!wi(i.Status);){if(t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");if(Date.now()+n>s)return b("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await WR(n,t.signal),t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");let c=await this.pollFor(i);if(n=Math.min(o,Math.round(n*1.5)),!c.ok){if(c.reason==="connection")continue;return c}i=c.data,wi(i.Status)||t.onUpdate?.(i);}return a(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,s){if(!e)return b("client","FeatureKey is required.");let n=i?.relatedEntityID;if(n!==void 0&&!VR.test(n))return b("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return c;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:n??d()},c$1=await s(o);return c$1.ok&&!c$1.data.CreditsConfirmation&&(await this.reconcileCharge(c$1.data,true),this.emitView(c$1.data)),c$1}async poll(e,t){if(!e)return b("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.GenerationID=e;let s=await t(i);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Zt.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===Zt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Zt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var jo="Collection",un=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(jo),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let n=e.cache.configSection("Season");return Object.values(n?.Chains??{}).some(c=>(c?.Seasons??[]).some(h=>!!h?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(jo,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(jo,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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,s){let n=this.ctx.auth.context;if(!n)return c;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${d()}`},c$1=await this.ctx.api.collection.openPack(o);return c$1.ok&&!c$1.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(c$1.data.Resources,c$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",c$1.data)),c$1}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return c;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${d()}`},o=await this.ctx.api.collection.openCollectionChest(n);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 c;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${d()}`},n=await this.ctx.api.collection.useCollectibleJoker(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",n.data)),n}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${d()}`},n=await this.ctx.api.collection.claimSetReward(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",n.data)),n}async claimSetRewardsBatch(e){if(!e||e.length===0)return b("client","sets is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${d()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,n,o=false){let c$1=this.ctx.auth.context;if(!c$1)return c;let h={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${c$1.userID}_${s}_${d()}`},R=await this.ctx.api.collection.sendTradeOffer(h);return R.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",R.data)),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${d()}`},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 c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${d()}`},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 c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${d()}`},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 c;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 c;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 KR=z.object({}).passthrough().transform(r=>r),QR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},HR={Active:"Active",Left:"Left",Replaced:"Replaced"},$R=z.object({ObjectIndex:z.number().nullish(),ObjectCompletionRewardClaimed:z.boolean().nullish()}).passthrough(),JR=z.object({UserID:z.string().nullish(),PublicData:qe.nullish(),BuildObjectsProgress:$R.nullish(),IsBot:z.boolean().nullish(),SpinsCount:z.number().nullish(),TokensSpent:z.number().nullish(),MemberStatus:z.string().nullish(),GrandPrizeClaimed:z.boolean().nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),ZR=z.object({Index:z.number().nullish(),OwnerUserID:z.string().nullish(),CurrentProgress:z.number().nullish(),MaxProgress:z.number().nullish(),IsCompleted:z.boolean().nullish()}).passthrough(),YR=z.object({Objects:z.array(ZR).nullish()}).passthrough(),Tc=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),CoopChainID:z.string().nullish(),CoopEventID:z.string().nullish(),CycleIndex:z.number().nullish(),Members:z.array(JR).nullish(),BuildObjectsState:YR.nullish(),Status:z.string().nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:z.number().nullish()}).passthrough(),Ac=z.object({CoopChainID:z.string(),CycleIndex:z.number().nullish(),EventOrder:z.number().nullish(),EventDef:z.lazy(()=>kc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:z.number().nullish()}).passthrough(),XR=z.string(),Wo=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Weight:z.number().nullish(),MinProgress:z.number().nullish(),MaxProgress:z.number().nullish()}).passthrough(),eC=z.object({Index:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxProgress:z.number().nullish(),CompletionReward:H.nullish()}).passthrough(),tC=z.object({Objects:z.array(eC).nullish(),PriceOptions:oe.nullish(),SpinnerTable:z.array(Wo).nullish(),MaxSpinsPerCall:z.number().nullish()}).passthrough(),kc=z.object({CoopEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),EventType:XR.nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),BuildObjects:tC.nullish(),GrandPrize:H.nullish()}).passthrough(),iC=z.object({CoopChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:ge.nullish(),Events:z.array(kc).nullish(),Gate:Z.nullish()}).passthrough(),cn=z.object({ServerTimeUtc:p.nullish(),UserState:KR.nullish(),ActiveGroup:Tc.nullish()}),Ko=z.object({ServerTimeUtc:p.nullish(),Group:Tc.nullish(),SecondsRemaining:W.nullish()}),zc=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),Resources:O.nullish(),ObjectIndex:z.number().nullish(),Sector:Wo.nullish(),RequestedSpins:z.number().nullish(),SpinsUsed:z.number().nullish(),Sectors:z.array(Wo).nullish(),ProgressDelta:z.number().nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),ObjectCompleted:z.boolean().nullish(),AllObjectsCompleted:z.boolean().nullish()}),Qo=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),wc=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),pn=z.object({Chains:z.record(z.string(),iC).nullish()}).passthrough(),yt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Mc="CoopEvent",Oc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},dn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Oc,{schema:cn,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Mc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Mc,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return b("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;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(Oc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","CoopChainID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let s=i.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,s,n){if(!e||!t)return b("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,CreditsConfirmationID:n,RelatedEntityID:d()},c$1=await this.ctx.api.coopEvent.spin(o);return c$1.ok&&!c$1.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(c$1.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",c$1.data)),c$1}async claimObjectReward(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c;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 b("client","GroupID is required.");if(!this.ctx.auth.context)return c;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 c;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 sC={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},nC={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},rC=z.object({NodeID:z.string().nullish(),Status:z.string().nullish(),ExecutionCount:z.number().nullish(),UnlockedAtUtc:p.nullish(),CompletedAtUtc:p.nullish(),LastExecutedAtUtc:p.nullish(),NextAvailableAtUtc:p.nullish(),LastExecutionRefID:z.string().nullish()}).passthrough(),oC=z.object({TrackID:z.string().nullish(),CurrentValue:z.number().nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),Ec=z.object({OfferID:z.string().nullish(),InstanceKey:z.string().nullish(),SourceOfferVersion:z.number().nullish(),Status:z.string().nullish(),ActivatedAtUtc:p.nullish(),ExhaustedAtUtc:p.nullish(),ExpiredAtUtc:p.nullish(),DismissedAtUtc:p.nullish(),ShowCount:z.number().nullish(),LastShownAtUtc:p.nullish(),Nodes:z.record(z.string(),rC).nullish(),Tracks:z.record(z.string(),oC).nullish(),SelectedChoiceNodeID:z.string().nullish()}).passthrough(),aC=z.object({SlotID:z.string().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),ActiveOfferID:z.string().nullish(),ActiveOfferStartedAtUtc:p.nullish(),ActiveOfferExpiresAtUtc:p.nullish(),ActiveOffer:Ec.nullish(),NextCycleStartsAtUtc:p.nullish(),LastUpdatedUtc:p.nullish(),DismissSkipAvailableAtUtc:p.nullish(),LastDismissedAtUtc:p.nullish(),ActiveScheduleInstanceKey:z.string().nullish()}).passthrough(),lC=z.object({TotalExecutions:z.number().nullish(),DailyExecutions:z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),uC=z.object({TotalActivations:z.number().nullish(),TotalExhausted:z.number().nullish(),TotalExpired:z.number().nullish(),TotalDismissed:z.number().nullish(),TotalShows:z.number().nullish(),LastShownAtUtc:p.nullish(),LastActivatedAtUtc:p.nullish(),LastExhaustedAtUtc:p.nullish(),NodeCounts:z.record(z.string(),lC).nullish()}).passthrough(),cC=z.object({Slots:z.record(z.string(),aC).nullish(),OfferHistory:z.record(z.string(),uC).nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),pC={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},dC={Eq:"Eq",Gte:"Gte",Lte:"Lte"},hC=z.object({Order:z.number().nullish(),OfferID:z.string().nullish(),DurationSec:z.number().nullish(),DelayBeforeActivationSec:z.number().nullish()}).passthrough(),hn=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Uc=z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),qc=z.object({AllowDismissSkip:z.boolean().nullish(),DismissSkipDelaySec:z.number().nullish()}).passthrough(),mC=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Behaviour:Q.nullish()}).passthrough(),fC=z.object({SlotID:z.string().nullish(),Enabled:z.boolean().nullish(),Identity:hn.nullish(),Availability:Uc.nullish(),Behaviour:qc.nullish(),Queue:z.array(hC).nullish(),Presets:mC.nullish()}).passthrough(),gC=z.object({ViewsRequiredToComplete:z.number().nullish(),MaxViewsPerActivation:z.number().nullish(),GrantRewardsPerView:z.boolean().nullish()}).passthrough(),yC=z.object({RewardedVideo:gC.nullish()}).passthrough(),RC=z.object({TrackID:z.string().nullish(),Operator:z.string().nullish(),Value:z.number().nullish()}).passthrough(),CC=z.object({Identity:Q.nullish(),Graph:Q.nullish(),Milestones:Q.nullish()}).passthrough(),SC=z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish()}).passthrough(),xC=z.object({TrackID:z.string().nullish(),Amount:z.number().nullish(),RespectBounds:z.boolean().nullish()}).passthrough(),bC=z.object({TrackID:z.string().nullish(),DisplayName:z.string().nullish(),StartValue:z.number().nullish(),MinValue:z.number().nullish(),MaxValue:z.number().nullish(),ClampToMin:z.boolean().nullish(),ClampToMax:z.boolean().nullish(),HiddenFromUI:z.boolean().nullish()}).passthrough(),DC=z.object({RequiredCompletedNodeIDs:z.array(z.string()).nullish(),RequiredAnyCompletedNodeIDs:z.array(z.string()).nullish(),RequiredTracks:z.array(RC).nullish(),VisibleWhileLocked:z.boolean().nullish()}).passthrough(),Bc=z.object({Options:oe.nullish()}).passthrough(),Lc=z.object({Grants:H.nullish(),TrackChanges:z.array(xC).nullish(),MilestonePoints:z.number().nullish()}).passthrough(),IC=z.object({NodeID:z.string().nullish(),Type:z.string().nullish(),Identity:hn.nullish(),Pricing:Bc.nullish(),Reward:Lc.nullish(),Action:yC.nullish(),UnlockRules:DC.nullish(),NextNodeIDs:z.array(z.string()).nullish(),ChoiceGroupID:z.string().nullish(),Limits:Ce.nullish(),HideWhenCompleted:z.boolean().nullish(),ExhaustOfferOnComplete:z.boolean().nullish(),Presets:SC.nullish()}).passthrough(),Gc=z.object({RootNodeIDs:z.array(z.string()).nullish(),Nodes:z.array(IC).nullish(),Tracks:z.array(bC).nullish(),ExhaustedWhenAllTerminalNodesCompleted:z.boolean().nullish()}).passthrough(),Fc=z.object({Milestones:z.record(z.string(),Ve).nullish(),ClaimMode:z.string().nullish(),Token:$t.nullish()}).passthrough(),Vc=z.object({OfferID:z.string().nullish(),Version:z.number().nullish(),Enabled:z.boolean().nullish(),Identity:hn.nullish(),Graph:Gc.nullish(),Milestones:Fc.nullish(),Presets:CC.nullish()}).passthrough(),PC=z.object({Identity:z.record(z.string(),hn).nullish(),Availability:z.record(z.string(),Uc).nullish(),Behaviour:z.record(z.string(),qc).nullish(),Graph:z.record(z.string(),Gc).nullish(),Milestones:z.record(z.string(),Fc).nullish(),Pricing:z.record(z.string(),Bc).nullish(),Reward:z.record(z.string(),Lc).nullish()}).passthrough(),Ho=z.object({Slots:z.record(z.string(),fC).nullish(),Offers:z.record(z.string(),Vc).nullish(),Presets:PC.nullish()}).passthrough(),Nc=z.object({DealOfferDefinitions:Ho.nullish()}),_c=z.object({DealOffers:cC.nullish()}),vC=z.object({EntityID:z.string().nullish(),TotalEarned:z.number().nullish(),ClaimedIDs:z.array(z.string()).nullish(),ReachedUnclaimedIDs:z.array(z.string()).nullish()}).passthrough(),TC=z.object({SlotID:z.string().nullish(),SortOrder:z.number().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),OfferDef:Vc.nullish(),ActivationState:Ec.nullish(),IsNewActivation:z.boolean().nullish(),ComputedExpiresAtUtc:p.nullish(),Cost:Tt.nullish(),Milestone:vC.nullish(),ScheduleInstanceKey:z.string().nullish()}).passthrough(),mn=z.object({Slots:z.array(TC).nullish()}),jc=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),NodeID:z.string().nullish(),NodeCompleted:z.boolean().nullish(),OfferExhausted:z.boolean().nullish(),Idempotent:z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Wc=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),Resources:O.nullish()}),Kc=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),Resources:O.nullish()}),Qc=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Hc=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),ClaimedIDs:z.array(z.string()).nullish(),Rejected:z.record(z.string(),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 AC="DealOffer",$c={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},fn=class{constructor(e){this.ctx=e;e.cache.bindLoginView($c,{schema:mn,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(AC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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($c,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${d()}`},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,s){if(!e||!t)return b("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return c;let n=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:n??`deal_exec_${e}_${t}_${d()}`},c$1=await this.ctx.api.dealOffer.executeNode(o);return c$1.ok&&!c$1.data.CreditsConfirmation&&(c$1.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(c$1.data.Resources,c$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",c$1.data)),c$1}async recordShow(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${d()}`},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 b("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${d()}`},s=await this.ctx.api.dealOffer.claimMilestone(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${d()}`},n=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",n.data)),n}};var Jc="Referral",gn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Jc,e);if(t){let n={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",n),a(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Jc,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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=Ht.parseReferralCode(e)?.toUpperCase();if(!t)return b("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},n=await this.ctx.api.referral.activateReferralCode(s);if(n.ok){let o=n.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 n}async claimInviteReward(e){let t=e.trim();if(!t)return b("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},n=await this.ctx.api.referral.claimInviteReward(s);if(n.ok){let o=n.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 n}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return b("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},n=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(n.ok){let o=n.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 n}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return c;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 kC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Zc=z.enum(["System","Reward","Gift","Social"]).catch("System"),zC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},wC=z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),MC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},OC=z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),st={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},EC={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"},UC=100,qC=z.object({Subject:z.string().nullish(),Body:z.string().nullish()}).passthrough(),Yc=z.object({FeatureID:z.string().nullish(),Args:z.record(z.string(),z.string()).nullish(),Url:z.string().nullish(),Label:z.string().nullish()}).passthrough(),BC=z.object({Texts:z.record(z.string(),qC).nullish(),Category:Zc.nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Yc.nullish(),SenderName:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),LC=z.object({Enabled:z.boolean().nullish(),Grant:ue.nullish(),Cost:ue.nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:p.nullish(),SenderGate:Z.nullish(),TemplateID:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),GC=z.object({Type:z.string().nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxAmountPerGift:z.number().nullish()}).passthrough(),FC=z.object({Enabled:z.boolean().nullish(),AllowedResources:z.array(GC).nullish(),MaxEntriesPerGift:z.number().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:p.nullish(),FeePercent:z.number().nullish(),FeeCost:ue.nullish(),SenderGate:Z.nullish(),ExpirationDays:z.number().nullish(),TemplateID:z.string().nullish()}).passthrough(),Xc=z.object({Enabled:z.boolean().nullish(),Capacity:z.number().nullish(),RewardLetterDays:z.number().nullish(),PlainLetterDays:z.number().nullish(),ClaimedRetentionDays:z.number().nullish(),DefaultLanguage:z.string().nullish(),Templates:z.record(z.string(),BC).nullish(),Gifts:z.object({Social:z.record(z.string(),LC).nullish(),Transfer:FC.nullish()}).passthrough().nullish(),Integrations:z.object({Leaderboard:z.boolean().nullish(),CoopEvent:z.boolean().nullish(),Season:z.boolean().nullish(),Referral:z.boolean().nullish()}).passthrough().nullish()}).passthrough(),VC=z.object({MessageID:z.string(),Source:wC,Category:Zc,TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Yc.nullish(),SenderName:z.string().nullish(),SenderUserID:z.string().nullish(),SenderAvatarUrl:z.string().nullish(),SenderNote:z.string().nullish(),Rewards:H.nullish(),HasRewards:z.boolean().nullish(),IsTransfer:z.boolean().nullish(),SentAt:p,ExpiresAt:p.nullish(),ReadAt:p.nullish(),ClaimedAt:p.nullish()}).passthrough(),NC=z.object({MessageID:z.string(),Module:OC,Key:z.string(),TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish()}).passthrough(),$o=z.object({ID:z.string(),Error:z.string().nullish()}).passthrough(),ep=z.object({ServerTimeUtc:p.nullish(),Messages:z.array(VC).default([]),NextCursor:z.string().nullish(),PendingRewards:z.array(NC).nullish(),UnreadCount:z.number().nullish(),UnclaimedCount:z.number().nullish(),DeliveredNow:z.number().nullish()}).passthrough(),yn=z.object({ServerTimeUtc:p.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Jo=z.object({ServerTimeUtc:p.nullish(),AffectedCount:z.number().default(0),Failed:z.array($o).default([]),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),_C=z.object({MessageID:z.string(),Rewards:ue.nullish()}).passthrough(),Rn=z.object({ServerTimeUtc:p.nullish(),Claimed:z.array(_C).default([]),Failed:z.array($o).default([]),Resources:O.nullish(),Inventory:K.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),tp=z.object({ServerTimeUtc:p.nullish(),GiftID:z.string().nullish(),Sent:z.array(z.string()).default([]),Failed:z.array($o).default([]),Resources:O.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:p.nullish()}).passthrough(),ip=z.object({ServerTimeUtc:p.nullish(),MessageID:z.string().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish(),RecipientReceives:ue.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:p.nullish(),IdempotentReplay:z.boolean().nullish()}).passthrough(),sp=z.object({ServerTimeUtc:p.nullish(),ResetsAt:p.nullish(),Social:z.record(z.string(),z.object({IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ReceivedInPeriod:z.number().default(0),SentTo:z.array(z.string()).default([]),ResetsAt:p.nullish()}).passthrough()).default({}),Transfer:z.object({Enabled:z.boolean().default(false),IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ResetsAt:p.nullish()}).passthrough().nullish()}).passthrough();var Zo="Mailbox",Yo={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},Cn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Yo,{schema:yn,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(Yo,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Zo)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Zo,e);if(t)return a(t);let i=this.request();if(!i)return c;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(Zo,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return c;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(Yo,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return c;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 c;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 b("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):c}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return b("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):c}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):c}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 c;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return b("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return b("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return c;let n=await this.ctx.api.mailbox.sendGift(s);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",n.data)),n}async sendTransfer(e,t,i){if(!e?.trim())return b("client","RecipientUserID is required.");if(!i?.requestID?.trim())return b("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return c;let n=await this.ctx.api.mailbox.sendTransfer(s);return n.ok&&(n.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(n.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",n.data)),n}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):c}};var Sn={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},Xo="idos-app",np=z.object({ServerTimeUtc:z.string().nullish(),Allowed:z.boolean(),DenyReason:z.string().nullish(),Message:z.string().nullish(),RetryAfterSeconds:z.number().nullish(),RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),AdUnitID:z.string().nullish(),Type:z.string().nullish(),ExpiresAtUtc:z.string().nullish(),CreditsToAward:z.number().nullish(),RequiresServerSideVerification:z.boolean().nullish()}),rp=z.object({ServerTimeUtc:z.string().nullish(),RequestID:z.string().nullish(),Status:z.string(),CreditsAwarded:z.number().nullish(),RetryAfterSeconds:z.number().nullish(),ExpiresAtUtc:z.string().nullish(),AlreadyProcessed:z.boolean().nullish(),GrantedWithoutSsv:z.boolean().nullish(),Resources:O.nullish()});var ea={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},jC=5*6e4;function xn(){return s()}async function ta(r){let e=await j(ea.request,ea.response,{titleID:r.titleID,userID:r.userID,requestID:r.requestID,placementID:r.placementID,adUnitID:r.adUnitID??null},{answerTimeoutMs:jC});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var WC=new Set(["CANCELLED","DECLINED","CLOSED"]),KC=45e3,QC=r=>new Promise(e=>setTimeout(e,r)),bn=class{constructor(e){this.ctx=e;}ctx;get available(){return xn()}async showRewarded(e){if(!xn())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 s=i.data;if(!s.Allowed)return {status:"denied",reason:s.DenyReason??void 0,retryAfterSeconds:s.RetryAfterSeconds??void 0};if(s.ProviderID!==Xo||!s.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let n=await ta({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:s.RequestID,placementID:e,adUnitID:s.AdUnitID});return n.ok?{...await this.awaitReward(s.RequestID,n.via),requestID:s.RequestID}:{status:WC.has(n.error??"")?"cancelled":"unavailable",reason:n.error}}async awaitReward(e,t){let i=Date.now()+KC;for(;;){let s=this.ctx.authedRequest();if(!s)return {status:"pending",via:t};let n=await this.ctx.api.advertising.completeView({...s,RequestID:e});if(n.ok&&n.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:n.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((n.ok?n.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>i)return {status:"pending",via:t,reason:n.ok?void 0:n.error};await QC(o);}}};var HC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},$C={Title:"Title",Platform:"Platform"},op=z.object({UserID:z.string(),PublicData:qe.nullish(),Source:z.enum(["Title","Platform"]).nullish()}),Mi=z.object({Friends:z.array(op).nullish()}),JC=z.object({FriendsCount:z.number().nullish(),IncomingRequestsCount:z.number().nullish(),OutgoingRequestsCount:z.number().nullish()}),Oi=z.object({TargetUserID:z.string().nullish(),Status:z.string().nullish(),Target:op.nullish(),Counters:JC.nullish()}),ZC={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},YC={Like:"Like",Favorite:"Favorite"},XC={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},eS={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},tS={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},iS=z.object({Key:z.string().nullish(),DisplayName:z.string().nullish(),AvatarUrl:z.string().nullish()}).passthrough(),sS=z.object({Id:z.string(),Verb:z.string().nullish(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),Count:z.number().nullish(),LastActors:z.array(iS).nullish(),Payload:z.object({Title:z.string().nullish(),Excerpt:z.string().nullish(),ImageUrl:z.string().nullish()}).passthrough().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),OccurredAt:p.nullish(),OwnerImpact:O.nullish(),IsBlocked:z.boolean().nullish(),TargetObjectName:z.string().nullish()}).passthrough(),ap=z.object({Items:z.array(sS).nullish(),HasMore:z.boolean().nullish(),NextBeforeUpdatedAt:z.string().nullish(),NextBeforeID:z.string().nullish(),UnreadCount:z.number().nullish(),SeenAt:p.nullish()}).passthrough(),Ei=z.object({UnreadCount:z.number().nullish(),SeenAt:p.nullish()}).passthrough(),nS=z.object({Likes:z.number().nullish(),Favorites:z.number().nullish(),Followers:z.number().nullish(),Following:z.number().nullish(),Comments:z.number().nullish(),Replies:z.number().nullish(),Posts:z.number().nullish(),Dislikes:z.number().nullish()}).passthrough(),Nt=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Counts:nS.nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish(),Following:z.boolean().nullish(),Blocked:z.boolean().nullish()}).passthrough(),lp=z.object({Items:z.array(Nt).nullish()}).passthrough(),ia={HasMore:z.boolean().nullish(),NextCursorAt:z.string().nullish(),NextCursorID:z.string().nullish()},rS=z.object({UserID:z.string(),PublicData:qe.nullish(),Mutual:z.boolean().nullish(),Since:p.nullish()}).passthrough(),Dn=z.object({Items:z.array(rS).nullish(),...ia}).passthrough(),oS=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Kind:z.string().nullish(),At:p.nullish()}).passthrough(),up=z.object({Items:z.array(oS).nullish(),...ia}).passthrough(),In=z.object({CommentID:z.string(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),ParentCommentID:z.string().nullish(),AuthorUserID:z.string().nullish(),AuthorPublicData:qe.nullish(),Text:z.string().nullish(),Status:z.string().nullish(),Pinned:z.boolean().nullish(),CreatedAt:p.nullish(),EditedAt:p.nullish(),Likes:z.number().nullish(),Replies:z.number().nullish(),Liked:z.boolean().nullish(),IsMine:z.boolean().nullish()}).passthrough(),cp=z.object({Items:z.array(In).nullish(),...ia,TotalCount:z.number().nullish()}).passthrough(),pp=z.object({CommentID:z.string().nullish(),Deleted:z.boolean().nullish()}).passthrough(),dp=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish(),AutoHidden:z.boolean().nullish()}).passthrough(),hp=z.object({CommentsEnabled:z.boolean().nullish(),CommentableTypes:z.array(z.string()).nullish(),CommentMaxLength:z.number().nullish(),CommentMaxLinks:z.number().nullish()}).passthrough(),aS="FRIENDS_FROM_PLATFORM",lS={Off:"Off",Default:"Default",Always:"Always"},uS={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},mp=z.object({Profile:z.enum(["Off","Default","Always"]).nullish(),Friends:z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:z.boolean().nullish()}).passthrough(),Se={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 sa={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Pn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(sa,{schema:Ei,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 c;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 c;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 b("client","TargetUserID is required.");if(!this.ctx.auth.context)return c;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 b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c;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 b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c;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 b("client","FriendUserID is required.");if(!this.ctx.auth.context)return c;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 c;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(sa,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return c;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 c;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(sa,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)):c}async getEntityStates(e,t){if(!t?.length)return b("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):c}async addComment(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i?.trim())return b("client","Text is required.");n.Text=i,n.ParentCommentID=s;let o=await this.ctx.api.social.addComment(n);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return b("client","CommentID is required.");if(!t?.trim())return b("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return c;i.CommentID=e,i.Text=t;let s=await this.ctx.api.social.editComment(i);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return b("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=i.parentCommentID,this.applyPage(s,i.cursor,i.limit),this.ctx.api.social.getComments(s))}async report(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i)return b("client","ReportReason is required.");n.ReportReason=i,n.ReportComment=s;let o=await this.ctx.api.social.report(n);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,s){let n=this.targetRequest(t,i);if("ok"in n)return n;n.ReactionKind=s;let o=await this.ctx.api.social[e](n);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):c}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 b("client","EntityType is required.");if(!t)return b("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):c}};var fp="TimedBoost";function cS(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var vn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(fp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(fp,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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(!cS(i))return b("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${i}_${d()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok&&!n.data.CreditsConfirmation){let o=n.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 n}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return c;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 Ot={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},pS={Client:"Client",Server:"Server",System:"System"},dS=z.enum(["Client","Server","System"]).catch("Client"),hS=z.object({Value:z.string().nullish(),UpdatedAt:p.nullish(),Version:z.number().nullish(),LastWriter:dS.nullish(),ExpiresAt:p.nullish()}).passthrough(),Tn=z.record(z.string(),hS),gp=z.object({Version:z.number().nullish(),Private:Tn.nullish(),Public:Tn.nullish(),ReadOnly:Tn.nullish()}),na=z.object({UserID:z.string().nullish(),Version:z.number().nullish(),Public:Tn.nullish()}),ra=z.object({ServerTimeUtc:p.nullish(),Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:p.nullish()}),mS=z.object({Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:p.nullish()}),yp=z.object({ServerTimeUtc:p.nullish(),Results:z.array(mS).nullish()}),Rp=z.object({ServerTimeUtc:p.nullish(),DeletedCount:z.number().nullish()}),Cp=z.object({Results:z.array(na).nullish(),NotFoundUserIDs:z.array(z.string()).nullish()}),fS={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},gS=z.enum(["String","Int","Bool","Json"]).catch("String"),yS=z.object({KeyID:z.string(),Bucket:z.string().nullish(),ValueType:gS.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),An=z.object({Keys:z.record(z.string(),yS).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),Rt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var RS="UserCustomData";function Sp(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var kn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(RS,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,Ot.Private)}async setPublicData(e,t){return this.setData(e,t,Ot.Public)}async setData(e,t,i){let s=e.trim();if(!Sp(s))return b("client",'KeyID is required and must not contain "." or "$".');if(t==null)return b("client","Value is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},c$1=await(i===Ot.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(c$1.ok){let h=c$1.data;this.ctx.data.user.patchUserCustomDataKey(i,h.KeyID,t,h.Version??0,h.ExpiresAt),this.ctx.emitter.emit(i===Ot.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",h);}return c$1}async deleteKey(e,t){let i=e.trim();if(!Sp(i))return b("client",'KeyID is required and must not contain "." or "$".');if(t!==Ot.Private&&t!==Ot.Public)return b("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},n=await this.ctx.api.userCustomData.deleteKey(s);return n.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),n}async batchSet(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let n=s.Bucket??Ot.Private,o=e.find(c=>c.Bucket===n&&c.KeyID===s.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(n,s.KeyID,o.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return b("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return c;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 CS="TitleCustomDataDefinitions",xp=50;function SS(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function oa(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function xS(r){let e={};for(let[t,i]of Object.entries(r))oa(i)||(e[t]=i);return e}var zn=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(CS,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return c;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(n=>n.trim()).filter(n=>n.length>0);if(!t.length)return b("client","At least one KeyID is required.");if(t.some(n=>!SS(n)))return b("client",'KeyID must not contain "." or "$".');if(t.length>xp)return b("client",`At most ${xp} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return c;i.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!oa(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!oa(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=xS(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 wn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 c;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 c;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var bS=15,DS="GameLoop",bp="BoardDefinition",Mn=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 c;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(DS,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(bp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),a(i);let s=this.ctx.authedRequest();if(!s)return c;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(bp,n.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n.data)),n}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return b("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return c;i.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let n=s.data,o=Yl(new Date,bS);this.ctx.data.user.patchBoardState(c=>{c.Position=n.NewPosition,c.CyclesCompleted=(c.CyclesCompleted??0)+(n.CyclesCompletedDelta??0),c.LastRollAtUtc=new Date().toISOString(),n.ActionRequired&&n.ActionData?c.Pending={Type:n.ActionRequired,TargetUserID:n.ActionData.TargetUserID,TargetPublicData:n.ActionData.PublicData,TargetBuildingStates:n.ActionData.TargetBuildingStates??void 0,TargetHasShield:n.ActionData.TargetHasShield??void 0,RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:o}:n.SpecialModeOffer&&(c.Pending={Type:"SPECIAL",RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:n.SpecialModeOffer.ModeID??void 0,Choices:n.SpecialModeOffer.Choices??void 0}});}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),n.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",n);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.IsBotTarget&&n.Operation?this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs):!n.IsBotTarget&&n.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(n.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",n);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return b("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${d()}`},n=await this.ctx.api.gameLoop.boardLoopRaid(s);if(n.ok){let o=n.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 n}async boardLoopRaidFast(e){if(!e.length)return b("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(s.ok){let n=s.data;n.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(n)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",n);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return b("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let n=s.data;n.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(n.BuiltIndex,o=>{n.NewLevel!=null&&(o.Level=n.NewLevel),o.IsDamaged=false,n.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",n);}return s}async boardSpecialChoose(e,t,i){if(!e)return b("client","choiceID must not be empty.");let s=this.ctx.auth.context;if(!s)return c;let n={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:i,RelatedEntityID:`special_choose_${s.userID}_${d()}`},o=await this.ctx.api.gameLoop.boardSpecialChoose(n);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(R=>{R.ChoiceID=e,R.ChosenMode=c.Mode??"Timed",R.StartedAtUtc=c.StartedAtUtc??null,R.DurationSeconds=c.DurationSeconds??null,R.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 c;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let n=s.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=n.AdViewsUsed??0,o.AccumulatedMultiplier=n.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",n);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${d()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",n);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 b("client","milestoneID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return c;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 c;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 On=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let n=e.trim();if(!n)return b("client","FunctionName is required.");if(!this.ctx.auth.context)return c;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},c$1=await this.ctx.api.cloudCode.execute(o);return c$1.ok&&this.ctx.emitter.emit("cloudCode:executed",c$1.data),c$1}};var Dp=z.object({ServerTimeUtc:p,SourceType:ai,SourceID:z.string(),TargetType:ai,TargetID:z.string(),SourceSpent:W,FeeAmount:W,RateApplied:Y,TargetCredited:W}),Ip=z.object({ServerTimeUtc:p,SourceType:ai,SourceID:z.string(),TargetType:ai,TargetID:z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),Pp=z.object({ServerTimeUtc:p,SpendID:z.string(),Resources:O.nullish()}),Ui={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},IS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},vp=z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),PS={Automatic:"Automatic",Manual:"Manual"},vS=z.enum(["Automatic","Manual"]).catch("Automatic"),TS=z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),InitialDeposit:z.number().nullish(),MinBalance:z.number().nullish(),MaxBalance:z.number().nullish(),DailyEarnLimit:z.number().nullish(),DailySpendLimit:z.number().nullish()}).passthrough(),AS=z.object({Rate:z.number().nullish(),Max:z.number().nullish(),Period:z.number().nullish()}).passthrough(),kS=z.object({IsTradable:z.boolean().nullish(),IsPurchasable:z.boolean().nullish(),IsRefundable:z.boolean().nullish()}).passthrough(),zS=z.object({TargetCurrencyType:ai.nullish(),TargetCurrencyID:z.string(),Rate:Y.nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish(),DailyLimit:z.number().nullish()}).passthrough(),Tp=z.object({Enabled:z.boolean().nullish(),RateMode:vS.nullish(),Fee:z.number().nullish(),Targets:z.array(zS).nullish()}).passthrough(),Ap=z.object({CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough(),wS=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Economy:TS.nullish(),Recharge:AS.nullish(),Conversion:Tp.nullish(),Permissions:kS.nullish(),Audit:Ap.nullish(),Status:vp.nullish()}).passthrough(),MS=z.object({NetworkID:z.string(),ContractAddress:z.string().nullish(),Decimals:z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),OS=z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),ES=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),SpendableInGame:z.boolean().nullish(),ConvertibleToVirtual:z.boolean().nullish()}).passthrough(),US=z.object({Mode:z.string().nullish(),FundingNetworkID:z.string().nullish(),PerPlayerDailyTokens:z.number().nullish(),TitleDailyTokens:z.number().nullish(),RefuseOverCap:z.boolean().nullish()}).passthrough(),aa=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),DisplayDecimals:z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),UsdPriceRefreshMinutes:z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:z.array(MS).nullish(),Limits:OS.nullish(),Permissions:ES.nullish(),Conversion:Tp.nullish(),Audit:Ap.nullish(),Status:vp.nullish(),ServerGrantPolicy:US.nullish(),UnbackedRewardCurrencyID:z.string().nullish()}).passthrough(),qS=z.object({SpendID:z.string().nullish(),DisplayName:z.string().nullish(),PriceOptions:z.record(z.string(),Ss).nullish()}).passthrough(),En=z.object({VirtualCurrencies:z.record(z.string(),wS).nullish(),CryptoCurrencies:z.record(z.string(),aa).nullish(),Spends:z.record(z.string(),qS).nullish()}).passthrough();var BS={EVM:"EVM",Solana:"Solana"},LS=z.enum(["EVM","Solana"]).catch("EVM"),GS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},FS=z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),VS={Token:"Token",Nft:"Nft"},kp=z.enum(["Token","Nft"]).catch("Token"),NS={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},_S=z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),jS={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},WS=z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),KS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},la=z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),zp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Un(r){let e=r?.trim();return e||zp.GameTopUp}var QS={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},wp=z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),HS=z.object({ContractAddress:z.string().nullish(),ItemCatalogID:z.string().nullish(),DisplayName:z.string().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),Mp=z.object({Ios:z.boolean().nullish(),Android:z.boolean().nullish(),Web:z.boolean().nullish()}).passthrough(),$S=z.object({NetworkID:z.string().nullish(),DisplayName:z.string().nullish(),Type:LS.nullish(),ChainID:z.number().nullish(),ChainTicker:z.string().nullish(),RewardPoolAddress:z.string().nullish(),VaultDepositAddress:z.string().nullish(),ChainConfigVersion:z.number().nullish(),RequiredConfirmations:z.number().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:Mp.nullish(),NftCollections:z.array(HS).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RpcUrl:z.string().nullish(),GasPrice:z.number().nullish(),NftBridgeAddress:z.string().nullish(),SignatureEpoch:z.number().nullish()}).passthrough(),JS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:Mp.nullish()}).passthrough(),ZS=z.object({MinAccountAgeDays:z.number().nullish(),MultiAccountCheckEnabled:z.boolean().nullish(),BanOnSharedWithdrawalAddress:z.boolean().nullish(),PendingWithdrawalTtlHours:z.number().nullish()}).passthrough(),YS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},XS=z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Op=z.object({Enabled:z.boolean().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:XS.nullish(),DenyMessage:z.string().nullish()}).passthrough(),ex=z.object({Enabled:z.boolean().nullish(),WalletConnectProjectId:z.string().nullish(),ShowOnLoginScreen:z.boolean().nullish()}).passthrough(),tx={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},qi=z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),ix=z.object({Mode:qi.nullish(),TokenGates:z.array(Op).nullish()}).passthrough(),ua=z.object({SystemState:JS.nullish(),Networks:z.record(z.string(),$S).nullish(),AccountSafety:ZS.nullish(),WalletLogin:ex.nullish(),PlayAccess:ix.nullish(),IframeConnectHosts:z.array(z.string()).nullish()}).passthrough(),sx=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),LinkedAt:p.nullish(),LastUsedAt:p.nullish(),LinkType:FS.nullish(),IsSignatureVerified:z.boolean().nullish()}).passthrough(),Ep=z.object({TitleTransactionID:z.string().nullish(),Type:kp.nullish(),NetworkID:z.string().nullish(),AssetID:z.string().nullish(),Amount:Y.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),nx=z.object({Status:_S.nullish(),Tier:WS.nullish(),VerifiedAt:p.nullish(),ExpiresAt:p.nullish(),RejectedAt:p.nullish(),ProviderReference:z.string().nullish(),RejectionReason:z.string().nullish()}).passthrough(),rx=z.object({CurrencyID:z.string().nullish(),Deposits:z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),ox=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:z.record(z.string(),rx).nullish()}).passthrough(),ax=z.object({NetworkID:z.string().nullish(),ItemCatalogID:z.string().nullish(),Deposits:z.number().nullish(),Withdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),lx=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),PerCollection:z.record(z.string(),ax).nullish()}).passthrough(),ux=z.object({Tokens:ox.nullish(),Nfts:lx.nullish()}).passthrough(),ca=z.object({CurrencyID:z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),_t=z.object({Granted:z.boolean(),Mode:qi.nullish(),Error:z.string().nullish(),WalletRequired:z.boolean().nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),GrantedUntil:p.nullish(),Balances:z.array(ca).nullish()}).passthrough(),cx=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:p.nullish(),Passed:z.boolean().nullish(),GrantedUntil:p.nullish(),Error:z.string().nullish(),Balances:z.array(ca).nullish()}).passthrough(),px=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CanUnlink:z.boolean().nullish()}).passthrough(),Up=z.object({Mode:qi.nullish(),TokenGates:z.array(Op).nullish(),WalletLoginEnabled:z.boolean().nullish(),CanLinkWallet:z.boolean().nullish(),WalletsFromPlatformProfile:z.boolean().nullish(),LinkedWallets:z.array(px).nullish(),Status:_t.nullish()}).passthrough(),dx=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:p.nullish(),LoggedInAt:p.nullish(),GatePassed:z.boolean().nullish(),GatedBalances:z.array(ca).nullish()}).passthrough(),hx=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),UnlinkedAt:p.nullish()}).passthrough(),mx=z.object({Version:z.number().nullish(),Stats:ux.nullish(),LinkedWallets:z.record(z.string(),sx).nullish(),LastWalletLogin:dx.nullish(),PlayAccess:cx.nullish(),PendingWithdrawals:z.array(Ep).nullish(),Kyc:nx.nullish(),FirstActivityAt:p.nullish(),LastActivityAt:p.nullish(),IsFlagged:z.boolean().nullish(),FlagReason:z.string().nullish(),UnlinkedWallets:z.array(hx).nullish()}).passthrough(),fx=z.object({CurrencyID:z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:p}).passthrough(),yi=z.object({CryptoBalances:z.record(z.string(),fx).nullish(),PendingAdded:Ep.nullish(),PendingRemovedIDs:z.array(z.string()).nullish()}).passthrough(),gx=z.object({Amount:Y,Frozen:Y,CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough().transform(r=>r),yx=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:wp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:la.nullish(),SignatureData:z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),TokenID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:p.nullish(),BurnAmount:z.number().nullish(),RefundedAt:p.nullish(),RefundCheckedAt:p.nullish()}).passthrough(),Rx=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:wp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:la.nullish(),SignatureData:z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),NFTID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),SkinID:z.string().nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:p.nullish()}).passthrough(),qp=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),pa=z.object({TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),ContractAddress:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(qp).nullish(),Signature:z.string().nullish()}).passthrough(),da=z.object({Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),ProgramID:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(qp).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),Bp=z.object({Blockchain:ua.nullish(),CryptoCurrencies:z.record(z.string(),aa).nullish()}).passthrough(),Lp=z.object({State:mx.nullish(),CryptoBalances:z.record(z.string(),gx).nullish()}).passthrough(),Gp=z.object({ServerTimeUtc:p.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:yi.nullish()}).passthrough(),Fp=z.object({ServerTimeUtc:p.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),Vp=z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:p.nullish(),EvmSignature:pa.nullish(),SolanaSignature:da.nullish(),StateDelta:yi.nullish(),ChainID:z.number().nullish()}).passthrough(),Np=z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish(),EvmSignature:pa.nullish(),SolanaSignature:da.nullish(),StateDelta:yi.nullish(),Inventory:K.nullish()}).passthrough(),_p=z.object({TokenTransactions:z.array(yx).nullish(),NFTTransactions:z.array(Rx).nullish(),RefundedIDs:z.array(z.string()).nullish()}).passthrough(),ha=z.object({ServerTimeUtc:p.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:z.string().nullish()}).passthrough(),jp=z.object({TitleTransactionID:z.string().nullish(),Kind:kp.nullish(),EvmSignature:pa.nullish(),SolanaSignature:da.nullish()}).passthrough(),Wp=z.object({TitleTransactionID:z.string().nullish(),OnChainTxHash:z.string().nullish(),Status:la.nullish(),StateDelta:yi.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 Cx="Blockchain",Kp="Blockchain:Definitions",qn=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Kp,e);if(t)return a(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return c;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(Cx,n.data.Blockchain),this.ctx.data.config.patchSection(Kp,n.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",n.data)),n)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,i,s,n){if(!e)return b("client","CurrencyID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return c;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=s,o.Category=Un(n);let c$1=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return c$1.ok&&(this.ctx.data.user.applyBlockchainStateDelta(c$1.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",c$1.data)),c$1}async requestNFTWithdrawal(e,t,i,s,n,o,c$1){if(!e)return b("client","ItemID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let h=this.ctx.authedRequest();if(!h)return c;h.ItemID=e,h.NetworkID=t,h.WalletAddress=i,h.Amount=s,h.Category=Un(n),o!==void 0&&(h.Level=o),c$1&&(h.ItemInstanceID=c$1);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(h);return R.ok&&(this.ctx.data.user.applyBlockchainStateDelta(R.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",R.data)),R}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","TitleTransactionID is required.");if(!t)return b("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.TitleTransactionID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return c;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 c;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var Sx={Head:"Head",Torso:"Torso",Legs:"Legs"},Bn=z.enum(["Head","Torso","Legs"]).catch("Head"),xx={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},ma=z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Hp=z.object({AttackTarget:Bn,DefenseTarget:Bn});var bx=z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),Dx=z.object({RoundIndex:z.number().nullish(),AttackerID:z.string().nullish(),DefenderID:z.string().nullish(),AttackZone:Bn.nullish(),DefenseZone:Bn.nullish(),HitType:bx.nullish(),DamageDealt:z.number().nullish(),DefenderHpRemaining:z.number().nullish()}).passthrough(),Ix=z.object({MaxHp:z.number().nullish(),CurrentHp:z.number().nullish(),Damage:z.number().nullish(),AttackSpeed:z.number().nullish(),CritChance:z.number().nullish(),CritMultiplier:z.number().nullish(),Armor:z.number().nullish(),DodgeChance:z.number().nullish()}).passthrough(),Px=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(r=>r),Qp=z.object({UserID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),SelectedCharacter:Bo.nullish(),BattleStrategy:z.array(Hp).nullish(),UnstackableItems:z.record(z.string(),Px).nullish(),Stats:Ix.nullish()}).passthrough(),vx=z.object({WinnerUserID:z.string().nullish(),LoserUserID:z.string().nullish(),Entry:ue.nullish(),NetReward:ue.nullish(),BattleLog:z.array(Dx).nullish(),IsDraw:z.boolean().nullish(),P1BattleProfile:Qp.nullish(),P2BattleProfile:Qp.nullish()}).passthrough(),$p=z.object({MatchID:z.string(),TitleID:z.string().nullish(),RuleID:z.string().nullish(),CreatedAt:p.nullish(),CreatorID:z.string().nullish(),CreatorCharacterID:z.string().nullish(),CreatorStrategy:z.array(Hp).nullish(),TargetUserID:z.string().nullish(),Entry:ue.nullish(),CreationCostPaid:ue.nullish(),RefundCreationCostOnCancel:z.boolean().nullish(),ExpiresAt:p.nullish(),JoinedByUserID:z.string().nullish(),JoinedByCharacterID:z.string().nullish(),JoinedAt:p.nullish(),Status:ma.nullish(),WinnerUserID:z.string().nullish(),CompletedAt:p.nullish(),IsRewardDistributed:z.boolean().nullish(),RewardDistributedAt:p.nullish()}).passthrough(),Jp=z.object({Status:ma,MatchID:z.string(),Entry:ue.nullish(),Resources:O.nullish()}),Zp=z.object({Match:$p.nullish()}),Yp=z.object({MatchID:z.string(),Status:ma,Resources:O.nullish()}),Xp=z.object({Battle:vx.nullish(),Resources:O.nullish(),ResourcesDual:At.nullish()}),fa=z.object({Matches:z.array($p).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}),Dt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var Tx=z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var Ax=z.enum(["Constant","Variable","Curve"]).catch("Constant"),kx=z.object({HealthStatID:z.string().nullish(),DamageStatID:z.string().nullish(),ArmorStatID:z.string().nullish(),AttackSpeedStatID:z.string().nullish(),CritChanceStatID:z.string().nullish(),CritDamageStatID:z.string().nullish(),DodgeStatID:z.string().nullish(),AllMightStatID:z.string().nullish()}).passthrough(),zx=z.enum(["Flat","PercentReduction"]).catch("Flat"),wx=z.object({MaxRounds:z.number().nullish(),BlockDamageMultiplier:z.number().nullish(),MinHitDamage:z.number().nullish(),DefaultCritMultiplier:z.number().nullish(),MaxCritChance:z.number().nullish(),MaxDodgeChance:z.number().nullish(),ArmorMode:zx.nullish(),MaxArmorReduction:z.number().nullish()}).passthrough(),Mx=z.object({Kind:Ax.nullish(),Constant:z.number().nullish(),VariableID:z.string().nullish(),Argument:z.string().nullish(),Curve:_e.nullish(),OnePlus:z.boolean().nullish()}).passthrough(),Ox=z.object({Coefficient:z.number().nullish(),Factors:z.array(Mx).nullish()}).passthrough(),Yt=z.object({Terms:z.array(Ox).nullish()}).passthrough(),Ex=z.object({Health:Yt.nullish(),Damage:Yt.nullish(),Armor:Yt.nullish(),AttackSpeed:Yt.nullish(),CritChance:Yt.nullish(),CritDamage:Yt.nullish(),Dodge:Yt.nullish()}).passthrough(),ed=z.object({StatMapping:kx.nullish(),Combat:wx.nullish(),Formula:Ex.nullish()}).passthrough(),Ux=z.object({BurnRate:z.number().nullish()}).passthrough(),Bi=z.object({Kind:Tx.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),TokenType:Hi.nullish(),EntityID:z.string().nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish()}).passthrough(),td=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Bi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),id=z.object({PriceOptions:oe.nullish(),RefundCostOnCancel:z.boolean().nullish(),MaxOpenMatches:z.number().nullish(),OfferLifetimeSeconds:z.number().nullish(),Limits:Ce.nullish(),AllowPrivateMatches:z.boolean().nullish(),MaxMatchesPerOpponentPerDay:z.number().nullish()}).passthrough(),qx=z.object({RuleID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Economy:Ux.nullish(),Entry:td.nullish(),Creation:id.nullish(),Settings:ed.nullish()}).passthrough(),Bx=z.object({Rules:z.record(z.string(),qx).nullish(),Defaults:ed.nullish(),EntryDefaults:td.nullish(),CreationDefaults:id.nullish()}).passthrough(),ga=z.object({InstantBattle:Bx.nullish()}).passthrough(),sd=ga;var Lx={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},ya=z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),Gx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Ra=z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),Fx={Burn:"Burn",Ledger:"Ledger"},Vx=z.enum(["Burn","Ledger"]).catch("Burn"),Gn={Item:"Item",VirtualCurrency:"VirtualCurrency"},Ca=z.enum(["Item","VirtualCurrency"]).catch("Item"),Nx=z.object({Percent:z.number().nullish(),MinPerPosition:W.nullish()}).passthrough(),Fn=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Bi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),Sa=z.object({Percent:z.number().nullish(),MinPerPosition:W.nullish(),Sink:Vx.nullish(),LedgerAccountID:z.string().nullish(),PerCatalogOverrides:z.record(z.string(),Nx).nullish(),ApplyToDirectTrades:z.boolean().nullish()}).passthrough(),_x=z.object({AllowedCatalogIDs:z.array(z.string()).nullish(),DeniedCatalogIDs:z.array(z.string()).nullish(),DeniedItemIDs:z.array(z.string()).nullish(),AllowUnstackableWithState:z.boolean().nullish(),AllowedCurrencyIDs:z.array(z.string()).nullish(),DeniedCurrencyIDs:z.array(z.string()).nullish()}).passthrough(),jx=z.object({Enabled:z.boolean().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),MaxActiveListings:z.number().nullish(),CreateLimits:Ce.nullish(),BuyLimits:Ce.nullish(),ListingFeeOptions:oe.nullish(),RefundListingFeeOnCancel:z.boolean().nullish()}).passthrough(),Wx=z.object({Enabled:z.boolean().nullish(),MinDurationHours:z.number().nullish(),MaxDurationHours:z.number().nullish(),AntiSnipeWindowSeconds:z.number().nullish(),AntiSnipeExtensionSeconds:z.number().nullish(),MaxAntiSnipeExtensions:z.number().nullish(),MinBidStepPercent:z.number().nullish(),MinBidStepAbsolute:W.nullish(),BidLimits:Ce.nullish()}).passthrough(),Kx=z.object({Enabled:z.boolean().nullish(),MaxActiveOrders:z.number().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),CreateLimits:Ce.nullish(),FillLimits:Ce.nullish()}).passthrough(),Qx=z.object({Enabled:z.boolean().nullish(),OfferExpirationHours:z.number().nullish(),MaxPendingOutgoing:z.number().nullish(),AllowGifts:z.boolean().nullish(),CreateLimits:Ce.nullish()}).passthrough(),Hx=z.object({Enabled:z.boolean().nullish()}).passthrough(),xa=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:ge.nullish(),PricePolicy:Fn.nullish(),Commission:Sa.nullish(),Tradability:_x.nullish(),Listings:jx.nullish(),Auctions:Wx.nullish(),BuyOrders:Kx.nullish(),DirectTrades:Qx.nullish(),Matching:Hx.nullish()}).passthrough(),nd=z.object({BidIndex:z.number().nullish(),UserID:z.string().nullish(),Amount:W.nullish(),Settled:z.boolean().nullish(),SettledAt:p.nullish()}).passthrough(),$x=z.object({BidAxisType:li.nullish(),BidCurrencyID:z.string().nullish(),BidCatalogID:z.string().nullish(),BidItemID:z.string().nullish(),StartingBid:W.nullish(),CurrentBid:W.nullish(),CurrentBidderID:z.string().nullish(),BidCount:z.number().nullish(),ExtensionCount:z.number().nullish(),PendingRefunds:z.array(nd).nullish()}).passthrough(),Ln=z.object({LastAt:p.nullish(),DailyCount:z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),Jx=z.object({Create:Ln.nullish(),Buy:Ln.nullish(),Sell:Ln.nullish(),Bid:Ln.nullish()}).passthrough(),Zx=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),Yx=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:Zx.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(r=>r),Et=z.object({OfferID:z.string().nullish(),OfferType:ya.nullish(),Status:Ra.nullish(),CreatorUserID:z.string().nullish(),CreatorPublicData:qe.nullish(),TargetUserID:z.string().nullish(),GoodsType:Ca.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:W.nullish(),GoodsInstances:z.array(Yx).nullish(),Price:ue.nullish(),Auction:$x.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),Xx=z.object({GoodsType:Ca.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),CountsByType:z.partialRecord(ya,W).nullish()}).passthrough(),rd=z.object({Definitions:xa.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish()}).passthrough(),ba=z.object({Offers:z.array(Et).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),od=z.object({Groups:z.array(Xx).nullish()}).passthrough(),ad=z.object({Offer:Et.nullish()}).passthrough(),ct=z.object({OfferID:z.string().nullish(),Status:Ra.nullish(),Settlement:At.nullish(),Resources:O.nullish(),CommissionTaken:ue.nullish()}).passthrough(),Li=z.object({OfferID:z.string().nullish(),Offer:Et.nullish(),Resources:O.nullish(),Matched:z.boolean().nullish(),Settlement:ct.nullish()}).passthrough(),ld=z.object({OfferID:z.string().nullish(),CurrentBid:W.nullish(),BidCount:z.number().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish()}).passthrough(),Vn=z.object({MyOffers:z.array(Et).nullish(),MyBids:z.array(Et).nullish(),MyBuyOrders:z.array(Et).nullish(),IncomingTrades:z.array(Et).nullish(),OutgoingTrades:z.array(Et).nullish(),Claimables:z.array(Et).nullish(),DrainedRefunds:z.array(nd).nullish(),Limits:Jx.nullish()}).passthrough(),eb=z.object({OfferID:z.string().nullish(),OfferType:ya.nullish(),FinalStatus:Ra.nullish(),SellerUserID:z.string().nullish(),BuyerUserID:z.string().nullish(),GoodsType:Ca.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:W.nullish(),PricePaid:ue.nullish(),CommissionTaken:ue.nullish(),CompletedAt:p.nullish(),MyRole:z.string().nullish()}).passthrough(),ud=z.object({Entries:z.array(eb).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Me={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 tb="Marketplace",cd={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"]},Nn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(cd,{schema:Vn,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(tb,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return c;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,s=20){if(!e)return b("client","ItemID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.ItemID=e,n.OfferTypeFilter=t,n.ContinuationToken=i,n.PageSize=s;let o=await this.ctx.api.marketplace.getOffersByItem(n);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 s=this.ctx.authedRequest();if(!s)return c;s.ItemID=e,s.ContinuationToken=t,s.PageSize=i;let n=await this.ctx.api.marketplace.getBuyOrders(s);return n.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",n.data),n}getMyState(e,t){return this.ctx.cache.read(cd,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return c;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 s=this.ctx.authedRequest();if(!s)return c;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let n=await this.ctx.api.marketplace.getHistory(s);return n.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",n.data),n}async createListing(e,t,i,s,n,o,c$1){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let h=this.ctx.authedRequest();if(!h)return c;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.PriceBundle=s,h.DurationHours=n,h.ItemInstanceIDs=o,h.SelectedOptionID=c$1;let R=await this.ctx.api.marketplace.createListing(h);return this.applyCreateOfferResult(R,"marketplace:listingCreated"),R}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,s,n,o,c$1={}){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");let h=this.ctx.authedRequest();if(!h)return c;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.BidAxisType=s,h.BidCurrencyID=c$1.bidCurrencyID,h.BidCatalogID=c$1.bidCatalogID,h.BidItemID=c$1.bidItemID,h.StartingBid=n,h.DurationHours=o,h.ItemInstanceIDs=c$1.itemInstanceIDs,h.SelectedOptionID=c$1.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(h);return this.applyCreateOfferResult(R,"marketplace:auctionCreated"),R}async placeBid(e,t){if(!e)return b("client","OfferID is required.");if(!t||t<=0)return b("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return c;i.OfferID=e,i.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;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,s,n){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return c;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=s,o.DurationHours=n;let c$1=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(c$1,"marketplace:buyOrderCreated"),c$1}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;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,s,n){if(!e)return b("client","TargetUserID is required.");if(!t)return b("client","CatalogID is required.");if(!i)return b("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return c;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=s,o.RequestedBundle=n;let c$1=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(c$1,"marketplace:directTradeCreated"),c$1}async respondDirectTrade(e,t){if(!e)return b("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.OfferID=e,i.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(i);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.OfferID=e;let n=await t(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,n.data)),n}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=Gn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Gn.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):b("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 _n=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return b("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return c;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 s=await this.ctx.api.multiplayer.createRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.RoomID=e,s.TargetUserID=t,s.Ban=i;let n=await this.ctx.api.multiplayer.kickMember(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",n.data),n}async unbanMember(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return c;i.Page=e,i.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(i);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,i,s){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");if(!i)return b("client","SignalKind is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.TargetUserID=t,n.SignalKind=i,n.Payload=s;let o=await this.ctx.api.multiplayer.sendSignal(n);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(i);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,i){if(!e)return b("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.RoomID=e,s.Ready=t,s.MemberState=i;let n=await this.ctx.api.multiplayer.setMemberState(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",n.data),n}};var pd=" (if the network is fine, the storage bucket has no CORS rule for this origin)",jn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;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)):c}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 b("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):c}async getCreatorProfile(e,t,i){if(!e)return b("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):c}async publish(e){if(!e.files||e.files.length===0)return b("client","At least one file is required.");let t=new Map,i=e.files.map((h,R)=>{if("sourceAssetUrl"in h)return {Role:h.role,ContentType:h.contentType,SourceAssetUrl:h.sourceAssetUrl};let _=dd(h.data,h.contentType);return t.set(R,_),{Role:h.role,ContentType:h.contentType,Size:_.size}}),s=e.thumbnail?dd(e.thumbnail.data,e.thumbnail.contentType):null,n=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!n.ok)return n;let o=n.data.Uploads??[];for(let h=0;h<o.length;h++){let R=o[h];if(!R||R.ServerCopy||!R.Url)continue;let _=t.get(h);if(!_)return b("client",`No bytes for file #${h+1}.`);let ce=await this.putBytes(R.Url,_,R.ContentType??_.type);if(!ce.ok)return ce}let c=n.data.ThumbnailUpload;if(c?.Url&&s){let h=await this.putBytes(c.Url,s,c.ContentType??s.type);if(!h.ok)return h}return this.ctx.credits.pay(h=>this.publishUploaded({CreditsConfirmationID:h,ContentID:n.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}):c}async publishUploaded(e){if(!e.ContentID)return b("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 s=await this.ctx.api.workshop.updateContent(i);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let 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 s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getMyContent(s)):c}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 s=await this.ctx.api.workshop.acquire(i);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let s of t.data.Files??[])if(s.Url)try{let n=await this.ctx.fetchImpl(s.Url);if(!n.ok)return b("connection",`Download failed (HTTP ${n.status}).`);i.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await n.arrayBuffer()});}catch(n){return b("connection",`Download failed: ${n instanceof Error?n.message:String(n)}${pd}`)}return a({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)):c}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):c}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${pd}`)}}contentRequest(e){if(!e)return b("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):c}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 dd(r,e){return r instanceof Blob?r:typeof r=="string"?new Blob([new TextEncoder().encode(r)],{type:e}):r instanceof Uint8Array?new Blob([r.slice().buffer],{type:e}):new Blob([r],{type:e})}var ib={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},sb=z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),nb={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},hd=z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),rb={Everyone:"Everyone",Owner:"Owner",Server:"Server"},md=z.enum(["Everyone","Owner","Server"]).catch("Everyone"),ob={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},ab=z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),lb={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},ub=z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),cb={Count:"Count",Sum:"Sum"},pb=z.enum(["Count","Sum"]).catch("Count"),db={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},hb=z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),mb={Strict:"Strict",Loose:"Loose"},fb=z.enum(["Strict","Loose"]).catch("Strict"),gb=z.object({Kind:ub,Collection:z.string().nullish(),Validate:z.boolean().nullish()}),yb=z.object({Type:hd,ItemType:hd.nullish(),Ref:gb.nullish(),Required:z.boolean().optional(),Default:z.string().nullish(),Min:z.number().nullish(),Max:z.number().nullish(),MaxLength:z.number().nullish(),MaxItems:z.number().nullish(),Enum:z.array(z.string()).nullish(),Unique:z.boolean().optional(),UniqueIgnoreCase:z.boolean().optional(),Indexed:z.boolean().optional(),Visibility:md.optional(),ClientWritable:z.boolean().nullish(),Immutable:z.boolean().optional(),Description:z.string().nullish(),AllowedMimeTypes:z.array(z.string()).nullish(),MaxFileBytes:z.number().nullish()}),Rb=z.object({ID:z.string(),Components:z.array(z.object({Field:z.string(),Descending:z.boolean().optional()})).default([])}),Wn=z.object({Mode:ab,Role:z.string().nullish(),MembersField:z.string().nullish()}),Cb=z.object({Read:z.array(Wn).nullish(),Create:z.array(Wn).nullish(),Update:z.array(Wn).nullish(),Delete:z.array(Wn).nullish()}),Da=z.object({Cost:ue.nullish(),Grant:ue.nullish()}),Sb=z.object({ID:z.string(),SortKey:z.string(),PartitionField:z.string().nullish(),PageSize:z.number().optional(),MaxItems:z.number().optional(),PublishItems:z.boolean().optional()}),xb=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Namespace:z.string().nullish(),Tags:z.array(z.string()).nullish(),Enabled:z.boolean().nullish(),Kind:sb,Mode:fb.optional(),SchemaVersion:z.number().optional(),Fields:z.record(z.string(),yb).nullish(),SortKeys:z.array(Rb).nullish(),Access:Cb.nullish(),Limits:z.object({MaxItemBytes:z.number().nullish(),MaxItemsPerOwner:z.number().nullish(),TtlSeconds:z.number().nullish()}).nullish(),OnOwnerDeleted:hb.optional(),Counters:z.array(z.object({ID:z.string(),Kind:pb,SumField:z.string().nullish(),GroupBy:z.string().nullish(),Visibility:md.optional()})).nullish(),Economy:z.object({OnCreate:Da.nullish(),OnUpdate:Da.nullish(),OnDelete:Da.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:z.array(Sb).nullish(),AnonymousSearch:z.boolean().nullish(),Integrations:z.object({QuestMetricOnCreate:z.string().nullish(),QuestMetricOnUpdate:z.string().nullish(),QuestMetricOnDelete:z.string().nullish(),AnalyticsEventOnCreate:z.string().nullish(),AnalyticsEventOnUpdate:z.string().nullish(),AnalyticsEventOnDelete:z.string().nullish(),TriggerOnCreate:z.string().nullish(),TriggerOnUpdate:z.string().nullish(),TriggerOnDelete:z.string().nullish()}).nullish(),Moderation:z.object({BlockedTerms:z.array(z.string()).nullish()}).nullish()}),fd=z.object({Enabled:z.boolean().optional(),Collections:z.record(z.string(),xb).default({})}),bb=z.object({FileID:z.string(),Url:z.string(),ContentType:z.string().nullish(),Size:z.number()}),gd=z.object({FileID:z.string(),UploadUrl:z.string(),ContentType:z.string(),MaxBytes:z.number(),ExpiresAt:z.string()}),Ri=z.object({Collection:z.string(),ItemID:z.string(),OwnerUserID:z.string().nullish(),Data:z.record(z.string(),z.unknown()).default({}),Version:z.number(),CreatedAt:z.string(),UpdatedAt:z.string(),ExpireAt:z.string().nullish(),Expanded:z.record(z.string(),z.unknown()).nullish(),Files:z.record(z.string(),bb).nullish()}),Ia=z.object({Item:Ri}),yd=z.object({Items:z.array(Ri).default([]),Missing:z.array(z.string()).default([])}),Pa=z.object({Items:z.array(Ri).default([]),NextCursor:z.string().nullish()}),Rd=z.object({Count:z.number(),Capped:z.boolean().optional()}),va=z.object({Item:Ri,AlreadyExists:z.boolean().optional(),Economy:O.nullish()}),Cd=z.object({ItemID:z.string(),Deleted:z.boolean(),Economy:O.nullish()}),Sd=z.object({CounterID:z.string(),Group:z.unknown().optional(),Value:z.number()}),xd=z.object({Results:z.array(z.object({Op:z.string(),Collection:z.string(),ItemID:z.string(),Item:Ri.nullish(),Deleted:z.boolean().optional()})).default([])}),bd=z.object({Roles:z.array(z.string()).default([])}),Dd=z.object({Views:z.record(z.string(),z.string()).default({}),ItemUrlTemplate:z.string().nullish()}),Id=z.object({Version:z.string(),Collection:z.string(),View:z.string(),SortKey:z.string().nullish(),PageSize:z.number(),UpdatedAt:z.string(),BaseUrl:z.string(),Partitions:z.record(z.string(),z.object({Segment:z.string(),Pages:z.number(),Total:z.number()})).default({})}),Pd=z.object({Page:z.number(),HasMore:z.boolean(),Items:z.array(Ri).default([])}),Db={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 Ib=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Ad=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Aa=100,vd=25,Td=100;function Pb(r,e,t){return {Field:r,Op:e,Value:t}}var Kn=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(c)}get(e,t,i={}){let s=nt(e)??Gi(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.get({...n,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let s=nt(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(o=>Ad.test(o)))];return n.length?n.length>Td?Promise.resolve(b("client",`At most ${Td} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:n,Expand:i.expand})):Promise.resolve(b("client","At least one valid item id is required."))}query(e,t={},i={}){let s=nt(e)??Ta(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.query({...n,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),n=[],o=t.Cursor;for(;;){let c=await this.query(e,{...t,Cursor:o,Limit:t.Limit??Aa},i);if(!c.ok)return c;if(n.push(...c.data.Items),o=c.data.NextCursor??void 0,!o||n.length>=s)return a(n.slice(0,s))}}count(e,t={}){let i=nt(e)??Ta(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,i={}){let s=nt(e)??(i.itemID?Gi(i.itemID):null);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.create({...n,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,s={}){let n=nt(e)??Gi(t);return n?Promise.resolve(n):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=nt(e)??Gi(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.delete({...n,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(b("client","Operations are empty."));if(e.length>vd)return Promise.resolve(b("client",`At most ${vd} operations per batch.`));let t=e.map(i=>nt(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 s=nt(e);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.getCounter({...n,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,s){let n=nt(e);return n?Promise.resolve(n):t?s>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(b("client","File size must be positive.")):Promise.resolve(b("client","Field is required."))}async uploadFile(e,t,i,s={}){let n=s.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,n,i.size);if(!o.ok)return o;let c=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||n);return c.ok?o:c}async getPublicViews(e){let t=nt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return a(i);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,i={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let n=s.data.Views[t];if(!n)return b("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(n,Id);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 a({pointer:o.data,page:{Page:h,HasMore:false,Items:[]}});let R=await this.fetchJson(`${o.data.BaseUrl}${c.Segment}/page-${h}.json`,Pd);return R.ok?a({pointer:o.data,page:R.data}):R}getPublic(e,t){let i=nt(e)??Gi(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=nt(e)??Ta(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(c)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return b("connection","Internet Connection Error")}if(!i.ok)return b("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return b("server","CDN answer is not JSON.")}let n=t.safeParse(s);return n.success?a(n.data):b("server","CDN answer has an unexpected shape.")}};function nt(r){return Ib.test(r??"")?null:b("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function Gi(r){return Ad.test(r??"")?null:b("client",`Item id '${r}' is invalid.`)}function Ta(r){return r.Limit!=null&&(r.Limit<1||r.Limit>Aa)?b("client",`Limit must be 1..${Aa}.`):(r.Where?.length??0)>8?b("client","At most 8 filters per query."):null}var ka={Open:"Open",Declared:"Declared"},vb=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Blocked:z.boolean().nullish(),Highlight:z.number().nullish()}).passthrough(),Tb=z.object({ParamName:z.string().nullish(),DisplayName:z.string().nullish()}).passthrough(),kd=z.object({Enabled:z.boolean().nullish(),EventNaming:z.string().nullish(),Events:z.record(z.string(),vb).nullish(),Dimensions:z.array(Tb).nullish(),RetentionDays:z.number().nullish(),AutomaticEvents:z.boolean().nullish()}).passthrough(),jt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},It={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Qn=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Ab={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},kb=z.object({Index:z.number().nullish(),Name:z.string().nullish(),Reason:z.string().nullish()}).passthrough(),zd=z.object({Accepted:z.number().nullish(),Dropped:z.array(kb).nullish(),Duplicate:z.boolean().nullish(),Disabled:z.boolean().nullish()}).passthrough(),za={LogEvents:"LogEvents"};function wd(r,e=0){let t=r??"",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 s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let c=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:c&&c!=="K"&&c!=="wv"?c:void 0}}let n=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(n)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(n[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 Md(r){let e=typeof navigator>"u"?void 0:navigator,t=wd(e?.userAgent??"",e?.maxTouchPoints??0),i={};r.appVersion&&(i.AppVersion=r.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 s=r.locale||e?.language;return s&&(i.Language=s),i}var zb=25,wb=3e4,Od=1800*1e3,Ed=500,Mb=5,Ob=1e3,Eb=3600*1e3,Ud="idos_analytics_queue",wa="idos_analytics_pending",Ma="idos_analytics_opt_out",qd="idos_analytics_first_open",Bd="idos_analytics_last_activity",Ld="idos_analytics_last_context",Gd="idos_analytics_owner",Hn=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"||!Qn.test(e)?b("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Ub(e)?b("client",`Event name "${e}" uses a reserved prefix (${It.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return b("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(jt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return a(null);if(this.config()?.Enabled===false)return this.clear(),a(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return a(null);this.pending={BatchID:d(),Events:this.queue.splice(0,It.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return c;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>=Mb)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Ma);return}this.write(Ma,"1"),this.clear();}get isEnabled(){return this.read(Ma)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(Gd);e&&t&&t!==e&&this.clear(),e&&this.write(Gd,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(Bd)??"0");this.read(qd)||(this.write(qd,new Date().toISOString()),this.enqueue(jt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Ld);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(jt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(jt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Ld,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Od)&&this.enqueue(jt.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>=Od&&this.enqueue(jt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,s){if(!this.isEnabled||this.disabledByServer)return a(null);let n=this.config();if(n?.Enabled===false)return a(null);if(s&&n?.AutomaticEvents===false)return a(null);if(n?.Events?.[e]?.Blocked)return b("client",`Event "${e}" is blocked by the title.`);if(!s&&n?.EventNaming?.toLowerCase()===ka.Declared.toLowerCase()&&!n.Events?.[e])return b("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return b("client","value must be a finite number.");let o=qb(t);if(o.error)return b("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>Ed&&this.queue.splice(0,this.queue.length-Ed),this.touch(),this.persist(),this.started&&this.queue.length>=zb&&this.flush(),a(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},Ob));}dropStale(){let e=Date.now()-(It.maxEventAgeMs-Eb);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??=Md({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(Ud);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(wa);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(Ud,this.queue),this.pending?this.writeJson(wa,this.pending):this.remove(wa);}touch(){this.write(Bd,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 Ub(r){let e=r.toLowerCase();return It.reservedPrefixes.some(t=>e.startsWith(t))}function qb(r){if(!r)return {};let e=Object.keys(r);if(e.length===0)return {};if(e.length>It.maxParams)return {error:`Too many parameters: ${e.length}, max ${It.maxParams}.`};let t={};for(let i of e){if(!Qn.test(i))return {error:`Invalid parameter name "${i}".`};let s=r[i];typeof s=="string"?t[i]=s.length>It.maxStringValueLength?s.slice(0,It.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var Bb="idos_experiments",$n=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 c;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 s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let n=Number(s);return s.trim()!==""&&Number.isFinite(n)?n:i}if(typeof i=="boolean"){let n=s.trim().toLowerCase();return n==="true"||n==="1"?true:n==="false"||n==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,n]of t){let o=this.views.get(s);(!o||o.VariantID!==n.VariantID||o.Status!==n.Status)&&i.push(n);}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 `${Bb}:${this.ctx.settings.titleID}`}};function Wt(r,e,t,i){let n=`api/v2/${r&&r.length>0?r:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var L=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Wt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,s){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...s,ticket:t.ClientSessionTicket})}};var Jn=class extends L{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(za.LogEvents,e,zd,{silent:true})}};var Lb=z.object({VariantID:z.string().nullish(),DisplayName:z.string().nullish(),Weight:z.number().nullish(),IsControl:z.boolean().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),Gb={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Fb=z.object({MetricID:z.string().nullish(),Kind:z.string().nullish(),EventName:z.string().nullish(),IsPrimary:z.boolean().nullish()}).passthrough(),Vb=z.object({ExperimentID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),IsEnabled:z.boolean().nullish(),Schedule:ge.nullish(),Gate:Z.nullish(),Variants:z.array(Lb).nullish(),Salt:z.string().nullish(),LayerID:z.string().nullish(),StickyAssignment:z.boolean().nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Goals:z.array(Fb).nullish(),ActivationEvent:z.string().nullish(),RolloutVariantID:z.string().nullish()}).passthrough(),Fd=z.object({Experiments:z.record(z.string(),Vb).nullish()}).passthrough(),Nb={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},_b=z.object({ExperimentID:z.string().nullish(),VariantID:z.string().nullish(),Status:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),Vd=z.object({Experiments:z.array(_b).nullish(),IsAbTestingAvailable:z.boolean().nullish()}).passthrough(),Oa={GetExperiments:"GetExperiments"};var Zn=class extends L{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Oa.GetExperiments,e,Vd)}};var Nd=z.object({PlatformUserID:z.string().nullish(),PlatformAuthToken:z.string().nullish(),PlatformAuthTokenExpiration:p.nullish(),TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:p,PlayAccess:_t.nullish(),RefreshToken:z.string().nullish(),RefreshTokenExpiration:p.nullish()}),_d=z.object({TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:p,RefreshToken:z.string(),RefreshTokenExpiration:p.nullish(),PlayAccess:_t.nullish()}),jb=z.object({ReturnMode:z.string().nullish(),UrlScheme:z.string().nullish(),UserCodeSupported:z.boolean().nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),jd=z.object({Google:z.object({Enabled:z.boolean().nullish(),WebClientID:z.string().nullish(),PlatformFallback:z.boolean().nullish(),AndroidClientID:z.string().nullish(),IosClientID:z.string().nullish(),DesktopClientID:z.string().nullish()}).passthrough().nullish(),Apple:z.object({Enabled:z.boolean().nullish(),BundleID:z.string().nullish(),ServiceID:z.string().nullish()}).passthrough().nullish(),PlayAccessMode:qi.nullish(),WalletLoginNetworks:z.array(z.object({NetworkID:z.string().nullish(),Type:z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:z.boolean().nullish(),NativeSso:jb.nullish()}).passthrough(),Wd=z.object({Linked:z.boolean().nullish(),Challenge:z.string().nullish(),ExpiresAt:p.nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),PlayAccess:_t.nullish()}).passthrough(),Kd=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CooldownUntil:p.nullish(),PlayAccess:_t.nullish()}).passthrough(),Qd=z.object({CodeTtlMinutes:z.number().nullish(),ResendCooldownSeconds:z.number().nullish()}),Ge=z.object({IsCompleted:z.boolean().nullish(),ServerTime:p.nullish()}),Hd=z.object({Message: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 Yn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Wt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,Nd,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Le.RefreshSession),e,_d,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Le.GetAuthOptions),e,jd,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Wt(this.ctx.settings.titleID,"Authentication",Le.LinkWallet,e.UserID??""),e,Wd,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Wt(this.ctx.settings.titleID,"Authentication",Le.UnlinkWallet,e.UserID??""),e,Kd,{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,Qd,{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,Hd,{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 Wb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},$d=z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Kb=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),IsEnabled:z.boolean().nullish(),Order:z.number().nullish()}).passthrough(),Jd=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),Locales:z.record(z.string(),Kb).nullish(),MissingKeyMode:$d.nullish(),MaxEntriesPerLocale:z.number().nullish(),MaxValueLengthBytes:z.number().nullish()}).passthrough(),Qb=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish()}).passthrough(),Zd=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish(),Fallback:Qb.nullish()}).passthrough(),Xn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Hb=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),Order:z.number().nullish(),Version:z.number().nullish()}).passthrough(),Yd=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),MissingKeyMode:$d.nullish(),ResolvedLocale:z.string().nullish(),Locales:z.array(Hb).nullish()}).passthrough(),Xd=z.object({RequestedLocale:z.string().nullish(),Locale:z.string().nullish(),Version:z.number().nullish(),NotModified:z.boolean().nullish(),Entries:z.record(z.string(),z.string()).nullish(),FallbackLocale:z.string().nullish(),FallbackVersion:z.number().nullish()}).passthrough();var Ea=z.object({TitleConfigVersion:z.string().nullish(),TitleConfigUrl:z.string().nullish(),User:z.unknown().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish(),Localization:Zd.nullish(),Views:z.array(z.object({Name:z.string(),Key:z.string().nullish(),Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(r=>r),eh=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish()}).passthrough().transform(r=>r),th=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),User:z.unknown().nullish()}).passthrough().transform(r=>r),ih=z.object({}).passthrough().transform(r=>r),sh=z.object({}).passthrough().transform(r=>r),nh=z.object({Today:z.number(),Yesterday:z.number(),CurrentWeek:z.number(),CurrentMonth:z.number(),Total:z.number(),TotalSessions:z.number(),FirstActiveAt:p.nullish(),LastActiveAt:p.nullish(),LongestSessionEverSeconds:z.number().nullish(),CurrentWeekActiveHoursMask:z.number().nullish(),CurrentMonthActiveHoursMask:z.number().nullish(),ReactivationCount:z.number().nullish(),History:z.record(z.string(),z.unknown()).nullish()}).passthrough(),rh=z.object({Username:z.string()}),pt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var er=class extends L{constructor(e){super(e,"User");}getClientState(e){return this.send(pt.GetClientState,e,Ea)}getClientStateExcept(e){return this.send(pt.GetClientStateExcept,e,Ea)}getStateVersions(e){return this.send(pt.GetStateVersions,e,eh)}getUserState(e){return this.send(pt.GetUserState,e,th)}getInventory(e){return this.send(pt.GetInventory,e,ih)}getEventTokens(e){return this.send(pt.GetEventTokens,e,sh)}getUsageTime(e){return this.send(pt.GetUsageTime,e,nh)}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,rh)}};var tr=class extends L{constructor(e){super(e,"Currency");}convert(e){return this.send(Ui.Convert,e,Dp)}spend(e){return this.send(Ui.Spend,e,Pp)}cryptoConvert(e){return this.send(Ui.CryptoConvert,e,Ip)}};var $b=z.object({ItemInstanceID:z.string(),Units:z.number(),Level:z.number()}),Ua=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Level:z.number(),Resources:O.nullish(),FodderConsumed:z.array($b).nullish()}),oh=z.array(Te(Ua)),ir={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Jb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},Zb=z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Yb={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Xb=z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),eD=z.object({ContractAddress:z.string().nullish(),TokenID:z.string().nullish(),TokenStandard:z.string().nullish(),MaxLevel:z.number().nullish()}).passthrough(),tD=z.object({Networks:z.record(z.string(),eD).nullish(),MetadataUrl:z.string().nullish()}).passthrough(),iD=z.object({FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),sD=z.object({MinCharacterLevel:z.number().nullish(),UseRequirements:z.record(z.string(),z.number()).nullish(),AllowedCharacterIDs:z.array(z.string()).nullish(),AllowedSlotIDs:z.array(z.string()).nullish(),IdleRateBonus:z.number().nullish()}).passthrough(),nD=z.object({ValuationMode:Zb.nullish(),WeightCurve:_e.nullish(),Selection:Xb.nullish()}).passthrough(),rD=z.object({MaxLevel:z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:_e.nullish(),FlatBonusCurve:_e.nullish(),PercentBonusCurve:_e.nullish(),PowerCurve:_e.nullish(),Fodder:nD.nullish()}).passthrough(),oD=z.object({RarityID:z.string().nullish(),CollectionID:z.string().nullish(),AuthorID:z.string().nullish()}).passthrough(),aD=z.object({ItemID:z.string(),CatalogID:z.string(),ItemClass:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),CustomData:z.record(z.string(),z.string()).nullish(),IsStackable:z.boolean().nullish(),IsTradable:z.boolean().nullish(),Weight:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),NFT:tD.nullish(),Stats:iD.nullish(),Equipment:sD.nullish(),Upgrade:rD.nullish(),Metadata:oD.nullish(),ExpirationDurationSeconds:z.number().nullish(),MaxSupply:z.number().nullish()}).passthrough(),lD=z.object({Items:z.record(z.string(),aD).nullish()}).passthrough(),sr=z.object({Catalogs:z.record(z.string(),lD).nullish()}).passthrough();function De(r){return z.unknown().transform((e,t)=>{let i=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(i!=null){let n=me.safeParse(i);return n.success?{...e,CreditsConfirmation:n.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${n.error.message}`}),z.NEVER)}let s=r.safeParse(e);return s.success?s.data:(t.addIssue({code:"custom",message:s.error.message}),z.NEVER)})}var nr=class extends L{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(ir.UpgradeLevel,e,De(Ua))}upgradeLevelsBatch(e){return this.send(ir.UpgradeLevelsBatch,e,oh)}};var rr=class extends L{constructor(e){super(e,"Store");}purchase(e){return this.send(zt.Purchase,e,vo)}purchaseBatch(e){return this.send(zt.PurchaseBatch,e,ou)}getDefinitions(e){return this.send(zt.GetDefinitions,e,bs)}getUserState(e){return this.send(zt.GetUserState,e,au)}getStorefront(e){return this.send(zt.GetStorefront,e,Ds)}getCreditsConfirmation(e){return this.send(zt.GetCreditsConfirmation,e,me)}getCreditsBalance(e){return this.send(zt.GetCreditsBalance,e,ru)}};var uD={Apple:"Apple",Google:"Google"},or=z.object({PremiumID:z.string().nullish(),PurchaseDate:z.string().nullish(),ExpirationDate:z.string().nullish(),TransactionID:z.string().nullish(),IsAutoRenewEnabled:z.boolean().nullish()}).passthrough(),ar=z.object({Subscriptions:z.record(z.string(),or).nullish(),ActivatedTrialIDs:z.array(z.string()).nullish(),MaxActiveTier:z.number().nullish()}).passthrough().transform(r=>r),cD=z.object({PremiumID:z.string().nullish(),DisplayName:z.string().nullish(),Tier:z.number().nullish(),DurationDays:z.number().nullish(),TrialDurationDays:z.number().nullish(),PriceOptions:oe.nullish(),Benefits:z.record(z.string(),z.string()).nullish()}).passthrough(),Ba=z.object({Definitions:z.record(z.string(),cD).nullish()}).passthrough(),ah=z.object({Premium:Ba.nullish()}),lh=z.object({ServerTimeUtc:p.nullish(),Premium:ar.nullish()}),lr=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),Premium:ar.nullish(),Subscription:or.nullish(),Resources:O.nullish()}),Xt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var pD={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},dD=z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),uh=z.object({StartUtc:p.nullish(),EndUtc:p.nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),La=z.object({ResourceAction:z.string().nullish(),RevokeEntitlement:z.boolean().nullish(),BlockFuturePurchases:z.boolean().nullish()}).passthrough(),hD=z.object({PremiumID:z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:z.number().nullish(),RevokeOnRefund:z.boolean().nullish()}).passthrough(),mD=z.object({Rewards:Q.nullish(),Rules:Q.nullish(),Refund:Q.nullish()}).passthrough(),fD=z.object({ProductID:z.string().nullish(),Name:z.string().nullish(),Type:dD.nullish(),Enabled:z.boolean().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:z.number().nullish(),TelegramStarsPrice:z.number().nullish(),Rules:uh.nullish(),Refund:La.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Subscription:hD.nullish(),Presets:mD.nullish()}).passthrough(),gD=z.object({StoreID:z.string().nullish(),Enabled:z.boolean().nullish(),PackageName:z.string().nullish(),VerificationMode:z.string().nullish(),PlayPublicKey:z.string().nullish(),RequireCertificateChain:z.boolean().nullish(),SecretName:z.string().nullish(),IssuerID:z.string().nullish(),KeyID:z.string().nullish(),AcknowledgePurchases:z.boolean().nullish(),NotificationPackageName:z.string().nullish()}).passthrough(),yD=z.object({Rewards:H.nullish()}).passthrough(),RD=z.object({Rules:uh.nullish()}).passthrough(),CD=z.object({Refund:La.nullish()}).passthrough(),SD=z.object({Rewards:z.record(z.string(),yD).nullish(),Rules:z.record(z.string(),RD).nullish(),Refund:z.record(z.string(),CD).nullish()}).passthrough(),xD=z.object({MaxPurchaseAgeDays:z.number().nullish(),AllowSandbox:z.boolean().nullish(),RequirePackageMatch:z.boolean().nullish(),MaxReceiptsPerBatch:z.number().nullish(),RefundCheckHorizonDays:z.number().nullish(),RejectCrossUserReceipts:z.boolean().nullish()}).passthrough(),bD=z.object({Enabled:z.boolean().nullish(),Products:z.record(z.string(),fD).nullish(),Stores:z.record(z.string(),gD).nullish(),Presets:SD.nullish(),Validation:xD.nullish(),Refund:La.nullish()}).passthrough(),ch=z.object({ProductID:z.string().nullish(),TotalPurchases:z.number().nullish(),DailyPurchases:z.number().nullish(),DailyResetUtc:p.nullish(),LastPurchasedAt:p.nullish(),Owned:z.boolean().nullish(),Refunded:z.boolean().nullish(),PurchaseBlocked:z.boolean().nullish(),Store:z.string().nullish(),LastTransactionID:z.string().nullish()}).passthrough(),ph=z.object({ProductID:z.string().nullish(),PremiumID:z.string().nullish(),Store:z.string().nullish(),OriginalTransactionID:z.string().nullish(),LastTransactionID:z.string().nullish(),ExpiresAt:p.nullish(),AutoRenew:z.boolean().nullish(),Status:z.string().nullish(),RenewalCount:z.number().nullish(),LastStoreCheckAt:p.nullish(),LastStoreCheckError:z.string().nullish(),UpdatedAt:p.nullish()}).passthrough(),DD=z.object({Products:z.record(z.string(),ch).nullish(),LifetimeSpendUsdCents:z.number().nullish(),Subscriptions:z.record(z.string(),ph).nullish(),LastRefundCheckAt:p.nullish(),TotalPurchases:z.number().nullish(),FirstPurchaseAt:p.nullish(),LastPurchaseAt:p.nullish()}).passthrough(),ID=z.object({ProductID:z.string(),Available:z.boolean(),Owned:z.boolean(),Blocked:z.boolean(),Reason:z.string().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish()}).passthrough(),dh=z.object({ServerTimeUtc:p,Purchase:bD.nullish(),Availability:z.array(ID).nullish()}),hh=z.object({ServerTimeUtc:p,Purchase:DD.nullish()}),PD={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},vD=z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Ga=z.object({ServerTimeUtc:p,Store:Qi.nullish(),ProductID:z.string().nullish(),TransactionID:z.string().nullish(),Status:vD.nullish(),Granted:z.boolean().nullish(),Quantity:z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish(),ProductState:ch.nullish(),Premium:ar.nullish(),Subscription:or.nullish(),SubscriptionMirror:ph.nullish()}).passthrough(),mh=z.object({ServerTimeUtc:p,ProductID:z.string().nullish(),Stars:z.number().nullish(),InvoiceLink:z.string(),ExpiresAt:p.nullish()}).passthrough(),fh=St(Ga),ei={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var ur=class extends L{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(ei.GetDefinitions,e,dh)}getUserState(e){return this.send(ei.GetUserState,e,hh)}validatePurchase(e){return this.send(ei.ValidatePurchase,e,Ga)}validatePurchasesBatch(e){return this.send(ei.ValidatePurchasesBatch,e,fh)}createTelegramInvoice(e){return this.send(ei.CreateTelegramInvoice,e,mh)}};var TD=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),gh=z.object({Reward:H.nullish(),Weight:z.number().nullish(),AmountRange:TD.nullish()}).passthrough(),Ci=z.object({SlotID:z.string().nullish(),MinRolls:z.number().nullish(),MaxRolls:z.number().nullish(),Pool:z.array(gh).nullish()}).passthrough(),Si=z.object({RuleID:z.string().nullish(),Threshold:z.number().nullish(),Pool:z.array(gh).nullish()}).passthrough(),AD=z.object({RewardSlots:z.array(Ci).nullish()}).passthrough(),kD=z.object({PityRules:z.array(Si).nullish()}).passthrough(),cr=z.object({SlotPresets:z.record(z.string(),AD).nullish(),PityPresets:z.record(z.string(),kD).nullish()}).passthrough();var zD=z.object({RuleID:z.string(),BoxIndex:z.number().nullish()}),yh=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,LootboxID:z.string(),OpenedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish(),Results:z.array(O).nullish(),TriggeredPity:z.array(zD).nullish()}),wD=z.object({RewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),MD=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxDrops:W.nullish()}).passthrough(),OD=z.object({LootboxID:z.string(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:oe.nullish(),RewardSlots:z.array(Ci).nullish(),PityRules:z.array(Si).nullish(),Presets:wD.nullish(),RewardMultiplier:$i.nullish(),SupplyLimits:z.array(MD).nullish(),MaxOpenCount:z.number().nullish()}).passthrough(),ED=z.object({MaxOpenCount:z.number().nullish()}).passthrough(),Fa=z.object({Definitions:z.record(z.string(),OD).nullish(),RewardPools:cr.nullish(),Settings:ED.nullish()}).passthrough(),Rh=z.object({LootboxDefinitions:Fa.nullish()}),pr={GetDefinitions:"GetDefinitions",Open:"Open"};var dr=class extends L{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(pr.GetDefinitions,e,Rh)}open(e){return this.send(pr.Open,e,De(yh))}};var UD=z.object({}).passthrough().transform(r=>r),qD=z.object({}).passthrough().transform(r=>r),BD=z.object({}).passthrough().transform(r=>r),LD=z.object({}).passthrough().transform(r=>r),GD=z.object({}).passthrough().transform(r=>r),FD=z.object({}).passthrough().transform(r=>r),Ch=z.object({ServerTimeUtc:p,CalendarID:z.string(),DayNumber:z.number().nullish(),DailyState:UD,Resources:O.nullish(),Inventory:K.nullish()}),Sh=z.object({ServerTimeUtc:p,AccrualID:z.string(),AccruedSeconds:W.nullish(),AppliedRatePerSecond:z.number().nullish(),IdleState:qD,Resources:O.nullish(),Inventory:K.nullish()}),xh=z.object({ServerTimeUtc:p,ComebackID:z.string(),ClaimedTierIndex:z.number().nullish(),ComebackState:BD,Resources:O.nullish(),Inventory:K.nullish()}),bh=z.object({ServerTimeUtc:p,ClaimID:z.string(),ClaimState:LD,Resources:O.nullish(),Inventory:K.nullish()}),VD={None:"None",Ad:"Ad",Vip:"Vip"},Dh=z.object({ServerTimeUtc:p,WindowID:z.string(),Boost:z.string().nullish(),BaseAmount:W.nullish(),Multiplier:z.number().nullish(),Granted:W.nullish(),WindowState:GD,Resources:O.nullish(),Inventory:K.nullish()}),Ih=z.object({Enabled:z.boolean(),Multiplier:z.number().nullish(),Progress:W.nullish(),Source:z.string().nullish(),SourceKey:z.string().nullish()}),ND=z.object({RewardMode:z.string().nullish(),RewardStackLowerTiers:z.boolean().nullish()}).passthrough(),_D=z.object({DayNumber:z.number().nullish(),Rewards:H.nullish(),IsMilestone:z.boolean().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Fi=z.object({Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),Va=z.object({Availability:Q.nullish()}).passthrough(),jD=z.object({Availability:z.record(z.string(),Fi).nullish()}).passthrough(),WD=z.object({CalendarID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Days:z.array(_D).nullish(),IsLooping:z.boolean().nullish(),MissBehavior:z.string().nullish(),ResetByDays:z.number().nullish(),MissThresholdMultiplier:z.number().nullish(),ClaimMode:z.string().nullish(),ClaimCooldownSeconds:z.number().nullish(),Availability:Fi.nullish(),Presets:Va.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),KD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Multiplier:z.number().nullish()}).passthrough(),QD=z.object({BaseRatePerSecond:z.number().nullish(),PowerCoefficient:z.number().nullish(),BoardRankCoefficient:z.number().nullish(),EquipmentBonusEnabled:z.boolean().nullish(),EquipmentCharacterID:z.string().nullish(),PremiumMultipliers:z.array(KD).nullish()}).passthrough(),HD=z.object({MinCharacterLevel:z.number().nullish(),RequirementsCharacterID:z.string().nullish(),Availability:Fi.nullish(),RequiredItemIDs:z.array(z.string()).nullish(),RequiredEquippedItemIDs:z.array(z.string()).nullish()}).passthrough(),$D=z.object({AccrualID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rate:QD.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:z.number().nullish(),MinClaimSeconds:z.number().nullish(),Requirements:HD.nullish(),FirstClaimMode:z.string().nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),JD=z.object({MinAbsenceSeconds:z.number().nullish(),Rewards:H.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),ZD=z.object({ComebackID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(JD).nullish(),ClaimCooldownSeconds:z.number().nullish(),ClaimWindowSeconds:z.number().nullish(),TrackPresenceOnRead:z.boolean().nullish(),Availability:Fi.nullish(),Presets:Va.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),YD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),CooldownSeconds:z.number().nullish(),MaxClaimsPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish(),TotalClaimLimit:z.number().nullish()}).passthrough(),XD=z.object({ClaimID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Mode:z.string().nullish(),Rewards:H.nullish(),PremiumLimitOverrides:z.array(YD).nullish(),Availability:Fi.nullish(),Presets:Va.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),eI=z.object({CurrencyID:z.string().nullish(),MaxBaseAmount:z.number().nullish(),AdPlacementID:z.string().nullish(),AdMultiplier:z.number().nullish(),VipMultiplier:z.number().nullish(),VipPremiumID:z.string().nullish(),Limits:z.record(z.string(),z.unknown()).nullish()}).passthrough(),Na=z.object({TierRewards:ND.nullish(),MilestoneRewardMultiplier:$i.nullish(),DailyCalendars:z.record(z.string(),WD).nullish(),IdleAccruals:z.record(z.string(),$D).nullish(),Comebacks:z.record(z.string(),ZD).nullish(),Claims:z.record(z.string(),XD).nullish(),Windows:z.record(z.string(),eI).nullish(),Presets:jD.nullish()}).passthrough(),Ph=z.object({RewardDefinitions:Na.nullish()}),vh=z.object({Rewards:FD.nullish()}),Pt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var hr=class extends L{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Pt.GetRewardDefinitions,e,Ph)}getUserRewardsState(e){return this.send(Pt.GetUserRewardsState,e,vh)}getMilestoneRewardMultiplier(e){return this.send(Pt.GetMilestoneRewardMultiplier,e,Ih)}claimDailyReward(e){return this.send(Pt.ClaimDailyReward,e,Ch)}collectIdleAccrual(e){return this.send(Pt.CollectIdleAccrual,e,Sh)}claimComebackReward(e){return this.send(Pt.ClaimComebackReward,e,xh)}claimReward(e){return this.send(Pt.ClaimReward,e,bh)}claimRewardWindow(e){return this.send(Pt.ClaimRewardWindow,e,Dh)}};var mr=class extends L{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(at.GetTutorialDefinitions,e,Fl)}getUserTutorialState(e){return this.send(at.GetUserTutorialState,e,Yi)}startFlow(e){return this.send(at.StartFlow,e,qt)}reportStepShown(e){return this.send(at.ReportStepShown,e,qt)}completeStep(e){return this.send(at.CompleteStep,e,qt)}completeStepsBatch(e){return this.send(at.CompleteStepsBatch,e,_l)}skipStep(e){return this.send(at.SkipStep,e,qt)}skipFlow(e){return this.send(at.SkipFlow,e,qt)}claimFlowReward(e){return this.send(at.ClaimFlowReward,e,Nl)}resetFlow(e){return this.send(at.ResetFlow,e,qt)}};var tI={Open:"Open",Application:"Application"},iI=z.enum(["Open","Application"]).catch("Open"),sI={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Th=z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),nI={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},_a=z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),rI={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var ti={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},oI=z.object({CampaignID:z.string().nullish(),DisplayNameKey:z.string().nullish(),DescriptionKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),IsRunning:z.boolean().nullish()}).passthrough(),Ah=z.object({IsEnabled:z.boolean().nullish(),CreatorPortalUrl:z.string().nullish(),ParticipationMode:iI.nullish(),IsCreator:z.boolean().nullish(),CreatorStatus:Th.nullish(),VerificationCode:z.string().nullish(),TeamID:z.string().nullish(),Campaigns:z.array(oI).nullish()}).passthrough(),aI=z.object({Earned:z.number().nullish(),Mature:z.number().nullish(),CountedMetrics:z.record(z.string(),z.number()).nullish(),ReachedMilestones:z.array(z.string()).nullish(),CappedBySubmissionLimit:z.boolean().nullish(),CappedByCreatorLimit:z.boolean().nullish(),NotPaidAsCopy:z.boolean().nullish()}).passthrough(),lI=z.object({CampaignID:z.string().nullish(),CurrencyKind:_a.nullish(),CurrencyID:z.string().nullish(),NetworkID:z.string().nullish(),Earned:z.number().nullish(),Mature:z.number().nullish(),Granted:z.number().nullish(),Paid:z.number().nullish(),Overpaid:z.number().nullish(),Claimable:z.number().nullish(),BySubmission:z.record(z.string(),aI).nullish(),ComputedAt:z.string().nullish()}).passthrough(),uI=z.object({PayoutID:z.string().nullish(),CampaignID:z.string().nullish(),Amount:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:_a.nullish(),NetworkID:z.string().nullish(),PaidAt:z.string().nullish()}).passthrough(),kh=z.object({ServerTimeUtc:z.string().nullish(),HoldDays:z.number().nullish(),Campaigns:z.array(lI).nullish(),Payouts:z.array(uI).nullish()}).passthrough(),zh=z.object({CampaignID:z.string().nullish(),PayoutID:z.string().nullish(),Claimed:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:_a.nullish(),NetworkID:z.string().nullish(),RemainingFraction:z.number().nullish(),IdempotentReplay:z.boolean().nullish(),Message:z.string().nullish()}).passthrough(),cI=z.object({To:z.string().nullish(),Amount:z.string().nullish()}).passthrough(),pI=z.object({ContractAddress:z.string().nullish(),TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),Signature:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(cI).nullish()}).passthrough(),dI=z.object({Kind:z.string().nullish(),Target:z.string().nullish(),Required:z.number().nullish(),Actual:z.number().nullish(),Passed:z.boolean().nullish()}).passthrough(),wh=z.object({Passed:z.boolean().nullish(),Approved:z.boolean().nullish(),Status:Th.nullish(),WalletMissing:z.boolean().nullish(),WalletConnectAllowed:z.boolean().nullish(),Conditions:z.array(dI).nullish()}).passthrough(),hI=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),mI=z.object({ProgramID:z.string().nullish(),Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(hI).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),Mh=z.object({ServerTimeUtc:z.string().nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ChainID:z.number().nullish(),CurrencyID:z.string().nullish(),AmountNative:z.number().nullish(),NetAmountNative:z.number().nullish(),BurnAmountNative:z.number().nullish(),AmountUsd:z.number().nullish(),ExpiresAt:z.string().nullish(),EvmSignature:pI.nullish(),SolanaSignature:mI.nullish(),StateDelta:yi.nullish()}).passthrough();var fr=class extends L{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(ti.GetCommunityMarketingState,e,Ah)}getEarnings(e){return this.send(ti.GetEarnings,e,kh)}claim(e){return this.send(ti.Claim,e,zh)}checkJoinEligibility(e){return this.send(ti.CheckJoinEligibility,e,wh)}withdrawCryptoReward(e){return this.send(ti.WithdrawCryptoReward,e,Mh)}};var gr=class extends L{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send($e.GetChatDefinitions,e,Du)}getChannels(e){return this.send($e.GetChannels,e,Us)}poll(e){return this.send($e.Poll,e,Iu)}getHistory(e){return this.send($e.GetHistory,e,Pu)}getConversations(e){return this.send($e.GetConversations,e,Au)}sendMessage(e){return this.send($e.SendMessage,e,vu)}openDirectChannel(e){return this.send($e.OpenDirectChannel,e,Tu)}markRead(e){return this.send($e.MarkRead,e,fi)}joinChannel(e){return this.send($e.JoinChannel,e,fi)}leaveChannel(e){return this.send($e.LeaveChannel,e,fi)}reportMessage(e){return this.send($e.ReportMessage,e,ku)}ignoreUser(e){return this.send($e.IgnoreUser,e,fi)}unignoreUser(e){return this.send($e.UnignoreUser,e,fi)}};var yr=class extends L{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(gi.GetPushConfig,e,Mu)}subscribePush(e){return this.send(gi.SubscribePush,e,ko)}unsubscribePush(e){return this.send(gi.UnsubscribePush,e,Ge)}getPushSubscriptions(e){return this.send(gi.GetPushSubscriptions,e,Ou)}};var Rr=class extends L{constructor(e){super(e,"Localization");}send(e,t,i,s){let n=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${n}:${t.Locale}`:n,...s})}getLocalizationManifest(e){return this.send(Xn.GetLocalizationManifest,e,Yd)}getLocalizationTable(e){return this.send(Xn.GetLocalizationTable,e,Xd)}};var Cr=class extends L{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(ft.GetQuestDefinitions,e,Zi)}getUserQuestState(e){return this.send(ft.GetUserQuestState,e,Al)}refreshQuestCycles(e){return this.send(ft.RefreshQuestCycles,e,Ge)}claimQuestReward(e){return this.send(ft.ClaimQuestReward,e,mo)}claimQuestRewardsBatch(e){return this.send(ft.ClaimQuestRewardsBatch,e,wl)}claimMilestoneReward(e){return this.send(ft.ClaimMilestoneReward,e,fo)}claimMilestoneRewardsBatch(e){return this.send(ft.ClaimMilestoneRewardsBatch,e,Ml)}claimGroupCompletionReward(e){return this.send(ft.ClaimGroupCompletionReward,e,kl)}addQuestProgress(e){return this.send(ft.AddQuestProgress,e,zl)}};var Sr=class extends L{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ut.GetActiveEvents,e,Ns)}getDefinitions(e){return this.send(ut.GetDefinitions,e,Vs)}getUserLteState(e){return this.send(ut.GetUserLteState,e,Bu)}grantTokens(e){return this.send(ut.GrantTokens,e,O)}spendTokens(e){return this.send(ut.SpendTokens,e,Mo)}claimMilestone(e){return this.send(ut.ClaimMilestone,e,Oo)}claimMilestonesBatch(e){return this.send(ut.ClaimMilestonesBatch,e,Eo)}claimAllMilestones(e){return this.send(ut.ClaimAllMilestones,e,Eo)}spendTokensBatch(e){return this.send(ut.SpendTokensBatch,e,Lu)}grantTokensBatch(e){return this.send(ut.GrantTokensBatch,e,Gu)}};var xr=class extends L{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(je.GetDefinitions,e,$s)}getLeaderboard(e){return this.send(je.GetLeaderboard,e,zi)}getMyProgress(e){return this.send(je.GetMyProgress,e,js)}submitScore(e){return this.send(je.SubmitScore,e,Ws)}submitScoreFromSource(e){return this.send(je.SubmitScoreFromSource,e,Ws)}claimCycleReward(e){return this.send(je.ClaimCycleReward,e,Ks)}claimMilestone(e){return this.send(je.ClaimMilestone,e,Qs)}getFriendsLeaderboard(e){return this.send(je.GetFriendsLeaderboard,e,zi)}getLeaderboardsBatch(e){return this.send(je.GetLeaderboardsBatch,e,Nu)}getProgressBatch(e){return this.send(je.GetProgressBatch,e,Hs)}claimCycleRewardsBatch(e){return this.send(je.ClaimCycleRewardsBatch,e,_u)}claimMilestonesBatch(e){return this.send(je.ClaimMilestonesBatch,e,ju)}submitScoresBatch(e){return this.send(je.SubmitScoresBatch,e,Wu)}claimAllRewardsBatch(e){return this.send(je.ClaimAllRewardsBatch,e,Ku)}getOverviewBatch(e){return this.send(je.GetOverviewBatch,e,Qu)}};var br=class extends L{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Gt.GetDefinitions,e,Ys)}getActiveSeason(e){return this.send(Gt.GetActiveSeason,e,Zs)}getUserState(e){return this.send(Gt.GetUserState,e,Uo)}grantStatusTokens(e){return this.send(Gt.GrantStatusTokens,e,Zu)}claimTierReward(e){return this.send(Gt.ClaimTierReward,e,qo)}claimTierRewardsBatch(e){return this.send(Gt.ClaimTierRewardsBatch,e,Yu)}};var Dr=class extends L{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Xt.GetDefinitions,e,ah)}getUserState(e){return this.send(Xt.GetUserState,e,lh)}activateTrial(e){return this.send(Xt.ActivateTrial,e,lr)}purchaseItemOrCurrency(e){return this.send(Xt.PurchaseWithResources,e,De(lr))}purchaseRealMoney(e){return this.send(Xt.PurchaseRealMoney,e,lr)}};var Ir=class extends L{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(We.GetCharacterDefinitions,e,sn)}getUserCharacters(e){return this.send(We.GetUserCharacters,e,nc)}unlockCharacter(e){return this.send(We.UnlockCharacter,e,De(Fo))}upgradeStatLevel(e){return this.send(We.UpgradeStatLevel,e,De(Lo))}upgradeCharacterLevel(e){return this.send(We.UpgradeCharacterLevel,e,De(Go))}equipItems(e){return this.send(We.EquipItems,e,rc)}unequipItems(e){return this.send(We.UnequipItems,e,oc)}unequipAllCharacters(e){return this.send(We.UnequipAllCharacters,e,ac)}unlockCharactersBatch(e){return this.send(We.UnlockCharactersBatch,e,dc)}upgradeCharacterLevelsBatch(e){return this.send(We.UpgradeCharacterLevelsBatch,e,hc)}upgradeStatLevelsBatch(e){return this.send(We.UpgradeStatLevelsBatch,e,mc)}unlockSkin(e){return this.send(We.UnlockSkin,e,De(lc))}equipSkin(e){return this.send(We.EquipSkin,e,uc)}unequipSkin(e){return this.send(We.UnequipSkin,e,cc)}getCharacterSkins(e){return this.send(We.GetCharacterSkins,e,pc)}};var Pr=class extends L{constructor(e){super(e,"Match");}createMatch(e){return this.send(Dt.CreateMatch,e,Jp)}updateMatch(e){return this.send(Dt.UpdateMatch,e,Zp)}cancelMatch(e){return this.send(Dt.CancelMatch,e,Yp)}instantBattle(e){return this.send(Dt.InstantBattle,e,Xp)}saveStrategy(e){return this.send(Dt.SaveStrategy,e,Ge)}getMyMatches(e){return this.send(Dt.GetMyMatches,e,fa)}getAvailableMatches(e){return this.send(Dt.GetAvailableMatches,e,fa)}getDefinitions(e){return this.send(Dt.GetDefinitions,e,sd)}};var fI={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Oh=z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),gI={None:"None",Min:"Min",Average:"Average",Max:"Max"},yI=z.enum(["None","Min","Average","Max"]).catch("None"),RI={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},CI=z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),SI={Clamp:"Clamp",Reject:"Reject"},xI=z.enum(["Clamp","Reject"]).catch("Clamp"),bI=z.object({ItemInstanceID:z.string().nullish(),ItemID:z.string().nullish(),Level:z.number().nullish(),Units:z.number().nullish()}),DI=z.object({Index:z.number().nullish(),BurnedItemIDs:z.array(z.string()).nullish(),RolledCollectionID:z.string().nullish(),UsedCollections:z.record(z.string(),z.number()).nullish(),Output:co.nullish(),OutputLevel:z.number().nullish(),BurnedInstances:z.array(bI).nullish()}),Eh=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,Type:Oh.nullish(),CraftID:z.string(),CraftedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),InputRarity:z.string().nullish(),OutputRarity:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish(),Results:z.array(DI).nullish()}),II=z.object({CraftID:z.string().nullish(),Type:Oh.nullish(),CatalogID:z.string().nullish(),CollectionID:z.string().nullish(),InputRarityID:z.string().nullish(),OutputRarityID:z.string().nullish(),RequiredItemCount:z.number().nullish(),PriceOptions:oe.nullish(),OutputLevelMode:yI.nullish(),InputSelection:CI.nullish(),OutputLevelOverflow:xI.nullish()}).passthrough(),ja=z.object({Definitions:z.record(z.string(),II).nullish()}).passthrough(),Uh=z.object({ServerTimeUtc:p.nullish(),CraftDefinitions:ja.nullish()}),vr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Tr=class extends L{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(vr.GetDefinitions,e,Uh)}craft(e){return this.send(vr.Craft,e,De(Eh))}};var PI=2e5,Ar=class extends L{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,De(an),{timeoutMs:PI,autoRetry:false})}readGeneration(e,t){return this.send(e,t,an,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Be.GetDefinitions,e,Pc)}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)}estimateTemplatePrice(e){return this.send(Be.EstimateTemplatePrice,e,Ic,{throttleKey:`AI:EstimateTemplatePrice:${e.FeatureKey??""}:${JSON.stringify(e.Params??{})}`})}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 vI={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},TI=z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),qh=z.object({}).passthrough().transform(r=>r),xi=z.object({CollectibleID:z.string(),Rarity:z.number().nullish(),IsSpecial:z.boolean().nullish(),IsDuplicate:z.boolean().nullish(),CollectionCurrencyConverted:z.number().nullish()}),Bh=z.object({GrantedCollectibles:z.array(xi).nullish(),DuplicateCollectibles:z.array(xi).nullish(),CollectionCurrencyEarned:W.nullish()}),Lh=z.object({CreditsConfirmation:me.nullish(),OpenedCount:z.number().nullish(),Packs:z.array(Bh).nullish(),GrantedCollectibles:z.array(xi).nullish(),DuplicateCollectibles:z.array(xi).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),NewlyCompletedSetIDs:z.array(z.string()).nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),Gh=z.object({OpenedCount:z.number().nullish(),Chests:z.array(Bh).nullish(),GrantedCollectibles:z.array(xi).nullish(),DuplicateCollectibles:z.array(xi).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),Fh=z.object({GrantedCollectibleID:z.string().nullish(),NewlyCompletedSetID:z.string().nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Wa=z.object({SetID:z.string(),Resources:O.nullish(),Inventory:K.nullish()}),Vh=z.array(Te(Wa)),Nh=z.object({Resources:O.nullish(),Inventory:K.nullish()}),AI=z.object({OfferID:z.string(),TitleID:z.string().nullish(),CollectionID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderPublicData:qe.nullish(),OfferedCollectibleID:z.string().nullish(),OfferedCollectibleIsSpecial:z.boolean().nullish(),ReceiverUserID:z.string().nullish(),RequestedCollectibleID:z.string().nullish(),RequestedCollectibleIsSpecial:z.boolean().nullish(),Status:TI.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RespondedAtUtc:p.nullish(),DeclineReason:z.string().nullish(),IsSpecialTradeEvent:z.boolean().nullish(),SpecialTradeEventID:z.string().nullish()}).passthrough(),_h=z.object({OfferID:z.string(),ExpiresAtUtc:p.nullish(),Resources:O.nullish()}),jh=z.object({OfferID:z.string(),Resources:O.nullish()}),Wh=z.object({OfferID:z.string(),ReceivedCollectibleID:z.string().nullish(),ReceivedIsSpecial:z.boolean().nullish(),SentCollectibleID:z.string().nullish(),SentCollectibleIsSpecial:z.boolean().nullish(),Transfer:z.unknown().nullish()}),Kh=z.object({OfferID:z.string(),Resources:O.nullish()}),Ka=z.object({Offers:z.array(AI).nullish()}),kI=z.object({CollectibleID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rarity:z.number().nullish(),HasSpecialVersion:z.boolean().nullish(),SortOrder:z.number().nullish()}).passthrough(),zI=z.object({SetID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SortOrder:z.number().nullish(),Collectibles:z.array(kI).nullish(),SetCompletionReward:H.nullish()}).passthrough(),wI=z.object({CollectionID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SeasonChainID:z.string().nullish(),Sets:z.array(zI).nullish(),GrandPrize:H.nullish()}).passthrough(),Qh=z.object({BonusRewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),MI=z.object({PackTypeID:z.string().nullish(),PriceOptions:oe.nullish(),BonusRewardSlots:z.array(Ci).nullish(),PityRules:z.array(Si).nullish(),Presets:Qh.nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectibleCount:z.number().nullish(),MaxOpenCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),GuaranteeMaxRarity:z.boolean().nullish(),RarityWeights:z.record(z.string(),z.number()).nullish(),ColorTier:z.number().nullish()}).passthrough(),OI=z.object({Rarity:z.number().nullish(),CollectionCurrencyGranted:z.number().nullish()}).passthrough(),EI=z.object({CollectionChestID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectionCurrencyCost:z.number().nullish(),MaxOpenCount:z.number().nullish(),MinCollectibleCount:z.number().nullish(),MaxCollectibleCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),BonusRewardSlots:z.array(Ci).nullish(),PityRules:z.array(Si).nullish(),Presets:Qh.nullish(),Tier:z.number().nullish()}).passthrough(),UI=z.object({SpecialTradeEventID:z.string().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),AllowedSpecialCollectibleIDs:z.array(z.string()).nullish(),SpecialTradeEventDailyTradeLimit:z.number().nullish()}).passthrough(),qI=z.object({MaxPackOpenCount:z.number().nullish(),MaxChestOpenCount:z.number().nullish()}).passthrough(),kr=z.object({Collections:z.record(z.string(),wI).nullish(),PackTypes:z.record(z.string(),MI).nullish(),CollectionChests:z.array(EI).nullish(),DuplicateConversions:z.array(OI).nullish(),DailyTradeLimit:z.number().nullish(),CollectibleJokerCatalogID:z.string().nullish(),CollectibleJokerItemID:z.string().nullish(),SpecialTradeEvents:z.array(UI).nullish(),RewardPools:cr.nullish(),Settings:qI.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 zr=class extends L{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ke.GetDefinitions,e,kr)}getUserState(e){return this.send(Ke.GetUserState,e,qh)}openPack(e){return this.send(Ke.OpenPack,e,De(Lh))}openCollectionChest(e){return this.send(Ke.OpenCollectionChest,e,Gh)}useCollectibleJoker(e){return this.send(Ke.UseCollectibleJoker,e,Fh)}claimSetReward(e){return this.send(Ke.ClaimSetReward,e,Wa)}claimSetRewardsBatch(e){return this.send(Ke.ClaimSetRewardsBatch,e,Vh)}claimGrandPrize(e){return this.send(Ke.ClaimGrandPrize,e,Nh)}sendTradeOffer(e){return this.send(Ke.SendTradeOffer,e,_h)}cancelTradeOffer(e){return this.send(Ke.CancelTradeOffer,e,jh)}acceptTradeOffer(e){return this.send(Ke.AcceptTradeOffer,e,Wh)}declineTradeOffer(e){return this.send(Ke.DeclineTradeOffer,e,Kh)}getMyTradeOffers(e){return this.send(Ke.GetMyTradeOffers,e,Ka)}getIncomingTradeOffers(e){return this.send(Ke.GetIncomingTradeOffers,e,Ka)}};var wr=class extends L{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(yt.GetDefinitions,e,pn)}getActiveEvent(e){return this.send(yt.GetActiveEvent,e,Ac)}getUserState(e){return this.send(yt.GetUserState,e,cn)}getGroupState(e){return this.send(yt.GetGroupState,e,Ko)}joinOrCreateGroup(e){return this.send(yt.JoinOrCreateGroup,e,Ko)}spin(e){return this.send(yt.Spin,e,De(zc))}claimObjectReward(e){return this.send(yt.ClaimObjectReward,e,Qo)}claimGrandPrize(e){return this.send(yt.ClaimGrandPrize,e,Qo)}leaveGroup(e){return this.send(yt.LeaveGroup,e,wc)}};var Mr=class extends L{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(bt.GetDefinition,e,Nc)}getUserState(e){return this.send(bt.GetUserState,e,_c)}getActiveDeals(e){return this.send(bt.GetActiveDeals,e,mn)}dismissDeal(e){return this.send(bt.DismissDeal,e,Wc)}executeNode(e){return this.send(bt.ExecuteNode,e,De(jc))}recordShow(e){return this.send(bt.RecordShow,e,Kc)}claimMilestone(e){return this.send(bt.ClaimMilestone,e,Qc)}claimMilestonesBatch(e){return this.send(bt.ClaimMilestonesBatch,e,Hc)}};var BI=z.object({}).passthrough().transform(r=>r),LI=z.object({FeatureKey:z.string().nullish(),IsEnabled:z.boolean().nullish(),Rate:z.number().nullish(),Basis:z.string().nullish(),SourceCurrencyID:z.string().nullish(),TargetCurrencyID:z.string().nullish(),MinSourceAmount:z.number().nullish(),MaxRewardPerOperation:z.number().nullish(),Limits:Ce.nullish()}).passthrough(),Qa=z.object({IsEnabled:z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:z.record(z.string(),Ve).nullish(),SpendRewards:z.array(LI).nullish(),Qualification:z.object({}).passthrough().transform(r=>r).nullish()}).passthrough(),Ha=z.object({Pending:z.boolean().nullish(),Qualified:z.boolean().nullish(),Groups:z.array(z.object({GroupID:z.string().nullish(),Met:z.boolean().nullish(),Conditions:z.array(z.object({Type:z.string().nullish(),Met:z.boolean().nullish(),Current:z.number().nullish(),Required:z.number().nullish()}).passthrough()).nullish()}).passthrough()).nullish()}).passthrough(),Hh=z.object({ReferralDefinitions:Qa.nullish()}).passthrough(),$h=z.object({Referral:BI.nullish(),InviteUrl:z.string().nullish(),Qualification:Ha.nullish()}).passthrough(),Jh=z.object({QualificationPending:z.boolean().nullish(),Qualification:Ha.nullish()}).passthrough(),Zh=z.object({ReferralCode:z.string().nullish(),ReferrerUserID:z.string().nullish(),IsFirstActivation:z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish(),QualificationPending:z.boolean().nullish(),Qualification:Ha.nullish()}).passthrough(),$a=z.object({RewardID:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),Yh=St($a),Kt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var Or=class extends L{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Kt.GetDefinitions,e,Hh)}getUserState(e){return this.send(Kt.GetUserState,e,$h)}activateReferralCode(e){return this.send(Kt.ActivateReferralCode,e,Zh)}claimInviteReward(e){return this.send(Kt.ClaimInviteReward,e,$a)}claimInviteRewardsBatch(e){return this.send(Kt.ClaimInviteRewardsBatch,e,Yh)}checkQualification(e){return this.send(Kt.CheckQualification,e,Jh)}};var Er=class extends L{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(st.GetDefinitions,e,Xc)}getMessages(e){return this.send(st.GetMessages,e,ep)}getUnreadCount(e){return this.send(st.GetUnreadCount,e,yn)}readMessages(e){return this.send(st.ReadMessages,e,Jo)}claimReward(e){return this.send(st.ClaimReward,e,Rn)}claimRewardsBatch(e){return this.send(st.ClaimRewardsBatch,e,Rn)}claimAll(e){return this.send(st.ClaimAll,e,Rn)}deleteMessages(e){return this.send(st.DeleteMessages,e,Jo)}sendGift(e){return this.send(st.SendGift,e,tp)}sendTransfer(e){return this.send(st.SendTransfer,e,ip)}getGiftStatus(e){return this.send(st.GetGiftStatus,e,sp)}};var Ur=class extends L{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Sn.RequestAdPermit,e,np)}completeView(e){return this.send(Sn.CompleteView,e,rp)}};var qr=class extends L{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Se.GetFriendsList,e,Mi)}getIncomingRequests(e){return this.send(Se.GetIncomingRequests,e,Mi)}getOutgoingRequests(e){return this.send(Se.GetOutgoingRequests,e,Mi)}getRecommendedFriends(e){return this.send(Se.GetRecommendedFriends,e,Mi)}sendFriendRequest(e){return this.send(Se.SendFriendRequest,e,Oi)}acceptFriendRequest(e){return this.send(Se.AcceptFriendRequest,e,Oi)}declineFriendRequest(e){return this.send(Se.DeclineFriendRequest,e,Oi)}removeFriend(e){return this.send(Se.RemoveFriend,e,Oi)}getInbox(e){return this.send(Se.GetInbox,e,ap)}markInboxSeen(e){return this.send(Se.MarkInboxSeen,e,Ei)}getInboxUnread(e){return this.send(Se.GetInboxUnread,e,Ei)}follow(e){return this.send(Se.Follow,e,Nt)}unfollow(e){return this.send(Se.Unfollow,e,Nt)}getFollowers(e){return this.send(Se.GetFollowers,e,Dn)}getFollowing(e){return this.send(Se.GetFollowing,e,Dn)}block(e){return this.send(Se.Block,e,Nt)}unblock(e){return this.send(Se.Unblock,e,Nt)}getBlocked(e){return this.send(Se.GetBlocked,e,Dn)}react(e){return this.send(Se.React,e,Nt)}unreact(e){return this.send(Se.Unreact,e,Nt)}getMyReactions(e){return this.send(Se.GetMyReactions,e,up)}getEntityStates(e){return this.send(Se.GetEntityStates,e,lp)}addComment(e){return this.send(Se.AddComment,e,In)}editComment(e){return this.send(Se.EditComment,e,In)}deleteComment(e){return this.send(Se.DeleteComment,e,pp)}getComments(e){return this.send(Se.GetComments,e,cp)}report(e){return this.send(Se.Report,e,dp)}};var GI={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var ii=z.object({Target:z.string().nullish(),Operation:z.string().nullish(),Value:z.number().nullish()}).passthrough(),FI=z.object({BoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:oe.nullish(),Effect:ii.nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),Br=z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Ja=z.object({Availability:Q.nullish(),Effects:Q.nullish()}).passthrough(),VI=z.object({ScheduledBoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Effects:z.array(ii).nullish(),Availability:Br.nullish(),Presets:Ja.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),NI=z.object({ChainedBoostID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Effects:z.array(ii).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),_I=z.object({ChainID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Phases:z.array(NI).nullish(),Availability:Br.nullish(),Presets:Ja.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),jI=z.object({TriggeredBoostID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Sources:z.array(ot).nullish(),Effects:z.array(ii).nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Availability:Br.nullish(),Presets:Ja.nullish()}).passthrough(),WI=z.object({MaxAddPercent:z.number().nullish(),MaxMultiply:z.number().nullish(),MaxAddFlat:z.number().nullish()}).passthrough(),KI=z.object({Effects:z.array(ii).nullish()}).passthrough(),QI=z.object({Availability:z.record(z.string(),Br).nullish(),Effects:z.record(z.string(),KI).nullish()}).passthrough(),HI=z.object({StackingCaps:z.record(z.string(),WI).nullish()}).passthrough(),Lr=z.object({Definitions:z.record(z.string(),FI).nullish(),ScheduledBoosts:z.record(z.string(),VI).nullish(),BoostChains:z.record(z.string(),_I).nullish(),TriggeredBoosts:z.record(z.string(),jI).nullish(),Settings:HI.nullish(),Presets:QI.nullish()}).passthrough(),Xh=z.object({InstanceID:z.string(),BoostID:z.string(),ActivatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RemainingCharges:z.number().nullish(),EffectSnapshot:ii.nullish(),SourceType:z.string().nullish(),SourceRef:z.string().nullish()}).passthrough();z.object({Date:p.nullish(),DailyCount:z.number().nullish(),LastFiredUtc:p.nullish()}).passthrough();var em=z.object({ServerTimeUtc:p.nullish(),Active:z.record(z.string(),Xh).nullish()}),tm=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),BoostID:z.string().nullish(),StackingPolicy:z.string().nullish(),ActivatedBoost:Xh.nullish(),Resources:O.nullish()}),$I={Scheduled:"Scheduled",Chain:"Chain"},JI=z.object({Kind:z.string().nullish(),SourceID:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),PhaseOrder:z.number().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),Effects:z.array(ii).nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),im=z.object({ServerTimeUtc:p.nullish(),Windows:z.array(JI).nullish()}),si={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Gr=class extends L{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(si.GetDefinitions,e,Lr)}getActive(e){return this.send(si.GetActive,e,em)}getActiveWindows(e){return this.send(si.GetActiveWindows,e,im)}activate(e){return this.send(si.Activate,e,De(tm))}cleanupExpired(e){return this.send(si.CleanupExpired,e,Ge)}};var Fr=class extends L{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(Rt.GetUserCustomDataDefinitions,e,An)}getMyUserCustomData(e){return this.send(Rt.GetMyUserCustomData,e,gp)}getPublicUserCustomDataOf(e){return this.send(Rt.GetPublicUserCustomDataOf,e,na)}setPrivateData(e){return this.send(Rt.SetPrivateData,e,ra)}setPublicData(e){return this.send(Rt.SetPublicData,e,ra)}deleteKey(e){return this.send(Rt.DeleteKey,e,Ge)}batchSet(e){return this.send(Rt.BatchSet,e,yp)}batchDelete(e){return this.send(Rt.BatchDelete,e,Rp)}batchGetPublicUserCustomDataOf(e){return this.send(Rt.BatchGetPublicUserCustomDataOf,e,Cp)}};var ZI={Static:"Static",Runtime:"Runtime"},YI={Public:"Public",Private:"Private"},XI=z.enum(["Client","Server","System"]).catch("Client"),eP=z.enum(["String","Int","Bool","Json"]).catch("String"),tP=z.object({Value:z.string().nullish(),UpdatedAt:p.nullish(),Version:z.number().nullish(),LastWriter:XI.nullish(),ExpiresAt:p.nullish()}).passthrough(),sm=z.record(z.string(),tP),Za=z.object({StaticVersion:z.number().nullish(),RuntimeVersion:z.number().nullish(),Static:sm.nullish(),Runtime:sm.nullish(),NotModified:z.boolean().nullish()}),iP=z.object({KeyID:z.string(),Scope:z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:eP.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),Vr=z.object({Keys:z.record(z.string(),iP).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),Vi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Nr=class extends L{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Vi.GetTitleCustomDataDefinitions,e,Vr)}getPublicTitleData(e){return this.send(Vi.GetPublicTitleData,e,Za)}getPublicTitleDataKeys(e){return this.send(Vi.GetPublicTitleDataKeys,e,Za)}};var nm=z.object({Theme:z.record(z.string(),z.string()).nullish(),Radius:z.number().nullish(),ButtonRadius:z.number().nullish(),Outline:z.number().nullish(),Background:z.string().nullish(),MotionSpeed:z.number().nullish(),MotionIntensity:z.number().nullish(),Particles:z.boolean().nullish(),SoundSet:z.string().nullish()}).passthrough();var sP={Fast:"Fast",Sequential:"Sequential"},nP={Instant:"Instant",Timed:"Timed"};var rP={Hit:"Hit",Blocked:"Blocked"},oP=z.object({SlotIndex:z.number(),Level:z.number().nullish(),IsDamaged:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish()}).passthrough(),aP=z.object({Symbol:z.union([z.string(),z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:z.string().nullish()}).passthrough();z.object({ElapsedSeconds:z.number().nullish(),Reward:H.nullish()}).passthrough();var lP=z.object({RequiredValue:z.number().nullish(),Reward:H.nullish()}).passthrough(),uP=z.object({Reward:H.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough();z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(lP).nullish(),Rate:uP.nullish()}).passthrough();z.object({PlayedCount:z.number().nullish(),RewardsClaimedCount:z.number().nullish(),InstantClaimsCount:z.number().nullish(),EarlyClaimsCount:z.number().nullish(),LateClaimsCount:z.number().nullish(),AdViewsTotal:z.number().nullish(),StatRewardClaimsCount:z.number().nullish(),StatReportsClampedCount:z.number().nullish(),StatReportsUnknownMetricCount:z.number().nullish()}).passthrough();var rm=z.object({}).passthrough().transform(r=>r),om=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),Qe=z.object({Operation:O.nullish(),ScaleWithRollMultiplier:z.boolean().nullish()}).passthrough(),cP=z.object({Count:z.number().nullish(),Sides:z.number().nullish()}).passthrough(),pP=z.object({ShieldChance:z.number().nullish(),DamagedBuildingChance:z.number().nullish(),RankMultiplierMin:z.number().nullish(),RankMultiplierMax:z.number().nullish(),RankOffsetMin:z.number().nullish(),RankOffsetMax:z.number().nullish(),StageLevelSpread:z.number().nullish()}).passthrough(),dP=z.object({CostMatrixTemplatesByID:z.record(z.string(),z.array(z.array(z.number()))).nullish(),PerBoardGrowth:z.number().nullish(),VisualTemplateCycle:z.array(z.string()).nullish(),EconomyScaledResources:ue.nullish(),ScaleRaidStealWithEconomy:z.boolean().nullish(),ScaleAttackRewardWithEconomy:z.boolean().nullish(),AttackValueFromCostMatrix:z.boolean().nullish(),AttackBlockedRewardFactor:z.number().nullish(),ScaleVictimLossWithEconomy:z.boolean().nullish(),ScaleVictimLossWithTier:z.boolean().nullish(),SynthesizedBuildingSlots:z.number().nullish(),SynthesizedBuildingMaxLevel:z.number().nullish(),DifficultyGrowthPerBoard:z.number().nullish()}).passthrough(),hP=z.object({CostMatrix:z.array(z.array(z.number())).nullish(),PerBoardGrowth:z.number().nullish(),EconomyScale:z.number().nullish(),ScaledResources:ue.nullish()}).passthrough(),am=z.object({SlotIndex:z.number().nullish(),Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxLevel:z.number().nullish(),MaxLevelReward:H.nullish()}).passthrough(),mP=z.object({Index:z.number().nullish(),Type:z.string().nullish(),CustomTypeID:z.string().nullish(),RandomActionAttackWeight:z.number().nullish(),RandomActionRaidWeight:z.number().nullish(),ChanceTableID:z.string().nullish(),SpecialModeID:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),fP=z.object({Tiles:z.record(z.string(),mP).nullish()}).passthrough(),gP=z.object({Weight:z.number().nullish(),Bonus:Qe.nullish(),Tag:z.string().nullish()}).passthrough(),yP=z.object({Weight:z.number().nullish(),Tag:z.string().nullish(),MinBonusCells:z.number().nullish(),MaxBonusCells:z.number().nullish(),BonusPool:z.array(gP).nullish(),GuaranteedBonus:Qe.nullish(),IsJackpot:z.boolean().nullish(),JackpotFinalMultiplier:z.number().nullish(),JackpotSymbolDistribution:z.record(z.string(),z.number()).nullish()}).passthrough(),RP=z.object({Variants:z.array(yP).nullish()}).passthrough(),CP=z.object({Weight:z.number().nullish(),OutcomeID:z.string().nullish(),Reward:Qe.nullish(),ForceAction:z.string().nullish(),SpecialModeID:z.string().nullish()}).passthrough(),SP=z.object({Outcomes:z.array(CP).nullish()}).passthrough(),lm=z.object({PerAdMultiplierRange:om.nullish(),MaxAdViews:z.number().nullish(),AdCreditCost:z.number().nullish(),FormulaKind:z.string().nullish(),ApplyMultiplierOnEarlyClaim:z.boolean().nullish()}).passthrough(),xP=z.object({ElapsedSeconds:z.number().nullish(),Reward:Qe.nullish()}).passthrough(),bP=z.object({Tiers:z.array(xP).nullish(),TierMode:z.string().nullish(),BelowFirstTierReward:Qe.nullish()}).passthrough(),DP=z.object({RequiredValue:z.number().nullish(),Reward:Qe.nullish()}).passthrough(),IP=z.object({Reward:Qe.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough(),PP=z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(DP).nullish(),Rate:IP.nullish()}).passthrough(),um=z.object({MetricsByID:z.record(z.string(),PP).nullish()}).passthrough(),vP=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:oe.nullish(),Multipliers:lm.nullish(),Gradation:bP.nullish(),RunStats:um.nullish()}).passthrough(),TP=z.object({Choices:z.array(vP).nullish(),OfferExpireSeconds:z.number().nullish(),ClaimExpireSeconds:z.number().nullish()}).passthrough(),AP=z.object({Chance:z.number().nullish(),RequiredOutcome:z.string().nullish(),Reward:Qe.nullish(),Tag:z.string().nullish()}).passthrough(),kP=z.object({OnPassStart:Qe.nullish(),OnTileLanding:z.record(z.string(),Qe).nullish(),OnAttack:z.record(z.string(),Qe).nullish(),OnRaid:z.record(z.string(),Qe).nullish(),OnBuild:Qe.nullish(),OnStageComplete:Qe.nullish(),OnAttackBonusDrops:z.array(AP).nullish(),ChanceTablesByID:z.record(z.string(),SP).nullish(),SpecialModesByID:z.record(z.string(),TP).nullish()}).passthrough(),cm=z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:z.number().nullish(),MaxShields:z.number().nullish(),Buildings:z.array(am).nullish(),HeistGridBonusConfig:RP.nullish(),StageOperations:kP.nullish(),TileLandingMultiplier:om.nullish(),EconomyOverride:hP.nullish()}).passthrough(),zP=z.object({Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BoardTemplateID:z.string().nullish(),Buildings:z.array(am).nullish(),StageTemplateID:z.string().nullish(),CostMatrixTemplateID:z.string().nullish(),UnitValue:z.number().nullish(),Override:cm.nullish()}).passthrough(),wP=z.object({AttackCooldownSeconds:z.number().nullish(),RaidCooldownSeconds:z.number().nullish(),MaxRecentTargets:z.number().nullish(),LiveOpponentActiveDays:z.number().nullish(),LiveOpponentPoolSize:z.number().nullish(),LiveOpponentPoolCacheSeconds:z.number().nullish(),MaxLiveCandidateReads:z.number().nullish(),VictimImmunitySeconds:z.number().nullish()}).passthrough(),MP=z.object({Enabled:z.boolean().nullish(),IntervalSeconds:z.number().nullish(),MaxPerCatchUp:z.number().nullish(),Chance:z.number().nullish(),AttackWeight:z.number().nullish(),RaidWeight:z.number().nullish(),MinBoardStageLevel:z.number().nullish(),RaidLossMultiplier:z.number().nullish()}).passthrough(),_r=z.object({RollCurrencyID:z.string().nullish(),ShieldCurrencyID:z.string().nullish(),RaidMode:z.string().nullish(),AllowedRollMultipliers:z.array(z.number()).nullish(),BoardTemplatesByID:z.record(z.string(),fP).nullish(),StageTemplatesByID:z.record(z.string(),cm).nullish(),StagesByLevel:z.record(z.string(),zP).nullish(),SoftCurrencyID:z.string().nullish(),ProceduralEconomy:dP.nullish(),Dice:cP.nullish(),Bots:pP.nullish(),Targeting:wP.nullish(),BotRaids:MP.nullish()}).passthrough(),OP=z.object({IsActive:z.boolean().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AnchorUtc:p.nullish(),RoundDurationSec:z.number().nullish(),PauseBetweenRoundsSec:z.number().nullish(),MaxRounds:z.number().nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),ContributionMin:z.number().nullish(),ContributionMax:z.number().nullish(),ScaleContributionWithRollMultiplier:z.boolean().nullish(),MaxProgress:z.number().nullish(),Milestones:z.record(z.string(),Ve).nullish(),GrandPrize:H.nullish()}).passthrough(),jr=z.object({Board:_r.nullish(),CommunityChest:OP.nullish()}).passthrough(),pm=z.object({AttackerGainByOutcome:z.record(z.string(),ue).nullish()}).passthrough(),EP=z.object({TargetUserID:z.string().nullish(),IsBot:z.boolean().nullish(),PublicData:qe.nullish(),TargetBuildingStates:z.array(oP).nullish(),TargetHasShield:z.boolean().nullish(),TargetStageLevel:z.number().nullish(),RaidRewardPreview:pm.nullish()}).passthrough(),UP=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:oe.nullish(),Multipliers:lm.nullish(),RunStats:um.nullish()}).passthrough(),qP=z.object({ModeID:z.string().nullish(),Choices:z.array(UP).nullish()}).passthrough(),BP=z.object({GroupID:z.string().nullish(),Delta:W.nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),UnlockedMilestoneIDs:z.array(z.string()).nullish(),Completed:z.boolean().nullish()}).passthrough(),dm=z.object({UsedMultiplier:z.number().nullish(),Steps:z.number().nullish(),DiceValues:z.array(z.number()).nullish(),OldPosition:z.number().nullish(),NewPosition:z.number(),CyclesCompletedDelta:W.nullish(),LandedTileType:z.string().nullish(),Operation:O.nullish(),Inventory:K.nullish(),ActionRequired:z.string().nullish(),ActionData:EP.nullish(),SpecialModeOffer:qP.nullish(),CommunityChestContribution:BP.nullish()}).passthrough(),hm=z.object({Outcome:z.string().nullish(),IsBotTarget:z.boolean().nullish(),BuildingIndexHit:z.number().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:At.nullish()}).passthrough(),Ya=z.object({Status:z.string().nullish(),Outcome:z.string().nullish(),FoundSymbol:z.union([z.string(),z.number()]).nullish(),FoundBonus:H.nullish(),OpenedIndex:z.number().nullish(),AttemptsLeft:z.number().nullish(),RaidLayout:z.array(aP).nullish(),HeistVariantTag:z.string().nullish(),IsJackpot:z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:At.nullish(),RaidRewardPreview:pm.nullish()}).passthrough(),mm=z.object({BuiltIndex:z.number(),NewLevel:z.number().nullish(),StageComplete:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish()}).passthrough(),fm=z.object({CreditsConfirmation:me.nullish(),Mode:z.union([z.string(),z.number()]).nullish(),Operation:O.nullish(),Inventory:K.nullish(),DurationSeconds:z.number().nullish(),StartedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish()}).passthrough(),gm=z.object({AdViewsUsed:z.number().nullish(),RolledMultiplier:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),RemainingAdViews:z.number().nullish()}).passthrough(),LP=z.object({MetricID:z.string().nullish(),ReachedTierIndex:z.number().nullish(),RequiredValue:z.number().nullish(),RewardUnits:z.number().nullish()}).passthrough(),ym=z.object({FinalMultiplier:z.number().nullish(),AdViewsUsed:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),IsEarlyClaim:z.boolean().nullish(),ReachedTierIndex:z.number().nullish(),Operation:O.nullish(),Inventory:K.nullish(),AcceptedRunStats:z.record(z.string(),z.number()).nullish(),RunStatAwards:z.array(LP).nullish(),RunStatsClamped:z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),GP={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Rm=z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),FP={Active:"Active",Left:"Left",Replaced:"Replaced"},VP=z.enum(["Active","Left","Replaced"]).catch("Active"),NP=z.object({CurrentProgress:W.nullish(),MaxProgress:W.nullish()}).passthrough(),_P=z.object({UserID:z.string().nullish(),PublicData:qe.nullish(),IsBot:z.boolean().nullish(),ContributionPoints:W.nullish(),MilestoneClaims:z.record(z.string(),Pl).nullish(),GrandPrizeClaimed:z.boolean().nullish(),MemberStatus:VP.nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),Cm=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),RoundIndex:z.number().nullish(),Members:z.array(_P).nullish(),SharedProgress:NP.nullish(),Status:Rm.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:z.number().nullish()}).passthrough(),jP=z.object({GroupID:z.string().nullish(),RoundIndex:z.number().nullish(),FinalStatus:Rm.nullish(),GrandPrizeReceived:z.boolean().nullish(),FinishedAtUtc:p.nullish()}).passthrough(),WP=z.object({ActiveGroupID:z.string().nullish(),ActiveRoundIndex:z.number().nullish(),History:z.array(jP).nullish()}).passthrough(),Sm=z.object({ServerTimeUtc:p.nullish(),UserState:WP.nullish(),ActiveGroup:Cm.nullish(),SecondsRemaining:W.nullish()}),xm=z.object({ServerTimeUtc:p.nullish(),Group:Cm.nullish(),SecondsRemaining:W.nullish()}),Xa=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),bm=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),Success: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 KP={Mesh:"Mesh",Host:"Host"},el=z.enum(["Mesh","Host"]).catch("Mesh"),QP={ServerRelay:"ServerRelay",P2P:"P2P"},tl=z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),HP={Public:"Public",Private:"Private"},$P=z.enum(["Public","Private"]).catch("Public"),JP={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},ZP=z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Dm=z.object({Urls:z.string().nullish(),Username:z.string().nullish(),Credential:z.string().nullish()}).passthrough(),YP=z.object({Enabled:z.boolean().nullish()}).passthrough(),Im=z.object({SystemState:YP.nullish(),DefaultTopology:el.nullish(),AllowCreatorTopologyOverride:z.boolean().nullish(),DefaultChatMode:tl.nullish(),AllowCreatorChatOverride:z.boolean().nullish(),MaxPlayersPerRoom:z.number().nullish(),RoomTtlSeconds:z.number().nullish(),MaxRoomLifetimeSeconds:z.number().nullish(),HeartbeatIntervalMs:z.number().nullish(),MemberTimeoutMs:z.number().nullish(),MaxSignalPayloadBytes:z.number().nullish(),MaxChatTextLength:z.number().nullish(),RoomLogCap:z.number().nullish(),VoiceEnabled:z.boolean().nullish(),RecordVoices:z.boolean().nullish(),IceServers:z.array(Dm).nullish()}).passthrough(),XP=z.object({UserID:z.string().nullish(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),Ready:z.boolean().nullish(),State:z.record(z.string(),z.string()).nullish(),JoinedAt:z.number().nullish(),IsHost:z.boolean().nullish(),LastSeenMs:z.number().nullish()}).passthrough(),ev=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),Topology:el.nullish(),ChatMode:tl.nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),MemberCount:z.number().nullish(),CreatedAt:z.number().nullish()}).passthrough(),tv=z.object({Seq:z.number().nullish(),Type:ZP.nullish(),FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Kind:z.string().nullish(),Payload:z.string().nullish(),Ts:z.number().nullish()}).passthrough(),Ni=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),OwnerUserID:z.string().nullish(),Topology:el.nullish(),ChatMode:tl.nullish(),Visibility:$P.nullish(),Status:z.string().nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),Members:z.array(XP).nullish(),IceServers:z.array(Dm).nullish(),Seq:z.number().nullish(),BannedUserIDs:z.array(z.string()).nullish()}).passthrough(),Pm=z.object({Removed:z.boolean().nullish(),Banned:z.boolean().nullish()}).passthrough(),vm=z.object({WasBanned:z.boolean().nullish()}).passthrough(),il=z.object({Closed:z.boolean().nullish(),NewHostUserID:z.string().nullish()}).passthrough(),Tm=z.object({Rooms:z.array(ev).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}).passthrough(),Am=z.object({Envelopes:z.array(tv).nullish(),MaxSeq:z.number().nullish()}).passthrough(),Wr=z.object({Seq: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 sl=z.object({TitleCustomData:Vr.nullish(),Character:sn.nullish(),Item:sr.nullish(),Currency:En.nullish(),Store:bs.nullish(),Lootbox:Fa.nullish(),Quest:Zi.nullish(),TimedEvent:Vs.nullish(),Leaderboard:$s.nullish(),Season:Ys.nullish(),Reward:Na.nullish(),Collection:kr.nullish(),Craft:ja.nullish(),DealOffer:Ho.nullish(),Premium:Ba.nullish(),TimedBoost:Lr.nullish(),CoopEvent:pn.nullish(),GameLoop:jr.nullish(),Match:ga.nullish(),Experiment:Fd.nullish(),Blockchain:ua.nullish(),Marketplace:xa.nullish(),Multiplayer:Im.nullish(),UserCustomData:An.nullish(),Referral:Qa.nullish(),Localization:Jd.nullish(),Analytics:kd.nullish(),Social:hp.nullish(),PlatformBridge:mp.nullish(),GameSpec:z.string().nullish(),Look:nm.nullish()}).passthrough();var ni={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Kr=class extends L{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(ni.GetTitlePublicConfiguration,e,sl)}getTitlePublicConfigurationExcept(e){return this.send(ni.GetTitlePublicConfigurationExcept,e,sl)}getCurrencyDefinitions(e){return this.send(ni.GetCurrencyDefinitions,e,En)}getItemDefinitions(e){return this.send(ni.GetItemDefinitions,e,sr)}getServerTime(e){return this.send(ni.GetServerTime,e,Ge)}};var Qr=class extends L{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Fe.GetGameLoops,e,jr)}getBoardDefinition(e,t=false){return this.send(Fe.GetBoardDefinition,e,_r,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Fe.GetBoardDefinitionForLevel,e,_r,{silent:t})}getUserBoardState(e){return this.send(Fe.GetUserBoardState,e,rm)}boardLoopRoll(e){return this.send(Fe.BoardLoopRoll,e,dm)}boardLoopAttack(e){return this.send(Fe.BoardLoopAttack,e,hm)}boardLoopRaid(e){return this.send(Fe.BoardLoopRaid,e,Ya)}boardLoopRaidFast(e){return this.send(Fe.BoardLoopRaidFast,e,Ya)}boardLoopBuild(e){return this.send(Fe.BoardLoopBuild,e,mm)}boardSpecialChoose(e){return this.send(Fe.BoardSpecialChoose,e,De(fm))}boardSpecialApplyMultiplier(e){return this.send(Fe.BoardSpecialApplyMultiplier,e,gm)}boardSpecialClaim(e){return this.send(Fe.BoardSpecialClaim,e,ym)}getCommunityChestState(e){return this.send(Fe.GetCommunityChestState,e,Sm)}joinOrCreateCommunityChest(e){return this.send(Fe.JoinOrCreateCommunityChest,e,xm)}claimCommunityChestMilestone(e){return this.send(Fe.ClaimCommunityChestMilestone,e,Xa)}claimCommunityChestGrandPrize(e){return this.send(Fe.ClaimCommunityChestGrandPrize,e,Xa)}leaveCommunityChest(e){return this.send(Fe.LeaveCommunityChest,e,bm)}};var iv={Live:"Live",Latest:"Latest",Specific:"Specific"},sv={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},nv=z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),rv={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"},ov=z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),av=z.object({Level:nv,Message:z.string().nullish(),Data:Ft.nullish()}),lv=z.object({Error:ov,Message:z.string().nullish(),StackTrace:z.string().nullish()}),zm=z.object({FunctionName:z.string().nullish(),Revision:z.number().nullish(),FunctionResult:Ft.nullish(),FunctionResultTooLarge:z.boolean().nullish(),Logs:z.array(av).nullish(),LogsTooLarge:z.boolean().nullish(),ExecutionTimeSeconds:z.number().nullish(),APIRequestsIssued:z.number().nullish(),Error:lv.nullish()}),nl={Execute:"Execute"};var Hr=class extends L{constructor(e){super(e,"CloudCode");}execute(e){return this.send(nl.Execute,e,zm)}};var $r=class extends L{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Je.GetDefinitions,e,Bp)}getUserState(e){return this.send(Je.GetUserState,e,Lp)}depositToken(e){return this.send(Je.DepositToken,e,Gp)}depositNFT(e){return this.send(Je.DepositNFT,e,Fp)}requestTokenWithdrawal(e){return this.send(Je.RequestTokenWithdrawal,e,Vp)}requestNFTWithdrawal(e){return this.send(Je.RequestNFTWithdrawal,e,Np)}getTransactionHistory(e){return this.send(Je.GetTransactionHistory,e,_p)}retryWithdrawal(e){return this.send(Je.RetryWithdrawal,e,jp)}confirmWithdrawal(e){return this.send(Je.ConfirmWithdrawal,e,Wp)}donateToDeveloper(e){return this.send(Je.DonateToDeveloper,e,ha)}donateToUsersPool(e){return this.send(Je.DonateToUsersPool,e,ha)}getPlayAccess(e){return this.send(Je.GetPlayAccess,e,Up)}confirmPlayAccess(e){return this.send(Je.ConfirmPlayAccess,e,_t)}};var Jr=class extends L{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Me.GetDefinitions,e,rd)}getGroupedOffers(e){return this.send(Me.GetGroupedOffers,e,od)}getOffersByItem(e){return this.send(Me.GetOffersByItem,e,ba)}getOffer(e){return this.send(Me.GetOffer,e,ad)}getBuyOrders(e){return this.send(Me.GetBuyOrders,e,ba)}getMyState(e){return this.send(Me.GetMyState,e,Vn)}getHistory(e){return this.send(Me.GetHistory,e,ud)}createListing(e){return this.send(Me.CreateListing,e,Li)}cancelListing(e){return this.send(Me.CancelListing,e,ct)}buy(e){return this.send(Me.Buy,e,ct)}marketBuy(e){return this.send(Me.MarketBuy,e,ct)}marketSell(e){return this.send(Me.MarketSell,e,ct)}createAuction(e){return this.send(Me.CreateAuction,e,Li)}placeBid(e){return this.send(Me.PlaceBid,e,ld)}claimAuction(e){return this.send(Me.ClaimAuction,e,ct)}createBuyOrder(e){return this.send(Me.CreateBuyOrder,e,Li)}cancelBuyOrder(e){return this.send(Me.CancelBuyOrder,e,ct)}fillBuyOrder(e){return this.send(Me.FillBuyOrder,e,ct)}createDirectTrade(e){return this.send(Me.CreateDirectTrade,e,Li)}respondDirectTrade(e){return this.send(Me.RespondDirectTrade,e,ct)}cancelDirectTrade(e){return this.send(Me.CancelDirectTrade,e,ct)}claimBack(e){return this.send(Me.ClaimBack,e,ct)}};var Zr=class extends L{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(Ze.CreateRoom,e,Ni)}joinRoom(e){return this.send(Ze.JoinRoom,e,Ni)}leaveRoom(e,t=false){return this.send(Ze.LeaveRoom,e,il,{keepalive:t})}listRooms(e){return this.send(Ze.ListRooms,e,Tm)}getRoom(e){return this.send(Ze.GetRoom,e,Ni)}closeRoom(e){return this.send(Ze.CloseRoom,e,il)}poll(e){return this.send(Ze.Poll,e,Am)}sendSignal(e){return this.send(Ze.SendSignal,e,Wr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(Ze.ClaimHost,e,Ni)}kickMember(e){return this.send(Ze.KickMember,e,Pm)}unbanMember(e){return this.send(Ze.UnbanMember,e,vm)}sendChat(e){return this.send(Ze.SendChat,e,Wr)}setMemberState(e){return this.send(Ze.SetMemberState,e,Wr)}};var uv={Free:"Free",Price:"Price",Holding:"Holding"},rl=z.enum(["Free","Price","Holding"]).catch("Free"),cv={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},pv=z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),dv={All:"All",Any:"Any"},hv=z.enum(["All","Any"]).catch("All"),mv={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},fv=z.enum(["Public","Unlisted","Friends"]).catch("Public"),gv={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},yv=z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),Rv={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Mm=z.enum(["Purchase","Free","Holding"]).catch("Free"),Cv={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},Sv={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},xv=z.enum(["Creator","License","Free","Holding"]).catch("License"),bv=z.object({Type:li.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),Amount:z.number().nullish(),MinLevel:z.number().nullish()}).passthrough(),Dv=z.object({Requirements:z.array(bv).nullish(),Match:hv.nullish(),Mode:pv.nullish()}).passthrough(),Iv=z.object({OptionID:z.string().nullish(),Mode:rl.nullish(),Price:ue.nullish(),Holding:Dv.nullish()}).passthrough(),Pv=z.object({AllowedMimeTypes:z.array(z.string()).nullish(),MaxBytes:z.number().nullish(),MaxCount:z.number().nullish(),Required:z.boolean().nullish()}).passthrough(),vv=z.object({DisplayName:z.string().nullish(),Enabled:z.boolean().nullish(),Files:z.record(z.string(),Pv).nullish(),ThumbnailRequired:z.boolean().nullish(),AllowedAccessModes:z.array(rl).nullish(),PricePolicy:Fn.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:oe.nullish(),TagVocabulary:z.array(z.string()).nullish(),MaxPublishedPerPlayer:z.number().nullish(),DailyPublishCap:z.number().nullish()}).passthrough(),Tv=z.object({Allowed:z.array(Bi).nullish(),MaxRequirements:z.number().nullish()}).passthrough(),Av=z.object({AutoHideReportThreshold:z.number().nullish(),RequireApproval:z.boolean().nullish(),BlockedTerms:z.array(z.string()).nullish()}).passthrough(),kv=z.object({MaxTitleLength:z.number().nullish(),MaxDescriptionLength:z.number().nullish(),MaxTags:z.number().nullish(),MaxTagLength:z.number().nullish(),MaxMetadataKeys:z.number().nullish(),MaxMetadataValueLength:z.number().nullish(),MaxAccessOptions:z.number().nullish(),ThumbnailMaxBytes:z.number().nullish()}).passthrough(),zv=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Schedule:ge.nullish(),Gate:Z.nullish(),Order:z.number().nullish()}).passthrough(),wv=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:ge.nullish(),ContentTypes:z.record(z.string(),vv).nullish(),PricePolicy:Fn.nullish(),Commission:Sa.nullish(),HoldingPolicy:Tv.nullish(),Moderation:Av.nullish(),Limits:kv.nullish(),Featured:z.array(zv).nullish()}).passthrough(),Mv=z.object({Acquisitions:z.number().nullish(),Downloads:z.number().nullish(),Likes:z.number().nullish(),Favorites:z.number().nullish(),ReportCount:z.number().nullish(),Remixes:z.number().nullish()}).passthrough(),ri=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),CreatorUserID:z.string().nullish(),IsOfficial:z.boolean().nullish(),CreatorPublicData:qe.nullish(),Title:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),Metadata:z.record(z.string(),z.string()).nullish(),ThumbnailUrl:z.string().nullish(),Visibility:fv.nullish(),Access:z.array(Iv).nullish(),Status:yv.nullish(),ModerationNote:z.string().nullish(),Stats:Mv.nullish(),Revision:z.number().nullish(),ParentContentID:z.string().nullish(),FileCount:z.number().nullish(),TotalBytes:z.number().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),PublishedAt:p.nullish(),IsMine:z.boolean().nullish(),Owned:z.boolean().nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish()}).passthrough(),Ov=z.object({OptionID:z.string().nullish(),Mode:rl.nullish(),Available:z.boolean().nullish()}).passthrough(),Om=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Order:z.number().nullish()}).passthrough(),Em=z.object({Definitions:wv.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish(),CanPublish:z.record(z.string(),z.boolean()).nullish(),Collections:z.array(Om).nullish()}).passthrough(),Yr=z.object({Items:z.array(ri).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Um=z.object({Content:ri.nullish(),AccessState:z.array(Ov).nullish(),CanDownload:z.boolean().nullish()}).passthrough(),qm=z.object({Collection:Om.nullish(),Items:z.array(ri).nullish()}).passthrough(),Bm=z.object({CreatorUserID:z.string().nullish(),PublicData:qe.nullish(),PublishedCount:z.number().nullish(),FollowerCount:z.number().nullish(),IsFollowing:z.boolean().nullish(),Items:z.array(ri).nullish()}).passthrough(),wm=z.object({Role:z.string().nullish(),Index:z.number().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish(),ServerCopy:z.boolean().nullish()}).passthrough(),Lm=z.object({ContentID:z.string().nullish(),Revision:z.number().nullish(),Uploads:z.array(wm).nullish(),ThumbnailUpload:wm.nullish(),ExpiresAt:p.nullish()}).passthrough(),Gm=z.object({CreditsConfirmation:me.nullish(),Content:ri.nullish(),Resources:O.nullish()}).passthrough(),ol=z.object({Content:ri.nullish()}).passthrough(),Fm=z.object({ContentID:z.string().nullish(),OptionID:z.string().nullish(),Source:Mm.nullish(),AlreadyOwned:z.boolean().nullish(),AccessActive:z.boolean().nullish(),Settlement:At.nullish(),Resources:O.nullish(),CommissionTaken:ue.nullish()}).passthrough(),Ev=z.object({Role:z.string().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish()}).passthrough(),Vm=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),Revision:z.number().nullish(),AccessVia:xv.nullish(),Files:z.array(Ev).nullish(),ThumbnailUrl:z.string().nullish(),ExpiresAt:p.nullish()}).passthrough(),Uv=z.object({ContentID:z.string().nullish(),Source:Mm.nullish(),OptionID:z.string().nullish(),PricePaid:ue.nullish(),AcquiredAt:p.nullish(),Content:ri.nullish()}).passthrough(),Nm=z.object({Licenses:z.array(Uv).nullish(),ContinuationToken: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 Xr=class extends L{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(He.GetDefinitions,e,Em)}browse(e){return this.send(He.Browse,e,Yr)}getContent(e){return this.send(He.GetContent,e,Um)}getCollection(e){return this.send(He.GetCollection,e,qm)}getCreatorProfile(e){return this.send(He.GetCreatorProfile,e,Bm)}beginUpload(e){return this.send(He.BeginUpload,e,Lm)}publish(e){return this.send(He.Publish,e,De(Gm))}updateContent(e){return this.send(He.UpdateContent,e,ol)}unpublish(e){return this.send(He.Unpublish,e,ol)}getMyContent(e){return this.send(He.GetMyContent,e,Yr)}acquire(e){return this.send(He.Acquire,e,Fm)}getDownload(e){return this.send(He.GetDownload,e,Vm)}getMyLicenses(e){return this.send(He.GetMyLicenses,e,Nm)}getMyFavorites(e){return this.send(He.GetMyFavorites,e,Yr)}};var eo=class extends L{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,fd,"defs")}get(e){return this.sendKeyed("Get",e,Ia,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,yd,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,Pa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Rd,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,va,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,va,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Cd,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,xd,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Sd,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,bd,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,gd,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Dd,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,Ia,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,Pa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var to=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$1){this.settings=pl(e$1),this.emitter=new Pi,this.platform=e$1.platform??new e,this.clientPlatform=e$1.clientPlatform??Dl(),this.acquisition=new Ht(this.platform),this.acquisition.capture(),this.playtime=new vi(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$1.fetch??globalThis.fetch.bind(globalThis),this.transport=new ns({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e$1.fetch,debugLogging:this.settings.debugLogging,throttleMs:e$1.throttleMs,maxRequestsPerSecond:e$1.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new ls(this.emitter),this.cache=new cs(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e$1.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 ps(this.platform.storage,this.settings.titleID),this.api={authentication:new Yn(this),user:new er(this),currency:new tr(this),item:new nr(this),store:new rr(this),purchase:new ur(this),lootbox:new dr(this),reward:new hr(this),quest:new Cr(this),tutorial:new mr(this),communityMarketing:new fr(this),chat:new gr(this),push:new yr(this),localization:new Rr(this),timedEvent:new Sr(this),leaderboard:new xr(this),season:new br(this),premium:new Dr(this),character:new Ir(this),match:new Pr(this),craft:new Tr(this),ai:new Ar(this),collection:new zr(this),coopEvent:new wr(this),dealOffer:new Mr(this),referral:new Or(this),mailbox:new Er(this),advertising:new Ur(this),social:new qr(this),timedBoost:new Gr(this),userCustomData:new Fr(this),titleCustomData:new Nr(this),title:new Kr(this),gameLoop:new Qr(this),cloudCode:new Hr(this),blockchain:new $r(this),marketplace:new Jr(this),multiplayer:new Zr(this),workshop:new Xr(this),dataCollections:new eo(this),analytics:new Jn(this),experiment:new Zn(this)},this.userService=new gs(this),this.cache.attachState(this.userService),this.auth=new ds(this),this.currency=new Rs(this),this.item=new Cs(this),this.store=new Is(this),this.credits=new Ps(this),this.purchase=new vs(this),this.checkout=new Ts(this),this.lootbox=new As(this),this.reward=new zs(this),this.quest=new Fs(this),this.tutorial=new Ms(this),this.communityMarketing=new Os(this),this.chat=new qs(this),this.push=new Bs(this),this.localization=new Gs(this),this.timedEvent=new _s(this),this.leaderboard=new Js(this),this.season=new Xs(this),this.premium=new en(this),this.character=new nn(this),this.match=new rn(this),this.craft=new on(this),this.ai=new ln(this),this.collection=new un(this),this.coopEvent=new dn(this),this.dealOffer=new fn(this),this.referral=new gn(this),this.mailbox=new Cn(this),this.ads=new bn(this),this.social=new Pn(this),this.timedBoost=new vn(this),this.userCustomData=new kn(this),this.titleCustomData=new zn(this),this.title=new wn(this),this.gameLoop=new Mn(this),this.cloudCode=new On(this),this.blockchain=new qn(this),this.marketplace=new Nn(this),this.multiplayer=new _n(this),this.workshop=new jn(this),this.dataCollections=new Kn(this),this.analytics=new Hn(this),this.experiments=new $n(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:d()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var io=class{ctx;constructor(e){this.ctx=new to(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Wt(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(n,{...s,...i},z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get 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 Bv(r){return new io(r)}var _m="idos_sso",jm="state",al="idos:sso:state",Lv="https://idosgames.com/sso/",Gv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],Fv=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function Vv(){if(typeof window>"u")return false;let{origin:r}=window.location;return Gv.includes(r)||Fv.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function Nv(){if(typeof window>"u")return null;let r=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!r)return null;let e=new URLSearchParams(r),t=e.get(_m);if(!t)return null;let i=e.get(jm)??"",s=Qv();return $v(e),Hv(),s&&i!==s?null:{code:t,state:i}}function _v(r){if(typeof window>"u")return;let e=r.returnTo??jv(),t=Wv();Kv(t);let i=new URL(r.ssoUrl??Lv);i.searchParams.set("title",r.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function jv(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function Wv(){let r=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(r);else for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*256);return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function Kv(r){try{window.sessionStorage.setItem(al,r);}catch{}}function Qv(){try{return window.sessionStorage.getItem(al)}catch{return null}}function Hv(){try{window.sessionStorage.removeItem(al);}catch{}}function $v(r){r.delete(_m),r.delete(jm);let e=r.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var Jv={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 Zv(r,e="Something went wrong. Please try again."){return r?Jv[r]??r:e}function Yv(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function Xv(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function eT(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function Km(r,e,t,i=1){if(!r)return e;let s=r.Base??e,n=Math.max(0,t-i),o;switch(r.Shape??"Flat"){case "PerStep":o=s+(r.PerStep??0)*n;break;case "PerStepRate":o=s*(1+(r.PerStepRate??0)*n);break;case "Geometric":o=s*Math.pow(1+(r.GrowthRate??0),n);break;case "Table":o=s*Wm(r,t,1);break;case "TableAbsolute":o=Wm(r,t,s);break;default:o=s;break}return Number.isNaN(o)?s:(r.MinResult!=null&&o<r.MinResult&&(o=r.MinResult),r.MaxResult!=null&&o>r.MaxResult&&(o=r.MaxResult),o)}function tT(r,e,t=1){return Km(r,1,e,t)}function iT(r){if(!r)return false;switch(r.Shape??"Flat"){case "PerStep":return (r.PerStep??0)!==0;case "PerStepRate":return (r.PerStepRate??0)!==0;case "Geometric":return (r.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return Qm(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function sT(r){if(Number.isNaN(r)||r<=0)return 0;if(!Number.isFinite(r))return Number.MAX_SAFE_INTEGER;let e=Math.round(r);return Math.abs(r-e)<=1e-9*Math.max(1,Math.abs(r))?e:Math.ceil(r)}function Qm(r){if(!r)return [];let e=[];for(let t of r)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function Wm(r,e,t){let i=Qm(r.Points);if(i.length===0)return t;let s=null,n=null,o=null;for(let c of i)(o===null||c.AtStep>o.AtStep)&&(o=c),c.AtStep<=e&&(s===null||c.AtStep>=s.AtStep)&&(s=c),c.AtStep>e&&(n===null||c.AtStep<n.AtStep)&&(n=c);if(s===null)return t;if(n===null){let c=r.TailGrowthRate??0;return c===0?o.Value:o.Value*Math.pow(1+c,e-o.AtStep)}switch(r.Interpolation??"Step"){case "Linear":{let c=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+c*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let h=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+h*(n.Value-s.Value)}let c=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,c)}default:return s.Value}}var nT={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},ll=z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),rT={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},oT=z.enum(["Top","Bottom","Left","Right"]).catch("Top"),aT=z.object({PlacementID:z.string().nullish(),Type:ll.nullish(),Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),CreditsRewarded:z.number().nullish(),AllowedProviderIDs:z.array(z.string()).nullish()}).passthrough(),lT=z.object({DefaultCreditsPerView:z.number().nullish(),MaxCreditsBalance:z.number().nullish(),DailyCreditEarnCap:z.number().nullish(),DailyViewCap:z.number().nullish(),MinSecondsBetweenViews:z.number().nullish()}).passthrough(),uT=z.object({CooldownSeconds:z.number().nullish(),MinSessionTimeBeforeFirstSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),cT=z.object({Enabled:z.boolean().nullish(),Position:oT.nullish(),RefreshIntervalSeconds:z.number().nullish()}).passthrough(),pT=z.object({Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish()}).passthrough(),dT=z.object({MaxImpressionsPerHour:z.number().nullish(),MaxImpressionsPerDay:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),hT=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),DisableInterstitials:z.boolean().nullish(),DisableBanners:z.boolean().nullish(),DisableAppOpen:z.boolean().nullish()}).passthrough(),mT=z.object({RequirePersonalizedAdsConsent:z.boolean().nullish(),RequireTrackingConsent:z.boolean().nullish(),CurrentPolicyVersion:z.string().nullish(),RegulatedRegions:z.array(z.string()).nullish()}).passthrough(),fT=z.object({RequireServerSideVerification:z.boolean().nullish(),PendingRequestTtlSeconds:z.number().nullish(),MaxPendingRequestsPerUser:z.number().nullish()}).passthrough(),gT=z.object({AndroidUnitID:z.string().nullish(),IosUnitID:z.string().nullish(),WebUnitID:z.string().nullish(),Type:ll.nullish()}).passthrough(),yT={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},RT=z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),CT=z.object({ProviderID:z.string().nullish(),Kind:RT.nullish(),Enabled:z.boolean().nullish(),Priority:z.number().nullish(),AndroidAppID:z.string().nullish(),IosAppID:z.string().nullish(),WebAppID:z.string().nullish(),Units:z.record(z.string(),gT).nullish()}).passthrough();z.object({Enabled:z.boolean().nullish(),Placements:z.record(z.string(),aT).nullish(),Providers:z.record(z.string(),CT).nullish(),RewardedVideo:lT.nullish(),Interstitial:uT.nullish(),Banner:cT.nullish(),AppOpen:pT.nullish(),FrequencyCapping:dT.nullish(),PremiumAdReductions:z.array(hT).nullish(),Consent:mT.nullish(),Verification:fT.nullish()}).passthrough();var ST=z.object({RewardedVideoCredit:z.number().nullish(),TotalEarned:z.number().nullish(),TotalSpent:z.number().nullish()}).passthrough(),xT=z.object({PlacementID:z.string().nullish(),LastShownAt:p.nullish(),LastCompletedAt:p.nullish(),TotalImpressions:z.number().nullish(),TotalCompletions:z.number().nullish(),ConsecutiveFailures:z.number().nullish()}).passthrough(),bT=z.object({Date:p.nullish(),ImpressionsByPlacement:z.record(z.string(),z.number()).nullish(),CompletionsByPlacement:z.record(z.string(),z.number()).nullish(),TotalImpressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish(),AppOpenImpressions:z.number().nullish(),CreditsEarnedToday:z.number().nullish()}).passthrough(),DT=z.object({SessionID:z.string().nullish(),SessionStartAt:p.nullish(),Impressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish()}).passthrough(),IT=z.object({PersonalizedAdsConsent:z.boolean().nullish(),TrackingConsent:z.boolean().nullish(),PolicyVersion:z.string().nullish(),Region:z.string().nullish(),ConsentGivenAt:p.nullish(),ConsentRevokedAt:p.nullish()}).passthrough(),PT=z.object({RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),Type:ll.nullish(),IssuedAt:p.nullish(),ExpiresAt:p.nullish(),CreditsToAward:z.number().nullish()}).passthrough(),vT=z.object({InvalidSsvCount:z.number().nullish(),OrphanCompletions:z.number().nullish(),FastCompletions:z.number().nullish(),LastFlaggedAt:p.nullish()}).passthrough();z.object({Credits:ST.nullish(),Placements:z.record(z.string(),xT).nullish(),Daily:bT.nullish(),Session:DT.nullish(),LastImpressionAt:p.nullish(),LastInterstitialAt:p.nullish(),LastRewardedAt:p.nullish(),LastAppOpenAt:p.nullish(),TotalImpressions:z.number().nullish(),TotalRewardedCompletions:z.number().nullish(),AdsDisabledUntil:p.nullish(),Consent:IT.nullish(),PendingRequests:z.record(z.string(),PT).nullish(),FraudFlags:vT.nullish(),UpdatedAt:p.nullish()}).passthrough();
|
|
2
|
-
export{Be as AIAction,
|
|
1
|
+
import {i,o,k,m,q,g,L as L$1,a,j,r,f,h,z as z$1}from'./chunk-YZ32MQXQ.js';export{r as AuthType,c as BrowserFileStore,d as BrowserStorage,j as ClientPlatform,f as CurrencyType,n as EventTokenType,l as IapStoreValues,b as MemoryFileStore,s as MemoryHost,e as MemoryStorage,v as NATIVE_HOST_GLOBAL,u as NATIVE_HOST_PROTOCOL,x as NativeHost,G as PLATFORM_AD_MESSAGES,B as PLATFORM_BRIDGE_ACK,I as PLATFORM_CREDITS_CONFIRM_FINAL,H as PLATFORM_CREDITS_CONFIRM_MESSAGES,z as PLATFORM_ORIGINS,C as PLATFORM_PAGE_UNAVAILABLE,E as PLATFORM_SIGN_IN_MESSAGES,F as PLATFORM_TOPUP_MESSAGES,h as ResourceEntryType,J as SITE_FRAME_HIDDEN_MESSAGE,p as ScheduleMode,K as WebHost,D as askPlatformPage,L as createDefaultHost,y as getTelegramWebApp,A as isPlatformParentOrigin,w as readNativeHostGlobal,t as shareFallbackText}from'./chunk-YZ32MQXQ.js';import {b,a as a$1,c}from'./chunk-CS7ACWDY.js';export{e as isFail,d as isOk}from'./chunk-CS7ACWDY.js';import {z}from'zod';import Jt from'decimal.js';var Ii=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,s=>{i(),t(s);});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 s of [...i])s(t);}removeAllListeners(){this.listeners.clear();}};function el(o){return {get:e=>o.getString(e),set:(e,t)=>o.setString(e,t),remove:e=>o.remove(e)}}var tl="https://api.idosgames.com";function il(o,e){return {titleID:o.titleID,titleTemplateID:o.titleTemplateID??"default",buildKey:o.buildKey??"",baseUrl:(o.baseUrl??tl).replace(/\/+$/,""),devBuild:o.devBuild??false,debugLogging:o.debugLogging??false,configStorage:o.configStorage??el(e.storage),locale:o.locale??e.getLanguage(),appVersion:o.appVersion??""}}var io="idos_acq",sl=["gclid","fbclid","ttclid","msclkid","yclid"],Fm=["ref","r"],Nm=["ref_","ref-","ref=","r_","r-"];var Ht=class{constructor(e){this.host=e;}host;capture(){let e=this.readFromEnvironment();jm(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=Km(this.host.getDeviceModel());return s&&(i.OsVersion=s),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.host.storage.remove(io);}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=ol(rl(t));if(i)return i}return Ki(t)}readFromEnvironment(){let e={},t=rl(this.host.getFullURL());Qt(e,"UtmSource",t.get("utm_source")),Qt(e,"UtmMedium",t.get("utm_medium")),Qt(e,"UtmCampaign",t.get("utm_campaign")),Qt(e,"UtmTerm",t.get("utm_term")),Qt(e,"UtmContent",t.get("utm_content")),Qt(e,"ClaimToken",t.get("idos_click"));for(let R of sl){let j=t.get(R);if(j){e.ClickID=j;break}}let i=this.host.getStartParameter()??"",s=Wm(i);if(s){for(let R of _m)Qt(e,R,s.get(al[R])??null);for(let R of sl){let j=s.get(R);if(j){e.ClickID=j;break}}}let n=Ki(s?s.get("ref")??s.get("r")??"":i),r=ol(t),c=n||r;c&&(e.ReferralCode=c,e.ChannelHint=n?"telegram":"query");let h=this.host.getReferrer();return h&&(e.Referrer=h),e}read(){try{let e=this.host.storage.getString(io);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.host.storage.setString(io,JSON.stringify(e));}catch{}}};function jm(o){return !!(o.UtmSource||o.UtmMedium||o.UtmCampaign||o.ClickID||o.Referrer||o.ReferralCode||o.ClaimToken)}function Qt(o,e,t){t&&(o[e]=t);}var nl="a1_",al={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},_m=Object.keys(al);function Wm(o){let e=(o||"").trim();if(!e.startsWith(nl))return null;let t=e.slice(nl.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),n=Uint8Array.from(s,h=>h.charCodeAt(0)),r=new TextDecoder().decode(n),c=new URLSearchParams(r);return [...c.keys()].length>0?c:null}catch{return null}}function rl(o){try{let e=o.indexOf("?");return new URLSearchParams(e>=0?o.slice(e):"")}catch{return new URLSearchParams}}function ol(o){for(let e of Fm){let t=o.get(e);if(t)return Ki(t)}return null}function Ki(o){let e=(o||"").trim();if(!e)return null;for(let t of Nm)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Km(o){let e=o||"",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 ll="idos_usage_pending",ul="idos_usage_session",cl="idos_usage_closed_session",pl="idos_usage_new_session",dl="idos_usage_last_activity",Pi=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;stopVisibility=null;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=!this.ctx.host.isVisible(),this.timer=setInterval(()=>this.tick(),200*1e3),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=e=>{if(!e){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,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(ll),this.currentSessionSeconds=this.readNumber(ul),this.pendingClosedSessionSeconds=this.readNumber(cl),this.isNewSessionPending=this.readNumber(pl)!==0;let e=this.readNumber(dl);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(ll,this.pendingSeconds),this.writeNumber(ul,this.currentSessionSeconds),this.writeNumber(cl,this.pendingClosedSessionSeconds),this.writeNumber(pl,this.isNewSessionPending?1:0),this.writeNumber(dl,Date.now());}readNumber(e){let t=this.ctx.host.storage.getString(e),i=t?Number(t):0;return Number.isFinite(i)&&i>0?i:0}writeNumber(e,t){try{this.ctx.host.storage.setString(e,String(Math.floor(t)));}catch{}}};var W=z.union([z.number(),z.string()]).transform((o,e)=>{let t=typeof o=="string"?Number(o):o;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(o)}`}),z.NEVER)}),Y=z.union([z.number(),z.string()]).transform((o,e)=>{let t=typeof o=="number"?String(o):o.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid decimal: ${String(o)}`}),z.NEVER):t}),p=z.string();var so=z.object({Type:i.nullish(),CurrencyID:z.string().nullish(),Amount:W.nullish(),AmountUsd:z.number().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ProductID:z.string().nullish()}),Qm=z.object({Type:o.nullish(),EntityID:z.string()}),Hm=z.object({Address:Qm.nullish(),Amount:W.nullish(),Source:z.string().nullish()}),ue=z.object({Entries:z.array(so).nullish(),EventTokens:z.array(Hm).nullish()}),hl=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Resources:ue.nullish()}),H=z.object({Standard:ue.nullish(),PremiumBonuses:z.array(z.unknown()).nullish(),PremiumTiers:z.array(hl).nullish()}),Tt=z.object({Standard:ue.nullish(),PremiumDiscounts:z.array(z.unknown()).nullish(),PremiumTiers:z.array(hl).nullish()}),O=z.object({Grant:H.nullish(),Consume:Tt.nullish()}),At=z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),FromResult:O.nullish(),ToResult:O.nullish()});z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Transferred:ue.nullish()});var $m=z.object({ExperimentID:z.string().nullish(),Variants:z.array(z.string()).nullish()}).passthrough(),Jm={Completed:"Completed",Started:"Started",StepReached:"StepReached"},Zm=z.object({FlowIDs:z.array(z.string()).nullish(),Mode:z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:z.string().nullish(),Negate:z.boolean().nullish(),SkippedCountsAsCompleted:z.boolean().nullish()}).passthrough(),Z=z.object({Segments:z.array(z.string()).nullish(),MinPremiumTier:z.number().nullish(),RequiredPremiumIDs:z.array(z.string()).nullish(),MinLevel:z.number().nullish(),MaxLevel:z.number().nullish(),Countries:z.array(z.string()).nullish(),RegisteredWithinDays:z.number().nullish(),ActiveWithinDays:z.number().nullish(),Experiment:$m.nullish(),Tutorial:Zm.nullish(),Platforms:z.array(k).nullish()}).passthrough();var Ce=z.object({TotalCap:z.number().nullish(),DailyCap:z.number().nullish(),DailyWeightCap:z.number().nullish(),PerActivationCap:z.number().nullish(),CooldownSeconds:z.number().nullish(),MaxPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish()}).passthrough();var Ym=z.object({OffsetSecondsFromParentStart:z.number().nullish(),DurationSeconds:z.number().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Xm=z.object({StartUtc:z.string().nullish(),EndUtc:z.string().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),ef=z.object({AnchorUtc:z.string().nullish(),MaxCycles:z.number().nullish(),PauseBetweenPhasesSec:z.number().nullish(),PauseBetweenCyclesSec:z.number().nullish()}).passthrough();z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();var tf=z.object({Reset:z.string().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:z.string().nullish(),PauseBetweenCyclesSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();z.object({SourceType:z.string().nullish(),TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),Outcome:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough();var at=z.object({SourceType:z.string().nullish(),BaseWeight:z.number().nullish(),ScaleWithRollMultiplier:z.boolean().nullish(),TileTypeFilter:z.array(z.string()).nullish(),TileIndexFilter:z.array(z.number()).nullish(),ChanceOutcomeFilter:z.array(z.string()).nullish(),OutcomeFilter:z.array(z.string()).nullish(),Params:z.record(z.string(),z.string()).nullish(),Limits:Ce.nullish()}).passthrough(),ge=z.object({Mode:z.string().nullish(),IsActive:z.boolean().nullish(),Scheduled:Xm.nullish(),Chain:ef.nullish(),Cyclic:tf.nullish(),ActivationTriggers:z.array(at).nullish(),Relative:Ym.nullish()}).passthrough();var sf={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},nf=z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),rf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},of=z.enum(["Step","Linear","Geometric"]).catch("Step"),af=z.object({AtStep:z.number().nullish(),Value:z.number().nullish()}).passthrough(),je=z.object({Base:z.number().nullish(),Shape:nf.nullish(),PerStep:z.number().nullish(),PerStepRate:z.number().nullish(),GrowthRate:z.number().nullish(),Points:z.array(af).nullish(),Interpolation:of.nullish(),TailGrowthRate:z.number().nullish(),MinResult:z.number().nullish(),MaxResult:z.number().nullish()}).passthrough();var lf=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Rewards:H.nullish()}).passthrough(),uf=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Multiplier:z.number().nullish()}).passthrough(),no=z.object({Bundles:z.array(lf).nullish(),Multipliers:z.array(uf).nullish()}).passthrough();var cf=z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Qi=z.object({Source:cf.nullish(),SourceKey:z.string().nullish(),Curve:je.nullish(),Anchor:z.number().nullish(),IncludeRewards:ue.nullish(),ExcludeRewards:ue.nullish()}).passthrough(),ml=z.object({ClaimedAt:z.string().nullish(),PremiumTiers:z.array(z.string()).nullish(),Unlocked:z.boolean().nullish()}).passthrough(),Fe=z.object({MilestoneID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredProgress:z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:no.nullish(),SortOrder:z.number().nullish(),IsFeatured:z.boolean().nullish()}).passthrough(),li=z.object({Milestones:z.record(z.string(),Fe).nullish()}).passthrough();var Q=z.object({PresetID:z.string().nullish(),Remove:z.array(z.string()).nullish()}).passthrough();var pf=z.object({TargetCurrencyID:z.string().nullish(),Rate:z.number().nullish(),MaxConvertAmount:z.number().nullish()}).passthrough(),$t=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxBalance:z.number().nullish(),MaxPerGrant:z.number().nullish(),DailyEarnCap:z.number().nullish(),BurnOnEventEnd:z.boolean().nullish(),BurnConversion:pf.nullish()}).passthrough();var df=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),fl=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:df.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),K=z.object({ChangedInstances:z.record(z.string(),fl).nullish(),RemovedInstanceIDs:z.array(z.string()).nullish()});var Te=o=>z.object({Id:z.string(),Success:z.boolean(),Error:z.string().nullish(),Data:o.nullish()}),St=o=>z.object({ServerTimeUtc:p,Items:z.array(Te(o)),Resources:O.nullish(),Inventory:K.nullish()});var hf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},gl=z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),mf=z.object({}).passthrough().transform(o=>o),ff=z.object({CycleID:z.string(),InstanceKey:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),CycleStartUtc:p.nullish(),CycleEndUtc:p.nullish(),PointsTotalEarned:W.nullish(),PointsCurrent:W.nullish(),ClaimedPointMilestoneIDs:z.array(z.string()).nullish(),NextMilestone:Fe.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),ro=z.object({QuestID:z.string(),CycleID:z.string().nullish(),ObjectiveID:z.string().nullish(),NewValue:W.nullish(),ObjectiveCompleted:z.boolean().nullish(),Status:gl}),yl=z.object({State:mf.nullish(),PointsTracks:z.record(z.string(),ff).nullish()}),oo=z.object({ServerTimeUtc:p,QuestID:z.string(),CycleID:z.string().nullish(),NewStatus:gl.nullish(),Resources:O.nullish(),Inventory:K.nullish()}),ao=z.object({ServerTimeUtc:p,CycleID:z.string(),MilestoneID:z.string(),PointsTotalEarned:W.nullish(),Resources:O.nullish(),Inventory:K.nullish(),NextMilestone:Fe.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),Rl=z.object({ServerTimeUtc:p,CycleID:z.string(),GroupCompletionID:z.string(),GroupID:z.string().nullish(),CompletedGroupQuests:z.number().nullish(),RequiredGroupQuests:z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Cl=z.object({MetricID:z.string(),Updates:z.array(ro).nullish()}),Sl=z.array(Te(oo)),xl=z.array(Te(ao)),gf={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},yf=z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Rf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Cf=z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),bl=z.object({ObjectiveID:z.string().nullish(),Source:yf.nullish(),MaxProgressPerCall:z.number().nullish(),MetricID:z.string().nullish(),Triggers:z.array(at).nullish(),TargetValue:z.number().nullish(),AggregationMethod:z.string().nullish()}).passthrough(),lo=z.object({Milestones:Q.nullish(),Linking:Q.nullish(),Availability:Q.nullish(),Reward:Q.nullish(),Objectives:Q.nullish()}).passthrough(),Sf=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Dl=z.object({CycleIDs:z.array(z.string()).nullish(),GroupID:z.string().nullish(),PhaseIDs:z.array(z.string()).nullish(),RequiredQuestIDs:z.array(z.string()).nullish(),PrerequisiteMode:Cf.nullish()}).passthrough(),Il=z.object({Schedule:ge.nullish(),AccrueProgressWhenLocked:z.boolean().nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),Pl=z.object({Grant:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),xf=z.object({QuestID:z.string().nullish(),Identity:Sf.nullish(),Linking:Dl.nullish(),Availability:Il.nullish(),Objectives:z.record(z.string(),bl).nullish(),Reward:Pl.nullish(),Presets:lo.nullish()}).passthrough(),bf=z.object({CompletionID:z.string().nullish(),GroupID:z.string().nullish(),RequiredCompletedQuests:z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),Df=z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Gate:Z.nullish(),Milestones:z.record(z.string(),Fe).nullish(),Presets:lo.nullish(),PointsToken:$t.nullish()}).passthrough(),If=z.object({Milestones:z.record(z.string(),li).nullish(),Linking:z.record(z.string(),Dl).nullish(),Availability:z.record(z.string(),Il).nullish(),Reward:z.record(z.string(),Pl).nullish(),Objectives:z.record(z.string(),z.record(z.string(),bl)).nullish()}).passthrough(),Pf=z.object({CycleID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:ge.nullish(),Milestones:z.record(z.string(),Fe).nullish(),Gate:Z.nullish(),PointsToken:$t.nullish(),GroupCompletions:z.record(z.string(),bf).nullish(),Phases:z.record(z.string(),Df).nullish(),Presets:lo.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),$i=z.object({Cycles:z.record(z.string(),Pf).nullish(),Quests:z.record(z.string(),xf).nullish(),Presets:If.nullish()}).passthrough(),gt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var vf={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},Tf=z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),Af={Never:"Never",OnRequest:"OnRequest",Always:"Always"},kf=z.enum(["Never","OnRequest","Always"]).catch("Never"),zf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},wf=z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),Mf={GameLoop:"GameLoop"},Of={Raid:"Raid",Attack:"Attack"},Ef=z.object({Title:z.string().nullish(),TitleKey:z.string().nullish(),Body:z.string().nullish(),BodyKey:z.string().nullish(),AnchorID:z.string().nullish(),HighlightTarget:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),UiHint:z.record(z.string(),z.string()).nullish()}).passthrough(),Uf=z.object({Mode:Tf.nullish(),Triggers:z.array(at).nullish(),TargetValue:z.number().nullish(),RequireAllTriggers:z.boolean().nullish()}).passthrough(),qf=z.object({Grant:H.nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),Bf=z.object({TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),RandomActionType:z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),Lf=z.object({Module:z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:Bf.nullish(),MaxUses:z.number().nullish()}).passthrough(),Gf=z.object({Skippable:z.boolean().nullish(),TimeoutSeconds:z.number().nullish()}).passthrough(),uo=z.object({StepID:z.string().nullish(),Order:z.number().nullish(),Identity:Ef.nullish(),Completion:Uf.nullish(),Effects:qf.nullish(),Script:Lf.nullish(),Policy:Gf.nullish()}).passthrough(),Vf=z.object({DisplayName:z.string().nullish(),DisplayNameKey:z.string().nullish(),Description:z.string().nullish(),DescriptionKey:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),vl=z.object({Schedule:ge.nullish(),Gate:Z.nullish(),RequiredFlowIDs:z.array(z.string()).nullish(),AutoStart:z.boolean().nullish(),StartTrigger:at.nullish()}).passthrough(),Tl=z.object({Skippable:z.boolean().nullish(),SkippableFromOrder:z.number().nullish(),RestartPolicy:kf.nullish(),ExpireAfterSeconds:z.number().nullish(),IsBlocking:z.boolean().nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),Al=z.object({Grant:H.nullish(),AutoClaim:z.boolean().nullish()}).passthrough(),Ff=z.object({Availability:Q.nullish(),Policy:Q.nullish(),Reward:Q.nullish(),Steps:Q.nullish()}).passthrough(),Nf=z.object({FlowID:z.string().nullish(),Identity:Vf.nullish(),Availability:vl.nullish(),Policy:Tl.nullish(),Steps:z.record(z.string(),uo).nullish(),Reward:Al.nullish(),Presets:Ff.nullish()}).passthrough(),jf=z.object({BlockingFlowIDs:z.array(z.string()).nullish(),BlockedModules:z.array(z.string()).nullish(),BlockedActions:z.record(z.string(),z.array(z.string())).nullish(),BlockBeforeStart:z.boolean().nullish(),SkipLiftsBlock:z.boolean().nullish()}).passthrough(),_f=z.object({IsEnabled:z.boolean().nullish(),MaxActiveFlows:z.number().nullish(),Blocking:jf.nullish()}).passthrough(),Wf=z.object({Availability:z.record(z.string(),vl).nullish(),Policy:z.record(z.string(),Tl).nullish(),Reward:z.record(z.string(),Al).nullish(),Steps:z.record(z.string(),z.record(z.string(),uo)).nullish()}).passthrough(),kl=z.object({Flows:z.record(z.string(),Nf).nullish(),Settings:_f.nullish(),Presets:Wf.nullish()}).passthrough(),Kf=z.object({}).passthrough().transform(o=>o),zl=z.object({FlowID:z.string(),Status:wf,CurrentStepID:z.string().nullish(),CurrentStep:uo.nullish(),TotalSteps:z.number(),CompletedSteps:z.number(),CanSkip:z.boolean(),RewardClaimed:z.boolean(),RewardPending:z.boolean(),VariantID:z.string().nullish()}).passthrough(),Ji=z.object({State:Kf.nullish(),Flows:z.array(zl).nullish(),UnlockedFeatures:z.array(z.string()).nullish()}).passthrough(),qt=z.object({Flow:zl.nullish()}).passthrough(),wl=z.object({FlowID:z.string().nullish(),Granted:O.nullish()}).passthrough(),Ml=z.array(Te(qt)),Ol=z.object({FlowID:z.string(),StepID:z.string(),Progress:z.number(),Target:z.number(),Completed:z.boolean()}).passthrough(),lt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Zi(o){return Array.isArray(o)?o.filter(e=>e!==null).map(Zi):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).filter(([,e])=>e!==null).map(([e,t])=>[e,Zi(t)])):o}var Yi=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 Xi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function El(o){return o===429||o>=500&&o<=599}function es(o,e=Math.random){let t=Math.min(500*Math.pow(2,o-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Bt(o){return new Promise(e=>setTimeout(e,o))}var Ul=15e3;async function ql(o){try{let t=JSON.parse(await o.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(o.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Bl(o,e=Math.random){return o+10+Math.min(250,o*.2)*e()}function Ll(o,e=Math.random){let t=o<=1?1500:o===2?4e3:6e3;return t+t*.1*e()}var co=15,Gl=1e3,ts=class{constructor(e=co,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]>=Gl;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(Gl-(e-this.starts[0])+5);}}};var Qf=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function ci(o){if(!o)return null;let e=Qf.exec(o);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new Jt(i),r=new Jt(s),c=r.minus(Jt.max(n,0));return c.lte(0)?null:{currencyID:t,required:r.toNumber(),available:n.toNumber(),missing:c.toNumber(),missingAmount:c.toFixed()}}var Hf=12e3,$f=new Set(["RelatedEntityID"]);function Jf(o,e){if(e===null||typeof e!="object"||Array.isArray(e))return o;let t={};for(let[i,s]of Object.entries(e))$f.has(i)||(t[i]=s);try{return `${o}|${JSON.stringify(t)}`}catch{return o}}var Zf=z.object({Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().optional(),QuestProgress:z.array(ro).nullish(),TutorialProgress:z.array(Ol).nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish()}).passthrough(),is=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Xi;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 Yi(e.throttleMs),this.pacer=new ts(e.maxRequestsPerSecond??co),this.clientPlatform=e.clientPlatform??j.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,s={}){let n=s.throttleKey??Jf(e,t);if(!this.throttler.tryAcquire(n))return b("throttled","Throttled");if(!this.inflight.add(n))return b("throttled","Duplicate request skipped");this.raiseBusy();try{let r=`${this.baseUrl}/${e}`,c=JSON.stringify(t),h=s.ticket??null,R=s.silent??!1,j=s.timeoutMs??Hf,ce=s.autoRetry??!0,Ae=!1,Re=!1,Ue=0;for(;;){let vt;s.keepalive||await this.pacer.take();try{vt=await this.doFetch(r,c,h,j,s.keepalive??!1);}catch{if(ce&&Ue<3){Ue++,await Bt(es(Ue));continue}return this.connectionFailure("Internet Connection Error",R)}let et=vt.status;if(et>=200&&et<300){let re=!Re&&this.cryptoTopUpHandler!==null,ve=await this.parseSuccess(vt,i,R,e,re);if(!ve.ok&&re){let pe=ci(ve.error);if(pe){if(Re=!0,await this.runTopUp(pe))continue;R||this.emitter.emit("error:global",ve.error);}}return ve}if(et===401){if(!Ae&&this.sessionRefreshHandler){Ae=!0;let re=null;try{re=await this.sessionRefreshHandler();}catch{re=null;}if(re){h=re;continue}}return this.emitter.emit("auth:unauthorized",void 0),b("unauthorized","Unauthorized")}if(El(et)){let re=et===429?await ql(vt):null;if(re!==null&&re>Ul)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(re/1e3)} s`,R);if(ce&&Ue<3){Ue++,await Bt(re!==null?Bl(re):et===429?Ll(Ue):es(Ue));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${et})`,R)}let xi="";try{xi=await vt.text();}catch{}if(et===409&&/operation in progress/i.test(xi)&&ce&&Ue<3){Ue++,await Bt(es(Ue));continue}return this.handleWebError(xi,et,R)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let r=new AbortController,c=setTimeout(()=>{r.abort();},s);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:r.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(c);}}async parseSuccess(e,t,i,s,n=false){let r;try{r=await e.text();}catch{return this.globalError("Failed to read response body",i)}let c;try{c=JSON.parse(r);}catch{return this.globalError("JSON Parse Error",i)}let h=Zf.safeParse(c);if(!h.success)return this.globalError("Malformed response envelope",i);if(!h.data.Success){let Re=h.data.Error??"Server returned Success=false",Ue=n&&ci(Re);return !i&&!Ue&&this.emitter.emit("error:global",Re),b("server",Re)}let R=h.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:h.data.StateEpoch??null,versions:R});let j=h.data.QuestProgress;j&&j.length>0&&this.emitter.emit("quest:systemProgress",j);let ce=h.data.TutorialProgress;ce&&ce.length>0&&this.emitter.emit("tutorial:systemProgress",ce);let Ae=t.safeParse(h.data.Data);if(!Ae.success){let Re=t.safeParse(Zi(h.data.Data));Re.success&&(Ae=Re);}if(!Ae.success){let Re=`Validation error (${s}): ${Ae.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",Re),i||this.emitter.emit("error:global",Re),b("validation",Re)}return a$1(Ae.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let r=JSON.parse(e)?.Error;if(t===403&&r==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),b("server","PLAY_ACCESS_REQUIRED");s=typeof r=="string"&&r.length>0?`HTTP ${t}: ${r}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),b("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),b("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),b("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 pi(o){return (typeof o=="string"?o:o.toISOString()).slice(0,10)}function vi(o){return `${pi(o)}T00:00:00.000Z`}function Vl(o){let e=new Date(o);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Fl(o,e){return new Date(o.getTime()+e*6e4).toISOString()}function mo(o,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;o.InventoryV2??={};let n=o.InventoryV2,r=i.toISOString(),c=new Map,h=new Map,R=new Map,j=new Map,ce=new Map,Ae=new Map,Re=new Map,Ue=new Map,vt=e.Grant?.PremiumTiers??[],et=vt.length;for(let re=0;;re++){let ve,pe;if(re===0)ve=e.Grant?.Standard?.Entries,pe=false;else if(re-1<et)ve=vt[re-1]?.Resources?.Entries,pe=false;else if(re===1+et)ve=e.Consume?.Standard?.Entries,pe=true;else break;if(ve)for(let le of ve){if(le.Type==null)continue;let de=Math.max(0,le.Amount??0);if(!(de<=0))switch(le.Type){case "VirtualCurrency":{if(!le.CurrencyID)continue;let he=pe?h:c;he.set(le.CurrencyID,(he.get(le.CurrencyID)??0)+de);break}case "CryptoCurrency":{if(!le.CurrencyID)continue;let he=pe?j:R;he.set(le.CurrencyID,(he.get(le.CurrencyID)??new Jt(0)).plus(de));break}case "Item":{if(!le.ItemID)continue;let he=Xf(t,le.CatalogID,le.ItemID),be=(he?he.IsStackable??true:true)?pe?Ae:ce:pe?Ue:Re;be.set(le.ItemID,(be.get(le.ItemID)??0)+de);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=c.size>0||h.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let re of new Set([...c.keys(),...h.keys()])){let ve=c.get(re)??0,pe=h.get(re)??0,le=ve-pe,de=n.VirtualCurrencies[re];de?(de.Amount+=le,de.UpdatedAt=r,de.Daily&&pi(de.Daily.PeriodStartUtc)===pi(i)?(de.Daily.Earned+=ve,de.Daily.Spent+=pe):de.Daily={PeriodStartUtc:vi(i),Earned:ve,Spent:pe}):n.VirtualCurrencies[re]={Amount:le,CreatedAt:r,UpdatedAt:r,Daily:{PeriodStartUtc:vi(i),Earned:ve,Spent:pe}};}}if(s.ccChanged=R.size>0||j.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let re of new Set([...R.keys(),...j.keys()])){let ve=R.get(re)??new Jt(0),pe=j.get(re)??new Jt(0),le=ve.minus(pe),de=n.CryptoCurrencies[re];de?(de.Amount=new Jt(de.Amount).plus(le).toString(),de.UpdatedAt=r):n.CryptoCurrencies[re]={Amount:le.toString(),Frozen:"0",CreatedAt:r,UpdatedAt:r};}}if(s.itemsChanged=ce.size>0||Ae.size>0||Re.size>0||Ue.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let re=n.UnstackableItems,ve=new Set([...ce.keys(),...Ae.keys(),...Re.keys(),...Ue.keys()]);for(let pe of ve){let le=(ce.get(pe)??0)-(Ae.get(pe)??0),de=(Re.get(pe)??0)-(Ue.get(pe)??0),he=le+de,ot=n.Items[pe];ot?(le!==0&&(ot.StackableAmount+=le),de!==0&&(ot.UnstackableAmount+=de),he!==0&&(ot.TotalAmount+=he)):n.Items[pe]={StackableAmount:Math.max(0,le),UnstackableAmount:Math.max(0,de),TotalAmount:Math.max(0,he)};}for(let[pe,le]of Ue){if(le<=0)continue;let de=Object.values(re).filter(he=>he.ItemID===pe&&he.EquippedSlot==null&&(he.ExpiresAt==null||new Date(he.ExpiresAt)>i)).sort(Yf).slice(0,le).map(he=>he.ItemInstanceID);for(let he of de)delete re[he];}for(let[pe,le]of Re){let de=eg(t,pe);for(let he=0;he<le;he++){let ot=a();re[ot]={ItemInstanceID:ot,ItemID:pe,CatalogID:de,RemainingUses:1,AcquiredAt:r};}}}o.EventToken??={};let xi=o.EventToken;for(let re=0;;re++){let ve,pe;if(re===0)ve=e.Grant?.Standard?.EventTokens,pe=false;else if(re-1<et)ve=vt[re-1]?.Resources?.EventTokens,pe=false;else if(re===1+et)ve=e.Consume?.Standard?.EventTokens,pe=true;else break;if(!(!ve||ve.length===0))for(let le of ve){let de=le.Address;if(!de||de.Type==null)continue;let he=le.Amount??0;if(he<=0)continue;let ot=tg(xi,de.Type);if(!ot)continue;let be=ot[de.EntityID];be||(be={},ot[de.EntityID]=be),be.Balance??={Current:0,TotalEarned:0,TotalSpent:0},be.Daily??={Date:vi(i),TotalEarned:0},be.Meta??={};let bi=le.Source&&le.Source.length>0?le.Source:"CustomAction";pe?(be.Balance.Current-=he,be.Balance.TotalSpent+=he):(be.Balance.Current+=he,be.Balance.TotalEarned+=he,pi(be.Daily.Date)!==pi(i)&&(be.Daily={Date:vi(i),TotalEarned:0}),be.Daily.TotalEarned+=he,be.Daily.EarnedBySource??={},be.Daily.EarnedBySource[bi]=(be.Daily.EarnedBySource[bi]??0)+he,be.Daily.TriggersBySource??={},be.Daily.TriggersBySource[bi]=(be.Daily.TriggersBySource[bi]??0)+1,be.Daily.LastTriggerBySource??={},be.Daily.LastTriggerBySource[bi]=r,be.Meta.JoinedAtUtc||(be.Meta.JoinedAtUtc=r),be.Meta.LastEarnedAtUtc=r),s.tokensChanged=true;}}return s}function Yf(o,e){return o.AcquiredAt!==e.AcquiredAt?o.AcquiredAt<e.AcquiredAt?-1:1:o.ItemInstanceID===e.ItemInstanceID?0:o.ItemInstanceID<e.ItemInstanceID?-1:1}function Xf(o,e,t){let i=o?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let n=s.Items?.[t];if(n)return n}}}function eg(o,e){let t=o?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function tg(o,e){switch(e){case "TimedEvent":return o.TimedEvent??={};case "Quest":return o.Quest??={};case "Leaderboard":return o.Leaderboard??={};case "CoopEvent":return o.CoopEvent??={};case "Season":return o.Season??={};default:return null}}function Nl(o,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},n=new Set(t.RemovedInstanceIDs??[]),r=new Set;for(let h of Object.values(s))h?.ItemID&&r.add(h.ItemID);for(let h of n){let R=o[h]?.ItemID;R&&r.add(R);}if(r.size===0)return i;let c=h=>n.has(h)||h in s;if(e){for(let[h,R]of Object.entries(e))h in o||c(h)||R&&r.has(R.ItemID)&&i.drop.push(h);for(let[h,R]of Object.entries(o))h in e||c(h)||R&&r.has(R.ItemID)&&(i.restore[h]=R);}return i}function fo(o,e){return o===e||o.startsWith(`${e}:`)}var ns=class o{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){o.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];o.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){o.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 s=mo(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let n=this.currentState,r={...n.InventoryV2?.UnstackableItems??{}},c=mo(n,e,i,s),h=Nl(r,n.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),j=t?.RemovedInstanceIDs??[],ce=h.drop.length>0||Object.keys(h.restore).length>0||R.length>0||j.length>0;if(ce){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let Ae=n.InventoryV2.UnstackableItems;for(let Re of h.drop)delete Ae[Re];for(let[Re,Ue]of Object.entries(h.restore))Ae[Re]=Ue;for(let[Re,Ue]of R)Ae[Re]=Ue;for(let Re of j)delete Ae[Re];}this.emitResourceChanges(c,ce);}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,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,r=t instanceof Jt?t:new Jt(t),c=s===void 0?new Jt(0):s instanceof Jt?s:new Jt(s),h=i??new Date().toISOString(),R=n[e];R?(R.Amount=new Jt(R.Amount).plus(r).toString(),c.isZero()||(R.Frozen=new Jt(R.Frozen??0).plus(c).toString()),R.UpdatedAt=h):n[e]={Amount:r.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 s=this.currentState.Store.Purchases,n=s[e];n||(n={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=n),n.TotalPurchases+=t,n.LastPurchasedAt=i,i>=n.DailyResetUtc?(n.DailyPurchases=t,n.DailyResetUtc=Vl(i)):n.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 s=this.currentState.Lootbox??={};if(s.Pity??={},t){let n=new Date().toISOString();for(let r of t)r.RuleID&&(s.Pity[`${e}:${r.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:n});}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 s=this.currentState.Quest;if(t){s.Cycles??={};let n=s.Cycles[t];if(!n)return;n.Quests??={};let r=n.Quests[e]??={QuestID:e,Status:i};r.Status=i,i==="Claimed"&&(r.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let n=s.PermanentQuests[e]??={QuestID:e,Status:i};n.Status=i,i==="Claimed"&&(n.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 s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,n=t[s]??={};n.Balance??={Current:0,TotalEarned:0,TotalSpent:0},n.Balance.Current=i.PointsCurrent??0,n.Balance.TotalEarned=i.PointsTotalEarned??0,n.Milestone??={};for(let r of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(n.Milestone,r);}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 s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let n=s.Steps[i.StepID]??={StepID:i.StepID};n.Progress=i.Progress,i.Completed&&(n.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let n=t.Cycles[i.CycleID];if(!n)continue;n.Quests??={},s=n.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let n=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};n.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(n.Completed=true,n.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(fo(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[n,r]of Object.entries(this.currentState.EventToken.TimedEvent))r&&((s?n!==s:!fo(n,t))||this.markMilestoneClaimed(r.Milestone??(r.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let n=this.activeEventsCache?.ActiveEvents;if(n)for(let r of n)r.Type!==e||r.TimedEventID!==t||s&&r.TokenEntityID&&r.TokenEntityID!==s||(r.Progress??={},this.markMilestoneClaimed(r.Progress.Milestone??(r.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,s){if(!e)return;let n=this.ensureLeaderboardProgress(e);(n.ScoreCycleVersion??0)<s&&(n.ScoreEarnedThisCycle=0,n.ClaimedMilestoneIDs=[],n.BracketID=null),n.CurrentScore=t,n.ScoreEarnedThisCycle=(n.ScoreEarnedThisCycle??0)+i,n.ScoreCycleVersion=s,n.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 s=false;for(let n of Object.values(i))for(let r of Object.values(n.Equipment??{}))r?.ItemInstanceID===e&&(r.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.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[s,n]of Object.entries(e.ChangedInstances??{}))t[s]=n,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],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 s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.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 s of Object.keys(i)){let n=i[s];n&&n.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}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,s,n){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let r=this.currentState.CustomData,c={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")r.Private??={},r.Private[t]=c;else if(e==="Public")r.Public??={},r.Public[t]=c;else return;r.Version=(r.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 s=i.BuildingStates.find(n=>n.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let 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 s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},n=s.PendingWithdrawals??[];t.size>0&&(n=n.filter(r=>!r.TitleTransactionID||!t.has(r.TitleTransactionID))),i&&!n.some(r=>r.TitleTransactionID===i.TitleTransactionID)&&(n=[...n,i]),s.PendingWithdrawals=n;}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 rs=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 os=class{user;config;constructor(e){this.user=new ns(e),this.config=new rs;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function ig(o){return o}var sg=0,ng=1500,rg=3,ls=class{constructor(e,t,i=null,s="",n="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=s;this.loginMode=n;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 a$1(void 0);let i=Date.now(),s=[],n=[];for(let h of new Set(e)){let R=this.rules.get(h);if(R&&(t?.force||R.needsServer(i))){s.push(this.runRule(h,R));continue}(t?.force||!this.state.isStateFresh(h,t?.maxAgeMs))&&n.push(h);}let c=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(a$1(void 0))])).find(h=>!h.ok);return c&&!c.ok?c:a$1(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}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();},sg),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(s=>i=s);try{let s=this.state?await this.state.readStateSlice(e):a$1(void 0),n=s.ok?a$1(void 0):s;for(let r of t)r(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=as(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let R=this.fresh(s,i?.maxAgeMs);if(R)return a$1(R.data);let j=this.loginFailures.get(s);if(j)return this.loginFailures.delete(s),j;let ce=this.inflight.get(s);if(ce)return ce}let n=this.generation.get(s)??0,r=Date.now(),h=t().then(R=>{if(!R.ok)return R;let j=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:R.data,storedAt:j,expiresAt:go(e,R.data,j)}),R;let ce=this.entries.get(s);if(ce&&ce.storedAt>=r)return R;let Ae=go(e,R.data,j);return this.entries.set(s,{data:R.data,storedAt:j,expiresAt:Math.min(Ae??1/0,j+ng)}),R}).finally(()=>{this.inflight.get(s)===h&&this.inflight.delete(s);});return this.inflight.set(s,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 s=t.Key?t.Key:void 0,n=as(i.view,s);if(!t.Success){this.loginFailures.set(n,b("server",t.Error??"View failed."));continue}let r=i.schema.safeParse(t.Data);r.success&&(this.loginFailures.delete(n),i.apply(r.data,s),this.put(i.view,r.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let n=jl({Name:s,Key:t});this.used.get(n)?.n!==this.session&&(this.used.set(n,{Name:s,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>rg||this.used.set(jl(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(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(as(e,t))?.data}put(e,t,i){this.register(e);let s=as(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:go(e,t,n)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===i||s.startsWith(`${i}|`))&&this.drop(s);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 s=Date.now();if(!(i.expiresAt!==null&&s>=i.expiresAt)&&!(t!==void 0&&s-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(s=>t.has(s))&&this.invalidate(i);}};function as(o,e){return e===void 0?o.key:`${o.key}|${e}`}function jl(o){return o.Key?`${o.Name}|${o.Key}`:o.Name}function go(o,e,t){let i=o.expiresAt?.(e)??null,s=o.ttlMs!==void 0?t+o.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var us=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 og(e)?e:r.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 og(o){return o!==null&&Object.values(r).includes(o)}var ag=8,lg=100,ug=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,cs=["GameLoop"];function cg(o){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(o)}var ps=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=r.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 s=this.authContext;if(!s)return c;let n=this.baseRequest();n.UserID=s.userID,n.ClientSessionTicket=s.clientSessionTicket,n.WalletAddress=e,n.NetworkID=t,i&&(n.WalletSignature=i);let r=await this.ctx.api.authentication.linkWallet(n);return r.ok&&r.data.PlayAccess&&this.setPlayAccess(r.data.PlayAccess),r}async unlinkWallet(e){let t=this.authContext;if(!t)return c;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(i);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.host.getDeviceID(),e.Device=this.ctx.host.getDeviceModel(),e.Platform=this.ctx.host.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(r.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.host.getTelegramInitDataRaw();if(!e)return b("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(r.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 s=await this.ctx.api.authentication.loginWithEmail(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(r.Email);return n.ok&&this.keepEmailCredentials(e,t),n}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.host.getDeviceID(),i.Device=this.ctx.host.getDeviceModel(),i.Platform=this.ctx.host.getPlatform();let s=await this.ctx.api.authentication.registerWithEmail(i);return s.ok?(this.pendingRegistration={email:e,password:t},a$1({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(r.Email);return n.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,n}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?a$1(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(r.Google)):i}async loginWithApple(e,t){if(!e?.trim())return b("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 s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(r.Apple)):s}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 s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=i,s.Platform=this.ctx.host.getPlatform(),s.Device=this.ctx.host.getDeviceModel(),s.DeviceID=this.ctx.host.getDeviceID();let n=await this.ctx.api.authentication.loginWithWallet(s);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(r.Wallet)):n}async loginWithSsoCode(e){if(!e)return b("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.host.getDeviceID(),t.Device=this.ctx.host.getDeviceModel(),t.Platform=this.ctx.host.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(r.iDosGames)):i}async loginWithPlatformGameTicket(e){if(!e)return b("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.userService.prepareLoginClientState(cs,cs);t.ClientState=i.request;let s=await this.ctx.api.authentication.resolvePlatformGameSession(t);if(!s.ok)return s;this.applyAuthContext(s.data),this.platformGameSession=true;let n=s.data.ClientState;return this.fetchAndApplyClientState(r.iDosGames,n?()=>i.finish(n):void 0)}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=i,this.ctx.api.authentication.resetPassword(s)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==r.None?e:r.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 s=await this.ctx.api.authentication.refreshSession(i);return s.ok?(this.applyRefresh(s.data),"ok"):(cg(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case r.Email:return this.loginWithEmail(t,i);case r.Device:case r.None:return this.loginWithDeviceID();case r.Telegram:return this.loginWithTelegram();default:return Promise.resolve(b("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;if(this.platformGameSession){this.refreshing=true;try{let t=await this.ctx.host.signIn(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let s=await this.ctx.api.authentication.resolvePlatformGameSession(i);return s.ok?(this.applyAuthContext(s.data),this.platformGameSession=!0,s.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==r.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===r.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&&ug.test(e)}static isValidPasswordLength(e){return e.length>=ag&&e.length<=lg}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=r.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e,t){let i=t?await t():await this.ctx.userService.getClientStateExcept(cs,cs);return i.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)),i}};var pg="idos:cfg",di=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${_l(t)}`:e&&e.length>0?`f:${_l(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 s={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${pg}:${this.titleId}:${e}`}};function _l(o){return [...o].map(e=>e.toLowerCase()).sort().join(",")}var Wl="idos:loc",hi=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 s={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[s,n]of Object.entries(t))typeof n=="number"&&n>0&&(i[s]=n);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 `${Wl}:${this.titleId}:${e}`}versionsKey(){return `${Wl}:${this.titleId}:versions`}};var dg="idos:sec",ds=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 `${dg}:${this.titleId}`}};var hg="idos:state",hs=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,s){if(!(!e||!t))try{let n={e:t,v:i,s};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}keyOf(e){return `${hg}:${this.titleId}:${e}`}};function mg(o,e){if(!o)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return o;let i={};for(let[s,n]of Object.entries(o))t.has(s.toLowerCase())||(i[s]=n);return i}function yo(o,e,t,i){let s={...o??{}};if(!e||!t||!i)return s;for(let[n,r]of Object.entries(t))i[n]===r&&n in e&&(s[n]=e[n]);return s}function fg(o){return {...o??{}}}function Ro(o){return typeof o.StateEpoch=="string"&&o.StateEpoch.length>0?o.StateEpoch:null}var ms=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 s=this.confirmedAt[e];return s===void 0?false:t===void 0||i-s<=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=mg(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 n=Object.keys(this.versions);this.reset(e),this.notify(n);}return}let i=Date.now(),s=[];for(let[n,r]of Object.entries(t)){let c=this.versions[n];c!==r&&(c!==void 0&&r===c+1?(this.versions[n]=r,this.confirmedAt[n]=i):(delete this.versions[n],delete this.confirmedAt[n]),s.push(n),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=fg(t);let s=Date.now();this.confirmedAt={};for(let r of Object.keys(this.versions))this.confirmedAt[r]=s;this.dirty=true;let n=new Set;for(let r of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[r]!==this.versions[r]&&n.add(r);this.notify([...n]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[n,r]of Object.entries(t??{}))this.versions[n]!==r&&s.push(n),this.versions[n]=r,this.confirmedAt[n]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Kl=b("server","Title configuration is unavailable (CDN and API both failed)."),fs=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:a()}:null}get configCache(){return this.cache??=new di(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new hi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new ds(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new ms(new hs(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 c;let t=di.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let n=await this.ctx.api.user.getClientState(e);if(!n.ok)return n;let r=await this.resolveTitleConfig(n.data,t,i,{Fields:e.TitleFields});return r==null?Kl:(this.finishStateHandshake(n.data,s),await this.restoreSections(n.data.TitleConfigVersion,r),await this.applyClientState(n.data,r,void 0,void 0),this.ctx.cache.acceptLoginViews(n.data.Views),await this.applyLocalization(n.data.Localization),await this.flushState(s),n)}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 s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let n=this.stateStore.currentEpoch;n&&(e.KnownStateEpoch=n);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=yo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=Ro(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,i,s){let n=e.TitleConfigVersion;if(i&&n&&i.v===n)return i.c;if(e.TitleConfigUrl){let c=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(c!=null)return n&&await this.configCache.write(t,n,c),c}let r=await this.fetchConfigFromApi(s);return r!=null?(n&&await this.configCache.write(t,n,r),r):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},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return c;let s=await this.prepareClientStateExcept(i,e,t,true),n=await this.ctx.api.user.getClientStateExcept(i);return n.ok?this.finishClientStateExcept(s,n.data):n}async prepareLoginClientState(e,t){let i={BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.host.getFullURL(),RelatedEntityID:a()},s=await this.prepareClientStateExcept(i,e,t,false);return {request:i,finish:async n=>{let r=this.ctx.auth.context?.userID??null;return r&&await this.stateStore.load(r),s.handshake={userId:r,cached:null,sent:void 0},this.finishClientStateExcept(s,n)}}}async prepareClientStateExcept(e,t,i,s){e.ExcludeFields=t,e.ExcludeTitleFields=i;let n=di.scopeOf(null,i??[]),r=await this.configCache.read(n);r&&(e.KnownTitleConfigVersion=r.v),await this.prepareLocalization(e);let c=s?await this.prepareStateHandshake(e,t??null):{userId:null,cached:null,sent:void 0};return await this.prepareLoginViews(e),{scope:n,cached:r,handshake:c,excludeFields:t,excludeTitleFields:i}}async finishClientStateExcept(e,t){let i=await this.resolveTitleConfig(t,e.scope,e.cached,{ExcludeFields:e.excludeTitleFields??[]});return i==null?Kl:(this.finishStateHandshake(t,e.handshake),await this.restoreSections(t.TitleConfigVersion,i),await this.applyClientState(t,i,e.excludeFields,e.excludeTitleFields),this.ctx.cache.acceptLoginViews(t.Views),await this.applyLocalization(t.Localization),await this.flushState(e.handshake),a$1(t))}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let i=t,s={};for(let[n,r]of Object.entries(await this.sectionCache.read(e)))i[n]==null&&(s[n]=r);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((n,r)=>{i[n]!=null||r==null||(s[n]=r,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let 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 s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let r=await this.fetchLocalizationFromCdn(e.Url);if(r!=null)return await this.localizationCache.write(t,i,r),r}let n=await this.fetchLocalizationFromApi(t,s?.v??0);return n??s?.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 s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let n=s.data;if(n.NotModified)return null;let r=n.Entries??{},c=n.Version??0,h=n.Locale??e;return c>0&&await this.localizationCache.write(h,c,r),r}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):c}async getUserState(e){let t=this.baseRequest();if(!t)return c;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let n=yo(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let r=i.sent??{},c$1=Object.entries(s.data.StateVersions??{}).filter(([R,j])=>r[R]!==j||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(n,c$1);let h=Ro(s.data);return h&&(this.stateStore.afterSliceRead(h,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return c;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 c;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 c;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 s=this.baseRequest();if(!s)return c;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=i;let n=await this.ctx.api.user.addUsageTime(s);return n.ok&&this.ctx.emitter.emit("user:usageTimeAdded",n.data),n}async deleteUserAccount(){let e=this.baseRequest();if(!e)return c;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 c;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,s){let n=i?.includes("GameLoop")===true,r=s?.includes("GameLoop")===true,c=n?this.ctx.data.user.state?.GameLoop:void 0,h=r?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let R=this.ctx.data.user.state;n&&R&&R.GameLoop==null&&(R.GameLoop=c);let j=this.ctx.data.config.titlePublicConfiguration;r&&j&&j.GameLoop==null&&(j.GameLoop=h),this.ctx.emitter.emit("user:clientStateReceived",e);}};var ys=class{constructor(e){this.ctx=e;}ctx;async spend(e,t={}){if(!e)return b("client","SpendID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SpendID:e,...t.selectedOptionID?{SelectedOptionID:t.selectedOptionID}:{},RelatedEntityID:t.relatedEntityID&&t.relatedEntityID.length>0?t.relatedEntityID:`spend_${e}_${a()}`},s=await this.ctx.api.currency.spend(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:spent",s.data)),s}async convert(e,t,i,s,n,r){if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(n<=0)return b("client","Amount must be positive.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===f.Crypto||i===f.Crypto)return b("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return c;let c$1={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(n)),TransactionID:r&&r.length>0?r:`convert_${e}_${t}_to_${i}_${s}_${a()}`},h=await this.ctx.api.currency.convert(c$1);if(h.ok){let R=h.data,j={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.SourceID,Amount:R.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.TargetID,Amount:R.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(j,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return h}async cryptoConvert(e,t,i,s,n,r){let c$1=n instanceof Jt?n:new Jt(n);if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(c$1.lte(0))return b("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===f.Virtual&&i===f.Virtual)return b("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===f.Virtual&&!c$1.isInteger())return b("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return c;let h={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:c$1.toString(),TransactionID:r&&r.length>0?r:`crypto_convert_${e}_${t}_to_${i}_${s}_${a()}`},R=await this.ctx.api.currency.cryptoConvert(h);if(R.ok){let j=R.data,ce=[],Ae=[];if(j.SourceType===f.Virtual&&ce.push({Type:"VirtualCurrency",CurrencyID:j.SourceID,Amount:Math.trunc(Number(j.SourceSpent))}),j.TargetType===f.Virtual&&Ae.push({Type:"VirtualCurrency",CurrencyID:j.TargetID,Amount:Math.trunc(Number(j.TargetCredited))}),ce.length>0||Ae.length>0){let Re={Consume:ce.length>0?{Standard:{Entries:ce}}:null,Grant:Ae.length>0?{Standard:{Entries:Ae}}:null};this.ctx.data.user.applyResourceOperation(Re,this.ctx.data.config.itemDefinitions);}j.SourceType===f.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.SourceID,new Jt(j.SourceSpent).negated(),j.ServerTimeUtc),j.TargetType===f.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.TargetID,new Jt(j.TargetCredited),j.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",j);}return R}};var Rs=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i,s){let n=e.trim();if(!n)return b("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:n,SelectedOptionID:i,CreditsConfirmationID:s,RelatedEntityID:`upgrade_item_${n}_${a()}`};t&&t.length>0&&(r.FodderInstanceIDs=[...t]);let c$1=await this.ctx.api.item.upgradeLevel(r);return c$1.ok&&!c$1.data.CreditsConfirmation&&(this.ctx.data.user.patchEquippedItemLevel(c$1.data.ItemInstanceID??n,c$1.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",c$1.data)),c$1}async upgradeLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let s of i.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var Cs=z.object({OptionID:z.string().nullish(),Name:z.string().nullish(),Cost:Tt.nullish(),AllowedPlatforms:z.array(k).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),oe=z.record(z.string(),Cs),gg=z.object({Store:m,Receipt:z.string(),Signature:z.string().nullish()}).passthrough();var Ti={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},me=z.object({ConfirmationID:z.string(),Url:z.string(),Status:z.string(),PriceCredits:z.number(),ExpiresAt:p}).passthrough(),Ql=z.object({Linked:z.boolean(),Credits:z.number(),TopUpUrl:z.string().nullish()}).passthrough(),yg={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"},Co=z.object({ServerTimeUtc:p,OfferID:z.string(),Count:z.number(),Resources:O.nullish(),Inventory:K.nullish(),CreditsConfirmation:me.nullish()}),Hl=z.array(Te(Co)),Rg=z.object({OfferID:z.string(),TotalPurchases:z.number(),DailyPurchases:z.number(),DailyResetUtc:p,LastPurchasedAt:p}),Cg=z.object({SlotKey:z.string(),InstanceKey:z.string(),OfferID:z.string().nullish(),Purchases:z.number(),LastPurchasedAt:p}),$l=z.object({Purchases:z.record(z.string(),Rg).nullish(),Rotations:z.record(z.string(),Cg).nullish()}).passthrough().transform(o=>o),kt=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Ss=z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Sg={Fixed:"Fixed",Title:"Title",Player:"Player"},xg=z.object({OfferID:z.string().nullish(),Weight:z.number().nullish(),Gate:Z.nullish()}).passthrough(),Jl=z.object({Mode:z.string().nullish(),OfferID:z.string().nullish(),Pool:z.array(xg).nullish(),Salt:z.string().nullish(),PerInstanceCap:z.number().nullish()}).passthrough(),bg=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Rotation:Q.nullish()}).passthrough(),Dg=z.object({SlotID:z.string().nullish(),Identity:kt.nullish(),Availability:Ss.nullish(),Rotation:Jl.nullish(),Presets:bg.nullish()}).passthrough(),Ig=z.object({Identity:Q.nullish(),Availability:Q.nullish()}).passthrough(),Pg=z.object({SectionID:z.string().nullish(),Identity:kt.nullish(),Availability:Ss.nullish(),Slots:z.record(z.string(),Dg).nullish(),UniqueOffersInSection:z.boolean().nullish(),Presets:Ig.nullish()}).passthrough(),Zl=z.object({Sections:z.record(z.string(),Pg).nullish()}).passthrough(),vg=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Layout:Q.nullish()}).passthrough(),Tg=z.object({StoreID:z.string().nullish(),Identity:kt.nullish(),Availability:Ss.nullish(),Layout:Zl.nullish(),Presets:vg.nullish()}).passthrough(),Yl=z.object({Options:oe.nullish(),CompareAt:z.record(z.string(),Tt).nullish()}).passthrough(),Xl=z.object({Grant:H.nullish()}).passthrough(),eu=z.object({Schedule:ge.nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),Ag=z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish(),Availability:Q.nullish()}).passthrough(),kg=z.object({OfferID:z.string().nullish(),Identity:kt.nullish(),Pricing:Yl.nullish(),Reward:Xl.nullish(),Availability:eu.nullish(),Presets:Ag.nullish()}).passthrough(),zg=z.object({Identity:z.record(z.string(),kt).nullish(),Availability:z.record(z.string(),Ss).nullish(),Layout:z.record(z.string(),Zl).nullish(),Rotation:z.record(z.string(),Jl).nullish(),Pricing:z.record(z.string(),Yl).nullish(),Reward:z.record(z.string(),Xl).nullish(),OfferAvailability:z.record(z.string(),eu).nullish()}).passthrough(),xs=z.object({Stores:z.record(z.string(),Tg).nullish(),StoreOffers:z.record(z.string(),kg).nullish(),Presets:zg.nullish()}).passthrough(),wg=z.object({PurchasedTotal:z.number(),PurchasedToday:z.number(),PurchasedThisRotation:z.number(),RemainingTotal:z.number().nullish(),RemainingToday:z.number().nullish(),IsFirstPurchaseAvailable:z.boolean(),SoldOut:z.boolean(),AvailableAtUtc:p.nullish()}).passthrough(),Mg=z.object({OptionID:z.string(),Name:z.string().nullish(),Cost:Tt.nullish(),CompareAtCost:Tt.nullish(),DiscountPercent:z.number().nullish(),IsFree:z.boolean(),IsAdPaid:z.boolean(),IsStorePaid:z.boolean(),IsCreditsPaid:z.boolean().nullish(),CreditsPrice:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Og=z.object({OfferID:z.string(),Identity:kt.nullish(),PriceOptions:z.array(Mg).nullish(),Rewards:H.nullish(),State:wg.nullish()}).passthrough(),Eg=z.object({SlotID:z.string(),Identity:kt.nullish(),SortOrder:z.number(),RotationMode:z.string().nullish(),RotationInstanceKey:z.string().nullish(),RefreshesAtUtc:p.nullish(),RemainingThisRotation:z.number().nullish(),Offer:Og.nullish()}).passthrough(),Ug=z.object({SectionID:z.string(),Identity:kt.nullish(),SortOrder:z.number(),Slots:z.array(Eg).nullish()}).passthrough(),qg=z.object({StoreID:z.string(),Identity:kt.nullish(),SortOrder:z.number(),ScheduleInstanceKey:z.string().nullish(),ExpiresAtUtc:p.nullish(),Sections:z.array(Ug).nullish()}).passthrough(),bs=z.object({ServerTimeUtc:p,Stores:z.array(qg).nullish(),AdCreditBalance:z.number()}).passthrough(),zt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},Bg="OFFER_NOT_IN_ROTATION";var tu="Store",iu={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:o=>{let e=null;for(let t of o.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},Ds=class{constructor(e){this.ctx=e;e.cache.bindLoginView(iu,{schema:bs,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return b("client","OfferID is required.");if(t<1)return b("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return c;let n={...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}_${s.userID}_${a()}`},r=await this.ctx.api.store.purchase(n);if(r.ok&&!r.data.CreditsConfirmation){let c=r.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 r}async purchaseWithCredits(e,t=1,i={}){return await this.ctx.credits.pay(s=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:s}),{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}):c}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):c}async purchaseBatch(e){if(!e||e.length===0)return b("client","purchases is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||!n.Data.OfferID||(this.ctx.data.user.patchStorePurchase(n.Data.OfferID,n.Data.Count,n.Data.ServerTimeUtc),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(tu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(tu,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(iu,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return c;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 s of i.Slots??[]){let n=s.RefreshesAtUtc;n&&(e===null||Date.parse(n)<Date.parse(e))&&(e=n);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 Is=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 s=i.data.CreditsConfirmation,n=()=>e(s.ConfirmationID);if(this.ctx.host.supports.creditsConfirm){let h=await this.ctx.host.confirmCredits({titleID:this.ctx.settings.titleID,confirmationID:s.ConfirmationID});if(h.ok)return await n();if(h.error==="DECLINED")return b("server","CREDITS_CONFIRMATION_DECLINED");if(h.error==="NOT_ENOUGH_CREDITS")return b("server","NOT_ENOUGH_CREDITS")}t.onConfirmation?.(s);let r=Math.max(1e3,t.pollMs??2500),c=Date.parse(s.ExpiresAt)+6e4;for(;;){if(t.signal?.aborted)return b("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>c)return b("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(j=>setTimeout(j,r));let h=await this.ctx.store.getCreditsConfirmation(s.ConfirmationID);if(!h.ok)continue;let R=h.data.Status;if(R!==Ti.Pending)return R===Ti.Declined?b("server","CREDITS_CONFIRMATION_DECLINED"):R===Ti.Expired?b("server","CREDITS_CONFIRMATION_EXPIRED"):await n()}}};var Ps=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return c;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return c;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?a$1(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return b("client","Receipt is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},n=await this.ctx.api.purchase.validatePurchase(s);return n.ok&&this.applyValidation(n.data),n}async buyWithTelegramStars(e,t){if(!e)return b("client","productID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(i);return s.ok&&t?.open!==false&&this.ctx.host.openInvoice(s.data.InvoiceLink),s}async buy(e){if(!e)return b("client","productID is required.");if(!this.ctx.host.supports.storePurchases)return b("client","UNAVAILABLE");if(!this.ctx.auth.context)return c;let t=await this.getDefinitions();if(!t.ok)return t;let i=t.data.Purchase?.Products?.[e],s=this.hostStore(),n=i?.StoreProductIDs?.[s];if(!i||i.Enabled===false||!n)return b("client","NOT_SOLD");let r=this.ctx.buildAuthedBaseRequest(),c$1=await this.ctx.host.buyProduct({storeProductID:n,type:i.Type??"Consumable",accountID:r.UserID??void 0});return !c$1.ok||!c$1.receipt?b("client",c$1.error??"FAILED"):this.deliver(c$1.receipt,i)}async restorePending(){if(!this.ctx.host.supports.storePurchases||!this.ctx.auth.context)return 0;let e=await this.ctx.host.pendingPurchases();if(e.length===0)return 0;let t=await this.getDefinitions(),i=t.ok?Object.values(t.data.Purchase?.Products??{}):[],s=0;for(let n of e){let r=i.find(c=>n.storeProductID&&c.StoreProductIDs?.[n.store]===n.storeProductID);(await this.deliver(n,r)).ok&&s++;}return s}async deliver(e,t){let i=await this.validatePurchase(e.store,e.receipt,{signature:e.signature});return i.ok&&await this.ctx.host.finishPurchase(e,(t?.Type??"Consumable")==="Consumable"),i}hostStore(){return this.ctx.host.getClientPlatform()===j.Ios?"AppleAppStore":"GooglePlay"}async validatePurchasesBatch(e){if(!e||e.length===0)return b("client","receipts is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let s of i.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var su=3,Lg=700,vs=class{constructor(e){this.ctx=e;e.host.supports.cryptoTopUp&&this.setTopUpHandler(this.hostTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return ci(e)}hostTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await this.ctx.host.topUp({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<=su;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===su)break;await Bt(Lg);}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===h.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!==h.CryptoCurrency||!i.CurrencyID)continue;let s=Number(i.Amount??0);if(!(s>0))continue;let n=this.cryptoBalance(i.CurrencyID);return n>=s?null:{currencyID:i.CurrencyID,required:s,available:n,missing:s-n}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var nu="Lootbox",Ts=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(nu,e);if(t){let n={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),a$1(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection(nu,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s,n){if(!e)return b("client","LootboxID is required.");if(t<1)return b("client","Count must be at least 1.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,CreditsConfirmationID:n,RelatedEntityID:`lootbox_${e}_${i??"default"}_${a()}`},c$1=await this.ctx.api.lootbox.open(r);if(c$1.ok&&!c$1.data.CreditsConfirmation){let h=c$1.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$1}};var So="Reward";function As(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var ks=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(So)?.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(So,e);if(t){let n={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),a$1(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(So,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 c;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${a()}`},s=await this.ctx.api.reward.claimDailyReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchDailyCalendarState(n.CalendarID,n.DailyState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",n);}return s}async collectIdleAccrual(e){if(!As(e))return b("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${a()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let s=i.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return i}async claimComebackReward(e){if(!As(e))return b("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${a()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return i}async claimReward(e){if(!As(e))return b("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${a()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return i}async claimRewardWindow(e,t,i={}){if(!As(e))return b("client",'WindowID is required and must not contain "." or "$".');if(!Number.isFinite(t)||t<=0)return b("client","Amount must be a positive number.");let s=i.boost??"None";if(s==="Ad"&&!i.adRequestID)return b("client",'Boost "Ad" needs the RequestID of the ad view.');if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),WindowID:e,Amount:Math.floor(t),Boost:s,...i.adRequestID?{AdRequestID:i.adRequestID}:{},RelatedEntityID:i.roundID??`reward_window_${e}_${a()}`},r=await this.ctx.api.reward.claimRewardWindow(n);if(r.ok){let c=r.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 r}};var zs="Tutorial",ru={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"]},ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ru,{schema:Ji,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(zs)?.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(zs,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(zs,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(ru,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return c;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}_${a()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return b("client","FlowID is required.");if(!t||t.length===0)return b("client","stepIDs is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${a()}`},n=await this.ctx.api.tutorial.completeStepsBatch(s);return n.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",n.data)),n}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 b("client","FlowID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${a()}`},s=await this.ctx.api.tutorial.claimFlowReward(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let s=e?.trim();if(!s)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:s},r=await t(n);return r.ok&&(this.applyFlowView(r.data),this.ctx.emitter.emit(i.event,r.data)),r}async stepCall(e,t,i,s){let n=e?.trim(),r=t?.trim();if(!n)return b("client","FlowID is required.");if(!r)return b("client","StepID is required.");if(!this.ctx.auth.context)return c;let c$1={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:r};s?.relatedEntityID&&(c$1.RelatedEntityID=s.relatedEntityID);let h=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,R=await i(c$1);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(n,r,h,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(zs)?.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 Ms=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 b("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","campaignID is required.");if(!t)return b("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return c;s.CampaignID=e,s.WalletAddress=t,i&&(s.Amount=i);let n=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return n.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",n.data),n}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var qe=z.object({Username:z.string().nullish(),Country:z.string().nullish(),AvatarUrl:z.string().nullish(),Premium:z.boolean().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),BoardRank:z.number().nullish()}).passthrough();var Gg={Global:"Global",Announcement:"Announcement",Group:"Group"},au=z.enum(["Global","Announcement","Group"]).catch("Global"),Vg={None:"None",Language:"Language",Region:"Region"},Fg=z.enum(["None","Language","Region"]).catch("None"),Ng={Anyone:"Anyone",Friends:"Friends"},jg=z.enum(["Anyone","Friends"]).catch("Anyone"),_g={Reject:"Reject",Mask:"Mask"},Wg=z.enum(["Reject","Mask"]).catch("Reject"),Kg={Player:"Player",Publisher:"Publisher",System:"System"},Qg=z.enum(["Player","Publisher","System"]).catch("Player"),Hg={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var $g=z.object({DisplayNameKey:z.string().nullish(),SortOrder:z.number().nullish(),IconPath:z.string().nullish(),JoinedByDefault:z.boolean().nullish()}).passthrough(),lu=z.object({Gate:Z.nullish(),Schedule:ge.nullish()}).passthrough(),uu=z.object({Gate:Z.nullish(),Limits:Ce.nullish(),MaxLength:z.number().nullish()}).passthrough(),cu=z.object({HotTailSize:z.number().nullish(),HistoryHours:z.number().nullish()}).passthrough(),Jg=z.object({Availability:Q.nullish(),Write:Q.nullish(),Retention:Q.nullish()}).passthrough(),Zg=z.object({ChannelID:z.string().nullish(),Identity:$g.nullish(),Type:au.nullish(),GroupSource:z.string().nullish(),Partitioning:Fg.nullish(),Capacity:z.number().nullish(),Availability:lu.nullish(),Write:uu.nullish(),Retention:cu.nullish(),Presets:Jg.nullish()}).passthrough(),Yg=z.object({IsEnabled:z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:jg.nullish(),Limits:Ce.nullish(),MaxLength:z.number().nullish(),HistoryHours:z.number().nullish(),MaxConversations:z.number().nullish()}).passthrough(),Xg=z.object({BlockedTerms:z.array(z.string()).nullish(),BlockedTermAction:Wg.nullish(),MaxIgnoreListSize:z.number().nullish(),ReportsEnabled:z.boolean().nullish(),ReportLimits:Ce.nullish()}).passthrough(),ey=z.object({MinIntervalSeconds:z.number().nullish(),MaxMessagesPerPoll:z.number().nullish(),MaxHistoryPageSize:z.number().nullish()}).passthrough(),ty=z.object({Availability:z.record(z.string(),lu).nullish(),Write:z.record(z.string(),uu).nullish(),Retention:z.record(z.string(),cu).nullish()}).passthrough(),pu=z.object({IsEnabled:z.boolean().nullish(),Channels:z.record(z.string(),Zg).nullish(),Direct:Yg.nullish(),Moderation:Xg.nullish(),Polling:ey.nullish(),Presets:ty.nullish()}).passthrough(),iy=z.object({LastReadAt:z.string().nullish(),LastReadMessageID:z.string().nullish(),Left:z.boolean().nullish()}).passthrough(),ou=z.object({LastAt:z.string().nullish(),DailyCount:z.number().nullish(),DailyResetUtc:z.string().nullish(),TotalCount:z.number().nullish(),LastTextHash:z.string().nullish()}).passthrough();z.object({MutedUntil:z.string().nullish(),MuteReason:z.string().nullish(),Ignored:z.array(z.string()).nullish(),Channels:z.record(z.string(),iy).nullish(),Limits:z.record(z.string(),ou).nullish(),ReportLimits:ou.nullish()}).passthrough();var xo=z.object({RoomID:z.string().nullish(),SentAt:z.string().nullish(),MessageID:z.string().nullish()}).passthrough(),Os=z.object({RoomID:z.string().nullish(),ChannelID:z.string().nullish(),MessageID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderProfile:qe.nullish(),AuthorType:Qg.nullish(),Text:z.string().nullish(),SentAt:z.string().nullish()}).passthrough(),sy=z.object({ChannelID:z.string().nullish(),RoomID:z.string().nullish(),DisplayNameKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),Type:au.nullish(),CanWrite:z.boolean().nullish(),WriteBlockedReason:z.string().nullish(),SlowModeSeconds:z.number().nullish(),MaxLength:z.number().nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),Es=z.object({Channels:z.array(sy).nullish(),PollIntervalSeconds:z.number().nullish(),MutedUntil:z.string().nullish(),MuteReason:z.string().nullish()}).passthrough(),ny=z.object({RoomID:z.string().nullish(),Messages:z.array(Os).nullish(),NextCursor:xo.nullish(),UnreadCount:z.number().nullish(),ServedFromDatabase:z.boolean().nullish()}).passthrough(),du=z.object({Rooms:z.array(ny).nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),hu=z.object({RoomID:z.string().nullish(),Messages:z.array(Os).nullish(),NextBefore:xo.nullish()}).passthrough(),mu=z.object({Message:Os.nullish(),Moderated:z.boolean().nullish()}).passthrough(),fu=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:qe.nullish(),MaxLength:z.number().nullish()}).passthrough(),ry=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:qe.nullish(),LastMessage:Os.nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),gu=z.object({Conversations:z.array(ry).nullish()}).passthrough(),mi=z.object({Ignored:z.array(z.string()).nullish(),Cursor:xo.nullish(),Joined:z.boolean().nullish()}).passthrough(),yu=z.object({ReportID:z.string().nullish(),AlreadyReported: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 Ru="Chat",Cu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Us=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Cu,{schema:Es,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(Ru,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ru,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(Cu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return c;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 c;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 s of i.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return i}async getHistory(e,t,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),i&&(s.Limit=i),this.ctx.api.chat.getHistory(s)):c}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return c;s.ChannelID=e,s.Text=t,i&&(s.Locale=i);let n=await this.ctx.api.chat.sendMessage(s);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.Text=t;let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):c}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):c}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(i);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):c}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):c}async reportMessage(e,t,i,s){let n=this.ctx.authedRequest();return n?(n.RoomID=e,n.MessageID=t,n.Reason=i,s&&(n.Comment=s),this.ctx.api.chat.reportMessage(n)):c}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):c}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):c}resetCursors(){this.cursors.clear();}};var oy={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},ay=z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),ly={Player:"player",Title:"title",Creator:"creator"},fi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Su=z.object({Configured:z.boolean().nullish(),PublicKey:z.string().nullish()}).passthrough(),uy=z.object({TitleID:z.string().nullish(),Topic:z.string().nullish()}).passthrough(),bo=z.object({EndpointHash:z.string().nullish(),Transport:ay.nullish(),Locale:z.string().nullish(),Topics:z.array(uy).nullish()}).passthrough(),xu=z.object({Configured:z.boolean().nullish(),Subscriptions:z.array(bo).nullish()}).passthrough(),Je={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var cy="IDOS_PLATFORM_PUSH_REQUEST",py="IDOS_PLATFORM_PUSH_RESPONSE",dy=12e4;function bu(o){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 s=false,n=h=>{s||(s=true,window.removeEventListener("message",r),clearTimeout(c),i(h));},r=h=>{let R=h?.data;!R||R.type!==py||R.requestId!==t||z$1.includes(h.origin)&&n(R.ok===true);},c=setTimeout(()=>n(false),dy);window.addEventListener("message",r);for(let h of z$1)try{e.postMessage({type:cy,requestId:t,titleID:o},h);}catch{}})}var hy="idos:push:deviceToken:",qs=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),s=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,i.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(this.ctx.host.supports.pushNotifications){if(!e.Configured)return Je.Unsupported;let n=await this.ctx.host.requestPushToken({prompt:false});return n.error==="BLOCKED"?Je.Blocked:n.token?this.ctx.host.storage.getString(this.deviceTokenKey())===n.token?Je.Subscribed:Je.Idle:n.error==="NOT_GRANTED"?Je.Idle:Je.Unsupported}if(!e.Configured||!e.PublicKey)return Je.Unsupported;if(this.isEmbedded())return Je.Embedded;if(!this.isSupported())return Je.Unsupported;let t=Notification.permission;return t==="denied"?Je.Blocked:t!=="granted"?Je.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?Je.Subscribed:Je.Idle}async subscribe(e={}){let t=await this.getConfig();if(this.ctx.host.supports.pushNotifications)return this.subscribeDevice(t,e);if(!t.Configured||!t.PublicKey)return b("client","Push notifications are not available for this title.");if(this.isEmbedded())return await bu(this.ctx.settings.titleID)?a$1({Where:"portal",Subscription:null}):b("client","The portal did not complete the subscription.");if(!this.isSupported())return b("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return b("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let r=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:my(t.PublicKey)}),c$1=this.ctx.authedRequest();if(!c$1)return c;let h=r.toJSON();c$1.PushEndpoint=h.endpoint,c$1.PushP256dh=h.keys?.p256dh,c$1.PushAuth=h.keys?.auth,c$1.PushTransport="WebPush",c$1.PushLocale=e.locale??navigator.language,c$1.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(c$1);return R.ok?(this.ctx.emitter.emit("push:subscribed",R.data),a$1({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return c;if(this.ctx.host.supports.pushNotifications){let i=this.ctx.host.storage.getString(this.deviceTokenKey());if(!i)return b("client","This device has no push subscription to remove.");e.PushDeviceToken=i;let s=await this.ctx.api.push.unsubscribePush(e);return s.ok&&(this.ctx.host.storage.remove(this.deviceTokenKey()),this.ctx.emitter.emit("push:unsubscribed",void 0)),s}if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return b("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):c}async unsubscribeByHash(e){if(!e)return b("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return c;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}async subscribeDevice(e,t){if(!e.Configured)return b("client","Push notifications are not available for this title.");let i=await this.ctx.host.requestPushToken({prompt:true});if(!i.token)return b("client",i.error==="BLOCKED"?"The player blocked notifications for this app.":"The device gave no push token.");let s=this.ctx.authedRequest();if(!s)return c;s.PushTransport=i.transport??"Fcm",s.PushDeviceToken=i.token,s.PushLocale=t.locale??(this.ctx.host.getLanguage()||void 0),s.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let n=await this.ctx.api.push.subscribePush(s);return n.ok?(this.ctx.host.storage.setString(this.deviceTokenKey(),i.token),this.ctx.emitter.emit("push:subscribed",n.data),a$1({Where:"game",Subscription:n.data})):n}deviceTokenKey(){return hy+this.ctx.settings.titleID}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function my(o){let e=o.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(o.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return i}var Bs=Object.freeze({}),Ls=class{constructor(e){this.ctx=e;}ctx;table={...Bs};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new hi(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),s=this.lookup(i)??this.lookup(e);return s===void 0?this.onMissing(e):t?fy(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Bs},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 c;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:r}=i.data,c$1=null;if(r){let h=await this.loadTableFromApi(r);h.ok&&(c$1=h.data.table);}return this.table=n,this.fallbackTable=c$1,this.currentFallbackLocale=r,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:r,entryCount:Object.keys(n).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):c}reset(){this.table={...Bs},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:a()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return c;t.Locale=e;let i=await this.cache.read(Du(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let n=s.data,r=n.Locale??Du(e),c$1=n.Version??0;if(n.NotModified){let R=i??await this.cache.read(r);return {ok:true,data:{locale:r,table:R?.t??{...Bs},fallbackLocale:n.FallbackLocale??null}}}let h=n.Entries??{};return c$1>0&&await this.cache.write(r,c$1,h),{ok:true,data:{locale:r,table:h,fallbackLocale:n.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 s=this.pluralCategory(i),n=`${e}.${s}`;if(this.lookup(n)!==void 0)return n;let r=`${e}.other`;return this.lookup(r)!==void 0?r: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 fy(o,e){return o.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function Du(o){return o.trim().replace(/_/g,"-").toLowerCase()}var Do="Quest",gy={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:o=>{let e=Date.now(),t=null,i=[...Object.values(o.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(o.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let n=Date.parse(s??"");!Number.isNaN(n)&&n>e&&(t===null||n<t)&&(t=n);}return t}},Gs=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let s=e.cache.configSection(Do)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let r of Object.keys(s)){let c=Date.parse(n[r]?.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(Do,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Do,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(gy,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return c;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let s=i.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","QuestID is required.");if(!this.ctx.auth.context)return c;let s=t&&t.trim().length>0?t.trim():void 0,n={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${a()}`},r=await this.ctx.api.quest.claimQuestReward(n);if(r.ok){let c=r.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 r}async claimQuestRewardsBatch(e){if(!e||e.length===0)return b("client","quests is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchQuestStatus(n.Data.QuestID,n.Data.CycleID,"Claimed"),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${a()}`},r=await this.ctx.api.quest.claimMilestoneReward(n);if(r.ok){let c=r.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 r}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchMilestoneClaimed(n.Data.CycleID,n.Data.MilestoneID),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${a()}`},r=await this.ctx.api.quest.claimGroupCompletionReward(n);if(r.ok){let c=r.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 r}async addQuestProgress(e,t){let i=e.trim();if(!i)return b("client","MetricID is required.");if(t<0)return b("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},n=await this.ctx.api.quest.addQuestProgress(s);return n.ok&&(this.ctx.data.user.patchQuestProgressUpdates(n.data.Updates),this.ctx.emitter.emit("quest:progressAdded",n.data)),n}};var Iu=z.object({}).passthrough().transform(o=>o);var yy=z.object({Order:z.number().nullish(),Type:z.string().nullish(),DurationSec:z.number().nullish(),BonusMultiplier:z.number().nullish()}).passthrough(),Ry=z.object({Schedule:z.array(yy).nullish(),RepeatCycle:z.boolean().nullish(),MaxCycles:z.number().nullish()}).passthrough(),Cy=z.object({IsActive:z.boolean().nullish(),CurrentPhaseEndUtc:p.nullish(),NextBonusStartUtc:p.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentPhaseIndex:z.number().nullish(),ActiveBonusMultiplier:z.number().nullish()}).passthrough(),Sy=z.object({Milestones:Q.nullish()}).passthrough(),Io=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Category:z.string().nullish(),Token:$t.nullish(),TokenSources:z.array(at).nullish(),ClaimMode:z.string().nullish(),Milestones:z.record(z.string(),Fe).nullish(),Presets:Sy.nullish(),BonusWindow:Ry.nullish()}).passthrough(),xy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Content:Io.nullish(),ClaimGraceHours:z.number().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),by=z.object({TimedEventID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:ge.nullish(),Content:Io.nullish(),Events:z.array(xy).nullish(),Gate:Z.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Dy=z.object({MaxConcurrentEvents:z.number().nullish()}).passthrough(),Iy=z.object({Milestones:z.record(z.string(),li).nullish()}).passthrough(),Vs=z.object({Definitions:z.record(z.string(),by).nullish(),Settings:Dy.nullish(),Presets:Iy.nullish()}).passthrough(),Py=z.object({Type:q,TimedEventID:z.string(),CurrentChainedEventID:z.string().nullish(),Content:Io.nullish(),Progress:Iu.nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),NextMilestone:Fe.nullish(),BonusWindow:Cy.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentEventOrder:z.number().nullish(),TotalEventsInChain:z.number().nullish(),TokenEntityID:z.string().nullish()}).passthrough(),Fs=z.object({ActiveEvents:z.array(Py).nullish()}).passthrough(),Pu=z.object({Tokens:z.record(z.string(),Iu).nullish()}),Po=z.object({Type:q.nullish(),LteID:z.string().nullish(),Resources:O.nullish()}),vo=z.object({Type:q.nullish(),LteID:z.string().nullish(),MilestoneID:z.string().nullish(),TokenEntityID:z.string().nullish(),Rewards:O.nullish(),Inventory:K.nullish()}),vy=z.object({Type:q.nullish(),LteID:z.string().nullish(),Resources:O.nullish()}),To=z.array(Te(vo)),vu=z.array(Te(Po)),Tu=z.array(Te(vy)),ct={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Au="TimedEvent",ku={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:o=>{let e=null;for(let t of o.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Ns=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ku,{schema:Fs,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(ku,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return c;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(Au,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Au,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return c;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,s,n,r,c$1=1){if(!t)return b("client","LteID is required.");if(!i)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c;let h={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:r,RollMultiplier:c$1},R=await this.ctx.api.timedEvent.grantTokens(h);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",R.data)),R}async spendTokens(e,t,i){if(!t)return b("client","LteID is required.");if(i<=0)return b("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},n=await this.ctx.api.timedEvent.spendTokens(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",n.data)),n}async claimMilestone(e,t,i){if(!t||!i)return b("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},n=await this.ctx.api.timedEvent.claimMilestone(s);if(n.ok){let r=n.data;this.ctx.data.user.applyResourcesWithDelta(r.Rewards,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,r.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",r);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c;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 c;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 b("client","spends is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return b("client","grants is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=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 s=i.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var Ty=z.object({UserID:z.string(),Score:W.nullish(),Rank:z.number().nullish(),LastScoreUpdateUtc:p.nullish(),IpHash:z.string().nullish(),PublicProfile:qe.nullish(),SeasonTierAtCycleEnd:z.number().nullish()}).passthrough(),Ai=z.object({LeaderboardID:z.string(),CycleVersion:z.number().nullish(),TotalParticipants:W.nullish(),CycleEndUtc:p.nullish(),TopUsers:z.array(Ty).nullish(),BracketID:z.string().nullish()}),Ay=z.object({CycleKey:z.string().nullish(),CycleEndUtc:p.nullish(),ClaimDeadlineUtc:p.nullish(),MilestoneTokensEarned:W.nullish(),ClaimableMilestoneIDs:z.array(z.string()).nullish(),CycleIndex:z.number().nullish(),ChainedEventID:z.string().nullish()}).passthrough(),js=z.object({LeaderboardID:z.string(),CurrentScore:W.nullish(),LastKnownRank:z.number().nullish(),HasUnclaimedReward:z.boolean().nullish(),UnclaimedRewardRank:z.number().nullish(),ScoreEarnedThisCycle:W.nullish(),MilestoneTokensEarned:W.nullish(),TokenEntityID:z.string().nullish(),NextMilestone:Fe.nullish(),HasUnclaimedMilestone:z.boolean().nullish(),GrantedPremiumTiers:z.record(z.string(),z.array(z.string())).nullish(),ClaimableGraceCycles:z.array(Ay).nullish()}),_s=z.object({LeaderboardID:z.string(),NewScore:W,CycleVersion:z.number()}),Ws=z.object({ServerTimeUtc:p,LeaderboardID:z.string(),Rank:z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Ks=z.object({ServerTimeUtc:p,LeaderboardID:z.string(),MilestoneID:z.string(),Resources:O.nullish(),Inventory:K.nullish()}),zu=z.array(Te(Ai)),Qs=z.array(Te(js)),wu=z.array(Te(Ws)),Mu=z.array(Te(Ks)),Ou=z.array(Te(_s)),ky=z.object({LeaderboardID:z.string(),CycleReward:Te(Ws).nullish(),Milestones:z.array(Te(Ks)).nullish()}),Eu=z.array(ky),zy=z.object({LeaderboardID:z.string(),Leaderboard:Te(Ai).nullish(),Progress:Te(js).nullish()}),Uu=z.array(zy),wy=z.string(),qu=z.object({Rank:z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:no.nullish()}).passthrough(),My=z.object({RankRewards:z.array(qu).nullish()}).passthrough(),Oy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Ey=z.object({Milestones:Q.nullish(),RankRewards:Q.nullish()}).passthrough(),Uy=z.object({LeaderboardID:z.string(),DisplayName:z.string().nullish(),ScoreDisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),IsEnabled:z.boolean().nullish(),ScoreAggregation:wy.nullish(),Schedule:ge.nullish(),ChainEvents:z.array(Oy).nullish(),Gate:Z.nullish(),TopUsersLimit:z.number().nullish(),MinScoreToEnterTop:z.number().nullish(),BracketSize:z.number().nullish(),LinkedSeasonChainID:z.string().nullish(),RankRewards:z.array(qu).nullish(),Milestones:z.record(z.string(),Fe).nullish(),Presets:Ey.nullish(),MilestoneClaimMode:z.string().nullish(),MilestoneClaimGraceHours:z.number().nullish(),ScoreSources:z.array(at).nullish()}).passthrough(),qy=z.object({Milestones:z.record(z.string(),li).nullish(),RankRewards:z.record(z.string(),My).nullish()}).passthrough(),Hs=z.object({Definitions:z.record(z.string(),Uy).nullish(),Presets:qy.nullish()}).passthrough(),_e={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 Bu="Leaderboard",Lu={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"]},$s=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Lu,{schema:Qs,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Bu,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Bu,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","LeaderboardID is required.");if(t<=0)return b("client","Score must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(i);if(s.ok){let n=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),n.NewScore,t,n.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",n);}return s}async submitScoreFromSource(e,t,i,s,n=1){if(!e)return b("client","LeaderboardID is required.");if(!t)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},c$1=await this.ctx.api.leaderboard.submitScoreFromSource(r);if(c$1.ok){let h=c$1.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),h.NewScore,h.NewScore,h.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",h);}return c$1}async claimCycleReward(e){if(!e)return b("client","LeaderboardID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return i}async claimMilestone(e,t,i){if(!e||!t)return b("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},n=await this.ctx.api.leaderboard.claimMilestone(s);if(n.ok){let r=n.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",r);}return n}async getFriendsLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c;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(b("client","leaderboardIDs is required.")):this.ctx.cache.read(Lu,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return b("client","scores is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let n=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(n),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let r of s.Milestones??[])!r.Success||!r.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(n,r.Data.MilestoneID),r.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.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 b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let s of i.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var Ao=z.object({}).passthrough().transform(o=>o),Js=z.object({SeasonChainID:z.string(),CycleIndex:z.number().nullish(),Season:z.lazy(()=>Nu).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:W.nullish(),UserState:Ao.nullish(),NextTier:z.lazy(()=>Fu).nullish()}).passthrough(),Gu=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),AmountGranted:W.nullish(),NewStatusTokens:W.nullish(),OldTier:z.number().nullish(),NewTier:z.number(),TierUp:z.boolean().nullish()}),ko=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),TierNumber:z.number(),Resources:O.nullish(),Inventory:K.nullish()}),Vu=St(ko);var Fu=z.object({Tier:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredTokens:W.nullish(),TierReachedReward:H.nullish()}).passthrough(),Nu=z.object({SeasonID:z.string().nullish(),Order:z.number().nullish(),DurationSec:W.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(Fu).nullish(),LinkedCollectionID:z.string().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough();var By=z.object({SeasonChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:ge.nullish(),Seasons:z.array(Nu).nullish(),GrantTokensAccessMode:z.string().nullish(),Gate:Z.nullish()}).passthrough(),Zs=z.object({Chains:z.record(z.string(),By).nullish()}).passthrough(),Gt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var ju="Season",_u={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:o=>{let e=Date.parse(o.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Ys=class{constructor(e){this.ctx=e;e.cache.bindLoginView(_u,{schema:Js,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ju,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ju,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(_u,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(b("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","SeasonChainID is required.");if(t<=0)return b("client","Amount must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${a()}`},s=await this.ctx.api.season.grantStatusTokens(i);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","TierNumber must be positive.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${a()}`},s=await this.ctx.api.season.claimTierReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",n);}return s}async claimTierRewardsBatch(e,t){if(!e)return b("client","SeasonChainID is required.");let i=(t??[]).filter(r=>r>0);if(i.length===0)return b("client","TierNumbers is required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${a()}`},n=await this.ctx.api.season.claimTierRewardsBatch(s);if(n.ok){let r=n.data;for(let c of r.Items??[]){let h=c.Data?.TierNumber;c.Success&&typeof h=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,h);}this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",r);}return n}};var Wu="Premium",Xs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Wu,e);if(t){let n={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",n),a$1(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(Wu,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(i);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,i="Default",s=1,n){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,CreditsConfirmationID:n,RelatedEntityID:`premium_purchase_${e}_${t}`},c$1=await this.ctx.api.premium.purchaseItemOrCurrency(r);if(c$1.ok&&!c$1.data.CreditsConfirmation){let h=c$1.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$1}async purchaseRealMoney(e,t,i,s,n,r,c$1,h){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!s||!n)return b("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return c;let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:r,PackageName:c$1,AppStoreEnvironment:h,RelatedEntityID:`premium_iap_${e}_${t}`},j=await this.ctx.api.premium.purchaseRealMoney(R);if(j.ok){let ce=j.data;ce.Premium&&this.ctx.data.user.applyPremium(ce.Premium),this.ctx.data.user.applyResourceOperation(ce.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",ce);}return j}};var en=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ItemInstanceID:z.string().nullish(),Level:z.number().nullish(),EquippedAt:p.nullish()}),zo=z.object({CharacterID:z.string(),Level:z.number().nullish(),Experience:W.nullish(),Power:z.number().nullish(),StatLevels:z.record(z.string(),z.number()).nullish(),Equipment:z.record(z.string(),en).nullish(),UpdatedAt:p.nullish()}).passthrough(),Ku=z.object({Characters:z.record(z.string(),zo).nullish()}),wo=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),StatID:z.string(),StatLevel:z.number(),Power:z.number().nullish(),Resources:O.nullish()}),Mo=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),NewLevel:z.number(),Power:z.number().nullish(),Resources:O.nullish()}),Qu=z.object({ServerTimeUtc:p,CharacterID:z.string(),Equipment:z.record(z.string(),en).nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),Hu=z.object({ServerTimeUtc:p,CharacterID:z.string(),ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),Ly=z.object({ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish()}),$u=z.object({ServerTimeUtc:p,Characters:z.record(z.string(),Ly).nullish(),Inventory:K.nullish()}),Oo=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),Power:z.number().nullish(),Resources:O.nullish()}),Ju=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,CharacterID:z.string(),SkinID:z.string(),Resources:O.nullish(),Inventory:K.nullish(),Equipped:z.boolean().nullish(),EquipError:z.string().nullish(),Equipment:en.nullish(),Power:z.number().nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish()}),Zu=z.object({ServerTimeUtc:p,CharacterID:z.string(),SkinID:z.string(),Equipped:en.nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),Yu=z.object({ServerTimeUtc:p,CharacterID:z.string(),Cleared:z.boolean().nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),Gy=z.object({SkinID:z.string(),IsDefault:z.boolean().nullish(),Misconfigured:z.string().nullish(),Owned:z.boolean().nullish(),OwnedCopies:z.number().nullish(),IsWorn:z.boolean().nullish(),MeetsRequirements:z.boolean().nullish(),SoldDirectly:z.boolean().nullish(),OnSale:z.boolean().nullish(),SaleEndsAtUtc:p.nullish(),GateOpen:z.boolean().nullish(),Purchasable:z.boolean().nullish(),PriceOptions:oe.nullish()}),Vy=z.object({CharacterID:z.string(),CharacterOpen:z.boolean().nullish(),DefaultSkinID:z.string().nullish(),WornSkinID:z.string().nullish(),Skins:z.array(Gy).nullish()}),Xu=z.object({ServerTimeUtc:p,Characters:z.record(z.string(),Vy).nullish()}),ec=St(Oo),tc=St(Mo),ic=St(wo),Eo=z.object({RequiredStatID:z.string(),RequiredLevel:z.number()}).passthrough(),sc=z.object({StatID:z.string(),TypeID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),MaxLevel:z.number().nullish(),Weight:z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:je.nullish(),BaseStatValue:z.number().nullish(),ValueCurve:je.nullish(),RankCurve:je.nullish(),Requirements:z.array(Eo).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Fy=z.object({SlotID:z.string(),MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Eo).nullish(),AllowedRarityIDs:z.array(z.string()).nullish(),AllowedItemTags:z.array(z.string()).nullish(),MinItemLevel:z.number().nullish(),MaxItemLevel:z.number().nullish()}).passthrough(),nc=z.object({Slots:z.record(z.string(),Fy).nullish()}).passthrough(),rc=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Lore:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Ny=z.object({ClassID:z.string().nullish(),RarityID:z.string().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),jy=z.object({UnlockedByDefault:z.boolean().nullish(),PriceOptions:oe.nullish()}).passthrough(),_y=z.object({Stats:Q.nullish(),Levels:Q.nullish(),Equipment:Q.nullish()}).passthrough(),oc=z.object({MaxRank:z.number().nullish(),FirstPaidRank:z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:je.nullish()}).passthrough(),Uo="@skin";function Wy(o){return !!o&&o.startsWith("@")}var Ky=z.object({CatalogID:z.string().nullish(),ItemID:z.string()}).passthrough(),Qy=z.object({PriceOptions:oe.nullish(),Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Hy=z.object({MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Eo).nullish()}).passthrough(),$y=z.object({SkinID:z.string().nullish(),Identity:rc.nullish(),Item:Ky.nullish(),Sale:Qy.nullish(),Requirements:Hy.nullish()}).passthrough(),Jy=z.object({DefaultSkinID:z.string().nullish(),Definitions:z.record(z.string(),$y).nullish()}).passthrough(),Zy=z.object({CharacterID:z.string(),Identity:rc.nullish(),Classification:Ny.nullish(),Unlock:jy.nullish(),Presets:_y.nullish(),Equipment:nc.nullish(),Stats:z.record(z.string(),sc).nullish(),RankLadder:oc.nullish(),RankStatCurve:je.nullish(),StatMaxLevelCurve:je.nullish(),Skins:Jy.nullish()}).passthrough(),Yy=z.object({Stats:z.record(z.string(),sc).nullish()}).passthrough(),Xy=z.object({RankLadder:oc.nullish()}).passthrough(),eR=z.object({Equipment:nc.nullish()}).passthrough(),tR=z.object({Stats:z.record(z.string(),Yy).nullish(),Levels:z.record(z.string(),Xy).nullish(),Equipment:z.record(z.string(),eR).nullish()}).passthrough(),tn=z.object({Definitions:z.record(z.string(),Zy).nullish(),Presets:tR.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"},iR="SKIN_ALREADY_OWNED";var qo="Character",sn=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(qo)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,n])=>n?.Unlock?.UnlockedByDefault===true&&!i[n.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(qo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(qo,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`unlock_char_${e}_${a()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok&&!s.data.CreditsConfirmation){let n=s.data;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.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",n);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return b("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${a()}`,SelectedOptionID:i?.selectedOptionID,CreditsConfirmationID:i?.creditsConfirmationID,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,c=>{c.StatLevels??={},c.StatLevels[r.StatID]=r.StatLevel,r.Power!=null&&(c.Power=r.Power),c.UpdatedAt=r.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",r);}return n}async upgradeCharacterLevel(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${a()}`,SelectedOptionID:t?.selectedOptionID,CreditsConfirmationID:t?.creditsConfirmationID,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok&&!s.data.CreditsConfirmation){let n=s.data;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.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",n);}return s}async equipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(i);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(i);if(s.ok){let n=s.data;this.applyUnequipChangesLocally(e,n),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:n.ClearedSlotIDs??[],power:n.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c;let s={...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}_${a()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),r.Equipped&&r.Equipment&&this.applySkinLocally(r.CharacterID,r.Equipment,r.Power,r.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",r);}return n}async equipSkin(e,t,i){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},n=await this.ctx.api.character.equipSkin(s);if(n.ok){let r=n.data;this.applyInventoryDelta(r.Inventory),this.applySkinLocally(r.CharacterID,r.Equipped??null,r.Power,r.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",r);}return n}async unequipSkin(e){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let s=i.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):c}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,Uo,t??null),n.patchCharacter(e,r=>{i!=null&&(r.Power=i),r.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return b("client","characterIDs is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level??=1,n.StatLevels??={},n.Equipment??={},s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level=s.NewLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(n.StatLevels??={},n.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.StatLevels??={},n.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.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[s,n]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,s,n);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let n of i)s.patchCharacterEquipment(e,n,null);s.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,s]of Object.entries(e.Characters??{})){for(let n of s.ClearedSlotIDs??[])t.patchCharacterEquipment(i,n,null);t.patchCharacter(i,n=>{s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=e.ServerTimeUtc;});}}};var ac="Match",nn=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,r){let c$1=this.ctx.auth.context;if(!c$1)return c;let h={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:r,RelatedEntityID:`pvp_create_${c$1.userID}_${a()}`},R=await this.ctx.api.match.createMatch(h);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",R.data)),R}async updateMatch(e,t={}){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(i);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c;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,s){let n=this.ctx.auth.context;if(!n)return c;let r={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${a()}`},c$1=await this.ctx.api.match.instantBattle(r);if(c$1.ok){let h=c$1.data,R=this.ctx.data.config.itemDefinitions;if(h.Resources)this.ctx.data.user.applyResourceOperation(h.Resources,R);else if(h.ResourcesDual){let j=h.ResourcesDual;j.FromUserID===n.userID&&j.FromResult?this.ctx.data.user.applyResourceOperation(j.FromResult,R):j.ToUserID===n.userID&&j.ToResult&&this.ctx.data.user.applyResourceOperation(j.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",h);}return c$1}async saveStrategy(e){if(!this.ctx.auth.context)return c;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 s=this.ctx.authedRequest();if(!s)return c;s.Page=e,s.PageSize=t,s.Statuses=i;let n=await this.ctx.api.match.getMyMatches(s);return n.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",n.data),n}async getAvailableMatches(e=0,t=20,i=false){let s=this.ctx.authedRequest();if(!s)return c;s.Page=e,s.PageSize=t,s.OnlyPublic=i;let n=await this.ctx.api.match.getAvailableMatches(s);return n.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",n.data),n}async getDefinitions(e){let t=this.ctx.cache.configSection(ac,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ac,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var lc="Craft",rn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(lc,e);if(t){let n={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),a$1(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(lc,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n,r){if(!e)return b("client","CraftID is required.");let c$1=this.ctx.auth.context;if(!c$1)return c;let h={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,CreditsConfirmationID:r,RelatedEntityID:`craft_${e}_${c$1.userID}_${a()}`},R=await this.ctx.api.craft.craft(h);return R.ok&&!R.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",R.data)),R}};var Vt=z.lazy(()=>z.union([z.string(),z.number(),z.boolean(),z.null(),z.array(Vt),z.record(z.string(),Vt)]));var Ft={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},uc=z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Zt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function ki(o){return o!==Zt.Pending&&o!==Zt.Running}var sR={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 nR(o){return o?/\b(AI_[A-Z_]+)\s*:/.exec(o)?.[1]??null:null}var rR=z.object({Url:z.string().nullish(),ContentType:z.string().nullish(),Variant:z.string().nullish()}),oR=z.object({Code:z.string().nullish(),Message:z.string().nullish()}),on=z.object({CreditsConfirmation:me.nullish(),GenerationID:z.string(),FeatureKey:z.string().nullish(),Modality:uc.nullish(),Status:z.string(),Progress:z.number().nullish(),OutputText:z.string().nullish(),OutputJson:z.record(z.string(),Vt).nullish(),Assets:z.array(rR).nullish(),Error:oR.nullish(),Charge:O.nullish(),PlayerRefunded:z.boolean().nullish(),Reused:z.boolean().nullish(),Reward:O.nullish(),Context:z.record(z.string(),Vt).nullish(),PaymentSettled:z.boolean().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish()}),cc=z.object({Data:z.array(on).nullish(),Skip:z.number().nullish(),Limit:z.number().nullish()}),aR=z.object({Name:z.string().nullish(),Type:z.string().nullish(),Required:z.boolean().nullish(),MaxLength:z.number().nullish(),Enum:z.array(z.string()).nullish()}).passthrough(),yt=z.record(z.string(),z.string()),lR=z.object({Key:z.string().nullish(),Role:z.string().nullish(),Required:z.boolean().nullish(),Label:yt.nullish()}).passthrough(),uR=z.object({Name:z.string().nullish(),Type:z.string().nullish(),Required:z.boolean().nullish(),MaxLength:z.number().nullish(),Default:z.string().nullish(),Multiline:z.boolean().nullish(),Label:yt.nullish(),Placeholder:yt.nullish(),Choices:z.array(z.object({Value:z.string().nullish(),Label:yt.nullish()}).passthrough()).nullish()}).passthrough(),pc=z.object({Key:z.string(),Kind:z.string().nullish(),Name:yt.nullish(),Hint:yt.nullish(),Unit:yt.nullish(),Choices:z.array(z.object({Value:z.string(),Name:yt.nullish(),Group:z.string().nullish()}).passthrough()).nullish(),Groups:z.array(z.object({Key:z.string(),Name:yt.nullish()}).passthrough()).nullish(),Default:z.string().nullish(),Min:z.number().nullish(),Max:z.number().nullish(),Step:z.number().nullish()}).passthrough(),dc=z.object({PriceOptions:oe.nullish()}).passthrough(),cR=z.object({Id:z.string().nullish(),Kind:z.string().nullish(),Action:z.string().nullish(),IsTrend:z.boolean().nullish(),Category:z.string().nullish(),Order:z.number().nullish(),Name:yt.nullish(),Description:yt.nullish(),Preview:z.object({Url:z.string().nullish(),PosterUrl:z.string().nullish(),Type:z.string().nullish()}).passthrough().nullish(),Inputs:z.array(lR).nullish(),Variables:z.array(uR).nullish(),Settings:z.array(pc).nullish()}).passthrough(),pR=z.object({Modality:uc.nullish(),Async:z.boolean().nullish(),Limits:Ce.nullish(),PriceOptions:oe.nullish(),Tags:z.array(z.string()).nullish(),HistoryMessages:z.number().nullish(),MaxTokens:z.number().nullish(),AllowImages:z.boolean().nullish(),MaxInputImages:z.number().nullish(),MaxInputImageBytes:z.number().nullish(),AllowedImageTypes:z.array(z.string()).nullish(),MaxImages:z.number().nullish(),AllowEdit:z.boolean().nullish(),AllowReferenceImage:z.boolean().nullish(),MaxPromptChars:z.number().nullish(),LockBehavior:z.boolean().nullish(),ImageSize:z.string().nullish(),VideoSize:z.string().nullish(),VideoSeconds:z.number().nullish(),Voice:z.string().nullish(),AudioFormat:z.string().nullish(),MusicFormat:z.string().nullish(),ThreeDOperation:z.string().nullish(),ThreeDAnimations:z.array(z.string()).nullish(),Reward:H.nullish(),PromptVariables:z.array(aR).nullish(),AllowFreePrompt:z.boolean().nullish(),PlatformTemplateId:z.string().nullish(),PlatformTemplate:cR.nullish(),Settings:z.array(pc).nullish(),FreePerDay:z.number().nullish(),FreeLeftToday:z.number().nullish()}).passthrough(),hc=z.object({Enabled:z.boolean().nullish(),Features:z.record(z.string(),pR).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",EstimateTemplatePrice:"EstimateTemplatePrice"};var mc="AI",dR=/^[A-Za-z0-9_-]{1,128}$/,hR=2e3,mR=5e3,fR=30*6e4;function gR(o,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,o);e?.addEventListener("abort",i,{once:true});})}var an=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(mc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(mc,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,i){return this.generate(e,{Text:t},i,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateFromTemplate(e,t,i){return this.generate(e,{TemplateInputs:t},i,s=>this.ctx.api.ai.generateFromTemplate(s))}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}):c:b("client","FeatureKey is required.")}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):c}async getGeneration(e){if(!e)return b("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):c}isTerminal(e){return ki(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 b("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??fR),n=Math.max(1,t.intervalMs??hR),r=Math.max(n,t.maxIntervalMs??mR);for(;!ki(i.Status);){if(t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");if(Date.now()+n>s)return b("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await gR(n,t.signal),t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");let c=await this.pollFor(i);if(n=Math.min(r,Math.round(n*1.5)),!c.ok){if(c.reason==="connection")continue;return c}i=c.data,ki(i.Status)||t.onUpdate?.(i);}return a$1(i)}pollFor(e){switch(e.Modality){case Ft.Text:return this.getText(e.GenerationID);case Ft.Image:return this.getImage(e.GenerationID);case Ft.Audio:return this.getAudio(e.GenerationID);case Ft.Music:return this.getMusic(e.GenerationID);case Ft.Video:return this.getVideo(e.GenerationID);case Ft.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,s){if(!e)return b("client","FeatureKey is required.");let n=i?.relatedEntityID;if(n!==void 0&&!dR.test(n))return b("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return c;let r={...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:n??a()},c$1=await s(r);return c$1.ok&&!c$1.data.CreditsConfirmation&&(await this.reconcileCharge(c$1.data,true),this.emitView(c$1.data)),c$1}async poll(e,t){if(!e)return b("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.GenerationID=e;let s=await t(i);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Zt.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===Zt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Zt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Bo="Collection",ln=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(Bo),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let n=e.cache.configSection("Season");return Object.values(n?.Chains??{}).some(c=>(c?.Seasons??[]).some(h=>!!h?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Bo,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Bo,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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,s){let n=this.ctx.auth.context;if(!n)return c;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${a()}`},c$1=await this.ctx.api.collection.openPack(r);return c$1.ok&&!c$1.data.CreditsConfirmation&&(this.ctx.data.user.applyResourcesWithDelta(c$1.data.Resources,c$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",c$1.data)),c$1}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return c;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${a()}`},r=await this.ctx.api.collection.openCollectionChest(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:chestOpened",r.data)),r}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${a()}`},n=await this.ctx.api.collection.useCollectibleJoker(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",n.data)),n}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${a()}`},n=await this.ctx.api.collection.claimSetReward(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",n.data)),n}async claimSetRewardsBatch(e){if(!e||e.length===0)return b("client","sets is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${a()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,n,r=false){let c$1=this.ctx.auth.context;if(!c$1)return c;let h={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:r,RelatedEntityID:`trade_send_${c$1.userID}_${s}_${a()}`},R=await this.ctx.api.collection.sendTradeOffer(h);return R.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",R.data)),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${a()}`},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 c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${a()}`},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 c;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${a()}`},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 c;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 c;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 yR=z.object({}).passthrough().transform(o=>o),RR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},CR={Active:"Active",Left:"Left",Replaced:"Replaced"},SR=z.object({ObjectIndex:z.number().nullish(),ObjectCompletionRewardClaimed:z.boolean().nullish()}).passthrough(),xR=z.object({UserID:z.string().nullish(),PublicData:qe.nullish(),BuildObjectsProgress:SR.nullish(),IsBot:z.boolean().nullish(),SpinsCount:z.number().nullish(),TokensSpent:z.number().nullish(),MemberStatus:z.string().nullish(),GrandPrizeClaimed:z.boolean().nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),bR=z.object({Index:z.number().nullish(),OwnerUserID:z.string().nullish(),CurrentProgress:z.number().nullish(),MaxProgress:z.number().nullish(),IsCompleted:z.boolean().nullish()}).passthrough(),DR=z.object({Objects:z.array(bR).nullish()}).passthrough(),fc=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),CoopChainID:z.string().nullish(),CoopEventID:z.string().nullish(),CycleIndex:z.number().nullish(),Members:z.array(xR).nullish(),BuildObjectsState:DR.nullish(),Status:z.string().nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:z.number().nullish()}).passthrough(),gc=z.object({CoopChainID:z.string(),CycleIndex:z.number().nullish(),EventOrder:z.number().nullish(),EventDef:z.lazy(()=>yc).nullish(),ComputedStartUtc:p.nullish(),ComputedEndUtc:p.nullish(),SecondsRemaining:z.number().nullish()}).passthrough(),IR=z.string(),Lo=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Weight:z.number().nullish(),MinProgress:z.number().nullish(),MaxProgress:z.number().nullish()}).passthrough(),PR=z.object({Index:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxProgress:z.number().nullish(),CompletionReward:H.nullish()}).passthrough(),vR=z.object({Objects:z.array(PR).nullish(),PriceOptions:oe.nullish(),SpinnerTable:z.array(Lo).nullish(),MaxSpinsPerCall:z.number().nullish()}).passthrough(),yc=z.object({CoopEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),EventType:IR.nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),BuildObjects:vR.nullish(),GrandPrize:H.nullish()}).passthrough(),TR=z.object({CoopChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:ge.nullish(),Events:z.array(yc).nullish(),Gate:Z.nullish()}).passthrough(),un=z.object({ServerTimeUtc:p.nullish(),UserState:yR.nullish(),ActiveGroup:fc.nullish()}),Go=z.object({ServerTimeUtc:p.nullish(),Group:fc.nullish(),SecondsRemaining:W.nullish()}),Rc=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),Resources:O.nullish(),ObjectIndex:z.number().nullish(),Sector:Lo.nullish(),RequestedSpins:z.number().nullish(),SpinsUsed:z.number().nullish(),Sectors:z.array(Lo).nullish(),ProgressDelta:z.number().nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),ObjectCompleted:z.boolean().nullish(),AllObjectsCompleted:z.boolean().nullish()}),Vo=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Cc=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),cn=z.object({Chains:z.record(z.string(),TR).nullish()}).passthrough(),Rt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Sc="CoopEvent",xc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},pn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(xc,{schema:un,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Sc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Sc,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return b("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return c;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(xc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","CoopChainID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let s=i.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,s,n){if(!e||!t)return b("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,CreditsConfirmationID:n,RelatedEntityID:a()},c$1=await this.ctx.api.coopEvent.spin(r);return c$1.ok&&!c$1.data.CreditsConfirmation&&(this.ctx.data.user.applyResourceOperation(c$1.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",c$1.data)),c$1}async claimObjectReward(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c;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 b("client","GroupID is required.");if(!this.ctx.auth.context)return c;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 c;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 AR={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},kR={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},zR=z.object({NodeID:z.string().nullish(),Status:z.string().nullish(),ExecutionCount:z.number().nullish(),UnlockedAtUtc:p.nullish(),CompletedAtUtc:p.nullish(),LastExecutedAtUtc:p.nullish(),NextAvailableAtUtc:p.nullish(),LastExecutionRefID:z.string().nullish()}).passthrough(),wR=z.object({TrackID:z.string().nullish(),CurrentValue:z.number().nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),bc=z.object({OfferID:z.string().nullish(),InstanceKey:z.string().nullish(),SourceOfferVersion:z.number().nullish(),Status:z.string().nullish(),ActivatedAtUtc:p.nullish(),ExhaustedAtUtc:p.nullish(),ExpiredAtUtc:p.nullish(),DismissedAtUtc:p.nullish(),ShowCount:z.number().nullish(),LastShownAtUtc:p.nullish(),Nodes:z.record(z.string(),zR).nullish(),Tracks:z.record(z.string(),wR).nullish(),SelectedChoiceNodeID:z.string().nullish()}).passthrough(),MR=z.object({SlotID:z.string().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),ActiveOfferID:z.string().nullish(),ActiveOfferStartedAtUtc:p.nullish(),ActiveOfferExpiresAtUtc:p.nullish(),ActiveOffer:bc.nullish(),NextCycleStartsAtUtc:p.nullish(),LastUpdatedUtc:p.nullish(),DismissSkipAvailableAtUtc:p.nullish(),LastDismissedAtUtc:p.nullish(),ActiveScheduleInstanceKey:z.string().nullish()}).passthrough(),OR=z.object({TotalExecutions:z.number().nullish(),DailyExecutions:z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),ER=z.object({TotalActivations:z.number().nullish(),TotalExhausted:z.number().nullish(),TotalExpired:z.number().nullish(),TotalDismissed:z.number().nullish(),TotalShows:z.number().nullish(),LastShownAtUtc:p.nullish(),LastActivatedAtUtc:p.nullish(),LastExhaustedAtUtc:p.nullish(),NodeCounts:z.record(z.string(),OR).nullish()}).passthrough(),UR=z.object({Slots:z.record(z.string(),MR).nullish(),OfferHistory:z.record(z.string(),ER).nullish(),LastUpdatedUtc:p.nullish()}).passthrough(),qR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},BR={Eq:"Eq",Gte:"Gte",Lte:"Lte"},LR=z.object({Order:z.number().nullish(),OfferID:z.string().nullish(),DurationSec:z.number().nullish(),DelayBeforeActivationSec:z.number().nullish()}).passthrough(),dn=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Dc=z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Ic=z.object({AllowDismissSkip:z.boolean().nullish(),DismissSkipDelaySec:z.number().nullish()}).passthrough(),GR=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Behaviour:Q.nullish()}).passthrough(),VR=z.object({SlotID:z.string().nullish(),Enabled:z.boolean().nullish(),Identity:dn.nullish(),Availability:Dc.nullish(),Behaviour:Ic.nullish(),Queue:z.array(LR).nullish(),Presets:GR.nullish()}).passthrough(),FR=z.object({ViewsRequiredToComplete:z.number().nullish(),MaxViewsPerActivation:z.number().nullish(),GrantRewardsPerView:z.boolean().nullish()}).passthrough(),NR=z.object({RewardedVideo:FR.nullish()}).passthrough(),jR=z.object({TrackID:z.string().nullish(),Operator:z.string().nullish(),Value:z.number().nullish()}).passthrough(),_R=z.object({Identity:Q.nullish(),Graph:Q.nullish(),Milestones:Q.nullish()}).passthrough(),WR=z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish()}).passthrough(),KR=z.object({TrackID:z.string().nullish(),Amount:z.number().nullish(),RespectBounds:z.boolean().nullish()}).passthrough(),QR=z.object({TrackID:z.string().nullish(),DisplayName:z.string().nullish(),StartValue:z.number().nullish(),MinValue:z.number().nullish(),MaxValue:z.number().nullish(),ClampToMin:z.boolean().nullish(),ClampToMax:z.boolean().nullish(),HiddenFromUI:z.boolean().nullish()}).passthrough(),HR=z.object({RequiredCompletedNodeIDs:z.array(z.string()).nullish(),RequiredAnyCompletedNodeIDs:z.array(z.string()).nullish(),RequiredTracks:z.array(jR).nullish(),VisibleWhileLocked:z.boolean().nullish()}).passthrough(),Pc=z.object({Options:oe.nullish()}).passthrough(),vc=z.object({Grants:H.nullish(),TrackChanges:z.array(KR).nullish(),MilestonePoints:z.number().nullish()}).passthrough(),$R=z.object({NodeID:z.string().nullish(),Type:z.string().nullish(),Identity:dn.nullish(),Pricing:Pc.nullish(),Reward:vc.nullish(),Action:NR.nullish(),UnlockRules:HR.nullish(),NextNodeIDs:z.array(z.string()).nullish(),ChoiceGroupID:z.string().nullish(),Limits:Ce.nullish(),HideWhenCompleted:z.boolean().nullish(),ExhaustOfferOnComplete:z.boolean().nullish(),Presets:WR.nullish()}).passthrough(),Tc=z.object({RootNodeIDs:z.array(z.string()).nullish(),Nodes:z.array($R).nullish(),Tracks:z.array(QR).nullish(),ExhaustedWhenAllTerminalNodesCompleted:z.boolean().nullish()}).passthrough(),Ac=z.object({Milestones:z.record(z.string(),Fe).nullish(),ClaimMode:z.string().nullish(),Token:$t.nullish()}).passthrough(),kc=z.object({OfferID:z.string().nullish(),Version:z.number().nullish(),Enabled:z.boolean().nullish(),Identity:dn.nullish(),Graph:Tc.nullish(),Milestones:Ac.nullish(),Presets:_R.nullish()}).passthrough(),JR=z.object({Identity:z.record(z.string(),dn).nullish(),Availability:z.record(z.string(),Dc).nullish(),Behaviour:z.record(z.string(),Ic).nullish(),Graph:z.record(z.string(),Tc).nullish(),Milestones:z.record(z.string(),Ac).nullish(),Pricing:z.record(z.string(),Pc).nullish(),Reward:z.record(z.string(),vc).nullish()}).passthrough(),Fo=z.object({Slots:z.record(z.string(),VR).nullish(),Offers:z.record(z.string(),kc).nullish(),Presets:JR.nullish()}).passthrough(),zc=z.object({DealOfferDefinitions:Fo.nullish()}),wc=z.object({DealOffers:UR.nullish()}),ZR=z.object({EntityID:z.string().nullish(),TotalEarned:z.number().nullish(),ClaimedIDs:z.array(z.string()).nullish(),ReachedUnclaimedIDs:z.array(z.string()).nullish()}).passthrough(),YR=z.object({SlotID:z.string().nullish(),SortOrder:z.number().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),OfferDef:kc.nullish(),ActivationState:bc.nullish(),IsNewActivation:z.boolean().nullish(),ComputedExpiresAtUtc:p.nullish(),Cost:Tt.nullish(),Milestone:ZR.nullish(),ScheduleInstanceKey:z.string().nullish()}).passthrough(),hn=z.object({Slots:z.array(YR).nullish()}),Mc=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),NodeID:z.string().nullish(),NodeCompleted:z.boolean().nullish(),OfferExhausted:z.boolean().nullish(),Idempotent:z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Oc=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),Resources:O.nullish()}),Ec=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),Resources:O.nullish()}),Uc=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),qc=z.object({ServerTimeUtc:p.nullish(),SlotID:z.string().nullish(),ClaimedIDs:z.array(z.string()).nullish(),Rejected:z.record(z.string(),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 XR="DealOffer",Bc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},mn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Bc,{schema:hn,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(XR,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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(Bc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${a()}`},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,s){if(!e||!t)return b("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return c;let n=i&&i.trim().length>0?i.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,CreditsConfirmationID:s?.creditsConfirmationID,RelatedEntityID:n??`deal_exec_${e}_${t}_${a()}`},c$1=await this.ctx.api.dealOffer.executeNode(r);return c$1.ok&&!c$1.data.CreditsConfirmation&&(c$1.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(c$1.data.Resources,c$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",c$1.data)),c$1}async recordShow(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${a()}`},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 b("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${a()}`},s=await this.ctx.api.dealOffer.claimMilestone(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c;let i=[...new Set(t.map(r=>r.trim()).filter(r=>r.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${a()}`},n=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",n.data)),n}};var Lc="Referral",fn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Lc,e);if(t){let n={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",n),a$1(n)}let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Lc,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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=Ht.parseReferralCode(e)?.toUpperCase();if(!t)return b("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},n=await this.ctx.api.referral.activateReferralCode(s);if(n.ok){let r=n.data;r.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(r.ReferrerUserID,r.QualificationPending),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",r);}return n}async claimInviteReward(e){let t=e.trim();if(!t)return b("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},n=await this.ctx.api.referral.claimInviteReward(s);if(n.ok){let r=n.data;r.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(r.RewardID),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",r);}return n}async claimInviteRewardsBatch(e){let t=(e??[]).map(r=>r?.trim()).filter(Boolean);if(t.length===0)return b("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},n=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(n.ok){let r=n.data;for(let c of r.Items??[])c.Success&&c.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(c.Id);this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",r);}return n}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return c;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 eC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Gc=z.enum(["System","Reward","Gift","Social"]).catch("System"),tC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},iC=z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),sC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},nC=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"},rC={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"},oC=100,aC=z.object({Subject:z.string().nullish(),Body:z.string().nullish()}).passthrough(),Vc=z.object({FeatureID:z.string().nullish(),Args:z.record(z.string(),z.string()).nullish(),Url:z.string().nullish(),Label:z.string().nullish()}).passthrough(),lC=z.object({Texts:z.record(z.string(),aC).nullish(),Category:Gc.nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Vc.nullish(),SenderName:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),uC=z.object({Enabled:z.boolean().nullish(),Grant:ue.nullish(),Cost:ue.nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:p.nullish(),SenderGate:Z.nullish(),TemplateID:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),cC=z.object({Type:z.string().nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxAmountPerGift:z.number().nullish()}).passthrough(),pC=z.object({Enabled:z.boolean().nullish(),AllowedResources:z.array(cC).nullish(),MaxEntriesPerGift:z.number().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:p.nullish(),FeePercent:z.number().nullish(),FeeCost:ue.nullish(),SenderGate:Z.nullish(),ExpirationDays:z.number().nullish(),TemplateID:z.string().nullish()}).passthrough(),Fc=z.object({Enabled:z.boolean().nullish(),Capacity:z.number().nullish(),RewardLetterDays:z.number().nullish(),PlainLetterDays:z.number().nullish(),ClaimedRetentionDays:z.number().nullish(),DefaultLanguage:z.string().nullish(),Templates:z.record(z.string(),lC).nullish(),Gifts:z.object({Social:z.record(z.string(),uC).nullish(),Transfer:pC.nullish()}).passthrough().nullish(),Integrations:z.object({Leaderboard:z.boolean().nullish(),CoopEvent:z.boolean().nullish(),Season:z.boolean().nullish(),Referral:z.boolean().nullish()}).passthrough().nullish()}).passthrough(),dC=z.object({MessageID:z.string(),Source:iC,Category:Gc,TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Vc.nullish(),SenderName:z.string().nullish(),SenderUserID:z.string().nullish(),SenderAvatarUrl:z.string().nullish(),SenderNote:z.string().nullish(),Rewards:H.nullish(),HasRewards:z.boolean().nullish(),IsTransfer:z.boolean().nullish(),SentAt:p,ExpiresAt:p.nullish(),ReadAt:p.nullish(),ClaimedAt:p.nullish()}).passthrough(),hC=z.object({MessageID:z.string(),Module:nC,Key:z.string(),TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish()}).passthrough(),No=z.object({ID:z.string(),Error:z.string().nullish()}).passthrough(),Nc=z.object({ServerTimeUtc:p.nullish(),Messages:z.array(dC).default([]),NextCursor:z.string().nullish(),PendingRewards:z.array(hC).nullish(),UnreadCount:z.number().nullish(),UnclaimedCount:z.number().nullish(),DeliveredNow:z.number().nullish()}).passthrough(),gn=z.object({ServerTimeUtc:p.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),jo=z.object({ServerTimeUtc:p.nullish(),AffectedCount:z.number().default(0),Failed:z.array(No).default([]),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),mC=z.object({MessageID:z.string(),Rewards:ue.nullish()}).passthrough(),yn=z.object({ServerTimeUtc:p.nullish(),Claimed:z.array(mC).default([]),Failed:z.array(No).default([]),Resources:O.nullish(),Inventory:K.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),jc=z.object({ServerTimeUtc:p.nullish(),GiftID:z.string().nullish(),Sent:z.array(z.string()).default([]),Failed:z.array(No).default([]),Resources:O.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:p.nullish()}).passthrough(),_c=z.object({ServerTimeUtc:p.nullish(),MessageID:z.string().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish(),RecipientReceives:ue.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:p.nullish(),IdempotentReplay:z.boolean().nullish()}).passthrough(),Wc=z.object({ServerTimeUtc:p.nullish(),ResetsAt:p.nullish(),Social:z.record(z.string(),z.object({IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ReceivedInPeriod:z.number().default(0),SentTo:z.array(z.string()).default([]),ResetsAt:p.nullish()}).passthrough()).default({}),Transfer:z.object({Enabled:z.boolean().default(false),IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ResetsAt:p.nullish()}).passthrough().nullish()}).passthrough();var _o="Mailbox",Wo={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},Rn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Wo,{schema:gn,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(Wo,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(_o)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(_o,e);if(t)return a$1(t);let i=this.request();if(!i)return c;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(_o,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return c;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(Wo,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return c;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 c;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 b("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):c}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return b("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):c}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):c}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 c;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return b("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return b("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return c;let n=await this.ctx.api.mailbox.sendGift(s);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",n.data)),n}async sendTransfer(e,t,i){if(!e?.trim())return b("client","RecipientUserID is required.");if(!i?.requestID?.trim())return b("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return c;let n=await this.ctx.api.mailbox.sendTransfer(s);return n.ok&&(n.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(n.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",n.data)),n}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):c}};var Cn={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},Ko="idos-app",Kc=z.object({ServerTimeUtc:z.string().nullish(),Allowed:z.boolean(),DenyReason:z.string().nullish(),Message:z.string().nullish(),RetryAfterSeconds:z.number().nullish(),RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),AdUnitID:z.string().nullish(),Type:z.string().nullish(),ExpiresAtUtc:z.string().nullish(),CreditsToAward:z.number().nullish(),RequiresServerSideVerification:z.boolean().nullish()}),Qc=z.object({ServerTimeUtc:z.string().nullish(),RequestID:z.string().nullish(),Status:z.string(),CreditsAwarded:z.number().nullish(),RetryAfterSeconds:z.number().nullish(),ExpiresAtUtc:z.string().nullish(),AlreadyProcessed:z.boolean().nullish(),GrantedWithoutSsv:z.boolean().nullish(),Resources:O.nullish()});var fC=new Set(["CANCELLED","DECLINED","CLOSED"]),gC=45e3,yC=o=>new Promise(e=>setTimeout(e,o)),Sn=class{constructor(e){this.ctx=e;}ctx;get available(){return this.ctx.host.supports.rewardedAds}async showRewarded(e){if(!this.ctx.host.supports.rewardedAds)return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let i=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!i.ok)return {status:"unavailable",reason:i.error};let s=i.data;if(!s.Allowed)return {status:"denied",reason:s.DenyReason??void 0,retryAfterSeconds:s.RetryAfterSeconds??void 0};if(!s.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let n=null;if(s.ProviderID!==Ko&&(n=this.titleProvider(s.ProviderID),!n))return {status:"unavailable",reason:"NO_WEB_ADS"};let r=await this.ctx.host.showRewardedAd({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:s.RequestID,placementID:e,adUnitID:s.AdUnitID,provider:n});return r.ok?{...await this.awaitReward(s.RequestID,r.via),requestID:s.RequestID}:{status:fC.has(r.error??"")?"cancelled":"unavailable",reason:r.error}}titleProvider(e){if(!this.ctx.host.supports.titleAds||!e)return null;let i=this.ctx.data.config.getSection("Advertising")?.Providers?.[e];if(!i||i.Enabled===false)return null;let s=this.ctx.host.getClientPlatform(),n=s===j.Android?i.AndroidAppID:s===j.Ios?i.IosAppID:i.WebAppID;return n?{id:e,kind:i.Kind??"AppLovinMax",appKey:n}:null}async awaitReward(e,t){let i=Date.now()+gC;for(;;){let s=this.ctx.authedRequest();if(!s)return {status:"pending",via:t};let n=await this.ctx.api.advertising.completeView({...s,RequestID:e});if(n.ok&&n.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:n.data.CreditsAwarded??0,via:t};let r=Math.min(Math.max((n.ok?n.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+r>i)return {status:"pending",via:t,reason:n.ok?void 0:n.error};await yC(r);}}};var RC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},CC={Title:"Title",Platform:"Platform"},Hc=z.object({UserID:z.string(),PublicData:qe.nullish(),Source:z.enum(["Title","Platform"]).nullish()}),zi=z.object({Friends:z.array(Hc).nullish()}),SC=z.object({FriendsCount:z.number().nullish(),IncomingRequestsCount:z.number().nullish(),OutgoingRequestsCount:z.number().nullish()}),wi=z.object({TargetUserID:z.string().nullish(),Status:z.string().nullish(),Target:Hc.nullish(),Counters:SC.nullish()}),xC={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},bC={Like:"Like",Favorite:"Favorite"},DC={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},IC={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},PC={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},vC=z.object({Key:z.string().nullish(),DisplayName:z.string().nullish(),AvatarUrl:z.string().nullish()}).passthrough(),TC=z.object({Id:z.string(),Verb:z.string().nullish(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),Count:z.number().nullish(),LastActors:z.array(vC).nullish(),Payload:z.object({Title:z.string().nullish(),Excerpt:z.string().nullish(),ImageUrl:z.string().nullish()}).passthrough().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),OccurredAt:p.nullish(),OwnerImpact:O.nullish(),IsBlocked:z.boolean().nullish(),TargetObjectName:z.string().nullish()}).passthrough(),$c=z.object({Items:z.array(TC).nullish(),HasMore:z.boolean().nullish(),NextBeforeUpdatedAt:z.string().nullish(),NextBeforeID:z.string().nullish(),UnreadCount:z.number().nullish(),SeenAt:p.nullish()}).passthrough(),Mi=z.object({UnreadCount:z.number().nullish(),SeenAt:p.nullish()}).passthrough(),AC=z.object({Likes:z.number().nullish(),Favorites:z.number().nullish(),Followers:z.number().nullish(),Following:z.number().nullish(),Comments:z.number().nullish(),Replies:z.number().nullish(),Posts:z.number().nullish(),Dislikes:z.number().nullish()}).passthrough(),Nt=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Counts:AC.nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish(),Following:z.boolean().nullish(),Blocked:z.boolean().nullish()}).passthrough(),Jc=z.object({Items:z.array(Nt).nullish()}).passthrough(),Qo={HasMore:z.boolean().nullish(),NextCursorAt:z.string().nullish(),NextCursorID:z.string().nullish()},kC=z.object({UserID:z.string(),PublicData:qe.nullish(),Mutual:z.boolean().nullish(),Since:p.nullish()}).passthrough(),xn=z.object({Items:z.array(kC).nullish(),...Qo}).passthrough(),zC=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Kind:z.string().nullish(),At:p.nullish()}).passthrough(),Zc=z.object({Items:z.array(zC).nullish(),...Qo}).passthrough(),bn=z.object({CommentID:z.string(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),ParentCommentID:z.string().nullish(),AuthorUserID:z.string().nullish(),AuthorPublicData:qe.nullish(),Text:z.string().nullish(),Status:z.string().nullish(),Pinned:z.boolean().nullish(),CreatedAt:p.nullish(),EditedAt:p.nullish(),Likes:z.number().nullish(),Replies:z.number().nullish(),Liked:z.boolean().nullish(),IsMine:z.boolean().nullish()}).passthrough(),Yc=z.object({Items:z.array(bn).nullish(),...Qo,TotalCount:z.number().nullish()}).passthrough(),Xc=z.object({CommentID:z.string().nullish(),Deleted:z.boolean().nullish()}).passthrough(),ep=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish(),AutoHidden:z.boolean().nullish()}).passthrough(),tp=z.object({CommentsEnabled:z.boolean().nullish(),CommentableTypes:z.array(z.string()).nullish(),CommentMaxLength:z.number().nullish(),CommentMaxLinks:z.number().nullish()}).passthrough(),wC="FRIENDS_FROM_PLATFORM",MC={Off:"Off",Default:"Default",Always:"Always"},OC={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},ip=z.object({Profile:z.enum(["Off","Default","Always"]).nullish(),Friends:z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:z.boolean().nullish()}).passthrough(),Se={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 Ho={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Dn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ho,{schema:Mi,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 c;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 c;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 b("client","TargetUserID is required.");if(!this.ctx.auth.context)return c;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 b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c;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 b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c;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 b("client","FriendUserID is required.");if(!this.ctx.auth.context)return c;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 c;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(Ho,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return c;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 c;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(Ho,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)):c}async getEntityStates(e,t){if(!t?.length)return b("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):c}async addComment(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i?.trim())return b("client","Text is required.");n.Text=i,n.ParentCommentID=s;let r=await this.ctx.api.social.addComment(n);return r.ok&&this.ctx.emitter.emit("social:commentAdded",r.data),r}async editComment(e,t){if(!e)return b("client","CommentID is required.");if(!t?.trim())return b("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return c;i.CommentID=e,i.Text=t;let s=await this.ctx.api.social.editComment(i);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return b("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=i.parentCommentID,this.applyPage(s,i.cursor,i.limit),this.ctx.api.social.getComments(s))}async report(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i)return b("client","ReportReason is required.");n.ReportReason=i,n.ReportComment=s;let r=await this.ctx.api.social.report(n);return r.ok&&this.ctx.emitter.emit("social:reported",r.data),r}async mutate(e,t,i,s){let n=this.targetRequest(t,i);if("ok"in n)return n;n.ReactionKind=s;let r=await this.ctx.api.social[e](n);return r.ok&&this.ctx.emitter.emit("social:entityStateChanged",r.data),r}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):c}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 b("client","EntityType is required.");if(!t)return b("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):c}};var sp="TimedBoost";function EC(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var In=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(sp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),a$1(t);let i=this.ctx.authedRequest();if(!i)return c;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(sp,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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(!EC(i))return b("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,CreditsConfirmationID:t?.creditsConfirmationID,RelatedEntityID:`timed_boost_activate_${i}_${a()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok&&!n.data.CreditsConfirmation){let r=n.data;if(r.ActivatedBoost){let c=r.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(r.ActivatedBoost,c);}this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",r);}return n}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return c;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 Mt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},UC={Client:"Client",Server:"Server",System:"System"},qC=z.enum(["Client","Server","System"]).catch("Client"),BC=z.object({Value:z.string().nullish(),UpdatedAt:p.nullish(),Version:z.number().nullish(),LastWriter:qC.nullish(),ExpiresAt:p.nullish()}).passthrough(),Pn=z.record(z.string(),BC),np=z.object({Version:z.number().nullish(),Private:Pn.nullish(),Public:Pn.nullish(),ReadOnly:Pn.nullish()}),$o=z.object({UserID:z.string().nullish(),Version:z.number().nullish(),Public:Pn.nullish()}),Jo=z.object({ServerTimeUtc:p.nullish(),Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:p.nullish()}),LC=z.object({Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:p.nullish()}),rp=z.object({ServerTimeUtc:p.nullish(),Results:z.array(LC).nullish()}),op=z.object({ServerTimeUtc:p.nullish(),DeletedCount:z.number().nullish()}),ap=z.object({Results:z.array($o).nullish(),NotFoundUserIDs:z.array(z.string()).nullish()}),GC={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},VC=z.enum(["String","Int","Bool","Json"]).catch("String"),FC=z.object({KeyID:z.string(),Bucket:z.string().nullish(),ValueType:VC.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),vn=z.object({Keys:z.record(z.string(),FC).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),Ct={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var NC="UserCustomData";function lp(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Tn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(NC,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,Mt.Private)}async setPublicData(e,t){return this.setData(e,t,Mt.Public)}async setData(e,t,i){let s=e.trim();if(!lp(s))return b("client",'KeyID is required and must not contain "." or "$".');if(t==null)return b("client","Value is required.");if(!this.ctx.auth.context)return c;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},c$1=await(i===Mt.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(c$1.ok){let h=c$1.data;this.ctx.data.user.patchUserCustomDataKey(i,h.KeyID,t,h.Version??0,h.ExpiresAt),this.ctx.emitter.emit(i===Mt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",h);}return c$1}async deleteKey(e,t){let i=e.trim();if(!lp(i))return b("client",'KeyID is required and must not contain "." or "$".');if(t!==Mt.Private&&t!==Mt.Public)return b("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return c;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},n=await this.ctx.api.userCustomData.deleteKey(s);return n.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),n}async batchSet(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let n=s.Bucket??Mt.Private,r=e.find(c=>c.Bucket===n&&c.KeyID===s.KeyID);r&&this.ctx.data.user.patchUserCustomDataKey(n,s.KeyID,r.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return b("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return c;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 jC="TitleCustomDataDefinitions",up=50;function _C(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}function Zo(o){if(o.ExpiresAt==null)return false;let e=Date.parse(o.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function WC(o){let e={};for(let[t,i]of Object.entries(o))Zo(i)||(e[t]=i);return e}var An=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(jC,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return c;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(n=>n.trim()).filter(n=>n.length>0);if(!t.length)return b("client","At least one KeyID is required.");if(t.some(n=>!_C(n)))return b("client",'KeyID must not contain "." or "$".');if(t.length>up)return b("client",`At most ${up} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return c;i.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Zo(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Zo(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=WC(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 kn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 c;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 c;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var KC=15,QC="GameLoop",cp="BoardDefinition",zn=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 c;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(QC,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(cp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),a$1(i);let s=this.ctx.authedRequest();if(!s)return c;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(cp,n.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n.data)),n}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return b("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return c;i.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${a()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let n=s.data,r=Fl(new Date,KC);this.ctx.data.user.patchBoardState(c=>{c.Position=n.NewPosition,c.CyclesCompleted=(c.CyclesCompleted??0)+(n.CyclesCompletedDelta??0),c.LastRollAtUtc=new Date().toISOString(),n.ActionRequired&&n.ActionData?c.Pending={Type:n.ActionRequired,TargetUserID:n.ActionData.TargetUserID,TargetPublicData:n.ActionData.PublicData,TargetBuildingStates:n.ActionData.TargetBuildingStates??void 0,TargetHasShield:n.ActionData.TargetHasShield??void 0,RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:r}:n.SpecialModeOffer&&(c.Pending={Type:"SPECIAL",RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:r,Special:{ModeID:n.SpecialModeOffer.ModeID??void 0,Choices:n.SpecialModeOffer.Choices??void 0}});}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),n.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",n);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${a()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.IsBotTarget&&n.Operation?this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs):!n.IsBotTarget&&n.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(n.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",n);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return b("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return c;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${a()}`},n=await this.ctx.api.gameLoop.boardLoopRaid(s);if(n.ok){let r=n.data;r.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(r.RaidLayout,r.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(r)),this.ctx.emitter.emit("gameLoop:boardRaided",r);}else await this.getUserBoardState();return n}async boardLoopRaidFast(e){if(!e.length)return b("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${a()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(s.ok){let n=s.data;n.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(n)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",n);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return b("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${a()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let n=s.data;n.StageComplete?this.ctx.data.user.patchBoardState(r=>{r.StageLevel=(r.StageLevel??1)+1,r.Position=0,r.Pending=null,r.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(n.BuiltIndex,r=>{n.NewLevel!=null&&(r.Level=n.NewLevel),r.IsDamaged=false,n.MaxLevelRewardClaimed&&(r.MaxLevelRewardClaimed=true);}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",n);}return s}async boardSpecialChoose(e,t,i){if(!e)return b("client","choiceID must not be empty.");let s=this.ctx.auth.context;if(!s)return c;let n={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,CreditsConfirmationID:i,RelatedEntityID:`special_choose_${s.userID}_${a()}`},r=await this.ctx.api.gameLoop.boardSpecialChoose(n);if(r.ok&&!r.data.CreditsConfirmation){let c=r.data;c.Mode==="Instant"||c.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(R=>{R.ChoiceID=e,R.ChosenMode=c.Mode??"Timed",R.StartedAtUtc=c.StartedAtUtc??null,R.DurationSeconds=c.DurationSeconds??null,R.AdViewsUsed=0;}),c.Operation&&this.ctx.data.user.applyResourcesWithDelta(c.Operation,c.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",c);}return r}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${a()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let n=s.data;this.ctx.data.user.patchBoardSpecialPending(r=>{r.AdViewsUsed=n.AdViewsUsed??0,r.AccumulatedMultiplier=n.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",n);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return c;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${a()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",n);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return c;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 c;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 b("client","milestoneID is required.");if(!this.ctx.auth.context)return c;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return c;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 c;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 wn=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let n=e.trim();if(!n)return b("client","FunctionName is required.");if(!this.ctx.auth.context)return c;let r={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},c$1=await this.ctx.api.cloudCode.execute(r);return c$1.ok&&this.ctx.emitter.emit("cloudCode:executed",c$1.data),c$1}};var pp=z.object({ServerTimeUtc:p,SourceType:g,SourceID:z.string(),TargetType:g,TargetID:z.string(),SourceSpent:W,FeeAmount:W,RateApplied:Y,TargetCredited:W}),dp=z.object({ServerTimeUtc:p,SourceType:g,SourceID:z.string(),TargetType:g,TargetID:z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),hp=z.object({ServerTimeUtc:p,SpendID:z.string(),Resources:O.nullish()}),Oi={Convert:"Convert",CryptoConvert:"CryptoConvert",Spend:"Spend"},HC={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},mp=z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),$C={Automatic:"Automatic",Manual:"Manual"},JC=z.enum(["Automatic","Manual"]).catch("Automatic"),ZC=z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),InitialDeposit:z.number().nullish(),MinBalance:z.number().nullish(),MaxBalance:z.number().nullish(),DailyEarnLimit:z.number().nullish(),DailySpendLimit:z.number().nullish()}).passthrough(),YC=z.object({Rate:z.number().nullish(),Max:z.number().nullish(),Period:z.number().nullish()}).passthrough(),XC=z.object({IsTradable:z.boolean().nullish(),IsPurchasable:z.boolean().nullish(),IsRefundable:z.boolean().nullish()}).passthrough(),eS=z.object({TargetCurrencyType:g.nullish(),TargetCurrencyID:z.string(),Rate:Y.nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish(),DailyLimit:z.number().nullish()}).passthrough(),fp=z.object({Enabled:z.boolean().nullish(),RateMode:JC.nullish(),Fee:z.number().nullish(),Targets:z.array(eS).nullish()}).passthrough(),gp=z.object({CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough(),tS=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Economy:ZC.nullish(),Recharge:YC.nullish(),Conversion:fp.nullish(),Permissions:XC.nullish(),Audit:gp.nullish(),Status:mp.nullish()}).passthrough(),iS=z.object({NetworkID:z.string(),ContractAddress:z.string().nullish(),Decimals:z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),sS=z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),nS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),SpendableInGame:z.boolean().nullish(),ConvertibleToVirtual:z.boolean().nullish()}).passthrough(),rS=z.object({Mode:z.string().nullish(),FundingNetworkID:z.string().nullish(),PerPlayerDailyTokens:z.number().nullish(),TitleDailyTokens:z.number().nullish(),RefuseOverCap:z.boolean().nullish()}).passthrough(),Yo=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),DisplayDecimals:z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:p.nullish(),UsdPriceRefreshMinutes:z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:z.array(iS).nullish(),Limits:sS.nullish(),Permissions:nS.nullish(),Conversion:fp.nullish(),Audit:gp.nullish(),Status:mp.nullish(),ServerGrantPolicy:rS.nullish(),UnbackedRewardCurrencyID:z.string().nullish()}).passthrough(),oS=z.object({SpendID:z.string().nullish(),DisplayName:z.string().nullish(),PriceOptions:z.record(z.string(),Cs).nullish()}).passthrough(),Mn=z.object({VirtualCurrencies:z.record(z.string(),tS).nullish(),CryptoCurrencies:z.record(z.string(),Yo).nullish(),Spends:z.record(z.string(),oS).nullish()}).passthrough();var aS={EVM:"EVM",Solana:"Solana"},lS=z.enum(["EVM","Solana"]).catch("EVM"),uS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},cS=z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),pS={Token:"Token",Nft:"Nft"},yp=z.enum(["Token","Nft"]).catch("Token"),dS={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},hS=z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),mS={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},fS=z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),gS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Xo=z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),Rp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function On(o){let e=o?.trim();return e||Rp.GameTopUp}var yS={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},Cp=z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),RS=z.object({ContractAddress:z.string().nullish(),ItemCatalogID:z.string().nullish(),DisplayName:z.string().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),Sp=z.object({Ios:z.boolean().nullish(),Android:z.boolean().nullish(),Web:z.boolean().nullish()}).passthrough(),CS=z.object({NetworkID:z.string().nullish(),DisplayName:z.string().nullish(),Type:lS.nullish(),ChainID:z.number().nullish(),ChainTicker:z.string().nullish(),RewardPoolAddress:z.string().nullish(),VaultDepositAddress:z.string().nullish(),ChainConfigVersion:z.number().nullish(),RequiredConfirmations:z.number().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:Sp.nullish(),NftCollections:z.array(RS).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RpcUrl:z.string().nullish(),GasPrice:z.number().nullish(),NftBridgeAddress:z.string().nullish(),SignatureEpoch:z.number().nullish()}).passthrough(),SS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:Sp.nullish()}).passthrough(),xS=z.object({MinAccountAgeDays:z.number().nullish(),MultiAccountCheckEnabled:z.boolean().nullish(),BanOnSharedWithdrawalAddress:z.boolean().nullish(),PendingWithdrawalTtlHours:z.number().nullish()}).passthrough(),bS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},DS=z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),xp=z.object({Enabled:z.boolean().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:DS.nullish(),DenyMessage:z.string().nullish()}).passthrough(),IS=z.object({Enabled:z.boolean().nullish(),WalletConnectProjectId:z.string().nullish(),ShowOnLoginScreen:z.boolean().nullish()}).passthrough(),PS={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Ei=z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),vS=z.object({Mode:Ei.nullish(),TokenGates:z.array(xp).nullish()}).passthrough(),ea=z.object({SystemState:SS.nullish(),Networks:z.record(z.string(),CS).nullish(),AccountSafety:xS.nullish(),WalletLogin:IS.nullish(),PlayAccess:vS.nullish(),IframeConnectHosts:z.array(z.string()).nullish()}).passthrough(),TS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),LinkedAt:p.nullish(),LastUsedAt:p.nullish(),LinkType:cS.nullish(),IsSignatureVerified:z.boolean().nullish()}).passthrough(),bp=z.object({TitleTransactionID:z.string().nullish(),Type:yp.nullish(),NetworkID:z.string().nullish(),AssetID:z.string().nullish(),Amount:Y.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),AS=z.object({Status:hS.nullish(),Tier:fS.nullish(),VerifiedAt:p.nullish(),ExpiresAt:p.nullish(),RejectedAt:p.nullish(),ProviderReference:z.string().nullish(),RejectionReason:z.string().nullish()}).passthrough(),kS=z.object({CurrencyID:z.string().nullish(),Deposits:z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),zS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:z.record(z.string(),kS).nullish()}).passthrough(),wS=z.object({NetworkID:z.string().nullish(),ItemCatalogID:z.string().nullish(),Deposits:z.number().nullish(),Withdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:p.nullish(),LastDepositAt:p.nullish(),FirstWithdrawalAt:p.nullish(),LastWithdrawalAt:p.nullish()}).passthrough(),MS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),PerCollection:z.record(z.string(),wS).nullish()}).passthrough(),OS=z.object({Tokens:zS.nullish(),Nfts:MS.nullish()}).passthrough(),ta=z.object({CurrencyID:z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),jt=z.object({Granted:z.boolean(),Mode:Ei.nullish(),Error:z.string().nullish(),WalletRequired:z.boolean().nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),GrantedUntil:p.nullish(),Balances:z.array(ta).nullish()}).passthrough(),ES=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:p.nullish(),Passed:z.boolean().nullish(),GrantedUntil:p.nullish(),Error:z.string().nullish(),Balances:z.array(ta).nullish()}).passthrough(),US=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CanUnlink:z.boolean().nullish()}).passthrough(),Dp=z.object({Mode:Ei.nullish(),TokenGates:z.array(xp).nullish(),WalletLoginEnabled:z.boolean().nullish(),CanLinkWallet:z.boolean().nullish(),WalletsFromPlatformProfile:z.boolean().nullish(),LinkedWallets:z.array(US).nullish(),Status:jt.nullish()}).passthrough(),qS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:p.nullish(),LoggedInAt:p.nullish(),GatePassed:z.boolean().nullish(),GatedBalances:z.array(ta).nullish()}).passthrough(),BS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),UnlinkedAt:p.nullish()}).passthrough(),LS=z.object({Version:z.number().nullish(),Stats:OS.nullish(),LinkedWallets:z.record(z.string(),TS).nullish(),LastWalletLogin:qS.nullish(),PlayAccess:ES.nullish(),PendingWithdrawals:z.array(bp).nullish(),Kyc:AS.nullish(),FirstActivityAt:p.nullish(),LastActivityAt:p.nullish(),IsFlagged:z.boolean().nullish(),FlagReason:z.string().nullish(),UnlinkedWallets:z.array(BS).nullish()}).passthrough(),GS=z.object({CurrencyID:z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:p}).passthrough(),gi=z.object({CryptoBalances:z.record(z.string(),GS).nullish(),PendingAdded:bp.nullish(),PendingRemovedIDs:z.array(z.string()).nullish()}).passthrough(),VS=z.object({Amount:Y,Frozen:Y,CreatedAt:p.nullish(),UpdatedAt:p.nullish()}).passthrough().transform(o=>o),FS=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:Cp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:Xo.nullish(),SignatureData:z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),TokenID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:p.nullish(),BurnAmount:z.number().nullish(),RefundedAt:p.nullish(),RefundCheckedAt:p.nullish()}).passthrough(),NS=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:Cp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:Xo.nullish(),SignatureData:z.string().nullish(),CompletedAt:p.nullish(),ExpiresAt:p.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),NFTID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),SkinID:z.string().nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:p.nullish()}).passthrough(),Ip=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),ia=z.object({TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),ContractAddress:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(Ip).nullish(),Signature:z.string().nullish()}).passthrough(),sa=z.object({Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),ProgramID:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(Ip).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),Pp=z.object({Blockchain:ea.nullish(),CryptoCurrencies:z.record(z.string(),Yo).nullish()}).passthrough(),vp=z.object({State:LS.nullish(),CryptoBalances:z.record(z.string(),VS).nullish()}).passthrough(),Tp=z.object({ServerTimeUtc:p.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:gi.nullish()}).passthrough(),Ap=z.object({ServerTimeUtc:p.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),kp=z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:p.nullish(),EvmSignature:ia.nullish(),SolanaSignature:sa.nullish(),StateDelta:gi.nullish(),ChainID:z.number().nullish()}).passthrough(),zp=z.object({ServerTimeUtc:p.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish(),EvmSignature:ia.nullish(),SolanaSignature:sa.nullish(),StateDelta:gi.nullish(),Inventory:K.nullish()}).passthrough(),wp=z.object({TokenTransactions:z.array(FS).nullish(),NFTTransactions:z.array(NS).nullish(),RefundedIDs:z.array(z.string()).nullish()}).passthrough(),na=z.object({ServerTimeUtc:p.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:z.string().nullish()}).passthrough(),Mp=z.object({TitleTransactionID:z.string().nullish(),Kind:yp.nullish(),EvmSignature:ia.nullish(),SolanaSignature:sa.nullish()}).passthrough(),Op=z.object({TitleTransactionID:z.string().nullish(),OnChainTxHash:z.string().nullish(),Status:Xo.nullish(),StateDelta:gi.nullish()}).passthrough(),Ze={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 jS="Blockchain",Ep="Blockchain:Definitions",En=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Ep,e);if(t)return a$1(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return c;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(jS,n.data.Blockchain),this.ctx.data.config.patchSection(Ep,n.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",n.data)),n)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c;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 b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,i,s,n){if(!e)return b("client","CurrencyID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let r=this.ctx.authedRequest();if(!r)return c;r.CurrencyID=e,r.NetworkID=t,r.WalletAddress=i,r.Amount=s,r.Category=On(n);let c$1=await this.ctx.api.blockchain.requestTokenWithdrawal(r);return c$1.ok&&(this.ctx.data.user.applyBlockchainStateDelta(c$1.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",c$1.data)),c$1}async requestNFTWithdrawal(e,t,i,s,n,r,c$1){if(!e)return b("client","ItemID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let h=this.ctx.authedRequest();if(!h)return c;h.ItemID=e,h.NetworkID=t,h.WalletAddress=i,h.Amount=s,h.Category=On(n),r!==void 0&&(h.Level=r),c$1&&(h.ItemInstanceID=c$1);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(h);return R.ok&&(this.ctx.data.user.applyBlockchainStateDelta(R.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",R.data)),R}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","TitleTransactionID is required.");if(!t)return b("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.TitleTransactionID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return c;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 c;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var _S={Head:"Head",Torso:"Torso",Legs:"Legs"},Un=z.enum(["Head","Torso","Legs"]).catch("Head"),WS={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},ra=z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),qp=z.object({AttackTarget:Un,DefenseTarget:Un});var KS=z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),QS=z.object({RoundIndex:z.number().nullish(),AttackerID:z.string().nullish(),DefenderID:z.string().nullish(),AttackZone:Un.nullish(),DefenseZone:Un.nullish(),HitType:KS.nullish(),DamageDealt:z.number().nullish(),DefenderHpRemaining:z.number().nullish()}).passthrough(),HS=z.object({MaxHp:z.number().nullish(),CurrentHp:z.number().nullish(),Damage:z.number().nullish(),AttackSpeed:z.number().nullish(),CritChance:z.number().nullish(),CritMultiplier:z.number().nullish(),Armor:z.number().nullish(),DodgeChance:z.number().nullish()}).passthrough(),$S=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Up=z.object({UserID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),SelectedCharacter:zo.nullish(),BattleStrategy:z.array(qp).nullish(),UnstackableItems:z.record(z.string(),$S).nullish(),Stats:HS.nullish()}).passthrough(),JS=z.object({WinnerUserID:z.string().nullish(),LoserUserID:z.string().nullish(),Entry:ue.nullish(),NetReward:ue.nullish(),BattleLog:z.array(QS).nullish(),IsDraw:z.boolean().nullish(),P1BattleProfile:Up.nullish(),P2BattleProfile:Up.nullish()}).passthrough(),Bp=z.object({MatchID:z.string(),TitleID:z.string().nullish(),RuleID:z.string().nullish(),CreatedAt:p.nullish(),CreatorID:z.string().nullish(),CreatorCharacterID:z.string().nullish(),CreatorStrategy:z.array(qp).nullish(),TargetUserID:z.string().nullish(),Entry:ue.nullish(),CreationCostPaid:ue.nullish(),RefundCreationCostOnCancel:z.boolean().nullish(),ExpiresAt:p.nullish(),JoinedByUserID:z.string().nullish(),JoinedByCharacterID:z.string().nullish(),JoinedAt:p.nullish(),Status:ra.nullish(),WinnerUserID:z.string().nullish(),CompletedAt:p.nullish(),IsRewardDistributed:z.boolean().nullish(),RewardDistributedAt:p.nullish()}).passthrough(),Lp=z.object({Status:ra,MatchID:z.string(),Entry:ue.nullish(),Resources:O.nullish()}),Gp=z.object({Match:Bp.nullish()}),Vp=z.object({MatchID:z.string(),Status:ra,Resources:O.nullish()}),Fp=z.object({Battle:JS.nullish(),Resources:O.nullish(),ResourcesDual:At.nullish()}),oa=z.object({Matches:z.array(Bp).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}),Dt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var ZS=z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var YS=z.enum(["Constant","Variable","Curve"]).catch("Constant"),XS=z.object({HealthStatID:z.string().nullish(),DamageStatID:z.string().nullish(),ArmorStatID:z.string().nullish(),AttackSpeedStatID:z.string().nullish(),CritChanceStatID:z.string().nullish(),CritDamageStatID:z.string().nullish(),DodgeStatID:z.string().nullish(),AllMightStatID:z.string().nullish()}).passthrough(),ex=z.enum(["Flat","PercentReduction"]).catch("Flat"),tx=z.object({MaxRounds:z.number().nullish(),BlockDamageMultiplier:z.number().nullish(),MinHitDamage:z.number().nullish(),DefaultCritMultiplier:z.number().nullish(),MaxCritChance:z.number().nullish(),MaxDodgeChance:z.number().nullish(),ArmorMode:ex.nullish(),MaxArmorReduction:z.number().nullish()}).passthrough(),ix=z.object({Kind:YS.nullish(),Constant:z.number().nullish(),VariableID:z.string().nullish(),Argument:z.string().nullish(),Curve:je.nullish(),OnePlus:z.boolean().nullish()}).passthrough(),sx=z.object({Coefficient:z.number().nullish(),Factors:z.array(ix).nullish()}).passthrough(),Yt=z.object({Terms:z.array(sx).nullish()}).passthrough(),nx=z.object({Health:Yt.nullish(),Damage:Yt.nullish(),Armor:Yt.nullish(),AttackSpeed:Yt.nullish(),CritChance:Yt.nullish(),CritDamage:Yt.nullish(),Dodge:Yt.nullish()}).passthrough(),Np=z.object({StatMapping:XS.nullish(),Combat:tx.nullish(),Formula:nx.nullish()}).passthrough(),rx=z.object({BurnRate:z.number().nullish()}).passthrough(),Ui=z.object({Kind:ZS.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),TokenType:o.nullish(),EntityID:z.string().nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish()}).passthrough(),jp=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Ui).nullish(),MaxPositions:z.number().nullish()}).passthrough(),_p=z.object({PriceOptions:oe.nullish(),RefundCostOnCancel:z.boolean().nullish(),MaxOpenMatches:z.number().nullish(),OfferLifetimeSeconds:z.number().nullish(),Limits:Ce.nullish(),AllowPrivateMatches:z.boolean().nullish(),MaxMatchesPerOpponentPerDay:z.number().nullish()}).passthrough(),ox=z.object({RuleID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Economy:rx.nullish(),Entry:jp.nullish(),Creation:_p.nullish(),Settings:Np.nullish()}).passthrough(),ax=z.object({Rules:z.record(z.string(),ox).nullish(),Defaults:Np.nullish(),EntryDefaults:jp.nullish(),CreationDefaults:_p.nullish()}).passthrough(),aa=z.object({InstantBattle:ax.nullish()}).passthrough(),Wp=aa;var lx={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},la=z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),ux={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},ua=z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),cx={Burn:"Burn",Ledger:"Ledger"},px=z.enum(["Burn","Ledger"]).catch("Burn"),Bn={Item:"Item",VirtualCurrency:"VirtualCurrency"},ca=z.enum(["Item","VirtualCurrency"]).catch("Item"),dx=z.object({Percent:z.number().nullish(),MinPerPosition:W.nullish()}).passthrough(),Ln=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(Ui).nullish(),MaxPositions:z.number().nullish()}).passthrough(),pa=z.object({Percent:z.number().nullish(),MinPerPosition:W.nullish(),Sink:px.nullish(),LedgerAccountID:z.string().nullish(),PerCatalogOverrides:z.record(z.string(),dx).nullish(),ApplyToDirectTrades:z.boolean().nullish()}).passthrough(),hx=z.object({AllowedCatalogIDs:z.array(z.string()).nullish(),DeniedCatalogIDs:z.array(z.string()).nullish(),DeniedItemIDs:z.array(z.string()).nullish(),AllowUnstackableWithState:z.boolean().nullish(),AllowedCurrencyIDs:z.array(z.string()).nullish(),DeniedCurrencyIDs:z.array(z.string()).nullish()}).passthrough(),mx=z.object({Enabled:z.boolean().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),MaxActiveListings:z.number().nullish(),CreateLimits:Ce.nullish(),BuyLimits:Ce.nullish(),ListingFeeOptions:oe.nullish(),RefundListingFeeOnCancel:z.boolean().nullish()}).passthrough(),fx=z.object({Enabled:z.boolean().nullish(),MinDurationHours:z.number().nullish(),MaxDurationHours:z.number().nullish(),AntiSnipeWindowSeconds:z.number().nullish(),AntiSnipeExtensionSeconds:z.number().nullish(),MaxAntiSnipeExtensions:z.number().nullish(),MinBidStepPercent:z.number().nullish(),MinBidStepAbsolute:W.nullish(),BidLimits:Ce.nullish()}).passthrough(),gx=z.object({Enabled:z.boolean().nullish(),MaxActiveOrders:z.number().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),CreateLimits:Ce.nullish(),FillLimits:Ce.nullish()}).passthrough(),yx=z.object({Enabled:z.boolean().nullish(),OfferExpirationHours:z.number().nullish(),MaxPendingOutgoing:z.number().nullish(),AllowGifts:z.boolean().nullish(),CreateLimits:Ce.nullish()}).passthrough(),Rx=z.object({Enabled:z.boolean().nullish()}).passthrough(),da=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:ge.nullish(),PricePolicy:Ln.nullish(),Commission:pa.nullish(),Tradability:hx.nullish(),Listings:mx.nullish(),Auctions:fx.nullish(),BuyOrders:gx.nullish(),DirectTrades:yx.nullish(),Matching:Rx.nullish()}).passthrough(),Kp=z.object({BidIndex:z.number().nullish(),UserID:z.string().nullish(),Amount:W.nullish(),Settled:z.boolean().nullish(),SettledAt:p.nullish()}).passthrough(),Cx=z.object({BidAxisType:i.nullish(),BidCurrencyID:z.string().nullish(),BidCatalogID:z.string().nullish(),BidItemID:z.string().nullish(),StartingBid:W.nullish(),CurrentBid:W.nullish(),CurrentBidderID:z.string().nullish(),BidCount:z.number().nullish(),ExtensionCount:z.number().nullish(),PendingRefunds:z.array(Kp).nullish()}).passthrough(),qn=z.object({LastAt:p.nullish(),DailyCount:z.number().nullish(),DailyResetUtc:p.nullish()}).passthrough(),Sx=z.object({Create:qn.nullish(),Buy:qn.nullish(),Sell:qn.nullish(),Bid:qn.nullish()}).passthrough(),xx=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),bx=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:p,ExpiresAt:p.nullish(),EquippedSlot:xx.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Ot=z.object({OfferID:z.string().nullish(),OfferType:la.nullish(),Status:ua.nullish(),CreatorUserID:z.string().nullish(),CreatorPublicData:qe.nullish(),TargetUserID:z.string().nullish(),GoodsType:ca.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:W.nullish(),GoodsInstances:z.array(bx).nullish(),Price:ue.nullish(),Auction:Cx.nullish(),CreatedAt:p.nullish(),ExpiresAt:p.nullish()}).passthrough(),Dx=z.object({GoodsType:ca.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),CountsByType:z.partialRecord(la,W).nullish()}).passthrough(),Qp=z.object({Definitions:da.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish()}).passthrough(),ha=z.object({Offers:z.array(Ot).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Hp=z.object({Groups:z.array(Dx).nullish()}).passthrough(),$p=z.object({Offer:Ot.nullish()}).passthrough(),pt=z.object({OfferID:z.string().nullish(),Status:ua.nullish(),Settlement:At.nullish(),Resources:O.nullish(),CommissionTaken:ue.nullish()}).passthrough(),qi=z.object({OfferID:z.string().nullish(),Offer:Ot.nullish(),Resources:O.nullish(),Matched:z.boolean().nullish(),Settlement:pt.nullish()}).passthrough(),Jp=z.object({OfferID:z.string().nullish(),CurrentBid:W.nullish(),BidCount:z.number().nullish(),ExpiresAt:p.nullish(),Resources:O.nullish()}).passthrough(),Gn=z.object({MyOffers:z.array(Ot).nullish(),MyBids:z.array(Ot).nullish(),MyBuyOrders:z.array(Ot).nullish(),IncomingTrades:z.array(Ot).nullish(),OutgoingTrades:z.array(Ot).nullish(),Claimables:z.array(Ot).nullish(),DrainedRefunds:z.array(Kp).nullish(),Limits:Sx.nullish()}).passthrough(),Ix=z.object({OfferID:z.string().nullish(),OfferType:la.nullish(),FinalStatus:ua.nullish(),SellerUserID:z.string().nullish(),BuyerUserID:z.string().nullish(),GoodsType:ca.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:W.nullish(),PricePaid:ue.nullish(),CommissionTaken:ue.nullish(),CompletedAt:p.nullish(),MyRole:z.string().nullish()}).passthrough(),Zp=z.object({Entries:z.array(Ix).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Me={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 Px="Marketplace",Yp={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"]},Vn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Yp,{schema:Gn,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(Px,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return c;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,s=20){if(!e)return b("client","ItemID is required.");let n=this.ctx.authedRequest();if(!n)return c;n.ItemID=e,n.OfferTypeFilter=t,n.ContinuationToken=i,n.PageSize=s;let r=await this.ctx.api.marketplace.getOffersByItem(n);return r.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",r.data),r}async getOffer(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 s=this.ctx.authedRequest();if(!s)return c;s.ItemID=e,s.ContinuationToken=t,s.PageSize=i;let n=await this.ctx.api.marketplace.getBuyOrders(s);return n.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",n.data),n}getMyState(e,t){return this.ctx.cache.read(Yp,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return c;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 s=this.ctx.authedRequest();if(!s)return c;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let n=await this.ctx.api.marketplace.getHistory(s);return n.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",n.data),n}async createListing(e,t,i,s,n,r,c$1){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let h=this.ctx.authedRequest();if(!h)return c;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.PriceBundle=s,h.DurationHours=n,h.ItemInstanceIDs=r,h.SelectedOptionID=c$1;let R=await this.ctx.api.marketplace.createListing(h);return this.applyCreateOfferResult(R,"marketplace:listingCreated"),R}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let r=await this.ctx.api.marketplace.marketBuy(s);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",r.data)),r}async marketSell(e,t,i){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let r=await this.ctx.api.marketplace.marketSell(s);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",r.data)),r}async createAuction(e,t,i,s,n,r,c$1={}){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");let h=this.ctx.authedRequest();if(!h)return c;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.BidAxisType=s,h.BidCurrencyID=c$1.bidCurrencyID,h.BidCatalogID=c$1.bidCatalogID,h.BidItemID=c$1.bidItemID,h.StartingBid=n,h.DurationHours=r,h.ItemInstanceIDs=c$1.itemInstanceIDs,h.SelectedOptionID=c$1.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(h);return this.applyCreateOfferResult(R,"marketplace:auctionCreated"),R}async placeBid(e,t){if(!e)return b("client","OfferID is required.");if(!t||t<=0)return b("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return c;i.OfferID=e,i.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;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,s,n){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let r=this.ctx.authedRequest();if(!r)return c;r.ItemID=e,r.CatalogID=t,r.GoodsAmount=i,r.PriceBundle=s,r.DurationHours=n;let c$1=await this.ctx.api.marketplace.createBuyOrder(r);return this.applyCreateOfferResult(c$1,"marketplace:buyOrderCreated"),c$1}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c;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,s,n){if(!e)return b("client","TargetUserID is required.");if(!t)return b("client","CatalogID is required.");if(!i)return b("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return c;r.TargetUserID=e,r.CatalogID=t,r.ItemID=i,r.ItemInstanceIDs=s,r.RequestedBundle=n;let c$1=await this.ctx.api.marketplace.createDirectTrade(r);return this.applyCreateOfferResult(c$1,"marketplace:directTradeCreated"),c$1}async respondDirectTrade(e,t){if(!e)return b("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.OfferID=e,i.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(i);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return c;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 b("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.OfferID=e;let n=await t(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,n.data)),n}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=Bn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Bn.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):b("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 Fn=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return b("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return c;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 s=await this.ctx.api.multiplayer.createRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.RoomID=e,s.TargetUserID=t,s.Ban=i;let n=await this.ctx.api.multiplayer.kickMember(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",n.data),n}async unbanMember(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return c;i.Page=e,i.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(i);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,i,s){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");if(!i)return b("client","SignalKind is required.");let n=this.ctx.authedRequest();if(!n)return c;n.RoomID=e,n.TargetUserID=t,n.SignalKind=i,n.Payload=s;let r=await this.ctx.api.multiplayer.sendSignal(n);return r.ok&&this.ctx.emitter.emit("multiplayer:signalSent",r.data),r}async sendChat(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return c;i.RoomID=e,i.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(i);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,i){if(!e)return b("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return c;s.RoomID=e,s.Ready=t,s.MemberState=i;let n=await this.ctx.api.multiplayer.setMemberState(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",n.data),n}};var Xp=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Nn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c;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)):c}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 b("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):c}async getCreatorProfile(e,t,i){if(!e)return b("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):c}async publish(e){if(!e.files||e.files.length===0)return b("client","At least one file is required.");let t=new Map,i=e.files.map((h,R)=>{if("sourceAssetUrl"in h)return {Role:h.role,ContentType:h.contentType,SourceAssetUrl:h.sourceAssetUrl};let j=ed(h.data,h.contentType);return t.set(R,j),{Role:h.role,ContentType:h.contentType,Size:j.size}}),s=e.thumbnail?ed(e.thumbnail.data,e.thumbnail.contentType):null,n=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!n.ok)return n;let r=n.data.Uploads??[];for(let h=0;h<r.length;h++){let R=r[h];if(!R||R.ServerCopy||!R.Url)continue;let j=t.get(h);if(!j)return b("client",`No bytes for file #${h+1}.`);let ce=await this.putBytes(R.Url,j,R.ContentType??j.type);if(!ce.ok)return ce}let c=n.data.ThumbnailUpload;if(c?.Url&&s){let h=await this.putBytes(c.Url,s,c.ContentType??s.type);if(!h.ok)return h}return this.ctx.credits.pay(h=>this.publishUploaded({CreditsConfirmationID:h,ContentID:n.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}):c}async publishUploaded(e){if(!e.ContentID)return b("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return c;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 s=await this.ctx.api.workshop.updateContent(i);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let 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 s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getMyContent(s)):c}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 s=await this.ctx.api.workshop.acquire(i);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let s of t.data.Files??[])if(s.Url)try{let n=await this.ctx.fetchImpl(s.Url);if(!n.ok)return b("connection",`Download failed (HTTP ${n.status}).`);i.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await n.arrayBuffer()});}catch(n){return b("connection",`Download failed: ${n instanceof Error?n.message:String(n)}${Xp}`)}return a$1({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)):c}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):c}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a$1(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${Xp}`)}}contentRequest(e){if(!e)return b("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):c}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 ed(o,e){return o instanceof Blob?o:typeof o=="string"?new Blob([new TextEncoder().encode(o)],{type:e}):o instanceof Uint8Array?new Blob([o.slice().buffer],{type:e}):new Blob([o],{type:e})}var vx={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},Tx=z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Ax={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},td=z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),kx={Everyone:"Everyone",Owner:"Owner",Server:"Server"},id=z.enum(["Everyone","Owner","Server"]).catch("Everyone"),zx={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},wx=z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),Mx={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},Ox=z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),Ex={Count:"Count",Sum:"Sum"},Ux=z.enum(["Count","Sum"]).catch("Count"),qx={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},Bx=z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),Lx={Strict:"Strict",Loose:"Loose"},Gx=z.enum(["Strict","Loose"]).catch("Strict"),Vx=z.object({Kind:Ox,Collection:z.string().nullish(),Validate:z.boolean().nullish()}),Fx=z.object({Type:td,ItemType:td.nullish(),Ref:Vx.nullish(),Required:z.boolean().optional(),Default:z.string().nullish(),Min:z.number().nullish(),Max:z.number().nullish(),MaxLength:z.number().nullish(),MaxItems:z.number().nullish(),Enum:z.array(z.string()).nullish(),Unique:z.boolean().optional(),UniqueIgnoreCase:z.boolean().optional(),Indexed:z.boolean().optional(),Visibility:id.optional(),ClientWritable:z.boolean().nullish(),Immutable:z.boolean().optional(),Description:z.string().nullish(),AllowedMimeTypes:z.array(z.string()).nullish(),MaxFileBytes:z.number().nullish()}),Nx=z.object({ID:z.string(),Components:z.array(z.object({Field:z.string(),Descending:z.boolean().optional()})).default([])}),jn=z.object({Mode:wx,Role:z.string().nullish(),MembersField:z.string().nullish()}),jx=z.object({Read:z.array(jn).nullish(),Create:z.array(jn).nullish(),Update:z.array(jn).nullish(),Delete:z.array(jn).nullish()}),ma=z.object({Cost:ue.nullish(),Grant:ue.nullish()}),_x=z.object({ID:z.string(),SortKey:z.string(),PartitionField:z.string().nullish(),PageSize:z.number().optional(),MaxItems:z.number().optional(),PublishItems:z.boolean().optional()}),Wx=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Namespace:z.string().nullish(),Tags:z.array(z.string()).nullish(),Enabled:z.boolean().nullish(),Kind:Tx,Mode:Gx.optional(),SchemaVersion:z.number().optional(),Fields:z.record(z.string(),Fx).nullish(),SortKeys:z.array(Nx).nullish(),Access:jx.nullish(),Limits:z.object({MaxItemBytes:z.number().nullish(),MaxItemsPerOwner:z.number().nullish(),TtlSeconds:z.number().nullish()}).nullish(),OnOwnerDeleted:Bx.optional(),Counters:z.array(z.object({ID:z.string(),Kind:Ux,SumField:z.string().nullish(),GroupBy:z.string().nullish(),Visibility:id.optional()})).nullish(),Economy:z.object({OnCreate:ma.nullish(),OnUpdate:ma.nullish(),OnDelete:ma.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:z.array(_x).nullish(),AnonymousSearch:z.boolean().nullish(),Integrations:z.object({QuestMetricOnCreate:z.string().nullish(),QuestMetricOnUpdate:z.string().nullish(),QuestMetricOnDelete:z.string().nullish(),AnalyticsEventOnCreate:z.string().nullish(),AnalyticsEventOnUpdate:z.string().nullish(),AnalyticsEventOnDelete:z.string().nullish(),TriggerOnCreate:z.string().nullish(),TriggerOnUpdate:z.string().nullish(),TriggerOnDelete:z.string().nullish()}).nullish(),Moderation:z.object({BlockedTerms:z.array(z.string()).nullish()}).nullish()}),sd=z.object({Enabled:z.boolean().optional(),Collections:z.record(z.string(),Wx).default({})}),Kx=z.object({FileID:z.string(),Url:z.string(),ContentType:z.string().nullish(),Size:z.number()}),nd=z.object({FileID:z.string(),UploadUrl:z.string(),ContentType:z.string(),MaxBytes:z.number(),ExpiresAt:z.string()}),yi=z.object({Collection:z.string(),ItemID:z.string(),OwnerUserID:z.string().nullish(),Data:z.record(z.string(),z.unknown()).default({}),Version:z.number(),CreatedAt:z.string(),UpdatedAt:z.string(),ExpireAt:z.string().nullish(),Expanded:z.record(z.string(),z.unknown()).nullish(),Files:z.record(z.string(),Kx).nullish()}),fa=z.object({Item:yi}),rd=z.object({Items:z.array(yi).default([]),Missing:z.array(z.string()).default([])}),ga=z.object({Items:z.array(yi).default([]),NextCursor:z.string().nullish()}),od=z.object({Count:z.number(),Capped:z.boolean().optional()}),ya=z.object({Item:yi,AlreadyExists:z.boolean().optional(),Economy:O.nullish()}),ad=z.object({ItemID:z.string(),Deleted:z.boolean(),Economy:O.nullish()}),ld=z.object({CounterID:z.string(),Group:z.unknown().optional(),Value:z.number()}),ud=z.object({Results:z.array(z.object({Op:z.string(),Collection:z.string(),ItemID:z.string(),Item:yi.nullish(),Deleted:z.boolean().optional()})).default([])}),cd=z.object({Roles:z.array(z.string()).default([])}),pd=z.object({Views:z.record(z.string(),z.string()).default({}),ItemUrlTemplate:z.string().nullish()}),dd=z.object({Version:z.string(),Collection:z.string(),View:z.string(),SortKey:z.string().nullish(),PageSize:z.number(),UpdatedAt:z.string(),BaseUrl:z.string(),Partitions:z.record(z.string(),z.object({Segment:z.string(),Pages:z.number(),Total:z.number()})).default({})}),hd=z.object({Page:z.number(),HasMore:z.boolean(),Items:z.array(yi).default([])}),Qx={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 Hx=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,gd=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Ca=100,md=25,fd=100;function $x(o,e,t){return {Field:o,Op:e,Value:t}}var _n=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(c)}get(e,t,i={}){let s=rt(e)??Bi(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.get({...n,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let s=rt(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(r=>gd.test(r)))];return n.length?n.length>fd?Promise.resolve(b("client",`At most ${fd} ids per call.`)):this.call(r=>this.ctx.api.dataCollections.getMany({...r,Collection:e,ItemIDs:n,Expand:i.expand})):Promise.resolve(b("client","At least one valid item id is required."))}query(e,t={},i={}){let s=rt(e)??Ra(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.query({...n,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),n=[],r=t.Cursor;for(;;){let c=await this.query(e,{...t,Cursor:r,Limit:t.Limit??Ca},i);if(!c.ok)return c;if(n.push(...c.data.Items),r=c.data.NextCursor??void 0,!r||n.length>=s)return a$1(n.slice(0,s))}}count(e,t={}){let i=rt(e)??Ra(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,i={}){let s=rt(e)??(i.itemID?Bi(i.itemID):null);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.create({...n,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,s={}){let n=rt(e)??Bi(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.update({...r,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=rt(e)??Bi(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.delete({...n,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(b("client","Operations are empty."));if(e.length>md)return Promise.resolve(b("client",`At most ${md} 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 s=rt(e);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.getCounter({...n,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,s){let n=rt(e);return n?Promise.resolve(n):t?s>0?this.call(r=>this.ctx.api.dataCollections.beginFileUpload({...r,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(b("client","File size must be positive.")):Promise.resolve(b("client","Field is required."))}async uploadFile(e,t,i,s={}){let n=s.contentType||i.type||"application/octet-stream",r=await this.beginFileUpload(e,t,n,i.size);if(!r.ok)return r;let c=await this.putBytes(r.data.UploadUrl,i,r.data.ContentType||n);return c.ok?r:c}async getPublicViews(e){let t=rt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return a$1(i);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,i={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let n=s.data.Views[t];if(!n)return b("client",`Collection '${e}' has no public view '${t}'.`);let r=await this.fetchJson(n,dd);if(!r.ok)return r;let c=r.data.Partitions[i.partition??""],h=Math.max(1,i.page??1);if(!c||h>c.Pages)return a$1({pointer:r.data,page:{Page:h,HasMore:false,Items:[]}});let R=await this.fetchJson(`${r.data.BaseUrl}${c.Segment}/page-${h}.json`,hd);return R.ok?a$1({pointer:r.data,page:R.data}):R}getPublic(e,t){let i=rt(e)??Bi(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=rt(e)??Ra(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(c)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a$1(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return b("connection","Internet Connection Error")}if(!i.ok)return b("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return b("server","CDN answer is not JSON.")}let n=t.safeParse(s);return n.success?a$1(n.data):b("server","CDN answer has an unexpected shape.")}};function rt(o){return Hx.test(o??"")?null:b("client",`Collection id '${o}' is invalid (letters, digits, '_', '-', ':').`)}function Bi(o){return gd.test(o??"")?null:b("client",`Item id '${o}' is invalid.`)}function Ra(o){return o.Limit!=null&&(o.Limit<1||o.Limit>Ca)?b("client",`Limit must be 1..${Ca}.`):(o.Where?.length??0)>8?b("client","At most 8 filters per query."):null}var Sa={Open:"Open",Declared:"Declared"},Jx=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Blocked:z.boolean().nullish(),Highlight:z.number().nullish()}).passthrough(),Zx=z.object({ParamName:z.string().nullish(),DisplayName:z.string().nullish()}).passthrough(),yd=z.object({Enabled:z.boolean().nullish(),EventNaming:z.string().nullish(),Events:z.record(z.string(),Jx).nullish(),Dimensions:z.array(Zx).nullish(),RetentionDays:z.number().nullish(),AutomaticEvents:z.boolean().nullish()}).passthrough(),_t={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},It={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Wn=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Yx={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},Xx=z.object({Index:z.number().nullish(),Name:z.string().nullish(),Reason:z.string().nullish()}).passthrough(),Rd=z.object({Accepted:z.number().nullish(),Dropped:z.array(Xx).nullish(),Duplicate:z.boolean().nullish(),Disabled:z.boolean().nullish()}).passthrough(),xa={LogEvents:"LogEvents"};function Cd(o,e=0){let t=o??"",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 s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let c=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:c&&c!=="K"&&c!=="wv"?c:void 0}}let n=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(n)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(n[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let r=/\bWindows NT (\d+\.\d+)/.exec(t);return r?{osName:"Windows",osVersion:r[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function Sd(o){let e=typeof navigator>"u"?void 0:navigator,t=Cd(e?.userAgent??"",e?.maxTouchPoints??0),i={};o.appVersion&&(i.AppVersion=o.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 s=o.locale||e?.language;return s&&(i.Language=s),i}var eb=25,tb=3e4,xd=1800*1e3,bd=500,ib=5,sb=1e3,nb=3600*1e3,Dd="idos_analytics_queue",ba="idos_analytics_pending",Da="idos_analytics_opt_out",Id="idos_analytics_first_open",Pd="idos_analytics_last_activity",vd="idos_analytics_last_context",Td="idos_analytics_owner",Kn=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;stopVisibility=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!Wn.test(e)?b("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):rb(e)?b("client",`Event name "${e}" uses a reserved prefix (${It.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return b("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(_t.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return a$1(null);if(this.config()?.Enabled===false)return this.clear(),a$1(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return a$1(null);this.pending={BatchID:a(),Events:this.queue.splice(0,It.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return c;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>=ib)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Da);return}this.write(Da,"1"),this.clear();}get isEnabled(){return this.read(Da)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(Td);e&&t&&t!==e&&this.clear(),e&&this.write(Td,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},tb),this.stopVisibility=this.ctx.host.onVisibilityChange(this.onVisibilityChange),typeof window<"u"&&window.addEventListener("pagehide",this.onPageHide),this.beginAutomatic(),this.flush();}async stop(){this.started&&(this.started=false,this.automaticDone=false,this.timer&&clearInterval(this.timer),this.drainTimer&&clearTimeout(this.drainTimer),this.timer=null,this.drainTimer=null,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null,this.stopVisibility?.(),this.stopVisibility=null,typeof window<"u"&&window.removeEventListener("pagehide",this.onPageHide),await this.flush());}beginAutomatic(){if(this.automaticDone||!this.started)return;if(this.config()?.Enabled!==true){this.stopWaitingForConfig??=this.ctx.emitter.on("title:publicConfigurationReceived",()=>this.beginAutomatic());return}this.automaticDone=true,this.stopWaitingForConfig?.(),this.stopWaitingForConfig=null;let e=Number(this.read(Pd)??"0");this.read(Id)||(this.write(Id,new Date().toISOString()),this.enqueue(_t.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(vd);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(_t.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(_t.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(vd,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=xd)&&this.enqueue(_t.SessionStart,void 0,void 0,true),this.touch();}onVisibilityChange=e=>{if(!e){this.hiddenAt=Date.now(),this.touch(),this.persist(),this.flush();return}this.hiddenAt!==null&&this.automaticDone&&Date.now()-this.hiddenAt>=xd&&this.enqueue(_t.SessionStart,void 0,void 0,true),this.hiddenAt=null;};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,s){if(!this.isEnabled||this.disabledByServer)return a$1(null);let n=this.config();if(n?.Enabled===false)return a$1(null);if(s&&n?.AutomaticEvents===false)return a$1(null);if(n?.Events?.[e]?.Blocked)return b("client",`Event "${e}" is blocked by the title.`);if(!s&&n?.EventNaming?.toLowerCase()===Sa.Declared.toLowerCase()&&!n.Events?.[e])return b("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return b("client","value must be a finite number.");let r=ob(t);if(r.error)return b("client",r.error);this.restore();let c={Name:e,ClientTimeUtc:new Date().toISOString()};return r.params&&(c.Params=r.params),i!==void 0&&(c.Value=i),this.queue.push(c),this.queue.length>bd&&this.queue.splice(0,this.queue.length-bd),this.touch(),this.persist(),this.started&&this.queue.length>=eb&&this.flush(),a$1(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},sb));}dropStale(){let e=Date.now()-(It.maxEventAgeMs-nb);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??=Sd({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(Dd);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(ba);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(Dd,this.queue),this.pending?this.writeJson(ba,this.pending):this.remove(ba);}touch(){this.write(Pd,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.host.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.host.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.host.storage.remove(this.key(e));}catch{}}readJson(e){let t=this.read(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}writeJson(e,t){this.write(e,JSON.stringify(t));}};function rb(o){let e=o.toLowerCase();return It.reservedPrefixes.some(t=>e.startsWith(t))}function ob(o){if(!o)return {};let e=Object.keys(o);if(e.length===0)return {};if(e.length>It.maxParams)return {error:`Too many parameters: ${e.length}, max ${It.maxParams}.`};let t={};for(let i of e){if(!Wn.test(i))return {error:`Invalid parameter name "${i}".`};let s=o[i];typeof s=="string"?t[i]=s.length>It.maxStringValueLength?s.slice(0,It.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var ab="idos_experiments",Qn=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 c;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 s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let n=Number(s);return s.trim()!==""&&Number.isFinite(n)?n:i}if(typeof i=="boolean"){let n=s.trim().toLowerCase();return n==="true"||n==="1"?true:n==="false"||n==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,n]of t){let r=this.views.get(s);(!r||r.VariantID!==n.VariantID||r.Status!==n.Status)&&i.push(n);}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.host.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.host.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${ab}:${this.ctx.settings.titleID}`}};function Wt(o,e,t,i){let n=`api/v2/${o&&o.length>0?o:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var L=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Wt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,s){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...s,ticket:t.ClientSessionTicket})}};var Hn=class extends L{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(xa.LogEvents,e,Rd,{silent:true})}};var lb=z.object({VariantID:z.string().nullish(),DisplayName:z.string().nullish(),Weight:z.number().nullish(),IsControl:z.boolean().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),ub={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},cb=z.object({MetricID:z.string().nullish(),Kind:z.string().nullish(),EventName:z.string().nullish(),IsPrimary:z.boolean().nullish()}).passthrough(),pb=z.object({ExperimentID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),IsEnabled:z.boolean().nullish(),Schedule:ge.nullish(),Gate:Z.nullish(),Variants:z.array(lb).nullish(),Salt:z.string().nullish(),LayerID:z.string().nullish(),StickyAssignment:z.boolean().nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Goals:z.array(cb).nullish(),ActivationEvent:z.string().nullish(),RolloutVariantID:z.string().nullish()}).passthrough(),Ad=z.object({Experiments:z.record(z.string(),pb).nullish()}).passthrough(),db={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},hb=z.object({ExperimentID:z.string().nullish(),VariantID:z.string().nullish(),Status:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),kd=z.object({Experiments:z.array(hb).nullish(),IsAbTestingAvailable:z.boolean().nullish()}).passthrough(),Ia={GetExperiments:"GetExperiments"};var $n=class extends L{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Ia.GetExperiments,e,kd)}};var mb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},zd=z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),fb=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),IsEnabled:z.boolean().nullish(),Order:z.number().nullish()}).passthrough(),wd=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),Locales:z.record(z.string(),fb).nullish(),MissingKeyMode:zd.nullish(),MaxEntriesPerLocale:z.number().nullish(),MaxValueLengthBytes:z.number().nullish()}).passthrough(),gb=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish()}).passthrough(),Md=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish(),Fallback:gb.nullish()}).passthrough(),Jn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},yb=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),Order:z.number().nullish(),Version:z.number().nullish()}).passthrough(),Od=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),MissingKeyMode:zd.nullish(),ResolvedLocale:z.string().nullish(),Locales:z.array(yb).nullish()}).passthrough(),Ed=z.object({RequestedLocale:z.string().nullish(),Locale:z.string().nullish(),Version:z.number().nullish(),NotModified:z.boolean().nullish(),Entries:z.record(z.string(),z.string()).nullish(),FallbackLocale:z.string().nullish(),FallbackVersion:z.number().nullish()}).passthrough();var Li=z.object({TitleConfigVersion:z.string().nullish(),TitleConfigUrl:z.string().nullish(),User:z.unknown().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish(),Localization:Md.nullish(),Views:z.array(z.object({Name:z.string(),Key:z.string().nullish(),Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(o=>o),Ud=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish()}).passthrough().transform(o=>o),qd=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),User:z.unknown().nullish()}).passthrough().transform(o=>o),Bd=z.object({}).passthrough().transform(o=>o),Ld=z.object({}).passthrough().transform(o=>o),Gd=z.object({Today:z.number(),Yesterday:z.number(),CurrentWeek:z.number(),CurrentMonth:z.number(),Total:z.number(),TotalSessions:z.number(),FirstActiveAt:p.nullish(),LastActiveAt:p.nullish(),LongestSessionEverSeconds:z.number().nullish(),CurrentWeekActiveHoursMask:z.number().nullish(),CurrentMonthActiveHoursMask:z.number().nullish(),ReactivationCount:z.number().nullish(),History:z.record(z.string(),z.unknown()).nullish()}).passthrough(),Vd=z.object({Username:z.string()}),dt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Fd=z.object({PlatformUserID:z.string().nullish(),PlatformAuthToken:z.string().nullish(),PlatformAuthTokenExpiration:p.nullish(),TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:p,PlayAccess:jt.nullish(),RefreshToken:z.string().nullish(),RefreshTokenExpiration:p.nullish(),ClientState:Li.nullish()}),Nd=z.object({TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:p,RefreshToken:z.string(),RefreshTokenExpiration:p.nullish(),PlayAccess:jt.nullish()}),Rb=z.object({ReturnMode:z.string().nullish(),UrlScheme:z.string().nullish(),UserCodeSupported:z.boolean().nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),jd=z.object({Google:z.object({Enabled:z.boolean().nullish(),WebClientID:z.string().nullish(),PlatformFallback:z.boolean().nullish(),AndroidClientID:z.string().nullish(),IosClientID:z.string().nullish(),DesktopClientID:z.string().nullish()}).passthrough().nullish(),Apple:z.object({Enabled:z.boolean().nullish(),BundleID:z.string().nullish(),ServiceID:z.string().nullish()}).passthrough().nullish(),PlayAccessMode:Ei.nullish(),WalletLoginNetworks:z.array(z.object({NetworkID:z.string().nullish(),Type:z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:z.boolean().nullish(),NativeSso:Rb.nullish()}).passthrough(),_d=z.object({Linked:z.boolean().nullish(),Challenge:z.string().nullish(),ExpiresAt:p.nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),PlayAccess:jt.nullish()}).passthrough(),Wd=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CooldownUntil:p.nullish(),PlayAccess:jt.nullish()}).passthrough(),Kd=z.object({CodeTtlMinutes:z.number().nullish(),ResendCooldownSeconds:z.number().nullish()}),Ge=z.object({IsCompleted:z.boolean().nullish(),ServerTime:p.nullish()}),Qd=z.object({Message: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 Zn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Wt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,Fd,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Le.RefreshSession),e,Nd,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Le.GetAuthOptions),e,jd,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Wt(this.ctx.settings.titleID,"Authentication",Le.LinkWallet,e.UserID??""),e,_d,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Wt(this.ctx.settings.titleID,"Authentication",Le.UnlinkWallet,e.UserID??""),e,Wd,{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,Kd,{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,Qd,{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 Yn=class extends L{constructor(e){super(e,"User");}getClientState(e){return this.send(dt.GetClientState,e,Li)}getClientStateExcept(e){return this.send(dt.GetClientStateExcept,e,Li)}getStateVersions(e){return this.send(dt.GetStateVersions,e,Ud)}getUserState(e){return this.send(dt.GetUserState,e,qd)}getInventory(e){return this.send(dt.GetInventory,e,Bd)}getEventTokens(e){return this.send(dt.GetEventTokens,e,Ld)}getUsageTime(e){return this.send(dt.GetUsageTime,e,Gd)}addUsageTime(e){return this.send(dt.AddUsageTime,e,Ge,{silent:true})}deleteUserAccount(e){return this.send(dt.DeleteUserAccount,e,Ge)}changeUsername(e){return this.send(dt.ChangeUsername,e,Vd)}};var Xn=class extends L{constructor(e){super(e,"Currency");}convert(e){return this.send(Oi.Convert,e,pp)}spend(e){return this.send(Oi.Spend,e,hp)}cryptoConvert(e){return this.send(Oi.CryptoConvert,e,dp)}};var Cb=z.object({ItemInstanceID:z.string(),Units:z.number(),Level:z.number()}),Pa=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Level:z.number(),Resources:O.nullish(),FodderConsumed:z.array(Cb).nullish()}),Hd=z.array(Te(Pa)),er={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Sb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},xb=z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),bb={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Db=z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Ib=z.object({ContractAddress:z.string().nullish(),TokenID:z.string().nullish(),TokenStandard:z.string().nullish(),MaxLevel:z.number().nullish()}).passthrough(),Pb=z.object({Networks:z.record(z.string(),Ib).nullish(),MetadataUrl:z.string().nullish()}).passthrough(),vb=z.object({FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),Tb=z.object({MinCharacterLevel:z.number().nullish(),UseRequirements:z.record(z.string(),z.number()).nullish(),AllowedCharacterIDs:z.array(z.string()).nullish(),AllowedSlotIDs:z.array(z.string()).nullish(),IdleRateBonus:z.number().nullish()}).passthrough(),Ab=z.object({ValuationMode:xb.nullish(),WeightCurve:je.nullish(),Selection:Db.nullish()}).passthrough(),kb=z.object({MaxLevel:z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:je.nullish(),FlatBonusCurve:je.nullish(),PercentBonusCurve:je.nullish(),PowerCurve:je.nullish(),Fodder:Ab.nullish()}).passthrough(),zb=z.object({RarityID:z.string().nullish(),CollectionID:z.string().nullish(),AuthorID:z.string().nullish()}).passthrough(),wb=z.object({ItemID:z.string(),CatalogID:z.string(),ItemClass:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),CustomData:z.record(z.string(),z.string()).nullish(),IsStackable:z.boolean().nullish(),IsTradable:z.boolean().nullish(),Weight:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),NFT:Pb.nullish(),Stats:vb.nullish(),Equipment:Tb.nullish(),Upgrade:kb.nullish(),Metadata:zb.nullish(),ExpirationDurationSeconds:z.number().nullish(),MaxSupply:z.number().nullish()}).passthrough(),Mb=z.object({Items:z.record(z.string(),wb).nullish()}).passthrough(),tr=z.object({Catalogs:z.record(z.string(),Mb).nullish()}).passthrough();function De(o){return z.unknown().transform((e,t)=>{let i=e&&typeof e=="object"?e.CreditsConfirmation:void 0;if(i!=null){let n=me.safeParse(i);return n.success?{...e,CreditsConfirmation:n.data}:(t.addIssue({code:"custom",message:`CreditsConfirmation: ${n.error.message}`}),z.NEVER)}let s=o.safeParse(e);return s.success?s.data:(t.addIssue({code:"custom",message:s.error.message}),z.NEVER)})}var ir=class extends L{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(er.UpgradeLevel,e,De(Pa))}upgradeLevelsBatch(e){return this.send(er.UpgradeLevelsBatch,e,Hd)}};var sr=class extends L{constructor(e){super(e,"Store");}purchase(e){return this.send(zt.Purchase,e,Co)}purchaseBatch(e){return this.send(zt.PurchaseBatch,e,Hl)}getDefinitions(e){return this.send(zt.GetDefinitions,e,xs)}getUserState(e){return this.send(zt.GetUserState,e,$l)}getStorefront(e){return this.send(zt.GetStorefront,e,bs)}getCreditsConfirmation(e){return this.send(zt.GetCreditsConfirmation,e,me)}getCreditsBalance(e){return this.send(zt.GetCreditsBalance,e,Ql)}};var Ob={Apple:"Apple",Google:"Google"},nr=z.object({PremiumID:z.string().nullish(),PurchaseDate:z.string().nullish(),ExpirationDate:z.string().nullish(),TransactionID:z.string().nullish(),IsAutoRenewEnabled:z.boolean().nullish()}).passthrough(),rr=z.object({Subscriptions:z.record(z.string(),nr).nullish(),ActivatedTrialIDs:z.array(z.string()).nullish(),MaxActiveTier:z.number().nullish()}).passthrough().transform(o=>o),Eb=z.object({PremiumID:z.string().nullish(),DisplayName:z.string().nullish(),Tier:z.number().nullish(),DurationDays:z.number().nullish(),TrialDurationDays:z.number().nullish(),PriceOptions:oe.nullish(),Benefits:z.record(z.string(),z.string()).nullish()}).passthrough(),Ta=z.object({Definitions:z.record(z.string(),Eb).nullish()}).passthrough(),$d=z.object({Premium:Ta.nullish()}),Jd=z.object({ServerTimeUtc:p.nullish(),Premium:rr.nullish()}),or=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),Premium:rr.nullish(),Subscription:nr.nullish(),Resources:O.nullish()}),Xt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var Ub={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},qb=z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Zd=z.object({StartUtc:p.nullish(),EndUtc:p.nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),Aa=z.object({ResourceAction:z.string().nullish(),RevokeEntitlement:z.boolean().nullish(),BlockFuturePurchases:z.boolean().nullish()}).passthrough(),Bb=z.object({PremiumID:z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:z.number().nullish(),RevokeOnRefund:z.boolean().nullish()}).passthrough(),Lb=z.object({Rewards:Q.nullish(),Rules:Q.nullish(),Refund:Q.nullish()}).passthrough(),Gb=z.object({ProductID:z.string().nullish(),Name:z.string().nullish(),Type:qb.nullish(),Enabled:z.boolean().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:z.number().nullish(),TelegramStarsPrice:z.number().nullish(),Rules:Zd.nullish(),Refund:Aa.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Subscription:Bb.nullish(),Presets:Lb.nullish()}).passthrough(),Vb=z.object({StoreID:z.string().nullish(),Enabled:z.boolean().nullish(),PackageName:z.string().nullish(),VerificationMode:z.string().nullish(),PlayPublicKey:z.string().nullish(),RequireCertificateChain:z.boolean().nullish(),SecretName:z.string().nullish(),IssuerID:z.string().nullish(),KeyID:z.string().nullish(),AcknowledgePurchases:z.boolean().nullish(),NotificationPackageName:z.string().nullish()}).passthrough(),Fb=z.object({Rewards:H.nullish()}).passthrough(),Nb=z.object({Rules:Zd.nullish()}).passthrough(),jb=z.object({Refund:Aa.nullish()}).passthrough(),_b=z.object({Rewards:z.record(z.string(),Fb).nullish(),Rules:z.record(z.string(),Nb).nullish(),Refund:z.record(z.string(),jb).nullish()}).passthrough(),Wb=z.object({MaxPurchaseAgeDays:z.number().nullish(),AllowSandbox:z.boolean().nullish(),RequirePackageMatch:z.boolean().nullish(),MaxReceiptsPerBatch:z.number().nullish(),RefundCheckHorizonDays:z.number().nullish(),RejectCrossUserReceipts:z.boolean().nullish()}).passthrough(),Kb=z.object({Enabled:z.boolean().nullish(),Products:z.record(z.string(),Gb).nullish(),Stores:z.record(z.string(),Vb).nullish(),Presets:_b.nullish(),Validation:Wb.nullish(),Refund:Aa.nullish()}).passthrough(),Yd=z.object({ProductID:z.string().nullish(),TotalPurchases:z.number().nullish(),DailyPurchases:z.number().nullish(),DailyResetUtc:p.nullish(),LastPurchasedAt:p.nullish(),Owned:z.boolean().nullish(),Refunded:z.boolean().nullish(),PurchaseBlocked:z.boolean().nullish(),Store:z.string().nullish(),LastTransactionID:z.string().nullish()}).passthrough(),Xd=z.object({ProductID:z.string().nullish(),PremiumID:z.string().nullish(),Store:z.string().nullish(),OriginalTransactionID:z.string().nullish(),LastTransactionID:z.string().nullish(),ExpiresAt:p.nullish(),AutoRenew:z.boolean().nullish(),Status:z.string().nullish(),RenewalCount:z.number().nullish(),LastStoreCheckAt:p.nullish(),LastStoreCheckError:z.string().nullish(),UpdatedAt:p.nullish()}).passthrough(),Qb=z.object({Products:z.record(z.string(),Yd).nullish(),LifetimeSpendUsdCents:z.number().nullish(),Subscriptions:z.record(z.string(),Xd).nullish(),LastRefundCheckAt:p.nullish(),TotalPurchases:z.number().nullish(),FirstPurchaseAt:p.nullish(),LastPurchaseAt:p.nullish()}).passthrough(),Hb=z.object({ProductID:z.string(),Available:z.boolean(),Owned:z.boolean(),Blocked:z.boolean(),Reason:z.string().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish()}).passthrough(),eh=z.object({ServerTimeUtc:p,Purchase:Kb.nullish(),Availability:z.array(Hb).nullish()}),th=z.object({ServerTimeUtc:p,Purchase:Qb.nullish()}),$b={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},Jb=z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),ka=z.object({ServerTimeUtc:p,Store:m.nullish(),ProductID:z.string().nullish(),TransactionID:z.string().nullish(),Status:Jb.nullish(),Granted:z.boolean().nullish(),Quantity:z.number().nullish(),Resources:O.nullish(),Inventory:K.nullish(),ProductState:Yd.nullish(),Premium:rr.nullish(),Subscription:nr.nullish(),SubscriptionMirror:Xd.nullish()}).passthrough(),ih=z.object({ServerTimeUtc:p,ProductID:z.string().nullish(),Stars:z.number().nullish(),InvoiceLink:z.string(),ExpiresAt:p.nullish()}).passthrough(),sh=St(ka),ei={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var ar=class extends L{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(ei.GetDefinitions,e,eh)}getUserState(e){return this.send(ei.GetUserState,e,th)}validatePurchase(e){return this.send(ei.ValidatePurchase,e,ka)}validatePurchasesBatch(e){return this.send(ei.ValidatePurchasesBatch,e,sh)}createTelegramInvoice(e){return this.send(ei.CreateTelegramInvoice,e,ih)}};var Zb=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),nh=z.object({Reward:H.nullish(),Weight:z.number().nullish(),AmountRange:Zb.nullish()}).passthrough(),Ri=z.object({SlotID:z.string().nullish(),MinRolls:z.number().nullish(),MaxRolls:z.number().nullish(),Pool:z.array(nh).nullish()}).passthrough(),Ci=z.object({RuleID:z.string().nullish(),Threshold:z.number().nullish(),Pool:z.array(nh).nullish()}).passthrough(),Yb=z.object({RewardSlots:z.array(Ri).nullish()}).passthrough(),Xb=z.object({PityRules:z.array(Ci).nullish()}).passthrough(),lr=z.object({SlotPresets:z.record(z.string(),Yb).nullish(),PityPresets:z.record(z.string(),Xb).nullish()}).passthrough();var eD=z.object({RuleID:z.string(),BoxIndex:z.number().nullish()}),rh=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,LootboxID:z.string(),OpenedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish(),Results:z.array(O).nullish(),TriggeredPity:z.array(eD).nullish()}),tD=z.object({RewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),iD=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxDrops:W.nullish()}).passthrough(),sD=z.object({LootboxID:z.string(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:oe.nullish(),RewardSlots:z.array(Ri).nullish(),PityRules:z.array(Ci).nullish(),Presets:tD.nullish(),RewardMultiplier:Qi.nullish(),SupplyLimits:z.array(iD).nullish(),MaxOpenCount:z.number().nullish()}).passthrough(),nD=z.object({MaxOpenCount:z.number().nullish()}).passthrough(),za=z.object({Definitions:z.record(z.string(),sD).nullish(),RewardPools:lr.nullish(),Settings:nD.nullish()}).passthrough(),oh=z.object({LootboxDefinitions:za.nullish()}),ur={GetDefinitions:"GetDefinitions",Open:"Open"};var cr=class extends L{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(ur.GetDefinitions,e,oh)}open(e){return this.send(ur.Open,e,De(rh))}};var rD=z.object({}).passthrough().transform(o=>o),oD=z.object({}).passthrough().transform(o=>o),aD=z.object({}).passthrough().transform(o=>o),lD=z.object({}).passthrough().transform(o=>o),uD=z.object({}).passthrough().transform(o=>o),cD=z.object({}).passthrough().transform(o=>o),ah=z.object({ServerTimeUtc:p,CalendarID:z.string(),DayNumber:z.number().nullish(),DailyState:rD,Resources:O.nullish(),Inventory:K.nullish()}),lh=z.object({ServerTimeUtc:p,AccrualID:z.string(),AccruedSeconds:W.nullish(),AppliedRatePerSecond:z.number().nullish(),IdleState:oD,Resources:O.nullish(),Inventory:K.nullish()}),uh=z.object({ServerTimeUtc:p,ComebackID:z.string(),ClaimedTierIndex:z.number().nullish(),ComebackState:aD,Resources:O.nullish(),Inventory:K.nullish()}),ch=z.object({ServerTimeUtc:p,ClaimID:z.string(),ClaimState:lD,Resources:O.nullish(),Inventory:K.nullish()}),pD={None:"None",Ad:"Ad",Vip:"Vip"},ph=z.object({ServerTimeUtc:p,WindowID:z.string(),Boost:z.string().nullish(),BaseAmount:W.nullish(),Multiplier:z.number().nullish(),Granted:W.nullish(),WindowState:uD,Resources:O.nullish(),Inventory:K.nullish()}),dh=z.object({Enabled:z.boolean(),Multiplier:z.number().nullish(),Progress:W.nullish(),Source:z.string().nullish(),SourceKey:z.string().nullish()}),dD=z.object({RewardMode:z.string().nullish(),RewardStackLowerTiers:z.boolean().nullish()}).passthrough(),hD=z.object({DayNumber:z.number().nullish(),Rewards:H.nullish(),IsMilestone:z.boolean().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Gi=z.object({Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),wa=z.object({Availability:Q.nullish()}).passthrough(),mD=z.object({Availability:z.record(z.string(),Gi).nullish()}).passthrough(),fD=z.object({CalendarID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Days:z.array(hD).nullish(),IsLooping:z.boolean().nullish(),MissBehavior:z.string().nullish(),ResetByDays:z.number().nullish(),MissThresholdMultiplier:z.number().nullish(),ClaimMode:z.string().nullish(),ClaimCooldownSeconds:z.number().nullish(),Availability:Gi.nullish(),Presets:wa.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),gD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Multiplier:z.number().nullish()}).passthrough(),yD=z.object({BaseRatePerSecond:z.number().nullish(),PowerCoefficient:z.number().nullish(),BoardRankCoefficient:z.number().nullish(),EquipmentBonusEnabled:z.boolean().nullish(),EquipmentCharacterID:z.string().nullish(),PremiumMultipliers:z.array(gD).nullish()}).passthrough(),RD=z.object({MinCharacterLevel:z.number().nullish(),RequirementsCharacterID:z.string().nullish(),Availability:Gi.nullish(),RequiredItemIDs:z.array(z.string()).nullish(),RequiredEquippedItemIDs:z.array(z.string()).nullish()}).passthrough(),CD=z.object({AccrualID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rate:yD.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:z.number().nullish(),MinClaimSeconds:z.number().nullish(),Requirements:RD.nullish(),FirstClaimMode:z.string().nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),SD=z.object({MinAbsenceSeconds:z.number().nullish(),Rewards:H.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),xD=z.object({ComebackID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(SD).nullish(),ClaimCooldownSeconds:z.number().nullish(),ClaimWindowSeconds:z.number().nullish(),TrackPresenceOnRead:z.boolean().nullish(),Availability:Gi.nullish(),Presets:wa.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),bD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),CooldownSeconds:z.number().nullish(),MaxClaimsPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish(),TotalClaimLimit:z.number().nullish()}).passthrough(),DD=z.object({ClaimID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Mode:z.string().nullish(),Rewards:H.nullish(),PremiumLimitOverrides:z.array(bD).nullish(),Availability:Gi.nullish(),Presets:wa.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),ID=z.object({CurrencyID:z.string().nullish(),MaxBaseAmount:z.number().nullish(),AdPlacementID:z.string().nullish(),AdMultiplier:z.number().nullish(),VipMultiplier:z.number().nullish(),VipPremiumID:z.string().nullish(),Limits:z.record(z.string(),z.unknown()).nullish()}).passthrough(),Ma=z.object({TierRewards:dD.nullish(),MilestoneRewardMultiplier:Qi.nullish(),DailyCalendars:z.record(z.string(),fD).nullish(),IdleAccruals:z.record(z.string(),CD).nullish(),Comebacks:z.record(z.string(),xD).nullish(),Claims:z.record(z.string(),DD).nullish(),Windows:z.record(z.string(),ID).nullish(),Presets:mD.nullish()}).passthrough(),hh=z.object({RewardDefinitions:Ma.nullish()}),mh=z.object({Rewards:cD.nullish()}),Pt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier",ClaimRewardWindow:"ClaimRewardWindow"};var pr=class extends L{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Pt.GetRewardDefinitions,e,hh)}getUserRewardsState(e){return this.send(Pt.GetUserRewardsState,e,mh)}getMilestoneRewardMultiplier(e){return this.send(Pt.GetMilestoneRewardMultiplier,e,dh)}claimDailyReward(e){return this.send(Pt.ClaimDailyReward,e,ah)}collectIdleAccrual(e){return this.send(Pt.CollectIdleAccrual,e,lh)}claimComebackReward(e){return this.send(Pt.ClaimComebackReward,e,uh)}claimReward(e){return this.send(Pt.ClaimReward,e,ch)}claimRewardWindow(e){return this.send(Pt.ClaimRewardWindow,e,ph)}};var dr=class extends L{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(lt.GetTutorialDefinitions,e,kl)}getUserTutorialState(e){return this.send(lt.GetUserTutorialState,e,Ji)}startFlow(e){return this.send(lt.StartFlow,e,qt)}reportStepShown(e){return this.send(lt.ReportStepShown,e,qt)}completeStep(e){return this.send(lt.CompleteStep,e,qt)}completeStepsBatch(e){return this.send(lt.CompleteStepsBatch,e,Ml)}skipStep(e){return this.send(lt.SkipStep,e,qt)}skipFlow(e){return this.send(lt.SkipFlow,e,qt)}claimFlowReward(e){return this.send(lt.ClaimFlowReward,e,wl)}resetFlow(e){return this.send(lt.ResetFlow,e,qt)}};var PD={Open:"Open",Application:"Application"},vD=z.enum(["Open","Application"]).catch("Open"),TD={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},fh=z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),AD={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Oa=z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),kD={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var ti={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},zD=z.object({CampaignID:z.string().nullish(),DisplayNameKey:z.string().nullish(),DescriptionKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),IsRunning:z.boolean().nullish()}).passthrough(),gh=z.object({IsEnabled:z.boolean().nullish(),CreatorPortalUrl:z.string().nullish(),ParticipationMode:vD.nullish(),IsCreator:z.boolean().nullish(),CreatorStatus:fh.nullish(),VerificationCode:z.string().nullish(),TeamID:z.string().nullish(),Campaigns:z.array(zD).nullish()}).passthrough(),wD=z.object({Earned:z.number().nullish(),Mature:z.number().nullish(),CountedMetrics:z.record(z.string(),z.number()).nullish(),ReachedMilestones:z.array(z.string()).nullish(),CappedBySubmissionLimit:z.boolean().nullish(),CappedByCreatorLimit:z.boolean().nullish(),NotPaidAsCopy:z.boolean().nullish()}).passthrough(),MD=z.object({CampaignID:z.string().nullish(),CurrencyKind:Oa.nullish(),CurrencyID:z.string().nullish(),NetworkID:z.string().nullish(),Earned:z.number().nullish(),Mature:z.number().nullish(),Granted:z.number().nullish(),Paid:z.number().nullish(),Overpaid:z.number().nullish(),Claimable:z.number().nullish(),BySubmission:z.record(z.string(),wD).nullish(),ComputedAt:z.string().nullish()}).passthrough(),OD=z.object({PayoutID:z.string().nullish(),CampaignID:z.string().nullish(),Amount:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Oa.nullish(),NetworkID:z.string().nullish(),PaidAt:z.string().nullish()}).passthrough(),yh=z.object({ServerTimeUtc:z.string().nullish(),HoldDays:z.number().nullish(),Campaigns:z.array(MD).nullish(),Payouts:z.array(OD).nullish()}).passthrough(),Rh=z.object({CampaignID:z.string().nullish(),PayoutID:z.string().nullish(),Claimed:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Oa.nullish(),NetworkID:z.string().nullish(),RemainingFraction:z.number().nullish(),IdempotentReplay:z.boolean().nullish(),Message:z.string().nullish()}).passthrough(),ED=z.object({To:z.string().nullish(),Amount:z.string().nullish()}).passthrough(),UD=z.object({ContractAddress:z.string().nullish(),TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),Signature:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(ED).nullish()}).passthrough(),qD=z.object({Kind:z.string().nullish(),Target:z.string().nullish(),Required:z.number().nullish(),Actual:z.number().nullish(),Passed:z.boolean().nullish()}).passthrough(),Ch=z.object({Passed:z.boolean().nullish(),Approved:z.boolean().nullish(),Status:fh.nullish(),WalletMissing:z.boolean().nullish(),WalletConnectAllowed:z.boolean().nullish(),Conditions:z.array(qD).nullish()}).passthrough(),BD=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),LD=z.object({ProgramID:z.string().nullish(),Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(BD).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),Sh=z.object({ServerTimeUtc:z.string().nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ChainID:z.number().nullish(),CurrencyID:z.string().nullish(),AmountNative:z.number().nullish(),NetAmountNative:z.number().nullish(),BurnAmountNative:z.number().nullish(),AmountUsd:z.number().nullish(),ExpiresAt:z.string().nullish(),EvmSignature:UD.nullish(),SolanaSignature:LD.nullish(),StateDelta:gi.nullish()}).passthrough();var hr=class extends L{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(ti.GetCommunityMarketingState,e,gh)}getEarnings(e){return this.send(ti.GetEarnings,e,yh)}claim(e){return this.send(ti.Claim,e,Rh)}checkJoinEligibility(e){return this.send(ti.CheckJoinEligibility,e,Ch)}withdrawCryptoReward(e){return this.send(ti.WithdrawCryptoReward,e,Sh)}};var mr=class extends L{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send($e.GetChatDefinitions,e,pu)}getChannels(e){return this.send($e.GetChannels,e,Es)}poll(e){return this.send($e.Poll,e,du)}getHistory(e){return this.send($e.GetHistory,e,hu)}getConversations(e){return this.send($e.GetConversations,e,gu)}sendMessage(e){return this.send($e.SendMessage,e,mu)}openDirectChannel(e){return this.send($e.OpenDirectChannel,e,fu)}markRead(e){return this.send($e.MarkRead,e,mi)}joinChannel(e){return this.send($e.JoinChannel,e,mi)}leaveChannel(e){return this.send($e.LeaveChannel,e,mi)}reportMessage(e){return this.send($e.ReportMessage,e,yu)}ignoreUser(e){return this.send($e.IgnoreUser,e,mi)}unignoreUser(e){return this.send($e.UnignoreUser,e,mi)}};var fr=class extends L{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(fi.GetPushConfig,e,Su)}subscribePush(e){return this.send(fi.SubscribePush,e,bo)}unsubscribePush(e){return this.send(fi.UnsubscribePush,e,Ge)}getPushSubscriptions(e){return this.send(fi.GetPushSubscriptions,e,xu)}};var gr=class extends L{constructor(e){super(e,"Localization");}send(e,t,i,s){let n=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${n}:${t.Locale}`:n,...s})}getLocalizationManifest(e){return this.send(Jn.GetLocalizationManifest,e,Od)}getLocalizationTable(e){return this.send(Jn.GetLocalizationTable,e,Ed)}};var yr=class extends L{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(gt.GetQuestDefinitions,e,$i)}getUserQuestState(e){return this.send(gt.GetUserQuestState,e,yl)}refreshQuestCycles(e){return this.send(gt.RefreshQuestCycles,e,Ge)}claimQuestReward(e){return this.send(gt.ClaimQuestReward,e,oo)}claimQuestRewardsBatch(e){return this.send(gt.ClaimQuestRewardsBatch,e,Sl)}claimMilestoneReward(e){return this.send(gt.ClaimMilestoneReward,e,ao)}claimMilestoneRewardsBatch(e){return this.send(gt.ClaimMilestoneRewardsBatch,e,xl)}claimGroupCompletionReward(e){return this.send(gt.ClaimGroupCompletionReward,e,Rl)}addQuestProgress(e){return this.send(gt.AddQuestProgress,e,Cl)}};var Rr=class extends L{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ct.GetActiveEvents,e,Fs)}getDefinitions(e){return this.send(ct.GetDefinitions,e,Vs)}getUserLteState(e){return this.send(ct.GetUserLteState,e,Pu)}grantTokens(e){return this.send(ct.GrantTokens,e,O)}spendTokens(e){return this.send(ct.SpendTokens,e,Po)}claimMilestone(e){return this.send(ct.ClaimMilestone,e,vo)}claimMilestonesBatch(e){return this.send(ct.ClaimMilestonesBatch,e,To)}claimAllMilestones(e){return this.send(ct.ClaimAllMilestones,e,To)}spendTokensBatch(e){return this.send(ct.SpendTokensBatch,e,vu)}grantTokensBatch(e){return this.send(ct.GrantTokensBatch,e,Tu)}};var Cr=class extends L{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(_e.GetDefinitions,e,Hs)}getLeaderboard(e){return this.send(_e.GetLeaderboard,e,Ai)}getMyProgress(e){return this.send(_e.GetMyProgress,e,js)}submitScore(e){return this.send(_e.SubmitScore,e,_s)}submitScoreFromSource(e){return this.send(_e.SubmitScoreFromSource,e,_s)}claimCycleReward(e){return this.send(_e.ClaimCycleReward,e,Ws)}claimMilestone(e){return this.send(_e.ClaimMilestone,e,Ks)}getFriendsLeaderboard(e){return this.send(_e.GetFriendsLeaderboard,e,Ai)}getLeaderboardsBatch(e){return this.send(_e.GetLeaderboardsBatch,e,zu)}getProgressBatch(e){return this.send(_e.GetProgressBatch,e,Qs)}claimCycleRewardsBatch(e){return this.send(_e.ClaimCycleRewardsBatch,e,wu)}claimMilestonesBatch(e){return this.send(_e.ClaimMilestonesBatch,e,Mu)}submitScoresBatch(e){return this.send(_e.SubmitScoresBatch,e,Ou)}claimAllRewardsBatch(e){return this.send(_e.ClaimAllRewardsBatch,e,Eu)}getOverviewBatch(e){return this.send(_e.GetOverviewBatch,e,Uu)}};var Sr=class extends L{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Gt.GetDefinitions,e,Zs)}getActiveSeason(e){return this.send(Gt.GetActiveSeason,e,Js)}getUserState(e){return this.send(Gt.GetUserState,e,Ao)}grantStatusTokens(e){return this.send(Gt.GrantStatusTokens,e,Gu)}claimTierReward(e){return this.send(Gt.ClaimTierReward,e,ko)}claimTierRewardsBatch(e){return this.send(Gt.ClaimTierRewardsBatch,e,Vu)}};var xr=class extends L{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Xt.GetDefinitions,e,$d)}getUserState(e){return this.send(Xt.GetUserState,e,Jd)}activateTrial(e){return this.send(Xt.ActivateTrial,e,or)}purchaseItemOrCurrency(e){return this.send(Xt.PurchaseWithResources,e,De(or))}purchaseRealMoney(e){return this.send(Xt.PurchaseRealMoney,e,or)}};var br=class extends L{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(We.GetCharacterDefinitions,e,tn)}getUserCharacters(e){return this.send(We.GetUserCharacters,e,Ku)}unlockCharacter(e){return this.send(We.UnlockCharacter,e,De(Oo))}upgradeStatLevel(e){return this.send(We.UpgradeStatLevel,e,De(wo))}upgradeCharacterLevel(e){return this.send(We.UpgradeCharacterLevel,e,De(Mo))}equipItems(e){return this.send(We.EquipItems,e,Qu)}unequipItems(e){return this.send(We.UnequipItems,e,Hu)}unequipAllCharacters(e){return this.send(We.UnequipAllCharacters,e,$u)}unlockCharactersBatch(e){return this.send(We.UnlockCharactersBatch,e,ec)}upgradeCharacterLevelsBatch(e){return this.send(We.UpgradeCharacterLevelsBatch,e,tc)}upgradeStatLevelsBatch(e){return this.send(We.UpgradeStatLevelsBatch,e,ic)}unlockSkin(e){return this.send(We.UnlockSkin,e,De(Ju))}equipSkin(e){return this.send(We.EquipSkin,e,Zu)}unequipSkin(e){return this.send(We.UnequipSkin,e,Yu)}getCharacterSkins(e){return this.send(We.GetCharacterSkins,e,Xu)}};var Dr=class extends L{constructor(e){super(e,"Match");}createMatch(e){return this.send(Dt.CreateMatch,e,Lp)}updateMatch(e){return this.send(Dt.UpdateMatch,e,Gp)}cancelMatch(e){return this.send(Dt.CancelMatch,e,Vp)}instantBattle(e){return this.send(Dt.InstantBattle,e,Fp)}saveStrategy(e){return this.send(Dt.SaveStrategy,e,Ge)}getMyMatches(e){return this.send(Dt.GetMyMatches,e,oa)}getAvailableMatches(e){return this.send(Dt.GetAvailableMatches,e,oa)}getDefinitions(e){return this.send(Dt.GetDefinitions,e,Wp)}};var GD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},xh=z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),VD={None:"None",Min:"Min",Average:"Average",Max:"Max"},FD=z.enum(["None","Min","Average","Max"]).catch("None"),ND={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},jD=z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),_D={Clamp:"Clamp",Reject:"Reject"},WD=z.enum(["Clamp","Reject"]).catch("Clamp"),KD=z.object({ItemInstanceID:z.string().nullish(),ItemID:z.string().nullish(),Level:z.number().nullish(),Units:z.number().nullish()}),QD=z.object({Index:z.number().nullish(),BurnedItemIDs:z.array(z.string()).nullish(),RolledCollectionID:z.string().nullish(),UsedCollections:z.record(z.string(),z.number()).nullish(),Output:so.nullish(),OutputLevel:z.number().nullish(),BurnedInstances:z.array(KD).nullish()}),bh=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p,Type:xh.nullish(),CraftID:z.string(),CraftedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),InputRarity:z.string().nullish(),OutputRarity:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish(),Results:z.array(QD).nullish()}),HD=z.object({CraftID:z.string().nullish(),Type:xh.nullish(),CatalogID:z.string().nullish(),CollectionID:z.string().nullish(),InputRarityID:z.string().nullish(),OutputRarityID:z.string().nullish(),RequiredItemCount:z.number().nullish(),PriceOptions:oe.nullish(),OutputLevelMode:FD.nullish(),InputSelection:jD.nullish(),OutputLevelOverflow:WD.nullish()}).passthrough(),Ea=z.object({Definitions:z.record(z.string(),HD).nullish()}).passthrough(),Dh=z.object({ServerTimeUtc:p.nullish(),CraftDefinitions:Ea.nullish()}),Ir={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Pr=class extends L{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Ir.GetDefinitions,e,Dh)}craft(e){return this.send(Ir.Craft,e,De(bh))}};var $D=2e5,vr=class extends L{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,De(on),{timeoutMs:$D,autoRetry:false})}readGeneration(e,t){return this.send(e,t,on,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Be.GetDefinitions,e,hc)}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)}estimateTemplatePrice(e){return this.send(Be.EstimateTemplatePrice,e,dc,{throttleKey:`AI:EstimateTemplatePrice:${e.FeatureKey??""}:${JSON.stringify(e.Params??{})}`})}generateThreeD(e){return this.generate(Be.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Be.GetThreeD,e)}listGenerations(e){return this.send(Be.ListGenerations,e,cc)}getGeneration(e){return this.readGeneration(Be.GetGeneration,e)}};var JD={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},ZD=z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),Ih=z.object({}).passthrough().transform(o=>o),Si=z.object({CollectibleID:z.string(),Rarity:z.number().nullish(),IsSpecial:z.boolean().nullish(),IsDuplicate:z.boolean().nullish(),CollectionCurrencyConverted:z.number().nullish()}),Ph=z.object({GrantedCollectibles:z.array(Si).nullish(),DuplicateCollectibles:z.array(Si).nullish(),CollectionCurrencyEarned:W.nullish()}),vh=z.object({CreditsConfirmation:me.nullish(),OpenedCount:z.number().nullish(),Packs:z.array(Ph).nullish(),GrantedCollectibles:z.array(Si).nullish(),DuplicateCollectibles:z.array(Si).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),NewlyCompletedSetIDs:z.array(z.string()).nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),Th=z.object({OpenedCount:z.number().nullish(),Chests:z.array(Ph).nullish(),GrantedCollectibles:z.array(Si).nullish(),DuplicateCollectibles:z.array(Si).nullish(),CollectionCurrencyEarned:W.nullish(),NewCollectionCurrencyBalance:W.nullish(),Resources:O.nullish(),Inventory:K.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),Ah=z.object({GrantedCollectibleID:z.string().nullish(),NewlyCompletedSetID:z.string().nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),Ua=z.object({SetID:z.string(),Resources:O.nullish(),Inventory:K.nullish()}),kh=z.array(Te(Ua)),zh=z.object({Resources:O.nullish(),Inventory:K.nullish()}),YD=z.object({OfferID:z.string(),TitleID:z.string().nullish(),CollectionID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderPublicData:qe.nullish(),OfferedCollectibleID:z.string().nullish(),OfferedCollectibleIsSpecial:z.boolean().nullish(),ReceiverUserID:z.string().nullish(),RequestedCollectibleID:z.string().nullish(),RequestedCollectibleIsSpecial:z.boolean().nullish(),Status:ZD.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RespondedAtUtc:p.nullish(),DeclineReason:z.string().nullish(),IsSpecialTradeEvent:z.boolean().nullish(),SpecialTradeEventID:z.string().nullish()}).passthrough(),wh=z.object({OfferID:z.string(),ExpiresAtUtc:p.nullish(),Resources:O.nullish()}),Mh=z.object({OfferID:z.string(),Resources:O.nullish()}),Oh=z.object({OfferID:z.string(),ReceivedCollectibleID:z.string().nullish(),ReceivedIsSpecial:z.boolean().nullish(),SentCollectibleID:z.string().nullish(),SentCollectibleIsSpecial:z.boolean().nullish(),Transfer:z.unknown().nullish()}),Eh=z.object({OfferID:z.string(),Resources:O.nullish()}),qa=z.object({Offers:z.array(YD).nullish()}),XD=z.object({CollectibleID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rarity:z.number().nullish(),HasSpecialVersion:z.boolean().nullish(),SortOrder:z.number().nullish()}).passthrough(),eI=z.object({SetID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SortOrder:z.number().nullish(),Collectibles:z.array(XD).nullish(),SetCompletionReward:H.nullish()}).passthrough(),tI=z.object({CollectionID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SeasonChainID:z.string().nullish(),Sets:z.array(eI).nullish(),GrandPrize:H.nullish()}).passthrough(),Uh=z.object({BonusRewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),iI=z.object({PackTypeID:z.string().nullish(),PriceOptions:oe.nullish(),BonusRewardSlots:z.array(Ri).nullish(),PityRules:z.array(Ci).nullish(),Presets:Uh.nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectibleCount:z.number().nullish(),MaxOpenCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),GuaranteeMaxRarity:z.boolean().nullish(),RarityWeights:z.record(z.string(),z.number()).nullish(),ColorTier:z.number().nullish()}).passthrough(),sI=z.object({Rarity:z.number().nullish(),CollectionCurrencyGranted:z.number().nullish()}).passthrough(),nI=z.object({CollectionChestID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectionCurrencyCost:z.number().nullish(),MaxOpenCount:z.number().nullish(),MinCollectibleCount:z.number().nullish(),MaxCollectibleCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),BonusRewardSlots:z.array(Ri).nullish(),PityRules:z.array(Ci).nullish(),Presets:Uh.nullish(),Tier:z.number().nullish()}).passthrough(),rI=z.object({SpecialTradeEventID:z.string().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),AllowedSpecialCollectibleIDs:z.array(z.string()).nullish(),SpecialTradeEventDailyTradeLimit:z.number().nullish()}).passthrough(),oI=z.object({MaxPackOpenCount:z.number().nullish(),MaxChestOpenCount:z.number().nullish()}).passthrough(),Tr=z.object({Collections:z.record(z.string(),tI).nullish(),PackTypes:z.record(z.string(),iI).nullish(),CollectionChests:z.array(nI).nullish(),DuplicateConversions:z.array(sI).nullish(),DailyTradeLimit:z.number().nullish(),CollectibleJokerCatalogID:z.string().nullish(),CollectibleJokerItemID:z.string().nullish(),SpecialTradeEvents:z.array(rI).nullish(),RewardPools:lr.nullish(),Settings:oI.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 Ar=class extends L{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ke.GetDefinitions,e,Tr)}getUserState(e){return this.send(Ke.GetUserState,e,Ih)}openPack(e){return this.send(Ke.OpenPack,e,De(vh))}openCollectionChest(e){return this.send(Ke.OpenCollectionChest,e,Th)}useCollectibleJoker(e){return this.send(Ke.UseCollectibleJoker,e,Ah)}claimSetReward(e){return this.send(Ke.ClaimSetReward,e,Ua)}claimSetRewardsBatch(e){return this.send(Ke.ClaimSetRewardsBatch,e,kh)}claimGrandPrize(e){return this.send(Ke.ClaimGrandPrize,e,zh)}sendTradeOffer(e){return this.send(Ke.SendTradeOffer,e,wh)}cancelTradeOffer(e){return this.send(Ke.CancelTradeOffer,e,Mh)}acceptTradeOffer(e){return this.send(Ke.AcceptTradeOffer,e,Oh)}declineTradeOffer(e){return this.send(Ke.DeclineTradeOffer,e,Eh)}getMyTradeOffers(e){return this.send(Ke.GetMyTradeOffers,e,qa)}getIncomingTradeOffers(e){return this.send(Ke.GetIncomingTradeOffers,e,qa)}};var kr=class extends L{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(Rt.GetDefinitions,e,cn)}getActiveEvent(e){return this.send(Rt.GetActiveEvent,e,gc)}getUserState(e){return this.send(Rt.GetUserState,e,un)}getGroupState(e){return this.send(Rt.GetGroupState,e,Go)}joinOrCreateGroup(e){return this.send(Rt.JoinOrCreateGroup,e,Go)}spin(e){return this.send(Rt.Spin,e,De(Rc))}claimObjectReward(e){return this.send(Rt.ClaimObjectReward,e,Vo)}claimGrandPrize(e){return this.send(Rt.ClaimGrandPrize,e,Vo)}leaveGroup(e){return this.send(Rt.LeaveGroup,e,Cc)}};var zr=class extends L{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(bt.GetDefinition,e,zc)}getUserState(e){return this.send(bt.GetUserState,e,wc)}getActiveDeals(e){return this.send(bt.GetActiveDeals,e,hn)}dismissDeal(e){return this.send(bt.DismissDeal,e,Oc)}executeNode(e){return this.send(bt.ExecuteNode,e,De(Mc))}recordShow(e){return this.send(bt.RecordShow,e,Ec)}claimMilestone(e){return this.send(bt.ClaimMilestone,e,Uc)}claimMilestonesBatch(e){return this.send(bt.ClaimMilestonesBatch,e,qc)}};var aI=z.object({}).passthrough().transform(o=>o),lI=z.object({FeatureKey:z.string().nullish(),IsEnabled:z.boolean().nullish(),Rate:z.number().nullish(),Basis:z.string().nullish(),SourceCurrencyID:z.string().nullish(),TargetCurrencyID:z.string().nullish(),MinSourceAmount:z.number().nullish(),MaxRewardPerOperation:z.number().nullish(),Limits:Ce.nullish()}).passthrough(),Ba=z.object({IsEnabled:z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:z.record(z.string(),Fe).nullish(),SpendRewards:z.array(lI).nullish(),Qualification:z.object({}).passthrough().transform(o=>o).nullish()}).passthrough(),La=z.object({Pending:z.boolean().nullish(),Qualified:z.boolean().nullish(),Groups:z.array(z.object({GroupID:z.string().nullish(),Met:z.boolean().nullish(),Conditions:z.array(z.object({Type:z.string().nullish(),Met:z.boolean().nullish(),Current:z.number().nullish(),Required:z.number().nullish()}).passthrough()).nullish()}).passthrough()).nullish()}).passthrough(),qh=z.object({ReferralDefinitions:Ba.nullish()}).passthrough(),Bh=z.object({Referral:aI.nullish(),InviteUrl:z.string().nullish(),Qualification:La.nullish()}).passthrough(),Lh=z.object({QualificationPending:z.boolean().nullish(),Qualification:La.nullish()}).passthrough(),Gh=z.object({ReferralCode:z.string().nullish(),ReferrerUserID:z.string().nullish(),IsFirstActivation:z.boolean().nullish(),Resources:O.nullish(),Inventory:K.nullish(),QualificationPending:z.boolean().nullish(),Qualification:La.nullish()}).passthrough(),Ga=z.object({RewardID:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}).passthrough(),Vh=St(Ga),Kt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var wr=class extends L{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Kt.GetDefinitions,e,qh)}getUserState(e){return this.send(Kt.GetUserState,e,Bh)}activateReferralCode(e){return this.send(Kt.ActivateReferralCode,e,Gh)}claimInviteReward(e){return this.send(Kt.ClaimInviteReward,e,Ga)}claimInviteRewardsBatch(e){return this.send(Kt.ClaimInviteRewardsBatch,e,Vh)}checkQualification(e){return this.send(Kt.CheckQualification,e,Lh)}};var Mr=class extends L{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(nt.GetDefinitions,e,Fc)}getMessages(e){return this.send(nt.GetMessages,e,Nc)}getUnreadCount(e){return this.send(nt.GetUnreadCount,e,gn)}readMessages(e){return this.send(nt.ReadMessages,e,jo)}claimReward(e){return this.send(nt.ClaimReward,e,yn)}claimRewardsBatch(e){return this.send(nt.ClaimRewardsBatch,e,yn)}claimAll(e){return this.send(nt.ClaimAll,e,yn)}deleteMessages(e){return this.send(nt.DeleteMessages,e,jo)}sendGift(e){return this.send(nt.SendGift,e,jc)}sendTransfer(e){return this.send(nt.SendTransfer,e,_c)}getGiftStatus(e){return this.send(nt.GetGiftStatus,e,Wc)}};var Or=class extends L{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Cn.RequestAdPermit,e,Kc)}completeView(e){return this.send(Cn.CompleteView,e,Qc)}};var Er=class extends L{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Se.GetFriendsList,e,zi)}getIncomingRequests(e){return this.send(Se.GetIncomingRequests,e,zi)}getOutgoingRequests(e){return this.send(Se.GetOutgoingRequests,e,zi)}getRecommendedFriends(e){return this.send(Se.GetRecommendedFriends,e,zi)}sendFriendRequest(e){return this.send(Se.SendFriendRequest,e,wi)}acceptFriendRequest(e){return this.send(Se.AcceptFriendRequest,e,wi)}declineFriendRequest(e){return this.send(Se.DeclineFriendRequest,e,wi)}removeFriend(e){return this.send(Se.RemoveFriend,e,wi)}getInbox(e){return this.send(Se.GetInbox,e,$c)}markInboxSeen(e){return this.send(Se.MarkInboxSeen,e,Mi)}getInboxUnread(e){return this.send(Se.GetInboxUnread,e,Mi)}follow(e){return this.send(Se.Follow,e,Nt)}unfollow(e){return this.send(Se.Unfollow,e,Nt)}getFollowers(e){return this.send(Se.GetFollowers,e,xn)}getFollowing(e){return this.send(Se.GetFollowing,e,xn)}block(e){return this.send(Se.Block,e,Nt)}unblock(e){return this.send(Se.Unblock,e,Nt)}getBlocked(e){return this.send(Se.GetBlocked,e,xn)}react(e){return this.send(Se.React,e,Nt)}unreact(e){return this.send(Se.Unreact,e,Nt)}getMyReactions(e){return this.send(Se.GetMyReactions,e,Zc)}getEntityStates(e){return this.send(Se.GetEntityStates,e,Jc)}addComment(e){return this.send(Se.AddComment,e,bn)}editComment(e){return this.send(Se.EditComment,e,bn)}deleteComment(e){return this.send(Se.DeleteComment,e,Xc)}getComments(e){return this.send(Se.GetComments,e,Yc)}report(e){return this.send(Se.Report,e,ep)}};var uI={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var ii=z.object({Target:z.string().nullish(),Operation:z.string().nullish(),Value:z.number().nullish()}).passthrough(),cI=z.object({BoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:oe.nullish(),Effect:ii.nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),Ur=z.object({Schedule:ge.nullish(),Gate:Z.nullish()}).passthrough(),Va=z.object({Availability:Q.nullish(),Effects:Q.nullish()}).passthrough(),pI=z.object({ScheduledBoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Effects:z.array(ii).nullish(),Availability:Ur.nullish(),Presets:Va.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),dI=z.object({ChainedBoostID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Effects:z.array(ii).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),hI=z.object({ChainID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Phases:z.array(dI).nullish(),Availability:Ur.nullish(),Presets:Va.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),mI=z.object({TriggeredBoostID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Sources:z.array(at).nullish(),Effects:z.array(ii).nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Availability:Ur.nullish(),Presets:Va.nullish()}).passthrough(),fI=z.object({MaxAddPercent:z.number().nullish(),MaxMultiply:z.number().nullish(),MaxAddFlat:z.number().nullish()}).passthrough(),gI=z.object({Effects:z.array(ii).nullish()}).passthrough(),yI=z.object({Availability:z.record(z.string(),Ur).nullish(),Effects:z.record(z.string(),gI).nullish()}).passthrough(),RI=z.object({StackingCaps:z.record(z.string(),fI).nullish()}).passthrough(),qr=z.object({Definitions:z.record(z.string(),cI).nullish(),ScheduledBoosts:z.record(z.string(),pI).nullish(),BoostChains:z.record(z.string(),hI).nullish(),TriggeredBoosts:z.record(z.string(),mI).nullish(),Settings:RI.nullish(),Presets:yI.nullish()}).passthrough(),Fh=z.object({InstanceID:z.string(),BoostID:z.string(),ActivatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),RemainingCharges:z.number().nullish(),EffectSnapshot:ii.nullish(),SourceType:z.string().nullish(),SourceRef:z.string().nullish()}).passthrough();z.object({Date:p.nullish(),DailyCount:z.number().nullish(),LastFiredUtc:p.nullish()}).passthrough();var Nh=z.object({ServerTimeUtc:p.nullish(),Active:z.record(z.string(),Fh).nullish()}),jh=z.object({CreditsConfirmation:me.nullish(),ServerTimeUtc:p.nullish(),BoostID:z.string().nullish(),StackingPolicy:z.string().nullish(),ActivatedBoost:Fh.nullish(),Resources:O.nullish()}),CI={Scheduled:"Scheduled",Chain:"Chain"},SI=z.object({Kind:z.string().nullish(),SourceID:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),PhaseOrder:z.number().nullish(),StartUtc:p.nullish(),EndUtc:p.nullish(),Effects:z.array(ii).nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),_h=z.object({ServerTimeUtc:p.nullish(),Windows:z.array(SI).nullish()}),si={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Br=class extends L{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(si.GetDefinitions,e,qr)}getActive(e){return this.send(si.GetActive,e,Nh)}getActiveWindows(e){return this.send(si.GetActiveWindows,e,_h)}activate(e){return this.send(si.Activate,e,De(jh))}cleanupExpired(e){return this.send(si.CleanupExpired,e,Ge)}};var Lr=class extends L{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(Ct.GetUserCustomDataDefinitions,e,vn)}getMyUserCustomData(e){return this.send(Ct.GetMyUserCustomData,e,np)}getPublicUserCustomDataOf(e){return this.send(Ct.GetPublicUserCustomDataOf,e,$o)}setPrivateData(e){return this.send(Ct.SetPrivateData,e,Jo)}setPublicData(e){return this.send(Ct.SetPublicData,e,Jo)}deleteKey(e){return this.send(Ct.DeleteKey,e,Ge)}batchSet(e){return this.send(Ct.BatchSet,e,rp)}batchDelete(e){return this.send(Ct.BatchDelete,e,op)}batchGetPublicUserCustomDataOf(e){return this.send(Ct.BatchGetPublicUserCustomDataOf,e,ap)}};var xI={Static:"Static",Runtime:"Runtime"},bI={Public:"Public",Private:"Private"},DI=z.enum(["Client","Server","System"]).catch("Client"),II=z.enum(["String","Int","Bool","Json"]).catch("String"),PI=z.object({Value:z.string().nullish(),UpdatedAt:p.nullish(),Version:z.number().nullish(),LastWriter:DI.nullish(),ExpiresAt:p.nullish()}).passthrough(),Wh=z.record(z.string(),PI),Fa=z.object({StaticVersion:z.number().nullish(),RuntimeVersion:z.number().nullish(),Static:Wh.nullish(),Runtime:Wh.nullish(),NotModified:z.boolean().nullish()}),vI=z.object({KeyID:z.string(),Scope:z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:II.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),Gr=z.object({Keys:z.record(z.string(),vI).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),Vi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Vr=class extends L{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Vi.GetTitleCustomDataDefinitions,e,Gr)}getPublicTitleData(e){return this.send(Vi.GetPublicTitleData,e,Fa)}getPublicTitleDataKeys(e){return this.send(Vi.GetPublicTitleDataKeys,e,Fa)}};var Kh=z.object({Theme:z.record(z.string(),z.string()).nullish(),Radius:z.number().nullish(),ButtonRadius:z.number().nullish(),Outline:z.number().nullish(),Background:z.string().nullish(),MotionSpeed:z.number().nullish(),MotionIntensity:z.number().nullish(),Particles:z.boolean().nullish(),SoundSet:z.string().nullish()}).passthrough();var TI={Fast:"Fast",Sequential:"Sequential"},AI={Instant:"Instant",Timed:"Timed"};var kI={Hit:"Hit",Blocked:"Blocked"},zI=z.object({SlotIndex:z.number(),Level:z.number().nullish(),IsDamaged:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish()}).passthrough(),wI=z.object({Symbol:z.union([z.string(),z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:z.string().nullish()}).passthrough();z.object({ElapsedSeconds:z.number().nullish(),Reward:H.nullish()}).passthrough();var MI=z.object({RequiredValue:z.number().nullish(),Reward:H.nullish()}).passthrough(),OI=z.object({Reward:H.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough();z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(MI).nullish(),Rate:OI.nullish()}).passthrough();z.object({PlayedCount:z.number().nullish(),RewardsClaimedCount:z.number().nullish(),InstantClaimsCount:z.number().nullish(),EarlyClaimsCount:z.number().nullish(),LateClaimsCount:z.number().nullish(),AdViewsTotal:z.number().nullish(),StatRewardClaimsCount:z.number().nullish(),StatReportsClampedCount:z.number().nullish(),StatReportsUnknownMetricCount:z.number().nullish()}).passthrough();var Qh=z.object({}).passthrough().transform(o=>o),Hh=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),Qe=z.object({Operation:O.nullish(),ScaleWithRollMultiplier:z.boolean().nullish()}).passthrough(),EI=z.object({Count:z.number().nullish(),Sides:z.number().nullish()}).passthrough(),UI=z.object({ShieldChance:z.number().nullish(),DamagedBuildingChance:z.number().nullish(),RankMultiplierMin:z.number().nullish(),RankMultiplierMax:z.number().nullish(),RankOffsetMin:z.number().nullish(),RankOffsetMax:z.number().nullish(),StageLevelSpread:z.number().nullish()}).passthrough(),qI=z.object({CostMatrixTemplatesByID:z.record(z.string(),z.array(z.array(z.number()))).nullish(),PerBoardGrowth:z.number().nullish(),VisualTemplateCycle:z.array(z.string()).nullish(),EconomyScaledResources:ue.nullish(),ScaleRaidStealWithEconomy:z.boolean().nullish(),ScaleAttackRewardWithEconomy:z.boolean().nullish(),AttackValueFromCostMatrix:z.boolean().nullish(),AttackBlockedRewardFactor:z.number().nullish(),ScaleVictimLossWithEconomy:z.boolean().nullish(),ScaleVictimLossWithTier:z.boolean().nullish(),SynthesizedBuildingSlots:z.number().nullish(),SynthesizedBuildingMaxLevel:z.number().nullish(),DifficultyGrowthPerBoard:z.number().nullish()}).passthrough(),BI=z.object({CostMatrix:z.array(z.array(z.number())).nullish(),PerBoardGrowth:z.number().nullish(),EconomyScale:z.number().nullish(),ScaledResources:ue.nullish()}).passthrough(),$h=z.object({SlotIndex:z.number().nullish(),Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxLevel:z.number().nullish(),MaxLevelReward:H.nullish()}).passthrough(),LI=z.object({Index:z.number().nullish(),Type:z.string().nullish(),CustomTypeID:z.string().nullish(),RandomActionAttackWeight:z.number().nullish(),RandomActionRaidWeight:z.number().nullish(),ChanceTableID:z.string().nullish(),SpecialModeID:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),GI=z.object({Tiles:z.record(z.string(),LI).nullish()}).passthrough(),VI=z.object({Weight:z.number().nullish(),Bonus:Qe.nullish(),Tag:z.string().nullish()}).passthrough(),FI=z.object({Weight:z.number().nullish(),Tag:z.string().nullish(),MinBonusCells:z.number().nullish(),MaxBonusCells:z.number().nullish(),BonusPool:z.array(VI).nullish(),GuaranteedBonus:Qe.nullish(),IsJackpot:z.boolean().nullish(),JackpotFinalMultiplier:z.number().nullish(),JackpotSymbolDistribution:z.record(z.string(),z.number()).nullish()}).passthrough(),NI=z.object({Variants:z.array(FI).nullish()}).passthrough(),jI=z.object({Weight:z.number().nullish(),OutcomeID:z.string().nullish(),Reward:Qe.nullish(),ForceAction:z.string().nullish(),SpecialModeID:z.string().nullish()}).passthrough(),_I=z.object({Outcomes:z.array(jI).nullish()}).passthrough(),Jh=z.object({PerAdMultiplierRange:Hh.nullish(),MaxAdViews:z.number().nullish(),AdCreditCost:z.number().nullish(),FormulaKind:z.string().nullish(),ApplyMultiplierOnEarlyClaim:z.boolean().nullish()}).passthrough(),WI=z.object({ElapsedSeconds:z.number().nullish(),Reward:Qe.nullish()}).passthrough(),KI=z.object({Tiers:z.array(WI).nullish(),TierMode:z.string().nullish(),BelowFirstTierReward:Qe.nullish()}).passthrough(),QI=z.object({RequiredValue:z.number().nullish(),Reward:Qe.nullish()}).passthrough(),HI=z.object({Reward:Qe.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough(),$I=z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(QI).nullish(),Rate:HI.nullish()}).passthrough(),Zh=z.object({MetricsByID:z.record(z.string(),$I).nullish()}).passthrough(),JI=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:oe.nullish(),Multipliers:Jh.nullish(),Gradation:KI.nullish(),RunStats:Zh.nullish()}).passthrough(),ZI=z.object({Choices:z.array(JI).nullish(),OfferExpireSeconds:z.number().nullish(),ClaimExpireSeconds:z.number().nullish()}).passthrough(),YI=z.object({Chance:z.number().nullish(),RequiredOutcome:z.string().nullish(),Reward:Qe.nullish(),Tag:z.string().nullish()}).passthrough(),XI=z.object({OnPassStart:Qe.nullish(),OnTileLanding:z.record(z.string(),Qe).nullish(),OnAttack:z.record(z.string(),Qe).nullish(),OnRaid:z.record(z.string(),Qe).nullish(),OnBuild:Qe.nullish(),OnStageComplete:Qe.nullish(),OnAttackBonusDrops:z.array(YI).nullish(),ChanceTablesByID:z.record(z.string(),_I).nullish(),SpecialModesByID:z.record(z.string(),ZI).nullish()}).passthrough(),Yh=z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:z.number().nullish(),MaxShields:z.number().nullish(),Buildings:z.array($h).nullish(),HeistGridBonusConfig:NI.nullish(),StageOperations:XI.nullish(),TileLandingMultiplier:Hh.nullish(),EconomyOverride:BI.nullish()}).passthrough(),eP=z.object({Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BoardTemplateID:z.string().nullish(),Buildings:z.array($h).nullish(),StageTemplateID:z.string().nullish(),CostMatrixTemplateID:z.string().nullish(),UnitValue:z.number().nullish(),Override:Yh.nullish()}).passthrough(),tP=z.object({AttackCooldownSeconds:z.number().nullish(),RaidCooldownSeconds:z.number().nullish(),MaxRecentTargets:z.number().nullish(),LiveOpponentActiveDays:z.number().nullish(),LiveOpponentPoolSize:z.number().nullish(),LiveOpponentPoolCacheSeconds:z.number().nullish(),MaxLiveCandidateReads:z.number().nullish(),VictimImmunitySeconds:z.number().nullish()}).passthrough(),iP=z.object({Enabled:z.boolean().nullish(),IntervalSeconds:z.number().nullish(),MaxPerCatchUp:z.number().nullish(),Chance:z.number().nullish(),AttackWeight:z.number().nullish(),RaidWeight:z.number().nullish(),MinBoardStageLevel:z.number().nullish(),RaidLossMultiplier:z.number().nullish()}).passthrough(),Fr=z.object({RollCurrencyID:z.string().nullish(),ShieldCurrencyID:z.string().nullish(),RaidMode:z.string().nullish(),AllowedRollMultipliers:z.array(z.number()).nullish(),BoardTemplatesByID:z.record(z.string(),GI).nullish(),StageTemplatesByID:z.record(z.string(),Yh).nullish(),StagesByLevel:z.record(z.string(),eP).nullish(),SoftCurrencyID:z.string().nullish(),ProceduralEconomy:qI.nullish(),Dice:EI.nullish(),Bots:UI.nullish(),Targeting:tP.nullish(),BotRaids:iP.nullish()}).passthrough(),sP=z.object({IsActive:z.boolean().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AnchorUtc:p.nullish(),RoundDurationSec:z.number().nullish(),PauseBetweenRoundsSec:z.number().nullish(),MaxRounds:z.number().nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),ContributionMin:z.number().nullish(),ContributionMax:z.number().nullish(),ScaleContributionWithRollMultiplier:z.boolean().nullish(),MaxProgress:z.number().nullish(),Milestones:z.record(z.string(),Fe).nullish(),GrandPrize:H.nullish()}).passthrough(),Nr=z.object({Board:Fr.nullish(),CommunityChest:sP.nullish()}).passthrough(),Xh=z.object({AttackerGainByOutcome:z.record(z.string(),ue).nullish()}).passthrough(),nP=z.object({TargetUserID:z.string().nullish(),IsBot:z.boolean().nullish(),PublicData:qe.nullish(),TargetBuildingStates:z.array(zI).nullish(),TargetHasShield:z.boolean().nullish(),TargetStageLevel:z.number().nullish(),RaidRewardPreview:Xh.nullish()}).passthrough(),rP=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:Qe.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:oe.nullish(),Multipliers:Jh.nullish(),RunStats:Zh.nullish()}).passthrough(),oP=z.object({ModeID:z.string().nullish(),Choices:z.array(rP).nullish()}).passthrough(),aP=z.object({GroupID:z.string().nullish(),Delta:W.nullish(),NewProgress:W.nullish(),MaxProgress:W.nullish(),UnlockedMilestoneIDs:z.array(z.string()).nullish(),Completed:z.boolean().nullish()}).passthrough(),em=z.object({UsedMultiplier:z.number().nullish(),Steps:z.number().nullish(),DiceValues:z.array(z.number()).nullish(),OldPosition:z.number().nullish(),NewPosition:z.number(),CyclesCompletedDelta:W.nullish(),LandedTileType:z.string().nullish(),Operation:O.nullish(),Inventory:K.nullish(),ActionRequired:z.string().nullish(),ActionData:nP.nullish(),SpecialModeOffer:oP.nullish(),CommunityChestContribution:aP.nullish()}).passthrough(),tm=z.object({Outcome:z.string().nullish(),IsBotTarget:z.boolean().nullish(),BuildingIndexHit:z.number().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:At.nullish()}).passthrough(),Na=z.object({Status:z.string().nullish(),Outcome:z.string().nullish(),FoundSymbol:z.union([z.string(),z.number()]).nullish(),FoundBonus:H.nullish(),OpenedIndex:z.number().nullish(),AttemptsLeft:z.number().nullish(),RaidLayout:z.array(wI).nullish(),HeistVariantTag:z.string().nullish(),IsJackpot:z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish(),DualResult:At.nullish(),RaidRewardPreview:Xh.nullish()}).passthrough(),im=z.object({BuiltIndex:z.number(),NewLevel:z.number().nullish(),StageComplete:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish(),Operation:O.nullish(),Inventory:K.nullish()}).passthrough(),sm=z.object({CreditsConfirmation:me.nullish(),Mode:z.union([z.string(),z.number()]).nullish(),Operation:O.nullish(),Inventory:K.nullish(),DurationSeconds:z.number().nullish(),StartedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish()}).passthrough(),nm=z.object({AdViewsUsed:z.number().nullish(),RolledMultiplier:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),RemainingAdViews:z.number().nullish()}).passthrough(),lP=z.object({MetricID:z.string().nullish(),ReachedTierIndex:z.number().nullish(),RequiredValue:z.number().nullish(),RewardUnits:z.number().nullish()}).passthrough(),rm=z.object({FinalMultiplier:z.number().nullish(),AdViewsUsed:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),IsEarlyClaim:z.boolean().nullish(),ReachedTierIndex:z.number().nullish(),Operation:O.nullish(),Inventory:K.nullish(),AcceptedRunStats:z.record(z.string(),z.number()).nullish(),RunStatAwards:z.array(lP).nullish(),RunStatsClamped:z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),uP={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},om=z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),cP={Active:"Active",Left:"Left",Replaced:"Replaced"},pP=z.enum(["Active","Left","Replaced"]).catch("Active"),dP=z.object({CurrentProgress:W.nullish(),MaxProgress:W.nullish()}).passthrough(),hP=z.object({UserID:z.string().nullish(),PublicData:qe.nullish(),IsBot:z.boolean().nullish(),ContributionPoints:W.nullish(),MilestoneClaims:z.record(z.string(),ml).nullish(),GrandPrizeClaimed:z.boolean().nullish(),MemberStatus:pP.nullish(),JoinedAtUtc:p.nullish(),LeftAtUtc:p.nullish()}).passthrough(),am=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),RoundIndex:z.number().nullish(),Members:z.array(hP).nullish(),SharedProgress:dP.nullish(),Status:om.nullish(),CreatedAtUtc:p.nullish(),ExpiresAtUtc:p.nullish(),Version:z.number().nullish()}).passthrough(),mP=z.object({GroupID:z.string().nullish(),RoundIndex:z.number().nullish(),FinalStatus:om.nullish(),GrandPrizeReceived:z.boolean().nullish(),FinishedAtUtc:p.nullish()}).passthrough(),fP=z.object({ActiveGroupID:z.string().nullish(),ActiveRoundIndex:z.number().nullish(),History:z.array(mP).nullish()}).passthrough(),lm=z.object({ServerTimeUtc:p.nullish(),UserState:fP.nullish(),ActiveGroup:am.nullish(),SecondsRemaining:W.nullish()}),um=z.object({ServerTimeUtc:p.nullish(),Group:am.nullish(),SecondsRemaining:W.nullish()}),ja=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:O.nullish(),Inventory:K.nullish()}),cm=z.object({ServerTimeUtc:p.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),Ve={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 gP={Mesh:"Mesh",Host:"Host"},_a=z.enum(["Mesh","Host"]).catch("Mesh"),yP={ServerRelay:"ServerRelay",P2P:"P2P"},Wa=z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),RP={Public:"Public",Private:"Private"},CP=z.enum(["Public","Private"]).catch("Public"),SP={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},xP=z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),pm=z.object({Urls:z.string().nullish(),Username:z.string().nullish(),Credential:z.string().nullish()}).passthrough(),bP=z.object({Enabled:z.boolean().nullish()}).passthrough(),dm=z.object({SystemState:bP.nullish(),DefaultTopology:_a.nullish(),AllowCreatorTopologyOverride:z.boolean().nullish(),DefaultChatMode:Wa.nullish(),AllowCreatorChatOverride:z.boolean().nullish(),MaxPlayersPerRoom:z.number().nullish(),RoomTtlSeconds:z.number().nullish(),MaxRoomLifetimeSeconds:z.number().nullish(),HeartbeatIntervalMs:z.number().nullish(),MemberTimeoutMs:z.number().nullish(),MaxSignalPayloadBytes:z.number().nullish(),MaxChatTextLength:z.number().nullish(),RoomLogCap:z.number().nullish(),VoiceEnabled:z.boolean().nullish(),RecordVoices:z.boolean().nullish(),IceServers:z.array(pm).nullish()}).passthrough(),DP=z.object({UserID:z.string().nullish(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),Ready:z.boolean().nullish(),State:z.record(z.string(),z.string()).nullish(),JoinedAt:z.number().nullish(),IsHost:z.boolean().nullish(),LastSeenMs:z.number().nullish()}).passthrough(),IP=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),Topology:_a.nullish(),ChatMode:Wa.nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),MemberCount:z.number().nullish(),CreatedAt:z.number().nullish()}).passthrough(),PP=z.object({Seq:z.number().nullish(),Type:xP.nullish(),FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Kind:z.string().nullish(),Payload:z.string().nullish(),Ts:z.number().nullish()}).passthrough(),Fi=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),OwnerUserID:z.string().nullish(),Topology:_a.nullish(),ChatMode:Wa.nullish(),Visibility:CP.nullish(),Status:z.string().nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),Members:z.array(DP).nullish(),IceServers:z.array(pm).nullish(),Seq:z.number().nullish(),BannedUserIDs:z.array(z.string()).nullish()}).passthrough(),hm=z.object({Removed:z.boolean().nullish(),Banned:z.boolean().nullish()}).passthrough(),mm=z.object({WasBanned:z.boolean().nullish()}).passthrough(),Ka=z.object({Closed:z.boolean().nullish(),NewHostUserID:z.string().nullish()}).passthrough(),fm=z.object({Rooms:z.array(IP).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}).passthrough(),gm=z.object({Envelopes:z.array(PP).nullish(),MaxSeq:z.number().nullish()}).passthrough(),jr=z.object({Seq:z.number().nullish()}).passthrough(),Ye={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 Qa=z.object({TitleCustomData:Gr.nullish(),Character:tn.nullish(),Item:tr.nullish(),Currency:Mn.nullish(),Store:xs.nullish(),Lootbox:za.nullish(),Quest:$i.nullish(),TimedEvent:Vs.nullish(),Leaderboard:Hs.nullish(),Season:Zs.nullish(),Reward:Ma.nullish(),Collection:Tr.nullish(),Craft:Ea.nullish(),DealOffer:Fo.nullish(),Premium:Ta.nullish(),TimedBoost:qr.nullish(),CoopEvent:cn.nullish(),GameLoop:Nr.nullish(),Match:aa.nullish(),Experiment:Ad.nullish(),Blockchain:ea.nullish(),Marketplace:da.nullish(),Multiplayer:dm.nullish(),UserCustomData:vn.nullish(),Referral:Ba.nullish(),Localization:wd.nullish(),Analytics:yd.nullish(),Social:tp.nullish(),PlatformBridge:ip.nullish(),GameSpec:z.string().nullish(),Look:Kh.nullish()}).passthrough();var ni={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var _r=class extends L{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(ni.GetTitlePublicConfiguration,e,Qa)}getTitlePublicConfigurationExcept(e){return this.send(ni.GetTitlePublicConfigurationExcept,e,Qa)}getCurrencyDefinitions(e){return this.send(ni.GetCurrencyDefinitions,e,Mn)}getItemDefinitions(e){return this.send(ni.GetItemDefinitions,e,tr)}getServerTime(e){return this.send(ni.GetServerTime,e,Ge)}};var Wr=class extends L{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Ve.GetGameLoops,e,Nr)}getBoardDefinition(e,t=false){return this.send(Ve.GetBoardDefinition,e,Fr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Ve.GetBoardDefinitionForLevel,e,Fr,{silent:t})}getUserBoardState(e){return this.send(Ve.GetUserBoardState,e,Qh)}boardLoopRoll(e){return this.send(Ve.BoardLoopRoll,e,em)}boardLoopAttack(e){return this.send(Ve.BoardLoopAttack,e,tm)}boardLoopRaid(e){return this.send(Ve.BoardLoopRaid,e,Na)}boardLoopRaidFast(e){return this.send(Ve.BoardLoopRaidFast,e,Na)}boardLoopBuild(e){return this.send(Ve.BoardLoopBuild,e,im)}boardSpecialChoose(e){return this.send(Ve.BoardSpecialChoose,e,De(sm))}boardSpecialApplyMultiplier(e){return this.send(Ve.BoardSpecialApplyMultiplier,e,nm)}boardSpecialClaim(e){return this.send(Ve.BoardSpecialClaim,e,rm)}getCommunityChestState(e){return this.send(Ve.GetCommunityChestState,e,lm)}joinOrCreateCommunityChest(e){return this.send(Ve.JoinOrCreateCommunityChest,e,um)}claimCommunityChestMilestone(e){return this.send(Ve.ClaimCommunityChestMilestone,e,ja)}claimCommunityChestGrandPrize(e){return this.send(Ve.ClaimCommunityChestGrandPrize,e,ja)}leaveCommunityChest(e){return this.send(Ve.LeaveCommunityChest,e,cm)}};var vP={Live:"Live",Latest:"Latest",Specific:"Specific"},TP={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},AP=z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),kP={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"},zP=z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),wP=z.object({Level:AP,Message:z.string().nullish(),Data:Vt.nullish()}),MP=z.object({Error:zP,Message:z.string().nullish(),StackTrace:z.string().nullish()}),Rm=z.object({FunctionName:z.string().nullish(),Revision:z.number().nullish(),FunctionResult:Vt.nullish(),FunctionResultTooLarge:z.boolean().nullish(),Logs:z.array(wP).nullish(),LogsTooLarge:z.boolean().nullish(),ExecutionTimeSeconds:z.number().nullish(),APIRequestsIssued:z.number().nullish(),Error:MP.nullish()}),Ha={Execute:"Execute"};var Kr=class extends L{constructor(e){super(e,"CloudCode");}execute(e){return this.send(Ha.Execute,e,Rm)}};var Qr=class extends L{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Ze.GetDefinitions,e,Pp)}getUserState(e){return this.send(Ze.GetUserState,e,vp)}depositToken(e){return this.send(Ze.DepositToken,e,Tp)}depositNFT(e){return this.send(Ze.DepositNFT,e,Ap)}requestTokenWithdrawal(e){return this.send(Ze.RequestTokenWithdrawal,e,kp)}requestNFTWithdrawal(e){return this.send(Ze.RequestNFTWithdrawal,e,zp)}getTransactionHistory(e){return this.send(Ze.GetTransactionHistory,e,wp)}retryWithdrawal(e){return this.send(Ze.RetryWithdrawal,e,Mp)}confirmWithdrawal(e){return this.send(Ze.ConfirmWithdrawal,e,Op)}donateToDeveloper(e){return this.send(Ze.DonateToDeveloper,e,na)}donateToUsersPool(e){return this.send(Ze.DonateToUsersPool,e,na)}getPlayAccess(e){return this.send(Ze.GetPlayAccess,e,Dp)}confirmPlayAccess(e){return this.send(Ze.ConfirmPlayAccess,e,jt)}};var Hr=class extends L{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Me.GetDefinitions,e,Qp)}getGroupedOffers(e){return this.send(Me.GetGroupedOffers,e,Hp)}getOffersByItem(e){return this.send(Me.GetOffersByItem,e,ha)}getOffer(e){return this.send(Me.GetOffer,e,$p)}getBuyOrders(e){return this.send(Me.GetBuyOrders,e,ha)}getMyState(e){return this.send(Me.GetMyState,e,Gn)}getHistory(e){return this.send(Me.GetHistory,e,Zp)}createListing(e){return this.send(Me.CreateListing,e,qi)}cancelListing(e){return this.send(Me.CancelListing,e,pt)}buy(e){return this.send(Me.Buy,e,pt)}marketBuy(e){return this.send(Me.MarketBuy,e,pt)}marketSell(e){return this.send(Me.MarketSell,e,pt)}createAuction(e){return this.send(Me.CreateAuction,e,qi)}placeBid(e){return this.send(Me.PlaceBid,e,Jp)}claimAuction(e){return this.send(Me.ClaimAuction,e,pt)}createBuyOrder(e){return this.send(Me.CreateBuyOrder,e,qi)}cancelBuyOrder(e){return this.send(Me.CancelBuyOrder,e,pt)}fillBuyOrder(e){return this.send(Me.FillBuyOrder,e,pt)}createDirectTrade(e){return this.send(Me.CreateDirectTrade,e,qi)}respondDirectTrade(e){return this.send(Me.RespondDirectTrade,e,pt)}cancelDirectTrade(e){return this.send(Me.CancelDirectTrade,e,pt)}claimBack(e){return this.send(Me.ClaimBack,e,pt)}};var $r=class extends L{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(Ye.CreateRoom,e,Fi)}joinRoom(e){return this.send(Ye.JoinRoom,e,Fi)}leaveRoom(e,t=false){return this.send(Ye.LeaveRoom,e,Ka,{keepalive:t})}listRooms(e){return this.send(Ye.ListRooms,e,fm)}getRoom(e){return this.send(Ye.GetRoom,e,Fi)}closeRoom(e){return this.send(Ye.CloseRoom,e,Ka)}poll(e){return this.send(Ye.Poll,e,gm)}sendSignal(e){return this.send(Ye.SendSignal,e,jr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(Ye.ClaimHost,e,Fi)}kickMember(e){return this.send(Ye.KickMember,e,hm)}unbanMember(e){return this.send(Ye.UnbanMember,e,mm)}sendChat(e){return this.send(Ye.SendChat,e,jr)}setMemberState(e){return this.send(Ye.SetMemberState,e,jr)}};var OP={Free:"Free",Price:"Price",Holding:"Holding"},$a=z.enum(["Free","Price","Holding"]).catch("Free"),EP={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},UP=z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),qP={All:"All",Any:"Any"},BP=z.enum(["All","Any"]).catch("All"),LP={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},GP=z.enum(["Public","Unlisted","Friends"]).catch("Public"),VP={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},FP=z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),NP={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Sm=z.enum(["Purchase","Free","Holding"]).catch("Free"),jP={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},_P={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},WP=z.enum(["Creator","License","Free","Holding"]).catch("License"),KP=z.object({Type:i.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),Amount:z.number().nullish(),MinLevel:z.number().nullish()}).passthrough(),QP=z.object({Requirements:z.array(KP).nullish(),Match:BP.nullish(),Mode:UP.nullish()}).passthrough(),HP=z.object({OptionID:z.string().nullish(),Mode:$a.nullish(),Price:ue.nullish(),Holding:QP.nullish()}).passthrough(),$P=z.object({AllowedMimeTypes:z.array(z.string()).nullish(),MaxBytes:z.number().nullish(),MaxCount:z.number().nullish(),Required:z.boolean().nullish()}).passthrough(),JP=z.object({DisplayName:z.string().nullish(),Enabled:z.boolean().nullish(),Files:z.record(z.string(),$P).nullish(),ThumbnailRequired:z.boolean().nullish(),AllowedAccessModes:z.array($a).nullish(),PricePolicy:Ln.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:oe.nullish(),TagVocabulary:z.array(z.string()).nullish(),MaxPublishedPerPlayer:z.number().nullish(),DailyPublishCap:z.number().nullish()}).passthrough(),ZP=z.object({Allowed:z.array(Ui).nullish(),MaxRequirements:z.number().nullish()}).passthrough(),YP=z.object({AutoHideReportThreshold:z.number().nullish(),RequireApproval:z.boolean().nullish(),BlockedTerms:z.array(z.string()).nullish()}).passthrough(),XP=z.object({MaxTitleLength:z.number().nullish(),MaxDescriptionLength:z.number().nullish(),MaxTags:z.number().nullish(),MaxTagLength:z.number().nullish(),MaxMetadataKeys:z.number().nullish(),MaxMetadataValueLength:z.number().nullish(),MaxAccessOptions:z.number().nullish(),ThumbnailMaxBytes:z.number().nullish()}).passthrough(),ev=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Schedule:ge.nullish(),Gate:Z.nullish(),Order:z.number().nullish()}).passthrough(),tv=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:ge.nullish(),ContentTypes:z.record(z.string(),JP).nullish(),PricePolicy:Ln.nullish(),Commission:pa.nullish(),HoldingPolicy:ZP.nullish(),Moderation:YP.nullish(),Limits:XP.nullish(),Featured:z.array(ev).nullish()}).passthrough(),iv=z.object({Acquisitions:z.number().nullish(),Downloads:z.number().nullish(),Likes:z.number().nullish(),Favorites:z.number().nullish(),ReportCount:z.number().nullish(),Remixes:z.number().nullish()}).passthrough(),ri=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),CreatorUserID:z.string().nullish(),IsOfficial:z.boolean().nullish(),CreatorPublicData:qe.nullish(),Title:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),Metadata:z.record(z.string(),z.string()).nullish(),ThumbnailUrl:z.string().nullish(),Visibility:GP.nullish(),Access:z.array(HP).nullish(),Status:FP.nullish(),ModerationNote:z.string().nullish(),Stats:iv.nullish(),Revision:z.number().nullish(),ParentContentID:z.string().nullish(),FileCount:z.number().nullish(),TotalBytes:z.number().nullish(),CreatedAt:p.nullish(),UpdatedAt:p.nullish(),PublishedAt:p.nullish(),IsMine:z.boolean().nullish(),Owned:z.boolean().nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish()}).passthrough(),sv=z.object({OptionID:z.string().nullish(),Mode:$a.nullish(),Available:z.boolean().nullish()}).passthrough(),xm=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Order:z.number().nullish()}).passthrough(),bm=z.object({Definitions:tv.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish(),CanPublish:z.record(z.string(),z.boolean()).nullish(),Collections:z.array(xm).nullish()}).passthrough(),Jr=z.object({Items:z.array(ri).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Dm=z.object({Content:ri.nullish(),AccessState:z.array(sv).nullish(),CanDownload:z.boolean().nullish()}).passthrough(),Im=z.object({Collection:xm.nullish(),Items:z.array(ri).nullish()}).passthrough(),Pm=z.object({CreatorUserID:z.string().nullish(),PublicData:qe.nullish(),PublishedCount:z.number().nullish(),FollowerCount:z.number().nullish(),IsFollowing:z.boolean().nullish(),Items:z.array(ri).nullish()}).passthrough(),Cm=z.object({Role:z.string().nullish(),Index:z.number().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish(),ServerCopy:z.boolean().nullish()}).passthrough(),vm=z.object({ContentID:z.string().nullish(),Revision:z.number().nullish(),Uploads:z.array(Cm).nullish(),ThumbnailUpload:Cm.nullish(),ExpiresAt:p.nullish()}).passthrough(),Tm=z.object({CreditsConfirmation:me.nullish(),Content:ri.nullish(),Resources:O.nullish()}).passthrough(),Ja=z.object({Content:ri.nullish()}).passthrough(),Am=z.object({ContentID:z.string().nullish(),OptionID:z.string().nullish(),Source:Sm.nullish(),AlreadyOwned:z.boolean().nullish(),AccessActive:z.boolean().nullish(),Settlement:At.nullish(),Resources:O.nullish(),CommissionTaken:ue.nullish()}).passthrough(),nv=z.object({Role:z.string().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish()}).passthrough(),km=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),Revision:z.number().nullish(),AccessVia:WP.nullish(),Files:z.array(nv).nullish(),ThumbnailUrl:z.string().nullish(),ExpiresAt:p.nullish()}).passthrough(),rv=z.object({ContentID:z.string().nullish(),Source:Sm.nullish(),OptionID:z.string().nullish(),PricePaid:ue.nullish(),AcquiredAt:p.nullish(),Content:ri.nullish()}).passthrough(),zm=z.object({Licenses:z.array(rv).nullish(),ContinuationToken: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 Zr=class extends L{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(He.GetDefinitions,e,bm)}browse(e){return this.send(He.Browse,e,Jr)}getContent(e){return this.send(He.GetContent,e,Dm)}getCollection(e){return this.send(He.GetCollection,e,Im)}getCreatorProfile(e){return this.send(He.GetCreatorProfile,e,Pm)}beginUpload(e){return this.send(He.BeginUpload,e,vm)}publish(e){return this.send(He.Publish,e,De(Tm))}updateContent(e){return this.send(He.UpdateContent,e,Ja)}unpublish(e){return this.send(He.Unpublish,e,Ja)}getMyContent(e){return this.send(He.GetMyContent,e,Jr)}acquire(e){return this.send(He.Acquire,e,Am)}getDownload(e){return this.send(He.GetDownload,e,km)}getMyLicenses(e){return this.send(He.GetMyLicenses,e,zm)}getMyFavorites(e){return this.send(He.GetMyFavorites,e,Jr)}};var Yr=class extends L{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let r=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(r,t,i,{throttleKey:`${r}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,sd,"defs")}get(e){return this.sendKeyed("Get",e,fa,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,rd,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,ga,`${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,ya,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,ya,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,ad,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,ud,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,ld,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,cd,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,nd,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,pd,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,fa,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,ga,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Xr=class{settings;emitter;host;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;credits;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;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.host=e.host??L$1(),this.settings=il(e,this.host),this.emitter=new Ii,this.clientPlatform=e.clientPlatform??this.host.getClientPlatform(),this.acquisition=new Ht(this.host),this.acquisition.capture(),this.playtime=new Pi(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{}),this.host.supports.storePurchases&&this.purchase.restorePending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new is({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 os(this.emitter),this.cache=new ls(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 us(this.host.storage,this.settings.titleID),this.api={authentication:new Zn(this),user:new Yn(this),currency:new Xn(this),item:new ir(this),store:new sr(this),purchase:new ar(this),lootbox:new cr(this),reward:new pr(this),quest:new yr(this),tutorial:new dr(this),communityMarketing:new hr(this),chat:new mr(this),push:new fr(this),localization:new gr(this),timedEvent:new Rr(this),leaderboard:new Cr(this),season:new Sr(this),premium:new xr(this),character:new br(this),match:new Dr(this),craft:new Pr(this),ai:new vr(this),collection:new Ar(this),coopEvent:new kr(this),dealOffer:new zr(this),referral:new wr(this),mailbox:new Mr(this),advertising:new Or(this),social:new Er(this),timedBoost:new Br(this),userCustomData:new Lr(this),titleCustomData:new Vr(this),title:new _r(this),gameLoop:new Wr(this),cloudCode:new Kr(this),blockchain:new Qr(this),marketplace:new Hr(this),multiplayer:new $r(this),workshop:new Zr(this),dataCollections:new Yr(this),analytics:new Hn(this),experiment:new $n(this)},this.userService=new fs(this),this.cache.attachState(this.userService),this.auth=new ps(this),this.currency=new ys(this),this.item=new Rs(this),this.store=new Ds(this),this.credits=new Is(this),this.purchase=new Ps(this),this.checkout=new vs(this),this.lootbox=new Ts(this),this.reward=new ks(this),this.quest=new Gs(this),this.tutorial=new ws(this),this.communityMarketing=new Ms(this),this.chat=new Us(this),this.push=new qs(this),this.localization=new Ls(this),this.timedEvent=new Ns(this),this.leaderboard=new $s(this),this.season=new Ys(this),this.premium=new Xs(this),this.character=new sn(this),this.match=new nn(this),this.craft=new rn(this),this.ai=new an(this),this.collection=new ln(this),this.coopEvent=new pn(this),this.dealOffer=new mn(this),this.referral=new fn(this),this.mailbox=new Rn(this),this.ads=new Sn(this),this.social=new Dn(this),this.timedBoost=new In(this),this.userCustomData=new Tn(this),this.titleCustomData=new An(this),this.title=new kn(this),this.gameLoop=new zn(this),this.cloudCode=new wn(this),this.blockchain=new En(this),this.marketplace=new Vn(this),this.multiplayer=new Fn(this),this.workshop=new Nn(this),this.dataCollections=new _n(this),this.analytics=new Kn(this),this.experiments=new Qn(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.host.getFullURL(),RelatedEntityID:a()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var eo=class{ctx;constructor(e){this.ctx=new Xr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Wt(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(n,{...s,...i},z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get credits(){return this.ctx.credits}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get 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 host(){return this.ctx.host}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function av(o){return new eo(o)}var wm="idos_sso",Mm="state",Za="idos:sso:state",lv="https://idosgames.com/sso/",uv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],cv=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function pv(){if(typeof window>"u")return false;let{origin:o}=window.location;return uv.includes(o)||cv.test(o)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function dv(){if(typeof window>"u")return null;let o=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!o)return null;let e=new URLSearchParams(o),t=e.get(wm);if(!t)return null;let i=e.get(Mm)??"",s=yv();return Cv(e),Rv(),s&&i!==s?null:{code:t,state:i}}function hv(o){if(typeof window>"u")return;let e=o.returnTo??mv(),t=fv();gv(t);let i=new URL(o.ssoUrl??lv);i.searchParams.set("title",o.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function mv(){let{origin:o,pathname:e,search:t}=window.location;return `${o}${e}${t}`}function fv(){let o=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(o);else for(let e=0;e<o.length;e++)o[e]=Math.floor(Math.random()*256);return Array.from(o,e=>e.toString(16).padStart(2,"0")).join("")}function gv(o){try{window.sessionStorage.setItem(Za,o);}catch{}}function yv(){try{return window.sessionStorage.getItem(Za)}catch{return null}}function Rv(){try{window.sessionStorage.removeItem(Za);}catch{}}function Cv(o){o.delete(wm),o.delete(Mm);let e=o.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var Sv={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 xv(o,e="Something went wrong. Please try again."){return o?Sv[o]??o:e}function bv(o,e){return !!o?.Claims?.[e]?.ClaimedAt}function Dv(o){let e=o?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function Iv(o,e){return o?.Claims?.[e]?.PremiumTiers??[]}function Em(o,e,t,i=1){if(!o)return e;let s=o.Base??e,n=Math.max(0,t-i),r;switch(o.Shape??"Flat"){case "PerStep":r=s+(o.PerStep??0)*n;break;case "PerStepRate":r=s*(1+(o.PerStepRate??0)*n);break;case "Geometric":r=s*Math.pow(1+(o.GrowthRate??0),n);break;case "Table":r=s*Om(o,t,1);break;case "TableAbsolute":r=Om(o,t,s);break;default:r=s;break}return Number.isNaN(r)?s:(o.MinResult!=null&&r<o.MinResult&&(r=o.MinResult),o.MaxResult!=null&&r>o.MaxResult&&(r=o.MaxResult),r)}function Pv(o,e,t=1){return Em(o,1,e,t)}function vv(o){if(!o)return false;switch(o.Shape??"Flat"){case "PerStep":return (o.PerStep??0)!==0;case "PerStepRate":return (o.PerStepRate??0)!==0;case "Geometric":return (o.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return Um(o.Points).length>0;default:return o.MinResult!=null||o.MaxResult!=null}}function Tv(o){if(Number.isNaN(o)||o<=0)return 0;if(!Number.isFinite(o))return Number.MAX_SAFE_INTEGER;let e=Math.round(o);return Math.abs(o-e)<=1e-9*Math.max(1,Math.abs(o))?e:Math.ceil(o)}function Um(o){if(!o)return [];let e=[];for(let t of o)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function Om(o,e,t){let i=Um(o.Points);if(i.length===0)return t;let s=null,n=null,r=null;for(let c of i)(r===null||c.AtStep>r.AtStep)&&(r=c),c.AtStep<=e&&(s===null||c.AtStep>=s.AtStep)&&(s=c),c.AtStep>e&&(n===null||c.AtStep<n.AtStep)&&(n=c);if(s===null)return t;if(n===null){let c=o.TailGrowthRate??0;return c===0?r.Value:r.Value*Math.pow(1+c,e-r.AtStep)}switch(o.Interpolation??"Step"){case "Linear":{let c=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+c*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let h=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+h*(n.Value-s.Value)}let c=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,c)}default:return s.Value}}var Av={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Ya=z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),kv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},zv=z.enum(["Top","Bottom","Left","Right"]).catch("Top"),wv=z.object({PlacementID:z.string().nullish(),Type:Ya.nullish(),Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),CreditsRewarded:z.number().nullish(),AllowedProviderIDs:z.array(z.string()).nullish()}).passthrough(),Mv=z.object({DefaultCreditsPerView:z.number().nullish(),MaxCreditsBalance:z.number().nullish(),DailyCreditEarnCap:z.number().nullish(),DailyViewCap:z.number().nullish(),MinSecondsBetweenViews:z.number().nullish()}).passthrough(),Ov=z.object({CooldownSeconds:z.number().nullish(),MinSessionTimeBeforeFirstSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),Ev=z.object({Enabled:z.boolean().nullish(),Position:zv.nullish(),RefreshIntervalSeconds:z.number().nullish()}).passthrough(),Uv=z.object({Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish()}).passthrough(),qv=z.object({MaxImpressionsPerHour:z.number().nullish(),MaxImpressionsPerDay:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),Bv=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),DisableInterstitials:z.boolean().nullish(),DisableBanners:z.boolean().nullish(),DisableAppOpen:z.boolean().nullish()}).passthrough(),Lv=z.object({RequirePersonalizedAdsConsent:z.boolean().nullish(),RequireTrackingConsent:z.boolean().nullish(),CurrentPolicyVersion:z.string().nullish(),RegulatedRegions:z.array(z.string()).nullish()}).passthrough(),Gv=z.object({RequireServerSideVerification:z.boolean().nullish(),PendingRequestTtlSeconds:z.number().nullish(),MaxPendingRequestsPerUser:z.number().nullish()}).passthrough(),Vv=z.object({AndroidUnitID:z.string().nullish(),IosUnitID:z.string().nullish(),WebUnitID:z.string().nullish(),Type:Ya.nullish()}).passthrough(),Fv={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},Nv=z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),jv=z.object({ProviderID:z.string().nullish(),Kind:Nv.nullish(),Enabled:z.boolean().nullish(),Priority:z.number().nullish(),AndroidAppID:z.string().nullish(),IosAppID:z.string().nullish(),WebAppID:z.string().nullish(),Units:z.record(z.string(),Vv).nullish()}).passthrough();z.object({Enabled:z.boolean().nullish(),Placements:z.record(z.string(),wv).nullish(),Providers:z.record(z.string(),jv).nullish(),RewardedVideo:Mv.nullish(),Interstitial:Ov.nullish(),Banner:Ev.nullish(),AppOpen:Uv.nullish(),FrequencyCapping:qv.nullish(),PremiumAdReductions:z.array(Bv).nullish(),Consent:Lv.nullish(),Verification:Gv.nullish()}).passthrough();var _v=z.object({RewardedVideoCredit:z.number().nullish(),TotalEarned:z.number().nullish(),TotalSpent:z.number().nullish()}).passthrough(),Wv=z.object({PlacementID:z.string().nullish(),LastShownAt:p.nullish(),LastCompletedAt:p.nullish(),TotalImpressions:z.number().nullish(),TotalCompletions:z.number().nullish(),ConsecutiveFailures:z.number().nullish()}).passthrough(),Kv=z.object({Date:p.nullish(),ImpressionsByPlacement:z.record(z.string(),z.number()).nullish(),CompletionsByPlacement:z.record(z.string(),z.number()).nullish(),TotalImpressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish(),AppOpenImpressions:z.number().nullish(),CreditsEarnedToday:z.number().nullish()}).passthrough(),Qv=z.object({SessionID:z.string().nullish(),SessionStartAt:p.nullish(),Impressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish()}).passthrough(),Hv=z.object({PersonalizedAdsConsent:z.boolean().nullish(),TrackingConsent:z.boolean().nullish(),PolicyVersion:z.string().nullish(),Region:z.string().nullish(),ConsentGivenAt:p.nullish(),ConsentRevokedAt:p.nullish()}).passthrough(),$v=z.object({RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),Type:Ya.nullish(),IssuedAt:p.nullish(),ExpiresAt:p.nullish(),CreditsToAward:z.number().nullish()}).passthrough(),Jv=z.object({InvalidSsvCount:z.number().nullish(),OrphanCompletions:z.number().nullish(),FastCompletions:z.number().nullish(),LastFlaggedAt:p.nullish()}).passthrough();z.object({Credits:_v.nullish(),Placements:z.record(z.string(),Wv).nullish(),Daily:Kv.nullish(),Session:Qv.nullish(),LastImpressionAt:p.nullish(),LastInterstitialAt:p.nullish(),LastRewardedAt:p.nullish(),LastAppOpenAt:p.nullish(),TotalImpressions:z.number().nullish(),TotalRewardedCompletions:z.number().nullish(),AdsDisabledUntil:p.nullish(),Consent:Hv.nullish(),PendingRequests:z.record(z.string(),$v).nullish(),FraudFlags:Jv.nullish(),UpdatedAt:p.nullish()}).passthrough();
|
|
2
|
+
export{Be as AIAction,sR as AIErrorCode,Zt as AIGenerationStatus,Ft as AIModality,Ht as AcquisitionCapture,Fv as AdProviderKind,Av as AdType,Cn as AdvertisingAction,xa as AnalyticsAction,Yx as AnalyticsDropReason,Sa as AnalyticsEventNaming,It as AnalyticsLimits,kI as AttackOutcome,Le as AuthenticationAction,_t as AutomaticEvent,kv as BannerPosition,Ze as BlockchainAction,aS as BlockchainNetworkType,Rp as BlockchainOperationCategory,gS as BlockchainTransactionStatus,pS as BlockchainTransactionType,_S as BodyPart,CI as BoostWindowKind,We as CharacterAction,$e as ChatAction,Kg as ChatAuthorType,_g as ChatBlockedTermAction,Gg as ChatChannelType,Ng as ChatDirectAudience,Vg as ChatPartitioning,Hg as ChatReportReason,Ha as CloudCodeAction,kP as CloudCodeErrorCode,TP as CloudCodeLogLevel,vP as CloudCodeRevisionSelection,Ke as CollectionAction,cx as CommissionSink,cP as CommunityChestMemberStatus,uP as CommunityChestStatus,TD as CommunityCreatorStatus,ti as CommunityMarketingAction,kD as CommunityMetricKind,PD as CommunityParticipationMode,AD as CommunityPayoutCurrencyKind,$C as ConversionRateMode,Rt as CoopEventAction,RR as CoopGroupStatus,CR as CoopMemberStatus,Ir as CraftAction,ND as CraftInputSelectionMode,VD as CraftOutputLevelMode,_D as CraftOutputLevelOverflow,GD as CraftType,Ti as CreditsConfirmationStatus,yg as CreditsError,Oi as CurrencyAction,HC as CurrencyStatus,rf as CurveInterpolation,sf as CurveShape,Mt as CustomDataBucket,GC as CustomDataValueType,UC as CustomDataWriter,tl as DEFAULT_BASE_URL,zx as DataAccessMode,vx as DataCollectionKind,Lx as DataCollectionSchemaMode,Qx as DataCollectionsAction,Ex as DataCounterKind,Ax as DataFieldType,kx as DataFieldVisibility,qx as DataOwnerDeletedPolicy,Mx as DataRefKind,BR as DealComparisonOperator,kR as DealNodeRuntimeStatus,qR as DealNodeType,bt as DealOfferAction,AR as DealOfferActivationStatus,Wn as EVENT_NAME_PATTERN,SP as EnvelopeType,Ia as ExperimentAction,ub as ExperimentGoalKind,wC as FRIENDS_FROM_PLATFORM,bb as FodderSelectionMode,Sb as FodderValuationMode,RC as FriendActionStatus,CC as FriendSource,Ve as GameLoopAction,eo as IDosGamesClient,Ub as IapProductType,$b as IapPurchaseStatus,er as ItemAction,dS as KycStatus,mS as KycTier,_e as LeaderboardAction,Jn as LocalizationAction,mb as LocalizationMissingKeyMode,ur as LootboxAction,oC as MAILBOX_COUNTER_CAP,nt as MailboxAction,eC as MailboxCategory,rC as MailboxErrors,tC as MailboxLetterSource,sC as MailboxRewardModule,Bn as MarketGoodsType,ux as MarketOfferStatus,lx as MarketOfferType,Me as MarketplaceAction,Dt as MatchAction,WS as MatchStatus,Ye as MultiplayerAction,yP as MultiplayerChatMode,gP as MultiplayerTopology,Bg as OFFER_NOT_IN_ROTATION,Ko as PLATFORM_AD_PROVIDER,OC as PlatformFriendsMode,MC as PlatformProfileMode,PS as PlayAccessMode,db as PlayerExperimentStatus,Pi as PlaytimeTracker,Xt as PremiumAction,ei as PurchaseAction,fi as PushAction,Je as PushPermissionState,ly as PushTopic,oy as PushTransport,gt as QuestAction,gf as QuestObjectiveSource,Rf as QuestPrerequisiteMode,hf as QuestStatus,TI as RaidMode,Kt as ReferralAction,Pt as RewardAction,pD as RewardWindowBoost,RP as RoomVisibility,iR as SKIN_ALREADY_OWNED,Uo as SKIN_SLOT,Gt as SeasonAction,Se as SocialAction,IC as SocialContentStatus,xC as SocialEntityType,PC as SocialInboxVerb,bC as SocialReactionKind,DC as SocialReportReason,AI as SpecialChoiceMode,zt as StoreAction,Sg as StoreRotationMode,Ob as StoreType,si as TimedBoostAction,uI as TimedBoostStackingPolicy,ct as TimedEventAction,ni as TitleAction,Vi as TitleCustomDataAction,bI as TitleDataBucket,xI as TitleDataScope,JD as TradeOfferStatus,yS as TransactionDirection,lt as TutorialAction,Of as TutorialBoardAction,zf as TutorialFlowStatus,Jm as TutorialGateMode,Af as TutorialRestartPolicy,Mf as TutorialScriptModule,vf as TutorialStepCompletionMode,Ii as TypedEmitter,dt as UserAction,Ct as UserCustomDataAction,bS as WalletGateBalanceSource,uS as WalletLinkType,OP as WorkshopAccessMode,_P as WorkshopAccessVia,He as WorkshopAction,VP as WorkshopContentStatus,qP as WorkshopHoldingMatch,EP as WorkshopHoldingMode,NP as WorkshopLicenseSource,jP as WorkshopSort,LP as WorkshopVisibility,xv as authErrorText,hv as beginSsoRedirect,Dv as claimedMilestoneIDs,av as createIDosGamesClient,ci as cryptoShortfallFromError,Pv as curveMultiplier,ig as defineView,Cd as describeUserAgent,Em as evaluateCurve,Iv as grantedPremiumTiers,ki as isAIGenerationTerminal,vv as isCurveConfigured,bv as isMilestoneClaimed,Wy as isReservedSlot,pv as isSsoAvailable,On as normalizeBlockchainCategory,nR as parseAIErrorCode,dv as readSsoCodeFromUrl,Tv as roundAmount,$x as where,gg as zPaymentProof,Cs as zPriceOption,oe as zPriceOptions};
|