@idosgames/core 0.24.0 → 0.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/dist/{VoiceController-B6naztyl.d.cts → VoiceController-Cqj-uRGO.d.cts} +58 -5
- package/dist/{VoiceController-5wloz5B8.d.ts → VoiceController-DhJv6fTF.d.ts} +58 -5
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/realtime/index.d.cts +2 -2
- package/dist/realtime/index.d.ts +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {e,d,o,p,l,m,f}from'./chunk-LWS7EEOF.js';export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,q as NoopPlatformAdapter,h as PLATFORM_BRIDGE_ACK,n as PLATFORM_CREDITS_CONFIRM_MESSAGES,f as PLATFORM_ORIGINS,i as PLATFORM_PAGE_UNAVAILABLE,r as PLATFORM_SIGN_IN_MESSAGES,k as PLATFORM_TOPUP_MESSAGES,j as askPlatformPage,o as canUsePlatformCreditsConfirm,s as canUsePlatformSignIn,l as canUsePlatformTopUp,v as clearPlatformSignInDeclined,g as isPlatformParentOrigin,w as isPlatformSignInDeclined,u as markPlatformSignInDeclined,p as requestPlatformCreditsConfirm,t as requestPlatformSignIn,m as requestPlatformTopUp}from'./chunk-LWS7EEOF.js';import {b,a,c as c$1}from'./chunk-CS7ACWDY.js';export{e as isFail,d as isOk}from'./chunk-CS7ACWDY.js';import {z}from'zod';import _t from'decimal.js';var Ci=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 Fm(){let o=new Map;return {get:e=>o.get(e)??null,set:(e,t)=>{o.set(e,t);},remove:e=>{o.delete(e);}}}function Ka(){return Vm()??Fm()}function Vm(){try{let o=globalThis.localStorage;if(!o)return null;let e="__idos_probe__";return o.setItem(e,"1"),o.removeItem(e),{get:t=>{try{return o.getItem(t)}catch{return null}},set:(t,i)=>{try{o.setItem(t,i);}catch{try{o.removeItem(t);}catch{}}},remove:t=>{try{o.removeItem(t);}catch{}}}}catch{return null}}var Qa="https://api.idosgames.com";function Ha(o){return {titleID:o.titleID,titleTemplateID:o.titleTemplateID??"default",buildKey:o.buildKey??"",baseUrl:(o.baseUrl??Qa).replace(/\/+$/,""),devBuild:o.devBuild??false,debugLogging:o.debugLogging??false,configStorage:o.configStorage??Ka(),locale:o.locale??Nm(),appVersion:o.appVersion??""}}function Nm(){try{return globalThis.navigator?.language??""}catch{return ""}}var $r="idos_acq",$a=["gclid","fbclid","ttclid","msclkid","yclid"],jm=["ref","r"],_m=["ref_","ref-","ref=","r_","r-"];var Nt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();Wm(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=Hm(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($r);}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=Ya(Za(t));if(i)return i}return Bi(t)}readFromEnvironment(){let e={},t=Za(this.platform.getFullURL());Vt(e,"UtmSource",t.get("utm_source")),Vt(e,"UtmMedium",t.get("utm_medium")),Vt(e,"UtmCampaign",t.get("utm_campaign")),Vt(e,"UtmTerm",t.get("utm_term")),Vt(e,"UtmContent",t.get("utm_content")),Vt(e,"ClaimToken",t.get("idos_click"));for(let R of $a){let V=t.get(R);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",s=Qm(i);if(s){for(let R of Km)Vt(e,R,s.get(Xa[R])??null);for(let R of $a){let V=s.get(R);if(V){e.ClickID=V;break}}}let n=Bi(s?s.get("ref")??s.get("r")??"":i),r=Ya(t),p=n||r;p&&(e.ReferralCode=p,e.ChannelHint=n?"telegram":"query");let d=this.platform.getReferrer?.();return d&&(e.Referrer=d),e}read(){try{let e=this.platform.storage.getString($r);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($r,JSON.stringify(e));}catch{}}};function Wm(o){return !!(o.UtmSource||o.UtmMedium||o.UtmCampaign||o.ClickID||o.Referrer||o.ReferralCode||o.ClaimToken)}function Vt(o,e,t){t&&(o[e]=t);}var Ja="a1_",Xa={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},Km=Object.keys(Xa);function Qm(o){let e=(o||"").trim();if(!e.startsWith(Ja))return null;let t=e.slice(Ja.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,d=>d.charCodeAt(0)),r=new TextDecoder().decode(n),p=new URLSearchParams(r);return [...p.keys()].length>0?p:null}catch{return null}}function Za(o){try{let e=o.indexOf("?");return new URLSearchParams(e>=0?o.slice(e):"")}catch{return new URLSearchParams}}function Ya(o){for(let e of jm){let t=o.get(e);if(t)return Bi(t)}return null}function Bi(o){let e=(o||"").trim();if(!e)return null;for(let t of _m)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Hm(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 el="idos_usage_pending",tl="idos_usage_session",il="idos_usage_closed_session",sl="idos_usage_new_session",nl="idos_usage_last_activity",Si=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(el),this.currentSessionSeconds=this.readNumber(tl),this.pendingClosedSessionSeconds=this.readNumber(il),this.isNewSessionPending=this.readNumber(sl)!==0;let e=this.readNumber(nl);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(el,this.pendingSeconds),this.writeNumber(tl,this.currentSessionSeconds),this.writeNumber(il,this.pendingClosedSessionSeconds),this.writeNumber(sl,this.isNewSessionPending?1:0),this.writeNumber(nl,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 ut={Virtual:"Virtual",Crypto:"Crypto"},ii=z.enum(["Virtual","Crypto"]).catch("Virtual"),Li={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},si=z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),mt={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Gi=z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),$m={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Fi=z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),Jm={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Vi=z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),Zm={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},xi=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 ol(){let o=globalThis,e=o.Capacitor?.getPlatform?.();if(e)return rl(e);let t=o.cordova?.platformId;return t?rl(t):o.navigator?.userAgent??""?mt.Web:mt.Unknown}function rl(o){let e=o.toLowerCase();return e==="android"?mt.Android:e==="ios"?mt.Ios:e==="web"?mt.Web:mt.Unknown}var _=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}),c=z.string();var Jr=z.object({Type:si.nullish(),CurrencyID:z.string().nullish(),Amount:_.nullish(),AmountUsd:z.number().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ProductID:z.string().nullish()}),Ym=z.object({Type:Vi.nullish(),EntityID:z.string()}),Xm=z.object({Address:Ym.nullish(),Amount:_.nullish(),Source:z.string().nullish()}),ue=z.object({Entries:z.array(Jr).nullish(),EventTokens:z.array(Xm).nullish()}),al=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(al).nullish()}),xt=z.object({Standard:ue.nullish(),PremiumDiscounts:z.array(z.unknown()).nullish(),PremiumTiers:z.array(al).nullish()}),M=z.object({Grant:H.nullish(),Consume:xt.nullish()}),bt=z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Transferred:ue.nullish()});var ef=z.object({ExperimentID:z.string().nullish(),Variants:z.array(z.string()).nullish()}).passthrough(),tf={Completed:"Completed",Started:"Started",StepReached:"StepReached"},sf=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:ef.nullish(),Tutorial:sf.nullish(),Platforms:z.array(Gi).nullish()}).passthrough();var ye=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 nf=z.object({OffsetSecondsFromParentStart:z.number().nullish(),DurationSeconds:z.number().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),rf=z.object({StartUtc:z.string().nullish(),EndUtc:z.string().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),of=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 af=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 st=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:ye.nullish()}).passthrough(),me=z.object({Mode:z.string().nullish(),IsActive:z.boolean().nullish(),Scheduled:rf.nullish(),Chain:of.nullish(),Cyclic:af.nullish(),ActivationTriggers:z.array(st).nullish(),Relative:nf.nullish()}).passthrough();var lf={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},uf=z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),cf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},pf=z.enum(["Step","Linear","Geometric"]).catch("Step"),hf=z.object({AtStep:z.number().nullish(),Value:z.number().nullish()}).passthrough(),Fe=z.object({Base:z.number().nullish(),Shape:uf.nullish(),PerStep:z.number().nullish(),PerStepRate:z.number().nullish(),GrowthRate:z.number().nullish(),Points:z.array(hf).nullish(),Interpolation:pf.nullish(),TailGrowthRate:z.number().nullish(),MinResult:z.number().nullish(),MaxResult:z.number().nullish()}).passthrough();var df=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Rewards:H.nullish()}).passthrough(),mf=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Multiplier:z.number().nullish()}).passthrough(),Zr=z.object({Bundles:z.array(df).nullish(),Multipliers:z.array(mf).nullish()}).passthrough();var ff=z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Ni=z.object({Source:ff.nullish(),SourceKey:z.string().nullish(),Curve:Fe.nullish(),Anchor:z.number().nullish(),IncludeRewards:ue.nullish(),ExcludeRewards:ue.nullish()}).passthrough(),ll=z.object({ClaimedAt:z.string().nullish(),PremiumTiers:z.array(z.string()).nullish(),Unlocked:z.boolean().nullish()}).passthrough(),Be=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:Zr.nullish(),SortOrder:z.number().nullish(),IsFeatured:z.boolean().nullish()}).passthrough(),ni=z.object({Milestones:z.record(z.string(),Be).nullish()}).passthrough();var K=z.object({PresetID:z.string().nullish(),Remove:z.array(z.string()).nullish()}).passthrough();var gf=z.object({TargetCurrencyID:z.string().nullish(),Rate:z.number().nullish(),MaxConvertAmount:z.number().nullish()}).passthrough(),jt=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:gf.nullish()}).passthrough();var yf=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),ul=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:c,ExpiresAt:c.nullish(),EquippedSlot:yf.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Q=z.object({ChangedInstances:z.record(z.string(),ul).nullish(),RemovedInstanceIDs:z.array(z.string()).nullish()});var Pe=o=>z.object({Id:z.string(),Success:z.boolean(),Error:z.string().nullish(),Data:o.nullish()}),ft=o=>z.object({ServerTimeUtc:c,Items:z.array(Pe(o)),Resources:M.nullish(),Inventory:Q.nullish()});var Rf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},cl=z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Cf=z.object({}).passthrough().transform(o=>o),Sf=z.object({CycleID:z.string(),InstanceKey:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),CycleStartUtc:c.nullish(),CycleEndUtc:c.nullish(),PointsTotalEarned:_.nullish(),PointsCurrent:_.nullish(),ClaimedPointMilestoneIDs:z.array(z.string()).nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),Yr=z.object({QuestID:z.string(),CycleID:z.string().nullish(),ObjectiveID:z.string().nullish(),NewValue:_.nullish(),ObjectiveCompleted:z.boolean().nullish(),Status:cl}),pl=z.object({State:Cf.nullish(),PointsTracks:z.record(z.string(),Sf).nullish()}),Xr=z.object({ServerTimeUtc:c,QuestID:z.string(),CycleID:z.string().nullish(),NewStatus:cl.nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),eo=z.object({ServerTimeUtc:c,CycleID:z.string(),MilestoneID:z.string(),PointsTotalEarned:_.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),hl=z.object({ServerTimeUtc:c,CycleID:z.string(),GroupCompletionID:z.string(),GroupID:z.string().nullish(),CompletedGroupQuests:z.number().nullish(),RequiredGroupQuests:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),dl=z.object({MetricID:z.string(),Updates:z.array(Yr).nullish()}),ml=z.array(Pe(Xr)),fl=z.array(Pe(eo)),xf={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},bf=z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Df={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Pf=z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),gl=z.object({ObjectiveID:z.string().nullish(),Source:bf.nullish(),MaxProgressPerCall:z.number().nullish(),MetricID:z.string().nullish(),Triggers:z.array(st).nullish(),TargetValue:z.number().nullish(),AggregationMethod:z.string().nullish()}).passthrough(),to=z.object({Milestones:K.nullish(),Linking:K.nullish(),Availability:K.nullish(),Reward:K.nullish(),Objectives:K.nullish()}).passthrough(),If=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(),yl=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:Pf.nullish()}).passthrough(),Rl=z.object({Schedule:me.nullish(),AccrueProgressWhenLocked:z.boolean().nullish(),Gate:Z.nullish(),Limits:ye.nullish()}).passthrough(),Cl=z.object({Grant:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),vf=z.object({QuestID:z.string().nullish(),Identity:If.nullish(),Linking:yl.nullish(),Availability:Rl.nullish(),Objectives:z.record(z.string(),gl).nullish(),Reward:Cl.nullish(),Presets:to.nullish()}).passthrough(),Tf=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(),kf=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(),Be).nullish(),Presets:to.nullish(),PointsToken:jt.nullish()}).passthrough(),Af=z.object({Milestones:z.record(z.string(),ni).nullish(),Linking:z.record(z.string(),yl).nullish(),Availability:z.record(z.string(),Rl).nullish(),Reward:z.record(z.string(),Cl).nullish(),Objectives:z.record(z.string(),z.record(z.string(),gl)).nullish()}).passthrough(),zf=z.object({CycleID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:me.nullish(),Milestones:z.record(z.string(),Be).nullish(),Gate:Z.nullish(),PointsToken:jt.nullish(),GroupCompletions:z.record(z.string(),Tf).nullish(),Phases:z.record(z.string(),kf).nullish(),Presets:to.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(),zf).nullish(),Quests:z.record(z.string(),vf).nullish(),Presets:Af.nullish()}).passthrough(),pt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var wf={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},Mf=z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),Of={Never:"Never",OnRequest:"OnRequest",Always:"Always"},Ef=z.enum(["Never","OnRequest","Always"]).catch("Never"),Uf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},qf=z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),Bf={GameLoop:"GameLoop"},Lf={Raid:"Raid",Attack:"Attack"},Gf=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(),Ff=z.object({Mode:Mf.nullish(),Triggers:z.array(st).nullish(),TargetValue:z.number().nullish(),RequireAllTriggers:z.boolean().nullish()}).passthrough(),Vf=z.object({Grant:H.nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),Nf=z.object({TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),RandomActionType:z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),jf=z.object({Module:z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:Nf.nullish(),MaxUses:z.number().nullish()}).passthrough(),_f=z.object({Skippable:z.boolean().nullish(),TimeoutSeconds:z.number().nullish()}).passthrough(),io=z.object({StepID:z.string().nullish(),Order:z.number().nullish(),Identity:Gf.nullish(),Completion:Ff.nullish(),Effects:Vf.nullish(),Script:jf.nullish(),Policy:_f.nullish()}).passthrough(),Wf=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(),Sl=z.object({Schedule:me.nullish(),Gate:Z.nullish(),RequiredFlowIDs:z.array(z.string()).nullish(),AutoStart:z.boolean().nullish(),StartTrigger:st.nullish()}).passthrough(),xl=z.object({Skippable:z.boolean().nullish(),SkippableFromOrder:z.number().nullish(),RestartPolicy:Ef.nullish(),ExpireAfterSeconds:z.number().nullish(),IsBlocking:z.boolean().nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),bl=z.object({Grant:H.nullish(),AutoClaim:z.boolean().nullish()}).passthrough(),Kf=z.object({Availability:K.nullish(),Policy:K.nullish(),Reward:K.nullish(),Steps:K.nullish()}).passthrough(),Qf=z.object({FlowID:z.string().nullish(),Identity:Wf.nullish(),Availability:Sl.nullish(),Policy:xl.nullish(),Steps:z.record(z.string(),io).nullish(),Reward:bl.nullish(),Presets:Kf.nullish()}).passthrough(),Hf=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:Hf.nullish()}).passthrough(),Jf=z.object({Availability:z.record(z.string(),Sl).nullish(),Policy:z.record(z.string(),xl).nullish(),Reward:z.record(z.string(),bl).nullish(),Steps:z.record(z.string(),z.record(z.string(),io)).nullish()}).passthrough(),Dl=z.object({Flows:z.record(z.string(),Qf).nullish(),Settings:$f.nullish(),Presets:Jf.nullish()}).passthrough(),Zf=z.object({}).passthrough().transform(o=>o),Pl=z.object({FlowID:z.string(),Status:qf,CurrentStepID:z.string().nullish(),CurrentStep:io.nullish(),TotalSteps:z.number(),CompletedSteps:z.number(),CanSkip:z.boolean(),RewardClaimed:z.boolean(),RewardPending:z.boolean(),VariantID:z.string().nullish()}).passthrough(),Wi=z.object({State:Zf.nullish(),Flows:z.array(Pl).nullish(),UnlockedFeatures:z.array(z.string()).nullish()}).passthrough(),wt=z.object({Flow:Pl.nullish()}).passthrough(),Il=z.object({FlowID:z.string().nullish(),Granted:M.nullish()}).passthrough(),vl=z.array(Pe(wt)),Tl=z.object({FlowID:z.string(),StepID:z.string(),Progress:z.number(),Target:z.number(),Completed:z.boolean()}).passthrough(),nt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Ki(o){return Array.isArray(o)?o.filter(e=>e!==null).map(Ki):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).filter(([,e])=>e!==null).map(([e,t])=>[e,Ki(t)])):o}var Qi=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 Hi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function kl(o){return o===429||o>=500&&o<=599}function $i(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 Mt(o){return new Promise(e=>setTimeout(e,o))}var Al=15e3;async function zl(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 wl(o,e=Math.random){return o+10+Math.min(250,o*.2)*e()}function Ml(o,e=Math.random){let t=o<=1?1500:o===2?4e3:6e3;return t+t*.1*e()}var so=15,Ol=1e3,Ji=class{constructor(e=so,t=()=>Date.now(),i=Mt){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]>=Ol;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(Ol-(e-this.starts[0])+5);}}};var Yf=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function oi(o){if(!o)return null;let e=Yf.exec(o);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new _t(i),r=new _t(s),p=r.minus(_t.max(n,0));return p.lte(0)?null:{currencyID:t,required:r.toNumber(),available:n.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var Xf=12e3,eg=new Set(["RelatedEntityID"]);function tg(o,e){if(e===null||typeof e!="object"||Array.isArray(e))return o;let t={};for(let[i,s]of Object.entries(e))eg.has(i)||(t[i]=s);try{return `${o}|${JSON.stringify(t)}`}catch{return o}}var ig=z.object({Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().optional(),QuestProgress:z.array(Yr).nullish(),TutorialProgress:z.array(Tl).nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish()}).passthrough(),Zi=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Hi;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 Qi(e.throttleMs),this.pacer=new Ji(e.maxRequestsPerSecond??so),this.clientPlatform=e.clientPlatform??mt.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??tg(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}`,p=JSON.stringify(t),d=s.ticket??null,R=s.silent??!1,V=s.timeoutMs??Xf,oe=s.autoRetry??!0,Ie=!1,ge=!1,Me=0;for(;;){let St;s.keepalive||await this.pacer.take();try{St=await this.doFetch(r,p,d,V,s.keepalive??!1);}catch{if(oe&&Me<3){Me++,await Mt($i(Me));continue}return this.connectionFailure("Internet Connection Error",R)}let Je=St.status;if(Je>=200&&Je<300){let ne=!ge&&this.cryptoTopUpHandler!==null,De=await this.parseSuccess(St,i,R,e,ne);if(!De.ok&&ne){let ce=oi(De.error);if(ce){if(ge=!0,await this.runTopUp(ce))continue;R||this.emitter.emit("error:global",De.error);}}return De}if(Je===401){if(!Ie&&this.sessionRefreshHandler){Ie=!0;let ne=null;try{ne=await this.sessionRefreshHandler();}catch{ne=null;}if(ne){d=ne;continue}}return this.emitter.emit("auth:unauthorized",void 0),b("unauthorized","Unauthorized")}if(kl(Je)){let ne=Je===429?await zl(St):null;if(ne!==null&&ne>Al)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ne/1e3)} s`,R);if(oe&&Me<3){Me++,await Mt(ne!==null?wl(ne):Je===429?Ml(Me):$i(Me));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Je})`,R)}let yi="";try{yi=await St.text();}catch{}if(Je===409&&/operation in progress/i.test(yi)&&oe&&Me<3){Me++,await Mt($i(Me));continue}return this.handleWebError(yi,Je,R)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let r=new AbortController,p=setTimeout(()=>{r.abort();},s);try{let d={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(d.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:d,signal:r.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(p);}}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 p;try{p=JSON.parse(r);}catch{return this.globalError("JSON Parse Error",i)}let d=ig.safeParse(p);if(!d.success)return this.globalError("Malformed response envelope",i);if(!d.data.Success){let ge=d.data.Error??"Server returned Success=false",Me=n&&oi(ge);return !i&&!Me&&this.emitter.emit("error:global",ge),b("server",ge)}let R=d.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:d.data.StateEpoch??null,versions:R});let V=d.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);let oe=d.data.TutorialProgress;oe&&oe.length>0&&this.emitter.emit("tutorial:systemProgress",oe);let Ie=t.safeParse(d.data.Data);if(!Ie.success){let ge=t.safeParse(Ki(d.data.Data));ge.success&&(Ie=ge);}if(!Ie.success){let ge=`Validation error (${s}): ${Ie.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",ge),i||this.emitter.emit("error:global",ge),b("validation",ge)}return a(Ie.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 ai(o){return (typeof o=="string"?o:o.toISOString()).slice(0,10)}function bi(o){return `${ai(o)}T00:00:00.000Z`}function El(o){let e=new Date(o);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function Ul(o,e){return new Date(o.getTime()+e*6e4).toISOString()}function oo(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(),p=new Map,d$1=new Map,R=new Map,V=new Map,oe=new Map,Ie=new Map,ge=new Map,Me=new Map,St=e.Grant?.PremiumTiers??[],Je=St.length;for(let ne=0;;ne++){let De,ce;if(ne===0)De=e.Grant?.Standard?.Entries,ce=false;else if(ne-1<Je)De=St[ne-1]?.Resources?.Entries,ce=false;else if(ne===1+Je)De=e.Consume?.Standard?.Entries,ce=true;else break;if(De)for(let ae of De){if(ae.Type==null)continue;let pe=Math.max(0,ae.Amount??0);if(!(pe<=0))switch(ae.Type){case "VirtualCurrency":{if(!ae.CurrencyID)continue;let he=ce?d$1:p;he.set(ae.CurrencyID,(he.get(ae.CurrencyID)??0)+pe);break}case "CryptoCurrency":{if(!ae.CurrencyID)continue;let he=ce?V:R;he.set(ae.CurrencyID,(he.get(ae.CurrencyID)??new _t(0)).plus(pe));break}case "Item":{if(!ae.ItemID)continue;let he=ng(t,ae.CatalogID,ae.ItemID),Se=(he?he.IsStackable??true:true)?ce?Ie:oe:ce?Me:ge;Se.set(ae.ItemID,(Se.get(ae.ItemID)??0)+pe);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||d$1.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let ne of new Set([...p.keys(),...d$1.keys()])){let De=p.get(ne)??0,ce=d$1.get(ne)??0,ae=De-ce,pe=n.VirtualCurrencies[ne];pe?(pe.Amount+=ae,pe.UpdatedAt=r,pe.Daily&&ai(pe.Daily.PeriodStartUtc)===ai(i)?(pe.Daily.Earned+=De,pe.Daily.Spent+=ce):pe.Daily={PeriodStartUtc:bi(i),Earned:De,Spent:ce}):n.VirtualCurrencies[ne]={Amount:ae,CreatedAt:r,UpdatedAt:r,Daily:{PeriodStartUtc:bi(i),Earned:De,Spent:ce}};}}if(s.ccChanged=R.size>0||V.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let ne of new Set([...R.keys(),...V.keys()])){let De=R.get(ne)??new _t(0),ce=V.get(ne)??new _t(0),ae=De.minus(ce),pe=n.CryptoCurrencies[ne];pe?(pe.Amount=new _t(pe.Amount).plus(ae).toString(),pe.UpdatedAt=r):n.CryptoCurrencies[ne]={Amount:ae.toString(),Frozen:"0",CreatedAt:r,UpdatedAt:r};}}if(s.itemsChanged=oe.size>0||Ie.size>0||ge.size>0||Me.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let ne=n.UnstackableItems,De=new Set([...oe.keys(),...Ie.keys(),...ge.keys(),...Me.keys()]);for(let ce of De){let ae=(oe.get(ce)??0)-(Ie.get(ce)??0),pe=(ge.get(ce)??0)-(Me.get(ce)??0),he=ae+pe,it=n.Items[ce];it?(ae!==0&&(it.StackableAmount+=ae),pe!==0&&(it.UnstackableAmount+=pe),he!==0&&(it.TotalAmount+=he)):n.Items[ce]={StackableAmount:Math.max(0,ae),UnstackableAmount:Math.max(0,pe),TotalAmount:Math.max(0,he)};}for(let[ce,ae]of Me){if(ae<=0)continue;let pe=Object.values(ne).filter(he=>he.ItemID===ce&&he.EquippedSlot==null&&(he.ExpiresAt==null||new Date(he.ExpiresAt)>i)).sort(sg).slice(0,ae).map(he=>he.ItemInstanceID);for(let he of pe)delete ne[he];}for(let[ce,ae]of ge){let pe=rg(t,ce);for(let he=0;he<ae;he++){let it=d();ne[it]={ItemInstanceID:it,ItemID:ce,CatalogID:pe,RemainingUses:1,AcquiredAt:r};}}}o.EventToken??={};let yi=o.EventToken;for(let ne=0;;ne++){let De,ce;if(ne===0)De=e.Grant?.Standard?.EventTokens,ce=false;else if(ne-1<Je)De=St[ne-1]?.Resources?.EventTokens,ce=false;else if(ne===1+Je)De=e.Consume?.Standard?.EventTokens,ce=true;else break;if(!(!De||De.length===0))for(let ae of De){let pe=ae.Address;if(!pe||pe.Type==null)continue;let he=ae.Amount??0;if(he<=0)continue;let it=og(yi,pe.Type);if(!it)continue;let Se=it[pe.EntityID];Se||(Se={},it[pe.EntityID]=Se),Se.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Se.Daily??={Date:bi(i),TotalEarned:0},Se.Meta??={};let Ri=ae.Source&&ae.Source.length>0?ae.Source:"CustomAction";ce?(Se.Balance.Current-=he,Se.Balance.TotalSpent+=he):(Se.Balance.Current+=he,Se.Balance.TotalEarned+=he,ai(Se.Daily.Date)!==ai(i)&&(Se.Daily={Date:bi(i),TotalEarned:0}),Se.Daily.TotalEarned+=he,Se.Daily.EarnedBySource??={},Se.Daily.EarnedBySource[Ri]=(Se.Daily.EarnedBySource[Ri]??0)+he,Se.Daily.TriggersBySource??={},Se.Daily.TriggersBySource[Ri]=(Se.Daily.TriggersBySource[Ri]??0)+1,Se.Daily.LastTriggerBySource??={},Se.Daily.LastTriggerBySource[Ri]=r,Se.Meta.JoinedAtUtc||(Se.Meta.JoinedAtUtc=r),Se.Meta.LastEarnedAtUtc=r),s.tokensChanged=true;}}return s}function sg(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 ng(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 rg(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 og(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 ql(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 d of Object.values(s))d?.ItemID&&r.add(d.ItemID);for(let d of n){let R=o[d]?.ItemID;R&&r.add(R);}if(r.size===0)return i;let p=d=>n.has(d)||d in s;if(e){for(let[d,R]of Object.entries(e))d in o||p(d)||R&&r.has(R.ItemID)&&i.drop.push(d);for(let[d,R]of Object.entries(o))d in e||p(d)||R&&r.has(R.ItemID)&&(i.restore[d]=R);}return i}function ao(o,e){return o===e||o.startsWith(`${e}:`)}var Xi=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=oo(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??{}},p=oo(n,e,i,s),d=ql(r,n.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],oe=d.drop.length>0||Object.keys(d.restore).length>0||R.length>0||V.length>0;if(oe){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let Ie=n.InventoryV2.UnstackableItems;for(let ge of d.drop)delete Ie[ge];for(let[ge,Me]of Object.entries(d.restore))Ie[ge]=Me;for(let[ge,Me]of R)Ie[ge]=Me;for(let ge of V)delete Ie[ge];}this.emitResourceChanges(p,oe);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,r=t instanceof _t?t:new _t(t),p=s===void 0?new _t(0):s instanceof _t?s:new _t(s),d=i??new Date().toISOString(),R=n[e];R?(R.Amount=new _t(R.Amount).plus(r).toString(),p.isZero()||(R.Frozen=new _t(R.Frozen??0).plus(p).toString()),R.UpdatedAt=d):n[e]={Amount:r.toString(),Frozen:p.toString(),CreatedAt:d,UpdatedAt:d},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=El(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));}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(ao(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:!ao(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){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,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,p={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")r.Private??={},r.Private[t]=p;else if(e==="Public")r.Public??={},r.Public[t]=p;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 es=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 ts=class{user;config;constructor(e){this.user=new Xi(e),this.config=new es;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function ag(o){return o}var lg=0,ug=1500,cg=3,ss=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 d of new Set(e)){let R=this.rules.get(d);if(R&&(t?.force||R.needsServer(i))){s.push(this.runRule(d,R));continue}(t?.force||!this.state.isStateFresh(d,t?.maxAgeMs))&&n.push(d);}let p=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(a(void 0))])).find(d=>!d.ok);return p&&!p.ok?p: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();},lg),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 r of t)r(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=is(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 V=this.loginFailures.get(s);if(V)return this.loginFailures.delete(s),V;let oe=this.inflight.get(s);if(oe)return oe}let n=this.generation.get(s)??0,r=Date.now(),d=t().then(R=>{if(!R.ok)return R;let V=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:lo(e,R.data,V)}),R;let oe=this.entries.get(s);if(oe&&oe.storedAt>=r)return R;let Ie=lo(e,R.data,V);return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:Math.min(Ie??1/0,V+ug)}),R}).finally(()=>{this.inflight.get(s)===d&&this.inflight.delete(s);});return this.inflight.set(s,d),d}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=is(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=Bl({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>cg||this.used.set(Bl(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(is(e,t))?.data}put(e,t,i){this.register(e);let s=is(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:lo(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 is(o,e){return e===void 0?o.key:`${o.key}|${e}`}function Bl(o){return o.Key?`${o.Name}|${o.Key}`:o.Name}function lo(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 ns=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 pg(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 pg(o){return o!==null&&Object.values(ze).includes(o)}var hg=8,dg=100,mg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,Ll=["GameLoop"];function fg(o){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(o)}var rs=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=ze.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";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$1;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$1;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 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;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&&mg.test(e)}static isValidPasswordLength(e){return e.length>=hg&&e.length<=dg}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.sessionAuthType=ze.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){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(Ll,Ll);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 gg="idos:cfg",li=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Gl(t)}`:e&&e.length>0?`f:${Gl(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 `${gg}:${this.titleId}:${e}`}};function Gl(o){return [...o].map(e=>e.toLowerCase()).sort().join(",")}var Fl="idos:loc",ui=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 `${Fl}:${this.titleId}:${e}`}versionsKey(){return `${Fl}:${this.titleId}:versions`}};var yg="idos:sec",os=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let i=JSON.parse(t);return !i||typeof i!="object"||i.v!==e||!i.s||typeof i.s!="object"?{}:i.s}catch{return {}}}async write(e,t){try{let i={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(i));}catch{}}keyOf(){return `${yg}:${this.titleId}`}};var Rg="idos:state",as=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 `${Rg}:${this.titleId}:${e}`}};function Cg(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 uo(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 Sg(o){return {...o??{}}}function co(o){return typeof o.StateEpoch=="string"&&o.StateEpoch.length>0?o.StateEpoch:null}var ls=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=Cg(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 p=this.versions[n];p!==r&&(p!==void 0&&r===p+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=Sg(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 Vl=b("server","Title configuration is unavailable (CDN and API both failed)."),us=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 li(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new ui(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new os(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new ls(new as(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$1;let t=li.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?Vl:(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=uo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=co(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 p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return n&&await this.configCache.write(t,n,p),p}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$1;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=li.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let r=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let p=await this.ctx.api.user.getClientStateExcept(i);if(!p.ok)return p;let d=await this.resolveTitleConfig(p.data,s,n,{ExcludeFields:t??[]});return d==null?Vl:(this.finishStateHandshake(p.data,r),await this.restoreSections(p.data.TitleConfigVersion,d),await this.applyClientState(p.data,d,e,t),this.ctx.cache.acceptLoginViews(p.data.Views),await this.applyLocalization(p.data.Localization),await this.flushState(r),p)}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??{},p=n.Version??0,d=n.Locale??e;return p>0&&await this.localizationCache.write(d,p,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$1}async getUserState(e){let t=this.baseRequest();if(!t)return c$1;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=uo(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let r=i.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([R,V])=>r[R]!==V||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(n,p);let d=co(s.data);return d&&(this.stateStore.afterSliceRead(d,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$1;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$1;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$1;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$1;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$1;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$1;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,p=n?this.ctx.data.user.state?.GameLoop:void 0,d=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=p);let V=this.ctx.data.config.titlePublicConfiguration;r&&V&&V.GameLoop==null&&(V.GameLoop=d),this.ctx.emitter.emit("user:clientStateReceived",e);}};var ps=class{constructor(e){this.ctx=e;}ctx;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===ut.Crypto||i===ut.Crypto)return b("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return c$1;let p={...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}_${d()}`},d$1=await this.ctx.api.currency.convert(p);if(d$1.ok){let R=d$1.data,V={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(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return d$1}async cryptoConvert(e,t,i,s,n,r){let p=n instanceof _t?n:new _t(n);if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(p.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===ut.Virtual&&i===ut.Virtual)return b("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ut.Virtual&&!p.isInteger())return b("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:p.toString(),TransactionID:r&&r.length>0?r:`crypto_convert_${e}_${t}_to_${i}_${s}_${d()}`},R=await this.ctx.api.currency.cryptoConvert(d$1);if(R.ok){let V=R.data,oe=[],Ie=[];if(V.SourceType===ut.Virtual&&oe.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===ut.Virtual&&Ie.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),oe.length>0||Ie.length>0){let ge={Consume:oe.length>0?{Standard:{Entries:oe}}:null,Grant:Ie.length>0?{Standard:{Entries:Ie}}:null};this.ctx.data.user.applyResourceOperation(ge,this.ctx.data.config.itemDefinitions);}V.SourceType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new _t(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new _t(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return R}};var hs=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let s=e.trim();if(!s)return b("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${s}_${d()}`};t&&t.length>0&&(n.FodderInstanceIDs=[...t]);let r=await this.ctx.api.item.upgradeLevel(n);return r.ok&&(this.ctx.data.user.patchEquippedItemLevel(r.data.ItemInstanceID??s,r.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",r.data)),r}async upgradeLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;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 Nl=z.object({OptionID:z.string().nullish(),Name:z.string().nullish(),Cost:xt.nullish(),AllowedPlatforms:z.array(Gi).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),le=z.record(z.string(),Nl),xg=z.object({Store:Fi,Receipt:z.string(),Signature:z.string().nullish()}).passthrough();var Di={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},po=z.object({ConfirmationID:z.string(),Url:z.string(),Status:z.string(),PriceCredits:z.number(),ExpiresAt:c}).passthrough(),jl=z.object({Linked:z.boolean(),Credits:z.number(),TopUpUrl:z.string().nullish()}).passthrough(),bg={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"},ho=z.object({ServerTimeUtc:c,OfferID:z.string(),Count:z.number(),Resources:M.nullish(),Inventory:Q.nullish(),CreditsConfirmation:po.nullish()}),_l=z.array(Pe(ho)),Dg=z.object({OfferID:z.string(),TotalPurchases:z.number(),DailyPurchases:z.number(),DailyResetUtc:c,LastPurchasedAt:c}),Pg=z.object({SlotKey:z.string(),InstanceKey:z.string(),OfferID:z.string().nullish(),Purchases:z.number(),LastPurchasedAt:c}),Wl=z.object({Purchases:z.record(z.string(),Dg).nullish(),Rotations:z.record(z.string(),Pg).nullish()}).passthrough().transform(o=>o),Dt=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(),ds=z.object({Schedule:me.nullish(),Gate:Z.nullish()}).passthrough(),Ig={Fixed:"Fixed",Title:"Title",Player:"Player"},vg=z.object({OfferID:z.string().nullish(),Weight:z.number().nullish(),Gate:Z.nullish()}).passthrough(),Kl=z.object({Mode:z.string().nullish(),OfferID:z.string().nullish(),Pool:z.array(vg).nullish(),Salt:z.string().nullish(),PerInstanceCap:z.number().nullish()}).passthrough(),Tg=z.object({Identity:K.nullish(),Availability:K.nullish(),Rotation:K.nullish()}).passthrough(),kg=z.object({SlotID:z.string().nullish(),Identity:Dt.nullish(),Availability:ds.nullish(),Rotation:Kl.nullish(),Presets:Tg.nullish()}).passthrough(),Ag=z.object({Identity:K.nullish(),Availability:K.nullish()}).passthrough(),zg=z.object({SectionID:z.string().nullish(),Identity:Dt.nullish(),Availability:ds.nullish(),Slots:z.record(z.string(),kg).nullish(),UniqueOffersInSection:z.boolean().nullish(),Presets:Ag.nullish()}).passthrough(),Ql=z.object({Sections:z.record(z.string(),zg).nullish()}).passthrough(),wg=z.object({Identity:K.nullish(),Availability:K.nullish(),Layout:K.nullish()}).passthrough(),Mg=z.object({StoreID:z.string().nullish(),Identity:Dt.nullish(),Availability:ds.nullish(),Layout:Ql.nullish(),Presets:wg.nullish()}).passthrough(),Hl=z.object({Options:le.nullish(),CompareAt:z.record(z.string(),xt).nullish()}).passthrough(),$l=z.object({Grant:H.nullish()}).passthrough(),Jl=z.object({Schedule:me.nullish(),Gate:Z.nullish(),Limits:ye.nullish()}).passthrough(),Og=z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish(),Availability:K.nullish()}).passthrough(),Eg=z.object({OfferID:z.string().nullish(),Identity:Dt.nullish(),Pricing:Hl.nullish(),Reward:$l.nullish(),Availability:Jl.nullish(),Presets:Og.nullish()}).passthrough(),Ug=z.object({Identity:z.record(z.string(),Dt).nullish(),Availability:z.record(z.string(),ds).nullish(),Layout:z.record(z.string(),Ql).nullish(),Rotation:z.record(z.string(),Kl).nullish(),Pricing:z.record(z.string(),Hl).nullish(),Reward:z.record(z.string(),$l).nullish(),OfferAvailability:z.record(z.string(),Jl).nullish()}).passthrough(),ms=z.object({Stores:z.record(z.string(),Mg).nullish(),StoreOffers:z.record(z.string(),Eg).nullish(),Presets:Ug.nullish()}).passthrough(),qg=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:c.nullish()}).passthrough(),Bg=z.object({OptionID:z.string(),Name:z.string().nullish(),Cost:xt.nullish(),CompareAtCost:xt.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(),Lg=z.object({OfferID:z.string(),Identity:Dt.nullish(),PriceOptions:z.array(Bg).nullish(),Rewards:H.nullish(),State:qg.nullish()}).passthrough(),Gg=z.object({SlotID:z.string(),Identity:Dt.nullish(),SortOrder:z.number(),RotationMode:z.string().nullish(),RotationInstanceKey:z.string().nullish(),RefreshesAtUtc:c.nullish(),RemainingThisRotation:z.number().nullish(),Offer:Lg.nullish()}).passthrough(),Fg=z.object({SectionID:z.string(),Identity:Dt.nullish(),SortOrder:z.number(),Slots:z.array(Gg).nullish()}).passthrough(),Vg=z.object({StoreID:z.string(),Identity:Dt.nullish(),SortOrder:z.number(),ScheduleInstanceKey:z.string().nullish(),ExpiresAtUtc:c.nullish(),Sections:z.array(Fg).nullish()}).passthrough(),fs=z.object({ServerTimeUtc:c,Stores:z.array(Vg).nullish(),AdCreditBalance:z.number()}).passthrough(),Pt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},Ng="OFFER_NOT_IN_ROTATION";var Zl="Store",Yl={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}},gs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Yl,{schema:fs,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$1;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()}`},r=await this.ctx.api.store.purchase(n);if(r.ok&&!r.data.CreditsConfirmation){let p=r.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return r}async purchaseWithCredits(e,t=1,i={}){let s=await this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot});if(!s.ok||!s.data.CreditsConfirmation)return s;let n=s.data.CreditsConfirmation,r=()=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:n.ConfirmationID});if(o()){let R=await p({titleID:this.ctx.settings.titleID,confirmationID:n.ConfirmationID});if(R.ok)return await r();if(R.error==="DECLINED")return b("server","CREDITS_CONFIRMATION_DECLINED");if(R.error==="NOT_ENOUGH_CREDITS")return b("server","NOT_ENOUGH_CREDITS")}i.onConfirmation?.(n);let p$1=Math.max(1e3,i.pollMs??2500),d=Date.parse(n.ExpiresAt)+6e4;for(;;){if(i.signal?.aborted)return b("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>d)return b("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(oe=>setTimeout(oe,p$1));let R=await this.getCreditsConfirmation(n.ConfirmationID);if(!R.ok)continue;let V=R.data.Status;if(V!==Di.Pending)return V===Di.Declined?b("server","CREDITS_CONFIRMATION_DECLINED"):V===Di.Expired?b("server","CREDITS_CONFIRMATION_EXPIRED"):await r()}}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):c$1}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):c$1}async purchaseBatch(e){if(!e||e.length===0)return b("client","purchases is required.");if(!this.ctx.auth.context)return c$1;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(Zl,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Zl,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(Yl,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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 ys=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return c$1;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return c$1;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$1;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$1;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$1;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 Xl=3,jg=700,Rs=class{constructor(e){this.ctx=e;l()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return oi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await m({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<=Xl;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===Xl)break;await Mt(jg);}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===Li.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!==Li.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 eu="Lootbox",Cs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(eu,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$1;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection(eu,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s){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$1;let n={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,RelatedEntityID:`lootbox_${e}_${i??"default"}_${d()}`},r=await this.ctx.api.lootbox.open(n);if(r.ok){let p=r.data;p.TriggeredPity&&p.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,p.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",p);}return r}};var mo="Reward";function fo(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Ss=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(mo)?.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(mo,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$1;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(mo,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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(!fo(e))return b("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;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(!fo(e))return b("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;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(!fo(e))return b("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;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}};var xs="Tutorial",tu={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"]},bs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(tu,{schema:Wi,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(xs)?.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(xs,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(xs,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(tu,()=>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$1;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$1;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$1;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$1;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$1;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:r};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let d=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,R=await i(p);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(n,r,d,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(xs)?.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 Ds=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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$1;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$1;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Oe=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 _g={Global:"Global",Announcement:"Announcement",Group:"Group"},su=z.enum(["Global","Announcement","Group"]).catch("Global"),Wg={None:"None",Language:"Language",Region:"Region"},Kg=z.enum(["None","Language","Region"]).catch("None"),Qg={Anyone:"Anyone",Friends:"Friends"},Hg=z.enum(["Anyone","Friends"]).catch("Anyone"),$g={Reject:"Reject",Mask:"Mask"},Jg=z.enum(["Reject","Mask"]).catch("Reject"),Zg={Player:"Player",Publisher:"Publisher",System:"System"},Yg=z.enum(["Player","Publisher","System"]).catch("Player"),Xg={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var ey=z.object({DisplayNameKey:z.string().nullish(),SortOrder:z.number().nullish(),IconPath:z.string().nullish(),JoinedByDefault:z.boolean().nullish()}).passthrough(),nu=z.object({Gate:Z.nullish(),Schedule:me.nullish()}).passthrough(),ru=z.object({Gate:Z.nullish(),Limits:ye.nullish(),MaxLength:z.number().nullish()}).passthrough(),ou=z.object({HotTailSize:z.number().nullish(),HistoryHours:z.number().nullish()}).passthrough(),ty=z.object({Availability:K.nullish(),Write:K.nullish(),Retention:K.nullish()}).passthrough(),iy=z.object({ChannelID:z.string().nullish(),Identity:ey.nullish(),Type:su.nullish(),GroupSource:z.string().nullish(),Partitioning:Kg.nullish(),Capacity:z.number().nullish(),Availability:nu.nullish(),Write:ru.nullish(),Retention:ou.nullish(),Presets:ty.nullish()}).passthrough(),sy=z.object({IsEnabled:z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:Hg.nullish(),Limits:ye.nullish(),MaxLength:z.number().nullish(),HistoryHours:z.number().nullish(),MaxConversations:z.number().nullish()}).passthrough(),ny=z.object({BlockedTerms:z.array(z.string()).nullish(),BlockedTermAction:Jg.nullish(),MaxIgnoreListSize:z.number().nullish(),ReportsEnabled:z.boolean().nullish(),ReportLimits:ye.nullish()}).passthrough(),ry=z.object({MinIntervalSeconds:z.number().nullish(),MaxMessagesPerPoll:z.number().nullish(),MaxHistoryPageSize:z.number().nullish()}).passthrough(),oy=z.object({Availability:z.record(z.string(),nu).nullish(),Write:z.record(z.string(),ru).nullish(),Retention:z.record(z.string(),ou).nullish()}).passthrough(),au=z.object({IsEnabled:z.boolean().nullish(),Channels:z.record(z.string(),iy).nullish(),Direct:sy.nullish(),Moderation:ny.nullish(),Polling:ry.nullish(),Presets:oy.nullish()}).passthrough(),ay=z.object({LastReadAt:z.string().nullish(),LastReadMessageID:z.string().nullish(),Left:z.boolean().nullish()}).passthrough(),iu=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(),ay).nullish(),Limits:z.record(z.string(),iu).nullish(),ReportLimits:iu.nullish()}).passthrough();var go=z.object({RoomID:z.string().nullish(),SentAt:z.string().nullish(),MessageID:z.string().nullish()}).passthrough(),Ps=z.object({RoomID:z.string().nullish(),ChannelID:z.string().nullish(),MessageID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderProfile:Oe.nullish(),AuthorType:Yg.nullish(),Text:z.string().nullish(),SentAt:z.string().nullish()}).passthrough(),ly=z.object({ChannelID:z.string().nullish(),RoomID:z.string().nullish(),DisplayNameKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),Type:su.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(),Is=z.object({Channels:z.array(ly).nullish(),PollIntervalSeconds:z.number().nullish(),MutedUntil:z.string().nullish(),MuteReason:z.string().nullish()}).passthrough(),uy=z.object({RoomID:z.string().nullish(),Messages:z.array(Ps).nullish(),NextCursor:go.nullish(),UnreadCount:z.number().nullish(),ServedFromDatabase:z.boolean().nullish()}).passthrough(),lu=z.object({Rooms:z.array(uy).nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),uu=z.object({RoomID:z.string().nullish(),Messages:z.array(Ps).nullish(),NextBefore:go.nullish()}).passthrough(),cu=z.object({Message:Ps.nullish(),Moderated:z.boolean().nullish()}).passthrough(),pu=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Oe.nullish(),MaxLength:z.number().nullish()}).passthrough(),cy=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Oe.nullish(),LastMessage:Ps.nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),hu=z.object({Conversations:z.array(cy).nullish()}).passthrough(),ci=z.object({Ignored:z.array(z.string()).nullish(),Cursor:go.nullish(),Joined:z.boolean().nullish()}).passthrough(),du=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish()}).passthrough(),Ke={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 mu="Chat",fu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},vs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fu,{schema:Is,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(mu,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(mu,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(fu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return c$1;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$1;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$1}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return c$1;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$1;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$1}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):c$1}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return c$1;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$1}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):c$1}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$1}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):c$1}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):c$1}resetCursors(){this.cursors.clear();}};var py={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},hy=z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),dy={Player:"player",Title:"title",Creator:"creator"},pi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},gu=z.object({Configured:z.boolean().nullish(),PublicKey:z.string().nullish()}).passthrough(),my=z.object({TitleID:z.string().nullish(),Topic:z.string().nullish()}).passthrough(),yo=z.object({EndpointHash:z.string().nullish(),Transport:hy.nullish(),Locale:z.string().nullish(),Topics:z.array(my).nullish()}).passthrough(),yu=z.object({Configured:z.boolean().nullish(),Subscriptions:z.array(yo).nullish()}).passthrough(),It={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var fy="IDOS_PLATFORM_PUSH_REQUEST",gy="IDOS_PLATFORM_PUSH_RESPONSE",yy=12e4;function Ru(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=d=>{s||(s=true,window.removeEventListener("message",r),clearTimeout(p),i(d));},r=d=>{let R=d?.data;!R||R.type!==gy||R.requestId!==t||f.includes(d.origin)&&n(R.ok===true);},p=setTimeout(()=>n(false),yy);window.addEventListener("message",r);for(let d of f)try{e.postMessage({type:fy,requestId:t,titleID:o},d);}catch{}})}var Ts=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 It.Unsupported;if(this.isEmbedded())return It.Embedded;if(!this.isSupported())return It.Unsupported;let t=Notification.permission;return t==="denied"?It.Blocked:t!=="granted"?It.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?It.Subscribed:It.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return b("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Ru(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 r=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:Ry(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return c$1;let d=r.toJSON();p.PushEndpoint=d.endpoint,p.PushP256dh=d.keys?.p256dh,p.PushAuth=d.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(p);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$1;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$1}async unsubscribeByHash(e){if(!e)return b("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 Ry(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 ks=Object.freeze({}),As=class{constructor(e){this.ctx=e;}ctx;table={...ks};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new ui(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?Cy(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...ks},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$1;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:r}=i.data,p=null;if(r){let d=await this.loadTableFromApi(r);d.ok&&(p=d.data.table);}return this.table=n,this.fallbackTable=p,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$1}reset(){this.table={...ks},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$1;t.Locale=e;let i=await this.cache.read(Cu(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??Cu(e),p=n.Version??0;if(n.NotModified){let R=i??await this.cache.read(r);return {ok:true,data:{locale:r,table:R?.t??{...ks},fallbackLocale:n.FallbackLocale??null}}}let d=n.Entries??{};return p>0&&await this.cache.write(r,p,d),{ok:true,data:{locale:r,table:d,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 Cy(o,e){return o.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function Cu(o){return o.trim().replace(/_/g,"-").toLowerCase()}var Ro="Quest",Sy={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}},zs=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(Ro)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let r of Object.keys(s)){let p=Date.parse(n[r]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=i&&t<p)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(Ro,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ro,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(Sy,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return c$1;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$1;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$1;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()}`},r=await this.ctx.api.quest.claimQuestReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return r}async claimQuestRewardsBatch(e){if(!e||e.length===0)return b("client","quests is required.");if(!this.ctx.auth.context)return c$1;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$1;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${d()}`},r=await this.ctx.api.quest.claimMilestoneReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return r}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;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$1;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${d()}`},r=await this.ctx.api.quest.claimGroupCompletionReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return 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$1;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 Su=z.object({}).passthrough().transform(o=>o);var xy=z.object({Order:z.number().nullish(),Type:z.string().nullish(),DurationSec:z.number().nullish(),BonusMultiplier:z.number().nullish()}).passthrough(),by=z.object({Schedule:z.array(xy).nullish(),RepeatCycle:z.boolean().nullish(),MaxCycles:z.number().nullish()}).passthrough(),Dy=z.object({IsActive:z.boolean().nullish(),CurrentPhaseEndUtc:c.nullish(),NextBonusStartUtc:c.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentPhaseIndex:z.number().nullish(),ActiveBonusMultiplier:z.number().nullish()}).passthrough(),Py=z.object({Milestones:K.nullish()}).passthrough(),Co=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Category:z.string().nullish(),Token:jt.nullish(),TokenSources:z.array(st).nullish(),ClaimMode:z.string().nullish(),Milestones:z.record(z.string(),Be).nullish(),Presets:Py.nullish(),BonusWindow:by.nullish()}).passthrough(),Iy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Content:Co.nullish(),ClaimGraceHours:z.number().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),vy=z.object({TimedEventID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:me.nullish(),Content:Co.nullish(),Events:z.array(Iy).nullish(),Gate:Z.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Ty=z.object({MaxConcurrentEvents:z.number().nullish()}).passthrough(),ky=z.object({Milestones:z.record(z.string(),ni).nullish()}).passthrough(),ws=z.object({Definitions:z.record(z.string(),vy).nullish(),Settings:Ty.nullish(),Presets:ky.nullish()}).passthrough(),Ay=z.object({Type:xi,TimedEventID:z.string(),CurrentChainedEventID:z.string().nullish(),Content:Co.nullish(),Progress:Su.nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),NextMilestone:Be.nullish(),BonusWindow:Dy.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentEventOrder:z.number().nullish(),TotalEventsInChain:z.number().nullish(),TokenEntityID:z.string().nullish()}).passthrough(),Ms=z.object({ActiveEvents:z.array(Ay).nullish()}).passthrough(),xu=z.object({Tokens:z.record(z.string(),Su).nullish()}),So=z.object({Type:xi.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),xo=z.object({Type:xi.nullish(),LteID:z.string().nullish(),MilestoneID:z.string().nullish(),TokenEntityID:z.string().nullish(),Rewards:M.nullish(),Inventory:Q.nullish()}),zy=z.object({Type:xi.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),bo=z.array(Pe(xo)),bu=z.array(Pe(So)),Du=z.array(Pe(zy)),ot={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Pu="TimedEvent",Iu={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}},Os=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Iu,{schema:Ms,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(Iu,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return c$1;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(Pu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Pu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return c$1;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,p=1){if(!t)return b("client","LteID is required.");if(!i)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c$1;let d={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:r,RollMultiplier:p},R=await this.ctx.api.timedEvent.grantTokens(d);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$1;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$1;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$1;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$1;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$1;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$1;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 wy=z.object({UserID:z.string(),Score:_.nullish(),Rank:z.number().nullish(),LastScoreUpdateUtc:c.nullish(),IpHash:z.string().nullish(),PublicProfile:Oe.nullish(),SeasonTierAtCycleEnd:z.number().nullish()}).passthrough(),Pi=z.object({LeaderboardID:z.string(),CycleVersion:z.number().nullish(),TotalParticipants:_.nullish(),CycleEndUtc:c.nullish(),TopUsers:z.array(wy).nullish(),BracketID:z.string().nullish()}),My=z.object({CycleKey:z.string().nullish(),CycleEndUtc:c.nullish(),ClaimDeadlineUtc:c.nullish(),MilestoneTokensEarned:_.nullish(),ClaimableMilestoneIDs:z.array(z.string()).nullish(),CycleIndex:z.number().nullish(),ChainedEventID:z.string().nullish()}).passthrough(),Es=z.object({LeaderboardID:z.string(),CurrentScore:_.nullish(),LastKnownRank:z.number().nullish(),HasUnclaimedReward:z.boolean().nullish(),UnclaimedRewardRank:z.number().nullish(),ScoreEarnedThisCycle:_.nullish(),MilestoneTokensEarned:_.nullish(),TokenEntityID:z.string().nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish(),GrantedPremiumTiers:z.record(z.string(),z.array(z.string())).nullish(),ClaimableGraceCycles:z.array(My).nullish()}),Us=z.object({LeaderboardID:z.string(),NewScore:_,CycleVersion:z.number()}),qs=z.object({ServerTimeUtc:c,LeaderboardID:z.string(),Rank:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Bs=z.object({ServerTimeUtc:c,LeaderboardID:z.string(),MilestoneID:z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),vu=z.array(Pe(Pi)),Ls=z.array(Pe(Es)),Tu=z.array(Pe(qs)),ku=z.array(Pe(Bs)),Au=z.array(Pe(Us)),Oy=z.object({LeaderboardID:z.string(),CycleReward:Pe(qs).nullish(),Milestones:z.array(Pe(Bs)).nullish()}),zu=z.array(Oy),Ey=z.object({LeaderboardID:z.string(),Leaderboard:Pe(Pi).nullish(),Progress:Pe(Es).nullish()}),wu=z.array(Ey),Uy=z.string(),Mu=z.object({Rank:z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:Zr.nullish()}).passthrough(),qy=z.object({RankRewards:z.array(Mu).nullish()}).passthrough(),By=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Ly=z.object({Milestones:K.nullish(),RankRewards:K.nullish()}).passthrough(),Gy=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:Uy.nullish(),Schedule:me.nullish(),ChainEvents:z.array(By).nullish(),Gate:Z.nullish(),TopUsersLimit:z.number().nullish(),MinScoreToEnterTop:z.number().nullish(),BracketSize:z.number().nullish(),LinkedSeasonChainID:z.string().nullish(),RankRewards:z.array(Mu).nullish(),Milestones:z.record(z.string(),Be).nullish(),Presets:Ly.nullish(),MilestoneClaimMode:z.string().nullish(),MilestoneClaimGraceHours:z.number().nullish(),ScoreSources:z.array(st).nullish()}).passthrough(),Fy=z.object({Milestones:z.record(z.string(),ni).nullish(),RankRewards:z.record(z.string(),qy).nullish()}).passthrough(),Gs=z.object({Definitions:z.record(z.string(),Gy).nullish(),Presets:Fy.nullish()}).passthrough(),Ve={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 Ou="Leaderboard",Eu={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"]},Fs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Eu,{schema:Ls,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Ou,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ou,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$1;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$1;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$1;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$1;let r={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},p=await this.ctx.api.leaderboard.submitScoreFromSource(r);if(p.ok){let d=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),d.NewScore,d.NewScore,d.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",d);}return p}async claimCycleReward(e){if(!e)return b("client","LeaderboardID is required.");if(!this.ctx.auth.context)return c$1;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$1;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$1;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$1;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(Eu,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return c$1;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$1;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$1;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$1;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$1;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$1;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 Do=z.object({}).passthrough().transform(o=>o),Vs=z.object({SeasonChainID:z.string(),CycleIndex:z.number().nullish(),Season:z.lazy(()=>Lu).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:_.nullish(),UserState:Do.nullish(),NextTier:z.lazy(()=>Bu).nullish()}).passthrough(),Uu=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),AmountGranted:_.nullish(),NewStatusTokens:_.nullish(),OldTier:z.number().nullish(),NewTier:z.number(),TierUp:z.boolean().nullish()}),Po=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),TierNumber:z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),qu=ft(Po);var Bu=z.object({Tier:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredTokens:_.nullish(),TierReachedReward:H.nullish()}).passthrough(),Lu=z.object({SeasonID:z.string().nullish(),Order:z.number().nullish(),DurationSec:_.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(Bu).nullish(),LinkedCollectionID:z.string().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough();var Vy=z.object({SeasonChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:me.nullish(),Seasons:z.array(Lu).nullish(),GrantTokensAccessMode:z.string().nullish(),Gate:Z.nullish()}).passthrough(),Ns=z.object({Chains:z.record(z.string(),Vy).nullish()}).passthrough(),Et={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Gu="Season",Fu={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}},js=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Fu,{schema:Vs,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Gu,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Gu,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(Fu,()=>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$1;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$1;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$1;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$1;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(r=>r>0);if(i.length===0)return b("client","TierNumbers is required.");if(!this.ctx.auth.context)return c$1;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 r=n.data;for(let p of r.Items??[]){let d=p.Data?.TierNumber;p.Success&&typeof d=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,d);}this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",r);}return n}};var Vu="Premium",_s=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Vu,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$1;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(Vu,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,RelatedEntityID:`premium_purchase_${e}_${t}`},r=await this.ctx.api.premium.purchaseItemOrCurrency(n);if(r.ok){let p=r.data;p.Premium&&this.ctx.data.user.applyPremium(p.Premium),this.ctx.data.user.applyResourceOperation(p.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",p);}return r}async purchaseRealMoney(e,t,i,s,n,r,p,d){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$1;let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:r,PackageName:p,AppStoreEnvironment:d,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(R);if(V.ok){let oe=V.data;oe.Premium&&this.ctx.data.user.applyPremium(oe.Premium),this.ctx.data.user.applyResourceOperation(oe.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",oe);}return V}};var Ws=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ItemInstanceID:z.string().nullish(),Level:z.number().nullish(),EquippedAt:c.nullish()}),Io=z.object({CharacterID:z.string(),Level:z.number().nullish(),Experience:_.nullish(),Power:z.number().nullish(),StatLevels:z.record(z.string(),z.number()).nullish(),Equipment:z.record(z.string(),Ws).nullish(),UpdatedAt:c.nullish()}).passthrough(),Nu=z.object({Characters:z.record(z.string(),Io).nullish()}),vo=z.object({ServerTimeUtc:c,CharacterID:z.string(),StatID:z.string(),StatLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),To=z.object({ServerTimeUtc:c,CharacterID:z.string(),NewLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),ju=z.object({ServerTimeUtc:c,CharacterID:z.string(),Equipment:z.record(z.string(),Ws).nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),_u=z.object({ServerTimeUtc:c,CharacterID:z.string(),ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),Ny=z.object({ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish()}),Wu=z.object({ServerTimeUtc:c,Characters:z.record(z.string(),Ny).nullish(),Inventory:Q.nullish()}),ko=z.object({ServerTimeUtc:c,CharacterID:z.string(),Power:z.number().nullish(),Resources:M.nullish()}),Ku=z.object({ServerTimeUtc:c,CharacterID:z.string(),SkinID:z.string(),Resources:M.nullish(),Inventory:Q.nullish(),Equipped:z.boolean().nullish(),EquipError:z.string().nullish(),Equipment:Ws.nullish(),Power:z.number().nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish()}),Qu=z.object({ServerTimeUtc:c,CharacterID:z.string(),SkinID:z.string(),Equipped:Ws.nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),Hu=z.object({ServerTimeUtc:c,CharacterID:z.string(),Cleared:z.boolean().nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),jy=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:c.nullish(),GateOpen:z.boolean().nullish(),Purchasable:z.boolean().nullish(),PriceOptions:le.nullish()}),_y=z.object({CharacterID:z.string(),CharacterOpen:z.boolean().nullish(),DefaultSkinID:z.string().nullish(),WornSkinID:z.string().nullish(),Skins:z.array(jy).nullish()}),$u=z.object({ServerTimeUtc:c,Characters:z.record(z.string(),_y).nullish()}),Ju=ft(ko),Zu=ft(To),Yu=ft(vo),Ao=z.object({RequiredStatID:z.string(),RequiredLevel:z.number()}).passthrough(),Xu=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:le.nullish(),CostCurve:Fe.nullish(),BaseStatValue:z.number().nullish(),ValueCurve:Fe.nullish(),RankCurve:Fe.nullish(),Requirements:z.array(Ao).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Wy=z.object({SlotID:z.string(),MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Ao).nullish(),AllowedRarityIDs:z.array(z.string()).nullish(),AllowedItemTags:z.array(z.string()).nullish(),MinItemLevel:z.number().nullish(),MaxItemLevel:z.number().nullish()}).passthrough(),ec=z.object({Slots:z.record(z.string(),Wy).nullish()}).passthrough(),tc=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(),Ky=z.object({ClassID:z.string().nullish(),RarityID:z.string().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),Qy=z.object({UnlockedByDefault:z.boolean().nullish(),PriceOptions:le.nullish()}).passthrough(),Hy=z.object({Stats:K.nullish(),Levels:K.nullish(),Equipment:K.nullish()}).passthrough(),ic=z.object({MaxRank:z.number().nullish(),FirstPaidRank:z.number().nullish(),PriceOptions:le.nullish(),CostCurve:Fe.nullish()}).passthrough(),zo="@skin";function $y(o){return !!o&&o.startsWith("@")}var Jy=z.object({CatalogID:z.string().nullish(),ItemID:z.string()}).passthrough(),Zy=z.object({PriceOptions:le.nullish(),Schedule:me.nullish(),Gate:Z.nullish()}).passthrough(),Yy=z.object({MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Ao).nullish()}).passthrough(),Xy=z.object({SkinID:z.string().nullish(),Identity:tc.nullish(),Item:Jy.nullish(),Sale:Zy.nullish(),Requirements:Yy.nullish()}).passthrough(),eR=z.object({DefaultSkinID:z.string().nullish(),Definitions:z.record(z.string(),Xy).nullish()}).passthrough(),tR=z.object({CharacterID:z.string(),Identity:tc.nullish(),Classification:Ky.nullish(),Unlock:Qy.nullish(),Presets:Hy.nullish(),Equipment:ec.nullish(),Stats:z.record(z.string(),Xu).nullish(),RankLadder:ic.nullish(),RankStatCurve:Fe.nullish(),StatMaxLevelCurve:Fe.nullish(),Skins:eR.nullish()}).passthrough(),iR=z.object({Stats:z.record(z.string(),Xu).nullish()}).passthrough(),sR=z.object({RankLadder:ic.nullish()}).passthrough(),nR=z.object({Equipment:ec.nullish()}).passthrough(),rR=z.object({Stats:z.record(z.string(),iR).nullish(),Levels:z.record(z.string(),sR).nullish(),Equipment:z.record(z.string(),nR).nullish()}).passthrough(),Ks=z.object({Definitions:z.record(z.string(),tR).nullish(),Presets:rR.nullish()}).passthrough(),Ne={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"},oR="SKIN_ALREADY_OWNED";var wo="Character",Qs=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(wo)?.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(wo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(wo,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${d()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok){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$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${d()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,p=>{p.StatLevels??={},p.StatLevels[r.StatID]=r.StatLevel,r.Power!=null&&(p.Power=r.Power),p.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$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${d()}`,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok){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$1;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$1;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$1;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$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${d()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok){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$1;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$1;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$1}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,zo,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$1;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$1;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$1;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 sc="Match",Hs=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,r){let p=this.ctx.auth.context;if(!p)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:r,RelatedEntityID:`pvp_create_${p.userID}_${d()}`},R=await this.ctx.api.match.createMatch(d$1);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$1;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$1;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$1;let r={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${d()}`},p=await this.ctx.api.match.instantBattle(r);if(p.ok){let d=p.data,R=this.ctx.data.config.itemDefinitions;if(d.Resources)this.ctx.data.user.applyResourceOperation(d.Resources,R);else if(d.ResourcesDual){let V=d.ResourcesDual;V.FromUserID===n.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,R):V.ToUserID===n.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",d);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return c$1;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$1;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$1;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(sc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(sc,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var nc="Craft",$s=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(nc,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$1;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(nc,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n){if(!e)return b("client","CraftID is required.");let r=this.ctx.auth.context;if(!r)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,RelatedEntityID:`craft_${e}_${r.userID}_${d()}`},d$1=await this.ctx.api.craft.craft(p);return d$1.ok&&(this.ctx.data.user.applyResourcesWithDelta(d$1.data.Resources,d$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",d$1.data)),d$1}};var Ut=z.lazy(()=>z.union([z.string(),z.number(),z.boolean(),z.null(),z.array(Ut),z.record(z.string(),Ut)]));var qt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},rc=z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Wt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Ii(o){return o!==Wt.Pending&&o!==Wt.Running}var aR={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 lR(o){return o?/\b(AI_[A-Z_]+)\s*:/.exec(o)?.[1]??null:null}var uR=z.object({Url:z.string().nullish(),ContentType:z.string().nullish(),Variant:z.string().nullish()}),cR=z.object({Code:z.string().nullish(),Message:z.string().nullish()}),Js=z.object({GenerationID:z.string(),FeatureKey:z.string().nullish(),Modality:rc.nullish(),Status:z.string(),Progress:z.number().nullish(),OutputText:z.string().nullish(),OutputJson:z.record(z.string(),Ut).nullish(),Assets:z.array(uR).nullish(),Error:cR.nullish(),Charge:M.nullish(),PlayerRefunded:z.boolean().nullish(),Reused:z.boolean().nullish(),Reward:M.nullish(),Context:z.record(z.string(),Ut).nullish(),PaymentSettled:z.boolean().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish()}),oc=z.object({Data:z.array(Js).nullish(),Skip:z.number().nullish(),Limit:z.number().nullish()}),pR=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(),hR=z.object({Modality:rc.nullish(),Async:z.boolean().nullish(),Limits:ye.nullish(),PriceOptions:le.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(),ArtStyle:z.string().nullish(),ThreeDFormat:z.string().nullish(),Reward:H.nullish(),PromptVariables:z.array(pR).nullish(),AllowFreePrompt:z.boolean().nullish()}).passthrough(),ac=z.object({Enabled:z.boolean().nullish(),Features:z.record(z.string(),hR).nullish()}).passthrough(),Ge={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"};var lc="AI",dR=/^[A-Za-z0-9_-]{1,128}$/,mR=2e3,fR=5e3,gR=30*6e4;function yR(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 Zs=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(lc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(lc,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))}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$1}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$1}isTerminal(e){return Ii(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;i=p.data;}else {if(!e?.GenerationID)return b("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??gR),n=Math.max(1,t.intervalMs??mR),r=Math.max(n,t.maxIntervalMs??fR);for(;!Ii(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 yR(n,t.signal),t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(i);if(n=Math.min(r,Math.round(n*1.5)),!p.ok){if(p.reason==="connection")continue;return p}i=p.data,Ii(i.Status)||t.onUpdate?.(i);}return a(i)}pollFor(e){switch(e.Modality){case qt.Text:return this.getText(e.GenerationID);case qt.Image:return this.getImage(e.GenerationID);case qt.Audio:return this.getAudio(e.GenerationID);case qt.Music:return this.getMusic(e.GenerationID);case qt.Video:return this.getVideo(e.GenerationID);case qt.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$1;let r={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:n??d()},p=await s(r);return p.ok&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return b("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;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===Wt.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===Wt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Wt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Mo="Collection",Ys=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(Mo),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let n=e.cache.configSection("Season");return Object.values(n?.Chains??{}).some(p=>(p?.Seasons??[]).some(d=>!!d?.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(Mo,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Mo,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${d()}`},p=await this.ctx.api.collection.openPack(r);return p.ok&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${d()}`},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$1;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$1;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$1;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$1;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,r=false){let p=this.ctx.auth.context;if(!p)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:r,RelatedEntityID:`trade_send_${p.userID}_${s}_${d()}`},R=await this.ctx.api.collection.sendTradeOffer(d$1);return R.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",R.data)),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return c$1;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$1;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$1;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$1;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$1;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 RR=z.object({}).passthrough().transform(o=>o),CR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},SR={Active:"Active",Left:"Left",Replaced:"Replaced"},xR=z.object({ObjectIndex:z.number().nullish(),ObjectCompletionRewardClaimed:z.boolean().nullish()}).passthrough(),bR=z.object({UserID:z.string().nullish(),PublicData:Oe.nullish(),BuildObjectsProgress:xR.nullish(),IsBot:z.boolean().nullish(),SpinsCount:z.number().nullish(),TokensSpent:z.number().nullish(),MemberStatus:z.string().nullish(),GrandPrizeClaimed:z.boolean().nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),DR=z.object({Index:z.number().nullish(),OwnerUserID:z.string().nullish(),CurrentProgress:z.number().nullish(),MaxProgress:z.number().nullish(),IsCompleted:z.boolean().nullish()}).passthrough(),PR=z.object({Objects:z.array(DR).nullish()}).passthrough(),uc=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(bR).nullish(),BuildObjectsState:PR.nullish(),Status:z.string().nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:z.number().nullish()}).passthrough(),cc=z.object({CoopChainID:z.string(),CycleIndex:z.number().nullish(),EventOrder:z.number().nullish(),EventDef:z.lazy(()=>pc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:z.number().nullish()}).passthrough(),IR=z.string(),Oo=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(),vR=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(),TR=z.object({Objects:z.array(vR).nullish(),PriceOptions:le.nullish(),SpinnerTable:z.array(Oo).nullish(),MaxSpinsPerCall:z.number().nullish()}).passthrough(),pc=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:TR.nullish(),GrandPrize:H.nullish()}).passthrough(),kR=z.object({CoopChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:me.nullish(),Events:z.array(pc).nullish(),Gate:Z.nullish()}).passthrough(),Xs=z.object({ServerTimeUtc:c.nullish(),UserState:RR.nullish(),ActiveGroup:uc.nullish()}),Eo=z.object({ServerTimeUtc:c.nullish(),Group:uc.nullish(),SecondsRemaining:_.nullish()}),hc=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Resources:M.nullish(),ObjectIndex:z.number().nullish(),Sector:Oo.nullish(),RequestedSpins:z.number().nullish(),SpinsUsed:z.number().nullish(),Sectors:z.array(Oo).nullish(),ProgressDelta:z.number().nullish(),NewProgress:_.nullish(),MaxProgress:_.nullish(),ObjectCompleted:z.boolean().nullish(),AllObjectsCompleted:z.boolean().nullish()}),Uo=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),dc=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),en=z.object({Chains:z.record(z.string(),kR).nullish()}).passthrough(),ht={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var mc="CoopEvent",fc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},tn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fc,{schema:Xs,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$1;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$1;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(fc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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){if(!e||!t)return b("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,RelatedEntityID:d()},r=await this.ctx.api.coopEvent.spin(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",r.data)),r}async claimObjectReward(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c$1;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$1;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$1;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"},zR={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},wR=z.object({NodeID:z.string().nullish(),Status:z.string().nullish(),ExecutionCount:z.number().nullish(),UnlockedAtUtc:c.nullish(),CompletedAtUtc:c.nullish(),LastExecutedAtUtc:c.nullish(),NextAvailableAtUtc:c.nullish(),LastExecutionRefID:z.string().nullish()}).passthrough(),MR=z.object({TrackID:z.string().nullish(),CurrentValue:z.number().nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),gc=z.object({OfferID:z.string().nullish(),InstanceKey:z.string().nullish(),SourceOfferVersion:z.number().nullish(),Status:z.string().nullish(),ActivatedAtUtc:c.nullish(),ExhaustedAtUtc:c.nullish(),ExpiredAtUtc:c.nullish(),DismissedAtUtc:c.nullish(),ShowCount:z.number().nullish(),LastShownAtUtc:c.nullish(),Nodes:z.record(z.string(),wR).nullish(),Tracks:z.record(z.string(),MR).nullish(),SelectedChoiceNodeID:z.string().nullish()}).passthrough(),OR=z.object({SlotID:z.string().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),ActiveOfferID:z.string().nullish(),ActiveOfferStartedAtUtc:c.nullish(),ActiveOfferExpiresAtUtc:c.nullish(),ActiveOffer:gc.nullish(),NextCycleStartsAtUtc:c.nullish(),LastUpdatedUtc:c.nullish(),DismissSkipAvailableAtUtc:c.nullish(),LastDismissedAtUtc:c.nullish(),ActiveScheduleInstanceKey:z.string().nullish()}).passthrough(),ER=z.object({TotalExecutions:z.number().nullish(),DailyExecutions:z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),UR=z.object({TotalActivations:z.number().nullish(),TotalExhausted:z.number().nullish(),TotalExpired:z.number().nullish(),TotalDismissed:z.number().nullish(),TotalShows:z.number().nullish(),LastShownAtUtc:c.nullish(),LastActivatedAtUtc:c.nullish(),LastExhaustedAtUtc:c.nullish(),NodeCounts:z.record(z.string(),ER).nullish()}).passthrough(),qR=z.object({Slots:z.record(z.string(),OR).nullish(),OfferHistory:z.record(z.string(),UR).nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),BR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},LR={Eq:"Eq",Gte:"Gte",Lte:"Lte"},GR=z.object({Order:z.number().nullish(),OfferID:z.string().nullish(),DurationSec:z.number().nullish(),DelayBeforeActivationSec:z.number().nullish()}).passthrough(),sn=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(),yc=z.object({Schedule:me.nullish(),Gate:Z.nullish()}).passthrough(),Rc=z.object({AllowDismissSkip:z.boolean().nullish(),DismissSkipDelaySec:z.number().nullish()}).passthrough(),FR=z.object({Identity:K.nullish(),Availability:K.nullish(),Behaviour:K.nullish()}).passthrough(),VR=z.object({SlotID:z.string().nullish(),Enabled:z.boolean().nullish(),Identity:sn.nullish(),Availability:yc.nullish(),Behaviour:Rc.nullish(),Queue:z.array(GR).nullish(),Presets:FR.nullish()}).passthrough(),NR=z.object({ViewsRequiredToComplete:z.number().nullish(),MaxViewsPerActivation:z.number().nullish(),GrantRewardsPerView:z.boolean().nullish()}).passthrough(),jR=z.object({RewardedVideo:NR.nullish()}).passthrough(),_R=z.object({TrackID:z.string().nullish(),Operator:z.string().nullish(),Value:z.number().nullish()}).passthrough(),WR=z.object({Identity:K.nullish(),Graph:K.nullish(),Milestones:K.nullish()}).passthrough(),KR=z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish()}).passthrough(),QR=z.object({TrackID:z.string().nullish(),Amount:z.number().nullish(),RespectBounds:z.boolean().nullish()}).passthrough(),HR=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(),$R=z.object({RequiredCompletedNodeIDs:z.array(z.string()).nullish(),RequiredAnyCompletedNodeIDs:z.array(z.string()).nullish(),RequiredTracks:z.array(_R).nullish(),VisibleWhileLocked:z.boolean().nullish()}).passthrough(),Cc=z.object({Options:le.nullish()}).passthrough(),Sc=z.object({Grants:H.nullish(),TrackChanges:z.array(QR).nullish(),MilestonePoints:z.number().nullish()}).passthrough(),JR=z.object({NodeID:z.string().nullish(),Type:z.string().nullish(),Identity:sn.nullish(),Pricing:Cc.nullish(),Reward:Sc.nullish(),Action:jR.nullish(),UnlockRules:$R.nullish(),NextNodeIDs:z.array(z.string()).nullish(),ChoiceGroupID:z.string().nullish(),Limits:ye.nullish(),HideWhenCompleted:z.boolean().nullish(),ExhaustOfferOnComplete:z.boolean().nullish(),Presets:KR.nullish()}).passthrough(),xc=z.object({RootNodeIDs:z.array(z.string()).nullish(),Nodes:z.array(JR).nullish(),Tracks:z.array(HR).nullish(),ExhaustedWhenAllTerminalNodesCompleted:z.boolean().nullish()}).passthrough(),bc=z.object({Milestones:z.record(z.string(),Be).nullish(),ClaimMode:z.string().nullish(),Token:jt.nullish()}).passthrough(),Dc=z.object({OfferID:z.string().nullish(),Version:z.number().nullish(),Enabled:z.boolean().nullish(),Identity:sn.nullish(),Graph:xc.nullish(),Milestones:bc.nullish(),Presets:WR.nullish()}).passthrough(),ZR=z.object({Identity:z.record(z.string(),sn).nullish(),Availability:z.record(z.string(),yc).nullish(),Behaviour:z.record(z.string(),Rc).nullish(),Graph:z.record(z.string(),xc).nullish(),Milestones:z.record(z.string(),bc).nullish(),Pricing:z.record(z.string(),Cc).nullish(),Reward:z.record(z.string(),Sc).nullish()}).passthrough(),qo=z.object({Slots:z.record(z.string(),VR).nullish(),Offers:z.record(z.string(),Dc).nullish(),Presets:ZR.nullish()}).passthrough(),Pc=z.object({DealOfferDefinitions:qo.nullish()}),Ic=z.object({DealOffers:qR.nullish()}),YR=z.object({EntityID:z.string().nullish(),TotalEarned:z.number().nullish(),ClaimedIDs:z.array(z.string()).nullish(),ReachedUnclaimedIDs:z.array(z.string()).nullish()}).passthrough(),XR=z.object({SlotID:z.string().nullish(),SortOrder:z.number().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),OfferDef:Dc.nullish(),ActivationState:gc.nullish(),IsNewActivation:z.boolean().nullish(),ComputedExpiresAtUtc:c.nullish(),Cost:xt.nullish(),Milestone:YR.nullish(),ScheduleInstanceKey:z.string().nullish()}).passthrough(),nn=z.object({Slots:z.array(XR).nullish()}),vc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),NodeID:z.string().nullish(),NodeCompleted:z.boolean().nullish(),OfferExhausted:z.boolean().nullish(),Idempotent:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Tc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),kc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),Ac=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),zc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),ClaimedIDs:z.array(z.string()).nullish(),Rejected:z.record(z.string(),z.string()).nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),yt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var eC="DealOffer",wc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},rn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(wc,{schema:nn,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(eC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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(wc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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,RelatedEntityID:n??`deal_exec_${e}_${t}_${d()}`},p=await this.ctx.api.dealOffer.executeNode(r);return p.ok&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;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$1;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$1;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}_${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 Mc="Referral",on=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Mc,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$1;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Mc,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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=Nt.parseReferralCode(e)?.toUpperCase();if(!t)return b("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return c$1;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),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$1;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$1;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 p of r.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",r);}return n}};var tC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Oc=z.enum(["System","Reward","Gift","Social"]).catch("System"),iC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},sC=z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),nC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},rC=z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),et={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},oC={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"},aC=100,lC=z.object({Subject:z.string().nullish(),Body:z.string().nullish()}).passthrough(),Ec=z.object({FeatureID:z.string().nullish(),Args:z.record(z.string(),z.string()).nullish(),Url:z.string().nullish(),Label:z.string().nullish()}).passthrough(),uC=z.object({Texts:z.record(z.string(),lC).nullish(),Category:Oc.nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Ec.nullish(),SenderName:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),cC=z.object({Enabled:z.boolean().nullish(),Grant:ue.nullish(),Cost:ue.nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:c.nullish(),SenderGate:Z.nullish(),TemplateID:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),pC=z.object({Type:z.string().nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxAmountPerGift:z.number().nullish()}).passthrough(),hC=z.object({Enabled:z.boolean().nullish(),AllowedResources:z.array(pC).nullish(),MaxEntriesPerGift:z.number().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:c.nullish(),FeePercent:z.number().nullish(),FeeCost:ue.nullish(),SenderGate:Z.nullish(),ExpirationDays:z.number().nullish(),TemplateID:z.string().nullish()}).passthrough(),Uc=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(),uC).nullish(),Gifts:z.object({Social:z.record(z.string(),cC).nullish(),Transfer:hC.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:sC,Category:Oc,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:Ec.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:c,ExpiresAt:c.nullish(),ReadAt:c.nullish(),ClaimedAt:c.nullish()}).passthrough(),mC=z.object({MessageID:z.string(),Module:rC,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(),Bo=z.object({ID:z.string(),Error:z.string().nullish()}).passthrough(),qc=z.object({ServerTimeUtc:c.nullish(),Messages:z.array(dC).default([]),NextCursor:z.string().nullish(),PendingRewards:z.array(mC).nullish(),UnreadCount:z.number().nullish(),UnclaimedCount:z.number().nullish(),DeliveredNow:z.number().nullish()}).passthrough(),an=z.object({ServerTimeUtc:c.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Lo=z.object({ServerTimeUtc:c.nullish(),AffectedCount:z.number().default(0),Failed:z.array(Bo).default([]),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),fC=z.object({MessageID:z.string(),Rewards:ue.nullish()}).passthrough(),ln=z.object({ServerTimeUtc:c.nullish(),Claimed:z.array(fC).default([]),Failed:z.array(Bo).default([]),Resources:M.nullish(),Inventory:Q.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Bc=z.object({ServerTimeUtc:c.nullish(),GiftID:z.string().nullish(),Sent:z.array(z.string()).default([]),Failed:z.array(Bo).default([]),Resources:M.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish()}).passthrough(),Lc=z.object({ServerTimeUtc:c.nullish(),MessageID:z.string().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),RecipientReceives:ue.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish(),IdempotentReplay:z.boolean().nullish()}).passthrough(),Gc=z.object({ServerTimeUtc:c.nullish(),ResetsAt:c.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:c.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:c.nullish()}).passthrough().nullish()}).passthrough();var Go="Mailbox",Fo={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},un=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Fo,{schema:an,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(Fo,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Go)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Go,e);if(t)return a(t);let i=this.request();if(!i)return c$1;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(Go,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$1;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(Fo,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return c$1;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$1;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$1}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$1}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):c$1}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$1;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$1;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$1;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$1}};var gC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},yC={Title:"Title",Platform:"Platform"},Fc=z.object({UserID:z.string(),PublicData:Oe.nullish(),Source:z.enum(["Title","Platform"]).nullish()}),vi=z.object({Friends:z.array(Fc).nullish()}),RC=z.object({FriendsCount:z.number().nullish(),IncomingRequestsCount:z.number().nullish(),OutgoingRequestsCount:z.number().nullish()}),Ti=z.object({TargetUserID:z.string().nullish(),Status:z.string().nullish(),Target:Fc.nullish(),Counters:RC.nullish()}),CC={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},SC={Like:"Like",Favorite:"Favorite"},xC={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},bC={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},DC={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},PC=z.object({Key:z.string().nullish(),DisplayName:z.string().nullish(),AvatarUrl:z.string().nullish()}).passthrough(),IC=z.object({Id:z.string(),Verb:z.string().nullish(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),Count:z.number().nullish(),LastActors:z.array(PC).nullish(),Payload:z.object({Title:z.string().nullish(),Excerpt:z.string().nullish(),ImageUrl:z.string().nullish()}).passthrough().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),OccurredAt:c.nullish(),OwnerImpact:M.nullish(),IsBlocked:z.boolean().nullish(),TargetObjectName:z.string().nullish()}).passthrough(),Vc=z.object({Items:z.array(IC).nullish(),HasMore:z.boolean().nullish(),NextBeforeUpdatedAt:z.string().nullish(),NextBeforeID:z.string().nullish(),UnreadCount:z.number().nullish(),SeenAt:c.nullish()}).passthrough(),ki=z.object({UnreadCount:z.number().nullish(),SeenAt:c.nullish()}).passthrough(),vC=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(),Bt=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Counts:vC.nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish(),Following:z.boolean().nullish(),Blocked:z.boolean().nullish()}).passthrough(),Nc=z.object({Items:z.array(Bt).nullish()}).passthrough(),Vo={HasMore:z.boolean().nullish(),NextCursorAt:z.string().nullish(),NextCursorID:z.string().nullish()},TC=z.object({UserID:z.string(),PublicData:Oe.nullish(),Mutual:z.boolean().nullish(),Since:c.nullish()}).passthrough(),cn=z.object({Items:z.array(TC).nullish(),...Vo}).passthrough(),kC=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Kind:z.string().nullish(),At:c.nullish()}).passthrough(),jc=z.object({Items:z.array(kC).nullish(),...Vo}).passthrough(),pn=z.object({CommentID:z.string(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),ParentCommentID:z.string().nullish(),AuthorUserID:z.string().nullish(),AuthorPublicData:Oe.nullish(),Text:z.string().nullish(),Status:z.string().nullish(),Pinned:z.boolean().nullish(),CreatedAt:c.nullish(),EditedAt:c.nullish(),Likes:z.number().nullish(),Replies:z.number().nullish(),Liked:z.boolean().nullish(),IsMine:z.boolean().nullish()}).passthrough(),_c=z.object({Items:z.array(pn).nullish(),...Vo,TotalCount:z.number().nullish()}).passthrough(),Wc=z.object({CommentID:z.string().nullish(),Deleted:z.boolean().nullish()}).passthrough(),Kc=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish(),AutoHidden:z.boolean().nullish()}).passthrough(),Qc=z.object({CommentsEnabled:z.boolean().nullish(),CommentableTypes:z.array(z.string()).nullish(),CommentMaxLength:z.number().nullish(),CommentMaxLinks:z.number().nullish()}).passthrough(),AC="FRIENDS_FROM_PLATFORM",zC={Off:"Off",Default:"Default",Always:"Always"},wC={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Hc=z.object({Profile:z.enum(["Off","Default","Always"]).nullish(),Friends:z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:z.boolean().nullish()}).passthrough(),Re={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 No={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},hn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(No,{schema:ki,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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(No,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(No,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$1}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$1}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$1;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$1;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$1}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$1}};var $c="TimedBoost";function MC(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var dn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection($c,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection($c,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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(!MC(i))return b("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${d()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok){let r=n.data;if(r.ActivatedBoost){let p=r.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(r.ActivatedBoost,p);}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$1;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 Tt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},OC={Client:"Client",Server:"Server",System:"System"},EC=z.enum(["Client","Server","System"]).catch("Client"),UC=z.object({Value:z.string().nullish(),UpdatedAt:c.nullish(),Version:z.number().nullish(),LastWriter:EC.nullish(),ExpiresAt:c.nullish()}).passthrough(),mn=z.record(z.string(),UC),Jc=z.object({Version:z.number().nullish(),Private:mn.nullish(),Public:mn.nullish(),ReadOnly:mn.nullish()}),jo=z.object({UserID:z.string().nullish(),Version:z.number().nullish(),Public:mn.nullish()}),_o=z.object({ServerTimeUtc:c.nullish(),Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:c.nullish()}),qC=z.object({Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:c.nullish()}),Zc=z.object({ServerTimeUtc:c.nullish(),Results:z.array(qC).nullish()}),Yc=z.object({ServerTimeUtc:c.nullish(),DeletedCount:z.number().nullish()}),Xc=z.object({Results:z.array(jo).nullish(),NotFoundUserIDs:z.array(z.string()).nullish()}),BC={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},LC=z.enum(["String","Int","Bool","Json"]).catch("String"),GC=z.object({KeyID:z.string(),Bucket:z.string().nullish(),ValueType:LC.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),fn=z.object({Keys:z.record(z.string(),GC).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),dt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var FC="UserCustomData";function ep(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var gn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(FC,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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,Tt.Private)}async setPublicData(e,t){return this.setData(e,t,Tt.Public)}async setData(e,t,i){let s=e.trim();if(!ep(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$1;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(i===Tt.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(p.ok){let d=p.data;this.ctx.data.user.patchUserCustomDataKey(i,d.KeyID,t,d.Version??0,d.ExpiresAt),this.ctx.emitter.emit(i===Tt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",d);}return p}async deleteKey(e,t){let i=e.trim();if(!ep(i))return b("client",'KeyID is required and must not contain "." or "$".');if(t!==Tt.Private&&t!==Tt.Public)return b("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return c$1;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$1;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??Tt.Private,r=e.find(p=>p.Bucket===n&&p.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$1;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$1;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 VC="TitleCustomDataDefinitions",tp=50;function NC(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}function Wo(o){if(o.ExpiresAt==null)return false;let e=Date.parse(o.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function jC(o){let e={};for(let[t,i]of Object.entries(o))Wo(i)||(e[t]=i);return e}var yn=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(VC,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return c$1;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=>!NC(n)))return b("client",'KeyID must not contain "." or "$".');if(t.length>tp)return b("client",`At most ${tp} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return c$1;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&&!Wo(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Wo(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=jC(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 Rn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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$1;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var _C=15,WC="GameLoop",ip="BoardDefinition",Cn=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$1;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(WC,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(ip,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),a(i);let s=this.ctx.authedRequest();if(!s)return c$1;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(ip,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$1;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$1;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$1;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,r=Ul(new Date,_C);this.ctx.data.user.patchBoardState(p=>{p.Position=n.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(n.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),n.ActionRequired&&n.ActionData?p.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&&(p.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$1;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$1;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 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$1;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$1;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(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){if(!e)return b("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${d()}`},n=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(n.ok){let r=n.data;r.Mode==="Instant"||r.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(d=>{d.ChoiceID=e,d.ChosenMode=r.Mode??"Timed",d.StartedAtUtc=r.StartedAtUtc??null,d.DurationSeconds=r.DurationSeconds??null,d.AdViewsUsed=0;}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",r);}return n}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return c$1;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(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$1;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$1;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$1;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$1;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$1;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$1;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 Sn=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$1;let r={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(r);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var sp=z.object({ServerTimeUtc:c,SourceType:ii,SourceID:z.string(),TargetType:ii,TargetID:z.string(),SourceSpent:_,FeeAmount:_,RateApplied:Y,TargetCredited:_}),np=z.object({ServerTimeUtc:c,SourceType:ii,SourceID:z.string(),TargetType:ii,TargetID:z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),xn={Convert:"Convert",CryptoConvert:"CryptoConvert"},KC={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},rp=z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),QC={Automatic:"Automatic",Manual:"Manual"},HC=z.enum(["Automatic","Manual"]).catch("Automatic"),$C=z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),InitialDeposit:z.number().nullish(),MinBalance:z.number().nullish(),MaxBalance:z.number().nullish(),DailyEarnLimit:z.number().nullish(),DailySpendLimit:z.number().nullish()}).passthrough(),JC=z.object({Rate:z.number().nullish(),Max:z.number().nullish(),Period:z.number().nullish()}).passthrough(),ZC=z.object({IsTradable:z.boolean().nullish(),IsPurchasable:z.boolean().nullish(),IsRefundable:z.boolean().nullish()}).passthrough(),YC=z.object({TargetCurrencyType:ii.nullish(),TargetCurrencyID:z.string(),Rate:Y.nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish(),DailyLimit:z.number().nullish()}).passthrough(),op=z.object({Enabled:z.boolean().nullish(),RateMode:HC.nullish(),Fee:z.number().nullish(),Targets:z.array(YC).nullish()}).passthrough(),ap=z.object({CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough(),XC=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Economy:$C.nullish(),Recharge:JC.nullish(),Conversion:op.nullish(),Permissions:ZC.nullish(),Audit:ap.nullish(),Status:rp.nullish()}).passthrough(),eS=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(),tS=z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),iS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),SpendableInGame:z.boolean().nullish(),ConvertibleToVirtual:z.boolean().nullish()}).passthrough(),sS=z.object({Mode:z.string().nullish(),FundingNetworkID:z.string().nullish(),PerPlayerDailyTokens:z.number().nullish(),TitleDailyTokens:z.number().nullish(),RefuseOverCap:z.boolean().nullish()}).passthrough(),Ko=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:c.nullish(),UsdPriceRefreshMinutes:z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:z.array(eS).nullish(),Limits:tS.nullish(),Permissions:iS.nullish(),Conversion:op.nullish(),Audit:ap.nullish(),Status:rp.nullish(),ServerGrantPolicy:sS.nullish(),UnbackedRewardCurrencyID:z.string().nullish()}).passthrough(),bn=z.object({VirtualCurrencies:z.record(z.string(),XC).nullish(),CryptoCurrencies:z.record(z.string(),Ko).nullish()}).passthrough();var nS={EVM:"EVM",Solana:"Solana"},rS=z.enum(["EVM","Solana"]).catch("EVM"),oS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},aS=z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),lS={Token:"Token",Nft:"Nft"},lp=z.enum(["Token","Nft"]).catch("Token"),uS={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},cS=z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),pS={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},hS=z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),dS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Qo=z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),up={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Dn(o){let e=o?.trim();return e||up.GameTopUp}var mS={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},cp=z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),fS=z.object({ContractAddress:z.string().nullish(),ItemCatalogID:z.string().nullish(),DisplayName:z.string().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),pp=z.object({Ios:z.boolean().nullish(),Android:z.boolean().nullish(),Web:z.boolean().nullish()}).passthrough(),gS=z.object({NetworkID:z.string().nullish(),DisplayName:z.string().nullish(),Type:rS.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:pp.nullish(),NftCollections:z.array(fS).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(),yS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:pp.nullish()}).passthrough(),RS=z.object({MinAccountAgeDays:z.number().nullish(),MultiAccountCheckEnabled:z.boolean().nullish(),BanOnSharedWithdrawalAddress:z.boolean().nullish(),PendingWithdrawalTtlHours:z.number().nullish()}).passthrough(),CS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},SS=z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),hp=z.object({Enabled:z.boolean().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:SS.nullish(),DenyMessage:z.string().nullish()}).passthrough(),xS=z.object({Enabled:z.boolean().nullish(),WalletConnectProjectId:z.string().nullish(),ShowOnLoginScreen:z.boolean().nullish()}).passthrough(),bS={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Ai=z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),DS=z.object({Mode:Ai.nullish(),TokenGates:z.array(hp).nullish()}).passthrough(),Ho=z.object({SystemState:yS.nullish(),Networks:z.record(z.string(),gS).nullish(),AccountSafety:RS.nullish(),WalletLogin:xS.nullish(),PlayAccess:DS.nullish(),IframeConnectHosts:z.array(z.string()).nullish()}).passthrough(),PS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),LinkedAt:c.nullish(),LastUsedAt:c.nullish(),LinkType:aS.nullish(),IsSignatureVerified:z.boolean().nullish()}).passthrough(),dp=z.object({TitleTransactionID:z.string().nullish(),Type:lp.nullish(),NetworkID:z.string().nullish(),AssetID:z.string().nullish(),Amount:Y.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),IS=z.object({Status:cS.nullish(),Tier:hS.nullish(),VerifiedAt:c.nullish(),ExpiresAt:c.nullish(),RejectedAt:c.nullish(),ProviderReference:z.string().nullish(),RejectionReason:z.string().nullish()}).passthrough(),vS=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:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),TS=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(),vS).nullish()}).passthrough(),kS=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:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),AS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),PerCollection:z.record(z.string(),kS).nullish()}).passthrough(),zS=z.object({Tokens:TS.nullish(),Nfts:AS.nullish()}).passthrough(),$o=z.object({CurrencyID:z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Lt=z.object({Granted:z.boolean(),Mode:Ai.nullish(),Error:z.string().nullish(),WalletRequired:z.boolean().nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),GrantedUntil:c.nullish(),Balances:z.array($o).nullish()}).passthrough(),wS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:c.nullish(),Passed:z.boolean().nullish(),GrantedUntil:c.nullish(),Error:z.string().nullish(),Balances:z.array($o).nullish()}).passthrough(),MS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CanUnlink:z.boolean().nullish()}).passthrough(),mp=z.object({Mode:Ai.nullish(),TokenGates:z.array(hp).nullish(),WalletLoginEnabled:z.boolean().nullish(),CanLinkWallet:z.boolean().nullish(),WalletsFromPlatformProfile:z.boolean().nullish(),LinkedWallets:z.array(MS).nullish(),Status:Lt.nullish()}).passthrough(),OS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:c.nullish(),LoggedInAt:c.nullish(),GatePassed:z.boolean().nullish(),GatedBalances:z.array($o).nullish()}).passthrough(),ES=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),UnlinkedAt:c.nullish()}).passthrough(),US=z.object({Version:z.number().nullish(),Stats:zS.nullish(),LinkedWallets:z.record(z.string(),PS).nullish(),LastWalletLogin:OS.nullish(),PlayAccess:wS.nullish(),PendingWithdrawals:z.array(dp).nullish(),Kyc:IS.nullish(),FirstActivityAt:c.nullish(),LastActivityAt:c.nullish(),IsFlagged:z.boolean().nullish(),FlagReason:z.string().nullish(),UnlinkedWallets:z.array(ES).nullish()}).passthrough(),qS=z.object({CurrencyID:z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:c}).passthrough(),hi=z.object({CryptoBalances:z.record(z.string(),qS).nullish(),PendingAdded:dp.nullish(),PendingRemovedIDs:z.array(z.string()).nullish()}).passthrough(),BS=z.object({Amount:Y,Frozen:Y,CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough().transform(o=>o),LS=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.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:Qo.nullish(),SignatureData:z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.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:c.nullish(),BurnAmount:z.number().nullish(),RefundedAt:c.nullish(),RefundCheckedAt:c.nullish()}).passthrough(),GS=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.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:Qo.nullish(),SignatureData:z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.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:c.nullish()}).passthrough(),fp=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),Jo=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(fp).nullish(),Signature:z.string().nullish()}).passthrough(),Zo=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(fp).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(),gp=z.object({Blockchain:Ho.nullish(),CryptoCurrencies:z.record(z.string(),Ko).nullish()}).passthrough(),yp=z.object({State:US.nullish(),CryptoBalances:z.record(z.string(),BS).nullish()}).passthrough(),Rp=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:hi.nullish()}).passthrough(),Cp=z.object({ServerTimeUtc:c.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:M.nullish(),Inventory:Q.nullish()}).passthrough(),Sp=z.object({ServerTimeUtc:c.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:c.nullish(),EvmSignature:Jo.nullish(),SolanaSignature:Zo.nullish(),StateDelta:hi.nullish(),ChainID:z.number().nullish()}).passthrough(),xp=z.object({ServerTimeUtc:c.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:c.nullish(),Resources:M.nullish(),EvmSignature:Jo.nullish(),SolanaSignature:Zo.nullish(),StateDelta:hi.nullish(),Inventory:Q.nullish()}).passthrough(),bp=z.object({TokenTransactions:z.array(LS).nullish(),NFTTransactions:z.array(GS).nullish(),RefundedIDs:z.array(z.string()).nullish()}).passthrough(),Yo=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:z.string().nullish()}).passthrough(),Dp=z.object({TitleTransactionID:z.string().nullish(),Kind:lp.nullish(),EvmSignature:Jo.nullish(),SolanaSignature:Zo.nullish()}).passthrough(),Pp=z.object({TitleTransactionID:z.string().nullish(),OnChainTxHash:z.string().nullish(),Status:Qo.nullish(),StateDelta:hi.nullish()}).passthrough(),Qe={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 FS="Blockchain",Ip="Blockchain:Definitions",Pn=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Ip,e);if(t)return a(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return c$1;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(FS,n.data.Blockchain),this.ctx.data.config.patchSection(Ip,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$1;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$1;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$1;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$1;r.CurrencyID=e,r.NetworkID=t,r.WalletAddress=i,r.Amount=s,r.Category=Dn(n);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(r);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,i,s,n,r,p){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 d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.NetworkID=t,d.WalletAddress=i,d.Amount=s,d.Category=Dn(n),r!==void 0&&(d.Level=r),p&&(d.ItemInstanceID=p);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(d);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$1;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$1;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$1;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$1;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$1;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$1;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$1;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var VS={Head:"Head",Torso:"Torso",Legs:"Legs"},In=z.enum(["Head","Torso","Legs"]).catch("Head"),NS={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},Xo=z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Tp=z.object({AttackTarget:In,DefenseTarget:In});var jS=z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),_S=z.object({RoundIndex:z.number().nullish(),AttackerID:z.string().nullish(),DefenderID:z.string().nullish(),AttackZone:In.nullish(),DefenseZone:In.nullish(),HitType:jS.nullish(),DamageDealt:z.number().nullish(),DefenderHpRemaining:z.number().nullish()}).passthrough(),WS=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(),KS=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:c,ExpiresAt:c.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),vp=z.object({UserID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),SelectedCharacter:Io.nullish(),BattleStrategy:z.array(Tp).nullish(),UnstackableItems:z.record(z.string(),KS).nullish(),Stats:WS.nullish()}).passthrough(),QS=z.object({WinnerUserID:z.string().nullish(),LoserUserID:z.string().nullish(),Entry:ue.nullish(),NetReward:ue.nullish(),BattleLog:z.array(_S).nullish(),IsDraw:z.boolean().nullish(),P1BattleProfile:vp.nullish(),P2BattleProfile:vp.nullish()}).passthrough(),kp=z.object({MatchID:z.string(),TitleID:z.string().nullish(),RuleID:z.string().nullish(),CreatedAt:c.nullish(),CreatorID:z.string().nullish(),CreatorCharacterID:z.string().nullish(),CreatorStrategy:z.array(Tp).nullish(),TargetUserID:z.string().nullish(),Entry:ue.nullish(),CreationCostPaid:ue.nullish(),RefundCreationCostOnCancel:z.boolean().nullish(),ExpiresAt:c.nullish(),JoinedByUserID:z.string().nullish(),JoinedByCharacterID:z.string().nullish(),JoinedAt:c.nullish(),Status:Xo.nullish(),WinnerUserID:z.string().nullish(),CompletedAt:c.nullish(),IsRewardDistributed:z.boolean().nullish(),RewardDistributedAt:c.nullish()}).passthrough(),Ap=z.object({Status:Xo,MatchID:z.string(),Entry:ue.nullish(),Resources:M.nullish()}),zp=z.object({Match:kp.nullish()}),wp=z.object({MatchID:z.string(),Status:Xo,Resources:M.nullish()}),Mp=z.object({Battle:QS.nullish(),Resources:M.nullish(),ResourcesDual:bt.nullish()}),ea=z.object({Matches:z.array(kp).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}),Rt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var HS=z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var $S=z.enum(["Constant","Variable","Curve"]).catch("Constant"),JS=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(),ZS=z.enum(["Flat","PercentReduction"]).catch("Flat"),YS=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:ZS.nullish(),MaxArmorReduction:z.number().nullish()}).passthrough(),XS=z.object({Kind:$S.nullish(),Constant:z.number().nullish(),VariableID:z.string().nullish(),Argument:z.string().nullish(),Curve:Fe.nullish(),OnePlus:z.boolean().nullish()}).passthrough(),ex=z.object({Coefficient:z.number().nullish(),Factors:z.array(XS).nullish()}).passthrough(),Kt=z.object({Terms:z.array(ex).nullish()}).passthrough(),tx=z.object({Health:Kt.nullish(),Damage:Kt.nullish(),Armor:Kt.nullish(),AttackSpeed:Kt.nullish(),CritChance:Kt.nullish(),CritDamage:Kt.nullish(),Dodge:Kt.nullish()}).passthrough(),Op=z.object({StatMapping:JS.nullish(),Combat:YS.nullish(),Formula:tx.nullish()}).passthrough(),ix=z.object({BurnRate:z.number().nullish()}).passthrough(),zi=z.object({Kind:HS.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),TokenType:Vi.nullish(),EntityID:z.string().nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish()}).passthrough(),Ep=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(zi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),Up=z.object({PriceOptions:le.nullish(),RefundCostOnCancel:z.boolean().nullish(),MaxOpenMatches:z.number().nullish(),OfferLifetimeSeconds:z.number().nullish(),Limits:ye.nullish(),AllowPrivateMatches:z.boolean().nullish(),MaxMatchesPerOpponentPerDay:z.number().nullish()}).passthrough(),sx=z.object({RuleID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Economy:ix.nullish(),Entry:Ep.nullish(),Creation:Up.nullish(),Settings:Op.nullish()}).passthrough(),nx=z.object({Rules:z.record(z.string(),sx).nullish(),Defaults:Op.nullish(),EntryDefaults:Ep.nullish(),CreationDefaults:Up.nullish()}).passthrough(),ta=z.object({InstantBattle:nx.nullish()}).passthrough(),qp=ta;var rx={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},ia=z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),ox={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},sa=z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),ax={Burn:"Burn",Ledger:"Ledger"},lx=z.enum(["Burn","Ledger"]).catch("Burn"),Tn={Item:"Item",VirtualCurrency:"VirtualCurrency"},na=z.enum(["Item","VirtualCurrency"]).catch("Item"),ux=z.object({Percent:z.number().nullish(),MinPerPosition:_.nullish()}).passthrough(),kn=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(zi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),ra=z.object({Percent:z.number().nullish(),MinPerPosition:_.nullish(),Sink:lx.nullish(),LedgerAccountID:z.string().nullish(),PerCatalogOverrides:z.record(z.string(),ux).nullish(),ApplyToDirectTrades:z.boolean().nullish()}).passthrough(),cx=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(),px=z.object({Enabled:z.boolean().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),MaxActiveListings:z.number().nullish(),CreateLimits:ye.nullish(),BuyLimits:ye.nullish(),ListingFeeOptions:le.nullish(),RefundListingFeeOnCancel:z.boolean().nullish()}).passthrough(),hx=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:_.nullish(),BidLimits:ye.nullish()}).passthrough(),dx=z.object({Enabled:z.boolean().nullish(),MaxActiveOrders:z.number().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),CreateLimits:ye.nullish(),FillLimits:ye.nullish()}).passthrough(),mx=z.object({Enabled:z.boolean().nullish(),OfferExpirationHours:z.number().nullish(),MaxPendingOutgoing:z.number().nullish(),AllowGifts:z.boolean().nullish(),CreateLimits:ye.nullish()}).passthrough(),fx=z.object({Enabled:z.boolean().nullish()}).passthrough(),oa=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:me.nullish(),PricePolicy:kn.nullish(),Commission:ra.nullish(),Tradability:cx.nullish(),Listings:px.nullish(),Auctions:hx.nullish(),BuyOrders:dx.nullish(),DirectTrades:mx.nullish(),Matching:fx.nullish()}).passthrough(),Bp=z.object({BidIndex:z.number().nullish(),UserID:z.string().nullish(),Amount:_.nullish(),Settled:z.boolean().nullish(),SettledAt:c.nullish()}).passthrough(),gx=z.object({BidAxisType:si.nullish(),BidCurrencyID:z.string().nullish(),BidCatalogID:z.string().nullish(),BidItemID:z.string().nullish(),StartingBid:_.nullish(),CurrentBid:_.nullish(),CurrentBidderID:z.string().nullish(),BidCount:z.number().nullish(),ExtensionCount:z.number().nullish(),PendingRefunds:z.array(Bp).nullish()}).passthrough(),vn=z.object({LastAt:c.nullish(),DailyCount:z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),yx=z.object({Create:vn.nullish(),Buy:vn.nullish(),Sell:vn.nullish(),Bid:vn.nullish()}).passthrough(),Rx=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),Cx=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:c,ExpiresAt:c.nullish(),EquippedSlot:Rx.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),kt=z.object({OfferID:z.string().nullish(),OfferType:ia.nullish(),Status:sa.nullish(),CreatorUserID:z.string().nullish(),CreatorPublicData:Oe.nullish(),TargetUserID:z.string().nullish(),GoodsType:na.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:_.nullish(),GoodsInstances:z.array(Cx).nullish(),Price:ue.nullish(),Auction:gx.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),Sx=z.object({GoodsType:na.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),CountsByType:z.partialRecord(ia,_).nullish()}).passthrough(),Lp=z.object({Definitions:oa.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish()}).passthrough(),aa=z.object({Offers:z.array(kt).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Gp=z.object({Groups:z.array(Sx).nullish()}).passthrough(),Fp=z.object({Offer:kt.nullish()}).passthrough(),at=z.object({OfferID:z.string().nullish(),Status:sa.nullish(),Settlement:bt.nullish(),Resources:M.nullish(),CommissionTaken:ue.nullish()}).passthrough(),wi=z.object({OfferID:z.string().nullish(),Offer:kt.nullish(),Resources:M.nullish(),Matched:z.boolean().nullish(),Settlement:at.nullish()}).passthrough(),Vp=z.object({OfferID:z.string().nullish(),CurrentBid:_.nullish(),BidCount:z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish()}).passthrough(),An=z.object({MyOffers:z.array(kt).nullish(),MyBids:z.array(kt).nullish(),MyBuyOrders:z.array(kt).nullish(),IncomingTrades:z.array(kt).nullish(),OutgoingTrades:z.array(kt).nullish(),Claimables:z.array(kt).nullish(),DrainedRefunds:z.array(Bp).nullish(),Limits:yx.nullish()}).passthrough(),xx=z.object({OfferID:z.string().nullish(),OfferType:ia.nullish(),FinalStatus:sa.nullish(),SellerUserID:z.string().nullish(),BuyerUserID:z.string().nullish(),GoodsType:na.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:_.nullish(),PricePaid:ue.nullish(),CommissionTaken:ue.nullish(),CompletedAt:c.nullish(),MyRole:z.string().nullish()}).passthrough(),Np=z.object({Entries:z.array(xx).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),ke={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 bx="Marketplace",jp={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"]},zn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(jp,{schema:An,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(bx,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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$1;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(jp,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return c$1;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$1;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,p){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 d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.PriceBundle=s,d.DurationHours=n,d.ItemInstanceIDs=r,d.SelectedOptionID=p;let R=await this.ctx.api.marketplace.createListing(d);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$1;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$1;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$1;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,p={}){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.BidAxisType=s,d.BidCurrencyID=p.bidCurrencyID,d.BidCatalogID=p.bidCatalogID,d.BidItemID=p.bidItemID,d.StartingBid=n,d.DurationHours=r,d.ItemInstanceIDs=p.itemInstanceIDs,d.SelectedOptionID=p.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(d);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$1;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$1;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$1;r.ItemID=e,r.CatalogID=t,r.GoodsAmount=i,r.PriceBundle=s,r.DurationHours=n;let p=await this.ctx.api.marketplace.createBuyOrder(r);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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$1;r.TargetUserID=e,r.CatalogID=t,r.ItemID=i,r.ItemInstanceIDs=s,r.RequestedBundle=n;let p=await this.ctx.api.marketplace.createDirectTrade(r);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return b("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;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$1;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$1;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=Tn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Tn.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 wn=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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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 _p=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Mn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1}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$1}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$1}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((d,R)=>{if("sourceAssetUrl"in d)return {Role:d.role,ContentType:d.contentType,SourceAssetUrl:d.sourceAssetUrl};let V=Wp(d.data,d.contentType);return t.set(R,V),{Role:d.role,ContentType:d.contentType,Size:V.size}}),s=e.thumbnail?Wp(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 d=0;d<r.length;d++){let R=r[d];if(!R||R.ServerCopy||!R.Url)continue;let V=t.get(d);if(!V)return b("client",`No bytes for file #${d+1}.`);let oe=await this.putBytes(R.Url,V,R.ContentType??V.type);if(!oe.ok)return oe}let p=n.data.ThumbnailUpload;if(p?.Url&&s){let d=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!d.ok)return d}return this.publishUploaded({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})}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):c$1}async publishUploaded(e){if(!e.ContentID)return b("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&(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$1}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)}${_p}`)}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$1}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):c$1}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)}${_p}`)}}contentRequest(e){if(!e)return b("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):c$1}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 Wp(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 Dx={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},Px=z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Ix={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Kp=z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),vx={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Qp=z.enum(["Everyone","Owner","Server"]).catch("Everyone"),Tx={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},kx=z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),Ax={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},zx=z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),wx={Count:"Count",Sum:"Sum"},Mx=z.enum(["Count","Sum"]).catch("Count"),Ox={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},Ex=z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),Ux={Strict:"Strict",Loose:"Loose"},qx=z.enum(["Strict","Loose"]).catch("Strict"),Bx=z.object({Kind:zx,Collection:z.string().nullish(),Validate:z.boolean().nullish()}),Lx=z.object({Type:Kp,ItemType:Kp.nullish(),Ref:Bx.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:Qp.optional(),ClientWritable:z.boolean().nullish(),Immutable:z.boolean().optional(),Description:z.string().nullish(),AllowedMimeTypes:z.array(z.string()).nullish(),MaxFileBytes:z.number().nullish()}),Gx=z.object({ID:z.string(),Components:z.array(z.object({Field:z.string(),Descending:z.boolean().optional()})).default([])}),On=z.object({Mode:kx,Role:z.string().nullish(),MembersField:z.string().nullish()}),Fx=z.object({Read:z.array(On).nullish(),Create:z.array(On).nullish(),Update:z.array(On).nullish(),Delete:z.array(On).nullish()}),la=z.object({Cost:ue.nullish(),Grant:ue.nullish()}),Vx=z.object({ID:z.string(),SortKey:z.string(),PartitionField:z.string().nullish(),PageSize:z.number().optional(),MaxItems:z.number().optional(),PublishItems:z.boolean().optional()}),Nx=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:Px,Mode:qx.optional(),SchemaVersion:z.number().optional(),Fields:z.record(z.string(),Lx).nullish(),SortKeys:z.array(Gx).nullish(),Access:Fx.nullish(),Limits:z.object({MaxItemBytes:z.number().nullish(),MaxItemsPerOwner:z.number().nullish(),TtlSeconds:z.number().nullish()}).nullish(),OnOwnerDeleted:Ex.optional(),Counters:z.array(z.object({ID:z.string(),Kind:Mx,SumField:z.string().nullish(),GroupBy:z.string().nullish(),Visibility:Qp.optional()})).nullish(),Economy:z.object({OnCreate:la.nullish(),OnUpdate:la.nullish(),OnDelete:la.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:z.array(Vx).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()}),Hp=z.object({Enabled:z.boolean().optional(),Collections:z.record(z.string(),Nx).default({})}),jx=z.object({FileID:z.string(),Url:z.string(),ContentType:z.string().nullish(),Size:z.number()}),$p=z.object({FileID:z.string(),UploadUrl:z.string(),ContentType:z.string(),MaxBytes:z.number(),ExpiresAt:z.string()}),di=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(),jx).nullish()}),ua=z.object({Item:di}),Jp=z.object({Items:z.array(di).default([]),Missing:z.array(z.string()).default([])}),ca=z.object({Items:z.array(di).default([]),NextCursor:z.string().nullish()}),Zp=z.object({Count:z.number(),Capped:z.boolean().optional()}),pa=z.object({Item:di,AlreadyExists:z.boolean().optional(),Economy:M.nullish()}),Yp=z.object({ItemID:z.string(),Deleted:z.boolean(),Economy:M.nullish()}),Xp=z.object({CounterID:z.string(),Group:z.unknown().optional(),Value:z.number()}),eh=z.object({Results:z.array(z.object({Op:z.string(),Collection:z.string(),ItemID:z.string(),Item:di.nullish(),Deleted:z.boolean().optional()})).default([])}),th=z.object({Roles:z.array(z.string()).default([])}),ih=z.object({Views:z.record(z.string(),z.string()).default({}),ItemUrlTemplate:z.string().nullish()}),sh=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({})}),nh=z.object({Page:z.number(),HasMore:z.boolean(),Items:z.array(di).default([])}),_x={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 Wx=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,ah=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,da=100,rh=25,oh=100;function Kx(o,e,t){return {Field:o,Op:e,Value:t}}var En=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$1)}get(e,t,i={}){let s=tt(e)??Mi(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=tt(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(r=>ah.test(r)))];return n.length?n.length>oh?Promise.resolve(b("client",`At most ${oh} 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=tt(e)??ha(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 p=await this.query(e,{...t,Cursor:r,Limit:t.Limit??da},i);if(!p.ok)return p;if(n.push(...p.data.Items),r=p.data.NextCursor??void 0,!r||n.length>=s)return a(n.slice(0,s))}}count(e,t={}){let i=tt(e)??ha(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=tt(e)??(i.itemID?Mi(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=tt(e)??Mi(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=tt(e)??Mi(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>rh)return Promise.resolve(b("client",`At most ${rh} operations per batch.`));let t=e.map(i=>tt(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=tt(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=tt(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 p=await this.putBytes(r.data.UploadUrl,i,r.data.ContentType||n);return p.ok?r:p}async getPublicViews(e){let t=tt(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 r=await this.fetchJson(n,sh);if(!r.ok)return r;let p=r.data.Partitions[i.partition??""],d=Math.max(1,i.page??1);if(!p||d>p.Pages)return a({pointer:r.data,page:{Page:d,HasMore:false,Items:[]}});let R=await this.fetchJson(`${r.data.BaseUrl}${p.Segment}/page-${d}.json`,nh);return R.ok?a({pointer:r.data,page:R.data}):R}getPublic(e,t){let i=tt(e)??Mi(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=tt(e)??ha(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$1)}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 tt(o){return Wx.test(o??"")?null:b("client",`Collection id '${o}' is invalid (letters, digits, '_', '-', ':').`)}function Mi(o){return ah.test(o??"")?null:b("client",`Item id '${o}' is invalid.`)}function ha(o){return o.Limit!=null&&(o.Limit<1||o.Limit>da)?b("client",`Limit must be 1..${da}.`):(o.Where?.length??0)>8?b("client","At most 8 filters per query."):null}var ma={Open:"Open",Declared:"Declared"},Qx=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Blocked:z.boolean().nullish(),Highlight:z.number().nullish()}).passthrough(),Hx=z.object({ParamName:z.string().nullish(),DisplayName:z.string().nullish()}).passthrough(),lh=z.object({Enabled:z.boolean().nullish(),EventNaming:z.string().nullish(),Events:z.record(z.string(),Qx).nullish(),Dimensions:z.array(Hx).nullish(),RetentionDays:z.number().nullish(),AutomaticEvents:z.boolean().nullish()}).passthrough(),Gt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Ct={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Un=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,$x={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},Jx=z.object({Index:z.number().nullish(),Name:z.string().nullish(),Reason:z.string().nullish()}).passthrough(),uh=z.object({Accepted:z.number().nullish(),Dropped:z.array(Jx).nullish(),Duplicate:z.boolean().nullish(),Disabled:z.boolean().nullish()}).passthrough(),fa={LogEvents:"LogEvents"};function ch(o,e=0){let t=o??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let p=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let p=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let 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 ph(o){let e=typeof navigator>"u"?void 0:navigator,t=ch(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 Zx=25,Yx=3e4,hh=1800*1e3,dh=500,Xx=5,eb=1e3,tb=3600*1e3,mh="idos_analytics_queue",ga="idos_analytics_pending",ya="idos_analytics_opt_out",fh="idos_analytics_first_open",gh="idos_analytics_last_activity",yh="idos_analytics_last_context",Rh="idos_analytics_owner",qn=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"||!Un.test(e)?b("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):ib(e)?b("client",`Event name "${e}" uses a reserved prefix (${Ct.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(Gt.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,Ct.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return c$1;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>=Xx)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(ya);return}this.write(ya,"1"),this.clear();}get isEnabled(){return this.read(ya)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(Rh);e&&t&&t!==e&&this.clear(),e&&this.write(Rh,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Yx),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(gh)??"0");this.read(fh)||(this.write(fh,new Date().toISOString()),this.enqueue(Gt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(yh);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Gt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Gt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(yh,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=hh)&&this.enqueue(Gt.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>=hh&&this.enqueue(Gt.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()===ma.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=sb(t);if(r.error)return b("client",r.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return r.params&&(p.Params=r.params),i!==void 0&&(p.Value=i),this.queue.push(p),this.queue.length>dh&&this.queue.splice(0,this.queue.length-dh),this.touch(),this.persist(),this.started&&this.queue.length>=Zx&&this.flush(),a(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},eb));}dropStale(){let e=Date.now()-(Ct.maxEventAgeMs-tb);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??=ph({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(mh);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(ga);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(mh,this.queue),this.pending?this.writeJson(ga,this.pending):this.remove(ga);}touch(){this.write(gh,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 ib(o){let e=o.toLowerCase();return Ct.reservedPrefixes.some(t=>e.startsWith(t))}function sb(o){if(!o)return {};let e=Object.keys(o);if(e.length===0)return {};if(e.length>Ct.maxParams)return {error:`Too many parameters: ${e.length}, max ${Ct.maxParams}.`};let t={};for(let i of e){if(!Un.test(i))return {error:`Invalid parameter name "${i}".`};let s=o[i];typeof s=="string"?t[i]=s.length>Ct.maxStringValueLength?s.slice(0,Ct.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var nb="idos_experiments",Bn=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$1;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.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 `${nb}:${this.ctx.settings.titleID}`}};function Ft(o,e,t,i){let n=`api/v2/${o&&o.length>0?o:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Ft(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 Ln=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(fa.LogEvents,e,uh,{silent:true})}};var rb=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(),ob={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},ab=z.object({MetricID:z.string().nullish(),Kind:z.string().nullish(),EventName:z.string().nullish(),IsPrimary:z.boolean().nullish()}).passthrough(),lb=z.object({ExperimentID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),IsEnabled:z.boolean().nullish(),Schedule:me.nullish(),Gate:Z.nullish(),Variants:z.array(rb).nullish(),Salt:z.string().nullish(),LayerID:z.string().nullish(),StickyAssignment:z.boolean().nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Goals:z.array(ab).nullish(),ActivationEvent:z.string().nullish(),RolloutVariantID:z.string().nullish()}).passthrough(),Ch=z.object({Experiments:z.record(z.string(),lb).nullish()}).passthrough(),ub={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},cb=z.object({ExperimentID:z.string().nullish(),VariantID:z.string().nullish(),Status:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),Sh=z.object({Experiments:z.array(cb).nullish(),IsAbTestingAvailable:z.boolean().nullish()}).passthrough(),Ra={GetExperiments:"GetExperiments"};var Gn=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Ra.GetExperiments,e,Sh)}};var xh=z.object({PlatformUserID:z.string().nullish(),PlatformAuthToken:z.string().nullish(),PlatformAuthTokenExpiration:c.nullish(),TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:c,PlayAccess:Lt.nullish(),RefreshToken:z.string().nullish(),RefreshTokenExpiration:c.nullish()}),bh=z.object({TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:c,RefreshToken:z.string(),RefreshTokenExpiration:c.nullish(),PlayAccess:Lt.nullish()}),pb=z.object({ReturnMode:z.string().nullish(),UrlScheme:z.string().nullish(),UserCodeSupported:z.boolean().nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),Dh=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:Ai.nullish(),WalletLoginNetworks:z.array(z.object({NetworkID:z.string().nullish(),Type:z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:z.boolean().nullish(),NativeSso:pb.nullish()}).passthrough(),Ph=z.object({Linked:z.boolean().nullish(),Challenge:z.string().nullish(),ExpiresAt:c.nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),PlayAccess:Lt.nullish()}).passthrough(),Ih=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CooldownUntil:c.nullish(),PlayAccess:Lt.nullish()}).passthrough(),vh=z.object({CodeTtlMinutes:z.number().nullish(),ResendCooldownSeconds:z.number().nullish()}),Ee=z.object({IsCompleted:z.boolean().nullish(),ServerTime:c.nullish()}),Th=z.object({Message:z.string(),ExpiresAt:c}),Ue={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var Fn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Ft(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,xh,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ue.RefreshSession),e,bh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ue.GetAuthOptions),e,Dh,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Ft(this.ctx.settings.titleID,"Authentication",Ue.LinkWallet,e.UserID??""),e,Ph,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Ft(this.ctx.settings.titleID,"Authentication",Ue.UnlinkWallet,e.UserID??""),e,Ih,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ue.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ue.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ue.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ue.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ue.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ue.LoginWithSsoCode,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ue.RegisterWithEmail),e,vh,{ticket:null})}confirmEmailRegistration(e){return this.login(Ue.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ue.ResendVerificationCode),e,Ee,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ue.RequestWalletChallenge),e,Th,{ticket:null})}loginWithWallet(e){return this.login(Ue.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ue.ForgotPassword),e,Ee,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ue.ResetPassword),e,Ee,{ticket:null})}};var hb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},kh=z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),db=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),IsEnabled:z.boolean().nullish(),Order:z.number().nullish()}).passthrough(),Ah=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),Locales:z.record(z.string(),db).nullish(),MissingKeyMode:kh.nullish(),MaxEntriesPerLocale:z.number().nullish(),MaxValueLengthBytes:z.number().nullish()}).passthrough(),mb=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish()}).passthrough(),zh=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish(),Fallback:mb.nullish()}).passthrough(),Vn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},fb=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),Order:z.number().nullish(),Version:z.number().nullish()}).passthrough(),wh=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),MissingKeyMode:kh.nullish(),ResolvedLocale:z.string().nullish(),Locales:z.array(fb).nullish()}).passthrough(),Mh=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 Ca=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:zh.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),Oh=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish()}).passthrough().transform(o=>o),Eh=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),User:z.unknown().nullish()}).passthrough().transform(o=>o),Uh=z.object({}).passthrough().transform(o=>o),qh=z.object({}).passthrough().transform(o=>o),Bh=z.object({Today:z.number(),Yesterday:z.number(),CurrentWeek:z.number(),CurrentMonth:z.number(),Total:z.number(),TotalSessions:z.number(),FirstActiveAt:c.nullish(),LastActiveAt:c.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(),Lh=z.object({Username:z.string()}),lt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Nn=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(lt.GetClientState,e,Ca)}getClientStateExcept(e){return this.send(lt.GetClientStateExcept,e,Ca)}getStateVersions(e){return this.send(lt.GetStateVersions,e,Oh)}getUserState(e){return this.send(lt.GetUserState,e,Eh)}getInventory(e){return this.send(lt.GetInventory,e,Uh)}getEventTokens(e){return this.send(lt.GetEventTokens,e,qh)}getUsageTime(e){return this.send(lt.GetUsageTime,e,Bh)}addUsageTime(e){return this.send(lt.AddUsageTime,e,Ee,{silent:true})}deleteUserAccount(e){return this.send(lt.DeleteUserAccount,e,Ee)}changeUsername(e){return this.send(lt.ChangeUsername,e,Lh)}};var jn=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(xn.Convert,e,sp)}cryptoConvert(e){return this.send(xn.CryptoConvert,e,np)}};var gb=z.object({ItemInstanceID:z.string(),Units:z.number(),Level:z.number()}),Sa=z.object({ServerTimeUtc:c,ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Level:z.number(),Resources:M.nullish(),FodderConsumed:z.array(gb).nullish()}),Gh=z.array(Pe(Sa)),_n={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},yb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},Rb=z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Cb={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Sb=z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),xb=z.object({ContractAddress:z.string().nullish(),TokenID:z.string().nullish(),TokenStandard:z.string().nullish(),MaxLevel:z.number().nullish()}).passthrough(),bb=z.object({Networks:z.record(z.string(),xb).nullish(),MetadataUrl:z.string().nullish()}).passthrough(),Db=z.object({FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),Pb=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(),Ib=z.object({ValuationMode:Rb.nullish(),WeightCurve:Fe.nullish(),Selection:Sb.nullish()}).passthrough(),vb=z.object({MaxLevel:z.number().nullish(),PriceOptions:le.nullish(),CostCurve:Fe.nullish(),FlatBonusCurve:Fe.nullish(),PercentBonusCurve:Fe.nullish(),PowerCurve:Fe.nullish(),Fodder:Ib.nullish()}).passthrough(),Tb=z.object({RarityID:z.string().nullish(),CollectionID:z.string().nullish(),AuthorID:z.string().nullish()}).passthrough(),kb=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:bb.nullish(),Stats:Db.nullish(),Equipment:Pb.nullish(),Upgrade:vb.nullish(),Metadata:Tb.nullish(),ExpirationDurationSeconds:z.number().nullish(),MaxSupply:z.number().nullish()}).passthrough(),Ab=z.object({Items:z.record(z.string(),kb).nullish()}).passthrough(),Wn=z.object({Catalogs:z.record(z.string(),Ab).nullish()}).passthrough();var Kn=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(_n.UpgradeLevel,e,Sa)}upgradeLevelsBatch(e){return this.send(_n.UpgradeLevelsBatch,e,Gh)}};var Qn=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(Pt.Purchase,e,ho)}purchaseBatch(e){return this.send(Pt.PurchaseBatch,e,_l)}getDefinitions(e){return this.send(Pt.GetDefinitions,e,ms)}getUserState(e){return this.send(Pt.GetUserState,e,Wl)}getStorefront(e){return this.send(Pt.GetStorefront,e,fs)}getCreditsConfirmation(e){return this.send(Pt.GetCreditsConfirmation,e,po)}getCreditsBalance(e){return this.send(Pt.GetCreditsBalance,e,jl)}};var zb={Apple:"Apple",Google:"Google"},Hn=z.object({PremiumID:z.string().nullish(),PurchaseDate:z.string().nullish(),ExpirationDate:z.string().nullish(),TransactionID:z.string().nullish(),IsAutoRenewEnabled:z.boolean().nullish()}).passthrough(),$n=z.object({Subscriptions:z.record(z.string(),Hn).nullish(),ActivatedTrialIDs:z.array(z.string()).nullish(),MaxActiveTier:z.number().nullish()}).passthrough().transform(o=>o),wb=z.object({PremiumID:z.string().nullish(),DisplayName:z.string().nullish(),Tier:z.number().nullish(),DurationDays:z.number().nullish(),TrialDurationDays:z.number().nullish(),PriceOptions:le.nullish(),Benefits:z.record(z.string(),z.string()).nullish()}).passthrough(),xa=z.object({Definitions:z.record(z.string(),wb).nullish()}).passthrough(),Fh=z.object({Premium:xa.nullish()}),Vh=z.object({ServerTimeUtc:c.nullish(),Premium:$n.nullish()}),Jn=z.object({ServerTimeUtc:c.nullish(),Premium:$n.nullish(),Subscription:Hn.nullish(),Resources:M.nullish()}),Qt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var Mb={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},Ob=z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Nh=z.object({StartUtc:c.nullish(),EndUtc:c.nullish(),Gate:Z.nullish(),Limits:ye.nullish()}).passthrough(),ba=z.object({ResourceAction:z.string().nullish(),RevokeEntitlement:z.boolean().nullish(),BlockFuturePurchases:z.boolean().nullish()}).passthrough(),Eb=z.object({PremiumID:z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:z.number().nullish(),RevokeOnRefund:z.boolean().nullish()}).passthrough(),Ub=z.object({Rewards:K.nullish(),Rules:K.nullish(),Refund:K.nullish()}).passthrough(),qb=z.object({ProductID:z.string().nullish(),Name:z.string().nullish(),Type:Ob.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:Nh.nullish(),Refund:ba.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Subscription:Eb.nullish(),Presets:Ub.nullish()}).passthrough(),Bb=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(),Lb=z.object({Rewards:H.nullish()}).passthrough(),Gb=z.object({Rules:Nh.nullish()}).passthrough(),Fb=z.object({Refund:ba.nullish()}).passthrough(),Vb=z.object({Rewards:z.record(z.string(),Lb).nullish(),Rules:z.record(z.string(),Gb).nullish(),Refund:z.record(z.string(),Fb).nullish()}).passthrough(),Nb=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(),jb=z.object({Enabled:z.boolean().nullish(),Products:z.record(z.string(),qb).nullish(),Stores:z.record(z.string(),Bb).nullish(),Presets:Vb.nullish(),Validation:Nb.nullish(),Refund:ba.nullish()}).passthrough(),jh=z.object({ProductID:z.string().nullish(),TotalPurchases:z.number().nullish(),DailyPurchases:z.number().nullish(),DailyResetUtc:c.nullish(),LastPurchasedAt:c.nullish(),Owned:z.boolean().nullish(),Refunded:z.boolean().nullish(),PurchaseBlocked:z.boolean().nullish(),Store:z.string().nullish(),LastTransactionID:z.string().nullish()}).passthrough(),_h=z.object({ProductID:z.string().nullish(),PremiumID:z.string().nullish(),Store:z.string().nullish(),OriginalTransactionID:z.string().nullish(),LastTransactionID:z.string().nullish(),ExpiresAt:c.nullish(),AutoRenew:z.boolean().nullish(),Status:z.string().nullish(),RenewalCount:z.number().nullish(),LastStoreCheckAt:c.nullish(),LastStoreCheckError:z.string().nullish(),UpdatedAt:c.nullish()}).passthrough(),_b=z.object({Products:z.record(z.string(),jh).nullish(),LifetimeSpendUsdCents:z.number().nullish(),Subscriptions:z.record(z.string(),_h).nullish(),LastRefundCheckAt:c.nullish(),TotalPurchases:z.number().nullish(),FirstPurchaseAt:c.nullish(),LastPurchaseAt:c.nullish()}).passthrough(),Wb=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(),Wh=z.object({ServerTimeUtc:c,Purchase:jb.nullish(),Availability:z.array(Wb).nullish()}),Kh=z.object({ServerTimeUtc:c,Purchase:_b.nullish()}),Kb={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},Qb=z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Da=z.object({ServerTimeUtc:c,Store:Fi.nullish(),ProductID:z.string().nullish(),TransactionID:z.string().nullish(),Status:Qb.nullish(),Granted:z.boolean().nullish(),Quantity:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),ProductState:jh.nullish(),Premium:$n.nullish(),Subscription:Hn.nullish(),SubscriptionMirror:_h.nullish()}).passthrough(),Qh=z.object({ServerTimeUtc:c,ProductID:z.string().nullish(),Stars:z.number().nullish(),InvoiceLink:z.string(),ExpiresAt:c.nullish()}).passthrough(),Hh=ft(Da),Ht={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var Zn=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(Ht.GetDefinitions,e,Wh)}getUserState(e){return this.send(Ht.GetUserState,e,Kh)}validatePurchase(e){return this.send(Ht.ValidatePurchase,e,Da)}validatePurchasesBatch(e){return this.send(Ht.ValidatePurchasesBatch,e,Hh)}createTelegramInvoice(e){return this.send(Ht.CreateTelegramInvoice,e,Qh)}};var Hb=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),$h=z.object({Reward:H.nullish(),Weight:z.number().nullish(),AmountRange:Hb.nullish()}).passthrough(),mi=z.object({SlotID:z.string().nullish(),MinRolls:z.number().nullish(),MaxRolls:z.number().nullish(),Pool:z.array($h).nullish()}).passthrough(),fi=z.object({RuleID:z.string().nullish(),Threshold:z.number().nullish(),Pool:z.array($h).nullish()}).passthrough(),$b=z.object({RewardSlots:z.array(mi).nullish()}).passthrough(),Jb=z.object({PityRules:z.array(fi).nullish()}).passthrough(),Yn=z.object({SlotPresets:z.record(z.string(),$b).nullish(),PityPresets:z.record(z.string(),Jb).nullish()}).passthrough();var Zb=z.object({RuleID:z.string(),BoxIndex:z.number().nullish()}),Jh=z.object({ServerTimeUtc:c,LootboxID:z.string(),OpenedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:z.array(M).nullish(),TriggeredPity:z.array(Zb).nullish()}),Yb=z.object({RewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),Xb=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxDrops:_.nullish()}).passthrough(),eD=z.object({LootboxID:z.string(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:le.nullish(),RewardSlots:z.array(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:Yb.nullish(),RewardMultiplier:Ni.nullish(),SupplyLimits:z.array(Xb).nullish(),MaxOpenCount:z.number().nullish()}).passthrough(),tD=z.object({MaxOpenCount:z.number().nullish()}).passthrough(),Pa=z.object({Definitions:z.record(z.string(),eD).nullish(),RewardPools:Yn.nullish(),Settings:tD.nullish()}).passthrough(),Zh=z.object({LootboxDefinitions:Pa.nullish()}),Xn={GetDefinitions:"GetDefinitions",Open:"Open"};var er=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(Xn.GetDefinitions,e,Zh)}open(e){return this.send(Xn.Open,e,Jh)}};var iD=z.object({}).passthrough().transform(o=>o),sD=z.object({}).passthrough().transform(o=>o),nD=z.object({}).passthrough().transform(o=>o),rD=z.object({}).passthrough().transform(o=>o),oD=z.object({}).passthrough().transform(o=>o),Yh=z.object({ServerTimeUtc:c,CalendarID:z.string(),DayNumber:z.number().nullish(),DailyState:iD,Resources:M.nullish(),Inventory:Q.nullish()}),Xh=z.object({ServerTimeUtc:c,AccrualID:z.string(),AccruedSeconds:_.nullish(),AppliedRatePerSecond:z.number().nullish(),IdleState:sD,Resources:M.nullish(),Inventory:Q.nullish()}),ed=z.object({ServerTimeUtc:c,ComebackID:z.string(),ClaimedTierIndex:z.number().nullish(),ComebackState:nD,Resources:M.nullish(),Inventory:Q.nullish()}),td=z.object({ServerTimeUtc:c,ClaimID:z.string(),ClaimState:rD,Resources:M.nullish(),Inventory:Q.nullish()}),id=z.object({Enabled:z.boolean(),Multiplier:z.number().nullish(),Progress:_.nullish(),Source:z.string().nullish(),SourceKey:z.string().nullish()}),aD=z.object({RewardMode:z.string().nullish(),RewardStackLowerTiers:z.boolean().nullish()}).passthrough(),lD=z.object({DayNumber:z.number().nullish(),Rewards:H.nullish(),IsMilestone:z.boolean().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Oi=z.object({Gate:Z.nullish(),Limits:ye.nullish()}).passthrough(),Ia=z.object({Availability:K.nullish()}).passthrough(),uD=z.object({Availability:z.record(z.string(),Oi).nullish()}).passthrough(),cD=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(lD).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:Oi.nullish(),Presets:Ia.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),pD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Multiplier:z.number().nullish()}).passthrough(),hD=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(pD).nullish()}).passthrough(),dD=z.object({MinCharacterLevel:z.number().nullish(),RequirementsCharacterID:z.string().nullish(),Availability:Oi.nullish(),RequiredItemIDs:z.array(z.string()).nullish(),RequiredEquippedItemIDs:z.array(z.string()).nullish()}).passthrough(),mD=z.object({AccrualID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rate:hD.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:z.number().nullish(),MinClaimSeconds:z.number().nullish(),Requirements:dD.nullish(),FirstClaimMode:z.string().nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),fD=z.object({MinAbsenceSeconds:z.number().nullish(),Rewards:H.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),gD=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(fD).nullish(),ClaimCooldownSeconds:z.number().nullish(),ClaimWindowSeconds:z.number().nullish(),TrackPresenceOnRead:z.boolean().nullish(),Availability:Oi.nullish(),Presets:Ia.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(),RD=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:Oi.nullish(),Presets:Ia.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),va=z.object({TierRewards:aD.nullish(),MilestoneRewardMultiplier:Ni.nullish(),DailyCalendars:z.record(z.string(),cD).nullish(),IdleAccruals:z.record(z.string(),mD).nullish(),Comebacks:z.record(z.string(),gD).nullish(),Claims:z.record(z.string(),RD).nullish(),Presets:uD.nullish()}).passthrough(),sd=z.object({RewardDefinitions:va.nullish()}),nd=z.object({Rewards:oD.nullish()}),At={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var tr=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(At.GetRewardDefinitions,e,sd)}getUserRewardsState(e){return this.send(At.GetUserRewardsState,e,nd)}getMilestoneRewardMultiplier(e){return this.send(At.GetMilestoneRewardMultiplier,e,id)}claimDailyReward(e){return this.send(At.ClaimDailyReward,e,Yh)}collectIdleAccrual(e){return this.send(At.CollectIdleAccrual,e,Xh)}claimComebackReward(e){return this.send(At.ClaimComebackReward,e,ed)}claimReward(e){return this.send(At.ClaimReward,e,td)}};var ir=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(nt.GetTutorialDefinitions,e,Dl)}getUserTutorialState(e){return this.send(nt.GetUserTutorialState,e,Wi)}startFlow(e){return this.send(nt.StartFlow,e,wt)}reportStepShown(e){return this.send(nt.ReportStepShown,e,wt)}completeStep(e){return this.send(nt.CompleteStep,e,wt)}completeStepsBatch(e){return this.send(nt.CompleteStepsBatch,e,vl)}skipStep(e){return this.send(nt.SkipStep,e,wt)}skipFlow(e){return this.send(nt.SkipFlow,e,wt)}claimFlowReward(e){return this.send(nt.ClaimFlowReward,e,Il)}resetFlow(e){return this.send(nt.ResetFlow,e,wt)}};var CD={Open:"Open",Application:"Application"},SD=z.enum(["Open","Application"]).catch("Open"),xD={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},rd=z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),bD={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Ta=z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),DD={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var $t={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},PD=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(),od=z.object({IsEnabled:z.boolean().nullish(),CreatorPortalUrl:z.string().nullish(),ParticipationMode:SD.nullish(),IsCreator:z.boolean().nullish(),CreatorStatus:rd.nullish(),VerificationCode:z.string().nullish(),TeamID:z.string().nullish(),Campaigns:z.array(PD).nullish()}).passthrough(),ID=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(),vD=z.object({CampaignID:z.string().nullish(),CurrencyKind:Ta.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(),ID).nullish(),ComputedAt:z.string().nullish()}).passthrough(),TD=z.object({PayoutID:z.string().nullish(),CampaignID:z.string().nullish(),Amount:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Ta.nullish(),NetworkID:z.string().nullish(),PaidAt:z.string().nullish()}).passthrough(),ad=z.object({ServerTimeUtc:z.string().nullish(),HoldDays:z.number().nullish(),Campaigns:z.array(vD).nullish(),Payouts:z.array(TD).nullish()}).passthrough(),ld=z.object({CampaignID:z.string().nullish(),PayoutID:z.string().nullish(),Claimed:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Ta.nullish(),NetworkID:z.string().nullish(),RemainingFraction:z.number().nullish(),IdempotentReplay:z.boolean().nullish(),Message:z.string().nullish()}).passthrough(),kD=z.object({To:z.string().nullish(),Amount:z.string().nullish()}).passthrough(),AD=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(kD).nullish()}).passthrough(),zD=z.object({Kind:z.string().nullish(),Target:z.string().nullish(),Required:z.number().nullish(),Actual:z.number().nullish(),Passed:z.boolean().nullish()}).passthrough(),ud=z.object({Passed:z.boolean().nullish(),Approved:z.boolean().nullish(),Status:rd.nullish(),WalletMissing:z.boolean().nullish(),WalletConnectAllowed:z.boolean().nullish(),Conditions:z.array(zD).nullish()}).passthrough(),wD=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),MD=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(wD).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(),cd=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:AD.nullish(),SolanaSignature:MD.nullish(),StateDelta:hi.nullish()}).passthrough();var sr=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send($t.GetCommunityMarketingState,e,od)}getEarnings(e){return this.send($t.GetEarnings,e,ad)}claim(e){return this.send($t.Claim,e,ld)}checkJoinEligibility(e){return this.send($t.CheckJoinEligibility,e,ud)}withdrawCryptoReward(e){return this.send($t.WithdrawCryptoReward,e,cd)}};var nr=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(Ke.GetChatDefinitions,e,au)}getChannels(e){return this.send(Ke.GetChannels,e,Is)}poll(e){return this.send(Ke.Poll,e,lu)}getHistory(e){return this.send(Ke.GetHistory,e,uu)}getConversations(e){return this.send(Ke.GetConversations,e,hu)}sendMessage(e){return this.send(Ke.SendMessage,e,cu)}openDirectChannel(e){return this.send(Ke.OpenDirectChannel,e,pu)}markRead(e){return this.send(Ke.MarkRead,e,ci)}joinChannel(e){return this.send(Ke.JoinChannel,e,ci)}leaveChannel(e){return this.send(Ke.LeaveChannel,e,ci)}reportMessage(e){return this.send(Ke.ReportMessage,e,du)}ignoreUser(e){return this.send(Ke.IgnoreUser,e,ci)}unignoreUser(e){return this.send(Ke.UnignoreUser,e,ci)}};var rr=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(pi.GetPushConfig,e,gu)}subscribePush(e){return this.send(pi.SubscribePush,e,yo)}unsubscribePush(e){return this.send(pi.UnsubscribePush,e,Ee)}getPushSubscriptions(e){return this.send(pi.GetPushSubscriptions,e,yu)}};var or=class extends B{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(Vn.GetLocalizationManifest,e,wh)}getLocalizationTable(e){return this.send(Vn.GetLocalizationTable,e,Mh)}};var ar=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(pt.GetQuestDefinitions,e,_i)}getUserQuestState(e){return this.send(pt.GetUserQuestState,e,pl)}refreshQuestCycles(e){return this.send(pt.RefreshQuestCycles,e,Ee)}claimQuestReward(e){return this.send(pt.ClaimQuestReward,e,Xr)}claimQuestRewardsBatch(e){return this.send(pt.ClaimQuestRewardsBatch,e,ml)}claimMilestoneReward(e){return this.send(pt.ClaimMilestoneReward,e,eo)}claimMilestoneRewardsBatch(e){return this.send(pt.ClaimMilestoneRewardsBatch,e,fl)}claimGroupCompletionReward(e){return this.send(pt.ClaimGroupCompletionReward,e,hl)}addQuestProgress(e){return this.send(pt.AddQuestProgress,e,dl)}};var lr=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ot.GetActiveEvents,e,Ms)}getDefinitions(e){return this.send(ot.GetDefinitions,e,ws)}getUserLteState(e){return this.send(ot.GetUserLteState,e,xu)}grantTokens(e){return this.send(ot.GrantTokens,e,M)}spendTokens(e){return this.send(ot.SpendTokens,e,So)}claimMilestone(e){return this.send(ot.ClaimMilestone,e,xo)}claimMilestonesBatch(e){return this.send(ot.ClaimMilestonesBatch,e,bo)}claimAllMilestones(e){return this.send(ot.ClaimAllMilestones,e,bo)}spendTokensBatch(e){return this.send(ot.SpendTokensBatch,e,bu)}grantTokensBatch(e){return this.send(ot.GrantTokensBatch,e,Du)}};var ur=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ve.GetDefinitions,e,Gs)}getLeaderboard(e){return this.send(Ve.GetLeaderboard,e,Pi)}getMyProgress(e){return this.send(Ve.GetMyProgress,e,Es)}submitScore(e){return this.send(Ve.SubmitScore,e,Us)}submitScoreFromSource(e){return this.send(Ve.SubmitScoreFromSource,e,Us)}claimCycleReward(e){return this.send(Ve.ClaimCycleReward,e,qs)}claimMilestone(e){return this.send(Ve.ClaimMilestone,e,Bs)}getFriendsLeaderboard(e){return this.send(Ve.GetFriendsLeaderboard,e,Pi)}getLeaderboardsBatch(e){return this.send(Ve.GetLeaderboardsBatch,e,vu)}getProgressBatch(e){return this.send(Ve.GetProgressBatch,e,Ls)}claimCycleRewardsBatch(e){return this.send(Ve.ClaimCycleRewardsBatch,e,Tu)}claimMilestonesBatch(e){return this.send(Ve.ClaimMilestonesBatch,e,ku)}submitScoresBatch(e){return this.send(Ve.SubmitScoresBatch,e,Au)}claimAllRewardsBatch(e){return this.send(Ve.ClaimAllRewardsBatch,e,zu)}getOverviewBatch(e){return this.send(Ve.GetOverviewBatch,e,wu)}};var cr=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Et.GetDefinitions,e,Ns)}getActiveSeason(e){return this.send(Et.GetActiveSeason,e,Vs)}getUserState(e){return this.send(Et.GetUserState,e,Do)}grantStatusTokens(e){return this.send(Et.GrantStatusTokens,e,Uu)}claimTierReward(e){return this.send(Et.ClaimTierReward,e,Po)}claimTierRewardsBatch(e){return this.send(Et.ClaimTierRewardsBatch,e,qu)}};var pr=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Qt.GetDefinitions,e,Fh)}getUserState(e){return this.send(Qt.GetUserState,e,Vh)}activateTrial(e){return this.send(Qt.ActivateTrial,e,Jn)}purchaseItemOrCurrency(e){return this.send(Qt.PurchaseWithResources,e,Jn)}purchaseRealMoney(e){return this.send(Qt.PurchaseRealMoney,e,Jn)}};var hr=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(Ne.GetCharacterDefinitions,e,Ks)}getUserCharacters(e){return this.send(Ne.GetUserCharacters,e,Nu)}unlockCharacter(e){return this.send(Ne.UnlockCharacter,e,ko)}upgradeStatLevel(e){return this.send(Ne.UpgradeStatLevel,e,vo)}upgradeCharacterLevel(e){return this.send(Ne.UpgradeCharacterLevel,e,To)}equipItems(e){return this.send(Ne.EquipItems,e,ju)}unequipItems(e){return this.send(Ne.UnequipItems,e,_u)}unequipAllCharacters(e){return this.send(Ne.UnequipAllCharacters,e,Wu)}unlockCharactersBatch(e){return this.send(Ne.UnlockCharactersBatch,e,Ju)}upgradeCharacterLevelsBatch(e){return this.send(Ne.UpgradeCharacterLevelsBatch,e,Zu)}upgradeStatLevelsBatch(e){return this.send(Ne.UpgradeStatLevelsBatch,e,Yu)}unlockSkin(e){return this.send(Ne.UnlockSkin,e,Ku)}equipSkin(e){return this.send(Ne.EquipSkin,e,Qu)}unequipSkin(e){return this.send(Ne.UnequipSkin,e,Hu)}getCharacterSkins(e){return this.send(Ne.GetCharacterSkins,e,$u)}};var dr=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(Rt.CreateMatch,e,Ap)}updateMatch(e){return this.send(Rt.UpdateMatch,e,zp)}cancelMatch(e){return this.send(Rt.CancelMatch,e,wp)}instantBattle(e){return this.send(Rt.InstantBattle,e,Mp)}saveStrategy(e){return this.send(Rt.SaveStrategy,e,Ee)}getMyMatches(e){return this.send(Rt.GetMyMatches,e,ea)}getAvailableMatches(e){return this.send(Rt.GetAvailableMatches,e,ea)}getDefinitions(e){return this.send(Rt.GetDefinitions,e,qp)}};var OD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},pd=z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),ED={None:"None",Min:"Min",Average:"Average",Max:"Max"},UD=z.enum(["None","Min","Average","Max"]).catch("None"),qD={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},BD=z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),LD={Clamp:"Clamp",Reject:"Reject"},GD=z.enum(["Clamp","Reject"]).catch("Clamp"),FD=z.object({ItemInstanceID:z.string().nullish(),ItemID:z.string().nullish(),Level:z.number().nullish(),Units:z.number().nullish()}),VD=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:Jr.nullish(),OutputLevel:z.number().nullish(),BurnedInstances:z.array(FD).nullish()}),hd=z.object({ServerTimeUtc:c,Type:pd.nullish(),CraftID:z.string(),CraftedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),InputRarity:z.string().nullish(),OutputRarity:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:z.array(VD).nullish()}),ND=z.object({CraftID:z.string().nullish(),Type:pd.nullish(),CatalogID:z.string().nullish(),CollectionID:z.string().nullish(),InputRarityID:z.string().nullish(),OutputRarityID:z.string().nullish(),RequiredItemCount:z.number().nullish(),PriceOptions:le.nullish(),OutputLevelMode:UD.nullish(),InputSelection:BD.nullish(),OutputLevelOverflow:GD.nullish()}).passthrough(),ka=z.object({Definitions:z.record(z.string(),ND).nullish()}).passthrough(),dd=z.object({ServerTimeUtc:c.nullish(),CraftDefinitions:ka.nullish()}),mr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var fr=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(mr.GetDefinitions,e,dd)}craft(e){return this.send(mr.Craft,e,hd)}};var jD=2e5,gr=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,Js,{timeoutMs:jD,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Js,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Ge.GetDefinitions,e,ac)}generateText(e){return this.generate(Ge.GenerateText,e)}getText(e){return this.readGeneration(Ge.GetText,e)}generateImage(e){return this.generate(Ge.GenerateImage,e)}editImage(e){return this.generate(Ge.EditImage,e)}getImage(e){return this.readGeneration(Ge.GetImage,e)}generateVideo(e){return this.generate(Ge.GenerateVideo,e)}getVideo(e){return this.readGeneration(Ge.GetVideo,e)}generateAudio(e){return this.generate(Ge.GenerateAudio,e)}getAudio(e){return this.readGeneration(Ge.GetAudio,e)}generateMusic(e){return this.generate(Ge.GenerateMusic,e)}getMusic(e){return this.readGeneration(Ge.GetMusic,e)}generateThreeD(e){return this.generate(Ge.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Ge.GetThreeD,e)}listGenerations(e){return this.send(Ge.ListGenerations,e,oc)}getGeneration(e){return this.readGeneration(Ge.GetGeneration,e)}};var _D={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},WD=z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),md=z.object({}).passthrough().transform(o=>o),gi=z.object({CollectibleID:z.string(),Rarity:z.number().nullish(),IsSpecial:z.boolean().nullish(),IsDuplicate:z.boolean().nullish(),CollectionCurrencyConverted:z.number().nullish()}),fd=z.object({GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish()}),gd=z.object({OpenedCount:z.number().nullish(),Packs:z.array(fd).nullish(),GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish(),NewCollectionCurrencyBalance:_.nullish(),NewlyCompletedSetIDs:z.array(z.string()).nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),yd=z.object({OpenedCount:z.number().nullish(),Chests:z.array(fd).nullish(),GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish(),NewCollectionCurrencyBalance:_.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),Rd=z.object({GrantedCollectibleID:z.string().nullish(),NewlyCompletedSetID:z.string().nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Aa=z.object({SetID:z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),Cd=z.array(Pe(Aa)),Sd=z.object({Resources:M.nullish(),Inventory:Q.nullish()}),KD=z.object({OfferID:z.string(),TitleID:z.string().nullish(),CollectionID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderPublicData:Oe.nullish(),OfferedCollectibleID:z.string().nullish(),OfferedCollectibleIsSpecial:z.boolean().nullish(),ReceiverUserID:z.string().nullish(),RequestedCollectibleID:z.string().nullish(),RequestedCollectibleIsSpecial:z.boolean().nullish(),Status:WD.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RespondedAtUtc:c.nullish(),DeclineReason:z.string().nullish(),IsSpecialTradeEvent:z.boolean().nullish(),SpecialTradeEventID:z.string().nullish()}).passthrough(),xd=z.object({OfferID:z.string(),ExpiresAtUtc:c.nullish(),Resources:M.nullish()}),bd=z.object({OfferID:z.string(),Resources:M.nullish()}),Dd=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()}),Pd=z.object({OfferID:z.string(),Resources:M.nullish()}),za=z.object({Offers:z.array(KD).nullish()}),QD=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(),HD=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(QD).nullish(),SetCompletionReward:H.nullish()}).passthrough(),$D=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(HD).nullish(),GrandPrize:H.nullish()}).passthrough(),Id=z.object({BonusRewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),JD=z.object({PackTypeID:z.string().nullish(),PriceOptions:le.nullish(),BonusRewardSlots:z.array(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:Id.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(),ZD=z.object({Rarity:z.number().nullish(),CollectionCurrencyGranted:z.number().nullish()}).passthrough(),YD=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(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:Id.nullish(),Tier:z.number().nullish()}).passthrough(),XD=z.object({SpecialTradeEventID:z.string().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),AllowedSpecialCollectibleIDs:z.array(z.string()).nullish(),SpecialTradeEventDailyTradeLimit:z.number().nullish()}).passthrough(),eP=z.object({MaxPackOpenCount:z.number().nullish(),MaxChestOpenCount:z.number().nullish()}).passthrough(),yr=z.object({Collections:z.record(z.string(),$D).nullish(),PackTypes:z.record(z.string(),JD).nullish(),CollectionChests:z.array(YD).nullish(),DuplicateConversions:z.array(ZD).nullish(),DailyTradeLimit:z.number().nullish(),CollectibleJokerCatalogID:z.string().nullish(),CollectibleJokerItemID:z.string().nullish(),SpecialTradeEvents:z.array(XD).nullish(),RewardPools:Yn.nullish(),Settings:eP.nullish()}).passthrough(),je={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 Rr=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(je.GetDefinitions,e,yr)}getUserState(e){return this.send(je.GetUserState,e,md)}openPack(e){return this.send(je.OpenPack,e,gd)}openCollectionChest(e){return this.send(je.OpenCollectionChest,e,yd)}useCollectibleJoker(e){return this.send(je.UseCollectibleJoker,e,Rd)}claimSetReward(e){return this.send(je.ClaimSetReward,e,Aa)}claimSetRewardsBatch(e){return this.send(je.ClaimSetRewardsBatch,e,Cd)}claimGrandPrize(e){return this.send(je.ClaimGrandPrize,e,Sd)}sendTradeOffer(e){return this.send(je.SendTradeOffer,e,xd)}cancelTradeOffer(e){return this.send(je.CancelTradeOffer,e,bd)}acceptTradeOffer(e){return this.send(je.AcceptTradeOffer,e,Dd)}declineTradeOffer(e){return this.send(je.DeclineTradeOffer,e,Pd)}getMyTradeOffers(e){return this.send(je.GetMyTradeOffers,e,za)}getIncomingTradeOffers(e){return this.send(je.GetIncomingTradeOffers,e,za)}};var Cr=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(ht.GetDefinitions,e,en)}getActiveEvent(e){return this.send(ht.GetActiveEvent,e,cc)}getUserState(e){return this.send(ht.GetUserState,e,Xs)}getGroupState(e){return this.send(ht.GetGroupState,e,Eo)}joinOrCreateGroup(e){return this.send(ht.JoinOrCreateGroup,e,Eo)}spin(e){return this.send(ht.Spin,e,hc)}claimObjectReward(e){return this.send(ht.ClaimObjectReward,e,Uo)}claimGrandPrize(e){return this.send(ht.ClaimGrandPrize,e,Uo)}leaveGroup(e){return this.send(ht.LeaveGroup,e,dc)}};var Sr=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(yt.GetDefinition,e,Pc)}getUserState(e){return this.send(yt.GetUserState,e,Ic)}getActiveDeals(e){return this.send(yt.GetActiveDeals,e,nn)}dismissDeal(e){return this.send(yt.DismissDeal,e,Tc)}executeNode(e){return this.send(yt.ExecuteNode,e,vc)}recordShow(e){return this.send(yt.RecordShow,e,kc)}claimMilestone(e){return this.send(yt.ClaimMilestone,e,Ac)}claimMilestonesBatch(e){return this.send(yt.ClaimMilestonesBatch,e,zc)}};var tP=z.object({}).passthrough().transform(o=>o),iP=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:ye.nullish()}).passthrough(),wa=z.object({IsEnabled:z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:z.record(z.string(),Be).nullish(),SpendRewards:z.array(iP).nullish()}).passthrough(),vd=z.object({ReferralDefinitions:wa.nullish()}).passthrough(),Td=z.object({Referral:tP.nullish(),InviteUrl:z.string().nullish()}).passthrough(),kd=z.object({ReferralCode:z.string().nullish(),ReferrerUserID:z.string().nullish(),IsFirstActivation:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),Ma=z.object({RewardID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),Ad=ft(Ma),Jt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch"};var xr=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Jt.GetDefinitions,e,vd)}getUserState(e){return this.send(Jt.GetUserState,e,Td)}activateReferralCode(e){return this.send(Jt.ActivateReferralCode,e,kd)}claimInviteReward(e){return this.send(Jt.ClaimInviteReward,e,Ma)}claimInviteRewardsBatch(e){return this.send(Jt.ClaimInviteRewardsBatch,e,Ad)}};var br=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(et.GetDefinitions,e,Uc)}getMessages(e){return this.send(et.GetMessages,e,qc)}getUnreadCount(e){return this.send(et.GetUnreadCount,e,an)}readMessages(e){return this.send(et.ReadMessages,e,Lo)}claimReward(e){return this.send(et.ClaimReward,e,ln)}claimRewardsBatch(e){return this.send(et.ClaimRewardsBatch,e,ln)}claimAll(e){return this.send(et.ClaimAll,e,ln)}deleteMessages(e){return this.send(et.DeleteMessages,e,Lo)}sendGift(e){return this.send(et.SendGift,e,Bc)}sendTransfer(e){return this.send(et.SendTransfer,e,Lc)}getGiftStatus(e){return this.send(et.GetGiftStatus,e,Gc)}};var Dr=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Re.GetFriendsList,e,vi)}getIncomingRequests(e){return this.send(Re.GetIncomingRequests,e,vi)}getOutgoingRequests(e){return this.send(Re.GetOutgoingRequests,e,vi)}getRecommendedFriends(e){return this.send(Re.GetRecommendedFriends,e,vi)}sendFriendRequest(e){return this.send(Re.SendFriendRequest,e,Ti)}acceptFriendRequest(e){return this.send(Re.AcceptFriendRequest,e,Ti)}declineFriendRequest(e){return this.send(Re.DeclineFriendRequest,e,Ti)}removeFriend(e){return this.send(Re.RemoveFriend,e,Ti)}getInbox(e){return this.send(Re.GetInbox,e,Vc)}markInboxSeen(e){return this.send(Re.MarkInboxSeen,e,ki)}getInboxUnread(e){return this.send(Re.GetInboxUnread,e,ki)}follow(e){return this.send(Re.Follow,e,Bt)}unfollow(e){return this.send(Re.Unfollow,e,Bt)}getFollowers(e){return this.send(Re.GetFollowers,e,cn)}getFollowing(e){return this.send(Re.GetFollowing,e,cn)}block(e){return this.send(Re.Block,e,Bt)}unblock(e){return this.send(Re.Unblock,e,Bt)}getBlocked(e){return this.send(Re.GetBlocked,e,cn)}react(e){return this.send(Re.React,e,Bt)}unreact(e){return this.send(Re.Unreact,e,Bt)}getMyReactions(e){return this.send(Re.GetMyReactions,e,jc)}getEntityStates(e){return this.send(Re.GetEntityStates,e,Nc)}addComment(e){return this.send(Re.AddComment,e,pn)}editComment(e){return this.send(Re.EditComment,e,pn)}deleteComment(e){return this.send(Re.DeleteComment,e,Wc)}getComments(e){return this.send(Re.GetComments,e,_c)}report(e){return this.send(Re.Report,e,Kc)}};var sP={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Zt=z.object({Target:z.string().nullish(),Operation:z.string().nullish(),Value:z.number().nullish()}).passthrough(),nP=z.object({BoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:le.nullish(),Effect:Zt.nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),Pr=z.object({Schedule:me.nullish(),Gate:Z.nullish()}).passthrough(),Oa=z.object({Availability:K.nullish(),Effects:K.nullish()}).passthrough(),rP=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(Zt).nullish(),Availability:Pr.nullish(),Presets:Oa.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),oP=z.object({ChainedBoostID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Effects:z.array(Zt).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),aP=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(oP).nullish(),Availability:Pr.nullish(),Presets:Oa.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),lP=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(st).nullish(),Effects:z.array(Zt).nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Availability:Pr.nullish(),Presets:Oa.nullish()}).passthrough(),uP=z.object({MaxAddPercent:z.number().nullish(),MaxMultiply:z.number().nullish(),MaxAddFlat:z.number().nullish()}).passthrough(),cP=z.object({Effects:z.array(Zt).nullish()}).passthrough(),pP=z.object({Availability:z.record(z.string(),Pr).nullish(),Effects:z.record(z.string(),cP).nullish()}).passthrough(),hP=z.object({StackingCaps:z.record(z.string(),uP).nullish()}).passthrough(),Ir=z.object({Definitions:z.record(z.string(),nP).nullish(),ScheduledBoosts:z.record(z.string(),rP).nullish(),BoostChains:z.record(z.string(),aP).nullish(),TriggeredBoosts:z.record(z.string(),lP).nullish(),Settings:hP.nullish(),Presets:pP.nullish()}).passthrough(),zd=z.object({InstanceID:z.string(),BoostID:z.string(),ActivatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RemainingCharges:z.number().nullish(),EffectSnapshot:Zt.nullish(),SourceType:z.string().nullish(),SourceRef:z.string().nullish()}).passthrough();z.object({Date:c.nullish(),DailyCount:z.number().nullish(),LastFiredUtc:c.nullish()}).passthrough();var wd=z.object({ServerTimeUtc:c.nullish(),Active:z.record(z.string(),zd).nullish()}),Md=z.object({ServerTimeUtc:c.nullish(),BoostID:z.string().nullish(),StackingPolicy:z.string().nullish(),ActivatedBoost:zd.nullish(),Resources:M.nullish()}),dP={Scheduled:"Scheduled",Chain:"Chain"},mP=z.object({Kind:z.string().nullish(),SourceID:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),PhaseOrder:z.number().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),Effects:z.array(Zt).nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Od=z.object({ServerTimeUtc:c.nullish(),Windows:z.array(mP).nullish()}),Yt={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var vr=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(Yt.GetDefinitions,e,Ir)}getActive(e){return this.send(Yt.GetActive,e,wd)}getActiveWindows(e){return this.send(Yt.GetActiveWindows,e,Od)}activate(e){return this.send(Yt.Activate,e,Md)}cleanupExpired(e){return this.send(Yt.CleanupExpired,e,Ee)}};var Tr=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(dt.GetUserCustomDataDefinitions,e,fn)}getMyUserCustomData(e){return this.send(dt.GetMyUserCustomData,e,Jc)}getPublicUserCustomDataOf(e){return this.send(dt.GetPublicUserCustomDataOf,e,jo)}setPrivateData(e){return this.send(dt.SetPrivateData,e,_o)}setPublicData(e){return this.send(dt.SetPublicData,e,_o)}deleteKey(e){return this.send(dt.DeleteKey,e,Ee)}batchSet(e){return this.send(dt.BatchSet,e,Zc)}batchDelete(e){return this.send(dt.BatchDelete,e,Yc)}batchGetPublicUserCustomDataOf(e){return this.send(dt.BatchGetPublicUserCustomDataOf,e,Xc)}};var fP={Static:"Static",Runtime:"Runtime"},gP={Public:"Public",Private:"Private"},yP=z.enum(["Client","Server","System"]).catch("Client"),RP=z.enum(["String","Int","Bool","Json"]).catch("String"),CP=z.object({Value:z.string().nullish(),UpdatedAt:c.nullish(),Version:z.number().nullish(),LastWriter:yP.nullish(),ExpiresAt:c.nullish()}).passthrough(),Ed=z.record(z.string(),CP),Ea=z.object({StaticVersion:z.number().nullish(),RuntimeVersion:z.number().nullish(),Static:Ed.nullish(),Runtime:Ed.nullish(),NotModified:z.boolean().nullish()}),SP=z.object({KeyID:z.string(),Scope:z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:RP.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),kr=z.object({Keys:z.record(z.string(),SP).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),Ei={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Ar=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Ei.GetTitleCustomDataDefinitions,e,kr)}getPublicTitleData(e){return this.send(Ei.GetPublicTitleData,e,Ea)}getPublicTitleDataKeys(e){return this.send(Ei.GetPublicTitleDataKeys,e,Ea)}};var xP={Fast:"Fast",Sequential:"Sequential"},bP={Instant:"Instant",Timed:"Timed"};var DP={Hit:"Hit",Blocked:"Blocked"},PP=z.object({SlotIndex:z.number(),Level:z.number().nullish(),IsDamaged:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish()}).passthrough(),IP=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 vP=z.object({RequiredValue:z.number().nullish(),Reward:H.nullish()}).passthrough(),TP=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(vP).nullish(),Rate:TP.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 Ud=z.object({}).passthrough().transform(o=>o),qd=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),_e=z.object({Operation:M.nullish(),ScaleWithRollMultiplier:z.boolean().nullish()}).passthrough(),kP=z.object({Count:z.number().nullish(),Sides:z.number().nullish()}).passthrough(),AP=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(),zP=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(),wP=z.object({CostMatrix:z.array(z.array(z.number())).nullish(),PerBoardGrowth:z.number().nullish(),EconomyScale:z.number().nullish(),ScaledResources:ue.nullish()}).passthrough(),Bd=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(),OP=z.object({Tiles:z.record(z.string(),MP).nullish()}).passthrough(),EP=z.object({Weight:z.number().nullish(),Bonus:_e.nullish(),Tag:z.string().nullish()}).passthrough(),UP=z.object({Weight:z.number().nullish(),Tag:z.string().nullish(),MinBonusCells:z.number().nullish(),MaxBonusCells:z.number().nullish(),BonusPool:z.array(EP).nullish(),GuaranteedBonus:_e.nullish(),IsJackpot:z.boolean().nullish(),JackpotFinalMultiplier:z.number().nullish(),JackpotSymbolDistribution:z.record(z.string(),z.number()).nullish()}).passthrough(),qP=z.object({Variants:z.array(UP).nullish()}).passthrough(),BP=z.object({Weight:z.number().nullish(),OutcomeID:z.string().nullish(),Reward:_e.nullish(),ForceAction:z.string().nullish(),SpecialModeID:z.string().nullish()}).passthrough(),LP=z.object({Outcomes:z.array(BP).nullish()}).passthrough(),Ld=z.object({PerAdMultiplierRange:qd.nullish(),MaxAdViews:z.number().nullish(),AdCreditCost:z.number().nullish(),FormulaKind:z.string().nullish(),ApplyMultiplierOnEarlyClaim:z.boolean().nullish()}).passthrough(),GP=z.object({ElapsedSeconds:z.number().nullish(),Reward:_e.nullish()}).passthrough(),FP=z.object({Tiers:z.array(GP).nullish(),TierMode:z.string().nullish(),BelowFirstTierReward:_e.nullish()}).passthrough(),VP=z.object({RequiredValue:z.number().nullish(),Reward:_e.nullish()}).passthrough(),NP=z.object({Reward:_e.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough(),jP=z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(VP).nullish(),Rate:NP.nullish()}).passthrough(),Gd=z.object({MetricsByID:z.record(z.string(),jP).nullish()}).passthrough(),_P=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:_e.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:le.nullish(),Multipliers:Ld.nullish(),Gradation:FP.nullish(),RunStats:Gd.nullish()}).passthrough(),WP=z.object({Choices:z.array(_P).nullish(),OfferExpireSeconds:z.number().nullish(),ClaimExpireSeconds:z.number().nullish()}).passthrough(),KP=z.object({Chance:z.number().nullish(),RequiredOutcome:z.string().nullish(),Reward:_e.nullish(),Tag:z.string().nullish()}).passthrough(),QP=z.object({OnPassStart:_e.nullish(),OnTileLanding:z.record(z.string(),_e).nullish(),OnAttack:z.record(z.string(),_e).nullish(),OnRaid:z.record(z.string(),_e).nullish(),OnBuild:_e.nullish(),OnStageComplete:_e.nullish(),OnAttackBonusDrops:z.array(KP).nullish(),ChanceTablesByID:z.record(z.string(),LP).nullish(),SpecialModesByID:z.record(z.string(),WP).nullish()}).passthrough(),Fd=z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:z.number().nullish(),MaxShields:z.number().nullish(),Buildings:z.array(Bd).nullish(),HeistGridBonusConfig:qP.nullish(),StageOperations:QP.nullish(),TileLandingMultiplier:qd.nullish(),EconomyOverride:wP.nullish()}).passthrough(),HP=z.object({Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BoardTemplateID:z.string().nullish(),Buildings:z.array(Bd).nullish(),StageTemplateID:z.string().nullish(),CostMatrixTemplateID:z.string().nullish(),UnitValue:z.number().nullish(),Override:Fd.nullish()}).passthrough(),$P=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(),JP=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(),zr=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(),OP).nullish(),StageTemplatesByID:z.record(z.string(),Fd).nullish(),StagesByLevel:z.record(z.string(),HP).nullish(),SoftCurrencyID:z.string().nullish(),ProceduralEconomy:zP.nullish(),Dice:kP.nullish(),Bots:AP.nullish(),Targeting:$P.nullish(),BotRaids:JP.nullish()}).passthrough(),ZP=z.object({IsActive:z.boolean().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AnchorUtc:c.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(),Be).nullish(),GrandPrize:H.nullish()}).passthrough(),wr=z.object({Board:zr.nullish(),CommunityChest:ZP.nullish()}).passthrough(),Vd=z.object({AttackerGainByOutcome:z.record(z.string(),ue).nullish()}).passthrough(),YP=z.object({TargetUserID:z.string().nullish(),IsBot:z.boolean().nullish(),PublicData:Oe.nullish(),TargetBuildingStates:z.array(PP).nullish(),TargetHasShield:z.boolean().nullish(),TargetStageLevel:z.number().nullish(),RaidRewardPreview:Vd.nullish()}).passthrough(),XP=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:_e.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:le.nullish(),Multipliers:Ld.nullish(),RunStats:Gd.nullish()}).passthrough(),eI=z.object({ModeID:z.string().nullish(),Choices:z.array(XP).nullish()}).passthrough(),tI=z.object({GroupID:z.string().nullish(),Delta:_.nullish(),NewProgress:_.nullish(),MaxProgress:_.nullish(),UnlockedMilestoneIDs:z.array(z.string()).nullish(),Completed:z.boolean().nullish()}).passthrough(),Nd=z.object({UsedMultiplier:z.number().nullish(),Steps:z.number().nullish(),DiceValues:z.array(z.number()).nullish(),OldPosition:z.number().nullish(),NewPosition:z.number(),CyclesCompletedDelta:_.nullish(),LandedTileType:z.string().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),ActionRequired:z.string().nullish(),ActionData:YP.nullish(),SpecialModeOffer:eI.nullish(),CommunityChestContribution:tI.nullish()}).passthrough(),jd=z.object({Outcome:z.string().nullish(),IsBotTarget:z.boolean().nullish(),BuildingIndexHit:z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:bt.nullish()}).passthrough(),Ua=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(IP).nullish(),HeistVariantTag:z.string().nullish(),IsJackpot:z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:bt.nullish(),RaidRewardPreview:Vd.nullish()}).passthrough(),_d=z.object({BuiltIndex:z.number(),NewLevel:z.number().nullish(),StageComplete:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish()}).passthrough(),Wd=z.object({Mode:z.union([z.string(),z.number()]).nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DurationSeconds:z.number().nullish(),StartedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish()}).passthrough(),Kd=z.object({AdViewsUsed:z.number().nullish(),RolledMultiplier:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),RemainingAdViews:z.number().nullish()}).passthrough(),iI=z.object({MetricID:z.string().nullish(),ReachedTierIndex:z.number().nullish(),RequiredValue:z.number().nullish(),RewardUnits:z.number().nullish()}).passthrough(),Qd=z.object({FinalMultiplier:z.number().nullish(),AdViewsUsed:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),IsEarlyClaim:z.boolean().nullish(),ReachedTierIndex:z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),AcceptedRunStats:z.record(z.string(),z.number()).nullish(),RunStatAwards:z.array(iI).nullish(),RunStatsClamped:z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),sI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Hd=z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),nI={Active:"Active",Left:"Left",Replaced:"Replaced"},rI=z.enum(["Active","Left","Replaced"]).catch("Active"),oI=z.object({CurrentProgress:_.nullish(),MaxProgress:_.nullish()}).passthrough(),aI=z.object({UserID:z.string().nullish(),PublicData:Oe.nullish(),IsBot:z.boolean().nullish(),ContributionPoints:_.nullish(),MilestoneClaims:z.record(z.string(),ll).nullish(),GrandPrizeClaimed:z.boolean().nullish(),MemberStatus:rI.nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),$d=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),RoundIndex:z.number().nullish(),Members:z.array(aI).nullish(),SharedProgress:oI.nullish(),Status:Hd.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:z.number().nullish()}).passthrough(),lI=z.object({GroupID:z.string().nullish(),RoundIndex:z.number().nullish(),FinalStatus:Hd.nullish(),GrandPrizeReceived:z.boolean().nullish(),FinishedAtUtc:c.nullish()}).passthrough(),uI=z.object({ActiveGroupID:z.string().nullish(),ActiveRoundIndex:z.number().nullish(),History:z.array(lI).nullish()}).passthrough(),Jd=z.object({ServerTimeUtc:c.nullish(),UserState:uI.nullish(),ActiveGroup:$d.nullish(),SecondsRemaining:_.nullish()}),Zd=z.object({ServerTimeUtc:c.nullish(),Group:$d.nullish(),SecondsRemaining:_.nullish()}),qa=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Yd=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),qe={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 cI={Mesh:"Mesh",Host:"Host"},Ba=z.enum(["Mesh","Host"]).catch("Mesh"),pI={ServerRelay:"ServerRelay",P2P:"P2P"},La=z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),hI={Public:"Public",Private:"Private"},dI=z.enum(["Public","Private"]).catch("Public"),mI={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},fI=z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Xd=z.object({Urls:z.string().nullish(),Username:z.string().nullish(),Credential:z.string().nullish()}).passthrough(),gI=z.object({Enabled:z.boolean().nullish()}).passthrough(),em=z.object({SystemState:gI.nullish(),DefaultTopology:Ba.nullish(),AllowCreatorTopologyOverride:z.boolean().nullish(),DefaultChatMode:La.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(Xd).nullish()}).passthrough(),yI=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(),RI=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),Topology:Ba.nullish(),ChatMode:La.nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),MemberCount:z.number().nullish(),CreatedAt:z.number().nullish()}).passthrough(),CI=z.object({Seq:z.number().nullish(),Type:fI.nullish(),FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Kind:z.string().nullish(),Payload:z.string().nullish(),Ts:z.number().nullish()}).passthrough(),Ui=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),OwnerUserID:z.string().nullish(),Topology:Ba.nullish(),ChatMode:La.nullish(),Visibility:dI.nullish(),Status:z.string().nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),Members:z.array(yI).nullish(),IceServers:z.array(Xd).nullish(),Seq:z.number().nullish(),BannedUserIDs:z.array(z.string()).nullish()}).passthrough(),tm=z.object({Removed:z.boolean().nullish(),Banned:z.boolean().nullish()}).passthrough(),im=z.object({WasBanned:z.boolean().nullish()}).passthrough(),Ga=z.object({Closed:z.boolean().nullish(),NewHostUserID:z.string().nullish()}).passthrough(),sm=z.object({Rooms:z.array(RI).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}).passthrough(),nm=z.object({Envelopes:z.array(CI).nullish(),MaxSeq:z.number().nullish()}).passthrough(),Mr=z.object({Seq:z.number().nullish()}).passthrough(),He={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 Fa=z.object({TitleCustomData:kr.nullish(),Character:Ks.nullish(),Item:Wn.nullish(),Currency:bn.nullish(),Store:ms.nullish(),Lootbox:Pa.nullish(),Quest:_i.nullish(),TimedEvent:ws.nullish(),Leaderboard:Gs.nullish(),Season:Ns.nullish(),Reward:va.nullish(),Collection:yr.nullish(),Craft:ka.nullish(),DealOffer:qo.nullish(),Premium:xa.nullish(),TimedBoost:Ir.nullish(),CoopEvent:en.nullish(),GameLoop:wr.nullish(),Match:ta.nullish(),Experiment:Ch.nullish(),Blockchain:Ho.nullish(),Marketplace:oa.nullish(),Multiplayer:em.nullish(),UserCustomData:fn.nullish(),Referral:wa.nullish(),Localization:Ah.nullish(),Analytics:lh.nullish(),Social:Qc.nullish(),PlatformBridge:Hc.nullish()}).passthrough();var Xt={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Or=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(Xt.GetTitlePublicConfiguration,e,Fa)}getTitlePublicConfigurationExcept(e){return this.send(Xt.GetTitlePublicConfigurationExcept,e,Fa)}getCurrencyDefinitions(e){return this.send(Xt.GetCurrencyDefinitions,e,bn)}getItemDefinitions(e){return this.send(Xt.GetItemDefinitions,e,Wn)}getServerTime(e){return this.send(Xt.GetServerTime,e,Ee)}};var Er=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(qe.GetGameLoops,e,wr)}getBoardDefinition(e,t=false){return this.send(qe.GetBoardDefinition,e,zr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(qe.GetBoardDefinitionForLevel,e,zr,{silent:t})}getUserBoardState(e){return this.send(qe.GetUserBoardState,e,Ud)}boardLoopRoll(e){return this.send(qe.BoardLoopRoll,e,Nd)}boardLoopAttack(e){return this.send(qe.BoardLoopAttack,e,jd)}boardLoopRaid(e){return this.send(qe.BoardLoopRaid,e,Ua)}boardLoopRaidFast(e){return this.send(qe.BoardLoopRaidFast,e,Ua)}boardLoopBuild(e){return this.send(qe.BoardLoopBuild,e,_d)}boardSpecialChoose(e){return this.send(qe.BoardSpecialChoose,e,Wd)}boardSpecialApplyMultiplier(e){return this.send(qe.BoardSpecialApplyMultiplier,e,Kd)}boardSpecialClaim(e){return this.send(qe.BoardSpecialClaim,e,Qd)}getCommunityChestState(e){return this.send(qe.GetCommunityChestState,e,Jd)}joinOrCreateCommunityChest(e){return this.send(qe.JoinOrCreateCommunityChest,e,Zd)}claimCommunityChestMilestone(e){return this.send(qe.ClaimCommunityChestMilestone,e,qa)}claimCommunityChestGrandPrize(e){return this.send(qe.ClaimCommunityChestGrandPrize,e,qa)}leaveCommunityChest(e){return this.send(qe.LeaveCommunityChest,e,Yd)}};var xI={Live:"Live",Latest:"Latest",Specific:"Specific"},bI={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},DI=z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),PI={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"},II=z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),vI=z.object({Level:DI,Message:z.string().nullish(),Data:Ut.nullish()}),TI=z.object({Error:II,Message:z.string().nullish(),StackTrace:z.string().nullish()}),rm=z.object({FunctionName:z.string().nullish(),Revision:z.number().nullish(),FunctionResult:Ut.nullish(),FunctionResultTooLarge:z.boolean().nullish(),Logs:z.array(vI).nullish(),LogsTooLarge:z.boolean().nullish(),ExecutionTimeSeconds:z.number().nullish(),APIRequestsIssued:z.number().nullish(),Error:TI.nullish()}),Va={Execute:"Execute"};var Ur=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(Va.Execute,e,rm)}};var qr=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Qe.GetDefinitions,e,gp)}getUserState(e){return this.send(Qe.GetUserState,e,yp)}depositToken(e){return this.send(Qe.DepositToken,e,Rp)}depositNFT(e){return this.send(Qe.DepositNFT,e,Cp)}requestTokenWithdrawal(e){return this.send(Qe.RequestTokenWithdrawal,e,Sp)}requestNFTWithdrawal(e){return this.send(Qe.RequestNFTWithdrawal,e,xp)}getTransactionHistory(e){return this.send(Qe.GetTransactionHistory,e,bp)}retryWithdrawal(e){return this.send(Qe.RetryWithdrawal,e,Dp)}confirmWithdrawal(e){return this.send(Qe.ConfirmWithdrawal,e,Pp)}donateToDeveloper(e){return this.send(Qe.DonateToDeveloper,e,Yo)}donateToUsersPool(e){return this.send(Qe.DonateToUsersPool,e,Yo)}getPlayAccess(e){return this.send(Qe.GetPlayAccess,e,mp)}confirmPlayAccess(e){return this.send(Qe.ConfirmPlayAccess,e,Lt)}};var Br=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(ke.GetDefinitions,e,Lp)}getGroupedOffers(e){return this.send(ke.GetGroupedOffers,e,Gp)}getOffersByItem(e){return this.send(ke.GetOffersByItem,e,aa)}getOffer(e){return this.send(ke.GetOffer,e,Fp)}getBuyOrders(e){return this.send(ke.GetBuyOrders,e,aa)}getMyState(e){return this.send(ke.GetMyState,e,An)}getHistory(e){return this.send(ke.GetHistory,e,Np)}createListing(e){return this.send(ke.CreateListing,e,wi)}cancelListing(e){return this.send(ke.CancelListing,e,at)}buy(e){return this.send(ke.Buy,e,at)}marketBuy(e){return this.send(ke.MarketBuy,e,at)}marketSell(e){return this.send(ke.MarketSell,e,at)}createAuction(e){return this.send(ke.CreateAuction,e,wi)}placeBid(e){return this.send(ke.PlaceBid,e,Vp)}claimAuction(e){return this.send(ke.ClaimAuction,e,at)}createBuyOrder(e){return this.send(ke.CreateBuyOrder,e,wi)}cancelBuyOrder(e){return this.send(ke.CancelBuyOrder,e,at)}fillBuyOrder(e){return this.send(ke.FillBuyOrder,e,at)}createDirectTrade(e){return this.send(ke.CreateDirectTrade,e,wi)}respondDirectTrade(e){return this.send(ke.RespondDirectTrade,e,at)}cancelDirectTrade(e){return this.send(ke.CancelDirectTrade,e,at)}claimBack(e){return this.send(ke.ClaimBack,e,at)}};var Lr=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(He.CreateRoom,e,Ui)}joinRoom(e){return this.send(He.JoinRoom,e,Ui)}leaveRoom(e,t=false){return this.send(He.LeaveRoom,e,Ga,{keepalive:t})}listRooms(e){return this.send(He.ListRooms,e,sm)}getRoom(e){return this.send(He.GetRoom,e,Ui)}closeRoom(e){return this.send(He.CloseRoom,e,Ga)}poll(e){return this.send(He.Poll,e,nm)}sendSignal(e){return this.send(He.SendSignal,e,Mr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(He.ClaimHost,e,Ui)}kickMember(e){return this.send(He.KickMember,e,tm)}unbanMember(e){return this.send(He.UnbanMember,e,im)}sendChat(e){return this.send(He.SendChat,e,Mr)}setMemberState(e){return this.send(He.SetMemberState,e,Mr)}};var kI={Free:"Free",Price:"Price",Holding:"Holding"},Na=z.enum(["Free","Price","Holding"]).catch("Free"),AI={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},zI=z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),wI={All:"All",Any:"Any"},MI=z.enum(["All","Any"]).catch("All"),OI={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},EI=z.enum(["Public","Unlisted","Friends"]).catch("Public"),UI={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},qI=z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),BI={Purchase:"Purchase",Free:"Free",Holding:"Holding"},am=z.enum(["Purchase","Free","Holding"]).catch("Free"),LI={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},GI={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},FI=z.enum(["Creator","License","Free","Holding"]).catch("License"),VI=z.object({Type:si.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),Amount:z.number().nullish(),MinLevel:z.number().nullish()}).passthrough(),NI=z.object({Requirements:z.array(VI).nullish(),Match:MI.nullish(),Mode:zI.nullish()}).passthrough(),jI=z.object({OptionID:z.string().nullish(),Mode:Na.nullish(),Price:ue.nullish(),Holding:NI.nullish()}).passthrough(),_I=z.object({AllowedMimeTypes:z.array(z.string()).nullish(),MaxBytes:z.number().nullish(),MaxCount:z.number().nullish(),Required:z.boolean().nullish()}).passthrough(),WI=z.object({DisplayName:z.string().nullish(),Enabled:z.boolean().nullish(),Files:z.record(z.string(),_I).nullish(),ThumbnailRequired:z.boolean().nullish(),AllowedAccessModes:z.array(Na).nullish(),PricePolicy:kn.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:le.nullish(),TagVocabulary:z.array(z.string()).nullish(),MaxPublishedPerPlayer:z.number().nullish(),DailyPublishCap:z.number().nullish()}).passthrough(),KI=z.object({Allowed:z.array(zi).nullish(),MaxRequirements:z.number().nullish()}).passthrough(),QI=z.object({AutoHideReportThreshold:z.number().nullish(),RequireApproval:z.boolean().nullish(),BlockedTerms:z.array(z.string()).nullish()}).passthrough(),HI=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(),$I=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Schedule:me.nullish(),Gate:Z.nullish(),Order:z.number().nullish()}).passthrough(),JI=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:me.nullish(),ContentTypes:z.record(z.string(),WI).nullish(),PricePolicy:kn.nullish(),Commission:ra.nullish(),HoldingPolicy:KI.nullish(),Moderation:QI.nullish(),Limits:HI.nullish(),Featured:z.array($I).nullish()}).passthrough(),ZI=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(),ei=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),CreatorUserID:z.string().nullish(),IsOfficial:z.boolean().nullish(),CreatorPublicData:Oe.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:EI.nullish(),Access:z.array(jI).nullish(),Status:qI.nullish(),ModerationNote:z.string().nullish(),Stats:ZI.nullish(),Revision:z.number().nullish(),ParentContentID:z.string().nullish(),FileCount:z.number().nullish(),TotalBytes:z.number().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),PublishedAt:c.nullish(),IsMine:z.boolean().nullish(),Owned:z.boolean().nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish()}).passthrough(),YI=z.object({OptionID:z.string().nullish(),Mode:Na.nullish(),Available:z.boolean().nullish()}).passthrough(),lm=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(),um=z.object({Definitions:JI.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish(),CanPublish:z.record(z.string(),z.boolean()).nullish(),Collections:z.array(lm).nullish()}).passthrough(),Gr=z.object({Items:z.array(ei).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),cm=z.object({Content:ei.nullish(),AccessState:z.array(YI).nullish(),CanDownload:z.boolean().nullish()}).passthrough(),pm=z.object({Collection:lm.nullish(),Items:z.array(ei).nullish()}).passthrough(),hm=z.object({CreatorUserID:z.string().nullish(),PublicData:Oe.nullish(),PublishedCount:z.number().nullish(),FollowerCount:z.number().nullish(),IsFollowing:z.boolean().nullish(),Items:z.array(ei).nullish()}).passthrough(),om=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(),dm=z.object({ContentID:z.string().nullish(),Revision:z.number().nullish(),Uploads:z.array(om).nullish(),ThumbnailUpload:om.nullish(),ExpiresAt:c.nullish()}).passthrough(),mm=z.object({Content:ei.nullish(),Resources:M.nullish()}).passthrough(),ja=z.object({Content:ei.nullish()}).passthrough(),fm=z.object({ContentID:z.string().nullish(),OptionID:z.string().nullish(),Source:am.nullish(),AlreadyOwned:z.boolean().nullish(),AccessActive:z.boolean().nullish(),Settlement:bt.nullish(),Resources:M.nullish(),CommissionTaken:ue.nullish()}).passthrough(),XI=z.object({Role:z.string().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish()}).passthrough(),gm=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),Revision:z.number().nullish(),AccessVia:FI.nullish(),Files:z.array(XI).nullish(),ThumbnailUrl:z.string().nullish(),ExpiresAt:c.nullish()}).passthrough(),ev=z.object({ContentID:z.string().nullish(),Source:am.nullish(),OptionID:z.string().nullish(),PricePaid:ue.nullish(),AcquiredAt:c.nullish(),Content:ei.nullish()}).passthrough(),ym=z.object({Licenses:z.array(ev).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),We={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 Fr=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(We.GetDefinitions,e,um)}browse(e){return this.send(We.Browse,e,Gr)}getContent(e){return this.send(We.GetContent,e,cm)}getCollection(e){return this.send(We.GetCollection,e,pm)}getCreatorProfile(e){return this.send(We.GetCreatorProfile,e,hm)}beginUpload(e){return this.send(We.BeginUpload,e,dm)}publish(e){return this.send(We.Publish,e,mm)}updateContent(e){return this.send(We.UpdateContent,e,ja)}unpublish(e){return this.send(We.Unpublish,e,ja)}getMyContent(e){return this.send(We.GetMyContent,e,Gr)}acquire(e){return this.send(We.Acquire,e,fm)}getDownload(e){return this.send(We.GetDownload,e,gm)}getMyLicenses(e){return this.send(We.GetMyLicenses,e,ym)}getMyFavorites(e){return this.send(We.GetMyFavorites,e,Gr)}};var Vr=class extends B{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,Hp,"defs")}get(e){return this.sendKeyed("Get",e,ua,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Jp,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,ca,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Zp,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,pa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,pa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Yp,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,eh,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Xp,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,th,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,$p,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,ih,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,ua,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,ca,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Nr=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e$1){this.settings=Ha(e$1),this.emitter=new Ci,this.platform=e$1.platform??new e,this.clientPlatform=e$1.clientPlatform??ol(),this.acquisition=new Nt(this.platform),this.acquisition.capture(),this.playtime=new Si(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear();}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e$1.fetch??globalThis.fetch.bind(globalThis),this.transport=new Zi({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 ts(this.emitter),this.cache=new ss(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 ns(this.platform.storage,this.settings.titleID),this.api={authentication:new Fn(this),user:new Nn(this),currency:new jn(this),item:new Kn(this),store:new Qn(this),purchase:new Zn(this),lootbox:new er(this),reward:new tr(this),quest:new ar(this),tutorial:new ir(this),communityMarketing:new sr(this),chat:new nr(this),push:new rr(this),localization:new or(this),timedEvent:new lr(this),leaderboard:new ur(this),season:new cr(this),premium:new pr(this),character:new hr(this),match:new dr(this),craft:new fr(this),ai:new gr(this),collection:new Rr(this),coopEvent:new Cr(this),dealOffer:new Sr(this),referral:new xr(this),mailbox:new br(this),social:new Dr(this),timedBoost:new vr(this),userCustomData:new Tr(this),titleCustomData:new Ar(this),title:new Or(this),gameLoop:new Er(this),cloudCode:new Ur(this),blockchain:new qr(this),marketplace:new Br(this),multiplayer:new Lr(this),workshop:new Fr(this),dataCollections:new Vr(this),analytics:new Ln(this),experiment:new Gn(this)},this.userService=new us(this),this.cache.attachState(this.userService),this.auth=new rs(this),this.currency=new ps(this),this.item=new hs(this),this.store=new gs(this),this.purchase=new ys(this),this.checkout=new Rs(this),this.lootbox=new Cs(this),this.reward=new Ss(this),this.quest=new zs(this),this.tutorial=new bs(this),this.communityMarketing=new Ds(this),this.chat=new vs(this),this.push=new Ts(this),this.localization=new As(this),this.timedEvent=new Os(this),this.leaderboard=new Fs(this),this.season=new js(this),this.premium=new _s(this),this.character=new Qs(this),this.match=new Hs(this),this.craft=new $s(this),this.ai=new Zs(this),this.collection=new Ys(this),this.coopEvent=new tn(this),this.dealOffer=new rn(this),this.referral=new on(this),this.mailbox=new un(this),this.social=new hn(this),this.timedBoost=new dn(this),this.userCustomData=new gn(this),this.titleCustomData=new yn(this),this.title=new Rn(this),this.gameLoop=new Cn(this),this.cloudCode=new Sn(this),this.blockchain=new Pn(this),this.marketplace=new zn(this),this.multiplayer=new wn(this),this.workshop=new Mn(this),this.dataCollections=new En(this),this.analytics=new qn(this),this.experiments=new Bn(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 jr=class{ctx;constructor(e){this.ctx=new Nr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Ft(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 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 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 iv(o){return new jr(o)}var Rm="idos_sso",Cm="state",_a="idos:sso:state",sv="https://idosgames.com/sso/",nv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],rv=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function ov(){if(typeof window>"u")return false;let{origin:o}=window.location;return nv.includes(o)||rv.test(o)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function av(){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(Rm);if(!t)return null;let i=e.get(Cm)??"",s=hv();return mv(e),dv(),s&&i!==s?null:{code:t,state:i}}function lv(o){if(typeof window>"u")return;let e=o.returnTo??uv(),t=cv();pv(t);let i=new URL(o.ssoUrl??sv);i.searchParams.set("title",o.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function uv(){let{origin:o,pathname:e,search:t}=window.location;return `${o}${e}${t}`}function cv(){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 pv(o){try{window.sessionStorage.setItem(_a,o);}catch{}}function hv(){try{return window.sessionStorage.getItem(_a)}catch{return null}}function dv(){try{window.sessionStorage.removeItem(_a);}catch{}}function mv(o){o.delete(Rm),o.delete(Cm);let e=o.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var fv={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 gv(o,e="Something went wrong. Please try again."){return o?fv[o]??o:e}function yv(o,e){return !!o?.Claims?.[e]?.ClaimedAt}function Rv(o){let e=o?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function Cv(o,e){return o?.Claims?.[e]?.PremiumTiers??[]}function xm(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*Sm(o,t,1);break;case "TableAbsolute":r=Sm(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 Sv(o,e,t=1){return xm(o,1,e,t)}function xv(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 bm(o.Points).length>0;default:return o.MinResult!=null||o.MaxResult!=null}}function bv(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 bm(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 Sm(o,e,t){let i=bm(o.Points);if(i.length===0)return t;let s=null,n=null,r=null;for(let p of i)(r===null||p.AtStep>r.AtStep)&&(r=p),p.AtStep<=e&&(s===null||p.AtStep>=s.AtStep)&&(s=p),p.AtStep>e&&(n===null||p.AtStep<n.AtStep)&&(n=p);if(s===null)return t;if(n===null){let p=o.TailGrowthRate??0;return p===0?r.Value:r.Value*Math.pow(1+p,e-r.AtStep)}switch(o.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+p*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let d=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+d*(n.Value-s.Value)}let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,p)}default:return s.Value}}var Dv={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Wa=z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),Pv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Iv=z.enum(["Top","Bottom","Left","Right"]).catch("Top"),vv=z.object({PlacementID:z.string().nullish(),Type:Wa.nullish(),Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),CreditsRewarded:z.number().nullish(),AllowedProviderIDs:z.array(z.string()).nullish()}).passthrough(),Tv=z.object({DefaultCreditsPerView:z.number().nullish(),MaxCreditsBalance:z.number().nullish(),DailyCreditEarnCap:z.number().nullish(),DailyViewCap:z.number().nullish(),MinSecondsBetweenViews:z.number().nullish()}).passthrough(),kv=z.object({CooldownSeconds:z.number().nullish(),MinSessionTimeBeforeFirstSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),Av=z.object({Enabled:z.boolean().nullish(),Position:Iv.nullish(),RefreshIntervalSeconds:z.number().nullish()}).passthrough(),zv=z.object({Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish()}).passthrough(),wv=z.object({MaxImpressionsPerHour:z.number().nullish(),MaxImpressionsPerDay:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),Mv=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),DisableInterstitials:z.boolean().nullish(),DisableBanners:z.boolean().nullish(),DisableAppOpen:z.boolean().nullish()}).passthrough(),Ov=z.object({RequirePersonalizedAdsConsent:z.boolean().nullish(),RequireTrackingConsent:z.boolean().nullish(),CurrentPolicyVersion:z.string().nullish(),RegulatedRegions:z.array(z.string()).nullish()}).passthrough(),Ev=z.object({RequireServerSideVerification:z.boolean().nullish(),PendingRequestTtlSeconds:z.number().nullish(),MaxPendingRequestsPerUser:z.number().nullish()}).passthrough(),Uv=z.object({AndroidUnitID:z.string().nullish(),IosUnitID:z.string().nullish(),WebUnitID:z.string().nullish(),Type:Wa.nullish()}).passthrough(),qv={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},Bv=z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),Lv=z.object({ProviderID:z.string().nullish(),Kind:Bv.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(),Uv).nullish()}).passthrough();z.object({Enabled:z.boolean().nullish(),Placements:z.record(z.string(),vv).nullish(),Providers:z.record(z.string(),Lv).nullish(),RewardedVideo:Tv.nullish(),Interstitial:kv.nullish(),Banner:Av.nullish(),AppOpen:zv.nullish(),FrequencyCapping:wv.nullish(),PremiumAdReductions:z.array(Mv).nullish(),Consent:Ov.nullish(),Verification:Ev.nullish()}).passthrough();var Gv=z.object({RewardedVideoCredit:z.number().nullish(),TotalEarned:z.number().nullish(),TotalSpent:z.number().nullish()}).passthrough(),Fv=z.object({PlacementID:z.string().nullish(),LastShownAt:c.nullish(),LastCompletedAt:c.nullish(),TotalImpressions:z.number().nullish(),TotalCompletions:z.number().nullish(),ConsecutiveFailures:z.number().nullish()}).passthrough(),Vv=z.object({Date:c.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(),Nv=z.object({SessionID:z.string().nullish(),SessionStartAt:c.nullish(),Impressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish()}).passthrough(),jv=z.object({PersonalizedAdsConsent:z.boolean().nullish(),TrackingConsent:z.boolean().nullish(),PolicyVersion:z.string().nullish(),Region:z.string().nullish(),ConsentGivenAt:c.nullish(),ConsentRevokedAt:c.nullish()}).passthrough(),_v=z.object({RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),Type:Wa.nullish(),IssuedAt:c.nullish(),ExpiresAt:c.nullish(),CreditsToAward:z.number().nullish()}).passthrough(),Wv=z.object({InvalidSsvCount:z.number().nullish(),OrphanCompletions:z.number().nullish(),FastCompletions:z.number().nullish(),LastFlaggedAt:c.nullish()}).passthrough();z.object({Credits:Gv.nullish(),Placements:z.record(z.string(),Fv).nullish(),Daily:Vv.nullish(),Session:Nv.nullish(),LastImpressionAt:c.nullish(),LastInterstitialAt:c.nullish(),LastRewardedAt:c.nullish(),LastAppOpenAt:c.nullish(),TotalImpressions:z.number().nullish(),TotalRewardedCompletions:z.number().nullish(),AdsDisabledUntil:c.nullish(),Consent:jv.nullish(),PendingRequests:z.record(z.string(),_v).nullish(),FraudFlags:Wv.nullish(),UpdatedAt:c.nullish()}).passthrough();
|
|
2
|
-
export{Ge as AIAction,
|
|
1
|
+
import {e,d,o,p,l,m,f}from'./chunk-LWS7EEOF.js';export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,q as NoopPlatformAdapter,h as PLATFORM_BRIDGE_ACK,n as PLATFORM_CREDITS_CONFIRM_MESSAGES,f as PLATFORM_ORIGINS,i as PLATFORM_PAGE_UNAVAILABLE,r as PLATFORM_SIGN_IN_MESSAGES,k as PLATFORM_TOPUP_MESSAGES,j as askPlatformPage,o as canUsePlatformCreditsConfirm,s as canUsePlatformSignIn,l as canUsePlatformTopUp,v as clearPlatformSignInDeclined,g as isPlatformParentOrigin,w as isPlatformSignInDeclined,u as markPlatformSignInDeclined,p as requestPlatformCreditsConfirm,t as requestPlatformSignIn,m as requestPlatformTopUp}from'./chunk-LWS7EEOF.js';import {b,a,c as c$1}from'./chunk-CS7ACWDY.js';export{e as isFail,d as isOk}from'./chunk-CS7ACWDY.js';import {z}from'zod';import Wt from'decimal.js';var Ci=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 Nm(){let o=new Map;return {get:e=>o.get(e)??null,set:(e,t)=>{o.set(e,t);},remove:e=>{o.delete(e);}}}function Ka(){return jm()??Nm()}function jm(){try{let o=globalThis.localStorage;if(!o)return null;let e="__idos_probe__";return o.setItem(e,"1"),o.removeItem(e),{get:t=>{try{return o.getItem(t)}catch{return null}},set:(t,i)=>{try{o.setItem(t,i);}catch{try{o.removeItem(t);}catch{}}},remove:t=>{try{o.removeItem(t);}catch{}}}}catch{return null}}var Ha="https://api.idosgames.com";function $a(o){return {titleID:o.titleID,titleTemplateID:o.titleTemplateID??"default",buildKey:o.buildKey??"",baseUrl:(o.baseUrl??Ha).replace(/\/+$/,""),devBuild:o.devBuild??false,debugLogging:o.debugLogging??false,configStorage:o.configStorage??Ka(),locale:o.locale??_m(),appVersion:o.appVersion??""}}function _m(){try{return globalThis.navigator?.language??""}catch{return ""}}var $r="idos_acq",Ja=["gclid","fbclid","ttclid","msclkid","yclid"],Wm=["ref","r"],Qm=["ref_","ref-","ref=","r_","r-"];var jt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();Km(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=Jm(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($r);}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=Xa(Ya(t));if(i)return i}return Bi(t)}readFromEnvironment(){let e={},t=Ya(this.platform.getFullURL());Nt(e,"UtmSource",t.get("utm_source")),Nt(e,"UtmMedium",t.get("utm_medium")),Nt(e,"UtmCampaign",t.get("utm_campaign")),Nt(e,"UtmTerm",t.get("utm_term")),Nt(e,"UtmContent",t.get("utm_content")),Nt(e,"ClaimToken",t.get("idos_click"));for(let R of Ja){let V=t.get(R);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",s=$m(i);if(s){for(let R of Hm)Nt(e,R,s.get(el[R])??null);for(let R of Ja){let V=s.get(R);if(V){e.ClickID=V;break}}}let n=Bi(s?s.get("ref")??s.get("r")??"":i),r=Xa(t),p=n||r;p&&(e.ReferralCode=p,e.ChannelHint=n?"telegram":"query");let d=this.platform.getReferrer?.();return d&&(e.Referrer=d),e}read(){try{let e=this.platform.storage.getString($r);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($r,JSON.stringify(e));}catch{}}};function Km(o){return !!(o.UtmSource||o.UtmMedium||o.UtmCampaign||o.ClickID||o.Referrer||o.ReferralCode||o.ClaimToken)}function Nt(o,e,t){t&&(o[e]=t);}var Za="a1_",el={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},Hm=Object.keys(el);function $m(o){let e=(o||"").trim();if(!e.startsWith(Za))return null;let t=e.slice(Za.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,d=>d.charCodeAt(0)),r=new TextDecoder().decode(n),p=new URLSearchParams(r);return [...p.keys()].length>0?p:null}catch{return null}}function Ya(o){try{let e=o.indexOf("?");return new URLSearchParams(e>=0?o.slice(e):"")}catch{return new URLSearchParams}}function Xa(o){for(let e of Wm){let t=o.get(e);if(t)return Bi(t)}return null}function Bi(o){let e=(o||"").trim();if(!e)return null;for(let t of Qm)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Jm(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 tl="idos_usage_pending",il="idos_usage_session",sl="idos_usage_closed_session",nl="idos_usage_new_session",rl="idos_usage_last_activity",Si=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(tl),this.currentSessionSeconds=this.readNumber(il),this.pendingClosedSessionSeconds=this.readNumber(sl),this.isNewSessionPending=this.readNumber(nl)!==0;let e=this.readNumber(rl);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(tl,this.pendingSeconds),this.writeNumber(il,this.currentSessionSeconds),this.writeNumber(sl,this.pendingClosedSessionSeconds),this.writeNumber(nl,this.isNewSessionPending?1:0),this.writeNumber(rl,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 ut={Virtual:"Virtual",Crypto:"Crypto"},ii=z.enum(["Virtual","Crypto"]).catch("Virtual"),Li={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},si=z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),mt={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Gi=z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),Zm={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Fi=z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),Ym={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Vi=z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),Xm={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},xi=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 al(){let o=globalThis,e=o.Capacitor?.getPlatform?.();if(e)return ol(e);let t=o.cordova?.platformId;return t?ol(t):o.navigator?.userAgent??""?mt.Web:mt.Unknown}function ol(o){let e=o.toLowerCase();return e==="android"?mt.Android:e==="ios"?mt.Ios:e==="web"?mt.Web:mt.Unknown}var _=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}),c=z.string();var Jr=z.object({Type:si.nullish(),CurrencyID:z.string().nullish(),Amount:_.nullish(),AmountUsd:z.number().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ProductID:z.string().nullish()}),ef=z.object({Type:Vi.nullish(),EntityID:z.string()}),tf=z.object({Address:ef.nullish(),Amount:_.nullish(),Source:z.string().nullish()}),ce=z.object({Entries:z.array(Jr).nullish(),EventTokens:z.array(tf).nullish()}),ll=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Resources:ce.nullish()}),H=z.object({Standard:ce.nullish(),PremiumBonuses:z.array(z.unknown()).nullish(),PremiumTiers:z.array(ll).nullish()}),xt=z.object({Standard:ce.nullish(),PremiumDiscounts:z.array(z.unknown()).nullish(),PremiumTiers:z.array(ll).nullish()}),M=z.object({Grant:H.nullish(),Consume:xt.nullish()}),bt=z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Transferred:ce.nullish()});var sf=z.object({ExperimentID:z.string().nullish(),Variants:z.array(z.string()).nullish()}).passthrough(),nf={Completed:"Completed",Started:"Started",StepReached:"StepReached"},rf=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:sf.nullish(),Tutorial:rf.nullish(),Platforms:z.array(Gi).nullish()}).passthrough();var Re=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 of=z.object({OffsetSecondsFromParentStart:z.number().nullish(),DurationSeconds:z.number().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),af=z.object({StartUtc:z.string().nullish(),EndUtc:z.string().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),lf=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 uf=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 st=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:Re.nullish()}).passthrough(),fe=z.object({Mode:z.string().nullish(),IsActive:z.boolean().nullish(),Scheduled:af.nullish(),Chain:lf.nullish(),Cyclic:uf.nullish(),ActivationTriggers:z.array(st).nullish(),Relative:of.nullish()}).passthrough();var cf={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},pf=z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),hf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},df=z.enum(["Step","Linear","Geometric"]).catch("Step"),mf=z.object({AtStep:z.number().nullish(),Value:z.number().nullish()}).passthrough(),Fe=z.object({Base:z.number().nullish(),Shape:pf.nullish(),PerStep:z.number().nullish(),PerStepRate:z.number().nullish(),GrowthRate:z.number().nullish(),Points:z.array(mf).nullish(),Interpolation:df.nullish(),TailGrowthRate:z.number().nullish(),MinResult:z.number().nullish(),MaxResult:z.number().nullish()}).passthrough();var ff=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(),Zr=z.object({Bundles:z.array(ff).nullish(),Multipliers:z.array(gf).nullish()}).passthrough();var yf=z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Ni=z.object({Source:yf.nullish(),SourceKey:z.string().nullish(),Curve:Fe.nullish(),Anchor:z.number().nullish(),IncludeRewards:ce.nullish(),ExcludeRewards:ce.nullish()}).passthrough(),ul=z.object({ClaimedAt:z.string().nullish(),PremiumTiers:z.array(z.string()).nullish(),Unlocked:z.boolean().nullish()}).passthrough(),Be=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:Zr.nullish(),SortOrder:z.number().nullish(),IsFeatured:z.boolean().nullish()}).passthrough(),ni=z.object({Milestones:z.record(z.string(),Be).nullish()}).passthrough();var Q=z.object({PresetID:z.string().nullish(),Remove:z.array(z.string()).nullish()}).passthrough();var Rf=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:Rf.nullish()}).passthrough();var Cf=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),cl=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:c,ExpiresAt:c.nullish(),EquippedSlot:Cf.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),K=z.object({ChangedInstances:z.record(z.string(),cl).nullish(),RemovedInstanceIDs:z.array(z.string()).nullish()});var Ie=o=>z.object({Id:z.string(),Success:z.boolean(),Error:z.string().nullish(),Data:o.nullish()}),ft=o=>z.object({ServerTimeUtc:c,Items:z.array(Ie(o)),Resources:M.nullish(),Inventory:K.nullish()});var Sf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},pl=z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),xf=z.object({}).passthrough().transform(o=>o),bf=z.object({CycleID:z.string(),InstanceKey:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),CycleStartUtc:c.nullish(),CycleEndUtc:c.nullish(),PointsTotalEarned:_.nullish(),PointsCurrent:_.nullish(),ClaimedPointMilestoneIDs:z.array(z.string()).nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),Yr=z.object({QuestID:z.string(),CycleID:z.string().nullish(),ObjectiveID:z.string().nullish(),NewValue:_.nullish(),ObjectiveCompleted:z.boolean().nullish(),Status:pl}),hl=z.object({State:xf.nullish(),PointsTracks:z.record(z.string(),bf).nullish()}),Xr=z.object({ServerTimeUtc:c,QuestID:z.string(),CycleID:z.string().nullish(),NewStatus:pl.nullish(),Resources:M.nullish(),Inventory:K.nullish()}),eo=z.object({ServerTimeUtc:c,CycleID:z.string(),MilestoneID:z.string(),PointsTotalEarned:_.nullish(),Resources:M.nullish(),Inventory:K.nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),dl=z.object({ServerTimeUtc:c,CycleID:z.string(),GroupCompletionID:z.string(),GroupID:z.string().nullish(),CompletedGroupQuests:z.number().nullish(),RequiredGroupQuests:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),ml=z.object({MetricID:z.string(),Updates:z.array(Yr).nullish()}),fl=z.array(Ie(Xr)),gl=z.array(Ie(eo)),Df={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Pf=z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),If={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},vf=z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),yl=z.object({ObjectiveID:z.string().nullish(),Source:Pf.nullish(),MaxProgressPerCall:z.number().nullish(),MetricID:z.string().nullish(),Triggers:z.array(st).nullish(),TargetValue:z.number().nullish(),AggregationMethod:z.string().nullish()}).passthrough(),to=z.object({Milestones:Q.nullish(),Linking:Q.nullish(),Availability:Q.nullish(),Reward:Q.nullish(),Objectives:Q.nullish()}).passthrough(),Tf=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(),Rl=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:vf.nullish()}).passthrough(),Cl=z.object({Schedule:fe.nullish(),AccrueProgressWhenLocked:z.boolean().nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Sl=z.object({Grant:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),kf=z.object({QuestID:z.string().nullish(),Identity:Tf.nullish(),Linking:Rl.nullish(),Availability:Cl.nullish(),Objectives:z.record(z.string(),yl).nullish(),Reward:Sl.nullish(),Presets:to.nullish()}).passthrough(),Af=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(),zf=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(),Be).nullish(),Presets:to.nullish(),PointsToken:_t.nullish()}).passthrough(),wf=z.object({Milestones:z.record(z.string(),ni).nullish(),Linking:z.record(z.string(),Rl).nullish(),Availability:z.record(z.string(),Cl).nullish(),Reward:z.record(z.string(),Sl).nullish(),Objectives:z.record(z.string(),z.record(z.string(),yl)).nullish()}).passthrough(),Mf=z.object({CycleID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:fe.nullish(),Milestones:z.record(z.string(),Be).nullish(),Gate:Z.nullish(),PointsToken:_t.nullish(),GroupCompletions:z.record(z.string(),Af).nullish(),Phases:z.record(z.string(),zf).nullish(),Presets:to.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(),Mf).nullish(),Quests:z.record(z.string(),kf).nullish(),Presets:wf.nullish()}).passthrough(),pt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var Of={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},Ef=z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),Uf={Never:"Never",OnRequest:"OnRequest",Always:"Always"},qf=z.enum(["Never","OnRequest","Always"]).catch("Never"),Bf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},Lf=z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),Gf={GameLoop:"GameLoop"},Ff={Raid:"Raid",Attack:"Attack"},Vf=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(),Nf=z.object({Mode:Ef.nullish(),Triggers:z.array(st).nullish(),TargetValue:z.number().nullish(),RequireAllTriggers:z.boolean().nullish()}).passthrough(),jf=z.object({Grant:H.nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),_f=z.object({TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),RandomActionType:z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),Wf=z.object({Module:z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:_f.nullish(),MaxUses:z.number().nullish()}).passthrough(),Qf=z.object({Skippable:z.boolean().nullish(),TimeoutSeconds:z.number().nullish()}).passthrough(),io=z.object({StepID:z.string().nullish(),Order:z.number().nullish(),Identity:Vf.nullish(),Completion:Nf.nullish(),Effects:jf.nullish(),Script:Wf.nullish(),Policy:Qf.nullish()}).passthrough(),Kf=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(),xl=z.object({Schedule:fe.nullish(),Gate:Z.nullish(),RequiredFlowIDs:z.array(z.string()).nullish(),AutoStart:z.boolean().nullish(),StartTrigger:st.nullish()}).passthrough(),bl=z.object({Skippable:z.boolean().nullish(),SkippableFromOrder:z.number().nullish(),RestartPolicy:qf.nullish(),ExpireAfterSeconds:z.number().nullish(),IsBlocking:z.boolean().nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),Dl=z.object({Grant:H.nullish(),AutoClaim:z.boolean().nullish()}).passthrough(),Hf=z.object({Availability:Q.nullish(),Policy:Q.nullish(),Reward:Q.nullish(),Steps:Q.nullish()}).passthrough(),$f=z.object({FlowID:z.string().nullish(),Identity:Kf.nullish(),Availability:xl.nullish(),Policy:bl.nullish(),Steps:z.record(z.string(),io).nullish(),Reward:Dl.nullish(),Presets:Hf.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(),Zf=z.object({IsEnabled:z.boolean().nullish(),MaxActiveFlows:z.number().nullish(),Blocking:Jf.nullish()}).passthrough(),Yf=z.object({Availability:z.record(z.string(),xl).nullish(),Policy:z.record(z.string(),bl).nullish(),Reward:z.record(z.string(),Dl).nullish(),Steps:z.record(z.string(),z.record(z.string(),io)).nullish()}).passthrough(),Pl=z.object({Flows:z.record(z.string(),$f).nullish(),Settings:Zf.nullish(),Presets:Yf.nullish()}).passthrough(),Xf=z.object({}).passthrough().transform(o=>o),Il=z.object({FlowID:z.string(),Status:Lf,CurrentStepID:z.string().nullish(),CurrentStep:io.nullish(),TotalSteps:z.number(),CompletedSteps:z.number(),CanSkip:z.boolean(),RewardClaimed:z.boolean(),RewardPending:z.boolean(),VariantID:z.string().nullish()}).passthrough(),Wi=z.object({State:Xf.nullish(),Flows:z.array(Il).nullish(),UnlockedFeatures:z.array(z.string()).nullish()}).passthrough(),wt=z.object({Flow:Il.nullish()}).passthrough(),vl=z.object({FlowID:z.string().nullish(),Granted:M.nullish()}).passthrough(),Tl=z.array(Ie(wt)),kl=z.object({FlowID:z.string(),StepID:z.string(),Progress:z.number(),Target:z.number(),Completed:z.boolean()}).passthrough(),nt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Qi(o){return Array.isArray(o)?o.filter(e=>e!==null).map(Qi):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).filter(([,e])=>e!==null).map(([e,t])=>[e,Qi(t)])):o}var Ki=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 Hi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Al(o){return o===429||o>=500&&o<=599}function $i(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 Mt(o){return new Promise(e=>setTimeout(e,o))}var zl=15e3;async function wl(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 Ml(o,e=Math.random){return o+10+Math.min(250,o*.2)*e()}function Ol(o,e=Math.random){let t=o<=1?1500:o===2?4e3:6e3;return t+t*.1*e()}var so=15,El=1e3,Ji=class{constructor(e=so,t=()=>Date.now(),i=Mt){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]>=El;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(El-(e-this.starts[0])+5);}}};var eg=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function oi(o){if(!o)return null;let e=eg.exec(o);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new Wt(i),r=new Wt(s),p=r.minus(Wt.max(n,0));return p.lte(0)?null:{currencyID:t,required:r.toNumber(),available:n.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var tg=12e3,ig=new Set(["RelatedEntityID"]);function sg(o,e){if(e===null||typeof e!="object"||Array.isArray(e))return o;let t={};for(let[i,s]of Object.entries(e))ig.has(i)||(t[i]=s);try{return `${o}|${JSON.stringify(t)}`}catch{return o}}var ng=z.object({Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().optional(),QuestProgress:z.array(Yr).nullish(),TutorialProgress:z.array(kl).nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish()}).passthrough(),Zi=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Hi;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 Ki(e.throttleMs),this.pacer=new Ji(e.maxRequestsPerSecond??so),this.clientPlatform=e.clientPlatform??mt.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??sg(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}`,p=JSON.stringify(t),d=s.ticket??null,R=s.silent??!1,V=s.timeoutMs??tg,ae=s.autoRetry??!0,ve=!1,ye=!1,Me=0;for(;;){let St;s.keepalive||await this.pacer.take();try{St=await this.doFetch(r,p,d,V,s.keepalive??!1);}catch{if(ae&&Me<3){Me++,await Mt($i(Me));continue}return this.connectionFailure("Internet Connection Error",R)}let Je=St.status;if(Je>=200&&Je<300){let re=!ye&&this.cryptoTopUpHandler!==null,Pe=await this.parseSuccess(St,i,R,e,re);if(!Pe.ok&&re){let pe=oi(Pe.error);if(pe){if(ye=!0,await this.runTopUp(pe))continue;R||this.emitter.emit("error:global",Pe.error);}}return Pe}if(Je===401){if(!ve&&this.sessionRefreshHandler){ve=!0;let re=null;try{re=await this.sessionRefreshHandler();}catch{re=null;}if(re){d=re;continue}}return this.emitter.emit("auth:unauthorized",void 0),b("unauthorized","Unauthorized")}if(Al(Je)){let re=Je===429?await wl(St):null;if(re!==null&&re>zl)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(re/1e3)} s`,R);if(ae&&Me<3){Me++,await Mt(re!==null?Ml(re):Je===429?Ol(Me):$i(Me));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Je})`,R)}let yi="";try{yi=await St.text();}catch{}if(Je===409&&/operation in progress/i.test(yi)&&ae&&Me<3){Me++,await Mt($i(Me));continue}return this.handleWebError(yi,Je,R)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let r=new AbortController,p=setTimeout(()=>{r.abort();},s);try{let d={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(d.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:d,signal:r.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(p);}}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 p;try{p=JSON.parse(r);}catch{return this.globalError("JSON Parse Error",i)}let d=ng.safeParse(p);if(!d.success)return this.globalError("Malformed response envelope",i);if(!d.data.Success){let ye=d.data.Error??"Server returned Success=false",Me=n&&oi(ye);return !i&&!Me&&this.emitter.emit("error:global",ye),b("server",ye)}let R=d.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:d.data.StateEpoch??null,versions:R});let V=d.data.QuestProgress;V&&V.length>0&&this.emitter.emit("quest:systemProgress",V);let ae=d.data.TutorialProgress;ae&&ae.length>0&&this.emitter.emit("tutorial:systemProgress",ae);let ve=t.safeParse(d.data.Data);if(!ve.success){let ye=t.safeParse(Qi(d.data.Data));ye.success&&(ve=ye);}if(!ve.success){let ye=`Validation error (${s}): ${ve.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",ye),i||this.emitter.emit("error:global",ye),b("validation",ye)}return a(ve.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 ai(o){return (typeof o=="string"?o:o.toISOString()).slice(0,10)}function bi(o){return `${ai(o)}T00:00:00.000Z`}function Ul(o){let e=new Date(o);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function ql(o,e){return new Date(o.getTime()+e*6e4).toISOString()}function oo(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(),p=new Map,d$1=new Map,R=new Map,V=new Map,ae=new Map,ve=new Map,ye=new Map,Me=new Map,St=e.Grant?.PremiumTiers??[],Je=St.length;for(let re=0;;re++){let Pe,pe;if(re===0)Pe=e.Grant?.Standard?.Entries,pe=false;else if(re-1<Je)Pe=St[re-1]?.Resources?.Entries,pe=false;else if(re===1+Je)Pe=e.Consume?.Standard?.Entries,pe=true;else break;if(Pe)for(let le of Pe){if(le.Type==null)continue;let he=Math.max(0,le.Amount??0);if(!(he<=0))switch(le.Type){case "VirtualCurrency":{if(!le.CurrencyID)continue;let de=pe?d$1:p;de.set(le.CurrencyID,(de.get(le.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!le.CurrencyID)continue;let de=pe?V:R;de.set(le.CurrencyID,(de.get(le.CurrencyID)??new Wt(0)).plus(he));break}case "Item":{if(!le.ItemID)continue;let de=og(t,le.CatalogID,le.ItemID),xe=(de?de.IsStackable??true:true)?pe?ve:ae:pe?Me:ye;xe.set(le.ItemID,(xe.get(le.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||d$1.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let re of new Set([...p.keys(),...d$1.keys()])){let Pe=p.get(re)??0,pe=d$1.get(re)??0,le=Pe-pe,he=n.VirtualCurrencies[re];he?(he.Amount+=le,he.UpdatedAt=r,he.Daily&&ai(he.Daily.PeriodStartUtc)===ai(i)?(he.Daily.Earned+=Pe,he.Daily.Spent+=pe):he.Daily={PeriodStartUtc:bi(i),Earned:Pe,Spent:pe}):n.VirtualCurrencies[re]={Amount:le,CreatedAt:r,UpdatedAt:r,Daily:{PeriodStartUtc:bi(i),Earned:Pe,Spent:pe}};}}if(s.ccChanged=R.size>0||V.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let re of new Set([...R.keys(),...V.keys()])){let Pe=R.get(re)??new Wt(0),pe=V.get(re)??new Wt(0),le=Pe.minus(pe),he=n.CryptoCurrencies[re];he?(he.Amount=new Wt(he.Amount).plus(le).toString(),he.UpdatedAt=r):n.CryptoCurrencies[re]={Amount:le.toString(),Frozen:"0",CreatedAt:r,UpdatedAt:r};}}if(s.itemsChanged=ae.size>0||ve.size>0||ye.size>0||Me.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let re=n.UnstackableItems,Pe=new Set([...ae.keys(),...ve.keys(),...ye.keys(),...Me.keys()]);for(let pe of Pe){let le=(ae.get(pe)??0)-(ve.get(pe)??0),he=(ye.get(pe)??0)-(Me.get(pe)??0),de=le+he,it=n.Items[pe];it?(le!==0&&(it.StackableAmount+=le),he!==0&&(it.UnstackableAmount+=he),de!==0&&(it.TotalAmount+=de)):n.Items[pe]={StackableAmount:Math.max(0,le),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,de)};}for(let[pe,le]of Me){if(le<=0)continue;let he=Object.values(re).filter(de=>de.ItemID===pe&&de.EquippedSlot==null&&(de.ExpiresAt==null||new Date(de.ExpiresAt)>i)).sort(rg).slice(0,le).map(de=>de.ItemInstanceID);for(let de of he)delete re[de];}for(let[pe,le]of ye){let he=ag(t,pe);for(let de=0;de<le;de++){let it=d();re[it]={ItemInstanceID:it,ItemID:pe,CatalogID:he,RemainingUses:1,AcquiredAt:r};}}}o.EventToken??={};let yi=o.EventToken;for(let re=0;;re++){let Pe,pe;if(re===0)Pe=e.Grant?.Standard?.EventTokens,pe=false;else if(re-1<Je)Pe=St[re-1]?.Resources?.EventTokens,pe=false;else if(re===1+Je)Pe=e.Consume?.Standard?.EventTokens,pe=true;else break;if(!(!Pe||Pe.length===0))for(let le of Pe){let he=le.Address;if(!he||he.Type==null)continue;let de=le.Amount??0;if(de<=0)continue;let it=lg(yi,he.Type);if(!it)continue;let xe=it[he.EntityID];xe||(xe={},it[he.EntityID]=xe),xe.Balance??={Current:0,TotalEarned:0,TotalSpent:0},xe.Daily??={Date:bi(i),TotalEarned:0},xe.Meta??={};let Ri=le.Source&&le.Source.length>0?le.Source:"CustomAction";pe?(xe.Balance.Current-=de,xe.Balance.TotalSpent+=de):(xe.Balance.Current+=de,xe.Balance.TotalEarned+=de,ai(xe.Daily.Date)!==ai(i)&&(xe.Daily={Date:bi(i),TotalEarned:0}),xe.Daily.TotalEarned+=de,xe.Daily.EarnedBySource??={},xe.Daily.EarnedBySource[Ri]=(xe.Daily.EarnedBySource[Ri]??0)+de,xe.Daily.TriggersBySource??={},xe.Daily.TriggersBySource[Ri]=(xe.Daily.TriggersBySource[Ri]??0)+1,xe.Daily.LastTriggerBySource??={},xe.Daily.LastTriggerBySource[Ri]=r,xe.Meta.JoinedAtUtc||(xe.Meta.JoinedAtUtc=r),xe.Meta.LastEarnedAtUtc=r),s.tokensChanged=true;}}return s}function rg(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 og(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 ag(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 lg(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 Bl(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 d of Object.values(s))d?.ItemID&&r.add(d.ItemID);for(let d of n){let R=o[d]?.ItemID;R&&r.add(R);}if(r.size===0)return i;let p=d=>n.has(d)||d in s;if(e){for(let[d,R]of Object.entries(e))d in o||p(d)||R&&r.has(R.ItemID)&&i.drop.push(d);for(let[d,R]of Object.entries(o))d in e||p(d)||R&&r.has(R.ItemID)&&(i.restore[d]=R);}return i}function ao(o,e){return o===e||o.startsWith(`${e}:`)}var Xi=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=oo(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??{}},p=oo(n,e,i,s),d=Bl(r,n.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],ae=d.drop.length>0||Object.keys(d.restore).length>0||R.length>0||V.length>0;if(ae){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let ve=n.InventoryV2.UnstackableItems;for(let ye of d.drop)delete ve[ye];for(let[ye,Me]of Object.entries(d.restore))ve[ye]=Me;for(let[ye,Me]of R)ve[ye]=Me;for(let ye of V)delete ve[ye];}this.emitResourceChanges(p,ae);}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 Wt?t:new Wt(t),p=s===void 0?new Wt(0):s instanceof Wt?s:new Wt(s),d=i??new Date().toISOString(),R=n[e];R?(R.Amount=new Wt(R.Amount).plus(r).toString(),p.isZero()||(R.Frozen=new Wt(R.Frozen??0).plus(p).toString()),R.UpdatedAt=d):n[e]={Amount:r.toString(),Frozen:p.toString(),CreatedAt:d,UpdatedAt:d},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=Ul(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));}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(ao(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:!ao(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,p={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")r.Private??={},r.Private[t]=p;else if(e==="Public")r.Public??={},r.Public[t]=p;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 es=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 ts=class{user;config;constructor(e){this.user=new Xi(e),this.config=new es;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function ug(o){return o}var cg=0,pg=1500,hg=3,ss=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 d of new Set(e)){let R=this.rules.get(d);if(R&&(t?.force||R.needsServer(i))){s.push(this.runRule(d,R));continue}(t?.force||!this.state.isStateFresh(d,t?.maxAgeMs))&&n.push(d);}let p=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(a(void 0))])).find(d=>!d.ok);return p&&!p.ok?p: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();},cg),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 r of t)r(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=is(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 V=this.loginFailures.get(s);if(V)return this.loginFailures.delete(s),V;let ae=this.inflight.get(s);if(ae)return ae}let n=this.generation.get(s)??0,r=Date.now(),d=t().then(R=>{if(!R.ok)return R;let V=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:lo(e,R.data,V)}),R;let ae=this.entries.get(s);if(ae&&ae.storedAt>=r)return R;let ve=lo(e,R.data,V);return this.entries.set(s,{data:R.data,storedAt:V,expiresAt:Math.min(ve??1/0,V+pg)}),R}).finally(()=>{this.inflight.get(s)===d&&this.inflight.delete(s);});return this.inflight.set(s,d),d}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=is(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=Ll({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>hg||this.used.set(Ll(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(is(e,t))?.data}put(e,t,i){this.register(e);let s=is(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:lo(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 is(o,e){return e===void 0?o.key:`${o.key}|${e}`}function Ll(o){return o.Key?`${o.Name}|${o.Key}`:o.Name}function lo(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 ns=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 dg(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 dg(o){return o!==null&&Object.values(ze).includes(o)}var mg=8,fg=100,gg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,Gl=["GameLoop"];function yg(o){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(o)}var rs=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=ze.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";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$1;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$1;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 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"):(yg(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;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>=mg&&e.length<=fg}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.sessionAuthType=ze.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){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(Gl,Gl);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 Rg="idos:cfg",li=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Fl(t)}`:e&&e.length>0?`f:${Fl(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 `${Rg}:${this.titleId}:${e}`}};function Fl(o){return [...o].map(e=>e.toLowerCase()).sort().join(",")}var Vl="idos:loc",ui=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 `${Vl}:${this.titleId}:${e}`}versionsKey(){return `${Vl}:${this.titleId}:versions`}};var Cg="idos:sec",os=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 `${Cg}:${this.titleId}`}};var Sg="idos:state",as=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 `${Sg}:${this.titleId}:${e}`}};function xg(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 uo(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 bg(o){return {...o??{}}}function co(o){return typeof o.StateEpoch=="string"&&o.StateEpoch.length>0?o.StateEpoch:null}var ls=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=xg(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 p=this.versions[n];p!==r&&(p!==void 0&&r===p+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=bg(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 Nl=b("server","Title configuration is unavailable (CDN and API both failed)."),us=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 li(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new ui(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new os(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new ls(new as(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$1;let t=li.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?Nl:(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=uo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=co(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 p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return n&&await this.configCache.write(t,n,p),p}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$1;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=li.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let r=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let p=await this.ctx.api.user.getClientStateExcept(i);if(!p.ok)return p;let d=await this.resolveTitleConfig(p.data,s,n,{ExcludeFields:t??[]});return d==null?Nl:(this.finishStateHandshake(p.data,r),await this.restoreSections(p.data.TitleConfigVersion,d),await this.applyClientState(p.data,d,e,t),this.ctx.cache.acceptLoginViews(p.data.Views),await this.applyLocalization(p.data.Localization),await this.flushState(r),p)}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??{},p=n.Version??0,d=n.Locale??e;return p>0&&await this.localizationCache.write(d,p,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$1}async getUserState(e){let t=this.baseRequest();if(!t)return c$1;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=uo(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let r=i.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([R,V])=>r[R]!==V||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(n,p);let d=co(s.data);return d&&(this.stateStore.afterSliceRead(d,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$1;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$1;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$1;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$1;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$1;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$1;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,p=n?this.ctx.data.user.state?.GameLoop:void 0,d=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=p);let V=this.ctx.data.config.titlePublicConfiguration;r&&V&&V.GameLoop==null&&(V.GameLoop=d),this.ctx.emitter.emit("user:clientStateReceived",e);}};var ps=class{constructor(e){this.ctx=e;}ctx;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===ut.Crypto||i===ut.Crypto)return b("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return c$1;let p={...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}_${d()}`},d$1=await this.ctx.api.currency.convert(p);if(d$1.ok){let R=d$1.data,V={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(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return d$1}async cryptoConvert(e,t,i,s,n,r){let p=n instanceof Wt?n:new Wt(n);if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(p.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===ut.Virtual&&i===ut.Virtual)return b("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ut.Virtual&&!p.isInteger())return b("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:p.toString(),TransactionID:r&&r.length>0?r:`crypto_convert_${e}_${t}_to_${i}_${s}_${d()}`},R=await this.ctx.api.currency.cryptoConvert(d$1);if(R.ok){let V=R.data,ae=[],ve=[];if(V.SourceType===ut.Virtual&&ae.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===ut.Virtual&&ve.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),ae.length>0||ve.length>0){let ye={Consume:ae.length>0?{Standard:{Entries:ae}}:null,Grant:ve.length>0?{Standard:{Entries:ve}}:null};this.ctx.data.user.applyResourceOperation(ye,this.ctx.data.config.itemDefinitions);}V.SourceType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new Wt(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new Wt(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return R}};var hs=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let s=e.trim();if(!s)return b("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${s}_${d()}`};t&&t.length>0&&(n.FodderInstanceIDs=[...t]);let r=await this.ctx.api.item.upgradeLevel(n);return r.ok&&(this.ctx.data.user.patchEquippedItemLevel(r.data.ItemInstanceID??s,r.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",r.data)),r}async upgradeLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;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 jl=z.object({OptionID:z.string().nullish(),Name:z.string().nullish(),Cost:xt.nullish(),AllowedPlatforms:z.array(Gi).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),ue=z.record(z.string(),jl),Dg=z.object({Store:Fi,Receipt:z.string(),Signature:z.string().nullish()}).passthrough();var Di={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},po=z.object({ConfirmationID:z.string(),Url:z.string(),Status:z.string(),PriceCredits:z.number(),ExpiresAt:c}).passthrough(),_l=z.object({Linked:z.boolean(),Credits:z.number(),TopUpUrl:z.string().nullish()}).passthrough(),Pg={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"},ho=z.object({ServerTimeUtc:c,OfferID:z.string(),Count:z.number(),Resources:M.nullish(),Inventory:K.nullish(),CreditsConfirmation:po.nullish()}),Wl=z.array(Ie(ho)),Ig=z.object({OfferID:z.string(),TotalPurchases:z.number(),DailyPurchases:z.number(),DailyResetUtc:c,LastPurchasedAt:c}),vg=z.object({SlotKey:z.string(),InstanceKey:z.string(),OfferID:z.string().nullish(),Purchases:z.number(),LastPurchasedAt:c}),Ql=z.object({Purchases:z.record(z.string(),Ig).nullish(),Rotations:z.record(z.string(),vg).nullish()}).passthrough().transform(o=>o),Dt=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(),ds=z.object({Schedule:fe.nullish(),Gate:Z.nullish()}).passthrough(),Tg={Fixed:"Fixed",Title:"Title",Player:"Player"},kg=z.object({OfferID:z.string().nullish(),Weight:z.number().nullish(),Gate:Z.nullish()}).passthrough(),Kl=z.object({Mode:z.string().nullish(),OfferID:z.string().nullish(),Pool:z.array(kg).nullish(),Salt:z.string().nullish(),PerInstanceCap:z.number().nullish()}).passthrough(),Ag=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Rotation:Q.nullish()}).passthrough(),zg=z.object({SlotID:z.string().nullish(),Identity:Dt.nullish(),Availability:ds.nullish(),Rotation:Kl.nullish(),Presets:Ag.nullish()}).passthrough(),wg=z.object({Identity:Q.nullish(),Availability:Q.nullish()}).passthrough(),Mg=z.object({SectionID:z.string().nullish(),Identity:Dt.nullish(),Availability:ds.nullish(),Slots:z.record(z.string(),zg).nullish(),UniqueOffersInSection:z.boolean().nullish(),Presets:wg.nullish()}).passthrough(),Hl=z.object({Sections:z.record(z.string(),Mg).nullish()}).passthrough(),Og=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Layout:Q.nullish()}).passthrough(),Eg=z.object({StoreID:z.string().nullish(),Identity:Dt.nullish(),Availability:ds.nullish(),Layout:Hl.nullish(),Presets:Og.nullish()}).passthrough(),$l=z.object({Options:ue.nullish(),CompareAt:z.record(z.string(),xt).nullish()}).passthrough(),Jl=z.object({Grant:H.nullish()}).passthrough(),Zl=z.object({Schedule:fe.nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Ug=z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish(),Availability:Q.nullish()}).passthrough(),qg=z.object({OfferID:z.string().nullish(),Identity:Dt.nullish(),Pricing:$l.nullish(),Reward:Jl.nullish(),Availability:Zl.nullish(),Presets:Ug.nullish()}).passthrough(),Bg=z.object({Identity:z.record(z.string(),Dt).nullish(),Availability:z.record(z.string(),ds).nullish(),Layout:z.record(z.string(),Hl).nullish(),Rotation:z.record(z.string(),Kl).nullish(),Pricing:z.record(z.string(),$l).nullish(),Reward:z.record(z.string(),Jl).nullish(),OfferAvailability:z.record(z.string(),Zl).nullish()}).passthrough(),ms=z.object({Stores:z.record(z.string(),Eg).nullish(),StoreOffers:z.record(z.string(),qg).nullish(),Presets:Bg.nullish()}).passthrough(),Lg=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:c.nullish()}).passthrough(),Gg=z.object({OptionID:z.string(),Name:z.string().nullish(),Cost:xt.nullish(),CompareAtCost:xt.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(),Fg=z.object({OfferID:z.string(),Identity:Dt.nullish(),PriceOptions:z.array(Gg).nullish(),Rewards:H.nullish(),State:Lg.nullish()}).passthrough(),Vg=z.object({SlotID:z.string(),Identity:Dt.nullish(),SortOrder:z.number(),RotationMode:z.string().nullish(),RotationInstanceKey:z.string().nullish(),RefreshesAtUtc:c.nullish(),RemainingThisRotation:z.number().nullish(),Offer:Fg.nullish()}).passthrough(),Ng=z.object({SectionID:z.string(),Identity:Dt.nullish(),SortOrder:z.number(),Slots:z.array(Vg).nullish()}).passthrough(),jg=z.object({StoreID:z.string(),Identity:Dt.nullish(),SortOrder:z.number(),ScheduleInstanceKey:z.string().nullish(),ExpiresAtUtc:c.nullish(),Sections:z.array(Ng).nullish()}).passthrough(),fs=z.object({ServerTimeUtc:c,Stores:z.array(jg).nullish(),AdCreditBalance:z.number()}).passthrough(),Pt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},_g="OFFER_NOT_IN_ROTATION";var Yl="Store",Xl={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}},gs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Xl,{schema:fs,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$1;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()}`},r=await this.ctx.api.store.purchase(n);if(r.ok&&!r.data.CreditsConfirmation){let p=r.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return r}async purchaseWithCredits(e,t=1,i={}){let s=await this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot});if(!s.ok||!s.data.CreditsConfirmation)return s;let n=s.data.CreditsConfirmation,r=()=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:n.ConfirmationID});if(o()){let R=await p({titleID:this.ctx.settings.titleID,confirmationID:n.ConfirmationID});if(R.ok)return await r();if(R.error==="DECLINED")return b("server","CREDITS_CONFIRMATION_DECLINED");if(R.error==="NOT_ENOUGH_CREDITS")return b("server","NOT_ENOUGH_CREDITS")}i.onConfirmation?.(n);let p$1=Math.max(1e3,i.pollMs??2500),d=Date.parse(n.ExpiresAt)+6e4;for(;;){if(i.signal?.aborted)return b("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>d)return b("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(ae=>setTimeout(ae,p$1));let R=await this.getCreditsConfirmation(n.ConfirmationID);if(!R.ok)continue;let V=R.data.Status;if(V!==Di.Pending)return V===Di.Declined?b("server","CREDITS_CONFIRMATION_DECLINED"):V===Di.Expired?b("server","CREDITS_CONFIRMATION_EXPIRED"):await r()}}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):c$1}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):c$1}async purchaseBatch(e){if(!e||e.length===0)return b("client","purchases is required.");if(!this.ctx.auth.context)return c$1;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(Yl,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Yl,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(Xl,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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 ys=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return c$1;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return c$1;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$1;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$1;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$1;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 eu=3,Wg=700,Rs=class{constructor(e){this.ctx=e;l()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return oi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await m({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<=eu;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===eu)break;await Mt(Wg);}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===Li.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!==Li.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 tu="Lootbox",Cs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(tu,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$1;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection(tu,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s){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$1;let n={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,RelatedEntityID:`lootbox_${e}_${i??"default"}_${d()}`},r=await this.ctx.api.lootbox.open(n);if(r.ok){let p=r.data;p.TriggeredPity&&p.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,p.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",p);}return r}};var mo="Reward";function fo(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Ss=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(mo)?.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(mo,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$1;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(mo,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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(!fo(e))return b("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;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(!fo(e))return b("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;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(!fo(e))return b("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;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}};var xs="Tutorial",iu={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"]},bs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(iu,{schema:Wi,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(xs)?.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(xs,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(xs,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(iu,()=>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$1;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$1;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$1;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$1;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$1;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:r};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let d=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,R=await i(p);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(n,r,d,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(xs)?.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 Ds=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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$1;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$1;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Oe=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 Qg={Global:"Global",Announcement:"Announcement",Group:"Group"},nu=z.enum(["Global","Announcement","Group"]).catch("Global"),Kg={None:"None",Language:"Language",Region:"Region"},Hg=z.enum(["None","Language","Region"]).catch("None"),$g={Anyone:"Anyone",Friends:"Friends"},Jg=z.enum(["Anyone","Friends"]).catch("Anyone"),Zg={Reject:"Reject",Mask:"Mask"},Yg=z.enum(["Reject","Mask"]).catch("Reject"),Xg={Player:"Player",Publisher:"Publisher",System:"System"},ey=z.enum(["Player","Publisher","System"]).catch("Player"),ty={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var iy=z.object({DisplayNameKey:z.string().nullish(),SortOrder:z.number().nullish(),IconPath:z.string().nullish(),JoinedByDefault:z.boolean().nullish()}).passthrough(),ru=z.object({Gate:Z.nullish(),Schedule:fe.nullish()}).passthrough(),ou=z.object({Gate:Z.nullish(),Limits:Re.nullish(),MaxLength:z.number().nullish()}).passthrough(),au=z.object({HotTailSize:z.number().nullish(),HistoryHours:z.number().nullish()}).passthrough(),sy=z.object({Availability:Q.nullish(),Write:Q.nullish(),Retention:Q.nullish()}).passthrough(),ny=z.object({ChannelID:z.string().nullish(),Identity:iy.nullish(),Type:nu.nullish(),GroupSource:z.string().nullish(),Partitioning:Hg.nullish(),Capacity:z.number().nullish(),Availability:ru.nullish(),Write:ou.nullish(),Retention:au.nullish(),Presets:sy.nullish()}).passthrough(),ry=z.object({IsEnabled:z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:Jg.nullish(),Limits:Re.nullish(),MaxLength:z.number().nullish(),HistoryHours:z.number().nullish(),MaxConversations:z.number().nullish()}).passthrough(),oy=z.object({BlockedTerms:z.array(z.string()).nullish(),BlockedTermAction:Yg.nullish(),MaxIgnoreListSize:z.number().nullish(),ReportsEnabled:z.boolean().nullish(),ReportLimits:Re.nullish()}).passthrough(),ay=z.object({MinIntervalSeconds:z.number().nullish(),MaxMessagesPerPoll:z.number().nullish(),MaxHistoryPageSize:z.number().nullish()}).passthrough(),ly=z.object({Availability:z.record(z.string(),ru).nullish(),Write:z.record(z.string(),ou).nullish(),Retention:z.record(z.string(),au).nullish()}).passthrough(),lu=z.object({IsEnabled:z.boolean().nullish(),Channels:z.record(z.string(),ny).nullish(),Direct:ry.nullish(),Moderation:oy.nullish(),Polling:ay.nullish(),Presets:ly.nullish()}).passthrough(),uy=z.object({LastReadAt:z.string().nullish(),LastReadMessageID:z.string().nullish(),Left:z.boolean().nullish()}).passthrough(),su=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(),uy).nullish(),Limits:z.record(z.string(),su).nullish(),ReportLimits:su.nullish()}).passthrough();var go=z.object({RoomID:z.string().nullish(),SentAt:z.string().nullish(),MessageID:z.string().nullish()}).passthrough(),Ps=z.object({RoomID:z.string().nullish(),ChannelID:z.string().nullish(),MessageID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderProfile:Oe.nullish(),AuthorType:ey.nullish(),Text:z.string().nullish(),SentAt:z.string().nullish()}).passthrough(),cy=z.object({ChannelID:z.string().nullish(),RoomID:z.string().nullish(),DisplayNameKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),Type:nu.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(),Is=z.object({Channels:z.array(cy).nullish(),PollIntervalSeconds:z.number().nullish(),MutedUntil:z.string().nullish(),MuteReason:z.string().nullish()}).passthrough(),py=z.object({RoomID:z.string().nullish(),Messages:z.array(Ps).nullish(),NextCursor:go.nullish(),UnreadCount:z.number().nullish(),ServedFromDatabase:z.boolean().nullish()}).passthrough(),uu=z.object({Rooms:z.array(py).nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),cu=z.object({RoomID:z.string().nullish(),Messages:z.array(Ps).nullish(),NextBefore:go.nullish()}).passthrough(),pu=z.object({Message:Ps.nullish(),Moderated:z.boolean().nullish()}).passthrough(),hu=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Oe.nullish(),MaxLength:z.number().nullish()}).passthrough(),hy=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Oe.nullish(),LastMessage:Ps.nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),du=z.object({Conversations:z.array(hy).nullish()}).passthrough(),ci=z.object({Ignored:z.array(z.string()).nullish(),Cursor:go.nullish(),Joined:z.boolean().nullish()}).passthrough(),mu=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish()}).passthrough(),Qe={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 fu="Chat",gu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},vs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(gu,{schema:Is,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(fu,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(fu,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(gu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return c$1;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$1;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$1}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return c$1;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$1;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$1}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):c$1}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return c$1;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$1}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):c$1}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$1}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):c$1}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):c$1}resetCursors(){this.cursors.clear();}};var dy={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},my=z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),fy={Player:"player",Title:"title",Creator:"creator"},pi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},yu=z.object({Configured:z.boolean().nullish(),PublicKey:z.string().nullish()}).passthrough(),gy=z.object({TitleID:z.string().nullish(),Topic:z.string().nullish()}).passthrough(),yo=z.object({EndpointHash:z.string().nullish(),Transport:my.nullish(),Locale:z.string().nullish(),Topics:z.array(gy).nullish()}).passthrough(),Ru=z.object({Configured:z.boolean().nullish(),Subscriptions:z.array(yo).nullish()}).passthrough(),It={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var yy="IDOS_PLATFORM_PUSH_REQUEST",Ry="IDOS_PLATFORM_PUSH_RESPONSE",Cy=12e4;function Cu(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=d=>{s||(s=true,window.removeEventListener("message",r),clearTimeout(p),i(d));},r=d=>{let R=d?.data;!R||R.type!==Ry||R.requestId!==t||f.includes(d.origin)&&n(R.ok===true);},p=setTimeout(()=>n(false),Cy);window.addEventListener("message",r);for(let d of f)try{e.postMessage({type:yy,requestId:t,titleID:o},d);}catch{}})}var Ts=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 It.Unsupported;if(this.isEmbedded())return It.Embedded;if(!this.isSupported())return It.Unsupported;let t=Notification.permission;return t==="denied"?It.Blocked:t!=="granted"?It.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?It.Subscribed:It.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return b("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Cu(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 r=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:Sy(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return c$1;let d=r.toJSON();p.PushEndpoint=d.endpoint,p.PushP256dh=d.keys?.p256dh,p.PushAuth=d.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(p);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$1;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$1}async unsubscribeByHash(e){if(!e)return b("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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 Sy(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 ks=Object.freeze({}),As=class{constructor(e){this.ctx=e;}ctx;table={...ks};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new ui(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?xy(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...ks},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$1;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:r}=i.data,p=null;if(r){let d=await this.loadTableFromApi(r);d.ok&&(p=d.data.table);}return this.table=n,this.fallbackTable=p,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$1}reset(){this.table={...ks},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$1;t.Locale=e;let i=await this.cache.read(Su(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??Su(e),p=n.Version??0;if(n.NotModified){let R=i??await this.cache.read(r);return {ok:true,data:{locale:r,table:R?.t??{...ks},fallbackLocale:n.FallbackLocale??null}}}let d=n.Entries??{};return p>0&&await this.cache.write(r,p,d),{ok:true,data:{locale:r,table:d,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 xy(o,e){return o.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function Su(o){return o.trim().replace(/_/g,"-").toLowerCase()}var Ro="Quest",by={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}},zs=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(Ro)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let r of Object.keys(s)){let p=Date.parse(n[r]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=i&&t<p)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(Ro,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ro,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(by,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return c$1;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$1;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$1;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()}`},r=await this.ctx.api.quest.claimQuestReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return r}async claimQuestRewardsBatch(e){if(!e||e.length===0)return b("client","quests is required.");if(!this.ctx.auth.context)return c$1;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$1;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${d()}`},r=await this.ctx.api.quest.claimMilestoneReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return r}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;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$1;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${d()}`},r=await this.ctx.api.quest.claimGroupCompletionReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return 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$1;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 xu=z.object({}).passthrough().transform(o=>o);var Dy=z.object({Order:z.number().nullish(),Type:z.string().nullish(),DurationSec:z.number().nullish(),BonusMultiplier:z.number().nullish()}).passthrough(),Py=z.object({Schedule:z.array(Dy).nullish(),RepeatCycle:z.boolean().nullish(),MaxCycles:z.number().nullish()}).passthrough(),Iy=z.object({IsActive:z.boolean().nullish(),CurrentPhaseEndUtc:c.nullish(),NextBonusStartUtc:c.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentPhaseIndex:z.number().nullish(),ActiveBonusMultiplier:z.number().nullish()}).passthrough(),vy=z.object({Milestones:Q.nullish()}).passthrough(),Co=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(st).nullish(),ClaimMode:z.string().nullish(),Milestones:z.record(z.string(),Be).nullish(),Presets:vy.nullish(),BonusWindow:Py.nullish()}).passthrough(),Ty=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Content:Co.nullish(),ClaimGraceHours:z.number().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),ky=z.object({TimedEventID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:fe.nullish(),Content:Co.nullish(),Events:z.array(Ty).nullish(),Gate:Z.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Ay=z.object({MaxConcurrentEvents:z.number().nullish()}).passthrough(),zy=z.object({Milestones:z.record(z.string(),ni).nullish()}).passthrough(),ws=z.object({Definitions:z.record(z.string(),ky).nullish(),Settings:Ay.nullish(),Presets:zy.nullish()}).passthrough(),wy=z.object({Type:xi,TimedEventID:z.string(),CurrentChainedEventID:z.string().nullish(),Content:Co.nullish(),Progress:xu.nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),NextMilestone:Be.nullish(),BonusWindow:Iy.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentEventOrder:z.number().nullish(),TotalEventsInChain:z.number().nullish(),TokenEntityID:z.string().nullish()}).passthrough(),Ms=z.object({ActiveEvents:z.array(wy).nullish()}).passthrough(),bu=z.object({Tokens:z.record(z.string(),xu).nullish()}),So=z.object({Type:xi.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),xo=z.object({Type:xi.nullish(),LteID:z.string().nullish(),MilestoneID:z.string().nullish(),TokenEntityID:z.string().nullish(),Rewards:M.nullish(),Inventory:K.nullish()}),My=z.object({Type:xi.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),bo=z.array(Ie(xo)),Du=z.array(Ie(So)),Pu=z.array(Ie(My)),ot={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Iu="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: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}},Os=class{constructor(e){this.ctx=e;e.cache.bindLoginView(vu,{schema:Ms,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$1;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(Iu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Iu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return c$1;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,p=1){if(!t)return b("client","LteID is required.");if(!i)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c$1;let d={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:r,RollMultiplier:p},R=await this.ctx.api.timedEvent.grantTokens(d);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$1;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$1;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$1;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$1;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$1;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$1;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 Oy=z.object({UserID:z.string(),Score:_.nullish(),Rank:z.number().nullish(),LastScoreUpdateUtc:c.nullish(),IpHash:z.string().nullish(),PublicProfile:Oe.nullish(),SeasonTierAtCycleEnd:z.number().nullish()}).passthrough(),Pi=z.object({LeaderboardID:z.string(),CycleVersion:z.number().nullish(),TotalParticipants:_.nullish(),CycleEndUtc:c.nullish(),TopUsers:z.array(Oy).nullish(),BracketID:z.string().nullish()}),Ey=z.object({CycleKey:z.string().nullish(),CycleEndUtc:c.nullish(),ClaimDeadlineUtc:c.nullish(),MilestoneTokensEarned:_.nullish(),ClaimableMilestoneIDs:z.array(z.string()).nullish(),CycleIndex:z.number().nullish(),ChainedEventID:z.string().nullish()}).passthrough(),Es=z.object({LeaderboardID:z.string(),CurrentScore:_.nullish(),LastKnownRank:z.number().nullish(),HasUnclaimedReward:z.boolean().nullish(),UnclaimedRewardRank:z.number().nullish(),ScoreEarnedThisCycle:_.nullish(),MilestoneTokensEarned:_.nullish(),TokenEntityID:z.string().nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish(),GrantedPremiumTiers:z.record(z.string(),z.array(z.string())).nullish(),ClaimableGraceCycles:z.array(Ey).nullish()}),Us=z.object({LeaderboardID:z.string(),NewScore:_,CycleVersion:z.number()}),qs=z.object({ServerTimeUtc:c,LeaderboardID:z.string(),Rank:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Bs=z.object({ServerTimeUtc:c,LeaderboardID:z.string(),MilestoneID:z.string(),Resources:M.nullish(),Inventory:K.nullish()}),Tu=z.array(Ie(Pi)),Ls=z.array(Ie(Es)),ku=z.array(Ie(qs)),Au=z.array(Ie(Bs)),zu=z.array(Ie(Us)),Uy=z.object({LeaderboardID:z.string(),CycleReward:Ie(qs).nullish(),Milestones:z.array(Ie(Bs)).nullish()}),wu=z.array(Uy),qy=z.object({LeaderboardID:z.string(),Leaderboard:Ie(Pi).nullish(),Progress:Ie(Es).nullish()}),Mu=z.array(qy),By=z.string(),Ou=z.object({Rank:z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:Zr.nullish()}).passthrough(),Ly=z.object({RankRewards:z.array(Ou).nullish()}).passthrough(),Gy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Fy=z.object({Milestones:Q.nullish(),RankRewards:Q.nullish()}).passthrough(),Vy=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:By.nullish(),Schedule:fe.nullish(),ChainEvents:z.array(Gy).nullish(),Gate:Z.nullish(),TopUsersLimit:z.number().nullish(),MinScoreToEnterTop:z.number().nullish(),BracketSize:z.number().nullish(),LinkedSeasonChainID:z.string().nullish(),RankRewards:z.array(Ou).nullish(),Milestones:z.record(z.string(),Be).nullish(),Presets:Fy.nullish(),MilestoneClaimMode:z.string().nullish(),MilestoneClaimGraceHours:z.number().nullish(),ScoreSources:z.array(st).nullish()}).passthrough(),Ny=z.object({Milestones:z.record(z.string(),ni).nullish(),RankRewards:z.record(z.string(),Ly).nullish()}).passthrough(),Gs=z.object({Definitions:z.record(z.string(),Vy).nullish(),Presets:Ny.nullish()}).passthrough(),Ve={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 Eu="Leaderboard",Uu={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"]},Fs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Uu,{schema:Ls,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Eu,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Eu,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$1;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$1;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$1;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$1;let r={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},p=await this.ctx.api.leaderboard.submitScoreFromSource(r);if(p.ok){let d=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),d.NewScore,d.NewScore,d.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",d);}return p}async claimCycleReward(e){if(!e)return b("client","LeaderboardID is required.");if(!this.ctx.auth.context)return c$1;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$1;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$1;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$1;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(Uu,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return c$1;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$1;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$1;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$1;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$1;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$1;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 Do=z.object({}).passthrough().transform(o=>o),Vs=z.object({SeasonChainID:z.string(),CycleIndex:z.number().nullish(),Season:z.lazy(()=>Gu).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:_.nullish(),UserState:Do.nullish(),NextTier:z.lazy(()=>Lu).nullish()}).passthrough(),qu=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),AmountGranted:_.nullish(),NewStatusTokens:_.nullish(),OldTier:z.number().nullish(),NewTier:z.number(),TierUp:z.boolean().nullish()}),Po=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),TierNumber:z.number(),Resources:M.nullish(),Inventory:K.nullish()}),Bu=ft(Po);var Lu=z.object({Tier:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredTokens:_.nullish(),TierReachedReward:H.nullish()}).passthrough(),Gu=z.object({SeasonID:z.string().nullish(),Order:z.number().nullish(),DurationSec:_.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(Lu).nullish(),LinkedCollectionID:z.string().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough();var jy=z.object({SeasonChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:fe.nullish(),Seasons:z.array(Gu).nullish(),GrantTokensAccessMode:z.string().nullish(),Gate:Z.nullish()}).passthrough(),Ns=z.object({Chains:z.record(z.string(),jy).nullish()}).passthrough(),Et={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Fu="Season",Vu={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}},js=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Vu,{schema:Vs,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Fu,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Fu,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(Vu,()=>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$1;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$1;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$1;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$1;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(r=>r>0);if(i.length===0)return b("client","TierNumbers is required.");if(!this.ctx.auth.context)return c$1;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 r=n.data;for(let p of r.Items??[]){let d=p.Data?.TierNumber;p.Success&&typeof d=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,d);}this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",r);}return n}};var Nu="Premium",_s=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Nu,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$1;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(Nu,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,RelatedEntityID:`premium_purchase_${e}_${t}`},r=await this.ctx.api.premium.purchaseItemOrCurrency(n);if(r.ok){let p=r.data;p.Premium&&this.ctx.data.user.applyPremium(p.Premium),this.ctx.data.user.applyResourceOperation(p.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",p);}return r}async purchaseRealMoney(e,t,i,s,n,r,p,d){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$1;let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:r,PackageName:p,AppStoreEnvironment:d,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(R);if(V.ok){let ae=V.data;ae.Premium&&this.ctx.data.user.applyPremium(ae.Premium),this.ctx.data.user.applyResourceOperation(ae.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",ae);}return V}};var Ws=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ItemInstanceID:z.string().nullish(),Level:z.number().nullish(),EquippedAt:c.nullish()}),Io=z.object({CharacterID:z.string(),Level:z.number().nullish(),Experience:_.nullish(),Power:z.number().nullish(),StatLevels:z.record(z.string(),z.number()).nullish(),Equipment:z.record(z.string(),Ws).nullish(),UpdatedAt:c.nullish()}).passthrough(),ju=z.object({Characters:z.record(z.string(),Io).nullish()}),vo=z.object({ServerTimeUtc:c,CharacterID:z.string(),StatID:z.string(),StatLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),To=z.object({ServerTimeUtc:c,CharacterID:z.string(),NewLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),_u=z.object({ServerTimeUtc:c,CharacterID:z.string(),Equipment:z.record(z.string(),Ws).nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),Wu=z.object({ServerTimeUtc:c,CharacterID:z.string(),ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),_y=z.object({ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish()}),Qu=z.object({ServerTimeUtc:c,Characters:z.record(z.string(),_y).nullish(),Inventory:K.nullish()}),ko=z.object({ServerTimeUtc:c,CharacterID:z.string(),Power:z.number().nullish(),Resources:M.nullish()}),Ku=z.object({ServerTimeUtc:c,CharacterID:z.string(),SkinID:z.string(),Resources:M.nullish(),Inventory:K.nullish(),Equipped:z.boolean().nullish(),EquipError:z.string().nullish(),Equipment:Ws.nullish(),Power:z.number().nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish()}),Hu=z.object({ServerTimeUtc:c,CharacterID:z.string(),SkinID:z.string(),Equipped:Ws.nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),$u=z.object({ServerTimeUtc:c,CharacterID:z.string(),Cleared:z.boolean().nullish(),Power:z.number().nullish(),Inventory:K.nullish()}),Wy=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:c.nullish(),GateOpen:z.boolean().nullish(),Purchasable:z.boolean().nullish(),PriceOptions:ue.nullish()}),Qy=z.object({CharacterID:z.string(),CharacterOpen:z.boolean().nullish(),DefaultSkinID:z.string().nullish(),WornSkinID:z.string().nullish(),Skins:z.array(Wy).nullish()}),Ju=z.object({ServerTimeUtc:c,Characters:z.record(z.string(),Qy).nullish()}),Zu=ft(ko),Yu=ft(To),Xu=ft(vo),Ao=z.object({RequiredStatID:z.string(),RequiredLevel:z.number()}).passthrough(),ec=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:ue.nullish(),CostCurve:Fe.nullish(),BaseStatValue:z.number().nullish(),ValueCurve:Fe.nullish(),RankCurve:Fe.nullish(),Requirements:z.array(Ao).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Ky=z.object({SlotID:z.string(),MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Ao).nullish(),AllowedRarityIDs:z.array(z.string()).nullish(),AllowedItemTags:z.array(z.string()).nullish(),MinItemLevel:z.number().nullish(),MaxItemLevel:z.number().nullish()}).passthrough(),tc=z.object({Slots:z.record(z.string(),Ky).nullish()}).passthrough(),ic=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(),Hy=z.object({ClassID:z.string().nullish(),RarityID:z.string().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),$y=z.object({UnlockedByDefault:z.boolean().nullish(),PriceOptions:ue.nullish()}).passthrough(),Jy=z.object({Stats:Q.nullish(),Levels:Q.nullish(),Equipment:Q.nullish()}).passthrough(),sc=z.object({MaxRank:z.number().nullish(),FirstPaidRank:z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Fe.nullish()}).passthrough(),zo="@skin";function Zy(o){return !!o&&o.startsWith("@")}var Yy=z.object({CatalogID:z.string().nullish(),ItemID:z.string()}).passthrough(),Xy=z.object({PriceOptions:ue.nullish(),Schedule:fe.nullish(),Gate:Z.nullish()}).passthrough(),eR=z.object({MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Ao).nullish()}).passthrough(),tR=z.object({SkinID:z.string().nullish(),Identity:ic.nullish(),Item:Yy.nullish(),Sale:Xy.nullish(),Requirements:eR.nullish()}).passthrough(),iR=z.object({DefaultSkinID:z.string().nullish(),Definitions:z.record(z.string(),tR).nullish()}).passthrough(),sR=z.object({CharacterID:z.string(),Identity:ic.nullish(),Classification:Hy.nullish(),Unlock:$y.nullish(),Presets:Jy.nullish(),Equipment:tc.nullish(),Stats:z.record(z.string(),ec).nullish(),RankLadder:sc.nullish(),RankStatCurve:Fe.nullish(),StatMaxLevelCurve:Fe.nullish(),Skins:iR.nullish()}).passthrough(),nR=z.object({Stats:z.record(z.string(),ec).nullish()}).passthrough(),rR=z.object({RankLadder:sc.nullish()}).passthrough(),oR=z.object({Equipment:tc.nullish()}).passthrough(),aR=z.object({Stats:z.record(z.string(),nR).nullish(),Levels:z.record(z.string(),rR).nullish(),Equipment:z.record(z.string(),oR).nullish()}).passthrough(),Qs=z.object({Definitions:z.record(z.string(),sR).nullish(),Presets:aR.nullish()}).passthrough(),Ne={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"},lR="SKIN_ALREADY_OWNED";var wo="Character",Ks=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(wo)?.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(wo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(wo,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${d()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok){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$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${d()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,p=>{p.StatLevels??={},p.StatLevels[r.StatID]=r.StatLevel,r.Power!=null&&(p.Power=r.Power),p.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$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${d()}`,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok){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$1;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$1;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$1;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$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${d()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok){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$1;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$1;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$1}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,zo,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$1;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$1;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$1;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 nc="Match",Hs=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,r){let p=this.ctx.auth.context;if(!p)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:r,RelatedEntityID:`pvp_create_${p.userID}_${d()}`},R=await this.ctx.api.match.createMatch(d$1);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$1;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$1;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$1;let r={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${d()}`},p=await this.ctx.api.match.instantBattle(r);if(p.ok){let d=p.data,R=this.ctx.data.config.itemDefinitions;if(d.Resources)this.ctx.data.user.applyResourceOperation(d.Resources,R);else if(d.ResourcesDual){let V=d.ResourcesDual;V.FromUserID===n.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,R):V.ToUserID===n.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",d);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return c$1;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$1;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$1;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(nc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(nc,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var rc="Craft",$s=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(rc,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$1;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(rc,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n){if(!e)return b("client","CraftID is required.");let r=this.ctx.auth.context;if(!r)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,RelatedEntityID:`craft_${e}_${r.userID}_${d()}`},d$1=await this.ctx.api.craft.craft(p);return d$1.ok&&(this.ctx.data.user.applyResourcesWithDelta(d$1.data.Resources,d$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",d$1.data)),d$1}};var Ut=z.lazy(()=>z.union([z.string(),z.number(),z.boolean(),z.null(),z.array(Ut),z.record(z.string(),Ut)]));var qt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},oc=z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Qt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Ii(o){return o!==Qt.Pending&&o!==Qt.Running}var uR={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 cR(o){return o?/\b(AI_[A-Z_]+)\s*:/.exec(o)?.[1]??null:null}var pR=z.object({Url:z.string().nullish(),ContentType:z.string().nullish(),Variant:z.string().nullish()}),hR=z.object({Code:z.string().nullish(),Message:z.string().nullish()}),Js=z.object({GenerationID:z.string(),FeatureKey:z.string().nullish(),Modality:oc.nullish(),Status:z.string(),Progress:z.number().nullish(),OutputText:z.string().nullish(),OutputJson:z.record(z.string(),Ut).nullish(),Assets:z.array(pR).nullish(),Error:hR.nullish(),Charge:M.nullish(),PlayerRefunded:z.boolean().nullish(),Reused:z.boolean().nullish(),Reward:M.nullish(),Context:z.record(z.string(),Ut).nullish(),PaymentSettled:z.boolean().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish()}),ac=z.object({Data:z.array(Js).nullish(),Skip:z.number().nullish(),Limit:z.number().nullish()}),dR=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(),mR=z.object({Modality:oc.nullish(),Async:z.boolean().nullish(),Limits:Re.nullish(),PriceOptions:ue.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(),ArtStyle:z.string().nullish(),ThreeDFormat:z.string().nullish(),Reward:H.nullish(),PromptVariables:z.array(dR).nullish(),AllowFreePrompt:z.boolean().nullish()}).passthrough(),lc=z.object({Enabled:z.boolean().nullish(),Features:z.record(z.string(),mR).nullish()}).passthrough(),Ge={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"};var uc="AI",fR=/^[A-Za-z0-9_-]{1,128}$/,gR=2e3,yR=5e3,RR=30*6e4;function CR(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 Zs=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(uc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(uc,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))}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$1}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$1}isTerminal(e){return Ii(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;i=p.data;}else {if(!e?.GenerationID)return b("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??RR),n=Math.max(1,t.intervalMs??gR),r=Math.max(n,t.maxIntervalMs??yR);for(;!Ii(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 CR(n,t.signal),t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(i);if(n=Math.min(r,Math.round(n*1.5)),!p.ok){if(p.reason==="connection")continue;return p}i=p.data,Ii(i.Status)||t.onUpdate?.(i);}return a(i)}pollFor(e){switch(e.Modality){case qt.Text:return this.getText(e.GenerationID);case qt.Image:return this.getImage(e.GenerationID);case qt.Audio:return this.getAudio(e.GenerationID);case qt.Music:return this.getMusic(e.GenerationID);case qt.Video:return this.getVideo(e.GenerationID);case qt.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&&!fR.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$1;let r={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:n??d()},p=await s(r);return p.ok&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return b("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;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===Qt.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===Qt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Qt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Mo="Collection",Ys=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(Mo),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let n=e.cache.configSection("Season");return Object.values(n?.Chains??{}).some(p=>(p?.Seasons??[]).some(d=>!!d?.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(Mo,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Mo,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${d()}`},p=await this.ctx.api.collection.openPack(r);return p.ok&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${d()}`},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$1;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$1;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$1;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$1;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,r=false){let p=this.ctx.auth.context;if(!p)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:r,RelatedEntityID:`trade_send_${p.userID}_${s}_${d()}`},R=await this.ctx.api.collection.sendTradeOffer(d$1);return R.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",R.data)),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return c$1;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$1;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$1;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$1;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$1;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 SR=z.object({}).passthrough().transform(o=>o),xR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},bR={Active:"Active",Left:"Left",Replaced:"Replaced"},DR=z.object({ObjectIndex:z.number().nullish(),ObjectCompletionRewardClaimed:z.boolean().nullish()}).passthrough(),PR=z.object({UserID:z.string().nullish(),PublicData:Oe.nullish(),BuildObjectsProgress:DR.nullish(),IsBot:z.boolean().nullish(),SpinsCount:z.number().nullish(),TokensSpent:z.number().nullish(),MemberStatus:z.string().nullish(),GrandPrizeClaimed:z.boolean().nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),IR=z.object({Index:z.number().nullish(),OwnerUserID:z.string().nullish(),CurrentProgress:z.number().nullish(),MaxProgress:z.number().nullish(),IsCompleted:z.boolean().nullish()}).passthrough(),vR=z.object({Objects:z.array(IR).nullish()}).passthrough(),cc=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(PR).nullish(),BuildObjectsState:vR.nullish(),Status:z.string().nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:z.number().nullish()}).passthrough(),pc=z.object({CoopChainID:z.string(),CycleIndex:z.number().nullish(),EventOrder:z.number().nullish(),EventDef:z.lazy(()=>hc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:z.number().nullish()}).passthrough(),TR=z.string(),Oo=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(),kR=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(),AR=z.object({Objects:z.array(kR).nullish(),PriceOptions:ue.nullish(),SpinnerTable:z.array(Oo).nullish(),MaxSpinsPerCall:z.number().nullish()}).passthrough(),hc=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:TR.nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),BuildObjects:AR.nullish(),GrandPrize:H.nullish()}).passthrough(),zR=z.object({CoopChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:fe.nullish(),Events:z.array(hc).nullish(),Gate:Z.nullish()}).passthrough(),Xs=z.object({ServerTimeUtc:c.nullish(),UserState:SR.nullish(),ActiveGroup:cc.nullish()}),Eo=z.object({ServerTimeUtc:c.nullish(),Group:cc.nullish(),SecondsRemaining:_.nullish()}),dc=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Resources:M.nullish(),ObjectIndex:z.number().nullish(),Sector:Oo.nullish(),RequestedSpins:z.number().nullish(),SpinsUsed:z.number().nullish(),Sectors:z.array(Oo).nullish(),ProgressDelta:z.number().nullish(),NewProgress:_.nullish(),MaxProgress:_.nullish(),ObjectCompleted:z.boolean().nullish(),AllObjectsCompleted:z.boolean().nullish()}),Uo=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),mc=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),en=z.object({Chains:z.record(z.string(),zR).nullish()}).passthrough(),ht={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var fc="CoopEvent",gc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},tn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(gc,{schema:Xs,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(fc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(fc,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$1;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(gc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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){if(!e||!t)return b("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,RelatedEntityID:d()},r=await this.ctx.api.coopEvent.spin(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",r.data)),r}async claimObjectReward(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c$1;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$1;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$1;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 wR={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},MR={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},OR=z.object({NodeID:z.string().nullish(),Status:z.string().nullish(),ExecutionCount:z.number().nullish(),UnlockedAtUtc:c.nullish(),CompletedAtUtc:c.nullish(),LastExecutedAtUtc:c.nullish(),NextAvailableAtUtc:c.nullish(),LastExecutionRefID:z.string().nullish()}).passthrough(),ER=z.object({TrackID:z.string().nullish(),CurrentValue:z.number().nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),yc=z.object({OfferID:z.string().nullish(),InstanceKey:z.string().nullish(),SourceOfferVersion:z.number().nullish(),Status:z.string().nullish(),ActivatedAtUtc:c.nullish(),ExhaustedAtUtc:c.nullish(),ExpiredAtUtc:c.nullish(),DismissedAtUtc:c.nullish(),ShowCount:z.number().nullish(),LastShownAtUtc:c.nullish(),Nodes:z.record(z.string(),OR).nullish(),Tracks:z.record(z.string(),ER).nullish(),SelectedChoiceNodeID:z.string().nullish()}).passthrough(),UR=z.object({SlotID:z.string().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),ActiveOfferID:z.string().nullish(),ActiveOfferStartedAtUtc:c.nullish(),ActiveOfferExpiresAtUtc:c.nullish(),ActiveOffer:yc.nullish(),NextCycleStartsAtUtc:c.nullish(),LastUpdatedUtc:c.nullish(),DismissSkipAvailableAtUtc:c.nullish(),LastDismissedAtUtc:c.nullish(),ActiveScheduleInstanceKey:z.string().nullish()}).passthrough(),qR=z.object({TotalExecutions:z.number().nullish(),DailyExecutions:z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),BR=z.object({TotalActivations:z.number().nullish(),TotalExhausted:z.number().nullish(),TotalExpired:z.number().nullish(),TotalDismissed:z.number().nullish(),TotalShows:z.number().nullish(),LastShownAtUtc:c.nullish(),LastActivatedAtUtc:c.nullish(),LastExhaustedAtUtc:c.nullish(),NodeCounts:z.record(z.string(),qR).nullish()}).passthrough(),LR=z.object({Slots:z.record(z.string(),UR).nullish(),OfferHistory:z.record(z.string(),BR).nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),GR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},FR={Eq:"Eq",Gte:"Gte",Lte:"Lte"},VR=z.object({Order:z.number().nullish(),OfferID:z.string().nullish(),DurationSec:z.number().nullish(),DelayBeforeActivationSec:z.number().nullish()}).passthrough(),sn=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(),Rc=z.object({Schedule:fe.nullish(),Gate:Z.nullish()}).passthrough(),Cc=z.object({AllowDismissSkip:z.boolean().nullish(),DismissSkipDelaySec:z.number().nullish()}).passthrough(),NR=z.object({Identity:Q.nullish(),Availability:Q.nullish(),Behaviour:Q.nullish()}).passthrough(),jR=z.object({SlotID:z.string().nullish(),Enabled:z.boolean().nullish(),Identity:sn.nullish(),Availability:Rc.nullish(),Behaviour:Cc.nullish(),Queue:z.array(VR).nullish(),Presets:NR.nullish()}).passthrough(),_R=z.object({ViewsRequiredToComplete:z.number().nullish(),MaxViewsPerActivation:z.number().nullish(),GrantRewardsPerView:z.boolean().nullish()}).passthrough(),WR=z.object({RewardedVideo:_R.nullish()}).passthrough(),QR=z.object({TrackID:z.string().nullish(),Operator:z.string().nullish(),Value:z.number().nullish()}).passthrough(),KR=z.object({Identity:Q.nullish(),Graph:Q.nullish(),Milestones:Q.nullish()}).passthrough(),HR=z.object({Identity:Q.nullish(),Pricing:Q.nullish(),Reward:Q.nullish()}).passthrough(),$R=z.object({TrackID:z.string().nullish(),Amount:z.number().nullish(),RespectBounds:z.boolean().nullish()}).passthrough(),JR=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(),ZR=z.object({RequiredCompletedNodeIDs:z.array(z.string()).nullish(),RequiredAnyCompletedNodeIDs:z.array(z.string()).nullish(),RequiredTracks:z.array(QR).nullish(),VisibleWhileLocked:z.boolean().nullish()}).passthrough(),Sc=z.object({Options:ue.nullish()}).passthrough(),xc=z.object({Grants:H.nullish(),TrackChanges:z.array($R).nullish(),MilestonePoints:z.number().nullish()}).passthrough(),YR=z.object({NodeID:z.string().nullish(),Type:z.string().nullish(),Identity:sn.nullish(),Pricing:Sc.nullish(),Reward:xc.nullish(),Action:WR.nullish(),UnlockRules:ZR.nullish(),NextNodeIDs:z.array(z.string()).nullish(),ChoiceGroupID:z.string().nullish(),Limits:Re.nullish(),HideWhenCompleted:z.boolean().nullish(),ExhaustOfferOnComplete:z.boolean().nullish(),Presets:HR.nullish()}).passthrough(),bc=z.object({RootNodeIDs:z.array(z.string()).nullish(),Nodes:z.array(YR).nullish(),Tracks:z.array(JR).nullish(),ExhaustedWhenAllTerminalNodesCompleted:z.boolean().nullish()}).passthrough(),Dc=z.object({Milestones:z.record(z.string(),Be).nullish(),ClaimMode:z.string().nullish(),Token:_t.nullish()}).passthrough(),Pc=z.object({OfferID:z.string().nullish(),Version:z.number().nullish(),Enabled:z.boolean().nullish(),Identity:sn.nullish(),Graph:bc.nullish(),Milestones:Dc.nullish(),Presets:KR.nullish()}).passthrough(),XR=z.object({Identity:z.record(z.string(),sn).nullish(),Availability:z.record(z.string(),Rc).nullish(),Behaviour:z.record(z.string(),Cc).nullish(),Graph:z.record(z.string(),bc).nullish(),Milestones:z.record(z.string(),Dc).nullish(),Pricing:z.record(z.string(),Sc).nullish(),Reward:z.record(z.string(),xc).nullish()}).passthrough(),qo=z.object({Slots:z.record(z.string(),jR).nullish(),Offers:z.record(z.string(),Pc).nullish(),Presets:XR.nullish()}).passthrough(),Ic=z.object({DealOfferDefinitions:qo.nullish()}),vc=z.object({DealOffers:LR.nullish()}),eC=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:Pc.nullish(),ActivationState:yc.nullish(),IsNewActivation:z.boolean().nullish(),ComputedExpiresAtUtc:c.nullish(),Cost:xt.nullish(),Milestone:eC.nullish(),ScheduleInstanceKey:z.string().nullish()}).passthrough(),nn=z.object({Slots:z.array(tC).nullish()}),Tc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),NodeID:z.string().nullish(),NodeCompleted:z.boolean().nullish(),OfferExhausted:z.boolean().nullish(),Idempotent:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),kc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),Ac=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),zc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),wc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),ClaimedIDs:z.array(z.string()).nullish(),Rejected:z.record(z.string(),z.string()).nullish(),Resources:M.nullish(),Inventory:K.nullish()}),yt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var iC="DealOffer",Mc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},rn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Mc,{schema:nn,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(iC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;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(Mc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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,RelatedEntityID:n??`deal_exec_${e}_${t}_${d()}`},p=await this.ctx.api.dealOffer.executeNode(r);return p.ok&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;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$1;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$1;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}_${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 Oc="Referral",on=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Oc,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$1;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Oc,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=jt.parseReferralCode(e)?.toUpperCase();if(!t)return b("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return c$1;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$1;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$1;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 p of r.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.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$1;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 sC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Ec=z.enum(["System","Reward","Gift","Social"]).catch("System"),nC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},rC=z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),oC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},aC=z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),et={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},lC={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,cC=z.object({Subject:z.string().nullish(),Body:z.string().nullish()}).passthrough(),Uc=z.object({FeatureID:z.string().nullish(),Args:z.record(z.string(),z.string()).nullish(),Url:z.string().nullish(),Label:z.string().nullish()}).passthrough(),pC=z.object({Texts:z.record(z.string(),cC).nullish(),Category:Ec.nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:Uc.nullish(),SenderName:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),hC=z.object({Enabled:z.boolean().nullish(),Grant:ce.nullish(),Cost:ce.nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:c.nullish(),SenderGate:Z.nullish(),TemplateID:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),dC=z.object({Type:z.string().nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxAmountPerGift:z.number().nullish()}).passthrough(),mC=z.object({Enabled:z.boolean().nullish(),AllowedResources:z.array(dC).nullish(),MaxEntriesPerGift:z.number().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:c.nullish(),FeePercent:z.number().nullish(),FeeCost:ce.nullish(),SenderGate:Z.nullish(),ExpirationDays:z.number().nullish(),TemplateID:z.string().nullish()}).passthrough(),qc=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(),pC).nullish(),Gifts:z.object({Social:z.record(z.string(),hC).nullish(),Transfer:mC.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(),fC=z.object({MessageID:z.string(),Source:rC,Category:Ec,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:Uc.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:c,ExpiresAt:c.nullish(),ReadAt:c.nullish(),ClaimedAt:c.nullish()}).passthrough(),gC=z.object({MessageID:z.string(),Module:aC,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(),Bo=z.object({ID:z.string(),Error:z.string().nullish()}).passthrough(),Bc=z.object({ServerTimeUtc:c.nullish(),Messages:z.array(fC).default([]),NextCursor:z.string().nullish(),PendingRewards:z.array(gC).nullish(),UnreadCount:z.number().nullish(),UnclaimedCount:z.number().nullish(),DeliveredNow:z.number().nullish()}).passthrough(),an=z.object({ServerTimeUtc:c.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Lo=z.object({ServerTimeUtc:c.nullish(),AffectedCount:z.number().default(0),Failed:z.array(Bo).default([]),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),yC=z.object({MessageID:z.string(),Rewards:ce.nullish()}).passthrough(),ln=z.object({ServerTimeUtc:c.nullish(),Claimed:z.array(yC).default([]),Failed:z.array(Bo).default([]),Resources:M.nullish(),Inventory:K.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Lc=z.object({ServerTimeUtc:c.nullish(),GiftID:z.string().nullish(),Sent:z.array(z.string()).default([]),Failed:z.array(Bo).default([]),Resources:M.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish()}).passthrough(),Gc=z.object({ServerTimeUtc:c.nullish(),MessageID:z.string().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),RecipientReceives:ce.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish(),IdempotentReplay:z.boolean().nullish()}).passthrough(),Fc=z.object({ServerTimeUtc:c.nullish(),ResetsAt:c.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:c.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:c.nullish()}).passthrough().nullish()}).passthrough();var Go="Mailbox",Fo={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},un=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Fo,{schema:an,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(Fo,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Go)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Go,e);if(t)return a(t);let i=this.request();if(!i)return c$1;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(Go,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$1;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(Fo,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return c$1;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$1;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$1}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$1}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):c$1}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$1;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$1;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$1;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$1}};var RC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},CC={Title:"Title",Platform:"Platform"},Vc=z.object({UserID:z.string(),PublicData:Oe.nullish(),Source:z.enum(["Title","Platform"]).nullish()}),vi=z.object({Friends:z.array(Vc).nullish()}),SC=z.object({FriendsCount:z.number().nullish(),IncomingRequestsCount:z.number().nullish(),OutgoingRequestsCount:z.number().nullish()}),Ti=z.object({TargetUserID:z.string().nullish(),Status:z.string().nullish(),Target:Vc.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"},PC={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},IC={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:c.nullish(),UpdatedAt:c.nullish(),OccurredAt:c.nullish(),OwnerImpact:M.nullish(),IsBlocked:z.boolean().nullish(),TargetObjectName:z.string().nullish()}).passthrough(),Nc=z.object({Items:z.array(TC).nullish(),HasMore:z.boolean().nullish(),NextBeforeUpdatedAt:z.string().nullish(),NextBeforeID:z.string().nullish(),UnreadCount:z.number().nullish(),SeenAt:c.nullish()}).passthrough(),ki=z.object({UnreadCount:z.number().nullish(),SeenAt:c.nullish()}).passthrough(),kC=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(),Bt=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Counts:kC.nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish(),Following:z.boolean().nullish(),Blocked:z.boolean().nullish()}).passthrough(),jc=z.object({Items:z.array(Bt).nullish()}).passthrough(),Vo={HasMore:z.boolean().nullish(),NextCursorAt:z.string().nullish(),NextCursorID:z.string().nullish()},AC=z.object({UserID:z.string(),PublicData:Oe.nullish(),Mutual:z.boolean().nullish(),Since:c.nullish()}).passthrough(),cn=z.object({Items:z.array(AC).nullish(),...Vo}).passthrough(),zC=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Kind:z.string().nullish(),At:c.nullish()}).passthrough(),_c=z.object({Items:z.array(zC).nullish(),...Vo}).passthrough(),pn=z.object({CommentID:z.string(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),ParentCommentID:z.string().nullish(),AuthorUserID:z.string().nullish(),AuthorPublicData:Oe.nullish(),Text:z.string().nullish(),Status:z.string().nullish(),Pinned:z.boolean().nullish(),CreatedAt:c.nullish(),EditedAt:c.nullish(),Likes:z.number().nullish(),Replies:z.number().nullish(),Liked:z.boolean().nullish(),IsMine:z.boolean().nullish()}).passthrough(),Wc=z.object({Items:z.array(pn).nullish(),...Vo,TotalCount:z.number().nullish()}).passthrough(),Qc=z.object({CommentID:z.string().nullish(),Deleted:z.boolean().nullish()}).passthrough(),Kc=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish(),AutoHidden:z.boolean().nullish()}).passthrough(),Hc=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"},$c=z.object({Profile:z.enum(["Off","Default","Always"]).nullish(),Friends:z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:z.boolean().nullish()}).passthrough(),Ce={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 No={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},hn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(No,{schema:ki,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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(No,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(No,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$1}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$1}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$1;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$1;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$1}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$1}};var Jc="TimedBoost";function EC(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var dn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Jc,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Jc,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${d()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok){let r=n.data;if(r.ActivatedBoost){let p=r.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(r.ActivatedBoost,p);}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$1;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 Tt={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:c.nullish(),Version:z.number().nullish(),LastWriter:qC.nullish(),ExpiresAt:c.nullish()}).passthrough(),mn=z.record(z.string(),BC),Zc=z.object({Version:z.number().nullish(),Private:mn.nullish(),Public:mn.nullish(),ReadOnly:mn.nullish()}),jo=z.object({UserID:z.string().nullish(),Version:z.number().nullish(),Public:mn.nullish()}),_o=z.object({ServerTimeUtc:c.nullish(),Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:c.nullish()}),LC=z.object({Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:c.nullish()}),Yc=z.object({ServerTimeUtc:c.nullish(),Results:z.array(LC).nullish()}),Xc=z.object({ServerTimeUtc:c.nullish(),DeletedCount:z.number().nullish()}),ep=z.object({Results:z.array(jo).nullish(),NotFoundUserIDs:z.array(z.string()).nullish()}),GC={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},FC=z.enum(["String","Int","Bool","Json"]).catch("String"),VC=z.object({KeyID:z.string(),Bucket:z.string().nullish(),ValueType:FC.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),fn=z.object({Keys:z.record(z.string(),VC).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),dt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var NC="UserCustomData";function tp(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var gn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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,Tt.Private)}async setPublicData(e,t){return this.setData(e,t,Tt.Public)}async setData(e,t,i){let s=e.trim();if(!tp(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$1;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(i===Tt.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(p.ok){let d=p.data;this.ctx.data.user.patchUserCustomDataKey(i,d.KeyID,t,d.Version??0,d.ExpiresAt),this.ctx.emitter.emit(i===Tt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",d);}return p}async deleteKey(e,t){let i=e.trim();if(!tp(i))return b("client",'KeyID is required and must not contain "." or "$".');if(t!==Tt.Private&&t!==Tt.Public)return b("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return c$1;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$1;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??Tt.Private,r=e.find(p=>p.Bucket===n&&p.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$1;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$1;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",ip=50;function _C(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}function Wo(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))Wo(i)||(e[t]=i);return e}var yn=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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>ip)return b("client",`At most ${ip} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return c$1;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&&!Wo(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Wo(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 Rn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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$1;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var QC=15,KC="GameLoop",sp="BoardDefinition",Cn=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$1;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(KC,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(sp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),a(i);let s=this.ctx.authedRequest();if(!s)return c$1;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(sp,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$1;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$1;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$1;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,r=ql(new Date,QC);this.ctx.data.user.patchBoardState(p=>{p.Position=n.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(n.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),n.ActionRequired&&n.ActionData?p.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&&(p.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$1;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$1;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 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$1;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$1;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(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){if(!e)return b("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${d()}`},n=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(n.ok){let r=n.data;r.Mode==="Instant"||r.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(d=>{d.ChoiceID=e,d.ChosenMode=r.Mode??"Timed",d.StartedAtUtc=r.StartedAtUtc??null,d.DurationSeconds=r.DurationSeconds??null,d.AdViewsUsed=0;}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",r);}return n}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return c$1;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(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$1;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$1;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$1;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$1;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$1;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$1;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 Sn=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$1;let r={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(r);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var np=z.object({ServerTimeUtc:c,SourceType:ii,SourceID:z.string(),TargetType:ii,TargetID:z.string(),SourceSpent:_,FeeAmount:_,RateApplied:Y,TargetCredited:_}),rp=z.object({ServerTimeUtc:c,SourceType:ii,SourceID:z.string(),TargetType:ii,TargetID:z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),xn={Convert:"Convert",CryptoConvert:"CryptoConvert"},HC={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},op=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:c.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:ii.nullish(),TargetCurrencyID:z.string(),Rate:Y.nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish(),DailyLimit:z.number().nullish()}).passthrough(),ap=z.object({Enabled:z.boolean().nullish(),RateMode:JC.nullish(),Fee:z.number().nullish(),Targets:z.array(eS).nullish()}).passthrough(),lp=z.object({CreatedAt:c.nullish(),UpdatedAt:c.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:ap.nullish(),Permissions:XC.nullish(),Audit:lp.nullish(),Status:op.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(),Qo=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:c.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:ap.nullish(),Audit:lp.nullish(),Status:op.nullish(),ServerGrantPolicy:rS.nullish(),UnbackedRewardCurrencyID:z.string().nullish()}).passthrough(),bn=z.object({VirtualCurrencies:z.record(z.string(),tS).nullish(),CryptoCurrencies:z.record(z.string(),Qo).nullish()}).passthrough();var oS={EVM:"EVM",Solana:"Solana"},aS=z.enum(["EVM","Solana"]).catch("EVM"),lS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},uS=z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),cS={Token:"Token",Nft:"Nft"},up=z.enum(["Token","Nft"]).catch("Token"),pS={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},hS=z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),dS={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},mS=z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),fS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Ko=z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),cp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Dn(o){let e=o?.trim();return e||cp.GameTopUp}var gS={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},pp=z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),yS=z.object({ContractAddress:z.string().nullish(),ItemCatalogID:z.string().nullish(),DisplayName:z.string().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),hp=z.object({Ios:z.boolean().nullish(),Android:z.boolean().nullish(),Web:z.boolean().nullish()}).passthrough(),RS=z.object({NetworkID:z.string().nullish(),DisplayName:z.string().nullish(),Type:aS.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:hp.nullish(),NftCollections:z.array(yS).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(),CS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:hp.nullish()}).passthrough(),SS=z.object({MinAccountAgeDays:z.number().nullish(),MultiAccountCheckEnabled:z.boolean().nullish(),BanOnSharedWithdrawalAddress:z.boolean().nullish(),PendingWithdrawalTtlHours:z.number().nullish()}).passthrough(),xS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},bS=z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),dp=z.object({Enabled:z.boolean().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:bS.nullish(),DenyMessage:z.string().nullish()}).passthrough(),DS=z.object({Enabled:z.boolean().nullish(),WalletConnectProjectId:z.string().nullish(),ShowOnLoginScreen:z.boolean().nullish()}).passthrough(),PS={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Ai=z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),IS=z.object({Mode:Ai.nullish(),TokenGates:z.array(dp).nullish()}).passthrough(),Ho=z.object({SystemState:CS.nullish(),Networks:z.record(z.string(),RS).nullish(),AccountSafety:SS.nullish(),WalletLogin:DS.nullish(),PlayAccess:IS.nullish(),IframeConnectHosts:z.array(z.string()).nullish()}).passthrough(),vS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),LinkedAt:c.nullish(),LastUsedAt:c.nullish(),LinkType:uS.nullish(),IsSignatureVerified:z.boolean().nullish()}).passthrough(),mp=z.object({TitleTransactionID:z.string().nullish(),Type:up.nullish(),NetworkID:z.string().nullish(),AssetID:z.string().nullish(),Amount:Y.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),TS=z.object({Status:hS.nullish(),Tier:mS.nullish(),VerifiedAt:c.nullish(),ExpiresAt:c.nullish(),RejectedAt:c.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:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),AS=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(),zS=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:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),wS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),PerCollection:z.record(z.string(),zS).nullish()}).passthrough(),MS=z.object({Tokens:AS.nullish(),Nfts:wS.nullish()}).passthrough(),$o=z.object({CurrencyID:z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Lt=z.object({Granted:z.boolean(),Mode:Ai.nullish(),Error:z.string().nullish(),WalletRequired:z.boolean().nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),GrantedUntil:c.nullish(),Balances:z.array($o).nullish()}).passthrough(),OS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:c.nullish(),Passed:z.boolean().nullish(),GrantedUntil:c.nullish(),Error:z.string().nullish(),Balances:z.array($o).nullish()}).passthrough(),ES=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CanUnlink:z.boolean().nullish()}).passthrough(),fp=z.object({Mode:Ai.nullish(),TokenGates:z.array(dp).nullish(),WalletLoginEnabled:z.boolean().nullish(),CanLinkWallet:z.boolean().nullish(),WalletsFromPlatformProfile:z.boolean().nullish(),LinkedWallets:z.array(ES).nullish(),Status:Lt.nullish()}).passthrough(),US=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:c.nullish(),LoggedInAt:c.nullish(),GatePassed:z.boolean().nullish(),GatedBalances:z.array($o).nullish()}).passthrough(),qS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),UnlinkedAt:c.nullish()}).passthrough(),BS=z.object({Version:z.number().nullish(),Stats:MS.nullish(),LinkedWallets:z.record(z.string(),vS).nullish(),LastWalletLogin:US.nullish(),PlayAccess:OS.nullish(),PendingWithdrawals:z.array(mp).nullish(),Kyc:TS.nullish(),FirstActivityAt:c.nullish(),LastActivityAt:c.nullish(),IsFlagged:z.boolean().nullish(),FlagReason:z.string().nullish(),UnlinkedWallets:z.array(qS).nullish()}).passthrough(),LS=z.object({CurrencyID:z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:c}).passthrough(),hi=z.object({CryptoBalances:z.record(z.string(),LS).nullish(),PendingAdded:mp.nullish(),PendingRemovedIDs:z.array(z.string()).nullish()}).passthrough(),GS=z.object({Amount:Y,Frozen:Y,CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough().transform(o=>o),FS=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.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:pp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:Ko.nullish(),SignatureData:z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.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:c.nullish(),BurnAmount:z.number().nullish(),RefundedAt:c.nullish(),RefundCheckedAt:c.nullish()}).passthrough(),VS=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.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:pp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:Ko.nullish(),SignatureData:z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.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:c.nullish()}).passthrough(),gp=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),Jo=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(gp).nullish(),Signature:z.string().nullish()}).passthrough(),Zo=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(gp).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(),yp=z.object({Blockchain:Ho.nullish(),CryptoCurrencies:z.record(z.string(),Qo).nullish()}).passthrough(),Rp=z.object({State:BS.nullish(),CryptoBalances:z.record(z.string(),GS).nullish()}).passthrough(),Cp=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:hi.nullish()}).passthrough(),Sp=z.object({ServerTimeUtc:c.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:M.nullish(),Inventory:K.nullish()}).passthrough(),xp=z.object({ServerTimeUtc:c.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:c.nullish(),EvmSignature:Jo.nullish(),SolanaSignature:Zo.nullish(),StateDelta:hi.nullish(),ChainID:z.number().nullish()}).passthrough(),bp=z.object({ServerTimeUtc:c.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:c.nullish(),Resources:M.nullish(),EvmSignature:Jo.nullish(),SolanaSignature:Zo.nullish(),StateDelta:hi.nullish(),Inventory:K.nullish()}).passthrough(),Dp=z.object({TokenTransactions:z.array(FS).nullish(),NFTTransactions:z.array(VS).nullish(),RefundedIDs:z.array(z.string()).nullish()}).passthrough(),Yo=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:z.string().nullish()}).passthrough(),Pp=z.object({TitleTransactionID:z.string().nullish(),Kind:up.nullish(),EvmSignature:Jo.nullish(),SolanaSignature:Zo.nullish()}).passthrough(),Ip=z.object({TitleTransactionID:z.string().nullish(),OnChainTxHash:z.string().nullish(),Status:Ko.nullish(),StateDelta:hi.nullish()}).passthrough(),Ke={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 NS="Blockchain",vp="Blockchain:Definitions",Pn=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(vp,e);if(t)return a(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return c$1;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(NS,n.data.Blockchain),this.ctx.data.config.patchSection(vp,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$1;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$1;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$1;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$1;r.CurrencyID=e,r.NetworkID=t,r.WalletAddress=i,r.Amount=s,r.Category=Dn(n);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(r);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,i,s,n,r,p){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 d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.NetworkID=t,d.WalletAddress=i,d.Amount=s,d.Category=Dn(n),r!==void 0&&(d.Level=r),p&&(d.ItemInstanceID=p);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(d);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$1;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$1;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$1;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$1;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$1;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$1;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$1;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var jS={Head:"Head",Torso:"Torso",Legs:"Legs"},In=z.enum(["Head","Torso","Legs"]).catch("Head"),_S={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},Xo=z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),kp=z.object({AttackTarget:In,DefenseTarget:In});var WS=z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),QS=z.object({RoundIndex:z.number().nullish(),AttackerID:z.string().nullish(),DefenderID:z.string().nullish(),AttackZone:In.nullish(),DefenseZone:In.nullish(),HitType:WS.nullish(),DamageDealt:z.number().nullish(),DefenderHpRemaining:z.number().nullish()}).passthrough(),KS=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(),HS=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:c,ExpiresAt:c.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Tp=z.object({UserID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),SelectedCharacter:Io.nullish(),BattleStrategy:z.array(kp).nullish(),UnstackableItems:z.record(z.string(),HS).nullish(),Stats:KS.nullish()}).passthrough(),$S=z.object({WinnerUserID:z.string().nullish(),LoserUserID:z.string().nullish(),Entry:ce.nullish(),NetReward:ce.nullish(),BattleLog:z.array(QS).nullish(),IsDraw:z.boolean().nullish(),P1BattleProfile:Tp.nullish(),P2BattleProfile:Tp.nullish()}).passthrough(),Ap=z.object({MatchID:z.string(),TitleID:z.string().nullish(),RuleID:z.string().nullish(),CreatedAt:c.nullish(),CreatorID:z.string().nullish(),CreatorCharacterID:z.string().nullish(),CreatorStrategy:z.array(kp).nullish(),TargetUserID:z.string().nullish(),Entry:ce.nullish(),CreationCostPaid:ce.nullish(),RefundCreationCostOnCancel:z.boolean().nullish(),ExpiresAt:c.nullish(),JoinedByUserID:z.string().nullish(),JoinedByCharacterID:z.string().nullish(),JoinedAt:c.nullish(),Status:Xo.nullish(),WinnerUserID:z.string().nullish(),CompletedAt:c.nullish(),IsRewardDistributed:z.boolean().nullish(),RewardDistributedAt:c.nullish()}).passthrough(),zp=z.object({Status:Xo,MatchID:z.string(),Entry:ce.nullish(),Resources:M.nullish()}),wp=z.object({Match:Ap.nullish()}),Mp=z.object({MatchID:z.string(),Status:Xo,Resources:M.nullish()}),Op=z.object({Battle:$S.nullish(),Resources:M.nullish(),ResourcesDual:bt.nullish()}),ea=z.object({Matches:z.array(Ap).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}),Rt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var JS=z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var ZS=z.enum(["Constant","Variable","Curve"]).catch("Constant"),YS=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(),XS=z.enum(["Flat","PercentReduction"]).catch("Flat"),ex=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:XS.nullish(),MaxArmorReduction:z.number().nullish()}).passthrough(),tx=z.object({Kind:ZS.nullish(),Constant:z.number().nullish(),VariableID:z.string().nullish(),Argument:z.string().nullish(),Curve:Fe.nullish(),OnePlus:z.boolean().nullish()}).passthrough(),ix=z.object({Coefficient:z.number().nullish(),Factors:z.array(tx).nullish()}).passthrough(),Kt=z.object({Terms:z.array(ix).nullish()}).passthrough(),sx=z.object({Health:Kt.nullish(),Damage:Kt.nullish(),Armor:Kt.nullish(),AttackSpeed:Kt.nullish(),CritChance:Kt.nullish(),CritDamage:Kt.nullish(),Dodge:Kt.nullish()}).passthrough(),Ep=z.object({StatMapping:YS.nullish(),Combat:ex.nullish(),Formula:sx.nullish()}).passthrough(),nx=z.object({BurnRate:z.number().nullish()}).passthrough(),zi=z.object({Kind:JS.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),TokenType:Vi.nullish(),EntityID:z.string().nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish()}).passthrough(),Up=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(zi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),qp=z.object({PriceOptions:ue.nullish(),RefundCostOnCancel:z.boolean().nullish(),MaxOpenMatches:z.number().nullish(),OfferLifetimeSeconds:z.number().nullish(),Limits:Re.nullish(),AllowPrivateMatches:z.boolean().nullish(),MaxMatchesPerOpponentPerDay:z.number().nullish()}).passthrough(),rx=z.object({RuleID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Economy:nx.nullish(),Entry:Up.nullish(),Creation:qp.nullish(),Settings:Ep.nullish()}).passthrough(),ox=z.object({Rules:z.record(z.string(),rx).nullish(),Defaults:Ep.nullish(),EntryDefaults:Up.nullish(),CreationDefaults:qp.nullish()}).passthrough(),ta=z.object({InstantBattle:ox.nullish()}).passthrough(),Bp=ta;var ax={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},ia=z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),lx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},sa=z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),ux={Burn:"Burn",Ledger:"Ledger"},cx=z.enum(["Burn","Ledger"]).catch("Burn"),Tn={Item:"Item",VirtualCurrency:"VirtualCurrency"},na=z.enum(["Item","VirtualCurrency"]).catch("Item"),px=z.object({Percent:z.number().nullish(),MinPerPosition:_.nullish()}).passthrough(),kn=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(zi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),ra=z.object({Percent:z.number().nullish(),MinPerPosition:_.nullish(),Sink:cx.nullish(),LedgerAccountID:z.string().nullish(),PerCatalogOverrides:z.record(z.string(),px).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(),dx=z.object({Enabled:z.boolean().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),MaxActiveListings:z.number().nullish(),CreateLimits:Re.nullish(),BuyLimits:Re.nullish(),ListingFeeOptions:ue.nullish(),RefundListingFeeOnCancel:z.boolean().nullish()}).passthrough(),mx=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:_.nullish(),BidLimits:Re.nullish()}).passthrough(),fx=z.object({Enabled:z.boolean().nullish(),MaxActiveOrders:z.number().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),CreateLimits:Re.nullish(),FillLimits:Re.nullish()}).passthrough(),gx=z.object({Enabled:z.boolean().nullish(),OfferExpirationHours:z.number().nullish(),MaxPendingOutgoing:z.number().nullish(),AllowGifts:z.boolean().nullish(),CreateLimits:Re.nullish()}).passthrough(),yx=z.object({Enabled:z.boolean().nullish()}).passthrough(),oa=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:fe.nullish(),PricePolicy:kn.nullish(),Commission:ra.nullish(),Tradability:hx.nullish(),Listings:dx.nullish(),Auctions:mx.nullish(),BuyOrders:fx.nullish(),DirectTrades:gx.nullish(),Matching:yx.nullish()}).passthrough(),Lp=z.object({BidIndex:z.number().nullish(),UserID:z.string().nullish(),Amount:_.nullish(),Settled:z.boolean().nullish(),SettledAt:c.nullish()}).passthrough(),Rx=z.object({BidAxisType:si.nullish(),BidCurrencyID:z.string().nullish(),BidCatalogID:z.string().nullish(),BidItemID:z.string().nullish(),StartingBid:_.nullish(),CurrentBid:_.nullish(),CurrentBidderID:z.string().nullish(),BidCount:z.number().nullish(),ExtensionCount:z.number().nullish(),PendingRefunds:z.array(Lp).nullish()}).passthrough(),vn=z.object({LastAt:c.nullish(),DailyCount:z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),Cx=z.object({Create:vn.nullish(),Buy:vn.nullish(),Sell:vn.nullish(),Bid:vn.nullish()}).passthrough(),Sx=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),xx=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:c,ExpiresAt:c.nullish(),EquippedSlot:Sx.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),kt=z.object({OfferID:z.string().nullish(),OfferType:ia.nullish(),Status:sa.nullish(),CreatorUserID:z.string().nullish(),CreatorPublicData:Oe.nullish(),TargetUserID:z.string().nullish(),GoodsType:na.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:_.nullish(),GoodsInstances:z.array(xx).nullish(),Price:ce.nullish(),Auction:Rx.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),bx=z.object({GoodsType:na.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),CountsByType:z.partialRecord(ia,_).nullish()}).passthrough(),Gp=z.object({Definitions:oa.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish()}).passthrough(),aa=z.object({Offers:z.array(kt).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Fp=z.object({Groups:z.array(bx).nullish()}).passthrough(),Vp=z.object({Offer:kt.nullish()}).passthrough(),at=z.object({OfferID:z.string().nullish(),Status:sa.nullish(),Settlement:bt.nullish(),Resources:M.nullish(),CommissionTaken:ce.nullish()}).passthrough(),wi=z.object({OfferID:z.string().nullish(),Offer:kt.nullish(),Resources:M.nullish(),Matched:z.boolean().nullish(),Settlement:at.nullish()}).passthrough(),Np=z.object({OfferID:z.string().nullish(),CurrentBid:_.nullish(),BidCount:z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish()}).passthrough(),An=z.object({MyOffers:z.array(kt).nullish(),MyBids:z.array(kt).nullish(),MyBuyOrders:z.array(kt).nullish(),IncomingTrades:z.array(kt).nullish(),OutgoingTrades:z.array(kt).nullish(),Claimables:z.array(kt).nullish(),DrainedRefunds:z.array(Lp).nullish(),Limits:Cx.nullish()}).passthrough(),Dx=z.object({OfferID:z.string().nullish(),OfferType:ia.nullish(),FinalStatus:sa.nullish(),SellerUserID:z.string().nullish(),BuyerUserID:z.string().nullish(),GoodsType:na.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:_.nullish(),PricePaid:ce.nullish(),CommissionTaken:ce.nullish(),CompletedAt:c.nullish(),MyRole:z.string().nullish()}).passthrough(),jp=z.object({Entries:z.array(Dx).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Ae={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",_p={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"]},zn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(_p,{schema:An,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1;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$1;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$1;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$1;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(_p,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return c$1;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$1;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,p){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 d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.PriceBundle=s,d.DurationHours=n,d.ItemInstanceIDs=r,d.SelectedOptionID=p;let R=await this.ctx.api.marketplace.createListing(d);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$1;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$1;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$1;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,p={}){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.BidAxisType=s,d.BidCurrencyID=p.bidCurrencyID,d.BidCatalogID=p.bidCatalogID,d.BidItemID=p.bidItemID,d.StartingBid=n,d.DurationHours=r,d.ItemInstanceIDs=p.itemInstanceIDs,d.SelectedOptionID=p.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(d);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$1;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$1;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$1;r.ItemID=e,r.CatalogID=t,r.GoodsAmount=i,r.PriceBundle=s,r.DurationHours=n;let p=await this.ctx.api.marketplace.createBuyOrder(r);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;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$1;r.TargetUserID=e,r.CatalogID=t,r.ItemID=i,r.ItemInstanceIDs=s,r.RequestedBundle=n;let p=await this.ctx.api.marketplace.createDirectTrade(r);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return b("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;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$1;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$1;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=Tn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Tn.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 wn=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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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$1;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 Wp=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Mn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;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$1}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$1}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$1}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((d,R)=>{if("sourceAssetUrl"in d)return {Role:d.role,ContentType:d.contentType,SourceAssetUrl:d.sourceAssetUrl};let V=Qp(d.data,d.contentType);return t.set(R,V),{Role:d.role,ContentType:d.contentType,Size:V.size}}),s=e.thumbnail?Qp(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 d=0;d<r.length;d++){let R=r[d];if(!R||R.ServerCopy||!R.Url)continue;let V=t.get(d);if(!V)return b("client",`No bytes for file #${d+1}.`);let ae=await this.putBytes(R.Url,V,R.ContentType??V.type);if(!ae.ok)return ae}let p=n.data.ThumbnailUpload;if(p?.Url&&s){let d=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!d.ok)return d}return this.publishUploaded({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})}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):c$1}async publishUploaded(e){if(!e.ContentID)return b("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&(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$1}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)}${Wp}`)}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$1}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):c$1}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)}${Wp}`)}}contentRequest(e){if(!e)return b("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):c$1}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 Qp(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 Ix={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},vx=z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),Tx={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Kp=z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),kx={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Hp=z.enum(["Everyone","Owner","Server"]).catch("Everyone"),Ax={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},zx=z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),wx={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},Mx=z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),Ox={Count:"Count",Sum:"Sum"},Ex=z.enum(["Count","Sum"]).catch("Count"),Ux={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},qx=z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),Bx={Strict:"Strict",Loose:"Loose"},Lx=z.enum(["Strict","Loose"]).catch("Strict"),Gx=z.object({Kind:Mx,Collection:z.string().nullish(),Validate:z.boolean().nullish()}),Fx=z.object({Type:Kp,ItemType:Kp.nullish(),Ref:Gx.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:Hp.optional(),ClientWritable:z.boolean().nullish(),Immutable:z.boolean().optional(),Description:z.string().nullish(),AllowedMimeTypes:z.array(z.string()).nullish(),MaxFileBytes:z.number().nullish()}),Vx=z.object({ID:z.string(),Components:z.array(z.object({Field:z.string(),Descending:z.boolean().optional()})).default([])}),On=z.object({Mode:zx,Role:z.string().nullish(),MembersField:z.string().nullish()}),Nx=z.object({Read:z.array(On).nullish(),Create:z.array(On).nullish(),Update:z.array(On).nullish(),Delete:z.array(On).nullish()}),la=z.object({Cost:ce.nullish(),Grant:ce.nullish()}),jx=z.object({ID:z.string(),SortKey:z.string(),PartitionField:z.string().nullish(),PageSize:z.number().optional(),MaxItems:z.number().optional(),PublishItems:z.boolean().optional()}),_x=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:vx,Mode:Lx.optional(),SchemaVersion:z.number().optional(),Fields:z.record(z.string(),Fx).nullish(),SortKeys:z.array(Vx).nullish(),Access:Nx.nullish(),Limits:z.object({MaxItemBytes:z.number().nullish(),MaxItemsPerOwner:z.number().nullish(),TtlSeconds:z.number().nullish()}).nullish(),OnOwnerDeleted:qx.optional(),Counters:z.array(z.object({ID:z.string(),Kind:Ex,SumField:z.string().nullish(),GroupBy:z.string().nullish(),Visibility:Hp.optional()})).nullish(),Economy:z.object({OnCreate:la.nullish(),OnUpdate:la.nullish(),OnDelete:la.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:z.array(jx).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()}),$p=z.object({Enabled:z.boolean().optional(),Collections:z.record(z.string(),_x).default({})}),Wx=z.object({FileID:z.string(),Url:z.string(),ContentType:z.string().nullish(),Size:z.number()}),Jp=z.object({FileID:z.string(),UploadUrl:z.string(),ContentType:z.string(),MaxBytes:z.number(),ExpiresAt:z.string()}),di=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(),Wx).nullish()}),ua=z.object({Item:di}),Zp=z.object({Items:z.array(di).default([]),Missing:z.array(z.string()).default([])}),ca=z.object({Items:z.array(di).default([]),NextCursor:z.string().nullish()}),Yp=z.object({Count:z.number(),Capped:z.boolean().optional()}),pa=z.object({Item:di,AlreadyExists:z.boolean().optional(),Economy:M.nullish()}),Xp=z.object({ItemID:z.string(),Deleted:z.boolean(),Economy:M.nullish()}),eh=z.object({CounterID:z.string(),Group:z.unknown().optional(),Value:z.number()}),th=z.object({Results:z.array(z.object({Op:z.string(),Collection:z.string(),ItemID:z.string(),Item:di.nullish(),Deleted:z.boolean().optional()})).default([])}),ih=z.object({Roles:z.array(z.string()).default([])}),sh=z.object({Views:z.record(z.string(),z.string()).default({}),ItemUrlTemplate:z.string().nullish()}),nh=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({})}),rh=z.object({Page:z.number(),HasMore:z.boolean(),Items:z.array(di).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 Kx=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,lh=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,da=100,oh=25,ah=100;function Hx(o,e,t){return {Field:o,Op:e,Value:t}}var En=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$1)}get(e,t,i={}){let s=tt(e)??Mi(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=tt(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(r=>lh.test(r)))];return n.length?n.length>ah?Promise.resolve(b("client",`At most ${ah} 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=tt(e)??ha(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 p=await this.query(e,{...t,Cursor:r,Limit:t.Limit??da},i);if(!p.ok)return p;if(n.push(...p.data.Items),r=p.data.NextCursor??void 0,!r||n.length>=s)return a(n.slice(0,s))}}count(e,t={}){let i=tt(e)??ha(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=tt(e)??(i.itemID?Mi(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=tt(e)??Mi(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=tt(e)??Mi(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>oh)return Promise.resolve(b("client",`At most ${oh} operations per batch.`));let t=e.map(i=>tt(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=tt(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=tt(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 p=await this.putBytes(r.data.UploadUrl,i,r.data.ContentType||n);return p.ok?r:p}async getPublicViews(e){let t=tt(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 r=await this.fetchJson(n,nh);if(!r.ok)return r;let p=r.data.Partitions[i.partition??""],d=Math.max(1,i.page??1);if(!p||d>p.Pages)return a({pointer:r.data,page:{Page:d,HasMore:false,Items:[]}});let R=await this.fetchJson(`${r.data.BaseUrl}${p.Segment}/page-${d}.json`,rh);return R.ok?a({pointer:r.data,page:R.data}):R}getPublic(e,t){let i=tt(e)??Mi(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=tt(e)??ha(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$1)}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 tt(o){return Kx.test(o??"")?null:b("client",`Collection id '${o}' is invalid (letters, digits, '_', '-', ':').`)}function Mi(o){return lh.test(o??"")?null:b("client",`Item id '${o}' is invalid.`)}function ha(o){return o.Limit!=null&&(o.Limit<1||o.Limit>da)?b("client",`Limit must be 1..${da}.`):(o.Where?.length??0)>8?b("client","At most 8 filters per query."):null}var ma={Open:"Open",Declared:"Declared"},$x=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Blocked:z.boolean().nullish(),Highlight:z.number().nullish()}).passthrough(),Jx=z.object({ParamName:z.string().nullish(),DisplayName:z.string().nullish()}).passthrough(),uh=z.object({Enabled:z.boolean().nullish(),EventNaming:z.string().nullish(),Events:z.record(z.string(),$x).nullish(),Dimensions:z.array(Jx).nullish(),RetentionDays:z.number().nullish(),AutomaticEvents:z.boolean().nullish()}).passthrough(),Gt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Ct={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Un=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Zx={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},Yx=z.object({Index:z.number().nullish(),Name:z.string().nullish(),Reason:z.string().nullish()}).passthrough(),ch=z.object({Accepted:z.number().nullish(),Dropped:z.array(Yx).nullish(),Duplicate:z.boolean().nullish(),Disabled:z.boolean().nullish()}).passthrough(),fa={LogEvents:"LogEvents"};function ph(o,e=0){let t=o??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let p=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let p=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let 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 hh(o){let e=typeof navigator>"u"?void 0:navigator,t=ph(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 Xx=25,eb=3e4,dh=1800*1e3,mh=500,tb=5,ib=1e3,sb=3600*1e3,fh="idos_analytics_queue",ga="idos_analytics_pending",ya="idos_analytics_opt_out",gh="idos_analytics_first_open",yh="idos_analytics_last_activity",Rh="idos_analytics_last_context",Ch="idos_analytics_owner",qn=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"||!Un.test(e)?b("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):nb(e)?b("client",`Event name "${e}" uses a reserved prefix (${Ct.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(Gt.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,Ct.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return c$1;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>=tb)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(ya);return}this.write(ya,"1"),this.clear();}get isEnabled(){return this.read(ya)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(Ch);e&&t&&t!==e&&this.clear(),e&&this.write(Ch,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},eb),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(yh)??"0");this.read(gh)||(this.write(gh,new Date().toISOString()),this.enqueue(Gt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Rh);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Gt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Gt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Rh,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=dh)&&this.enqueue(Gt.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>=dh&&this.enqueue(Gt.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()===ma.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=rb(t);if(r.error)return b("client",r.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return r.params&&(p.Params=r.params),i!==void 0&&(p.Value=i),this.queue.push(p),this.queue.length>mh&&this.queue.splice(0,this.queue.length-mh),this.touch(),this.persist(),this.started&&this.queue.length>=Xx&&this.flush(),a(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},ib));}dropStale(){let e=Date.now()-(Ct.maxEventAgeMs-sb);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??=hh({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(fh);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(ga);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(fh,this.queue),this.pending?this.writeJson(ga,this.pending):this.remove(ga);}touch(){this.write(yh,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 nb(o){let e=o.toLowerCase();return Ct.reservedPrefixes.some(t=>e.startsWith(t))}function rb(o){if(!o)return {};let e=Object.keys(o);if(e.length===0)return {};if(e.length>Ct.maxParams)return {error:`Too many parameters: ${e.length}, max ${Ct.maxParams}.`};let t={};for(let i of e){if(!Un.test(i))return {error:`Invalid parameter name "${i}".`};let s=o[i];typeof s=="string"?t[i]=s.length>Ct.maxStringValueLength?s.slice(0,Ct.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var ob="idos_experiments",Bn=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$1;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.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 `${ob}:${this.ctx.settings.titleID}`}};function Ft(o,e,t,i){let n=`api/v2/${o&&o.length>0?o:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var B=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Ft(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 Ln=class extends B{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(fa.LogEvents,e,ch,{silent:true})}};var ab=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(),lb={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},ub=z.object({MetricID:z.string().nullish(),Kind:z.string().nullish(),EventName:z.string().nullish(),IsPrimary:z.boolean().nullish()}).passthrough(),cb=z.object({ExperimentID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),IsEnabled:z.boolean().nullish(),Schedule:fe.nullish(),Gate:Z.nullish(),Variants:z.array(ab).nullish(),Salt:z.string().nullish(),LayerID:z.string().nullish(),StickyAssignment:z.boolean().nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Goals:z.array(ub).nullish(),ActivationEvent:z.string().nullish(),RolloutVariantID:z.string().nullish()}).passthrough(),Sh=z.object({Experiments:z.record(z.string(),cb).nullish()}).passthrough(),pb={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(),xh=z.object({Experiments:z.array(hb).nullish(),IsAbTestingAvailable:z.boolean().nullish()}).passthrough(),Ra={GetExperiments:"GetExperiments"};var Gn=class extends B{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Ra.GetExperiments,e,xh)}};var bh=z.object({PlatformUserID:z.string().nullish(),PlatformAuthToken:z.string().nullish(),PlatformAuthTokenExpiration:c.nullish(),TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:c,PlayAccess:Lt.nullish(),RefreshToken:z.string().nullish(),RefreshTokenExpiration:c.nullish()}),Dh=z.object({TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:c,RefreshToken:z.string(),RefreshTokenExpiration:c.nullish(),PlayAccess:Lt.nullish()}),db=z.object({ReturnMode:z.string().nullish(),UrlScheme:z.string().nullish(),UserCodeSupported:z.boolean().nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),Ph=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:Ai.nullish(),WalletLoginNetworks:z.array(z.object({NetworkID:z.string().nullish(),Type:z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:z.boolean().nullish(),NativeSso:db.nullish()}).passthrough(),Ih=z.object({Linked:z.boolean().nullish(),Challenge:z.string().nullish(),ExpiresAt:c.nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),PlayAccess:Lt.nullish()}).passthrough(),vh=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CooldownUntil:c.nullish(),PlayAccess:Lt.nullish()}).passthrough(),Th=z.object({CodeTtlMinutes:z.number().nullish(),ResendCooldownSeconds:z.number().nullish()}),Ee=z.object({IsCompleted:z.boolean().nullish(),ServerTime:c.nullish()}),kh=z.object({Message:z.string(),ExpiresAt:c}),Ue={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var Fn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Ft(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,bh,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ue.RefreshSession),e,Dh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ue.GetAuthOptions),e,Ph,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Ft(this.ctx.settings.titleID,"Authentication",Ue.LinkWallet,e.UserID??""),e,Ih,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Ft(this.ctx.settings.titleID,"Authentication",Ue.UnlinkWallet,e.UserID??""),e,vh,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ue.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ue.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ue.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ue.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ue.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ue.LoginWithSsoCode,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ue.RegisterWithEmail),e,Th,{ticket:null})}confirmEmailRegistration(e){return this.login(Ue.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ue.ResendVerificationCode),e,Ee,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ue.RequestWalletChallenge),e,kh,{ticket:null})}loginWithWallet(e){return this.login(Ue.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ue.ForgotPassword),e,Ee,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ue.ResetPassword),e,Ee,{ticket:null})}};var mb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},Ah=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(),zh=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),Locales:z.record(z.string(),fb).nullish(),MissingKeyMode:Ah.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(),wh=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish(),Fallback:gb.nullish()}).passthrough(),Vn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},yb=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),Order:z.number().nullish(),Version:z.number().nullish()}).passthrough(),Mh=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),MissingKeyMode:Ah.nullish(),ResolvedLocale:z.string().nullish(),Locales:z.array(yb).nullish()}).passthrough(),Oh=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 Ca=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:wh.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),Eh=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish()}).passthrough().transform(o=>o),Uh=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),User:z.unknown().nullish()}).passthrough().transform(o=>o),qh=z.object({}).passthrough().transform(o=>o),Bh=z.object({}).passthrough().transform(o=>o),Lh=z.object({Today:z.number(),Yesterday:z.number(),CurrentWeek:z.number(),CurrentMonth:z.number(),Total:z.number(),TotalSessions:z.number(),FirstActiveAt:c.nullish(),LastActiveAt:c.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(),Gh=z.object({Username:z.string()}),lt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Nn=class extends B{constructor(e){super(e,"User");}getClientState(e){return this.send(lt.GetClientState,e,Ca)}getClientStateExcept(e){return this.send(lt.GetClientStateExcept,e,Ca)}getStateVersions(e){return this.send(lt.GetStateVersions,e,Eh)}getUserState(e){return this.send(lt.GetUserState,e,Uh)}getInventory(e){return this.send(lt.GetInventory,e,qh)}getEventTokens(e){return this.send(lt.GetEventTokens,e,Bh)}getUsageTime(e){return this.send(lt.GetUsageTime,e,Lh)}addUsageTime(e){return this.send(lt.AddUsageTime,e,Ee,{silent:true})}deleteUserAccount(e){return this.send(lt.DeleteUserAccount,e,Ee)}changeUsername(e){return this.send(lt.ChangeUsername,e,Gh)}};var jn=class extends B{constructor(e){super(e,"Currency");}convert(e){return this.send(xn.Convert,e,np)}cryptoConvert(e){return this.send(xn.CryptoConvert,e,rp)}};var Rb=z.object({ItemInstanceID:z.string(),Units:z.number(),Level:z.number()}),Sa=z.object({ServerTimeUtc:c,ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Level:z.number(),Resources:M.nullish(),FodderConsumed:z.array(Rb).nullish()}),Fh=z.array(Ie(Sa)),_n={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Cb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},Sb=z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),xb={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},bb=z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Db=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(),Db).nullish(),MetadataUrl:z.string().nullish()}).passthrough(),Ib=z.object({FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),vb=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(),Tb=z.object({ValuationMode:Sb.nullish(),WeightCurve:Fe.nullish(),Selection:bb.nullish()}).passthrough(),kb=z.object({MaxLevel:z.number().nullish(),PriceOptions:ue.nullish(),CostCurve:Fe.nullish(),FlatBonusCurve:Fe.nullish(),PercentBonusCurve:Fe.nullish(),PowerCurve:Fe.nullish(),Fodder:Tb.nullish()}).passthrough(),Ab=z.object({RarityID:z.string().nullish(),CollectionID:z.string().nullish(),AuthorID:z.string().nullish()}).passthrough(),zb=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:Ib.nullish(),Equipment:vb.nullish(),Upgrade:kb.nullish(),Metadata:Ab.nullish(),ExpirationDurationSeconds:z.number().nullish(),MaxSupply:z.number().nullish()}).passthrough(),wb=z.object({Items:z.record(z.string(),zb).nullish()}).passthrough(),Wn=z.object({Catalogs:z.record(z.string(),wb).nullish()}).passthrough();var Qn=class extends B{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(_n.UpgradeLevel,e,Sa)}upgradeLevelsBatch(e){return this.send(_n.UpgradeLevelsBatch,e,Fh)}};var Kn=class extends B{constructor(e){super(e,"Store");}purchase(e){return this.send(Pt.Purchase,e,ho)}purchaseBatch(e){return this.send(Pt.PurchaseBatch,e,Wl)}getDefinitions(e){return this.send(Pt.GetDefinitions,e,ms)}getUserState(e){return this.send(Pt.GetUserState,e,Ql)}getStorefront(e){return this.send(Pt.GetStorefront,e,fs)}getCreditsConfirmation(e){return this.send(Pt.GetCreditsConfirmation,e,po)}getCreditsBalance(e){return this.send(Pt.GetCreditsBalance,e,_l)}};var Mb={Apple:"Apple",Google:"Google"},Hn=z.object({PremiumID:z.string().nullish(),PurchaseDate:z.string().nullish(),ExpirationDate:z.string().nullish(),TransactionID:z.string().nullish(),IsAutoRenewEnabled:z.boolean().nullish()}).passthrough(),$n=z.object({Subscriptions:z.record(z.string(),Hn).nullish(),ActivatedTrialIDs:z.array(z.string()).nullish(),MaxActiveTier:z.number().nullish()}).passthrough().transform(o=>o),Ob=z.object({PremiumID:z.string().nullish(),DisplayName:z.string().nullish(),Tier:z.number().nullish(),DurationDays:z.number().nullish(),TrialDurationDays:z.number().nullish(),PriceOptions:ue.nullish(),Benefits:z.record(z.string(),z.string()).nullish()}).passthrough(),xa=z.object({Definitions:z.record(z.string(),Ob).nullish()}).passthrough(),Vh=z.object({Premium:xa.nullish()}),Nh=z.object({ServerTimeUtc:c.nullish(),Premium:$n.nullish()}),Jn=z.object({ServerTimeUtc:c.nullish(),Premium:$n.nullish(),Subscription:Hn.nullish(),Resources:M.nullish()}),Ht={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var Eb={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},Ub=z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),jh=z.object({StartUtc:c.nullish(),EndUtc:c.nullish(),Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),ba=z.object({ResourceAction:z.string().nullish(),RevokeEntitlement:z.boolean().nullish(),BlockFuturePurchases:z.boolean().nullish()}).passthrough(),qb=z.object({PremiumID:z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:z.number().nullish(),RevokeOnRefund:z.boolean().nullish()}).passthrough(),Bb=z.object({Rewards:Q.nullish(),Rules:Q.nullish(),Refund:Q.nullish()}).passthrough(),Lb=z.object({ProductID:z.string().nullish(),Name:z.string().nullish(),Type:Ub.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:jh.nullish(),Refund:ba.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Subscription:qb.nullish(),Presets:Bb.nullish()}).passthrough(),Gb=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(),Vb=z.object({Rules:jh.nullish()}).passthrough(),Nb=z.object({Refund:ba.nullish()}).passthrough(),jb=z.object({Rewards:z.record(z.string(),Fb).nullish(),Rules:z.record(z.string(),Vb).nullish(),Refund:z.record(z.string(),Nb).nullish()}).passthrough(),_b=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(),Wb=z.object({Enabled:z.boolean().nullish(),Products:z.record(z.string(),Lb).nullish(),Stores:z.record(z.string(),Gb).nullish(),Presets:jb.nullish(),Validation:_b.nullish(),Refund:ba.nullish()}).passthrough(),_h=z.object({ProductID:z.string().nullish(),TotalPurchases:z.number().nullish(),DailyPurchases:z.number().nullish(),DailyResetUtc:c.nullish(),LastPurchasedAt:c.nullish(),Owned:z.boolean().nullish(),Refunded:z.boolean().nullish(),PurchaseBlocked:z.boolean().nullish(),Store:z.string().nullish(),LastTransactionID:z.string().nullish()}).passthrough(),Wh=z.object({ProductID:z.string().nullish(),PremiumID:z.string().nullish(),Store:z.string().nullish(),OriginalTransactionID:z.string().nullish(),LastTransactionID:z.string().nullish(),ExpiresAt:c.nullish(),AutoRenew:z.boolean().nullish(),Status:z.string().nullish(),RenewalCount:z.number().nullish(),LastStoreCheckAt:c.nullish(),LastStoreCheckError:z.string().nullish(),UpdatedAt:c.nullish()}).passthrough(),Qb=z.object({Products:z.record(z.string(),_h).nullish(),LifetimeSpendUsdCents:z.number().nullish(),Subscriptions:z.record(z.string(),Wh).nullish(),LastRefundCheckAt:c.nullish(),TotalPurchases:z.number().nullish(),FirstPurchaseAt:c.nullish(),LastPurchaseAt:c.nullish()}).passthrough(),Kb=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(),Qh=z.object({ServerTimeUtc:c,Purchase:Wb.nullish(),Availability:z.array(Kb).nullish()}),Kh=z.object({ServerTimeUtc:c,Purchase:Qb.nullish()}),Hb={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},$b=z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Da=z.object({ServerTimeUtc:c,Store:Fi.nullish(),ProductID:z.string().nullish(),TransactionID:z.string().nullish(),Status:$b.nullish(),Granted:z.boolean().nullish(),Quantity:z.number().nullish(),Resources:M.nullish(),Inventory:K.nullish(),ProductState:_h.nullish(),Premium:$n.nullish(),Subscription:Hn.nullish(),SubscriptionMirror:Wh.nullish()}).passthrough(),Hh=z.object({ServerTimeUtc:c,ProductID:z.string().nullish(),Stars:z.number().nullish(),InvoiceLink:z.string(),ExpiresAt:c.nullish()}).passthrough(),$h=ft(Da),$t={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var Zn=class extends B{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send($t.GetDefinitions,e,Qh)}getUserState(e){return this.send($t.GetUserState,e,Kh)}validatePurchase(e){return this.send($t.ValidatePurchase,e,Da)}validatePurchasesBatch(e){return this.send($t.ValidatePurchasesBatch,e,$h)}createTelegramInvoice(e){return this.send($t.CreateTelegramInvoice,e,Hh)}};var Jb=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),Jh=z.object({Reward:H.nullish(),Weight:z.number().nullish(),AmountRange:Jb.nullish()}).passthrough(),mi=z.object({SlotID:z.string().nullish(),MinRolls:z.number().nullish(),MaxRolls:z.number().nullish(),Pool:z.array(Jh).nullish()}).passthrough(),fi=z.object({RuleID:z.string().nullish(),Threshold:z.number().nullish(),Pool:z.array(Jh).nullish()}).passthrough(),Zb=z.object({RewardSlots:z.array(mi).nullish()}).passthrough(),Yb=z.object({PityRules:z.array(fi).nullish()}).passthrough(),Yn=z.object({SlotPresets:z.record(z.string(),Zb).nullish(),PityPresets:z.record(z.string(),Yb).nullish()}).passthrough();var Xb=z.object({RuleID:z.string(),BoxIndex:z.number().nullish()}),Zh=z.object({ServerTimeUtc:c,LootboxID:z.string(),OpenedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish(),Results:z.array(M).nullish(),TriggeredPity:z.array(Xb).nullish()}),eD=z.object({RewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),tD=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxDrops:_.nullish()}).passthrough(),iD=z.object({LootboxID:z.string(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:ue.nullish(),RewardSlots:z.array(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:eD.nullish(),RewardMultiplier:Ni.nullish(),SupplyLimits:z.array(tD).nullish(),MaxOpenCount:z.number().nullish()}).passthrough(),sD=z.object({MaxOpenCount:z.number().nullish()}).passthrough(),Pa=z.object({Definitions:z.record(z.string(),iD).nullish(),RewardPools:Yn.nullish(),Settings:sD.nullish()}).passthrough(),Yh=z.object({LootboxDefinitions:Pa.nullish()}),Xn={GetDefinitions:"GetDefinitions",Open:"Open"};var er=class extends B{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(Xn.GetDefinitions,e,Yh)}open(e){return this.send(Xn.Open,e,Zh)}};var nD=z.object({}).passthrough().transform(o=>o),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),Xh=z.object({ServerTimeUtc:c,CalendarID:z.string(),DayNumber:z.number().nullish(),DailyState:nD,Resources:M.nullish(),Inventory:K.nullish()}),ed=z.object({ServerTimeUtc:c,AccrualID:z.string(),AccruedSeconds:_.nullish(),AppliedRatePerSecond:z.number().nullish(),IdleState:rD,Resources:M.nullish(),Inventory:K.nullish()}),td=z.object({ServerTimeUtc:c,ComebackID:z.string(),ClaimedTierIndex:z.number().nullish(),ComebackState:oD,Resources:M.nullish(),Inventory:K.nullish()}),id=z.object({ServerTimeUtc:c,ClaimID:z.string(),ClaimState:aD,Resources:M.nullish(),Inventory:K.nullish()}),sd=z.object({Enabled:z.boolean(),Multiplier:z.number().nullish(),Progress:_.nullish(),Source:z.string().nullish(),SourceKey:z.string().nullish()}),uD=z.object({RewardMode:z.string().nullish(),RewardStackLowerTiers:z.boolean().nullish()}).passthrough(),cD=z.object({DayNumber:z.number().nullish(),Rewards:H.nullish(),IsMilestone:z.boolean().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Oi=z.object({Gate:Z.nullish(),Limits:Re.nullish()}).passthrough(),Ia=z.object({Availability:Q.nullish()}).passthrough(),pD=z.object({Availability:z.record(z.string(),Oi).nullish()}).passthrough(),hD=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(cD).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:Oi.nullish(),Presets:Ia.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),dD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Multiplier:z.number().nullish()}).passthrough(),mD=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(dD).nullish()}).passthrough(),fD=z.object({MinCharacterLevel:z.number().nullish(),RequirementsCharacterID:z.string().nullish(),Availability:Oi.nullish(),RequiredItemIDs:z.array(z.string()).nullish(),RequiredEquippedItemIDs:z.array(z.string()).nullish()}).passthrough(),gD=z.object({AccrualID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rate:mD.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:z.number().nullish(),MinClaimSeconds:z.number().nullish(),Requirements:fD.nullish(),FirstClaimMode:z.string().nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),yD=z.object({MinAbsenceSeconds:z.number().nullish(),Rewards:H.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),RD=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(yD).nullish(),ClaimCooldownSeconds:z.number().nullish(),ClaimWindowSeconds:z.number().nullish(),TrackPresenceOnRead:z.boolean().nullish(),Availability:Oi.nullish(),Presets:Ia.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),CD=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(),SD=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(CD).nullish(),Availability:Oi.nullish(),Presets:Ia.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),va=z.object({TierRewards:uD.nullish(),MilestoneRewardMultiplier:Ni.nullish(),DailyCalendars:z.record(z.string(),hD).nullish(),IdleAccruals:z.record(z.string(),gD).nullish(),Comebacks:z.record(z.string(),RD).nullish(),Claims:z.record(z.string(),SD).nullish(),Presets:pD.nullish()}).passthrough(),nd=z.object({RewardDefinitions:va.nullish()}),rd=z.object({Rewards:lD.nullish()}),At={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var tr=class extends B{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(At.GetRewardDefinitions,e,nd)}getUserRewardsState(e){return this.send(At.GetUserRewardsState,e,rd)}getMilestoneRewardMultiplier(e){return this.send(At.GetMilestoneRewardMultiplier,e,sd)}claimDailyReward(e){return this.send(At.ClaimDailyReward,e,Xh)}collectIdleAccrual(e){return this.send(At.CollectIdleAccrual,e,ed)}claimComebackReward(e){return this.send(At.ClaimComebackReward,e,td)}claimReward(e){return this.send(At.ClaimReward,e,id)}};var ir=class extends B{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(nt.GetTutorialDefinitions,e,Pl)}getUserTutorialState(e){return this.send(nt.GetUserTutorialState,e,Wi)}startFlow(e){return this.send(nt.StartFlow,e,wt)}reportStepShown(e){return this.send(nt.ReportStepShown,e,wt)}completeStep(e){return this.send(nt.CompleteStep,e,wt)}completeStepsBatch(e){return this.send(nt.CompleteStepsBatch,e,Tl)}skipStep(e){return this.send(nt.SkipStep,e,wt)}skipFlow(e){return this.send(nt.SkipFlow,e,wt)}claimFlowReward(e){return this.send(nt.ClaimFlowReward,e,vl)}resetFlow(e){return this.send(nt.ResetFlow,e,wt)}};var xD={Open:"Open",Application:"Application"},bD=z.enum(["Open","Application"]).catch("Open"),DD={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},od=z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),PD={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Ta=z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),ID={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var Jt={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},vD=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(),ad=z.object({IsEnabled:z.boolean().nullish(),CreatorPortalUrl:z.string().nullish(),ParticipationMode:bD.nullish(),IsCreator:z.boolean().nullish(),CreatorStatus:od.nullish(),VerificationCode:z.string().nullish(),TeamID:z.string().nullish(),Campaigns:z.array(vD).nullish()}).passthrough(),TD=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(),kD=z.object({CampaignID:z.string().nullish(),CurrencyKind:Ta.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(),TD).nullish(),ComputedAt:z.string().nullish()}).passthrough(),AD=z.object({PayoutID:z.string().nullish(),CampaignID:z.string().nullish(),Amount:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Ta.nullish(),NetworkID:z.string().nullish(),PaidAt:z.string().nullish()}).passthrough(),ld=z.object({ServerTimeUtc:z.string().nullish(),HoldDays:z.number().nullish(),Campaigns:z.array(kD).nullish(),Payouts:z.array(AD).nullish()}).passthrough(),ud=z.object({CampaignID:z.string().nullish(),PayoutID:z.string().nullish(),Claimed:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Ta.nullish(),NetworkID:z.string().nullish(),RemainingFraction:z.number().nullish(),IdempotentReplay:z.boolean().nullish(),Message:z.string().nullish()}).passthrough(),zD=z.object({To:z.string().nullish(),Amount:z.string().nullish()}).passthrough(),wD=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(zD).nullish()}).passthrough(),MD=z.object({Kind:z.string().nullish(),Target:z.string().nullish(),Required:z.number().nullish(),Actual:z.number().nullish(),Passed:z.boolean().nullish()}).passthrough(),cd=z.object({Passed:z.boolean().nullish(),Approved:z.boolean().nullish(),Status:od.nullish(),WalletMissing:z.boolean().nullish(),WalletConnectAllowed:z.boolean().nullish(),Conditions:z.array(MD).nullish()}).passthrough(),OD=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),ED=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(OD).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(),pd=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:wD.nullish(),SolanaSignature:ED.nullish(),StateDelta:hi.nullish()}).passthrough();var sr=class extends B{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(Jt.GetCommunityMarketingState,e,ad)}getEarnings(e){return this.send(Jt.GetEarnings,e,ld)}claim(e){return this.send(Jt.Claim,e,ud)}checkJoinEligibility(e){return this.send(Jt.CheckJoinEligibility,e,cd)}withdrawCryptoReward(e){return this.send(Jt.WithdrawCryptoReward,e,pd)}};var nr=class extends B{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(Qe.GetChatDefinitions,e,lu)}getChannels(e){return this.send(Qe.GetChannels,e,Is)}poll(e){return this.send(Qe.Poll,e,uu)}getHistory(e){return this.send(Qe.GetHistory,e,cu)}getConversations(e){return this.send(Qe.GetConversations,e,du)}sendMessage(e){return this.send(Qe.SendMessage,e,pu)}openDirectChannel(e){return this.send(Qe.OpenDirectChannel,e,hu)}markRead(e){return this.send(Qe.MarkRead,e,ci)}joinChannel(e){return this.send(Qe.JoinChannel,e,ci)}leaveChannel(e){return this.send(Qe.LeaveChannel,e,ci)}reportMessage(e){return this.send(Qe.ReportMessage,e,mu)}ignoreUser(e){return this.send(Qe.IgnoreUser,e,ci)}unignoreUser(e){return this.send(Qe.UnignoreUser,e,ci)}};var rr=class extends B{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(pi.GetPushConfig,e,yu)}subscribePush(e){return this.send(pi.SubscribePush,e,yo)}unsubscribePush(e){return this.send(pi.UnsubscribePush,e,Ee)}getPushSubscriptions(e){return this.send(pi.GetPushSubscriptions,e,Ru)}};var or=class extends B{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(Vn.GetLocalizationManifest,e,Mh)}getLocalizationTable(e){return this.send(Vn.GetLocalizationTable,e,Oh)}};var ar=class extends B{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(pt.GetQuestDefinitions,e,_i)}getUserQuestState(e){return this.send(pt.GetUserQuestState,e,hl)}refreshQuestCycles(e){return this.send(pt.RefreshQuestCycles,e,Ee)}claimQuestReward(e){return this.send(pt.ClaimQuestReward,e,Xr)}claimQuestRewardsBatch(e){return this.send(pt.ClaimQuestRewardsBatch,e,fl)}claimMilestoneReward(e){return this.send(pt.ClaimMilestoneReward,e,eo)}claimMilestoneRewardsBatch(e){return this.send(pt.ClaimMilestoneRewardsBatch,e,gl)}claimGroupCompletionReward(e){return this.send(pt.ClaimGroupCompletionReward,e,dl)}addQuestProgress(e){return this.send(pt.AddQuestProgress,e,ml)}};var lr=class extends B{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ot.GetActiveEvents,e,Ms)}getDefinitions(e){return this.send(ot.GetDefinitions,e,ws)}getUserLteState(e){return this.send(ot.GetUserLteState,e,bu)}grantTokens(e){return this.send(ot.GrantTokens,e,M)}spendTokens(e){return this.send(ot.SpendTokens,e,So)}claimMilestone(e){return this.send(ot.ClaimMilestone,e,xo)}claimMilestonesBatch(e){return this.send(ot.ClaimMilestonesBatch,e,bo)}claimAllMilestones(e){return this.send(ot.ClaimAllMilestones,e,bo)}spendTokensBatch(e){return this.send(ot.SpendTokensBatch,e,Du)}grantTokensBatch(e){return this.send(ot.GrantTokensBatch,e,Pu)}};var ur=class extends B{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ve.GetDefinitions,e,Gs)}getLeaderboard(e){return this.send(Ve.GetLeaderboard,e,Pi)}getMyProgress(e){return this.send(Ve.GetMyProgress,e,Es)}submitScore(e){return this.send(Ve.SubmitScore,e,Us)}submitScoreFromSource(e){return this.send(Ve.SubmitScoreFromSource,e,Us)}claimCycleReward(e){return this.send(Ve.ClaimCycleReward,e,qs)}claimMilestone(e){return this.send(Ve.ClaimMilestone,e,Bs)}getFriendsLeaderboard(e){return this.send(Ve.GetFriendsLeaderboard,e,Pi)}getLeaderboardsBatch(e){return this.send(Ve.GetLeaderboardsBatch,e,Tu)}getProgressBatch(e){return this.send(Ve.GetProgressBatch,e,Ls)}claimCycleRewardsBatch(e){return this.send(Ve.ClaimCycleRewardsBatch,e,ku)}claimMilestonesBatch(e){return this.send(Ve.ClaimMilestonesBatch,e,Au)}submitScoresBatch(e){return this.send(Ve.SubmitScoresBatch,e,zu)}claimAllRewardsBatch(e){return this.send(Ve.ClaimAllRewardsBatch,e,wu)}getOverviewBatch(e){return this.send(Ve.GetOverviewBatch,e,Mu)}};var cr=class extends B{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Et.GetDefinitions,e,Ns)}getActiveSeason(e){return this.send(Et.GetActiveSeason,e,Vs)}getUserState(e){return this.send(Et.GetUserState,e,Do)}grantStatusTokens(e){return this.send(Et.GrantStatusTokens,e,qu)}claimTierReward(e){return this.send(Et.ClaimTierReward,e,Po)}claimTierRewardsBatch(e){return this.send(Et.ClaimTierRewardsBatch,e,Bu)}};var pr=class extends B{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Ht.GetDefinitions,e,Vh)}getUserState(e){return this.send(Ht.GetUserState,e,Nh)}activateTrial(e){return this.send(Ht.ActivateTrial,e,Jn)}purchaseItemOrCurrency(e){return this.send(Ht.PurchaseWithResources,e,Jn)}purchaseRealMoney(e){return this.send(Ht.PurchaseRealMoney,e,Jn)}};var hr=class extends B{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(Ne.GetCharacterDefinitions,e,Qs)}getUserCharacters(e){return this.send(Ne.GetUserCharacters,e,ju)}unlockCharacter(e){return this.send(Ne.UnlockCharacter,e,ko)}upgradeStatLevel(e){return this.send(Ne.UpgradeStatLevel,e,vo)}upgradeCharacterLevel(e){return this.send(Ne.UpgradeCharacterLevel,e,To)}equipItems(e){return this.send(Ne.EquipItems,e,_u)}unequipItems(e){return this.send(Ne.UnequipItems,e,Wu)}unequipAllCharacters(e){return this.send(Ne.UnequipAllCharacters,e,Qu)}unlockCharactersBatch(e){return this.send(Ne.UnlockCharactersBatch,e,Zu)}upgradeCharacterLevelsBatch(e){return this.send(Ne.UpgradeCharacterLevelsBatch,e,Yu)}upgradeStatLevelsBatch(e){return this.send(Ne.UpgradeStatLevelsBatch,e,Xu)}unlockSkin(e){return this.send(Ne.UnlockSkin,e,Ku)}equipSkin(e){return this.send(Ne.EquipSkin,e,Hu)}unequipSkin(e){return this.send(Ne.UnequipSkin,e,$u)}getCharacterSkins(e){return this.send(Ne.GetCharacterSkins,e,Ju)}};var dr=class extends B{constructor(e){super(e,"Match");}createMatch(e){return this.send(Rt.CreateMatch,e,zp)}updateMatch(e){return this.send(Rt.UpdateMatch,e,wp)}cancelMatch(e){return this.send(Rt.CancelMatch,e,Mp)}instantBattle(e){return this.send(Rt.InstantBattle,e,Op)}saveStrategy(e){return this.send(Rt.SaveStrategy,e,Ee)}getMyMatches(e){return this.send(Rt.GetMyMatches,e,ea)}getAvailableMatches(e){return this.send(Rt.GetAvailableMatches,e,ea)}getDefinitions(e){return this.send(Rt.GetDefinitions,e,Bp)}};var UD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},hd=z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),qD={None:"None",Min:"Min",Average:"Average",Max:"Max"},BD=z.enum(["None","Min","Average","Max"]).catch("None"),LD={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},GD=z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),FD={Clamp:"Clamp",Reject:"Reject"},VD=z.enum(["Clamp","Reject"]).catch("Clamp"),ND=z.object({ItemInstanceID:z.string().nullish(),ItemID:z.string().nullish(),Level:z.number().nullish(),Units:z.number().nullish()}),jD=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:Jr.nullish(),OutputLevel:z.number().nullish(),BurnedInstances:z.array(ND).nullish()}),dd=z.object({ServerTimeUtc:c,Type:hd.nullish(),CraftID:z.string(),CraftedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),InputRarity:z.string().nullish(),OutputRarity:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish(),Results:z.array(jD).nullish()}),_D=z.object({CraftID:z.string().nullish(),Type:hd.nullish(),CatalogID:z.string().nullish(),CollectionID:z.string().nullish(),InputRarityID:z.string().nullish(),OutputRarityID:z.string().nullish(),RequiredItemCount:z.number().nullish(),PriceOptions:ue.nullish(),OutputLevelMode:BD.nullish(),InputSelection:GD.nullish(),OutputLevelOverflow:VD.nullish()}).passthrough(),ka=z.object({Definitions:z.record(z.string(),_D).nullish()}).passthrough(),md=z.object({ServerTimeUtc:c.nullish(),CraftDefinitions:ka.nullish()}),mr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var fr=class extends B{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(mr.GetDefinitions,e,md)}craft(e){return this.send(mr.Craft,e,dd)}};var WD=2e5,gr=class extends B{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,Js,{timeoutMs:WD,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Js,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Ge.GetDefinitions,e,lc)}generateText(e){return this.generate(Ge.GenerateText,e)}getText(e){return this.readGeneration(Ge.GetText,e)}generateImage(e){return this.generate(Ge.GenerateImage,e)}editImage(e){return this.generate(Ge.EditImage,e)}getImage(e){return this.readGeneration(Ge.GetImage,e)}generateVideo(e){return this.generate(Ge.GenerateVideo,e)}getVideo(e){return this.readGeneration(Ge.GetVideo,e)}generateAudio(e){return this.generate(Ge.GenerateAudio,e)}getAudio(e){return this.readGeneration(Ge.GetAudio,e)}generateMusic(e){return this.generate(Ge.GenerateMusic,e)}getMusic(e){return this.readGeneration(Ge.GetMusic,e)}generateThreeD(e){return this.generate(Ge.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Ge.GetThreeD,e)}listGenerations(e){return this.send(Ge.ListGenerations,e,ac)}getGeneration(e){return this.readGeneration(Ge.GetGeneration,e)}};var QD={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},KD=z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),fd=z.object({}).passthrough().transform(o=>o),gi=z.object({CollectibleID:z.string(),Rarity:z.number().nullish(),IsSpecial:z.boolean().nullish(),IsDuplicate:z.boolean().nullish(),CollectionCurrencyConverted:z.number().nullish()}),gd=z.object({GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish()}),yd=z.object({OpenedCount:z.number().nullish(),Packs:z.array(gd).nullish(),GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish(),NewCollectionCurrencyBalance:_.nullish(),NewlyCompletedSetIDs:z.array(z.string()).nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),Rd=z.object({OpenedCount:z.number().nullish(),Chests:z.array(gd).nullish(),GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish(),NewCollectionCurrencyBalance:_.nullish(),Resources:M.nullish(),Inventory:K.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),Cd=z.object({GrantedCollectibleID:z.string().nullish(),NewlyCompletedSetID:z.string().nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),Aa=z.object({SetID:z.string(),Resources:M.nullish(),Inventory:K.nullish()}),Sd=z.array(Ie(Aa)),xd=z.object({Resources:M.nullish(),Inventory:K.nullish()}),HD=z.object({OfferID:z.string(),TitleID:z.string().nullish(),CollectionID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderPublicData:Oe.nullish(),OfferedCollectibleID:z.string().nullish(),OfferedCollectibleIsSpecial:z.boolean().nullish(),ReceiverUserID:z.string().nullish(),RequestedCollectibleID:z.string().nullish(),RequestedCollectibleIsSpecial:z.boolean().nullish(),Status:KD.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RespondedAtUtc:c.nullish(),DeclineReason:z.string().nullish(),IsSpecialTradeEvent:z.boolean().nullish(),SpecialTradeEventID:z.string().nullish()}).passthrough(),bd=z.object({OfferID:z.string(),ExpiresAtUtc:c.nullish(),Resources:M.nullish()}),Dd=z.object({OfferID:z.string(),Resources:M.nullish()}),Pd=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()}),Id=z.object({OfferID:z.string(),Resources:M.nullish()}),za=z.object({Offers:z.array(HD).nullish()}),$D=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(),JD=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($D).nullish(),SetCompletionReward:H.nullish()}).passthrough(),ZD=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(JD).nullish(),GrandPrize:H.nullish()}).passthrough(),vd=z.object({BonusRewardSlots:Q.nullish(),PityRules:Q.nullish()}).passthrough(),YD=z.object({PackTypeID:z.string().nullish(),PriceOptions:ue.nullish(),BonusRewardSlots:z.array(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:vd.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(),XD=z.object({Rarity:z.number().nullish(),CollectionCurrencyGranted:z.number().nullish()}).passthrough(),eP=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(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:vd.nullish(),Tier:z.number().nullish()}).passthrough(),tP=z.object({SpecialTradeEventID:z.string().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),AllowedSpecialCollectibleIDs:z.array(z.string()).nullish(),SpecialTradeEventDailyTradeLimit:z.number().nullish()}).passthrough(),iP=z.object({MaxPackOpenCount:z.number().nullish(),MaxChestOpenCount:z.number().nullish()}).passthrough(),yr=z.object({Collections:z.record(z.string(),ZD).nullish(),PackTypes:z.record(z.string(),YD).nullish(),CollectionChests:z.array(eP).nullish(),DuplicateConversions:z.array(XD).nullish(),DailyTradeLimit:z.number().nullish(),CollectibleJokerCatalogID:z.string().nullish(),CollectibleJokerItemID:z.string().nullish(),SpecialTradeEvents:z.array(tP).nullish(),RewardPools:Yn.nullish(),Settings:iP.nullish()}).passthrough(),je={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 Rr=class extends B{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(je.GetDefinitions,e,yr)}getUserState(e){return this.send(je.GetUserState,e,fd)}openPack(e){return this.send(je.OpenPack,e,yd)}openCollectionChest(e){return this.send(je.OpenCollectionChest,e,Rd)}useCollectibleJoker(e){return this.send(je.UseCollectibleJoker,e,Cd)}claimSetReward(e){return this.send(je.ClaimSetReward,e,Aa)}claimSetRewardsBatch(e){return this.send(je.ClaimSetRewardsBatch,e,Sd)}claimGrandPrize(e){return this.send(je.ClaimGrandPrize,e,xd)}sendTradeOffer(e){return this.send(je.SendTradeOffer,e,bd)}cancelTradeOffer(e){return this.send(je.CancelTradeOffer,e,Dd)}acceptTradeOffer(e){return this.send(je.AcceptTradeOffer,e,Pd)}declineTradeOffer(e){return this.send(je.DeclineTradeOffer,e,Id)}getMyTradeOffers(e){return this.send(je.GetMyTradeOffers,e,za)}getIncomingTradeOffers(e){return this.send(je.GetIncomingTradeOffers,e,za)}};var Cr=class extends B{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(ht.GetDefinitions,e,en)}getActiveEvent(e){return this.send(ht.GetActiveEvent,e,pc)}getUserState(e){return this.send(ht.GetUserState,e,Xs)}getGroupState(e){return this.send(ht.GetGroupState,e,Eo)}joinOrCreateGroup(e){return this.send(ht.JoinOrCreateGroup,e,Eo)}spin(e){return this.send(ht.Spin,e,dc)}claimObjectReward(e){return this.send(ht.ClaimObjectReward,e,Uo)}claimGrandPrize(e){return this.send(ht.ClaimGrandPrize,e,Uo)}leaveGroup(e){return this.send(ht.LeaveGroup,e,mc)}};var Sr=class extends B{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(yt.GetDefinition,e,Ic)}getUserState(e){return this.send(yt.GetUserState,e,vc)}getActiveDeals(e){return this.send(yt.GetActiveDeals,e,nn)}dismissDeal(e){return this.send(yt.DismissDeal,e,kc)}executeNode(e){return this.send(yt.ExecuteNode,e,Tc)}recordShow(e){return this.send(yt.RecordShow,e,Ac)}claimMilestone(e){return this.send(yt.ClaimMilestone,e,zc)}claimMilestonesBatch(e){return this.send(yt.ClaimMilestonesBatch,e,wc)}};var sP=z.object({}).passthrough().transform(o=>o),nP=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:Re.nullish()}).passthrough(),wa=z.object({IsEnabled:z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:z.record(z.string(),Be).nullish(),SpendRewards:z.array(nP).nullish(),Qualification:z.object({}).passthrough().transform(o=>o).nullish()}).passthrough(),Ma=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(),Td=z.object({ReferralDefinitions:wa.nullish()}).passthrough(),kd=z.object({Referral:sP.nullish(),InviteUrl:z.string().nullish(),Qualification:Ma.nullish()}).passthrough(),Ad=z.object({QualificationPending:z.boolean().nullish(),Qualification:Ma.nullish()}).passthrough(),zd=z.object({ReferralCode:z.string().nullish(),ReferrerUserID:z.string().nullish(),IsFirstActivation:z.boolean().nullish(),Resources:M.nullish(),Inventory:K.nullish(),QualificationPending:z.boolean().nullish(),Qualification:Ma.nullish()}).passthrough(),Oa=z.object({RewardID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}).passthrough(),wd=ft(Oa),Vt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var xr=class extends B{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Vt.GetDefinitions,e,Td)}getUserState(e){return this.send(Vt.GetUserState,e,kd)}activateReferralCode(e){return this.send(Vt.ActivateReferralCode,e,zd)}claimInviteReward(e){return this.send(Vt.ClaimInviteReward,e,Oa)}claimInviteRewardsBatch(e){return this.send(Vt.ClaimInviteRewardsBatch,e,wd)}checkQualification(e){return this.send(Vt.CheckQualification,e,Ad)}};var br=class extends B{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(et.GetDefinitions,e,qc)}getMessages(e){return this.send(et.GetMessages,e,Bc)}getUnreadCount(e){return this.send(et.GetUnreadCount,e,an)}readMessages(e){return this.send(et.ReadMessages,e,Lo)}claimReward(e){return this.send(et.ClaimReward,e,ln)}claimRewardsBatch(e){return this.send(et.ClaimRewardsBatch,e,ln)}claimAll(e){return this.send(et.ClaimAll,e,ln)}deleteMessages(e){return this.send(et.DeleteMessages,e,Lo)}sendGift(e){return this.send(et.SendGift,e,Lc)}sendTransfer(e){return this.send(et.SendTransfer,e,Gc)}getGiftStatus(e){return this.send(et.GetGiftStatus,e,Fc)}};var Dr=class extends B{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Ce.GetFriendsList,e,vi)}getIncomingRequests(e){return this.send(Ce.GetIncomingRequests,e,vi)}getOutgoingRequests(e){return this.send(Ce.GetOutgoingRequests,e,vi)}getRecommendedFriends(e){return this.send(Ce.GetRecommendedFriends,e,vi)}sendFriendRequest(e){return this.send(Ce.SendFriendRequest,e,Ti)}acceptFriendRequest(e){return this.send(Ce.AcceptFriendRequest,e,Ti)}declineFriendRequest(e){return this.send(Ce.DeclineFriendRequest,e,Ti)}removeFriend(e){return this.send(Ce.RemoveFriend,e,Ti)}getInbox(e){return this.send(Ce.GetInbox,e,Nc)}markInboxSeen(e){return this.send(Ce.MarkInboxSeen,e,ki)}getInboxUnread(e){return this.send(Ce.GetInboxUnread,e,ki)}follow(e){return this.send(Ce.Follow,e,Bt)}unfollow(e){return this.send(Ce.Unfollow,e,Bt)}getFollowers(e){return this.send(Ce.GetFollowers,e,cn)}getFollowing(e){return this.send(Ce.GetFollowing,e,cn)}block(e){return this.send(Ce.Block,e,Bt)}unblock(e){return this.send(Ce.Unblock,e,Bt)}getBlocked(e){return this.send(Ce.GetBlocked,e,cn)}react(e){return this.send(Ce.React,e,Bt)}unreact(e){return this.send(Ce.Unreact,e,Bt)}getMyReactions(e){return this.send(Ce.GetMyReactions,e,_c)}getEntityStates(e){return this.send(Ce.GetEntityStates,e,jc)}addComment(e){return this.send(Ce.AddComment,e,pn)}editComment(e){return this.send(Ce.EditComment,e,pn)}deleteComment(e){return this.send(Ce.DeleteComment,e,Qc)}getComments(e){return this.send(Ce.GetComments,e,Wc)}report(e){return this.send(Ce.Report,e,Kc)}};var rP={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Zt=z.object({Target:z.string().nullish(),Operation:z.string().nullish(),Value:z.number().nullish()}).passthrough(),oP=z.object({BoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:ue.nullish(),Effect:Zt.nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),Pr=z.object({Schedule:fe.nullish(),Gate:Z.nullish()}).passthrough(),Ea=z.object({Availability:Q.nullish(),Effects:Q.nullish()}).passthrough(),aP=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(Zt).nullish(),Availability:Pr.nullish(),Presets:Ea.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),lP=z.object({ChainedBoostID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Effects:z.array(Zt).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),uP=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(lP).nullish(),Availability:Pr.nullish(),Presets:Ea.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),cP=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(st).nullish(),Effects:z.array(Zt).nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Availability:Pr.nullish(),Presets:Ea.nullish()}).passthrough(),pP=z.object({MaxAddPercent:z.number().nullish(),MaxMultiply:z.number().nullish(),MaxAddFlat:z.number().nullish()}).passthrough(),hP=z.object({Effects:z.array(Zt).nullish()}).passthrough(),dP=z.object({Availability:z.record(z.string(),Pr).nullish(),Effects:z.record(z.string(),hP).nullish()}).passthrough(),mP=z.object({StackingCaps:z.record(z.string(),pP).nullish()}).passthrough(),Ir=z.object({Definitions:z.record(z.string(),oP).nullish(),ScheduledBoosts:z.record(z.string(),aP).nullish(),BoostChains:z.record(z.string(),uP).nullish(),TriggeredBoosts:z.record(z.string(),cP).nullish(),Settings:mP.nullish(),Presets:dP.nullish()}).passthrough(),Md=z.object({InstanceID:z.string(),BoostID:z.string(),ActivatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RemainingCharges:z.number().nullish(),EffectSnapshot:Zt.nullish(),SourceType:z.string().nullish(),SourceRef:z.string().nullish()}).passthrough();z.object({Date:c.nullish(),DailyCount:z.number().nullish(),LastFiredUtc:c.nullish()}).passthrough();var Od=z.object({ServerTimeUtc:c.nullish(),Active:z.record(z.string(),Md).nullish()}),Ed=z.object({ServerTimeUtc:c.nullish(),BoostID:z.string().nullish(),StackingPolicy:z.string().nullish(),ActivatedBoost:Md.nullish(),Resources:M.nullish()}),fP={Scheduled:"Scheduled",Chain:"Chain"},gP=z.object({Kind:z.string().nullish(),SourceID:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),PhaseOrder:z.number().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),Effects:z.array(Zt).nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Ud=z.object({ServerTimeUtc:c.nullish(),Windows:z.array(gP).nullish()}),Yt={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var vr=class extends B{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(Yt.GetDefinitions,e,Ir)}getActive(e){return this.send(Yt.GetActive,e,Od)}getActiveWindows(e){return this.send(Yt.GetActiveWindows,e,Ud)}activate(e){return this.send(Yt.Activate,e,Ed)}cleanupExpired(e){return this.send(Yt.CleanupExpired,e,Ee)}};var Tr=class extends B{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(dt.GetUserCustomDataDefinitions,e,fn)}getMyUserCustomData(e){return this.send(dt.GetMyUserCustomData,e,Zc)}getPublicUserCustomDataOf(e){return this.send(dt.GetPublicUserCustomDataOf,e,jo)}setPrivateData(e){return this.send(dt.SetPrivateData,e,_o)}setPublicData(e){return this.send(dt.SetPublicData,e,_o)}deleteKey(e){return this.send(dt.DeleteKey,e,Ee)}batchSet(e){return this.send(dt.BatchSet,e,Yc)}batchDelete(e){return this.send(dt.BatchDelete,e,Xc)}batchGetPublicUserCustomDataOf(e){return this.send(dt.BatchGetPublicUserCustomDataOf,e,ep)}};var yP={Static:"Static",Runtime:"Runtime"},RP={Public:"Public",Private:"Private"},CP=z.enum(["Client","Server","System"]).catch("Client"),SP=z.enum(["String","Int","Bool","Json"]).catch("String"),xP=z.object({Value:z.string().nullish(),UpdatedAt:c.nullish(),Version:z.number().nullish(),LastWriter:CP.nullish(),ExpiresAt:c.nullish()}).passthrough(),qd=z.record(z.string(),xP),Ua=z.object({StaticVersion:z.number().nullish(),RuntimeVersion:z.number().nullish(),Static:qd.nullish(),Runtime:qd.nullish(),NotModified:z.boolean().nullish()}),bP=z.object({KeyID:z.string(),Scope:z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:SP.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),kr=z.object({Keys:z.record(z.string(),bP).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),Ei={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Ar=class extends B{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Ei.GetTitleCustomDataDefinitions,e,kr)}getPublicTitleData(e){return this.send(Ei.GetPublicTitleData,e,Ua)}getPublicTitleDataKeys(e){return this.send(Ei.GetPublicTitleDataKeys,e,Ua)}};var DP={Fast:"Fast",Sequential:"Sequential"},PP={Instant:"Instant",Timed:"Timed"};var IP={Hit:"Hit",Blocked:"Blocked"},vP=z.object({SlotIndex:z.number(),Level:z.number().nullish(),IsDamaged:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish()}).passthrough(),TP=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 kP=z.object({RequiredValue:z.number().nullish(),Reward:H.nullish()}).passthrough(),AP=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(kP).nullish(),Rate:AP.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 Bd=z.object({}).passthrough().transform(o=>o),Ld=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),_e=z.object({Operation:M.nullish(),ScaleWithRollMultiplier:z.boolean().nullish()}).passthrough(),zP=z.object({Count:z.number().nullish(),Sides:z.number().nullish()}).passthrough(),wP=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(),MP=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:ce.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(),OP=z.object({CostMatrix:z.array(z.array(z.number())).nullish(),PerBoardGrowth:z.number().nullish(),EconomyScale:z.number().nullish(),ScaledResources:ce.nullish()}).passthrough(),Gd=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(),EP=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(),UP=z.object({Tiles:z.record(z.string(),EP).nullish()}).passthrough(),qP=z.object({Weight:z.number().nullish(),Bonus:_e.nullish(),Tag:z.string().nullish()}).passthrough(),BP=z.object({Weight:z.number().nullish(),Tag:z.string().nullish(),MinBonusCells:z.number().nullish(),MaxBonusCells:z.number().nullish(),BonusPool:z.array(qP).nullish(),GuaranteedBonus:_e.nullish(),IsJackpot:z.boolean().nullish(),JackpotFinalMultiplier:z.number().nullish(),JackpotSymbolDistribution:z.record(z.string(),z.number()).nullish()}).passthrough(),LP=z.object({Variants:z.array(BP).nullish()}).passthrough(),GP=z.object({Weight:z.number().nullish(),OutcomeID:z.string().nullish(),Reward:_e.nullish(),ForceAction:z.string().nullish(),SpecialModeID:z.string().nullish()}).passthrough(),FP=z.object({Outcomes:z.array(GP).nullish()}).passthrough(),Fd=z.object({PerAdMultiplierRange:Ld.nullish(),MaxAdViews:z.number().nullish(),AdCreditCost:z.number().nullish(),FormulaKind:z.string().nullish(),ApplyMultiplierOnEarlyClaim:z.boolean().nullish()}).passthrough(),VP=z.object({ElapsedSeconds:z.number().nullish(),Reward:_e.nullish()}).passthrough(),NP=z.object({Tiers:z.array(VP).nullish(),TierMode:z.string().nullish(),BelowFirstTierReward:_e.nullish()}).passthrough(),jP=z.object({RequiredValue:z.number().nullish(),Reward:_e.nullish()}).passthrough(),_P=z.object({Reward:_e.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough(),WP=z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(jP).nullish(),Rate:_P.nullish()}).passthrough(),Vd=z.object({MetricsByID:z.record(z.string(),WP).nullish()}).passthrough(),QP=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:_e.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:ue.nullish(),Multipliers:Fd.nullish(),Gradation:NP.nullish(),RunStats:Vd.nullish()}).passthrough(),KP=z.object({Choices:z.array(QP).nullish(),OfferExpireSeconds:z.number().nullish(),ClaimExpireSeconds:z.number().nullish()}).passthrough(),HP=z.object({Chance:z.number().nullish(),RequiredOutcome:z.string().nullish(),Reward:_e.nullish(),Tag:z.string().nullish()}).passthrough(),$P=z.object({OnPassStart:_e.nullish(),OnTileLanding:z.record(z.string(),_e).nullish(),OnAttack:z.record(z.string(),_e).nullish(),OnRaid:z.record(z.string(),_e).nullish(),OnBuild:_e.nullish(),OnStageComplete:_e.nullish(),OnAttackBonusDrops:z.array(HP).nullish(),ChanceTablesByID:z.record(z.string(),FP).nullish(),SpecialModesByID:z.record(z.string(),KP).nullish()}).passthrough(),Nd=z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:z.number().nullish(),MaxShields:z.number().nullish(),Buildings:z.array(Gd).nullish(),HeistGridBonusConfig:LP.nullish(),StageOperations:$P.nullish(),TileLandingMultiplier:Ld.nullish(),EconomyOverride:OP.nullish()}).passthrough(),JP=z.object({Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BoardTemplateID:z.string().nullish(),Buildings:z.array(Gd).nullish(),StageTemplateID:z.string().nullish(),CostMatrixTemplateID:z.string().nullish(),UnitValue:z.number().nullish(),Override:Nd.nullish()}).passthrough(),ZP=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(),YP=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(),zr=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(),UP).nullish(),StageTemplatesByID:z.record(z.string(),Nd).nullish(),StagesByLevel:z.record(z.string(),JP).nullish(),SoftCurrencyID:z.string().nullish(),ProceduralEconomy:MP.nullish(),Dice:zP.nullish(),Bots:wP.nullish(),Targeting:ZP.nullish(),BotRaids:YP.nullish()}).passthrough(),XP=z.object({IsActive:z.boolean().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AnchorUtc:c.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(),Be).nullish(),GrandPrize:H.nullish()}).passthrough(),wr=z.object({Board:zr.nullish(),CommunityChest:XP.nullish()}).passthrough(),jd=z.object({AttackerGainByOutcome:z.record(z.string(),ce).nullish()}).passthrough(),eI=z.object({TargetUserID:z.string().nullish(),IsBot:z.boolean().nullish(),PublicData:Oe.nullish(),TargetBuildingStates:z.array(vP).nullish(),TargetHasShield:z.boolean().nullish(),TargetStageLevel:z.number().nullish(),RaidRewardPreview:jd.nullish()}).passthrough(),tI=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:_e.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:ue.nullish(),Multipliers:Fd.nullish(),RunStats:Vd.nullish()}).passthrough(),iI=z.object({ModeID:z.string().nullish(),Choices:z.array(tI).nullish()}).passthrough(),sI=z.object({GroupID:z.string().nullish(),Delta:_.nullish(),NewProgress:_.nullish(),MaxProgress:_.nullish(),UnlockedMilestoneIDs:z.array(z.string()).nullish(),Completed:z.boolean().nullish()}).passthrough(),_d=z.object({UsedMultiplier:z.number().nullish(),Steps:z.number().nullish(),DiceValues:z.array(z.number()).nullish(),OldPosition:z.number().nullish(),NewPosition:z.number(),CyclesCompletedDelta:_.nullish(),LandedTileType:z.string().nullish(),Operation:M.nullish(),Inventory:K.nullish(),ActionRequired:z.string().nullish(),ActionData:eI.nullish(),SpecialModeOffer:iI.nullish(),CommunityChestContribution:sI.nullish()}).passthrough(),Wd=z.object({Outcome:z.string().nullish(),IsBotTarget:z.boolean().nullish(),BuildingIndexHit:z.number().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:bt.nullish()}).passthrough(),qa=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(TP).nullish(),HeistVariantTag:z.string().nullish(),IsJackpot:z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish(),DualResult:bt.nullish(),RaidRewardPreview:jd.nullish()}).passthrough(),Qd=z.object({BuiltIndex:z.number(),NewLevel:z.number().nullish(),StageComplete:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish(),Operation:M.nullish(),Inventory:K.nullish()}).passthrough(),Kd=z.object({Mode:z.union([z.string(),z.number()]).nullish(),Operation:M.nullish(),Inventory:K.nullish(),DurationSeconds:z.number().nullish(),StartedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish()}).passthrough(),Hd=z.object({AdViewsUsed:z.number().nullish(),RolledMultiplier:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),RemainingAdViews:z.number().nullish()}).passthrough(),nI=z.object({MetricID:z.string().nullish(),ReachedTierIndex:z.number().nullish(),RequiredValue:z.number().nullish(),RewardUnits:z.number().nullish()}).passthrough(),$d=z.object({FinalMultiplier:z.number().nullish(),AdViewsUsed:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),IsEarlyClaim:z.boolean().nullish(),ReachedTierIndex:z.number().nullish(),Operation:M.nullish(),Inventory:K.nullish(),AcceptedRunStats:z.record(z.string(),z.number()).nullish(),RunStatAwards:z.array(nI).nullish(),RunStatsClamped:z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),rI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Jd=z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),oI={Active:"Active",Left:"Left",Replaced:"Replaced"},aI=z.enum(["Active","Left","Replaced"]).catch("Active"),lI=z.object({CurrentProgress:_.nullish(),MaxProgress:_.nullish()}).passthrough(),uI=z.object({UserID:z.string().nullish(),PublicData:Oe.nullish(),IsBot:z.boolean().nullish(),ContributionPoints:_.nullish(),MilestoneClaims:z.record(z.string(),ul).nullish(),GrandPrizeClaimed:z.boolean().nullish(),MemberStatus:aI.nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),Zd=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),RoundIndex:z.number().nullish(),Members:z.array(uI).nullish(),SharedProgress:lI.nullish(),Status:Jd.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:z.number().nullish()}).passthrough(),cI=z.object({GroupID:z.string().nullish(),RoundIndex:z.number().nullish(),FinalStatus:Jd.nullish(),GrandPrizeReceived:z.boolean().nullish(),FinishedAtUtc:c.nullish()}).passthrough(),pI=z.object({ActiveGroupID:z.string().nullish(),ActiveRoundIndex:z.number().nullish(),History:z.array(cI).nullish()}).passthrough(),Yd=z.object({ServerTimeUtc:c.nullish(),UserState:pI.nullish(),ActiveGroup:Zd.nullish(),SecondsRemaining:_.nullish()}),Xd=z.object({ServerTimeUtc:c.nullish(),Group:Zd.nullish(),SecondsRemaining:_.nullish()}),Ba=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:K.nullish()}),em=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),qe={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 hI={Mesh:"Mesh",Host:"Host"},La=z.enum(["Mesh","Host"]).catch("Mesh"),dI={ServerRelay:"ServerRelay",P2P:"P2P"},Ga=z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),mI={Public:"Public",Private:"Private"},fI=z.enum(["Public","Private"]).catch("Public"),gI={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},yI=z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),tm=z.object({Urls:z.string().nullish(),Username:z.string().nullish(),Credential:z.string().nullish()}).passthrough(),RI=z.object({Enabled:z.boolean().nullish()}).passthrough(),im=z.object({SystemState:RI.nullish(),DefaultTopology:La.nullish(),AllowCreatorTopologyOverride:z.boolean().nullish(),DefaultChatMode:Ga.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(tm).nullish()}).passthrough(),CI=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(),SI=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),Topology:La.nullish(),ChatMode:Ga.nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),MemberCount:z.number().nullish(),CreatedAt:z.number().nullish()}).passthrough(),xI=z.object({Seq:z.number().nullish(),Type:yI.nullish(),FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Kind:z.string().nullish(),Payload:z.string().nullish(),Ts:z.number().nullish()}).passthrough(),Ui=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),OwnerUserID:z.string().nullish(),Topology:La.nullish(),ChatMode:Ga.nullish(),Visibility:fI.nullish(),Status:z.string().nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Voice:z.boolean().nullish(),Members:z.array(CI).nullish(),IceServers:z.array(tm).nullish(),Seq:z.number().nullish(),BannedUserIDs:z.array(z.string()).nullish()}).passthrough(),sm=z.object({Removed:z.boolean().nullish(),Banned:z.boolean().nullish()}).passthrough(),nm=z.object({WasBanned:z.boolean().nullish()}).passthrough(),Fa=z.object({Closed:z.boolean().nullish(),NewHostUserID:z.string().nullish()}).passthrough(),rm=z.object({Rooms:z.array(SI).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}).passthrough(),om=z.object({Envelopes:z.array(xI).nullish(),MaxSeq:z.number().nullish()}).passthrough(),Mr=z.object({Seq:z.number().nullish()}).passthrough(),He={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 Va=z.object({TitleCustomData:kr.nullish(),Character:Qs.nullish(),Item:Wn.nullish(),Currency:bn.nullish(),Store:ms.nullish(),Lootbox:Pa.nullish(),Quest:_i.nullish(),TimedEvent:ws.nullish(),Leaderboard:Gs.nullish(),Season:Ns.nullish(),Reward:va.nullish(),Collection:yr.nullish(),Craft:ka.nullish(),DealOffer:qo.nullish(),Premium:xa.nullish(),TimedBoost:Ir.nullish(),CoopEvent:en.nullish(),GameLoop:wr.nullish(),Match:ta.nullish(),Experiment:Sh.nullish(),Blockchain:Ho.nullish(),Marketplace:oa.nullish(),Multiplayer:im.nullish(),UserCustomData:fn.nullish(),Referral:wa.nullish(),Localization:zh.nullish(),Analytics:uh.nullish(),Social:Hc.nullish(),PlatformBridge:$c.nullish()}).passthrough();var Xt={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Or=class extends B{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(Xt.GetTitlePublicConfiguration,e,Va)}getTitlePublicConfigurationExcept(e){return this.send(Xt.GetTitlePublicConfigurationExcept,e,Va)}getCurrencyDefinitions(e){return this.send(Xt.GetCurrencyDefinitions,e,bn)}getItemDefinitions(e){return this.send(Xt.GetItemDefinitions,e,Wn)}getServerTime(e){return this.send(Xt.GetServerTime,e,Ee)}};var Er=class extends B{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(qe.GetGameLoops,e,wr)}getBoardDefinition(e,t=false){return this.send(qe.GetBoardDefinition,e,zr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(qe.GetBoardDefinitionForLevel,e,zr,{silent:t})}getUserBoardState(e){return this.send(qe.GetUserBoardState,e,Bd)}boardLoopRoll(e){return this.send(qe.BoardLoopRoll,e,_d)}boardLoopAttack(e){return this.send(qe.BoardLoopAttack,e,Wd)}boardLoopRaid(e){return this.send(qe.BoardLoopRaid,e,qa)}boardLoopRaidFast(e){return this.send(qe.BoardLoopRaidFast,e,qa)}boardLoopBuild(e){return this.send(qe.BoardLoopBuild,e,Qd)}boardSpecialChoose(e){return this.send(qe.BoardSpecialChoose,e,Kd)}boardSpecialApplyMultiplier(e){return this.send(qe.BoardSpecialApplyMultiplier,e,Hd)}boardSpecialClaim(e){return this.send(qe.BoardSpecialClaim,e,$d)}getCommunityChestState(e){return this.send(qe.GetCommunityChestState,e,Yd)}joinOrCreateCommunityChest(e){return this.send(qe.JoinOrCreateCommunityChest,e,Xd)}claimCommunityChestMilestone(e){return this.send(qe.ClaimCommunityChestMilestone,e,Ba)}claimCommunityChestGrandPrize(e){return this.send(qe.ClaimCommunityChestGrandPrize,e,Ba)}leaveCommunityChest(e){return this.send(qe.LeaveCommunityChest,e,em)}};var DI={Live:"Live",Latest:"Latest",Specific:"Specific"},PI={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},II=z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),vI={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"},TI=z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),kI=z.object({Level:II,Message:z.string().nullish(),Data:Ut.nullish()}),AI=z.object({Error:TI,Message:z.string().nullish(),StackTrace:z.string().nullish()}),am=z.object({FunctionName:z.string().nullish(),Revision:z.number().nullish(),FunctionResult:Ut.nullish(),FunctionResultTooLarge:z.boolean().nullish(),Logs:z.array(kI).nullish(),LogsTooLarge:z.boolean().nullish(),ExecutionTimeSeconds:z.number().nullish(),APIRequestsIssued:z.number().nullish(),Error:AI.nullish()}),Na={Execute:"Execute"};var Ur=class extends B{constructor(e){super(e,"CloudCode");}execute(e){return this.send(Na.Execute,e,am)}};var qr=class extends B{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Ke.GetDefinitions,e,yp)}getUserState(e){return this.send(Ke.GetUserState,e,Rp)}depositToken(e){return this.send(Ke.DepositToken,e,Cp)}depositNFT(e){return this.send(Ke.DepositNFT,e,Sp)}requestTokenWithdrawal(e){return this.send(Ke.RequestTokenWithdrawal,e,xp)}requestNFTWithdrawal(e){return this.send(Ke.RequestNFTWithdrawal,e,bp)}getTransactionHistory(e){return this.send(Ke.GetTransactionHistory,e,Dp)}retryWithdrawal(e){return this.send(Ke.RetryWithdrawal,e,Pp)}confirmWithdrawal(e){return this.send(Ke.ConfirmWithdrawal,e,Ip)}donateToDeveloper(e){return this.send(Ke.DonateToDeveloper,e,Yo)}donateToUsersPool(e){return this.send(Ke.DonateToUsersPool,e,Yo)}getPlayAccess(e){return this.send(Ke.GetPlayAccess,e,fp)}confirmPlayAccess(e){return this.send(Ke.ConfirmPlayAccess,e,Lt)}};var Br=class extends B{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Ae.GetDefinitions,e,Gp)}getGroupedOffers(e){return this.send(Ae.GetGroupedOffers,e,Fp)}getOffersByItem(e){return this.send(Ae.GetOffersByItem,e,aa)}getOffer(e){return this.send(Ae.GetOffer,e,Vp)}getBuyOrders(e){return this.send(Ae.GetBuyOrders,e,aa)}getMyState(e){return this.send(Ae.GetMyState,e,An)}getHistory(e){return this.send(Ae.GetHistory,e,jp)}createListing(e){return this.send(Ae.CreateListing,e,wi)}cancelListing(e){return this.send(Ae.CancelListing,e,at)}buy(e){return this.send(Ae.Buy,e,at)}marketBuy(e){return this.send(Ae.MarketBuy,e,at)}marketSell(e){return this.send(Ae.MarketSell,e,at)}createAuction(e){return this.send(Ae.CreateAuction,e,wi)}placeBid(e){return this.send(Ae.PlaceBid,e,Np)}claimAuction(e){return this.send(Ae.ClaimAuction,e,at)}createBuyOrder(e){return this.send(Ae.CreateBuyOrder,e,wi)}cancelBuyOrder(e){return this.send(Ae.CancelBuyOrder,e,at)}fillBuyOrder(e){return this.send(Ae.FillBuyOrder,e,at)}createDirectTrade(e){return this.send(Ae.CreateDirectTrade,e,wi)}respondDirectTrade(e){return this.send(Ae.RespondDirectTrade,e,at)}cancelDirectTrade(e){return this.send(Ae.CancelDirectTrade,e,at)}claimBack(e){return this.send(Ae.ClaimBack,e,at)}};var Lr=class extends B{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(He.CreateRoom,e,Ui)}joinRoom(e){return this.send(He.JoinRoom,e,Ui)}leaveRoom(e,t=false){return this.send(He.LeaveRoom,e,Fa,{keepalive:t})}listRooms(e){return this.send(He.ListRooms,e,rm)}getRoom(e){return this.send(He.GetRoom,e,Ui)}closeRoom(e){return this.send(He.CloseRoom,e,Fa)}poll(e){return this.send(He.Poll,e,om)}sendSignal(e){return this.send(He.SendSignal,e,Mr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(He.ClaimHost,e,Ui)}kickMember(e){return this.send(He.KickMember,e,sm)}unbanMember(e){return this.send(He.UnbanMember,e,nm)}sendChat(e){return this.send(He.SendChat,e,Mr)}setMemberState(e){return this.send(He.SetMemberState,e,Mr)}};var zI={Free:"Free",Price:"Price",Holding:"Holding"},ja=z.enum(["Free","Price","Holding"]).catch("Free"),wI={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},MI=z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),OI={All:"All",Any:"Any"},EI=z.enum(["All","Any"]).catch("All"),UI={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},qI=z.enum(["Public","Unlisted","Friends"]).catch("Public"),BI={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},LI=z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),GI={Purchase:"Purchase",Free:"Free",Holding:"Holding"},um=z.enum(["Purchase","Free","Holding"]).catch("Free"),FI={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},VI={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},NI=z.enum(["Creator","License","Free","Holding"]).catch("License"),jI=z.object({Type:si.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),Amount:z.number().nullish(),MinLevel:z.number().nullish()}).passthrough(),_I=z.object({Requirements:z.array(jI).nullish(),Match:EI.nullish(),Mode:MI.nullish()}).passthrough(),WI=z.object({OptionID:z.string().nullish(),Mode:ja.nullish(),Price:ce.nullish(),Holding:_I.nullish()}).passthrough(),QI=z.object({AllowedMimeTypes:z.array(z.string()).nullish(),MaxBytes:z.number().nullish(),MaxCount:z.number().nullish(),Required:z.boolean().nullish()}).passthrough(),KI=z.object({DisplayName:z.string().nullish(),Enabled:z.boolean().nullish(),Files:z.record(z.string(),QI).nullish(),ThumbnailRequired:z.boolean().nullish(),AllowedAccessModes:z.array(ja).nullish(),PricePolicy:kn.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ue.nullish(),TagVocabulary:z.array(z.string()).nullish(),MaxPublishedPerPlayer:z.number().nullish(),DailyPublishCap:z.number().nullish()}).passthrough(),HI=z.object({Allowed:z.array(zi).nullish(),MaxRequirements:z.number().nullish()}).passthrough(),$I=z.object({AutoHideReportThreshold:z.number().nullish(),RequireApproval:z.boolean().nullish(),BlockedTerms:z.array(z.string()).nullish()}).passthrough(),JI=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(),ZI=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Schedule:fe.nullish(),Gate:Z.nullish(),Order:z.number().nullish()}).passthrough(),YI=z.object({Enabled:z.boolean().nullish(),Gate:Z.nullish(),Schedule:fe.nullish(),ContentTypes:z.record(z.string(),KI).nullish(),PricePolicy:kn.nullish(),Commission:ra.nullish(),HoldingPolicy:HI.nullish(),Moderation:$I.nullish(),Limits:JI.nullish(),Featured:z.array(ZI).nullish()}).passthrough(),XI=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(),ei=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),CreatorUserID:z.string().nullish(),IsOfficial:z.boolean().nullish(),CreatorPublicData:Oe.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:qI.nullish(),Access:z.array(WI).nullish(),Status:LI.nullish(),ModerationNote:z.string().nullish(),Stats:XI.nullish(),Revision:z.number().nullish(),ParentContentID:z.string().nullish(),FileCount:z.number().nullish(),TotalBytes:z.number().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),PublishedAt:c.nullish(),IsMine:z.boolean().nullish(),Owned:z.boolean().nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish()}).passthrough(),ev=z.object({OptionID:z.string().nullish(),Mode:ja.nullish(),Available:z.boolean().nullish()}).passthrough(),cm=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(),pm=z.object({Definitions:YI.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish(),CanPublish:z.record(z.string(),z.boolean()).nullish(),Collections:z.array(cm).nullish()}).passthrough(),Gr=z.object({Items:z.array(ei).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),hm=z.object({Content:ei.nullish(),AccessState:z.array(ev).nullish(),CanDownload:z.boolean().nullish()}).passthrough(),dm=z.object({Collection:cm.nullish(),Items:z.array(ei).nullish()}).passthrough(),mm=z.object({CreatorUserID:z.string().nullish(),PublicData:Oe.nullish(),PublishedCount:z.number().nullish(),FollowerCount:z.number().nullish(),IsFollowing:z.boolean().nullish(),Items:z.array(ei).nullish()}).passthrough(),lm=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(),fm=z.object({ContentID:z.string().nullish(),Revision:z.number().nullish(),Uploads:z.array(lm).nullish(),ThumbnailUpload:lm.nullish(),ExpiresAt:c.nullish()}).passthrough(),gm=z.object({Content:ei.nullish(),Resources:M.nullish()}).passthrough(),_a=z.object({Content:ei.nullish()}).passthrough(),ym=z.object({ContentID:z.string().nullish(),OptionID:z.string().nullish(),Source:um.nullish(),AlreadyOwned:z.boolean().nullish(),AccessActive:z.boolean().nullish(),Settlement:bt.nullish(),Resources:M.nullish(),CommissionTaken:ce.nullish()}).passthrough(),tv=z.object({Role:z.string().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish()}).passthrough(),Rm=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),Revision:z.number().nullish(),AccessVia:NI.nullish(),Files:z.array(tv).nullish(),ThumbnailUrl:z.string().nullish(),ExpiresAt:c.nullish()}).passthrough(),iv=z.object({ContentID:z.string().nullish(),Source:um.nullish(),OptionID:z.string().nullish(),PricePaid:ce.nullish(),AcquiredAt:c.nullish(),Content:ei.nullish()}).passthrough(),Cm=z.object({Licenses:z.array(iv).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),We={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 Fr=class extends B{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(We.GetDefinitions,e,pm)}browse(e){return this.send(We.Browse,e,Gr)}getContent(e){return this.send(We.GetContent,e,hm)}getCollection(e){return this.send(We.GetCollection,e,dm)}getCreatorProfile(e){return this.send(We.GetCreatorProfile,e,mm)}beginUpload(e){return this.send(We.BeginUpload,e,fm)}publish(e){return this.send(We.Publish,e,gm)}updateContent(e){return this.send(We.UpdateContent,e,_a)}unpublish(e){return this.send(We.Unpublish,e,_a)}getMyContent(e){return this.send(We.GetMyContent,e,Gr)}acquire(e){return this.send(We.Acquire,e,ym)}getDownload(e){return this.send(We.GetDownload,e,Rm)}getMyLicenses(e){return this.send(We.GetMyLicenses,e,Cm)}getMyFavorites(e){return this.send(We.GetMyFavorites,e,Gr)}};var Vr=class extends B{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,$p,"defs")}get(e){return this.sendKeyed("Get",e,ua,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Zp,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,ca,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Yp,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,pa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,pa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Xp,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,th,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,eh,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,ih,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,Jp,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,sh,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,ua,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,ca,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Nr=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e$1){this.settings=$a(e$1),this.emitter=new Ci,this.platform=e$1.platform??new e,this.clientPlatform=e$1.clientPlatform??al(),this.acquisition=new jt(this.platform),this.acquisition.capture(),this.playtime=new Si(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 Zi({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 ts(this.emitter),this.cache=new ss(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 ns(this.platform.storage,this.settings.titleID),this.api={authentication:new Fn(this),user:new Nn(this),currency:new jn(this),item:new Qn(this),store:new Kn(this),purchase:new Zn(this),lootbox:new er(this),reward:new tr(this),quest:new ar(this),tutorial:new ir(this),communityMarketing:new sr(this),chat:new nr(this),push:new rr(this),localization:new or(this),timedEvent:new lr(this),leaderboard:new ur(this),season:new cr(this),premium:new pr(this),character:new hr(this),match:new dr(this),craft:new fr(this),ai:new gr(this),collection:new Rr(this),coopEvent:new Cr(this),dealOffer:new Sr(this),referral:new xr(this),mailbox:new br(this),social:new Dr(this),timedBoost:new vr(this),userCustomData:new Tr(this),titleCustomData:new Ar(this),title:new Or(this),gameLoop:new Er(this),cloudCode:new Ur(this),blockchain:new qr(this),marketplace:new Br(this),multiplayer:new Lr(this),workshop:new Fr(this),dataCollections:new Vr(this),analytics:new Ln(this),experiment:new Gn(this)},this.userService=new us(this),this.cache.attachState(this.userService),this.auth=new rs(this),this.currency=new ps(this),this.item=new hs(this),this.store=new gs(this),this.purchase=new ys(this),this.checkout=new Rs(this),this.lootbox=new Cs(this),this.reward=new Ss(this),this.quest=new zs(this),this.tutorial=new bs(this),this.communityMarketing=new Ds(this),this.chat=new vs(this),this.push=new Ts(this),this.localization=new As(this),this.timedEvent=new Os(this),this.leaderboard=new Fs(this),this.season=new js(this),this.premium=new _s(this),this.character=new Ks(this),this.match=new Hs(this),this.craft=new $s(this),this.ai=new Zs(this),this.collection=new Ys(this),this.coopEvent=new tn(this),this.dealOffer=new rn(this),this.referral=new on(this),this.mailbox=new un(this),this.social=new hn(this),this.timedBoost=new dn(this),this.userCustomData=new gn(this),this.titleCustomData=new yn(this),this.title=new Rn(this),this.gameLoop=new Cn(this),this.cloudCode=new Sn(this),this.blockchain=new Pn(this),this.marketplace=new zn(this),this.multiplayer=new wn(this),this.workshop=new Mn(this),this.dataCollections=new En(this),this.analytics=new qn(this),this.experiments=new Bn(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 jr=class{ctx;constructor(e){this.ctx=new Nr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Ft(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 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 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 nv(o){return new jr(o)}var Sm="idos_sso",xm="state",Wa="idos:sso:state",rv="https://idosgames.com/sso/",ov=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],av=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function lv(){if(typeof window>"u")return false;let{origin:o}=window.location;return ov.includes(o)||av.test(o)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function uv(){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(Sm);if(!t)return null;let i=e.get(xm)??"",s=mv();return gv(e),fv(),s&&i!==s?null:{code:t,state:i}}function cv(o){if(typeof window>"u")return;let e=o.returnTo??pv(),t=hv();dv(t);let i=new URL(o.ssoUrl??rv);i.searchParams.set("title",o.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function pv(){let{origin:o,pathname:e,search:t}=window.location;return `${o}${e}${t}`}function hv(){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 dv(o){try{window.sessionStorage.setItem(Wa,o);}catch{}}function mv(){try{return window.sessionStorage.getItem(Wa)}catch{return null}}function fv(){try{window.sessionStorage.removeItem(Wa);}catch{}}function gv(o){o.delete(Sm),o.delete(xm);let e=o.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var yv={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 Rv(o,e="Something went wrong. Please try again."){return o?yv[o]??o:e}function Cv(o,e){return !!o?.Claims?.[e]?.ClaimedAt}function Sv(o){let e=o?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function xv(o,e){return o?.Claims?.[e]?.PremiumTiers??[]}function Dm(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*bm(o,t,1);break;case "TableAbsolute":r=bm(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 bv(o,e,t=1){return Dm(o,1,e,t)}function Dv(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 Pm(o.Points).length>0;default:return o.MinResult!=null||o.MaxResult!=null}}function Pv(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 Pm(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 bm(o,e,t){let i=Pm(o.Points);if(i.length===0)return t;let s=null,n=null,r=null;for(let p of i)(r===null||p.AtStep>r.AtStep)&&(r=p),p.AtStep<=e&&(s===null||p.AtStep>=s.AtStep)&&(s=p),p.AtStep>e&&(n===null||p.AtStep<n.AtStep)&&(n=p);if(s===null)return t;if(n===null){let p=o.TailGrowthRate??0;return p===0?r.Value:r.Value*Math.pow(1+p,e-r.AtStep)}switch(o.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+p*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let d=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+d*(n.Value-s.Value)}let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,p)}default:return s.Value}}var Iv={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Qa=z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),vv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Tv=z.enum(["Top","Bottom","Left","Right"]).catch("Top"),kv=z.object({PlacementID:z.string().nullish(),Type:Qa.nullish(),Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),CreditsRewarded:z.number().nullish(),AllowedProviderIDs:z.array(z.string()).nullish()}).passthrough(),Av=z.object({DefaultCreditsPerView:z.number().nullish(),MaxCreditsBalance:z.number().nullish(),DailyCreditEarnCap:z.number().nullish(),DailyViewCap:z.number().nullish(),MinSecondsBetweenViews:z.number().nullish()}).passthrough(),zv=z.object({CooldownSeconds:z.number().nullish(),MinSessionTimeBeforeFirstSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),wv=z.object({Enabled:z.boolean().nullish(),Position:Tv.nullish(),RefreshIntervalSeconds:z.number().nullish()}).passthrough(),Mv=z.object({Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish()}).passthrough(),Ov=z.object({MaxImpressionsPerHour:z.number().nullish(),MaxImpressionsPerDay:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),Ev=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),DisableInterstitials:z.boolean().nullish(),DisableBanners:z.boolean().nullish(),DisableAppOpen:z.boolean().nullish()}).passthrough(),Uv=z.object({RequirePersonalizedAdsConsent:z.boolean().nullish(),RequireTrackingConsent:z.boolean().nullish(),CurrentPolicyVersion:z.string().nullish(),RegulatedRegions:z.array(z.string()).nullish()}).passthrough(),qv=z.object({RequireServerSideVerification:z.boolean().nullish(),PendingRequestTtlSeconds:z.number().nullish(),MaxPendingRequestsPerUser:z.number().nullish()}).passthrough(),Bv=z.object({AndroidUnitID:z.string().nullish(),IosUnitID:z.string().nullish(),WebUnitID:z.string().nullish(),Type:Qa.nullish()}).passthrough(),Lv={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},Gv=z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),Fv=z.object({ProviderID:z.string().nullish(),Kind:Gv.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(),Bv).nullish()}).passthrough();z.object({Enabled:z.boolean().nullish(),Placements:z.record(z.string(),kv).nullish(),Providers:z.record(z.string(),Fv).nullish(),RewardedVideo:Av.nullish(),Interstitial:zv.nullish(),Banner:wv.nullish(),AppOpen:Mv.nullish(),FrequencyCapping:Ov.nullish(),PremiumAdReductions:z.array(Ev).nullish(),Consent:Uv.nullish(),Verification:qv.nullish()}).passthrough();var Vv=z.object({RewardedVideoCredit:z.number().nullish(),TotalEarned:z.number().nullish(),TotalSpent:z.number().nullish()}).passthrough(),Nv=z.object({PlacementID:z.string().nullish(),LastShownAt:c.nullish(),LastCompletedAt:c.nullish(),TotalImpressions:z.number().nullish(),TotalCompletions:z.number().nullish(),ConsecutiveFailures:z.number().nullish()}).passthrough(),jv=z.object({Date:c.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(),_v=z.object({SessionID:z.string().nullish(),SessionStartAt:c.nullish(),Impressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish()}).passthrough(),Wv=z.object({PersonalizedAdsConsent:z.boolean().nullish(),TrackingConsent:z.boolean().nullish(),PolicyVersion:z.string().nullish(),Region:z.string().nullish(),ConsentGivenAt:c.nullish(),ConsentRevokedAt:c.nullish()}).passthrough(),Qv=z.object({RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),Type:Qa.nullish(),IssuedAt:c.nullish(),ExpiresAt:c.nullish(),CreditsToAward:z.number().nullish()}).passthrough(),Kv=z.object({InvalidSsvCount:z.number().nullish(),OrphanCompletions:z.number().nullish(),FastCompletions:z.number().nullish(),LastFlaggedAt:c.nullish()}).passthrough();z.object({Credits:Vv.nullish(),Placements:z.record(z.string(),Nv).nullish(),Daily:jv.nullish(),Session:_v.nullish(),LastImpressionAt:c.nullish(),LastInterstitialAt:c.nullish(),LastRewardedAt:c.nullish(),LastAppOpenAt:c.nullish(),TotalImpressions:z.number().nullish(),TotalRewardedCompletions:z.number().nullish(),AdsDisabledUntil:c.nullish(),Consent:Wv.nullish(),PendingRequests:z.record(z.string(),Qv).nullish(),FraudFlags:Kv.nullish(),UpdatedAt:c.nullish()}).passthrough();
|
|
2
|
+
export{Ge as AIAction,uR as AIErrorCode,Qt as AIGenerationStatus,qt as AIModality,jt as AcquisitionCapture,Lv as AdProviderKind,Iv as AdType,fa as AnalyticsAction,Zx as AnalyticsDropReason,ma as AnalyticsEventNaming,Ct as AnalyticsLimits,IP as AttackOutcome,ze as AuthType,Ue as AuthenticationAction,Gt as AutomaticEvent,vv as BannerPosition,Ke as BlockchainAction,oS as BlockchainNetworkType,cp as BlockchainOperationCategory,fS as BlockchainTransactionStatus,cS as BlockchainTransactionType,jS as BodyPart,fP as BoostWindowKind,Ne as CharacterAction,Qe as ChatAction,Xg as ChatAuthorType,Zg as ChatBlockedTermAction,Qg as ChatChannelType,$g as ChatDirectAudience,Kg as ChatPartitioning,ty as ChatReportReason,mt as ClientPlatform,Na as CloudCodeAction,vI as CloudCodeErrorCode,PI as CloudCodeLogLevel,DI as CloudCodeRevisionSelection,je as CollectionAction,ux as CommissionSink,oI as CommunityChestMemberStatus,rI as CommunityChestStatus,DD as CommunityCreatorStatus,Jt as CommunityMarketingAction,ID as CommunityMetricKind,xD as CommunityParticipationMode,PD as CommunityPayoutCurrencyKind,$C as ConversionRateMode,ht as CoopEventAction,xR as CoopGroupStatus,bR as CoopMemberStatus,mr as CraftAction,LD as CraftInputSelectionMode,qD as CraftOutputLevelMode,FD as CraftOutputLevelOverflow,UD as CraftType,Di as CreditsConfirmationStatus,Pg as CreditsError,xn as CurrencyAction,HC as CurrencyStatus,ut as CurrencyType,hf as CurveInterpolation,cf as CurveShape,Tt as CustomDataBucket,GC as CustomDataValueType,UC as CustomDataWriter,Ha as DEFAULT_BASE_URL,Ax as DataAccessMode,Ix as DataCollectionKind,Bx as DataCollectionSchemaMode,Qx as DataCollectionsAction,Ox as DataCounterKind,Tx as DataFieldType,kx as DataFieldVisibility,Ux as DataOwnerDeletedPolicy,wx as DataRefKind,FR as DealComparisonOperator,MR as DealNodeRuntimeStatus,GR as DealNodeType,yt as DealOfferAction,wR as DealOfferActivationStatus,Un as EVENT_NAME_PATTERN,gI as EnvelopeType,Ym as EventTokenType,Ra as ExperimentAction,lb as ExperimentGoalKind,wC as FRIENDS_FROM_PLATFORM,xb as FodderSelectionMode,Cb as FodderValuationMode,RC as FriendActionStatus,CC as FriendSource,qe as GameLoopAction,jr as IDosGamesClient,Eb as IapProductType,Hb as IapPurchaseStatus,Zm as IapStoreValues,_n as ItemAction,pS as KycStatus,dS as KycTier,Ve as LeaderboardAction,Vn as LocalizationAction,mb as LocalizationMissingKeyMode,Xn as LootboxAction,uC as MAILBOX_COUNTER_CAP,et as MailboxAction,sC as MailboxCategory,lC as MailboxErrors,nC as MailboxLetterSource,oC as MailboxRewardModule,Tn as MarketGoodsType,lx as MarketOfferStatus,ax as MarketOfferType,Ae as MarketplaceAction,Rt as MatchAction,_S as MatchStatus,He as MultiplayerAction,dI as MultiplayerChatMode,hI as MultiplayerTopology,_g as OFFER_NOT_IN_ROTATION,OC as PlatformFriendsMode,MC as PlatformProfileMode,PS as PlayAccessMode,pb as PlayerExperimentStatus,Si as PlaytimeTracker,Ht as PremiumAction,$t as PurchaseAction,pi as PushAction,It as PushPermissionState,fy as PushTopic,dy as PushTransport,pt as QuestAction,Df as QuestObjectiveSource,If as QuestPrerequisiteMode,Sf as QuestStatus,DP as RaidMode,Vt as ReferralAction,Li as ResourceEntryType,At as RewardAction,mI as RoomVisibility,lR as SKIN_ALREADY_OWNED,zo as SKIN_SLOT,Xm as ScheduleMode,Et as SeasonAction,Ce as SocialAction,PC as SocialContentStatus,xC as SocialEntityType,IC as SocialInboxVerb,bC as SocialReactionKind,DC as SocialReportReason,PP as SpecialChoiceMode,Pt as StoreAction,Tg as StoreRotationMode,Mb as StoreType,Yt as TimedBoostAction,rP as TimedBoostStackingPolicy,ot as TimedEventAction,Xt as TitleAction,Ei as TitleCustomDataAction,RP as TitleDataBucket,yP as TitleDataScope,QD as TradeOfferStatus,gS as TransactionDirection,nt as TutorialAction,Ff as TutorialBoardAction,Bf as TutorialFlowStatus,nf as TutorialGateMode,Uf as TutorialRestartPolicy,Gf as TutorialScriptModule,Of as TutorialStepCompletionMode,Ci as TypedEmitter,lt as UserAction,dt as UserCustomDataAction,xS as WalletGateBalanceSource,lS as WalletLinkType,zI as WorkshopAccessMode,VI as WorkshopAccessVia,We as WorkshopAction,BI as WorkshopContentStatus,OI as WorkshopHoldingMatch,wI as WorkshopHoldingMode,GI as WorkshopLicenseSource,FI as WorkshopSort,UI as WorkshopVisibility,Rv as authErrorText,cv as beginSsoRedirect,Sv as claimedMilestoneIDs,nv as createIDosGamesClient,oi as cryptoShortfallFromError,bv as curveMultiplier,ug as defineView,ph as describeUserAgent,Dm as evaluateCurve,xv as grantedPremiumTiers,Ii as isAIGenerationTerminal,Dv as isCurveConfigured,Cv as isMilestoneClaimed,Zy as isReservedSlot,lv as isSsoAvailable,Dn as normalizeBlockchainCategory,cR as parseAIErrorCode,uv as readSsoCodeFromUrl,Pv as roundAmount,Hx as where,Dg as zPaymentProof,jl as zPriceOption,ue as zPriceOptions};
|