@idosgames/core 0.24.2 → 0.25.0
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 +10 -0
- package/dist/{VoiceController-7H1grlKL.d.cts → VoiceController-CAqhPZ15.d.cts} +36 -7
- package/dist/{VoiceController-B2m4oYGx.d.ts → VoiceController-CNq9Lm0f.d.ts} +36 -7
- package/dist/chunk-YSPGQWAB.js +2 -0
- package/dist/index-BKjfSSxG.d.ts +188 -0
- package/dist/index-DMmtsWR2.d.cts +188 -0
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/platform/index.cjs +2 -2
- package/dist/platform/index.d.cts +2 -184
- package/dist/platform/index.d.ts +2 -184
- package/dist/platform/index.js +1 -1
- package/dist/realtime/index.d.cts +2 -2
- package/dist/realtime/index.d.ts +2 -2
- package/package.json +1 -1
- package/dist/chunk-J3S34XCF.js +0 -2
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var zod=require('zod'),Ht=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Ht__default=/*#__PURE__*/_interopDefault(Ht);var Ti=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 Zm(){let r=new Map;return {get:e=>r.get(e)??null,set:(e,t)=>{r.set(e,t);},remove:e=>{r.delete(e);}}}function dl(){return Ym()??Zm()}function Ym(){try{let r=globalThis.localStorage;if(!r)return null;let e="__idos_probe__";return r.setItem(e,"1"),r.removeItem(e),{get:t=>{try{return r.getItem(t)}catch{return null}},set:(t,i)=>{try{r.setItem(t,i);}catch{try{r.removeItem(t);}catch{}}},remove:t=>{try{r.removeItem(t);}catch{}}}}catch{return null}}var hl="https://api.idosgames.com";function ml(r){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??hl).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??dl(),locale:r.locale??Xm(),appVersion:r.appVersion??""}}function Xm(){try{return globalThis.navigator?.language??""}catch{return ""}}var ri=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,t){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,t);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},oi=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,t){this.map.set(e,t);}remove(e){this.map.delete(e);}};function ai(){return globalThis.Telegram?.WebApp??null}function G(){return crypto.randomUUID()}var fl="idos_device_id",li=class{storage;constructor(e=new ri){this.storage=e;}getPlatform(){return ai()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=ai()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=ai()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(fl);return e||(e=G(),this.storage.setString(fl,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let t=ai();if(t?.openTelegramLink){t.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let t=ai();if(t?.openInvoice){t.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let t=globalThis;typeof t.showAd=="function"&&await t.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var so="idos_acq",gl=["gclid","fbclid","ttclid","msclkid","yclid"],ef=["ref","r"],tf=["ref_","ref-","ref=","r_","r-"];var Kt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();sf(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=of(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(so);}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=Cl(Rl(t));if(i)return i}return ji(t)}readFromEnvironment(){let e={},t=Rl(this.platform.getFullURL());Wt(e,"UtmSource",t.get("utm_source")),Wt(e,"UtmMedium",t.get("utm_medium")),Wt(e,"UtmCampaign",t.get("utm_campaign")),Wt(e,"UtmTerm",t.get("utm_term")),Wt(e,"UtmContent",t.get("utm_content")),Wt(e,"ClaimToken",t.get("idos_click"));for(let R of gl){let B=t.get(R);if(B){e.ClickID=B;break}}let i=this.platform.getStartParameter()??"",s=rf(i);if(s){for(let R of nf)Wt(e,R,s.get(Sl[R])??null);for(let R of gl){let B=s.get(R);if(B){e.ClickID=B;break}}}let n=ji(s?s.get("ref")??s.get("r")??"":i),o=Cl(t),p=n||o;p&&(e.ReferralCode=p,e.ChannelHint=n?"telegram":"query");let h=this.platform.getReferrer?.();return h&&(e.Referrer=h),e}read(){try{let e=this.platform.storage.getString(so);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(so,JSON.stringify(e));}catch{}}};function sf(r){return !!(r.UtmSource||r.UtmMedium||r.UtmCampaign||r.ClickID||r.Referrer||r.ReferralCode||r.ClaimToken)}function Wt(r,e,t){t&&(r[e]=t);}var yl="a1_",Sl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},nf=Object.keys(Sl);function rf(r){let e=(r||"").trim();if(!e.startsWith(yl))return null;let t=e.slice(yl.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),n=Uint8Array.from(s,h=>h.charCodeAt(0)),o=new TextDecoder().decode(n),p=new URLSearchParams(o);return [...p.keys()].length>0?p:null}catch{return null}}function Rl(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function Cl(r){for(let e of ef){let t=r.get(e);if(t)return ji(t)}return null}function ji(r){let e=(r||"").trim();if(!e)return null;for(let t of tf)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function of(r){let e=r||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var xl="idos_usage_pending",bl="idos_usage_session",Dl="idos_usage_closed_session",Pl="idos_usage_new_session",Il="idos_usage_last_activity",Ai=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(xl),this.currentSessionSeconds=this.readNumber(bl),this.pendingClosedSessionSeconds=this.readNumber(Dl),this.isNewSessionPending=this.readNumber(Pl)!==0;let e=this.readNumber(Il);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(xl,this.pendingSeconds),this.writeNumber(bl,this.currentSessionSeconds),this.writeNumber(Dl,this.pendingClosedSessionSeconds),this.writeNumber(Pl,this.isNewSessionPending?1:0),this.writeNumber(Il,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 ct={Virtual:"Virtual",Crypto:"Crypto"},ci=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),Wi={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},pi=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),ft={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Ki=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),af={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Qi=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),lf={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Hi=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),uf={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},ki=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),ke={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function Tl(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return vl(e);let t=r.cordova?.platformId;return t?vl(t):r.navigator?.userAgent??""?ft.Web:ft.Unknown}function vl(r){let e=r.toLowerCase();return e==="android"?ft.Android:e==="ios"?ft.Ios:e==="web"?ft.Web:ft.Unknown}function _(r){return {ok:true,data:r}}function u(r,e){return {ok:false,reason:r,error:e}}var a=u("unauthorized","Not logged in.");function cf(r){return r.ok}function pf(r){return !r.ok}var j=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="string"?Number(r):r;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(r)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="number"?String(r):r.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(r)}`}),zod.z.NEVER):t}),c=zod.z.string();var no=zod.z.object({Type:pi.nullish(),CurrencyID:zod.z.string().nullish(),Amount:j.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),df=zod.z.object({Type:Hi.nullish(),EntityID:zod.z.string()}),hf=zod.z.object({Address:df.nullish(),Amount:j.nullish(),Source:zod.z.string().nullish()}),pe=zod.z.object({Entries:zod.z.array(no).nullish(),EventTokens:zod.z.array(hf).nullish()}),Al=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:pe.nullish()}),H=zod.z.object({Standard:pe.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Al).nullish()}),bt=zod.z.object({Standard:pe.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(Al).nullish()}),M=zod.z.object({Grant:H.nullish(),Consume:bt.nullish()}),Dt=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:pe.nullish()});var mf=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),ff={Completed:"Completed",Started:"Started",StepReached:"StepReached"},gf=zod.z.object({FlowIDs:zod.z.array(zod.z.string()).nullish(),Mode:zod.z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:zod.z.string().nullish(),Negate:zod.z.boolean().nullish(),SkippedCountsAsCompleted:zod.z.boolean().nullish()}).passthrough(),Z=zod.z.object({Segments:zod.z.array(zod.z.string()).nullish(),MinPremiumTier:zod.z.number().nullish(),RequiredPremiumIDs:zod.z.array(zod.z.string()).nullish(),MinLevel:zod.z.number().nullish(),MaxLevel:zod.z.number().nullish(),Countries:zod.z.array(zod.z.string()).nullish(),RegisteredWithinDays:zod.z.number().nullish(),ActiveWithinDays:zod.z.number().nullish(),Experiment:mf.nullish(),Tutorial:gf.nullish(),Platforms:zod.z.array(Ki).nullish()}).passthrough();var Ce=zod.z.object({TotalCap:zod.z.number().nullish(),DailyCap:zod.z.number().nullish(),DailyWeightCap:zod.z.number().nullish(),PerActivationCap:zod.z.number().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish()}).passthrough();var yf=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Rf=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Cf=zod.z.object({AnchorUtc:zod.z.string().nullish(),MaxCycles:zod.z.number().nullish(),PauseBetweenPhasesSec:zod.z.number().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish()}).passthrough();zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();var Sf=zod.z.object({Reset:zod.z.string().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:zod.z.string().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();zod.z.object({SourceType:zod.z.string().nullish(),TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var nt=zod.z.object({SourceType:zod.z.string().nullish(),BaseWeight:zod.z.number().nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish(),TileTypeFilter:zod.z.array(zod.z.string()).nullish(),TileIndexFilter:zod.z.array(zod.z.number()).nullish(),ChanceOutcomeFilter:zod.z.array(zod.z.string()).nullish(),OutcomeFilter:zod.z.array(zod.z.string()).nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Limits:Ce.nullish()}).passthrough(),ye=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:Rf.nullish(),Chain:Cf.nullish(),Cyclic:Sf.nullish(),ActivationTriggers:zod.z.array(nt).nullish(),Relative:yf.nullish()}).passthrough();var xf={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},bf=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Df={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Pf=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),If=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),_e=zod.z.object({Base:zod.z.number().nullish(),Shape:bf.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(If).nullish(),Interpolation:Pf.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var vf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:H.nullish()}).passthrough(),Tf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),ro=zod.z.object({Bundles:zod.z.array(vf).nullish(),Multipliers:zod.z.array(Tf).nullish()}).passthrough();var Af=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),$i=zod.z.object({Source:Af.nullish(),SourceKey:zod.z.string().nullish(),Curve:_e.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:pe.nullish(),ExcludeRewards:pe.nullish()}).passthrough(),kl=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),Be=zod.z.object({MilestoneID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredProgress:zod.z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:ro.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),di=zod.z.object({Milestones:zod.z.record(zod.z.string(),Be).nullish()}).passthrough();var K=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var kf=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Qt=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxBalance:zod.z.number().nullish(),MaxPerGrant:zod.z.number().nullish(),DailyEarnCap:zod.z.number().nullish(),BurnOnEventEnd:zod.z.boolean().nullish(),BurnConversion:kf.nullish()}).passthrough();var wf=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),wl=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:wf.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Q=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),wl).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var Te=r=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:r.nullish()}),gt=r=>zod.z.object({ServerTimeUtc:c,Items:zod.z.array(Te(r)),Resources:M.nullish(),Inventory:Q.nullish()});var zf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},zl=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Mf=zod.z.object({}).passthrough().transform(r=>r),Of=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:c.nullish(),CycleEndUtc:c.nullish(),PointsTotalEarned:j.nullish(),PointsCurrent:j.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),oo=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:j.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:zl}),Ml=zod.z.object({State:Mf.nullish(),PointsTracks:zod.z.record(zod.z.string(),Of).nullish()}),ao=zod.z.object({ServerTimeUtc:c,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:zl.nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),lo=zod.z.object({ServerTimeUtc:c,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:j.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Ol=zod.z.object({ServerTimeUtc:c,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),El=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(oo).nullish()}),Ul=zod.z.array(Te(ao)),ql=zod.z.array(Te(lo)),Ef={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Uf=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),qf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Lf=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),Ll=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:Uf.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(nt).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),uo=zod.z.object({Milestones:K.nullish(),Linking:K.nullish(),Availability:K.nullish(),Reward:K.nullish(),Objectives:K.nullish()}).passthrough(),Bf=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Bl=zod.z.object({CycleIDs:zod.z.array(zod.z.string()).nullish(),GroupID:zod.z.string().nullish(),PhaseIDs:zod.z.array(zod.z.string()).nullish(),RequiredQuestIDs:zod.z.array(zod.z.string()).nullish(),PrerequisiteMode:Lf.nullish()}).passthrough(),Gl=zod.z.object({Schedule:ye.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),Fl=zod.z.object({Grant:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Gf=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Bf.nullish(),Linking:Bl.nullish(),Availability:Gl.nullish(),Objectives:zod.z.record(zod.z.string(),Ll).nullish(),Reward:Fl.nullish(),Presets:uo.nullish()}).passthrough(),Ff=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),_f=zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Gate:Z.nullish(),Milestones:zod.z.record(zod.z.string(),Be).nullish(),Presets:uo.nullish(),PointsToken:Qt.nullish()}).passthrough(),Vf=zod.z.object({Milestones:zod.z.record(zod.z.string(),di).nullish(),Linking:zod.z.record(zod.z.string(),Bl).nullish(),Availability:zod.z.record(zod.z.string(),Gl).nullish(),Reward:zod.z.record(zod.z.string(),Fl).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Ll)).nullish()}).passthrough(),Nf=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ye.nullish(),Milestones:zod.z.record(zod.z.string(),Be).nullish(),Gate:Z.nullish(),PointsToken:Qt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),Ff).nullish(),Phases:zod.z.record(zod.z.string(),_f).nullish(),Presets:uo.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Zi=zod.z.object({Cycles:zod.z.record(zod.z.string(),Nf).nullish(),Quests:zod.z.record(zod.z.string(),Gf).nullish(),Presets:Vf.nullish()}).passthrough(),dt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var jf={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},Wf=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),Kf={Never:"Never",OnRequest:"OnRequest",Always:"Always"},Qf=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),Hf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},$f=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),Jf={GameLoop:"GameLoop"},Zf={Raid:"Raid",Attack:"Attack"},Yf=zod.z.object({Title:zod.z.string().nullish(),TitleKey:zod.z.string().nullish(),Body:zod.z.string().nullish(),BodyKey:zod.z.string().nullish(),AnchorID:zod.z.string().nullish(),HighlightTarget:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),UiHint:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Xf=zod.z.object({Mode:Wf.nullish(),Triggers:zod.z.array(nt).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),eg=zod.z.object({Grant:H.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),tg=zod.z.object({TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),RandomActionType:zod.z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),ig=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:tg.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),sg=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),co=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:Yf.nullish(),Completion:Xf.nullish(),Effects:eg.nullish(),Script:ig.nullish(),Policy:sg.nullish()}).passthrough(),ng=zod.z.object({DisplayName:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),Description:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),_l=zod.z.object({Schedule:ye.nullish(),Gate:Z.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:nt.nullish()}).passthrough(),Vl=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:Qf.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Nl=zod.z.object({Grant:H.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),rg=zod.z.object({Availability:K.nullish(),Policy:K.nullish(),Reward:K.nullish(),Steps:K.nullish()}).passthrough(),og=zod.z.object({FlowID:zod.z.string().nullish(),Identity:ng.nullish(),Availability:_l.nullish(),Policy:Vl.nullish(),Steps:zod.z.record(zod.z.string(),co).nullish(),Reward:Nl.nullish(),Presets:rg.nullish()}).passthrough(),ag=zod.z.object({BlockingFlowIDs:zod.z.array(zod.z.string()).nullish(),BlockedModules:zod.z.array(zod.z.string()).nullish(),BlockedActions:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),BlockBeforeStart:zod.z.boolean().nullish(),SkipLiftsBlock:zod.z.boolean().nullish()}).passthrough(),lg=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:ag.nullish()}).passthrough(),ug=zod.z.object({Availability:zod.z.record(zod.z.string(),_l).nullish(),Policy:zod.z.record(zod.z.string(),Vl).nullish(),Reward:zod.z.record(zod.z.string(),Nl).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),co)).nullish()}).passthrough(),jl=zod.z.object({Flows:zod.z.record(zod.z.string(),og).nullish(),Settings:lg.nullish(),Presets:ug.nullish()}).passthrough(),cg=zod.z.object({}).passthrough().transform(r=>r),Wl=zod.z.object({FlowID:zod.z.string(),Status:$f,CurrentStepID:zod.z.string().nullish(),CurrentStep:co.nullish(),TotalSteps:zod.z.number(),CompletedSteps:zod.z.number(),CanSkip:zod.z.boolean(),RewardClaimed:zod.z.boolean(),RewardPending:zod.z.boolean(),VariantID:zod.z.string().nullish()}).passthrough(),Yi=zod.z.object({State:cg.nullish(),Flows:zod.z.array(Wl).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Et=zod.z.object({Flow:Wl.nullish()}).passthrough(),Kl=zod.z.object({FlowID:zod.z.string().nullish(),Granted:M.nullish()}).passthrough(),Ql=zod.z.array(Te(Et)),Hl=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),rt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Xi(r){return Array.isArray(r)?r.filter(e=>e!==null).map(Xi):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,Xi(t)])):r}var es=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var ts=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function $l(r){return r===429||r>=500&&r<=599}function is(r,e=Math.random){let t=Math.min(500*Math.pow(2,r-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Ut(r){return new Promise(e=>setTimeout(e,r))}var Jl=15e3;async function Zl(r){try{let t=JSON.parse(await r.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(r.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Yl(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function Xl(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var po=15,eu=1e3,ss=class{constructor(e=po,t=()=>Date.now(),i=Ut){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]>=eu;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(eu-(e-this.starts[0])+5);}}};var pg=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function mi(r){if(!r)return null;let e=pg.exec(r);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new Ht__default.default(i),o=new Ht__default.default(s),p=o.minus(Ht__default.default.max(n,0));return p.lte(0)?null:{currencyID:t,required:o.toNumber(),available:n.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var dg=12e3,hg=new Set(["RelatedEntityID"]);function mg(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[i,s]of Object.entries(e))hg.has(i)||(t[i]=s);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var fg=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(oo).nullish(),TutorialProgress:zod.z.array(Hl).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),ns=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new ts;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new es(e.throttleMs),this.pacer=new ss(e.maxRequestsPerSecond??po),this.clientPlatform=e.clientPlatform??ft.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??mg(e,t);if(!this.throttler.tryAcquire(n))return u("throttled","Throttled");if(!this.inflight.add(n))return u("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,p=JSON.stringify(t),h=s.ticket??null,R=s.silent??!1,B=s.timeoutMs??dg,re=s.autoRetry??!0,xe=!1,le=!1,fe=0;for(;;){let xt;s.keepalive||await this.pacer.take();try{xt=await this.doFetch(o,p,h,B,s.keepalive??!1);}catch{if(re&&fe<3){fe++,await Ut(is(fe));continue}return this.connectionFailure("Internet Connection Error",R)}let Ze=xt.status;if(Ze>=200&&Ze<300){let oe=!le&&this.cryptoTopUpHandler!==null,ve=await this.parseSuccess(xt,i,R,e,oe);if(!ve.ok&&oe){let de=mi(ve.error);if(de){if(le=!0,await this.runTopUp(de))continue;R||this.emitter.emit("error:global",ve.error);}}return ve}if(Ze===401){if(!xe&&this.sessionRefreshHandler){xe=!0;let oe=null;try{oe=await this.sessionRefreshHandler();}catch{oe=null;}if(oe){h=oe;continue}}return this.emitter.emit("auth:unauthorized",void 0),u("unauthorized","Unauthorized")}if($l(Ze)){let oe=Ze===429?await Zl(xt):null;if(oe!==null&&oe>Jl)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(oe/1e3)} s`,R);if(re&&fe<3){fe++,await Ut(oe!==null?Yl(oe):Ze===429?Xl(fe):is(fe));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Ze})`,R)}let Ii="";try{Ii=await xt.text();}catch{}if(Ze===409&&/operation in progress/i.test(Ii)&&re&&fe<3){fe++,await Ut(is(fe));continue}return this.handleWebError(Ii,Ze,R)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let o=new AbortController,p=setTimeout(()=>{o.abort();},s);try{let h={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(h.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:h,signal:o.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,i,s,n=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",i)}let p;try{p=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",i)}let h=fg.safeParse(p);if(!h.success)return this.globalError("Malformed response envelope",i);if(!h.data.Success){let le=h.data.Error??"Server returned Success=false",fe=n&&mi(le);return !i&&!fe&&this.emitter.emit("error:global",le),u("server",le)}let R=h.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:h.data.StateEpoch??null,versions:R});let B=h.data.QuestProgress;B&&B.length>0&&this.emitter.emit("quest:systemProgress",B);let re=h.data.TutorialProgress;re&&re.length>0&&this.emitter.emit("tutorial:systemProgress",re);let xe=t.safeParse(h.data.Data);if(!xe.success){let le=t.safeParse(Xi(h.data.Data));le.success&&(xe=le);}if(!xe.success){let le=`Validation error (${s}): ${xe.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",le),i||this.emitter.emit("error:global",le),u("validation",le)}return _(xe.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),u("server","PLAY_ACCESS_REQUIRED");s=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),u("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),u("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),u("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function fi(r){return (typeof r=="string"?r:r.toISOString()).slice(0,10)}function wi(r){return `${fi(r)}T00:00:00.000Z`}function tu(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function iu(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function fo(r,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;r.InventoryV2??={};let n=r.InventoryV2,o=i.toISOString(),p=new Map,h=new Map,R=new Map,B=new Map,re=new Map,xe=new Map,le=new Map,fe=new Map,xt=e.Grant?.PremiumTiers??[],Ze=xt.length;for(let oe=0;;oe++){let ve,de;if(oe===0)ve=e.Grant?.Standard?.Entries,de=false;else if(oe-1<Ze)ve=xt[oe-1]?.Resources?.Entries,de=false;else if(oe===1+Ze)ve=e.Consume?.Standard?.Entries,de=true;else break;if(ve)for(let ue of ve){if(ue.Type==null)continue;let he=Math.max(0,ue.Amount??0);if(!(he<=0))switch(ue.Type){case "VirtualCurrency":{if(!ue.CurrencyID)continue;let me=de?h:p;me.set(ue.CurrencyID,(me.get(ue.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!ue.CurrencyID)continue;let me=de?B:R;me.set(ue.CurrencyID,(me.get(ue.CurrencyID)??new Ht__default.default(0)).plus(he));break}case "Item":{if(!ue.ItemID)continue;let me=yg(t,ue.CatalogID,ue.ItemID),De=(me?me.IsStackable??true:true)?de?xe:re:de?fe:le;De.set(ue.ItemID,(De.get(ue.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||h.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let oe of new Set([...p.keys(),...h.keys()])){let ve=p.get(oe)??0,de=h.get(oe)??0,ue=ve-de,he=n.VirtualCurrencies[oe];he?(he.Amount+=ue,he.UpdatedAt=o,he.Daily&&fi(he.Daily.PeriodStartUtc)===fi(i)?(he.Daily.Earned+=ve,he.Daily.Spent+=de):he.Daily={PeriodStartUtc:wi(i),Earned:ve,Spent:de}):n.VirtualCurrencies[oe]={Amount:ue,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:wi(i),Earned:ve,Spent:de}};}}if(s.ccChanged=R.size>0||B.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let oe of new Set([...R.keys(),...B.keys()])){let ve=R.get(oe)??new Ht__default.default(0),de=B.get(oe)??new Ht__default.default(0),ue=ve.minus(de),he=n.CryptoCurrencies[oe];he?(he.Amount=new Ht__default.default(he.Amount).plus(ue).toString(),he.UpdatedAt=o):n.CryptoCurrencies[oe]={Amount:ue.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(s.itemsChanged=re.size>0||xe.size>0||le.size>0||fe.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let oe=n.UnstackableItems,ve=new Set([...re.keys(),...xe.keys(),...le.keys(),...fe.keys()]);for(let de of ve){let ue=(re.get(de)??0)-(xe.get(de)??0),he=(le.get(de)??0)-(fe.get(de)??0),me=ue+he,st=n.Items[de];st?(ue!==0&&(st.StackableAmount+=ue),he!==0&&(st.UnstackableAmount+=he),me!==0&&(st.TotalAmount+=me)):n.Items[de]={StackableAmount:Math.max(0,ue),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,me)};}for(let[de,ue]of fe){if(ue<=0)continue;let he=Object.values(oe).filter(me=>me.ItemID===de&&me.EquippedSlot==null&&(me.ExpiresAt==null||new Date(me.ExpiresAt)>i)).sort(gg).slice(0,ue).map(me=>me.ItemInstanceID);for(let me of he)delete oe[me];}for(let[de,ue]of le){let he=Rg(t,de);for(let me=0;me<ue;me++){let st=G();oe[st]={ItemInstanceID:st,ItemID:de,CatalogID:he,RemainingUses:1,AcquiredAt:o};}}}r.EventToken??={};let Ii=r.EventToken;for(let oe=0;;oe++){let ve,de;if(oe===0)ve=e.Grant?.Standard?.EventTokens,de=false;else if(oe-1<Ze)ve=xt[oe-1]?.Resources?.EventTokens,de=false;else if(oe===1+Ze)ve=e.Consume?.Standard?.EventTokens,de=true;else break;if(!(!ve||ve.length===0))for(let ue of ve){let he=ue.Address;if(!he||he.Type==null)continue;let me=ue.Amount??0;if(me<=0)continue;let st=Cg(Ii,he.Type);if(!st)continue;let De=st[he.EntityID];De||(De={},st[he.EntityID]=De),De.Balance??={Current:0,TotalEarned:0,TotalSpent:0},De.Daily??={Date:wi(i),TotalEarned:0},De.Meta??={};let vi=ue.Source&&ue.Source.length>0?ue.Source:"CustomAction";de?(De.Balance.Current-=me,De.Balance.TotalSpent+=me):(De.Balance.Current+=me,De.Balance.TotalEarned+=me,fi(De.Daily.Date)!==fi(i)&&(De.Daily={Date:wi(i),TotalEarned:0}),De.Daily.TotalEarned+=me,De.Daily.EarnedBySource??={},De.Daily.EarnedBySource[vi]=(De.Daily.EarnedBySource[vi]??0)+me,De.Daily.TriggersBySource??={},De.Daily.TriggersBySource[vi]=(De.Daily.TriggersBySource[vi]??0)+1,De.Daily.LastTriggerBySource??={},De.Daily.LastTriggerBySource[vi]=o,De.Meta.JoinedAtUtc||(De.Meta.JoinedAtUtc=o),De.Meta.LastEarnedAtUtc=o),s.tokensChanged=true;}}return s}function gg(r,e){return r.AcquiredAt!==e.AcquiredAt?r.AcquiredAt<e.AcquiredAt?-1:1:r.ItemInstanceID===e.ItemInstanceID?0:r.ItemInstanceID<e.ItemInstanceID?-1:1}function yg(r,e,t){let i=r?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let n=s.Items?.[t];if(n)return n}}}function Rg(r,e){let t=r?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function Cg(r,e){switch(e){case "TimedEvent":return r.TimedEvent??={};case "Quest":return r.Quest??={};case "Leaderboard":return r.Leaderboard??={};case "CoopEvent":return r.CoopEvent??={};case "Season":return r.Season??={};default:return null}}function su(r,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},n=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let h of Object.values(s))h?.ItemID&&o.add(h.ItemID);for(let h of n){let R=r[h]?.ItemID;R&&o.add(R);}if(o.size===0)return i;let p=h=>n.has(h)||h in s;if(e){for(let[h,R]of Object.entries(e))h in r||p(h)||R&&o.has(R.ItemID)&&i.drop.push(h);for(let[h,R]of Object.entries(r))h in e||p(h)||R&&o.has(R.ItemID)&&(i.restore[h]=R);}return i}function go(r,e){return r===e||r.startsWith(`${e}:`)}var os=class r{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){r.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];r.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){r.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let s=fo(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let n=this.currentState,o={...n.InventoryV2?.UnstackableItems??{}},p=fo(n,e,i,s),h=su(o,n.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),B=t?.RemovedInstanceIDs??[],re=h.drop.length>0||Object.keys(h.restore).length>0||R.length>0||B.length>0;if(re){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let xe=n.InventoryV2.UnstackableItems;for(let le of h.drop)delete xe[le];for(let[le,fe]of Object.entries(h.restore))xe[le]=fe;for(let[le,fe]of R)xe[le]=fe;for(let le of B)delete xe[le];}this.emitResourceChanges(p,re);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof Ht__default.default?t:new Ht__default.default(t),p=s===void 0?new Ht__default.default(0):s instanceof Ht__default.default?s:new Ht__default.default(s),h=i??new Date().toISOString(),R=n[e];R?(R.Amount=new Ht__default.default(R.Amount).plus(o).toString(),p.isZero()||(R.Frozen=new Ht__default.default(R.Frozen??0).plus(p).toString()),R.UpdatedAt=h):n[e]={Amount:o.toString(),Frozen:p.toString(),CreatedAt:h,UpdatedAt:h},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,n=s[e];n||(n={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=n),n.TotalPurchases+=t,n.LastPurchasedAt=i,i>=n.DailyResetUtc?(n.DailyPurchases=t,n.DailyResetUtc=tu(i)):n.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let n=new Date().toISOString();for(let o of t)o.RuleID&&(s.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:n});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let n=s.Cycles[t];if(!n)return;n.Quests??={};let o=n.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let n=s.PermanentQuests[e]??={QuestID:e,Status:i};n.Status=i,i==="Claimed"&&(n.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,n=t[s]??={};n.Balance??={Current:0,TotalEarned:0,TotalSpent:0},n.Balance.Current=i.PointsCurrent??0,n.Balance.TotalEarned=i.PointsTotalEarned??0,n.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(n.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let n=s.Steps[i.StepID]??={StepID:i.StepID};n.Progress=i.Progress,i.Completed&&(n.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let n=t.Cycles[i.CycleID];if(!n)continue;n.Quests??={},s=n.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let n=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};n.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(n.Completed=true,n.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(go(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[n,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((s?n!==s:!go(n,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let n=this.activeEventsCache?.ActiveEvents;if(n)for(let o of n)o.Type!==e||o.TimedEventID!==t||s&&o.TokenEntityID&&o.TokenEntityID!==s||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,s){if(!e)return;let n=this.ensureLeaderboardProgress(e);(n.ScoreCycleVersion??0)<s&&(n.ScoreEarnedThisCycle=0,n.ClaimedMilestoneIDs=[],n.BracketID=null),n.CurrentScore=t,n.ScoreEarnedThisCycle=(n.ScoreEarnedThisCycle??0)+i,n.ScoreCycleVersion=s,n.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let s=false;for(let n of Object.values(i))for(let o of Object.values(n.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[s,n]of Object.entries(e.ChangedInstances??{}))t[s]=n,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(i)){let n=i[s];n&&n.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,s,n){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,p={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")o.Private??={},o.Private[t]=p;else if(e==="Public")o.Public??={},o.Public[t]=p;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let s=i.BuildingStates.find(n=>n.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},n=s.PendingWithdrawals??[];t.size>0&&(n=n.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!n.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(n=[...n,i]),s.PendingWithdrawals=n;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var as=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,i]of Object.entries(e))this.sections.has(t)||this.sections.set(t,i);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let i=this.config?.[e];return i??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var ls=class{user;config;constructor(e){this.user=new os(e),this.config=new as;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Sg(r){return r}var xg=0,bg=1500,Dg=3,cs=class{constructor(e,t,i=null,s="",n="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=s;this.loginMode=n;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return _(void 0);let i=Date.now(),s=[],n=[];for(let h of new Set(e)){let R=this.rules.get(h);if(R&&(t?.force||R.needsServer(i))){s.push(this.runRule(h,R));continue}(t?.force||!this.state.isStateFresh(h,t?.maxAgeMs))&&n.push(h);}let p=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(_(void 0))])).find(h=>!h.ok);return p&&!p.ok?p:_(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();},xg),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):_(void 0),n=s.ok?_(void 0):s;for(let o of t)o(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=us(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let R=this.fresh(s,i?.maxAgeMs);if(R)return _(R.data);let B=this.loginFailures.get(s);if(B)return this.loginFailures.delete(s),B;let re=this.inflight.get(s);if(re)return re}let n=this.generation.get(s)??0,o=Date.now(),h=t().then(R=>{if(!R.ok)return R;let B=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:R.data,storedAt:B,expiresAt:yo(e,R.data,B)}),R;let re=this.entries.get(s);if(re&&re.storedAt>=o)return R;let xe=yo(e,R.data,B);return this.entries.set(s,{data:R.data,storedAt:B,expiresAt:Math.min(xe??1/0,B+bg)}),R}).finally(()=>{this.inflight.get(s)===h&&this.inflight.delete(s);});return this.inflight.set(s,h),h}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let s=t.Key?t.Key:void 0,n=us(i.view,s);if(!t.Success){this.loginFailures.set(n,u("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(n),i.apply(o.data,s),this.put(i.view,o.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let n=nu({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>Dg||this.used.set(nu(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(us(e,t))?.data}put(e,t,i){this.register(e);let s=us(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:yo(e,t,n)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===i||s.startsWith(`${i}|`))&&this.drop(s);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let s=Date.now();if(!(i.expiresAt!==null&&s>=i.expiresAt)&&!(t!==void 0&&s-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(s=>t.has(s))&&this.invalidate(i);}};function us(r,e){return e===void 0?r.key:`${r.key}|${e}`}function nu(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function yo(r,e,t){let i=r.expiresAt?.(e)??null,s=r.ttlMs!==void 0?t+r.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var ps=class{constructor(e,t){this.storage=e;this.authTypeKey=`Saved_AuthType_${t}`,this.emailKey=`Saved_Auth_Email_${t}`,this.passwordKey=`Saved_Auth_Password_${t}`,this.refreshTokenKey=`Saved_Auth_RefreshToken_${t}`;}storage;authTypeKey;emailKey;passwordKey;refreshTokenKey;get lastAuthType(){let e=this.storage.getString(this.authTypeKey);return Pg(e)?e:ke.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(r){return r!==null&&Object.values(ke).includes(r)}var Pt=["https://idosgames.com","https://www.idosgames.com"];function ru(r){return r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r.endsWith(".localhost")}function ds(r){if(Pt.includes(r))return true;if(typeof window>"u"||!ru(window.location.hostname))return false;try{return ru(new URL(r).hostname)}catch{return false}}var ou="IDOS_PLATFORM_WALLET_ACK",au="PLATFORM_WALLET_UNAVAILABLE",Ig=5e3,vg=18e4;function Tg(){let r=[...Pt],e=window.location.ancestorOrigins?.[0];return e&&!r.includes(e)&&ds(e)&&r.push(e),r}function Ag(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function It(r,e,t,i={}){let s={ok:false,error:au,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(s);let n=window.parent;if(!n)return Promise.resolve(s);let o=Ag(),p=i.answerTimeoutMs??vg;return new Promise(h=>{let R=false,B,re=le=>{R||(R=true,window.removeEventListener("message",xe),clearTimeout(B),h(le));},xe=le=>{if(!ds(le.origin))return;let fe=le.data;if(!(!fe||fe.requestId!==o)){if(fe.type===ou){clearTimeout(B),B=setTimeout(()=>re({ok:false,error:"TIMEOUT",data:{}}),p);return}fe.type===e&&re({ok:fe.ok===true,error:typeof fe.error=="string"?fe.error:void 0,data:fe});}};B=setTimeout(()=>re(s),Ig),window.addEventListener("message",xe);for(let le of Tg())try{n.postMessage({type:r,requestId:o,...t},le);}catch{}})}var Ro={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},kg=30*6e4,wg=/^[a-z0-9]{8}-preview\.idos\.games$/,Co="idos:platformSignIn:declined:";function zg(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(wg.test(window.location.hostname.toLowerCase()))return false;let r=window.location.ancestorOrigins?.[0];if(r&&!Pt.includes(r))try{let e=new URL(r).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}async function So(r){let e=await It(Ro.request,Ro.response,{titleID:r,supports:["pgs"]},{answerTimeoutMs:kg}),t=e.data.ticket;if(e.ok&&typeof t=="string"&&t.length>0)return {ticket:t};let i=e.data.code;return e.ok&&typeof i=="string"&&i.length>0?{code:i}:{error:e.error??"no_code"}}function Mg(r){try{window.localStorage.setItem(Co+r,"1");}catch{}}function Og(r){try{window.localStorage.removeItem(Co+r);}catch{}}function Eg(r){try{return window.localStorage.getItem(Co+r)==="1"}catch{return false}}var Ug=8,qg=100,Lg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,lu=["GameLoop"];function Bg(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var hs=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=ke.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let s=this.authContext;if(!s)return a;let n=this.baseRequest();n.UserID=s.userID,n.ClientSessionTicket=s.clientSessionTicket,n.WalletAddress=e,n.NetworkID=t,i&&(n.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(n);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return a;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(ke.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return u("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ke.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(ke.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},_({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(ke.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?_(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(ke.Google)):i}async loginWithApple(e,t){if(!e?.trim())return u("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(ke.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(ke.Wallet)):n}async loginWithSsoCode(e){if(!e)return u("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.platform.getDeviceID(),t.Device=this.ctx.platform.getDeviceModel(),t.Platform=this.ctx.platform.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ke.iDosGames)):i}async loginWithPlatformGameTicket(e){if(!e)return u("client","Platform game ticket is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.PlatformGameTicket=e;let i=await this.ctx.api.authentication.resolvePlatformGameSession(t);return i.ok?(this.applyAuthContext(i.data),this.platformGameSession=true,this.fetchAndApplyClientState(ke.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!==ke.None?e:ke.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"):(Bg(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 ke.Email:return this.loginWithEmail(t,i);case ke.Device:case ke.None:return this.loginWithDeviceID();case ke.Telegram:return this.loginWithTelegram();default:return Promise.resolve(u("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;if(this.platformGameSession){this.refreshing=true;try{let t=await So(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let s=await this.ctx.api.authentication.resolvePlatformGameSession(i);return s.ok?(this.applyAuthContext(s.data),this.platformGameSession=!0,s.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==ke.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===ke.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&&Lg.test(e)}static isValidPasswordLength(e){return e.length>=Ug&&e.length<=qg}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=ke.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e){let t=await this.ctx.userService.getClientStateExcept(lu,lu);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",gi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${uu(t)}`:e&&e.length>0?`f:${uu(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 uu(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var cu="idos:loc",yi=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 `${cu}:${this.titleId}:${e}`}versionsKey(){return `${cu}:${this.titleId}:versions`}};var Fg="idos:sec",ms=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 `${Fg}:${this.titleId}`}};var _g="idos:state",fs=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,s){if(!(!e||!t))try{let n={e:t,v:i,s};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}keyOf(e){return `${_g}:${this.titleId}:${e}`}};function Vg(r,e){if(!r)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return r;let i={};for(let[s,n]of Object.entries(r))t.has(s.toLowerCase())||(i[s]=n);return i}function xo(r,e,t,i){let s={...r??{}};if(!e||!t||!i)return s;for(let[n,o]of Object.entries(t))i[n]===o&&n in e&&(s[n]=e[n]);return s}function Ng(r){return {...r??{}}}function bo(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.StateEpoch:null}var gs=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=Vg(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let n=Object.keys(this.versions);this.reset(e),this.notify(n);}return}let i=Date.now(),s=[];for(let[n,o]of Object.entries(t)){let p=this.versions[n];p!==o&&(p!==void 0&&o===p+1?(this.versions[n]=o,this.confirmedAt[n]=i):(delete this.versions[n],delete this.confirmedAt[n]),s.push(n),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=Ng(t);let s=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=s;this.dirty=true;let n=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&n.add(o);this.notify([...n]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[n,o]of Object.entries(t??{}))this.versions[n]!==o&&s.push(n),this.versions[n]=o,this.confirmedAt[n]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var pu=u("server","Title configuration is unavailable (CDN and API both failed)."),ys=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),RelatedEntityID:G()}:null}get configCache(){return this.cache??=new gi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new yi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new ms(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new gs(new fs(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return a;let t=gi.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let n=await this.ctx.api.user.getClientState(e);if(!n.ok)return n;let o=await this.resolveTitleConfig(n.data,t,i,{Fields:e.TitleFields});return o==null?pu:(this.finishStateHandshake(n.data,s),await this.restoreSections(n.data.TitleConfigVersion,o),await this.applyClientState(n.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(n.data.Views),await this.applyLocalization(n.data.Localization),await this.flushState(s),n)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let n=this.stateStore.currentEpoch;n&&(e.KnownStateEpoch=n);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=xo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=bo(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 o=await this.fetchConfigFromApi(s);return o!=null?(n&&await this.configCache.write(t,n,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return a;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=gi.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let p=await this.ctx.api.user.getClientStateExcept(i);if(!p.ok)return p;let h=await this.resolveTitleConfig(p.data,s,n,{ExcludeFields:t??[]});return h==null?pu:(this.finishStateHandshake(p.data,o),await this.restoreSections(p.data.TitleConfigVersion,h),await this.applyClientState(p.data,h,e,t),this.ctx.cache.acceptLoginViews(p.data.Views),await this.applyLocalization(p.data.Localization),await this.flushState(o),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,o]of Object.entries(await this.sectionCache.read(e)))i[n]==null&&(s[n]=o);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((n,o)=>{i[n]!=null||o==null||(s[n]=o,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let n=await this.fetchLocalizationFromApi(t,s?.v??0);return n??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let n=s.data;if(n.NotModified)return null;let o=n.Entries??{},p=n.Version??0,h=n.Locale??e;return p>0&&await this.localizationCache.write(h,p,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):a}async getUserState(e){let t=this.baseRequest();if(!t)return a;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let n=xo(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let o=i.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([R,B])=>o[R]!==B||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(n,p);let h=bo(s.data);return h&&(this.stateStore.afterSliceRead(h,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let s=this.baseRequest();if(!s)return a;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 a;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return a;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,s){let n=i?.includes("GameLoop")===true,o=s?.includes("GameLoop")===true,p=n?this.ctx.data.user.state?.GameLoop:void 0,h=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let R=this.ctx.data.user.state;n&&R&&R.GameLoop==null&&(R.GameLoop=p);let B=this.ctx.data.config.titlePublicConfiguration;o&&B&&B.GameLoop==null&&(B.GameLoop=h),this.ctx.emitter.emit("user:clientStateReceived",e);}};var Cs=class{constructor(e){this.ctx=e;}ctx;async convert(e,t,i,s,n,o){if(!t)return u("client","SourceID is required.");if(!s)return u("client","TargetID is required.");if(n<=0)return u("client","Amount must be positive.");if(e===i&&t===s)return u("client","Source and target must differ.");if(e===ct.Crypto||i===ct.Crypto)return u("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return a;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(n)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${s}_${G()}`},h=await this.ctx.api.currency.convert(p);if(h.ok){let R=h.data,B={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(B,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return h}async cryptoConvert(e,t,i,s,n,o){let p=n instanceof Ht__default.default?n:new Ht__default.default(n);if(!t)return u("client","SourceID is required.");if(!s)return u("client","TargetID is required.");if(p.lte(0))return u("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return u("client","Source and target must differ.");if(e===ct.Virtual&&i===ct.Virtual)return u("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ct.Virtual&&!p.isInteger())return u("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:p.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${s}_${G()}`},R=await this.ctx.api.currency.cryptoConvert(h);if(R.ok){let B=R.data,re=[],xe=[];if(B.SourceType===ct.Virtual&&re.push({Type:"VirtualCurrency",CurrencyID:B.SourceID,Amount:Math.trunc(Number(B.SourceSpent))}),B.TargetType===ct.Virtual&&xe.push({Type:"VirtualCurrency",CurrencyID:B.TargetID,Amount:Math.trunc(Number(B.TargetCredited))}),re.length>0||xe.length>0){let le={Consume:re.length>0?{Standard:{Entries:re}}:null,Grant:xe.length>0?{Standard:{Entries:xe}}:null};this.ctx.data.user.applyResourceOperation(le,this.ctx.data.config.itemDefinitions);}B.SourceType===ct.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(B.SourceID,new Ht__default.default(B.SourceSpent).negated(),B.ServerTimeUtc),B.TargetType===ct.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(B.TargetID,new Ht__default.default(B.TargetCredited),B.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",B);}return R}};var Ss=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let s=e.trim();if(!s)return u("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${s}_${G()}`};t&&t.length>0&&(n.FodderInstanceIDs=[...t]);let o=await this.ctx.api.item.upgradeLevel(n);return o.ok&&(this.ctx.data.user.patchEquippedItemLevel(o.data.ItemInstanceID??s,o.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",o.data)),o}async upgradeLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let 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 du=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:bt.nullish(),AllowedPlatforms:zod.z.array(Ki).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ce=zod.z.record(zod.z.string(),du),jg=zod.z.object({Store:Qi,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var zi={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},Do=zod.z.object({ConfirmationID:zod.z.string(),Url:zod.z.string(),Status:zod.z.string(),PriceCredits:zod.z.number(),ExpiresAt:c}).passthrough(),hu=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),Wg={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"},Po=zod.z.object({ServerTimeUtc:c,OfferID:zod.z.string(),Count:zod.z.number(),Resources:M.nullish(),Inventory:Q.nullish(),CreditsConfirmation:Do.nullish()}),mu=zod.z.array(Te(Po)),Kg=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:c,LastPurchasedAt:c}),Qg=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:c}),fu=zod.z.object({Purchases:zod.z.record(zod.z.string(),Kg).nullish(),Rotations:zod.z.record(zod.z.string(),Qg).nullish()}).passthrough().transform(r=>r),vt=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),xs=zod.z.object({Schedule:ye.nullish(),Gate:Z.nullish()}).passthrough(),Hg={Fixed:"Fixed",Title:"Title",Player:"Player"},$g=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:Z.nullish()}).passthrough(),gu=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array($g).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),Jg=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Rotation:K.nullish()}).passthrough(),Zg=zod.z.object({SlotID:zod.z.string().nullish(),Identity:vt.nullish(),Availability:xs.nullish(),Rotation:gu.nullish(),Presets:Jg.nullish()}).passthrough(),Yg=zod.z.object({Identity:K.nullish(),Availability:K.nullish()}).passthrough(),Xg=zod.z.object({SectionID:zod.z.string().nullish(),Identity:vt.nullish(),Availability:xs.nullish(),Slots:zod.z.record(zod.z.string(),Zg).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:Yg.nullish()}).passthrough(),yu=zod.z.object({Sections:zod.z.record(zod.z.string(),Xg).nullish()}).passthrough(),ey=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Layout:K.nullish()}).passthrough(),ty=zod.z.object({StoreID:zod.z.string().nullish(),Identity:vt.nullish(),Availability:xs.nullish(),Layout:yu.nullish(),Presets:ey.nullish()}).passthrough(),Ru=zod.z.object({Options:ce.nullish(),CompareAt:zod.z.record(zod.z.string(),bt).nullish()}).passthrough(),Cu=zod.z.object({Grant:H.nullish()}).passthrough(),Su=zod.z.object({Schedule:ye.nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),iy=zod.z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish(),Availability:K.nullish()}).passthrough(),sy=zod.z.object({OfferID:zod.z.string().nullish(),Identity:vt.nullish(),Pricing:Ru.nullish(),Reward:Cu.nullish(),Availability:Su.nullish(),Presets:iy.nullish()}).passthrough(),ny=zod.z.object({Identity:zod.z.record(zod.z.string(),vt).nullish(),Availability:zod.z.record(zod.z.string(),xs).nullish(),Layout:zod.z.record(zod.z.string(),yu).nullish(),Rotation:zod.z.record(zod.z.string(),gu).nullish(),Pricing:zod.z.record(zod.z.string(),Ru).nullish(),Reward:zod.z.record(zod.z.string(),Cu).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Su).nullish()}).passthrough(),bs=zod.z.object({Stores:zod.z.record(zod.z.string(),ty).nullish(),StoreOffers:zod.z.record(zod.z.string(),sy).nullish(),Presets:ny.nullish()}).passthrough(),ry=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:c.nullish()}).passthrough(),oy=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:bt.nullish(),CompareAtCost:bt.nullish(),DiscountPercent:zod.z.number().nullish(),IsFree:zod.z.boolean(),IsAdPaid:zod.z.boolean(),IsStorePaid:zod.z.boolean(),IsCreditsPaid:zod.z.boolean().nullish(),CreditsPrice:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ay=zod.z.object({OfferID:zod.z.string(),Identity:vt.nullish(),PriceOptions:zod.z.array(oy).nullish(),Rewards:H.nullish(),State:ry.nullish()}).passthrough(),ly=zod.z.object({SlotID:zod.z.string(),Identity:vt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:c.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:ay.nullish()}).passthrough(),uy=zod.z.object({SectionID:zod.z.string(),Identity:vt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(ly).nullish()}).passthrough(),cy=zod.z.object({StoreID:zod.z.string(),Identity:vt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:c.nullish(),Sections:zod.z.array(uy).nullish()}).passthrough(),Ds=zod.z.object({ServerTimeUtc:c,Stores:zod.z.array(cy).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Tt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},py="OFFER_NOT_IN_ROTATION";var Io={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},dy=15*6e4,hy=/^[a-z0-9]{8}-preview\.idos\.games$/;function $t(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !hy.test(window.location.hostname.toLowerCase())}async function vo(r){let e=await It(Io.request,Io.response,{titleID:r.titleID,userID:r.userID,currencyID:r.currencyID,amount:r.amount},{answerTimeoutMs:dy});return e.ok?{ok:true}:{ok:false,error:e.error}}var To={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},my=10*6e4;function Ao(){return $t()}async function ko(r){let e=await It(To.request,To.response,{titleID:r.titleID,confirmationID:r.confirmationID},{answerTimeoutMs:my});return e.ok?{ok:true}:{ok:false,error:e.error}}var xu="Store",bu={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=null;for(let t of r.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},Ps=class{constructor(e){this.ctx=e;e.cache.bindLoginView(bu,{schema:Ds,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return u("client","OfferID is required.");if(t<1)return u("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return a;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}_${G()}`},o=await this.ctx.api.store.purchase(n);if(o.ok&&!o.data.CreditsConfirmation){let p=o.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return o}async purchaseWithCredits(e,t=1,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,o=()=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:n.ConfirmationID});if(Ao()){let R=await ko({titleID:this.ctx.settings.titleID,confirmationID:n.ConfirmationID});if(R.ok)return await o();if(R.error==="DECLINED")return u("server","CREDITS_CONFIRMATION_DECLINED");if(R.error==="NOT_ENOUGH_CREDITS")return u("server","NOT_ENOUGH_CREDITS")}i.onConfirmation?.(n);let p=Math.max(1e3,i.pollMs??2500),h=Date.parse(n.ExpiresAt)+6e4;for(;;){if(i.signal?.aborted)return u("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>h)return u("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(re=>setTimeout(re,p));let R=await this.getCreditsConfirmation(n.ConfirmationID);if(!R.ok)continue;let B=R.data.Status;if(B!==zi.Pending)return B===zi.Declined?u("server","CREDITS_CONFIRMATION_DECLINED"):B===zi.Expired?u("server","CREDITS_CONFIRMATION_EXPIRED"):await o()}}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):a}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):a}async purchaseBatch(e){if(!e||e.length===0)return u("client","purchases is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let 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(xu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(xu,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(bu,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let 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 a;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var Is=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?_(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return u("client","Receipt is required.");if(!this.ctx.auth.context)return a;let 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 u("client","productID is required.");if(!this.ctx.auth.context)return a;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 u("client","receipts is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let 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 Du=3,fy=700,vs=class{constructor(e){this.ctx=e;$t()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return mi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await vo({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<=Du;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===Du)break;await Ut(fy);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t)if(i?.Type===Wi.Purchase&&i.ProductID)return i.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t){if(i?.Type!==Wi.CryptoCurrency||!i.CurrencyID)continue;let s=Number(i.Amount??0);if(!(s>0))continue;let n=this.cryptoBalance(i.CurrencyID);return n>=s?null:{currencyID:i.CurrencyID,required:s,available:n,missing:s-n}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var Pu="Lootbox",Ts=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Pu,e);if(t){let n={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),_(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection(Pu,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s){if(!e)return u("client","LootboxID is required.");if(t<1)return u("client","Count must be at least 1.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,RelatedEntityID:`lootbox_${e}_${i??"default"}_${G()}`},o=await this.ctx.api.lootbox.open(n);if(o.ok){let p=o.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 o}};var wo="Reward";function zo(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var As=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(wo)?.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(wo,e);if(t){let n={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),_(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(wo,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${G()}`},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(!zo(e))return u("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${G()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let 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(!zo(e))return u("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let 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(!zo(e))return u("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let 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 ks="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"]},ws=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Iu,{schema:Yi,apply:i=>this.applyUserTutorialState(i)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(ks)?.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(ks,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ks,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 a;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${G()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return u("client","FlowID is required.");if(!t||t.length===0)return u("client","stepIDs is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${G()}`},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 u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${G()}`},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 u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:s},o=await t(n);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,s){let n=e?.trim(),o=t?.trim();if(!n)return u("client","FlowID is required.");if(!o)return u("client","StepID is required.");if(!this.ctx.auth.context)return a;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:o};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let h=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,R=await i(p);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(n,o,h,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(ks)?.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 zs=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return a;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return u("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return u("client","campaignID is required.");if(!t)return u("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return a;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 a;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Ee=zod.z.object({Username:zod.z.string().nullish(),Country:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Premium:zod.z.boolean().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BoardRank:zod.z.number().nullish()}).passthrough();var gy={Global:"Global",Announcement:"Announcement",Group:"Group"},Tu=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),yy={None:"None",Language:"Language",Region:"Region"},Ry=zod.z.enum(["None","Language","Region"]).catch("None"),Cy={Anyone:"Anyone",Friends:"Friends"},Sy=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),xy={Reject:"Reject",Mask:"Mask"},by=zod.z.enum(["Reject","Mask"]).catch("Reject"),Dy={Player:"Player",Publisher:"Publisher",System:"System"},Py=zod.z.enum(["Player","Publisher","System"]).catch("Player"),Iy={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var vy=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),Au=zod.z.object({Gate:Z.nullish(),Schedule:ye.nullish()}).passthrough(),ku=zod.z.object({Gate:Z.nullish(),Limits:Ce.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),wu=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),Ty=zod.z.object({Availability:K.nullish(),Write:K.nullish(),Retention:K.nullish()}).passthrough(),Ay=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:vy.nullish(),Type:Tu.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:Ry.nullish(),Capacity:zod.z.number().nullish(),Availability:Au.nullish(),Write:ku.nullish(),Retention:wu.nullish(),Presets:Ty.nullish()}).passthrough(),ky=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:Sy.nullish(),Limits:Ce.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),wy=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:by.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Ce.nullish()}).passthrough(),zy=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),My=zod.z.object({Availability:zod.z.record(zod.z.string(),Au).nullish(),Write:zod.z.record(zod.z.string(),ku).nullish(),Retention:zod.z.record(zod.z.string(),wu).nullish()}).passthrough(),zu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),Ay).nullish(),Direct:ky.nullish(),Moderation:wy.nullish(),Polling:zy.nullish(),Presets:My.nullish()}).passthrough(),Oy=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),vu=zod.z.object({LastAt:zod.z.string().nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:zod.z.string().nullish(),TotalCount:zod.z.number().nullish(),LastTextHash:zod.z.string().nullish()}).passthrough();zod.z.object({MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish(),Ignored:zod.z.array(zod.z.string()).nullish(),Channels:zod.z.record(zod.z.string(),Oy).nullish(),Limits:zod.z.record(zod.z.string(),vu).nullish(),ReportLimits:vu.nullish()}).passthrough();var Mo=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),Ms=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:Ee.nullish(),AuthorType:Py.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),Ey=zod.z.object({ChannelID:zod.z.string().nullish(),RoomID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Type:Tu.nullish(),CanWrite:zod.z.boolean().nullish(),WriteBlockedReason:zod.z.string().nullish(),SlowModeSeconds:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Os=zod.z.object({Channels:zod.z.array(Ey).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),Uy=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Ms).nullish(),NextCursor:Mo.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Mu=zod.z.object({Rooms:zod.z.array(Uy).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Ou=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Ms).nullish(),NextBefore:Mo.nullish()}).passthrough(),Eu=zod.z.object({Message:Ms.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),Uu=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ee.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),qy=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ee.nullish(),LastMessage:Ms.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),qu=zod.z.object({Conversations:zod.z.array(qy).nullish()}).passthrough(),Ri=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:Mo.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),Lu=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.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 Bu="Chat",Gu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Es=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Gu,{schema:Os,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(Bu,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Bu,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 a;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let 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)):a}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return a;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 a;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)):a}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):a}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let 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)):a}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):a}async reportMessage(e,t,i,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)):a}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):a}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):a}resetCursors(){this.cursors.clear();}};var Ly={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},By=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),Gy={Player:"player",Title:"title",Creator:"creator"},Ci={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Fu=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),Fy=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),Oo=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:By.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(Fy).nullish()}).passthrough(),_u=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(Oo).nullish()}).passthrough(),At={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var _y="IDOS_PLATFORM_PUSH_REQUEST",Vy="IDOS_PLATFORM_PUSH_RESPONSE",Ny=12e4;function Vu(r){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let s=false,n=h=>{s||(s=true,window.removeEventListener("message",o),clearTimeout(p),i(h));},o=h=>{let R=h?.data;!R||R.type!==Vy||R.requestId!==t||Pt.includes(h.origin)&&n(R.ok===true);},p=setTimeout(()=>n(false),Ny);window.addEventListener("message",o);for(let h of Pt)try{e.postMessage({type:_y,requestId:t,titleID:r},h);}catch{}})}var Us=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 At.Unsupported;if(this.isEmbedded())return At.Embedded;if(!this.isSupported())return At.Unsupported;let t=Notification.permission;return t==="denied"?At.Blocked:t!=="granted"?At.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?At.Subscribed:At.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return u("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Vu(this.ctx.settings.titleID)?_({Where:"portal",Subscription:null}):u("client","The portal did not complete the subscription.");if(!this.isSupported())return u("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return u("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:jy(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return a;let h=o.toJSON();p.PushEndpoint=h.endpoint,p.PushP256dh=h.keys?.p256dh,p.PushAuth=h.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),_({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return a;if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return u("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):a}async unsubscribeByHash(e){if(!e)return u("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return a;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function jy(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return i}var qs=Object.freeze({}),Ls=class{constructor(e){this.ctx=e;}ctx;table={...qs};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new yi(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?Wy(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...qs},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return a;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:o}=i.data,p=null;if(o){let h=await this.loadTableFromApi(o);h.ok&&(p=h.data.table);}return this.table=n,this.fallbackTable=p,this.currentFallbackLocale=o,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:o,entryCount:Object.keys(n).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):a}reset(){this.table={...qs},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:G()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return a;t.Locale=e;let i=await this.cache.read(Nu(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let n=s.data,o=n.Locale??Nu(e),p=n.Version??0;if(n.NotModified){let R=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:R?.t??{...qs},fallbackLocale:n.FallbackLocale??null}}}let h=n.Entries??{};return p>0&&await this.cache.write(o,p,h),{ok:true,data:{locale:o,table:h,fallbackLocale:n.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let s=this.pluralCategory(i),n=`${e}.${s}`;if(this.lookup(n)!==void 0)return n;let o=`${e}.other`;return this.lookup(o)!==void 0?o:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function Wy(r,e){return r.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function Nu(r){return r.trim().replace(/_/g,"-").toLowerCase()}var Eo="Quest",Ky={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:r=>{let e=Date.now(),t=null,i=[...Object.values(r.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(r.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let n=Date.parse(s??"");!Number.isNaN(n)&&n>e&&(t===null||n<t)&&(t=n);}return t}},Bs=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(Eo)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(s)){let p=Date.parse(n[o]?.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(Eo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Eo,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(Ky,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let 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 a;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let i=e.trim();if(!i)return u("client","QuestID is required.");if(!this.ctx.auth.context)return a;let s=t&&t.trim().length>0?t.trim():void 0,n={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${G()}`},o=await this.ctx.api.quest.claimQuestReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return u("client","quests is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let 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 u("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${G()}`},o=await this.ctx.api.quest.claimMilestoneReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let 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 u("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${G()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return u("client","MetricID is required.");if(t<0)return u("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return a;let 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 ju=zod.z.object({}).passthrough().transform(r=>r);var Qy=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),Hy=zod.z.object({Schedule:zod.z.array(Qy).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),$y=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:c.nullish(),NextBonusStartUtc:c.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),Jy=zod.z.object({Milestones:K.nullish()}).passthrough(),Uo=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Category:zod.z.string().nullish(),Token:Qt.nullish(),TokenSources:zod.z.array(nt).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),Be).nullish(),Presets:Jy.nullish(),BonusWindow:Hy.nullish()}).passthrough(),Zy=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:Uo.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Yy=zod.z.object({TimedEventID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:ye.nullish(),Content:Uo.nullish(),Events:zod.z.array(Zy).nullish(),Gate:Z.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Xy=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),eR=zod.z.object({Milestones:zod.z.record(zod.z.string(),di).nullish()}).passthrough(),Gs=zod.z.object({Definitions:zod.z.record(zod.z.string(),Yy).nullish(),Settings:Xy.nullish(),Presets:eR.nullish()}).passthrough(),tR=zod.z.object({Type:ki,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:Uo.nullish(),Progress:ju.nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:Be.nullish(),BonusWindow:$y.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),Fs=zod.z.object({ActiveEvents:zod.z.array(tR).nullish()}).passthrough(),Wu=zod.z.object({Tokens:zod.z.record(zod.z.string(),ju).nullish()}),qo=zod.z.object({Type:ki.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Lo=zod.z.object({Type:ki.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:M.nullish(),Inventory:Q.nullish()}),iR=zod.z.object({Type:ki.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Bo=zod.z.array(Te(Lo)),Ku=zod.z.array(Te(qo)),Qu=zod.z.array(Te(iR)),at={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Hu="TimedEvent",$u={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:r=>{let e=null;for(let t of r.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},_s=class{constructor(e){this.ctx=e;e.cache.bindLoginView($u,{schema:Fs,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read($u,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(Hu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Hu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,s,n,o,p=1){if(!t)return u("client","LteID is required.");if(!i)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:o,RollMultiplier:p},R=await this.ctx.api.timedEvent.grantTokens(h);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",R.data)),R}async spendTokens(e,t,i){if(!t)return u("client","LteID is required.");if(i<=0)return u("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return a;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 u("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},n=await this.ctx.api.timedEvent.claimMilestone(s);if(n.ok){let o=n.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return a;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return u("client","spends is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let 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 u("client","grants is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let 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 sR=zod.z.object({UserID:zod.z.string(),Score:j.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:c.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:Ee.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),Mi=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:j.nullish(),CycleEndUtc:c.nullish(),TopUsers:zod.z.array(sR).nullish(),BracketID:zod.z.string().nullish()}),nR=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:c.nullish(),ClaimDeadlineUtc:c.nullish(),MilestoneTokensEarned:j.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Vs=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:j.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:j.nullish(),MilestoneTokensEarned:j.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(nR).nullish()}),Ns=zod.z.object({LeaderboardID:zod.z.string(),NewScore:j,CycleVersion:zod.z.number()}),js=zod.z.object({ServerTimeUtc:c,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ws=zod.z.object({ServerTimeUtc:c,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),Ju=zod.z.array(Te(Mi)),Ks=zod.z.array(Te(Vs)),Zu=zod.z.array(Te(js)),Yu=zod.z.array(Te(Ws)),Xu=zod.z.array(Te(Ns)),rR=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:Te(js).nullish(),Milestones:zod.z.array(Te(Ws)).nullish()}),ec=zod.z.array(rR),oR=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:Te(Mi).nullish(),Progress:Te(Vs).nullish()}),tc=zod.z.array(oR),aR=zod.z.string(),ic=zod.z.object({Rank:zod.z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:ro.nullish()}).passthrough(),lR=zod.z.object({RankRewards:zod.z.array(ic).nullish()}).passthrough(),uR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),cR=zod.z.object({Milestones:K.nullish(),RankRewards:K.nullish()}).passthrough(),pR=zod.z.object({LeaderboardID:zod.z.string(),DisplayName:zod.z.string().nullish(),ScoreDisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsEnabled:zod.z.boolean().nullish(),ScoreAggregation:aR.nullish(),Schedule:ye.nullish(),ChainEvents:zod.z.array(uR).nullish(),Gate:Z.nullish(),TopUsersLimit:zod.z.number().nullish(),MinScoreToEnterTop:zod.z.number().nullish(),BracketSize:zod.z.number().nullish(),LinkedSeasonChainID:zod.z.string().nullish(),RankRewards:zod.z.array(ic).nullish(),Milestones:zod.z.record(zod.z.string(),Be).nullish(),Presets:cR.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(nt).nullish()}).passthrough(),dR=zod.z.object({Milestones:zod.z.record(zod.z.string(),di).nullish(),RankRewards:zod.z.record(zod.z.string(),lR).nullish()}).passthrough(),Qs=zod.z.object({Definitions:zod.z.record(zod.z.string(),pR).nullish(),Presets:dR.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 sc="Leaderboard",nc={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"]},Hs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(nc,{schema:Ks,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(sc,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(sc,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return u("client","LeaderboardID is required.");if(t<=0)return u("client","Score must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},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 u("client","LeaderboardID is required.");if(!t)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},p=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(p.ok){let h=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),h.NewScore,h.NewScore,h.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",h);}return p}async claimCycleReward(e){if(!e)return u("client","LeaderboardID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let 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 u("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},n=await this.ctx.api.leaderboard.claimMilestone(s);if(n.ok){let o=n.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",o);}return n}async getFriendsLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(u("client","leaderboardIDs is required.")):this.ctx.cache.read(nc,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let 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 u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let 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 u("client","scores is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let 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 u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let n=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(n),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of s.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(n,o.Data.MilestoneID),o.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(o.Data.Resources,o.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let 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 Go=zod.z.object({}).passthrough().transform(r=>r),$s=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>lc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:j.nullish(),UserState:Go.nullish(),NextTier:zod.z.lazy(()=>ac).nullish()}).passthrough(),rc=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:j.nullish(),NewStatusTokens:j.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),Fo=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),oc=gt(Fo);var ac=zod.z.object({Tier:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredTokens:j.nullish(),TierReachedReward:H.nullish()}).passthrough(),lc=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:j.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(ac).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var hR=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ye.nullish(),Seasons:zod.z.array(lc).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:Z.nullish()}).passthrough(),Js=zod.z.object({Chains:zod.z.record(zod.z.string(),hR).nullish()}).passthrough(),Lt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var uc="Season",cc={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=Date.parse(r.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Zs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(cc,{schema:$s,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(uc,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(uc,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(cc,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(u("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return u("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","Amount must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${G()}`},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 u("client","SeasonChainID is required.");if(t<=0)return u("client","TierNumber must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${G()}`},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 u("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return u("client","TierNumbers is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${G()}`},n=await this.ctx.api.season.claimTierRewardsBatch(s);if(n.ok){let o=n.data;for(let p of o.Items??[]){let h=p.Data?.TierNumber;p.Success&&typeof h=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,h);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return n}};var pc="Premium",Ys=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(pc,e);if(t){let n={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",n),_(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(pc,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},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 u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,RelatedEntityID:`premium_purchase_${e}_${t}`},o=await this.ctx.api.premium.purchaseItemOrCurrency(n);if(o.ok){let p=o.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 o}async purchaseRealMoney(e,t,i,s,n,o,p,h){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!s||!n)return u("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return a;let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:o,PackageName:p,AppStoreEnvironment:h,RelatedEntityID:`premium_iap_${e}_${t}`},B=await this.ctx.api.premium.purchaseRealMoney(R);if(B.ok){let re=B.data;re.Premium&&this.ctx.data.user.applyPremium(re.Premium),this.ctx.data.user.applyResourceOperation(re.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",re);}return B}};var Xs=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:c.nullish()}),_o=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:j.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),Xs).nullish(),UpdatedAt:c.nullish()}).passthrough(),dc=zod.z.object({Characters:zod.z.record(zod.z.string(),_o).nullish()}),Vo=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),No=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),hc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Xs).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),mc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),mR=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),fc=zod.z.object({ServerTimeUtc:c,Characters:zod.z.record(zod.z.string(),mR).nullish(),Inventory:Q.nullish()}),jo=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:M.nullish()}),gc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:Xs.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),yc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Xs.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),Rc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),fR=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:c.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:ce.nullish()}),gR=zod.z.object({CharacterID:zod.z.string(),CharacterOpen:zod.z.boolean().nullish(),DefaultSkinID:zod.z.string().nullish(),WornSkinID:zod.z.string().nullish(),Skins:zod.z.array(fR).nullish()}),Cc=zod.z.object({ServerTimeUtc:c,Characters:zod.z.record(zod.z.string(),gR).nullish()}),Sc=gt(jo),xc=gt(No),bc=gt(Vo),Wo=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),Dc=zod.z.object({StatID:zod.z.string(),TypeID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish(),Weight:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:_e.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:_e.nullish(),RankCurve:_e.nullish(),Requirements:zod.z.array(Wo).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),yR=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Wo).nullish(),AllowedRarityIDs:zod.z.array(zod.z.string()).nullish(),AllowedItemTags:zod.z.array(zod.z.string()).nullish(),MinItemLevel:zod.z.number().nullish(),MaxItemLevel:zod.z.number().nullish()}).passthrough(),Pc=zod.z.object({Slots:zod.z.record(zod.z.string(),yR).nullish()}).passthrough(),Ic=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Lore:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),RR=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),CR=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:ce.nullish()}).passthrough(),SR=zod.z.object({Stats:K.nullish(),Levels:K.nullish(),Equipment:K.nullish()}).passthrough(),vc=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:_e.nullish()}).passthrough(),Ko="@skin";function xR(r){return !!r&&r.startsWith("@")}var bR=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),DR=zod.z.object({PriceOptions:ce.nullish(),Schedule:ye.nullish(),Gate:Z.nullish()}).passthrough(),PR=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Wo).nullish()}).passthrough(),IR=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Ic.nullish(),Item:bR.nullish(),Sale:DR.nullish(),Requirements:PR.nullish()}).passthrough(),vR=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),IR).nullish()}).passthrough(),TR=zod.z.object({CharacterID:zod.z.string(),Identity:Ic.nullish(),Classification:RR.nullish(),Unlock:CR.nullish(),Presets:SR.nullish(),Equipment:Pc.nullish(),Stats:zod.z.record(zod.z.string(),Dc).nullish(),RankLadder:vc.nullish(),RankStatCurve:_e.nullish(),StatMaxLevelCurve:_e.nullish(),Skins:vR.nullish()}).passthrough(),AR=zod.z.object({Stats:zod.z.record(zod.z.string(),Dc).nullish()}).passthrough(),kR=zod.z.object({RankLadder:vc.nullish()}).passthrough(),wR=zod.z.object({Equipment:Pc.nullish()}).passthrough(),zR=zod.z.object({Stats:zod.z.record(zod.z.string(),AR).nullish(),Levels:zod.z.record(zod.z.string(),kR).nullish(),Equipment:zod.z.record(zod.z.string(),wR).nullish()}).passthrough(),en=zod.z.object({Definitions:zod.z.record(zod.z.string(),TR).nullish(),Presets:zR.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"},MR="SKIN_ALREADY_OWNED";var Qo="Character",tn=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Qo)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,n])=>n?.Unlock?.UnlockedByDefault===true&&!i[n.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(Qo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Qo,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${G()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",n);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return u("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${G()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok){let o=n.data;this.ctx.data.user.patchCharacter(o.CharacterID,p=>{p.StatLevels??={},p.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(p.Power=o.Power),p.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return n}async upgradeCharacterLevel(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${G()}`,...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,o=>{o.Level=n.NewLevel,n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",n);}return s}async equipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;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 u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;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 a;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${G()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok){let o=n.data;this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),o.Equipped&&o.Equipment&&this.applySkinLocally(o.CharacterID,o.Equipment,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",o);}return n}async equipSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},n=await this.ctx.api.character.equipSkin(s);if(n.ok){let o=n.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return n}async unequipSkin(e){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let 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)):a}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,Ko,t??null),n.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return u("client","characterIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,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 u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,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 u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,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 Tc="Match",sn=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,o){let p=this.ctx.auth.context;if(!p)return a;let h={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:o,RelatedEntityID:`pvp_create_${p.userID}_${G()}`},R=await this.ctx.api.match.createMatch(h);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",R.data)),R}async updateMatch(e,t={}){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},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 u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,s){let n=this.ctx.auth.context;if(!n)return a;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${G()}`},p=await this.ctx.api.match.instantBattle(o);if(p.ok){let h=p.data,R=this.ctx.data.config.itemDefinitions;if(h.Resources)this.ctx.data.user.applyResourceOperation(h.Resources,R);else if(h.ResourcesDual){let B=h.ResourcesDual;B.FromUserID===n.userID&&B.FromResult?this.ctx.data.user.applyResourceOperation(B.FromResult,R):B.ToUserID===n.userID&&B.ToResult&&this.ctx.data.user.applyResourceOperation(B.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",h);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let s=this.ctx.authedRequest();if(!s)return a;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 a;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(Tc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Tc,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var Ac="Craft",nn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ac,e);if(t){let n={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),_(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(Ac,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n){if(!e)return u("client","CraftID is required.");let o=this.ctx.auth.context;if(!o)return a;let p={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,RelatedEntityID:`craft_${e}_${o.userID}_${G()}`},h=await this.ctx.api.craft.craft(p);return h.ok&&(this.ctx.data.user.applyResourcesWithDelta(h.data.Resources,h.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",h.data)),h}};var Bt=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(Bt),zod.z.record(zod.z.string(),Bt)]));var Gt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},kc=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Jt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Oi(r){return r!==Jt.Pending&&r!==Jt.Running}var OR={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 ER(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var UR=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),qR=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),rn=zod.z.object({GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:kc.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),Bt).nullish(),Assets:zod.z.array(UR).nullish(),Error:qR.nullish(),Charge:M.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:M.nullish(),Context:zod.z.record(zod.z.string(),Bt).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish()}),wc=zod.z.object({Data:zod.z.array(rn).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),LR=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish()}).passthrough(),BR=zod.z.object({Modality:kc.nullish(),Async:zod.z.boolean().nullish(),Limits:Ce.nullish(),PriceOptions:ce.nullish(),Tags:zod.z.array(zod.z.string()).nullish(),HistoryMessages:zod.z.number().nullish(),MaxTokens:zod.z.number().nullish(),AllowImages:zod.z.boolean().nullish(),MaxInputImages:zod.z.number().nullish(),MaxInputImageBytes:zod.z.number().nullish(),AllowedImageTypes:zod.z.array(zod.z.string()).nullish(),MaxImages:zod.z.number().nullish(),AllowEdit:zod.z.boolean().nullish(),AllowReferenceImage:zod.z.boolean().nullish(),MaxPromptChars:zod.z.number().nullish(),LockBehavior:zod.z.boolean().nullish(),ImageSize:zod.z.string().nullish(),VideoSize:zod.z.string().nullish(),VideoSeconds:zod.z.number().nullish(),Voice:zod.z.string().nullish(),AudioFormat:zod.z.string().nullish(),MusicFormat:zod.z.string().nullish(),ThreeDOperation:zod.z.string().nullish(),ArtStyle:zod.z.string().nullish(),ThreeDFormat:zod.z.string().nullish(),Reward:H.nullish(),PromptVariables:zod.z.array(LR).nullish(),AllowFreePrompt:zod.z.boolean().nullish()}).passthrough(),zc=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),BR).nullish()}).passthrough(),Fe={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 Mc="AI",GR=/^[A-Za-z0-9_-]{1,128}$/,FR=2e3,_R=5e3,VR=30*6e4;function NR(r,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,r);e?.addEventListener("abort",i,{once:true});})}var on=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(Mc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Mc,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,i){return this.generate(e,{Text:t},i,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}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)):a}async getGeneration(e){if(!e)return u("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):a}isTerminal(e){return Oi(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 u("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??VR),n=Math.max(1,t.intervalMs??FR),o=Math.max(n,t.maxIntervalMs??_R);for(;!Oi(i.Status);){if(t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");if(Date.now()+n>s)return u("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await NR(n,t.signal),t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(i);if(n=Math.min(o,Math.round(n*1.5)),!p.ok){if(p.reason==="connection")continue;return p}i=p.data,Oi(i.Status)||t.onUpdate?.(i);}return _(i)}pollFor(e){switch(e.Modality){case Gt.Text:return this.getText(e.GenerationID);case Gt.Image:return this.getImage(e.GenerationID);case Gt.Audio:return this.getAudio(e.GenerationID);case Gt.Music:return this.getMusic(e.GenerationID);case Gt.Video:return this.getVideo(e.GenerationID);case Gt.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,s){if(!e)return u("client","FeatureKey is required.");let n=i?.relatedEntityID;if(n!==void 0&&!GR.test(n))return u("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:n??G()},p=await s(o);return p.ok&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return u("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.GenerationID=e;let 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===Jt.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===Jt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Jt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Ho="Collection",an=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(Ho),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(h=>!!h?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ho,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ho,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,s){let n=this.ctx.auth.context;if(!n)return a;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${G()}`},p=await this.ctx.api.collection.openPack(o);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 a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${G()}`},o=await this.ctx.api.collection.openCollectionChest(n);return o.ok&&(this.ctx.data.user.applyResourcesWithDelta(o.data.Resources,o.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",o.data)),o}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${G()}`},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 a;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${G()}`},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 u("client","sets is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let 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 a;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${G()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,n,o=false){let p=this.ctx.auth.context;if(!p)return a;let h={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${p.userID}_${s}_${G()}`},R=await this.ctx.api.collection.sendTradeOffer(h);return R.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",R.data)),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${G()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${G()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${G()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var jR=zod.z.object({}).passthrough().transform(r=>r),WR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},KR={Active:"Active",Left:"Left",Replaced:"Replaced"},QR=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),HR=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ee.nullish(),BuildObjectsProgress:QR.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),$R=zod.z.object({Index:zod.z.number().nullish(),OwnerUserID:zod.z.string().nullish(),CurrentProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish(),IsCompleted:zod.z.boolean().nullish()}).passthrough(),JR=zod.z.object({Objects:zod.z.array($R).nullish()}).passthrough(),Oc=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CoopChainID:zod.z.string().nullish(),CoopEventID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),Members:zod.z.array(HR).nullish(),BuildObjectsState:JR.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:zod.z.number().nullish()}).passthrough(),Ec=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>Uc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),ZR=zod.z.string(),$o=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Weight:zod.z.number().nullish(),MinProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish()}).passthrough(),YR=zod.z.object({Index:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxProgress:zod.z.number().nullish(),CompletionReward:H.nullish()}).passthrough(),XR=zod.z.object({Objects:zod.z.array(YR).nullish(),PriceOptions:ce.nullish(),SpinnerTable:zod.z.array($o).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),Uc=zod.z.object({CoopEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),EventType:ZR.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:XR.nullish(),GrandPrize:H.nullish()}).passthrough(),eC=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ye.nullish(),Events:zod.z.array(Uc).nullish(),Gate:Z.nullish()}).passthrough(),ln=zod.z.object({ServerTimeUtc:c.nullish(),UserState:jR.nullish(),ActiveGroup:Oc.nullish()}),Jo=zod.z.object({ServerTimeUtc:c.nullish(),Group:Oc.nullish(),SecondsRemaining:j.nullish()}),qc=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Resources:M.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:$o.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array($o).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),Zo=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Lc=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),un=zod.z.object({Chains:zod.z.record(zod.z.string(),eC).nullish()}).passthrough(),ht={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var Bc="CoopEvent",Gc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},cn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Gc,{schema:ln,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Bc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Bc,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return u("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(Gc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return u("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return u("client","CoopChainID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let 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 u("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,RelatedEntityID:G()},o=await this.ctx.api.coopEvent.spin(n);return o.ok&&(this.ctx.data.user.applyResourceOperation(o.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",o.data)),o}async claimObjectReward(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var tC={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},iC={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},sC=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:c.nullish(),CompletedAtUtc:c.nullish(),LastExecutedAtUtc:c.nullish(),NextAvailableAtUtc:c.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),nC=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),Fc=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:c.nullish(),ExhaustedAtUtc:c.nullish(),ExpiredAtUtc:c.nullish(),DismissedAtUtc:c.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:c.nullish(),Nodes:zod.z.record(zod.z.string(),sC).nullish(),Tracks:zod.z.record(zod.z.string(),nC).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),rC=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:c.nullish(),ActiveOfferExpiresAtUtc:c.nullish(),ActiveOffer:Fc.nullish(),NextCycleStartsAtUtc:c.nullish(),LastUpdatedUtc:c.nullish(),DismissSkipAvailableAtUtc:c.nullish(),LastDismissedAtUtc:c.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),oC=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),aC=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:c.nullish(),LastActivatedAtUtc:c.nullish(),LastExhaustedAtUtc:c.nullish(),NodeCounts:zod.z.record(zod.z.string(),oC).nullish()}).passthrough(),lC=zod.z.object({Slots:zod.z.record(zod.z.string(),rC).nullish(),OfferHistory:zod.z.record(zod.z.string(),aC).nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),uC={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},cC={Eq:"Eq",Gte:"Gte",Lte:"Lte"},pC=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),pn=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),_c=zod.z.object({Schedule:ye.nullish(),Gate:Z.nullish()}).passthrough(),Vc=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),dC=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Behaviour:K.nullish()}).passthrough(),hC=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:pn.nullish(),Availability:_c.nullish(),Behaviour:Vc.nullish(),Queue:zod.z.array(pC).nullish(),Presets:dC.nullish()}).passthrough(),mC=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),fC=zod.z.object({RewardedVideo:mC.nullish()}).passthrough(),gC=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),yC=zod.z.object({Identity:K.nullish(),Graph:K.nullish(),Milestones:K.nullish()}).passthrough(),RC=zod.z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish()}).passthrough(),CC=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),SC=zod.z.object({TrackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),StartValue:zod.z.number().nullish(),MinValue:zod.z.number().nullish(),MaxValue:zod.z.number().nullish(),ClampToMin:zod.z.boolean().nullish(),ClampToMax:zod.z.boolean().nullish(),HiddenFromUI:zod.z.boolean().nullish()}).passthrough(),xC=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(gC).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),Nc=zod.z.object({Options:ce.nullish()}).passthrough(),jc=zod.z.object({Grants:H.nullish(),TrackChanges:zod.z.array(CC).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),bC=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:pn.nullish(),Pricing:Nc.nullish(),Reward:jc.nullish(),Action:fC.nullish(),UnlockRules:xC.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:Ce.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:RC.nullish()}).passthrough(),Wc=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(bC).nullish(),Tracks:zod.z.array(SC).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),Kc=zod.z.object({Milestones:zod.z.record(zod.z.string(),Be).nullish(),ClaimMode:zod.z.string().nullish(),Token:Qt.nullish()}).passthrough(),Qc=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:pn.nullish(),Graph:Wc.nullish(),Milestones:Kc.nullish(),Presets:yC.nullish()}).passthrough(),DC=zod.z.object({Identity:zod.z.record(zod.z.string(),pn).nullish(),Availability:zod.z.record(zod.z.string(),_c).nullish(),Behaviour:zod.z.record(zod.z.string(),Vc).nullish(),Graph:zod.z.record(zod.z.string(),Wc).nullish(),Milestones:zod.z.record(zod.z.string(),Kc).nullish(),Pricing:zod.z.record(zod.z.string(),Nc).nullish(),Reward:zod.z.record(zod.z.string(),jc).nullish()}).passthrough(),Yo=zod.z.object({Slots:zod.z.record(zod.z.string(),hC).nullish(),Offers:zod.z.record(zod.z.string(),Qc).nullish(),Presets:DC.nullish()}).passthrough(),Hc=zod.z.object({DealOfferDefinitions:Yo.nullish()}),$c=zod.z.object({DealOffers:lC.nullish()}),PC=zod.z.object({EntityID:zod.z.string().nullish(),TotalEarned:zod.z.number().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),ReachedUnclaimedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),IC=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:Qc.nullish(),ActivationState:Fc.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:c.nullish(),Cost:bt.nullish(),Milestone:PC.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),dn=zod.z.object({Slots:zod.z.array(IC).nullish()}),Jc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Zc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),Yc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),Xc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),ep=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Rt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var vC="DealOffer",tp={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},hn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(tp,{schema:dn,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(vC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(tp,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${G()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,s){if(!e||!t)return u("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return a;let n=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:n??`deal_exec_${e}_${t}_${G()}`},p=await this.ctx.api.dealOffer.executeNode(o);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 u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${G()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return u("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${G()}`},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 u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${G()}`},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 ip="Referral",mn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ip,e);if(t){let n={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",n),_(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(ip,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=Kt.parseReferralCode(e)?.toUpperCase();if(!t)return u("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},n=await this.ctx.api.referral.activateReferralCode(s);if(n.ok){let o=n.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID,o.QualificationPending),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return n}async claimInviteReward(e){let t=e.trim();if(!t)return u("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},n=await this.ctx.api.referral.claimInviteReward(s);if(n.ok){let o=n.data;o.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(o.RewardID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",o);}return n}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return u("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},n=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(n.ok){let o=n.data;for(let p of o.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return n}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.checkQualification(e);return t.ok&&t.data.Qualification&&!t.data.QualificationPending&&await this.getUserState(),t}async checkQualificationIfPending(){this.ctx.data.user.state?.Referral?.QualificationPending===true&&await this.checkQualification();}};var TC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},sp=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),AC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},kC=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),wC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},zC=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),tt={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},MC={Disabled:"MAILBOX_DISABLED",MessageNotFound:"MESSAGE_NOT_FOUND",MessageIDRequired:"MESSAGE_ID_REQUIRED",AlreadyClaimed:"ALREADY_CLAIMED",Expired:"EXPIRED",NoRewards:"NO_REWARDS",HasUnclaimedRewards:"HAS_UNCLAIMED_REWARDS",NotFriends:"NOT_FRIENDS",Blocked:"BLOCKED",RecipientNotFound:"RECIPIENT_NOT_FOUND",CannotGiftSelf:"CANNOT_GIFT_SELF",GiftNotFound:"GIFT_NOT_FOUND",GiftNotAllowed:"GIFT_NOT_ALLOWED",AlreadySent:"ALREADY_SENT",SendLimit:"SEND_LIMIT",NotEnoughResources:"NOT_ENOUGH_RESOURCES",AmountTooSmall:"AMOUNT_TOO_SMALL",RecipientLimit:"RECIPIENT_LIMIT",TransferDisabled:"TRANSFER_DISABLED",ResourceNotGiftable:"RESOURCE_NOT_GIFTABLE",AmountTooLarge:"AMOUNT_TOO_LARGE",AmountInvalid:"AMOUNT_INVALID",TooManyEntries:"TOO_MANY_ENTRIES",EntriesRequired:"ENTRIES_REQUIRED",FriendshipTooNew:"FRIENDSHIP_TOO_NEW",RequestIDRequired:"RELATED_ENTITY_ID_REQUIRED",CryptoForbidden:"CRYPTO_FORBIDDEN",ModuleRewardUnavailable:"MODULE_REWARD_UNAVAILABLE",Conflict:"CONFLICT"},OC=100,EC=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),np=zod.z.object({FeatureID:zod.z.string().nullish(),Args:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Url:zod.z.string().nullish(),Label:zod.z.string().nullish()}).passthrough(),UC=zod.z.object({Texts:zod.z.record(zod.z.string(),EC).nullish(),Category:sp.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:np.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),qC=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:pe.nullish(),Cost:pe.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:c.nullish(),SenderGate:Z.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),LC=zod.z.object({Type:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxAmountPerGift:zod.z.number().nullish()}).passthrough(),BC=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(LC).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:c.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:pe.nullish(),SenderGate:Z.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),rp=zod.z.object({Enabled:zod.z.boolean().nullish(),Capacity:zod.z.number().nullish(),RewardLetterDays:zod.z.number().nullish(),PlainLetterDays:zod.z.number().nullish(),ClaimedRetentionDays:zod.z.number().nullish(),DefaultLanguage:zod.z.string().nullish(),Templates:zod.z.record(zod.z.string(),UC).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),qC).nullish(),Transfer:BC.nullish()}).passthrough().nullish(),Integrations:zod.z.object({Leaderboard:zod.z.boolean().nullish(),CoopEvent:zod.z.boolean().nullish(),Season:zod.z.boolean().nullish(),Referral:zod.z.boolean().nullish()}).passthrough().nullish()}).passthrough(),GC=zod.z.object({MessageID:zod.z.string(),Source:kC,Category:sp,TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:np.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:H.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:c,ExpiresAt:c.nullish(),ReadAt:c.nullish(),ClaimedAt:c.nullish()}).passthrough(),FC=zod.z.object({MessageID:zod.z.string(),Module:zC,Key:zod.z.string(),TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish()}).passthrough(),Xo=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),op=zod.z.object({ServerTimeUtc:c.nullish(),Messages:zod.z.array(GC).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(FC).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),fn=zod.z.object({ServerTimeUtc:c.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),ea=zod.z.object({ServerTimeUtc:c.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(Xo).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),_C=zod.z.object({MessageID:zod.z.string(),Rewards:pe.nullish()}).passthrough(),gn=zod.z.object({ServerTimeUtc:c.nullish(),Claimed:zod.z.array(_C).default([]),Failed:zod.z.array(Xo).default([]),Resources:M.nullish(),Inventory:Q.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),ap=zod.z.object({ServerTimeUtc:c.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(Xo).default([]),Resources:M.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish()}).passthrough(),lp=zod.z.object({ServerTimeUtc:c.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),RecipientReceives:pe.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),up=zod.z.object({ServerTimeUtc:c.nullish(),ResetsAt:c.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:c.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish()}).passthrough().nullish()}).passthrough();var ta="Mailbox",ia={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},yn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ia,{schema:fn,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(ia,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(ta)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(ta,e);if(t)return _(t);let i=this.request();if(!i)return a;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(ta,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 a;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(ia,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return a;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return a;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return u("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):a}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return u("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):a}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):a}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return a;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return u("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return u("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return a;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 u("client","RecipientUserID is required.");if(!i?.requestID?.trim())return u("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return a;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):a}};var Rn={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},sa="idos-app",cp=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),Allowed:zod.z.boolean(),DenyReason:zod.z.string().nullish(),Message:zod.z.string().nullish(),RetryAfterSeconds:zod.z.number().nullish(),RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),AdUnitID:zod.z.string().nullish(),Type:zod.z.string().nullish(),ExpiresAtUtc:zod.z.string().nullish(),CreditsToAward:zod.z.number().nullish(),RequiresServerSideVerification:zod.z.boolean().nullish()}),pp=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),RequestID:zod.z.string().nullish(),Status:zod.z.string(),CreditsAwarded:zod.z.number().nullish(),RetryAfterSeconds:zod.z.number().nullish(),ExpiresAtUtc:zod.z.string().nullish(),AlreadyProcessed:zod.z.boolean().nullish(),GrantedWithoutSsv:zod.z.boolean().nullish(),Resources:M.nullish()});var na={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},VC=5*6e4;function Cn(){return $t()}async function ra(r){let e=await It(na.request,na.response,{titleID:r.titleID,userID:r.userID,requestID:r.requestID,placementID:r.placementID,adUnitID:r.adUnitID??null},{answerTimeoutMs:VC});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var NC=new Set(["CANCELLED","DECLINED","CLOSED"]),jC=45e3,WC=r=>new Promise(e=>setTimeout(e,r)),Sn=class{constructor(e){this.ctx=e;}ctx;get available(){return Cn()}async showRewarded(e){if(!Cn())return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let i=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!i.ok)return {status:"unavailable",reason:i.error};let s=i.data;if(!s.Allowed)return {status:"denied",reason:s.DenyReason??void 0,retryAfterSeconds:s.RetryAfterSeconds??void 0};if(s.ProviderID!==sa||!s.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let n=await ra({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:s.RequestID,placementID:e,adUnitID:s.AdUnitID});return n.ok?this.awaitReward(s.RequestID,n.via):{status:NC.has(n.error??"")?"cancelled":"unavailable",reason:n.error}}async awaitReward(e,t){let i=Date.now()+jC;for(;;){let s=this.ctx.authedRequest();if(!s)return {status:"pending",via:t};let n=await this.ctx.api.advertising.completeView({...s,RequestID:e});if(n.ok&&n.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:n.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((n.ok?n.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>i)return {status:"pending",via:t,reason:n.ok?void 0:n.error};await WC(o);}}};var KC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},QC={Title:"Title",Platform:"Platform"},dp=zod.z.object({UserID:zod.z.string(),PublicData:Ee.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),Ei=zod.z.object({Friends:zod.z.array(dp).nullish()}),HC=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),Ui=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:dp.nullish(),Counters:HC.nullish()}),$C={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},JC={Like:"Like",Favorite:"Favorite"},ZC={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},YC={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},XC={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},eS=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),tS=zod.z.object({Id:zod.z.string(),Verb:zod.z.string().nullish(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Count:zod.z.number().nullish(),LastActors:zod.z.array(eS).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),OccurredAt:c.nullish(),OwnerImpact:M.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),hp=zod.z.object({Items:zod.z.array(tS).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:c.nullish()}).passthrough(),qi=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:c.nullish()}).passthrough(),iS=zod.z.object({Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),Followers:zod.z.number().nullish(),Following:zod.z.number().nullish(),Comments:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Posts:zod.z.number().nullish(),Dislikes:zod.z.number().nullish()}).passthrough(),Ft=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:iS.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),mp=zod.z.object({Items:zod.z.array(Ft).nullish()}).passthrough(),oa={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},sS=zod.z.object({UserID:zod.z.string(),PublicData:Ee.nullish(),Mutual:zod.z.boolean().nullish(),Since:c.nullish()}).passthrough(),xn=zod.z.object({Items:zod.z.array(sS).nullish(),...oa}).passthrough(),nS=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:c.nullish()}).passthrough(),fp=zod.z.object({Items:zod.z.array(nS).nullish(),...oa}).passthrough(),bn=zod.z.object({CommentID:zod.z.string(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),ParentCommentID:zod.z.string().nullish(),AuthorUserID:zod.z.string().nullish(),AuthorPublicData:Ee.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:c.nullish(),EditedAt:c.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),gp=zod.z.object({Items:zod.z.array(bn).nullish(),...oa,TotalCount:zod.z.number().nullish()}).passthrough(),yp=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),Rp=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),Cp=zod.z.object({CommentsEnabled:zod.z.boolean().nullish(),CommentableTypes:zod.z.array(zod.z.string()).nullish(),CommentMaxLength:zod.z.number().nullish(),CommentMaxLinks:zod.z.number().nullish()}).passthrough(),rS="FRIENDS_FROM_PLATFORM",oS={Off:"Off",Default:"Default",Always:"Always"},aS={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Sp=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:zod.z.boolean().nullish()}).passthrough(),Se={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report"};var aa={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Dn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(aa,{schema:qi,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return a;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return u("client","TargetUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return u("client","FriendUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return a;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(aa,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(aa,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):a}async getEntityStates(e,t){if(!t?.length)return u("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):a}async addComment(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i?.trim())return u("client","Text is required.");n.Text=i,n.ParentCommentID=s;let o=await this.ctx.api.social.addComment(n);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return u("client","CommentID is required.");if(!t?.trim())return u("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return a;i.CommentID=e,i.Text=t;let 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 u("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let 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 u("client","ReportReason is required.");n.ReportReason=i,n.ReportComment=s;let o=await this.ctx.api.social.report(n);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,s){let n=this.targetRequest(t,i);if("ok"in n)return n;n.ReactionKind=s;let o=await this.ctx.api.social[e](n);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):a}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return u("client","EntityType is required.");if(!t)return u("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):a}};var xp="TimedBoost";function lS(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Pn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(xp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(xp,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let i=e.trim();if(!lS(i))return u("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${G()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok){let o=n.data;if(o.ActivatedBoost){let p=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,p);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return n}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var wt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},uS={Client:"Client",Server:"Server",System:"System"},cS=zod.z.enum(["Client","Server","System"]).catch("Client"),pS=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:c.nullish(),Version:zod.z.number().nullish(),LastWriter:cS.nullish(),ExpiresAt:c.nullish()}).passthrough(),In=zod.z.record(zod.z.string(),pS),bp=zod.z.object({Version:zod.z.number().nullish(),Private:In.nullish(),Public:In.nullish(),ReadOnly:In.nullish()}),la=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:In.nullish()}),ua=zod.z.object({ServerTimeUtc:c.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:c.nullish()}),dS=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:c.nullish()}),Dp=zod.z.object({ServerTimeUtc:c.nullish(),Results:zod.z.array(dS).nullish()}),Pp=zod.z.object({ServerTimeUtc:c.nullish(),DeletedCount:zod.z.number().nullish()}),Ip=zod.z.object({Results:zod.z.array(la).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),hS={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},mS=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),fS=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:mS.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),vn=zod.z.object({Keys:zod.z.record(zod.z.string(),fS).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),mt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var gS="UserCustomData";function vp(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var Tn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(gS,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TargetUserID=t;let 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,wt.Private)}async setPublicData(e,t){return this.setData(e,t,wt.Public)}async setData(e,t,i){let s=e.trim();if(!vp(s))return u("client",'KeyID is required and must not contain "." or "$".');if(t==null)return u("client","Value is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(i===wt.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(p.ok){let h=p.data;this.ctx.data.user.patchUserCustomDataKey(i,h.KeyID,t,h.Version??0,h.ExpiresAt),this.ctx.emitter.emit(i===wt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",h);}return p}async deleteKey(e,t){let i=e.trim();if(!vp(i))return u("client",'KeyID is required and must not contain "." or "$".');if(t!==wt.Private&&t!==wt.Public)return u("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return a;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 u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let n=s.Bucket??wt.Private,o=e.find(p=>p.Bucket===n&&p.KeyID===s.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(n,s.KeyID,o.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let 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 u("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var yS="TitleCustomDataDefinitions",Tp=50;function RS(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function ca(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function CS(r){let e={};for(let[t,i]of Object.entries(r))ca(i)||(e[t]=i);return e}var An=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(yS,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return a;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(n=>n.trim()).filter(n=>n.length>0);if(!t.length)return u("client","At least one KeyID is required.");if(t.some(n=>!RS(n)))return u("client",'KeyID must not contain "." or "$".');if(t.length>Tp)return u("client",`At most ${Tp} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return a;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&&!ca(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!ca(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=CS(this.runtimeCache),e.Runtime=this.runtimeCache):e.Runtime&&(this.runtimeCache=e.Runtime),e.RuntimeVersion!=null&&(this.lastRuntimeVersion=e.RuntimeVersion),this.ctx.emitter.emit("titleCustomData:publicDataLoaded",e);}};var kn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var SS=15,xS="GameLoop",Ap="BoardDefinition",wn=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(xS,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(Ap,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),_(i);let s=this.ctx.authedRequest();if(!s)return a;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(Ap,n.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n.data)),n}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return u("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return a;i.StageLevel=e;let 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 a;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return u("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${G()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let n=s.data,o=iu(new Date,SS);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:o}:n.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:n.SpecialModeOffer.ModeID??void 0,Choices:n.SpecialModeOffer.Choices??void 0}});}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),n.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",n);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${G()}`},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 u("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopRaid(s);if(n.ok){let o=n.data;o.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(o.RaidLayout,o.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(o)),this.ctx.emitter.emit("gameLoop:boardRaided",o);}else await this.getUserBoardState();return n}async boardLoopRaidFast(e){if(!e.length)return u("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${G()}`},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 u("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${G()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let n=s.data;n.StageComplete?this.ctx.data.user.patchBoardState(o=>{o.StageLevel=(o.StageLevel??1)+1,o.Position=0,o.Pending=null,o.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(n.BuiltIndex,o=>{n.NewLevel!=null&&(o.Level=n.NewLevel),o.IsDamaged=false,n.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",n);}return s}async boardSpecialChoose(e,t){if(!e)return u("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(n.ok){let o=n.data;o.Mode==="Instant"||o.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(h=>{h.ChoiceID=e,h.ChosenMode=o.Mode??"Timed",h.StartedAtUtc=o.StartedAtUtc??null,h.DurationSeconds=o.DurationSeconds??null,h.AdViewsUsed=0;}),o.Operation&&this.ctx.data.user.applyResourcesWithDelta(o.Operation,o.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",o);}return n}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${G()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let n=s.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=n.AdViewsUsed??0,o.AccumulatedMultiplier=n.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",n);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${G()}`,...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 a;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return u("client","milestoneID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},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 a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var zn=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let n=e.trim();if(!n)return u("client","FunctionName is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(o);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var kp=zod.z.object({ServerTimeUtc:c,SourceType:ci,SourceID:zod.z.string(),TargetType:ci,TargetID:zod.z.string(),SourceSpent:j,FeeAmount:j,RateApplied:Y,TargetCredited:j}),wp=zod.z.object({ServerTimeUtc:c,SourceType:ci,SourceID:zod.z.string(),TargetType:ci,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),Mn={Convert:"Convert",CryptoConvert:"CryptoConvert"},bS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},zp=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),DS={Automatic:"Automatic",Manual:"Manual"},PS=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),IS=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),vS=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),TS=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),AS=zod.z.object({TargetCurrencyType:ci.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),Mp=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:PS.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(AS).nullish()}).passthrough(),Op=zod.z.object({CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough(),kS=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:IS.nullish(),Recharge:vS.nullish(),Conversion:Mp.nullish(),Permissions:TS.nullish(),Audit:Op.nullish(),Status:zp.nullish()}).passthrough(),wS=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),zS=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),MS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),OS=zod.z.object({Mode:zod.z.string().nullish(),FundingNetworkID:zod.z.string().nullish(),PerPlayerDailyTokens:zod.z.number().nullish(),TitleDailyTokens:zod.z.number().nullish(),RefuseOverCap:zod.z.boolean().nullish()}).passthrough(),pa=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),DisplayDecimals:zod.z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:zod.z.array(wS).nullish(),Limits:zS.nullish(),Permissions:MS.nullish(),Conversion:Mp.nullish(),Audit:Op.nullish(),Status:zp.nullish(),ServerGrantPolicy:OS.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),On=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),kS).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),pa).nullish()}).passthrough();var ES={EVM:"EVM",Solana:"Solana"},US=zod.z.enum(["EVM","Solana"]).catch("EVM"),qS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},LS=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),BS={Token:"Token",Nft:"Nft"},Ep=zod.z.enum(["Token","Nft"]).catch("Token"),GS={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},FS=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),_S={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},VS=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),NS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},da=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),Up={GameTopUp:"game_topup",CommunityReward:"community_reward"};function En(r){let e=r?.trim();return e||Up.GameTopUp}var jS={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},qp=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),WS=zod.z.object({ContractAddress:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),Lp=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),KS=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:US.nullish(),ChainID:zod.z.number().nullish(),ChainTicker:zod.z.string().nullish(),RewardPoolAddress:zod.z.string().nullish(),VaultDepositAddress:zod.z.string().nullish(),ChainConfigVersion:zod.z.number().nullish(),RequiredConfirmations:zod.z.number().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Lp.nullish(),NftCollections:zod.z.array(WS).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RpcUrl:zod.z.string().nullish(),GasPrice:zod.z.number().nullish(),NftBridgeAddress:zod.z.string().nullish(),SignatureEpoch:zod.z.number().nullish()}).passthrough(),QS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Lp.nullish()}).passthrough(),HS=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),$S={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},JS=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),Bp=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:JS.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),ZS=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),YS={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Li=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),XS=zod.z.object({Mode:Li.nullish(),TokenGates:zod.z.array(Bp).nullish()}).passthrough(),ha=zod.z.object({SystemState:QS.nullish(),Networks:zod.z.record(zod.z.string(),KS).nullish(),AccountSafety:HS.nullish(),WalletLogin:ZS.nullish(),PlayAccess:XS.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),ex=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:c.nullish(),LastUsedAt:c.nullish(),LinkType:LS.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),Gp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:Ep.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),tx=zod.z.object({Status:FS.nullish(),Tier:VS.nullish(),VerifiedAt:c.nullish(),ExpiresAt:c.nullish(),RejectedAt:c.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),ix=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),sx=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:zod.z.record(zod.z.string(),ix).nullish()}).passthrough(),nx=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),rx=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),PerCollection:zod.z.record(zod.z.string(),nx).nullish()}).passthrough(),ox=zod.z.object({Tokens:sx.nullish(),Nfts:rx.nullish()}).passthrough(),ma=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),_t=zod.z.object({Granted:zod.z.boolean(),Mode:Li.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:c.nullish(),Balances:zod.z.array(ma).nullish()}).passthrough(),ax=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:c.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:c.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(ma).nullish()}).passthrough(),lx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),Fp=zod.z.object({Mode:Li.nullish(),TokenGates:zod.z.array(Bp).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(lx).nullish(),Status:_t.nullish()}).passthrough(),ux=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:c.nullish(),LoggedInAt:c.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(ma).nullish()}).passthrough(),cx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:c.nullish()}).passthrough(),px=zod.z.object({Version:zod.z.number().nullish(),Stats:ox.nullish(),LinkedWallets:zod.z.record(zod.z.string(),ex).nullish(),LastWalletLogin:ux.nullish(),PlayAccess:ax.nullish(),PendingWithdrawals:zod.z.array(Gp).nullish(),Kyc:tx.nullish(),FirstActivityAt:c.nullish(),LastActivityAt:c.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(cx).nullish()}).passthrough(),dx=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:c}).passthrough(),Si=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),dx).nullish(),PendingAdded:Gp.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),hx=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough().transform(r=>r),mx=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:qp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:da.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:c.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:c.nullish(),RefundCheckedAt:c.nullish()}).passthrough(),fx=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:qp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:da.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:c.nullish()}).passthrough(),_p=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),fa=zod.z.object({TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ContractAddress:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(_p).nullish(),Signature:zod.z.string().nullish()}).passthrough(),ga=zod.z.object({Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),ProgramID:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(_p).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Vp=zod.z.object({Blockchain:ha.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),pa).nullish()}).passthrough(),Np=zod.z.object({State:px.nullish(),CryptoBalances:zod.z.record(zod.z.string(),hx).nullish()}).passthrough(),jp=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:Si.nullish()}).passthrough(),Wp=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),Kp=zod.z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:c.nullish(),EvmSignature:fa.nullish(),SolanaSignature:ga.nullish(),StateDelta:Si.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),Qp=zod.z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),EvmSignature:fa.nullish(),SolanaSignature:ga.nullish(),StateDelta:Si.nullish(),Inventory:Q.nullish()}).passthrough(),Hp=zod.z.object({TokenTransactions:zod.z.array(mx).nullish(),NFTTransactions:zod.z.array(fx).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),ya=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:zod.z.string().nullish()}).passthrough(),$p=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:Ep.nullish(),EvmSignature:fa.nullish(),SolanaSignature:ga.nullish()}).passthrough(),Jp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:da.nullish(),StateDelta:Si.nullish()}).passthrough(),He={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 gx="Blockchain",Zp="Blockchain:Definitions",Un=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Zp,e);if(t)return _(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return a;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(gx,n.data.Blockchain),this.ctx.data.config.patchSection(Zp,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 a;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let 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 u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let 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 u("client","CurrencyID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!s)return u("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return a;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=s,o.Category=En(n);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,i,s,n,o,p){if(!e)return u("client","ItemID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!s)return u("client","Amount is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.NetworkID=t,h.WalletAddress=i,h.Amount=s,h.Category=En(n),o!==void 0&&(h.Level=o),p&&(h.ItemInstanceID=p);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(h);return R.ok&&(this.ctx.data.user.applyBlockchainStateDelta(R.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",R.data)),R}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return a;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return u("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return u("client","TitleTransactionID is required.");if(!t)return u("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TitleTransactionID=e,i.TransactionHash=t;let 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 u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let 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 u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let 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 a;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var yx={Head:"Head",Torso:"Torso",Legs:"Legs"},qn=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),Rx={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},Ra=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Xp=zod.z.object({AttackTarget:qn,DefenseTarget:qn});var Cx=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),Sx=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:qn.nullish(),DefenseZone:qn.nullish(),HitType:Cx.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),xx=zod.z.object({MaxHp:zod.z.number().nullish(),CurrentHp:zod.z.number().nullish(),Damage:zod.z.number().nullish(),AttackSpeed:zod.z.number().nullish(),CritChance:zod.z.number().nullish(),CritMultiplier:zod.z.number().nullish(),Armor:zod.z.number().nullish(),DodgeChance:zod.z.number().nullish()}).passthrough(),bx=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Yp=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:_o.nullish(),BattleStrategy:zod.z.array(Xp).nullish(),UnstackableItems:zod.z.record(zod.z.string(),bx).nullish(),Stats:xx.nullish()}).passthrough(),Dx=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:pe.nullish(),NetReward:pe.nullish(),BattleLog:zod.z.array(Sx).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:Yp.nullish(),P2BattleProfile:Yp.nullish()}).passthrough(),ed=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:c.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(Xp).nullish(),TargetUserID:zod.z.string().nullish(),Entry:pe.nullish(),CreationCostPaid:pe.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:c.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:c.nullish(),Status:Ra.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:c.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:c.nullish()}).passthrough(),td=zod.z.object({Status:Ra,MatchID:zod.z.string(),Entry:pe.nullish(),Resources:M.nullish()}),id=zod.z.object({Match:ed.nullish()}),sd=zod.z.object({MatchID:zod.z.string(),Status:Ra,Resources:M.nullish()}),nd=zod.z.object({Battle:Dx.nullish(),Resources:M.nullish(),ResourcesDual:Dt.nullish()}),Ca=zod.z.object({Matches:zod.z.array(ed).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),Ct={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var Px=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var Ix=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),vx=zod.z.object({HealthStatID:zod.z.string().nullish(),DamageStatID:zod.z.string().nullish(),ArmorStatID:zod.z.string().nullish(),AttackSpeedStatID:zod.z.string().nullish(),CritChanceStatID:zod.z.string().nullish(),CritDamageStatID:zod.z.string().nullish(),DodgeStatID:zod.z.string().nullish(),AllMightStatID:zod.z.string().nullish()}).passthrough(),Tx=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),Ax=zod.z.object({MaxRounds:zod.z.number().nullish(),BlockDamageMultiplier:zod.z.number().nullish(),MinHitDamage:zod.z.number().nullish(),DefaultCritMultiplier:zod.z.number().nullish(),MaxCritChance:zod.z.number().nullish(),MaxDodgeChance:zod.z.number().nullish(),ArmorMode:Tx.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),kx=zod.z.object({Kind:Ix.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:_e.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),wx=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(kx).nullish()}).passthrough(),Zt=zod.z.object({Terms:zod.z.array(wx).nullish()}).passthrough(),zx=zod.z.object({Health:Zt.nullish(),Damage:Zt.nullish(),Armor:Zt.nullish(),AttackSpeed:Zt.nullish(),CritChance:Zt.nullish(),CritDamage:Zt.nullish(),Dodge:Zt.nullish()}).passthrough(),rd=zod.z.object({StatMapping:vx.nullish(),Combat:Ax.nullish(),Formula:zx.nullish()}).passthrough(),Mx=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),Bi=zod.z.object({Kind:Px.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:Hi.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),od=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(Bi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),ad=zod.z.object({PriceOptions:ce.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:Ce.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),Ox=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:Mx.nullish(),Entry:od.nullish(),Creation:ad.nullish(),Settings:rd.nullish()}).passthrough(),Ex=zod.z.object({Rules:zod.z.record(zod.z.string(),Ox).nullish(),Defaults:rd.nullish(),EntryDefaults:od.nullish(),CreationDefaults:ad.nullish()}).passthrough(),Sa=zod.z.object({InstantBattle:Ex.nullish()}).passthrough(),ld=Sa;var Ux={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},xa=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),qx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},ba=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),Lx={Burn:"Burn",Ledger:"Ledger"},Bx=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Bn={Item:"Item",VirtualCurrency:"VirtualCurrency"},Da=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),Gx=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish()}).passthrough(),Gn=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(Bi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Pa=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish(),Sink:Bx.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),Gx).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),Fx=zod.z.object({AllowedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedItemIDs:zod.z.array(zod.z.string()).nullish(),AllowUnstackableWithState:zod.z.boolean().nullish(),AllowedCurrencyIDs:zod.z.array(zod.z.string()).nullish(),DeniedCurrencyIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),_x=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:Ce.nullish(),BuyLimits:Ce.nullish(),ListingFeeOptions:ce.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),Vx=zod.z.object({Enabled:zod.z.boolean().nullish(),MinDurationHours:zod.z.number().nullish(),MaxDurationHours:zod.z.number().nullish(),AntiSnipeWindowSeconds:zod.z.number().nullish(),AntiSnipeExtensionSeconds:zod.z.number().nullish(),MaxAntiSnipeExtensions:zod.z.number().nullish(),MinBidStepPercent:zod.z.number().nullish(),MinBidStepAbsolute:j.nullish(),BidLimits:Ce.nullish()}).passthrough(),Nx=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:Ce.nullish(),FillLimits:Ce.nullish()}).passthrough(),jx=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:Ce.nullish()}).passthrough(),Wx=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Ia=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:ye.nullish(),PricePolicy:Gn.nullish(),Commission:Pa.nullish(),Tradability:Fx.nullish(),Listings:_x.nullish(),Auctions:Vx.nullish(),BuyOrders:Nx.nullish(),DirectTrades:jx.nullish(),Matching:Wx.nullish()}).passthrough(),ud=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:j.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:c.nullish()}).passthrough(),Kx=zod.z.object({BidAxisType:pi.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:j.nullish(),CurrentBid:j.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(ud).nullish()}).passthrough(),Ln=zod.z.object({LastAt:c.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),Qx=zod.z.object({Create:Ln.nullish(),Buy:Ln.nullish(),Sell:Ln.nullish(),Bid:Ln.nullish()}).passthrough(),Hx=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),$x=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:Hx.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),zt=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:xa.nullish(),Status:ba.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:Ee.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:Da.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),GoodsInstances:zod.z.array($x).nullish(),Price:pe.nullish(),Auction:Kx.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),Jx=zod.z.object({GoodsType:Da.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(xa,j).nullish()}).passthrough(),cd=zod.z.object({Definitions:Ia.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),va=zod.z.object({Offers:zod.z.array(zt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),pd=zod.z.object({Groups:zod.z.array(Jx).nullish()}).passthrough(),dd=zod.z.object({Offer:zt.nullish()}).passthrough(),lt=zod.z.object({OfferID:zod.z.string().nullish(),Status:ba.nullish(),Settlement:Dt.nullish(),Resources:M.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Gi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:zt.nullish(),Resources:M.nullish(),Matched:zod.z.boolean().nullish(),Settlement:lt.nullish()}).passthrough(),hd=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:j.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish()}).passthrough(),Fn=zod.z.object({MyOffers:zod.z.array(zt).nullish(),MyBids:zod.z.array(zt).nullish(),MyBuyOrders:zod.z.array(zt).nullish(),IncomingTrades:zod.z.array(zt).nullish(),OutgoingTrades:zod.z.array(zt).nullish(),Claimables:zod.z.array(zt).nullish(),DrainedRefunds:zod.z.array(ud).nullish(),Limits:Qx.nullish()}).passthrough(),Zx=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:xa.nullish(),FinalStatus:ba.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:Da.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),PricePaid:pe.nullish(),CommissionTaken:pe.nullish(),CompletedAt:c.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),md=zod.z.object({Entries:zod.z.array(Zx).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),ze={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 Yx="Marketplace",fd={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"]},_n=class{constructor(e){this.ctx=e;e.cache.bindLoginView(fd,{schema:Fn,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(Yx,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,s=20){if(!e)return u("client","ItemID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.ItemID=e,n.OfferTypeFilter=t,n.ContinuationToken=i,n.PageSize=s;let o=await this.ctx.api.marketplace.getOffersByItem(n);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let s=this.ctx.authedRequest();if(!s)return a;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(fd,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let s=this.ctx.authedRequest();if(!s)return a;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let n=await this.ctx.api.marketplace.getHistory(s);return n.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",n.data),n}async createListing(e,t,i,s,n,o,p){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!s)return u("client","PriceBundle is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.PriceBundle=s,h.DurationHours=n,h.ItemInstanceIDs=o,h.SelectedOptionID=p;let R=await this.ctx.api.marketplace.createListing(h);return this.applyCreateOfferResult(R,"marketplace:listingCreated"),R}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return a;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return a;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,s,n,o,p={}){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.BidAxisType=s,h.BidCurrencyID=p.bidCurrencyID,h.BidCatalogID=p.bidCatalogID,h.BidItemID=p.bidItemID,h.StartingBid=n,h.DurationHours=o,h.ItemInstanceIDs=p.itemInstanceIDs,h.SelectedOptionID=p.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(h);return this.applyCreateOfferResult(R,"marketplace:auctionCreated"),R}async placeBid(e,t){if(!e)return u("client","OfferID is required.");if(!t||t<=0)return u("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.BidAmount=t;let 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 u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,s,n){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!s)return u("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return a;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=s,o.DurationHours=n;let p=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,s,n){if(!e)return u("client","TargetUserID is required.");if(!t)return u("client","CatalogID is required.");if(!i)return u("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return a;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=s,o.RequestedBundle=n;let p=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return u("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.Accept=t;let 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 a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return u("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.OfferID=e;let n=await t(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,n.data)),n}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=Bn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Bn.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):u("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var Vn=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return u("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let 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 u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;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 u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;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 u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return a;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 u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.TargetUserID=t;let 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 a;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 u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.LastSeq=t;let 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 u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");if(!i)return u("client","SignalKind is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.TargetUserID=t,n.SignalKind=i,n.Payload=s;let o=await this.ctx.api.multiplayer.sendSignal(n);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.ChatText=t;let 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 u("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return a;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 gd=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Nn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.ParentContentID=e.parentContentID,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):a}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return u("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):a}async getCreatorProfile(e,t,i){if(!e)return u("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):a}async publish(e){if(!e.files||e.files.length===0)return u("client","At least one file is required.");let t=new Map,i=e.files.map((h,R)=>{if("sourceAssetUrl"in h)return {Role:h.role,ContentType:h.contentType,SourceAssetUrl:h.sourceAssetUrl};let B=yd(h.data,h.contentType);return t.set(R,B),{Role:h.role,ContentType:h.contentType,Size:B.size}}),s=e.thumbnail?yd(e.thumbnail.data,e.thumbnail.contentType):null,n=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!n.ok)return n;let o=n.data.Uploads??[];for(let h=0;h<o.length;h++){let R=o[h];if(!R||R.ServerCopy||!R.Url)continue;let B=t.get(h);if(!B)return u("client",`No bytes for file #${h+1}.`);let re=await this.putBytes(R.Url,B,R.ContentType??B.type);if(!re.ok)return re}let p=n.data.ThumbnailUpload;if(p?.Url&&s){let h=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!h.ok)return h}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}):a}async publishUploaded(e){if(!e.ContentID)return u("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return a;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&(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)):a}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let 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 u("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 u("connection",`Download failed: ${n instanceof Error?n.message:String(n)}${gd}`)}return _({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):a}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):a}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?_(!0):u("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return u("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${gd}`)}}contentRequest(e){if(!e)return u("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):a}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function yd(r,e){return r instanceof Blob?r:typeof r=="string"?new Blob([new TextEncoder().encode(r)],{type:e}):r instanceof Uint8Array?new Blob([r.slice().buffer],{type:e}):new Blob([r],{type:e})}var Xx={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},eb=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),tb={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Rd=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),ib={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Cd=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),sb={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},nb=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),rb={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},ob=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),ab={Count:"Count",Sum:"Sum"},lb=zod.z.enum(["Count","Sum"]).catch("Count"),ub={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},cb=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),pb={Strict:"Strict",Loose:"Loose"},db=zod.z.enum(["Strict","Loose"]).catch("Strict"),hb=zod.z.object({Kind:ob,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),mb=zod.z.object({Type:Rd,ItemType:Rd.nullish(),Ref:hb.nullish(),Required:zod.z.boolean().optional(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),MaxItems:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish(),Unique:zod.z.boolean().optional(),UniqueIgnoreCase:zod.z.boolean().optional(),Indexed:zod.z.boolean().optional(),Visibility:Cd.optional(),ClientWritable:zod.z.boolean().nullish(),Immutable:zod.z.boolean().optional(),Description:zod.z.string().nullish(),AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxFileBytes:zod.z.number().nullish()}),fb=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),jn=zod.z.object({Mode:nb,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),gb=zod.z.object({Read:zod.z.array(jn).nullish(),Create:zod.z.array(jn).nullish(),Update:zod.z.array(jn).nullish(),Delete:zod.z.array(jn).nullish()}),Ta=zod.z.object({Cost:pe.nullish(),Grant:pe.nullish()}),yb=zod.z.object({ID:zod.z.string(),SortKey:zod.z.string(),PartitionField:zod.z.string().nullish(),PageSize:zod.z.number().optional(),MaxItems:zod.z.number().optional(),PublishItems:zod.z.boolean().optional()}),Rb=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Namespace:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Enabled:zod.z.boolean().nullish(),Kind:eb,Mode:db.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),mb).nullish(),SortKeys:zod.z.array(fb).nullish(),Access:gb.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:cb.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:lb,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:Cd.optional()})).nullish(),Economy:zod.z.object({OnCreate:Ta.nullish(),OnUpdate:Ta.nullish(),OnDelete:Ta.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:zod.z.array(yb).nullish(),AnonymousSearch:zod.z.boolean().nullish(),Integrations:zod.z.object({QuestMetricOnCreate:zod.z.string().nullish(),QuestMetricOnUpdate:zod.z.string().nullish(),QuestMetricOnDelete:zod.z.string().nullish(),AnalyticsEventOnCreate:zod.z.string().nullish(),AnalyticsEventOnUpdate:zod.z.string().nullish(),AnalyticsEventOnDelete:zod.z.string().nullish(),TriggerOnCreate:zod.z.string().nullish(),TriggerOnUpdate:zod.z.string().nullish(),TriggerOnDelete:zod.z.string().nullish()}).nullish(),Moderation:zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish()}).nullish()}),Sd=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),Rb).default({})}),Cb=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),xd=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),xi=zod.z.object({Collection:zod.z.string(),ItemID:zod.z.string(),OwnerUserID:zod.z.string().nullish(),Data:zod.z.record(zod.z.string(),zod.z.unknown()).default({}),Version:zod.z.number(),CreatedAt:zod.z.string(),UpdatedAt:zod.z.string(),ExpireAt:zod.z.string().nullish(),Expanded:zod.z.record(zod.z.string(),zod.z.unknown()).nullish(),Files:zod.z.record(zod.z.string(),Cb).nullish()}),Aa=zod.z.object({Item:xi}),bd=zod.z.object({Items:zod.z.array(xi).default([]),Missing:zod.z.array(zod.z.string()).default([])}),ka=zod.z.object({Items:zod.z.array(xi).default([]),NextCursor:zod.z.string().nullish()}),Dd=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),wa=zod.z.object({Item:xi,AlreadyExists:zod.z.boolean().optional(),Economy:M.nullish()}),Pd=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:M.nullish()}),Id=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),vd=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:xi.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),Td=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),Ad=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),kd=zod.z.object({Version:zod.z.string(),Collection:zod.z.string(),View:zod.z.string(),SortKey:zod.z.string().nullish(),PageSize:zod.z.number(),UpdatedAt:zod.z.string(),BaseUrl:zod.z.string(),Partitions:zod.z.record(zod.z.string(),zod.z.object({Segment:zod.z.string(),Pages:zod.z.number(),Total:zod.z.number()})).default({})}),wd=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(xi).default([])}),Sb={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 xb=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Od=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Ma=100,zd=25,Md=100;function bb(r,e,t){return {Field:r,Op:e,Value:t}}var Wn=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(a)}get(e,t,i={}){let s=it(e)??Fi(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=it(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(o=>Od.test(o)))];return n.length?n.length>Md?Promise.resolve(u("client",`At most ${Md} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:n,Expand:i.expand})):Promise.resolve(u("client","At least one valid item id is required."))}query(e,t={},i={}){let s=it(e)??za(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.query({...n,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),n=[],o=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:o,Limit:t.Limit??Ma},i);if(!p.ok)return p;if(n.push(...p.data.Items),o=p.data.NextCursor??void 0,!o||n.length>=s)return _(n.slice(0,s))}}count(e,t={}){let i=it(e)??za(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=it(e)??(i.itemID?Fi(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=it(e)??Fi(t);return n?Promise.resolve(n):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=it(e)??Fi(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(u("client","Operations are empty."));if(e.length>zd)return Promise.resolve(u("client",`At most ${zd} operations per batch.`));let t=e.map(i=>it(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=it(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=it(e);return n?Promise.resolve(n):t?s>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(u("client","File size must be positive.")):Promise.resolve(u("client","Field is required."))}async uploadFile(e,t,i,s={}){let n=s.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,n,i.size);if(!o.ok)return o;let p=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||n);return p.ok?o:p}async getPublicViews(e){let t=it(e);if(t)return t;let i=this.publicViews.get(e);if(i)return _(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 u("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(n,kd);if(!o.ok)return o;let p=o.data.Partitions[i.partition??""],h=Math.max(1,i.page??1);if(!p||h>p.Pages)return _({pointer:o.data,page:{Page:h,HasMore:false,Items:[]}});let R=await this.fetchJson(`${o.data.BaseUrl}${p.Segment}/page-${h}.json`,wd);return R.ok?_({pointer:o.data,page:R.data}):R}getPublic(e,t){let i=it(e)??Fi(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=it(e)??za(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(a)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?_(!0):u("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return u("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 u("connection","Internet Connection Error")}if(!i.ok)return u("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return u("server","CDN answer is not JSON.")}let n=t.safeParse(s);return n.success?_(n.data):u("server","CDN answer has an unexpected shape.")}};function it(r){return xb.test(r??"")?null:u("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function Fi(r){return Od.test(r??"")?null:u("client",`Item id '${r}' is invalid.`)}function za(r){return r.Limit!=null&&(r.Limit<1||r.Limit>Ma)?u("client",`Limit must be 1..${Ma}.`):(r.Where?.length??0)>8?u("client","At most 8 filters per query."):null}var Oa={Open:"Open",Declared:"Declared"},Db=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),Pb=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),Ed=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Db).nullish(),Dimensions:zod.z.array(Pb).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),Vt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},St={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Kn=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Ib={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},vb=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),Ud=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(vb).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),Ea={LogEvents:"LogEvents"};function qd(r,e=0){let t=r??"",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 o=/\bWindows NT (\d+\.\d+)/.exec(t);return o?{osName:"Windows",osVersion:o[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function Ld(r){let e=typeof navigator>"u"?void 0:navigator,t=qd(e?.userAgent??"",e?.maxTouchPoints??0),i={};r.appVersion&&(i.AppVersion=r.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let s=r.locale||e?.language;return s&&(i.Language=s),i}var Tb=25,Ab=3e4,Bd=1800*1e3,Gd=500,kb=5,wb=1e3,zb=3600*1e3,Fd="idos_analytics_queue",Ua="idos_analytics_pending",qa="idos_analytics_opt_out",_d="idos_analytics_first_open",Vd="idos_analytics_last_activity",Nd="idos_analytics_last_context",jd="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"||!Kn.test(e)?u("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Mb(e)?u("client",`Event name "${e}" uses a reserved prefix (${St.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return u("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Vt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return _(null);if(this.config()?.Enabled===false)return this.clear(),_(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return _(null);this.pending={BatchID:G(),Events:this.queue.splice(0,St.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=kb)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(qa);return}this.write(qa,"1"),this.clear();}get isEnabled(){return this.read(qa)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(jd);e&&t&&t!==e&&this.clear(),e&&this.write(jd,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Ab),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(Vd)??"0");this.read(_d)||(this.write(_d,new Date().toISOString()),this.enqueue(Vt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Nd);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Vt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Vt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Nd,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=Bd)&&this.enqueue(Vt.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>=Bd&&this.enqueue(Vt.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 _(null);let n=this.config();if(n?.Enabled===false)return _(null);if(s&&n?.AutomaticEvents===false)return _(null);if(n?.Events?.[e]?.Blocked)return u("client",`Event "${e}" is blocked by the title.`);if(!s&&n?.EventNaming?.toLowerCase()===Oa.Declared.toLowerCase()&&!n.Events?.[e])return u("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return u("client","value must be a finite number.");let o=Ob(t);if(o.error)return u("client",o.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(p.Params=o.params),i!==void 0&&(p.Value=i),this.queue.push(p),this.queue.length>Gd&&this.queue.splice(0,this.queue.length-Gd),this.touch(),this.persist(),this.started&&this.queue.length>=Tb&&this.flush(),_(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},wb));}dropStale(){let e=Date.now()-(St.maxEventAgeMs-zb);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??=Ld({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(Fd);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(Ua);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(Fd,this.queue),this.pending?this.writeJson(Ua,this.pending):this.remove(Ua);}touch(){this.write(Vd,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 Mb(r){let e=r.toLowerCase();return St.reservedPrefixes.some(t=>e.startsWith(t))}function Ob(r){if(!r)return {};let e=Object.keys(r);if(e.length===0)return {};if(e.length>St.maxParams)return {error:`Too many parameters: ${e.length}, max ${St.maxParams}.`};let t={};for(let i of e){if(!Kn.test(i))return {error:`Invalid parameter name "${i}".`};let s=r[i];typeof s=="string"?t[i]=s.length>St.maxStringValueLength?s.slice(0,St.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var Eb="idos_experiments",Hn=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let n=Number(s);return s.trim()!==""&&Number.isFinite(n)?n:i}if(typeof i=="boolean"){let n=s.trim().toLowerCase();return n==="true"||n==="1"?true:n==="false"||n==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,n]of t){let o=this.views.get(s);(!o||o.VariantID!==n.VariantID||o.Status!==n.Status)&&i.push(n);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.platform.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.platform.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${Eb}:${this.ctx.settings.titleID}`}};function Nt(r,e,t,i){let n=`api/v2/${r&&r.length>0?r:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var L=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Nt(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 $n=class extends L{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(Ea.LogEvents,e,Ud,{silent:true})}};var Ub=zod.z.object({VariantID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Weight:zod.z.number().nullish(),IsControl:zod.z.boolean().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),qb={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Lb=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),Bb=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:ye.nullish(),Gate:Z.nullish(),Variants:zod.z.array(Ub).nullish(),Salt:zod.z.string().nullish(),LayerID:zod.z.string().nullish(),StickyAssignment:zod.z.boolean().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Goals:zod.z.array(Lb).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),Wd=zod.z.object({Experiments:zod.z.record(zod.z.string(),Bb).nullish()}).passthrough(),Gb={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Fb=zod.z.object({ExperimentID:zod.z.string().nullish(),VariantID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Kd=zod.z.object({Experiments:zod.z.array(Fb).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),La={GetExperiments:"GetExperiments"};var Jn=class extends L{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(La.GetExperiments,e,Kd)}};var Qd=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:c.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:c,PlayAccess:_t.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:c.nullish()}),Hd=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:c,RefreshToken:zod.z.string(),RefreshTokenExpiration:c.nullish(),PlayAccess:_t.nullish()}),_b=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),$d=zod.z.object({Google:zod.z.object({Enabled:zod.z.boolean().nullish(),WebClientID:zod.z.string().nullish(),PlatformFallback:zod.z.boolean().nullish(),AndroidClientID:zod.z.string().nullish(),IosClientID:zod.z.string().nullish(),DesktopClientID:zod.z.string().nullish()}).passthrough().nullish(),Apple:zod.z.object({Enabled:zod.z.boolean().nullish(),BundleID:zod.z.string().nullish(),ServiceID:zod.z.string().nullish()}).passthrough().nullish(),PlayAccessMode:Li.nullish(),WalletLoginNetworks:zod.z.array(zod.z.object({NetworkID:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:zod.z.boolean().nullish(),NativeSso:_b.nullish()}).passthrough(),Jd=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:c.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:_t.nullish()}).passthrough(),Zd=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:c.nullish(),PlayAccess:_t.nullish()}).passthrough(),Yd=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),qe=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:c.nullish()}),Xd=zod.z.object({Message:zod.z.string(),ExpiresAt:c}),Ue={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",ResolvePlatformGameSession:"ResolvePlatformGameSession",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var Zn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Nt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,Qd,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ue.RefreshSession),e,Hd,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ue.GetAuthOptions),e,$d,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Nt(this.ctx.settings.titleID,"Authentication",Ue.LinkWallet,e.UserID??""),e,Jd,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Nt(this.ctx.settings.titleID,"Authentication",Ue.UnlinkWallet,e.UserID??""),e,Zd,{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)}resolvePlatformGameSession(e){return this.login(Ue.ResolvePlatformGameSession,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ue.RegisterWithEmail),e,Yd,{ticket:null})}confirmEmailRegistration(e){return this.login(Ue.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ue.ResendVerificationCode),e,qe,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ue.RequestWalletChallenge),e,Xd,{ticket:null})}loginWithWallet(e){return this.login(Ue.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ue.ForgotPassword),e,qe,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ue.ResetPassword),e,qe,{ticket:null})}};var Vb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},eh=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Nb=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),th=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),Nb).nullish(),MissingKeyMode:eh.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),jb=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),ih=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:jb.nullish()}).passthrough(),Yn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Wb=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),sh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:eh.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(Wb).nullish()}).passthrough(),nh=zod.z.object({RequestedLocale:zod.z.string().nullish(),Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),NotModified:zod.z.boolean().nullish(),Entries:zod.z.record(zod.z.string(),zod.z.string()).nullish(),FallbackLocale:zod.z.string().nullish(),FallbackVersion:zod.z.number().nullish()}).passthrough();var Ba=zod.z.object({TitleConfigVersion:zod.z.string().nullish(),TitleConfigUrl:zod.z.string().nullish(),User:zod.z.unknown().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish(),Localization:ih.nullish(),Views:zod.z.array(zod.z.object({Name:zod.z.string(),Key:zod.z.string().nullish(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(r=>r),rh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(r=>r),oh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),User:zod.z.unknown().nullish()}).passthrough().transform(r=>r),ah=zod.z.object({}).passthrough().transform(r=>r),lh=zod.z.object({}).passthrough().transform(r=>r),uh=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:c.nullish(),LastActiveAt:c.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),ch=zod.z.object({Username:zod.z.string()}),ut={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Xn=class extends L{constructor(e){super(e,"User");}getClientState(e){return this.send(ut.GetClientState,e,Ba)}getClientStateExcept(e){return this.send(ut.GetClientStateExcept,e,Ba)}getStateVersions(e){return this.send(ut.GetStateVersions,e,rh)}getUserState(e){return this.send(ut.GetUserState,e,oh)}getInventory(e){return this.send(ut.GetInventory,e,ah)}getEventTokens(e){return this.send(ut.GetEventTokens,e,lh)}getUsageTime(e){return this.send(ut.GetUsageTime,e,uh)}addUsageTime(e){return this.send(ut.AddUsageTime,e,qe,{silent:true})}deleteUserAccount(e){return this.send(ut.DeleteUserAccount,e,qe)}changeUsername(e){return this.send(ut.ChangeUsername,e,ch)}};var er=class extends L{constructor(e){super(e,"Currency");}convert(e){return this.send(Mn.Convert,e,kp)}cryptoConvert(e){return this.send(Mn.CryptoConvert,e,wp)}};var Kb=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),Ga=zod.z.object({ServerTimeUtc:c,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:M.nullish(),FodderConsumed:zod.z.array(Kb).nullish()}),ph=zod.z.array(Te(Ga)),tr={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Qb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},Hb=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),$b={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Jb=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Zb=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),Yb=zod.z.object({Networks:zod.z.record(zod.z.string(),Zb).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),Xb=zod.z.object({FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),eD=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),UseRequirements:zod.z.record(zod.z.string(),zod.z.number()).nullish(),AllowedCharacterIDs:zod.z.array(zod.z.string()).nullish(),AllowedSlotIDs:zod.z.array(zod.z.string()).nullish(),IdleRateBonus:zod.z.number().nullish()}).passthrough(),tD=zod.z.object({ValuationMode:Hb.nullish(),WeightCurve:_e.nullish(),Selection:Jb.nullish()}).passthrough(),iD=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:_e.nullish(),FlatBonusCurve:_e.nullish(),PercentBonusCurve:_e.nullish(),PowerCurve:_e.nullish(),Fodder:tD.nullish()}).passthrough(),sD=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),nD=zod.z.object({ItemID:zod.z.string(),CatalogID:zod.z.string(),ItemClass:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsStackable:zod.z.boolean().nullish(),IsTradable:zod.z.boolean().nullish(),Weight:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),NFT:Yb.nullish(),Stats:Xb.nullish(),Equipment:eD.nullish(),Upgrade:iD.nullish(),Metadata:sD.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),rD=zod.z.object({Items:zod.z.record(zod.z.string(),nD).nullish()}).passthrough(),ir=zod.z.object({Catalogs:zod.z.record(zod.z.string(),rD).nullish()}).passthrough();var sr=class extends L{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(tr.UpgradeLevel,e,Ga)}upgradeLevelsBatch(e){return this.send(tr.UpgradeLevelsBatch,e,ph)}};var nr=class extends L{constructor(e){super(e,"Store");}purchase(e){return this.send(Tt.Purchase,e,Po)}purchaseBatch(e){return this.send(Tt.PurchaseBatch,e,mu)}getDefinitions(e){return this.send(Tt.GetDefinitions,e,bs)}getUserState(e){return this.send(Tt.GetUserState,e,fu)}getStorefront(e){return this.send(Tt.GetStorefront,e,Ds)}getCreditsConfirmation(e){return this.send(Tt.GetCreditsConfirmation,e,Do)}getCreditsBalance(e){return this.send(Tt.GetCreditsBalance,e,hu)}};var oD={Apple:"Apple",Google:"Google"},rr=zod.z.object({PremiumID:zod.z.string().nullish(),PurchaseDate:zod.z.string().nullish(),ExpirationDate:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),IsAutoRenewEnabled:zod.z.boolean().nullish()}).passthrough(),or=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),rr).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(r=>r),aD=zod.z.object({PremiumID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Tier:zod.z.number().nullish(),DurationDays:zod.z.number().nullish(),TrialDurationDays:zod.z.number().nullish(),PriceOptions:ce.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Fa=zod.z.object({Definitions:zod.z.record(zod.z.string(),aD).nullish()}).passthrough(),dh=zod.z.object({Premium:Fa.nullish()}),hh=zod.z.object({ServerTimeUtc:c.nullish(),Premium:or.nullish()}),ar=zod.z.object({ServerTimeUtc:c.nullish(),Premium:or.nullish(),Subscription:rr.nullish(),Resources:M.nullish()}),Yt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var lD={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},uD=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),mh=zod.z.object({StartUtc:c.nullish(),EndUtc:c.nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),_a=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),cD=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),pD=zod.z.object({Rewards:K.nullish(),Rules:K.nullish(),Refund:K.nullish()}).passthrough(),dD=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:uD.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:mh.nullish(),Refund:_a.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:cD.nullish(),Presets:pD.nullish()}).passthrough(),hD=zod.z.object({StoreID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),PackageName:zod.z.string().nullish(),VerificationMode:zod.z.string().nullish(),PlayPublicKey:zod.z.string().nullish(),RequireCertificateChain:zod.z.boolean().nullish(),SecretName:zod.z.string().nullish(),IssuerID:zod.z.string().nullish(),KeyID:zod.z.string().nullish(),AcknowledgePurchases:zod.z.boolean().nullish(),NotificationPackageName:zod.z.string().nullish()}).passthrough(),mD=zod.z.object({Rewards:H.nullish()}).passthrough(),fD=zod.z.object({Rules:mh.nullish()}).passthrough(),gD=zod.z.object({Refund:_a.nullish()}).passthrough(),yD=zod.z.object({Rewards:zod.z.record(zod.z.string(),mD).nullish(),Rules:zod.z.record(zod.z.string(),fD).nullish(),Refund:zod.z.record(zod.z.string(),gD).nullish()}).passthrough(),RD=zod.z.object({MaxPurchaseAgeDays:zod.z.number().nullish(),AllowSandbox:zod.z.boolean().nullish(),RequirePackageMatch:zod.z.boolean().nullish(),MaxReceiptsPerBatch:zod.z.number().nullish(),RefundCheckHorizonDays:zod.z.number().nullish(),RejectCrossUserReceipts:zod.z.boolean().nullish()}).passthrough(),CD=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),dD).nullish(),Stores:zod.z.record(zod.z.string(),hD).nullish(),Presets:yD.nullish(),Validation:RD.nullish(),Refund:_a.nullish()}).passthrough(),fh=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:c.nullish(),LastPurchasedAt:c.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),gh=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:c.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:c.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:c.nullish()}).passthrough(),SD=zod.z.object({Products:zod.z.record(zod.z.string(),fh).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),gh).nullish(),LastRefundCheckAt:c.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:c.nullish(),LastPurchaseAt:c.nullish()}).passthrough(),xD=zod.z.object({ProductID:zod.z.string(),Available:zod.z.boolean(),Owned:zod.z.boolean(),Blocked:zod.z.boolean(),Reason:zod.z.string().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),yh=zod.z.object({ServerTimeUtc:c,Purchase:CD.nullish(),Availability:zod.z.array(xD).nullish()}),Rh=zod.z.object({ServerTimeUtc:c,Purchase:SD.nullish()}),bD={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},DD=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Va=zod.z.object({ServerTimeUtc:c,Store:Qi.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:DD.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),ProductState:fh.nullish(),Premium:or.nullish(),Subscription:rr.nullish(),SubscriptionMirror:gh.nullish()}).passthrough(),Ch=zod.z.object({ServerTimeUtc:c,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:c.nullish()}).passthrough(),Sh=gt(Va),Xt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var lr=class extends L{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(Xt.GetDefinitions,e,yh)}getUserState(e){return this.send(Xt.GetUserState,e,Rh)}validatePurchase(e){return this.send(Xt.ValidatePurchase,e,Va)}validatePurchasesBatch(e){return this.send(Xt.ValidatePurchasesBatch,e,Sh)}createTelegramInvoice(e){return this.send(Xt.CreateTelegramInvoice,e,Ch)}};var PD=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),xh=zod.z.object({Reward:H.nullish(),Weight:zod.z.number().nullish(),AmountRange:PD.nullish()}).passthrough(),bi=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(xh).nullish()}).passthrough(),Di=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(xh).nullish()}).passthrough(),ID=zod.z.object({RewardSlots:zod.z.array(bi).nullish()}).passthrough(),vD=zod.z.object({PityRules:zod.z.array(Di).nullish()}).passthrough(),ur=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),ID).nullish(),PityPresets:zod.z.record(zod.z.string(),vD).nullish()}).passthrough();var TD=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),bh=zod.z.object({ServerTimeUtc:c,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:zod.z.array(M).nullish(),TriggeredPity:zod.z.array(TD).nullish()}),AD=zod.z.object({RewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),kD=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:j.nullish()}).passthrough(),wD=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ce.nullish(),RewardSlots:zod.z.array(bi).nullish(),PityRules:zod.z.array(Di).nullish(),Presets:AD.nullish(),RewardMultiplier:$i.nullish(),SupplyLimits:zod.z.array(kD).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),zD=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Na=zod.z.object({Definitions:zod.z.record(zod.z.string(),wD).nullish(),RewardPools:ur.nullish(),Settings:zD.nullish()}).passthrough(),Dh=zod.z.object({LootboxDefinitions:Na.nullish()}),cr={GetDefinitions:"GetDefinitions",Open:"Open"};var pr=class extends L{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(cr.GetDefinitions,e,Dh)}open(e){return this.send(cr.Open,e,bh)}};var MD=zod.z.object({}).passthrough().transform(r=>r),OD=zod.z.object({}).passthrough().transform(r=>r),ED=zod.z.object({}).passthrough().transform(r=>r),UD=zod.z.object({}).passthrough().transform(r=>r),qD=zod.z.object({}).passthrough().transform(r=>r),Ph=zod.z.object({ServerTimeUtc:c,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:MD,Resources:M.nullish(),Inventory:Q.nullish()}),Ih=zod.z.object({ServerTimeUtc:c,AccrualID:zod.z.string(),AccruedSeconds:j.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:OD,Resources:M.nullish(),Inventory:Q.nullish()}),vh=zod.z.object({ServerTimeUtc:c,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:ED,Resources:M.nullish(),Inventory:Q.nullish()}),Th=zod.z.object({ServerTimeUtc:c,ClaimID:zod.z.string(),ClaimState:UD,Resources:M.nullish(),Inventory:Q.nullish()}),Ah=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:j.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),LD=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),BD=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:H.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),_i=zod.z.object({Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),ja=zod.z.object({Availability:K.nullish()}).passthrough(),GD=zod.z.object({Availability:zod.z.record(zod.z.string(),_i).nullish()}).passthrough(),FD=zod.z.object({CalendarID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Days:zod.z.array(BD).nullish(),IsLooping:zod.z.boolean().nullish(),MissBehavior:zod.z.string().nullish(),ResetByDays:zod.z.number().nullish(),MissThresholdMultiplier:zod.z.number().nullish(),ClaimMode:zod.z.string().nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),Availability:_i.nullish(),Presets:ja.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),_D=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),VD=zod.z.object({BaseRatePerSecond:zod.z.number().nullish(),PowerCoefficient:zod.z.number().nullish(),BoardRankCoefficient:zod.z.number().nullish(),EquipmentBonusEnabled:zod.z.boolean().nullish(),EquipmentCharacterID:zod.z.string().nullish(),PremiumMultipliers:zod.z.array(_D).nullish()}).passthrough(),ND=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:_i.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),jD=zod.z.object({AccrualID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rate:VD.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:ND.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),WD=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:H.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),KD=zod.z.object({ComebackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(WD).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:_i.nullish(),Presets:ja.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),QD=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxClaimsPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish(),TotalClaimLimit:zod.z.number().nullish()}).passthrough(),HD=zod.z.object({ClaimID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Mode:zod.z.string().nullish(),Rewards:H.nullish(),PremiumLimitOverrides:zod.z.array(QD).nullish(),Availability:_i.nullish(),Presets:ja.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),Wa=zod.z.object({TierRewards:LD.nullish(),MilestoneRewardMultiplier:$i.nullish(),DailyCalendars:zod.z.record(zod.z.string(),FD).nullish(),IdleAccruals:zod.z.record(zod.z.string(),jD).nullish(),Comebacks:zod.z.record(zod.z.string(),KD).nullish(),Claims:zod.z.record(zod.z.string(),HD).nullish(),Presets:GD.nullish()}).passthrough(),kh=zod.z.object({RewardDefinitions:Wa.nullish()}),wh=zod.z.object({Rewards:qD.nullish()}),Mt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var dr=class extends L{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Mt.GetRewardDefinitions,e,kh)}getUserRewardsState(e){return this.send(Mt.GetUserRewardsState,e,wh)}getMilestoneRewardMultiplier(e){return this.send(Mt.GetMilestoneRewardMultiplier,e,Ah)}claimDailyReward(e){return this.send(Mt.ClaimDailyReward,e,Ph)}collectIdleAccrual(e){return this.send(Mt.CollectIdleAccrual,e,Ih)}claimComebackReward(e){return this.send(Mt.ClaimComebackReward,e,vh)}claimReward(e){return this.send(Mt.ClaimReward,e,Th)}};var hr=class extends L{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(rt.GetTutorialDefinitions,e,jl)}getUserTutorialState(e){return this.send(rt.GetUserTutorialState,e,Yi)}startFlow(e){return this.send(rt.StartFlow,e,Et)}reportStepShown(e){return this.send(rt.ReportStepShown,e,Et)}completeStep(e){return this.send(rt.CompleteStep,e,Et)}completeStepsBatch(e){return this.send(rt.CompleteStepsBatch,e,Ql)}skipStep(e){return this.send(rt.SkipStep,e,Et)}skipFlow(e){return this.send(rt.SkipFlow,e,Et)}claimFlowReward(e){return this.send(rt.ClaimFlowReward,e,Kl)}resetFlow(e){return this.send(rt.ResetFlow,e,Et)}};var $D={Open:"Open",Application:"Application"},JD=zod.z.enum(["Open","Application"]).catch("Open"),ZD={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},zh=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),YD={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Ka=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),XD={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var ei={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},eP=zod.z.object({CampaignID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IsRunning:zod.z.boolean().nullish()}).passthrough(),Mh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:JD.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:zh.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(eP).nullish()}).passthrough(),tP=zod.z.object({Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),CountedMetrics:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ReachedMilestones:zod.z.array(zod.z.string()).nullish(),CappedBySubmissionLimit:zod.z.boolean().nullish(),CappedByCreatorLimit:zod.z.boolean().nullish(),NotPaidAsCopy:zod.z.boolean().nullish()}).passthrough(),iP=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:Ka.nullish(),CurrencyID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),Granted:zod.z.number().nullish(),Paid:zod.z.number().nullish(),Overpaid:zod.z.number().nullish(),Claimable:zod.z.number().nullish(),BySubmission:zod.z.record(zod.z.string(),tP).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),sP=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:Ka.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),Oh=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(iP).nullish(),Payouts:zod.z.array(sP).nullish()}).passthrough(),Eh=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:Ka.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),nP=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),rP=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),Signature:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(nP).nullish()}).passthrough(),oP=zod.z.object({Kind:zod.z.string().nullish(),Target:zod.z.string().nullish(),Required:zod.z.number().nullish(),Actual:zod.z.number().nullish(),Passed:zod.z.boolean().nullish()}).passthrough(),Uh=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:zh.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(oP).nullish()}).passthrough(),aP=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),lP=zod.z.object({ProgramID:zod.z.string().nullish(),Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(aP).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),qh=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:zod.z.number().nullish(),NetAmountNative:zod.z.number().nullish(),BurnAmountNative:zod.z.number().nullish(),AmountUsd:zod.z.number().nullish(),ExpiresAt:zod.z.string().nullish(),EvmSignature:rP.nullish(),SolanaSignature:lP.nullish(),StateDelta:Si.nullish()}).passthrough();var mr=class extends L{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(ei.GetCommunityMarketingState,e,Mh)}getEarnings(e){return this.send(ei.GetEarnings,e,Oh)}claim(e){return this.send(ei.Claim,e,Eh)}checkJoinEligibility(e){return this.send(ei.CheckJoinEligibility,e,Uh)}withdrawCryptoReward(e){return this.send(ei.WithdrawCryptoReward,e,qh)}};var fr=class extends L{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(Qe.GetChatDefinitions,e,zu)}getChannels(e){return this.send(Qe.GetChannels,e,Os)}poll(e){return this.send(Qe.Poll,e,Mu)}getHistory(e){return this.send(Qe.GetHistory,e,Ou)}getConversations(e){return this.send(Qe.GetConversations,e,qu)}sendMessage(e){return this.send(Qe.SendMessage,e,Eu)}openDirectChannel(e){return this.send(Qe.OpenDirectChannel,e,Uu)}markRead(e){return this.send(Qe.MarkRead,e,Ri)}joinChannel(e){return this.send(Qe.JoinChannel,e,Ri)}leaveChannel(e){return this.send(Qe.LeaveChannel,e,Ri)}reportMessage(e){return this.send(Qe.ReportMessage,e,Lu)}ignoreUser(e){return this.send(Qe.IgnoreUser,e,Ri)}unignoreUser(e){return this.send(Qe.UnignoreUser,e,Ri)}};var gr=class extends L{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(Ci.GetPushConfig,e,Fu)}subscribePush(e){return this.send(Ci.SubscribePush,e,Oo)}unsubscribePush(e){return this.send(Ci.UnsubscribePush,e,qe)}getPushSubscriptions(e){return this.send(Ci.GetPushSubscriptions,e,_u)}};var yr=class extends L{constructor(e){super(e,"Localization");}send(e,t,i,s){let n=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${n}:${t.Locale}`:n,...s})}getLocalizationManifest(e){return this.send(Yn.GetLocalizationManifest,e,sh)}getLocalizationTable(e){return this.send(Yn.GetLocalizationTable,e,nh)}};var Rr=class extends L{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(dt.GetQuestDefinitions,e,Zi)}getUserQuestState(e){return this.send(dt.GetUserQuestState,e,Ml)}refreshQuestCycles(e){return this.send(dt.RefreshQuestCycles,e,qe)}claimQuestReward(e){return this.send(dt.ClaimQuestReward,e,ao)}claimQuestRewardsBatch(e){return this.send(dt.ClaimQuestRewardsBatch,e,Ul)}claimMilestoneReward(e){return this.send(dt.ClaimMilestoneReward,e,lo)}claimMilestoneRewardsBatch(e){return this.send(dt.ClaimMilestoneRewardsBatch,e,ql)}claimGroupCompletionReward(e){return this.send(dt.ClaimGroupCompletionReward,e,Ol)}addQuestProgress(e){return this.send(dt.AddQuestProgress,e,El)}};var Cr=class extends L{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(at.GetActiveEvents,e,Fs)}getDefinitions(e){return this.send(at.GetDefinitions,e,Gs)}getUserLteState(e){return this.send(at.GetUserLteState,e,Wu)}grantTokens(e){return this.send(at.GrantTokens,e,M)}spendTokens(e){return this.send(at.SpendTokens,e,qo)}claimMilestone(e){return this.send(at.ClaimMilestone,e,Lo)}claimMilestonesBatch(e){return this.send(at.ClaimMilestonesBatch,e,Bo)}claimAllMilestones(e){return this.send(at.ClaimAllMilestones,e,Bo)}spendTokensBatch(e){return this.send(at.SpendTokensBatch,e,Ku)}grantTokensBatch(e){return this.send(at.GrantTokensBatch,e,Qu)}};var Sr=class extends L{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ve.GetDefinitions,e,Qs)}getLeaderboard(e){return this.send(Ve.GetLeaderboard,e,Mi)}getMyProgress(e){return this.send(Ve.GetMyProgress,e,Vs)}submitScore(e){return this.send(Ve.SubmitScore,e,Ns)}submitScoreFromSource(e){return this.send(Ve.SubmitScoreFromSource,e,Ns)}claimCycleReward(e){return this.send(Ve.ClaimCycleReward,e,js)}claimMilestone(e){return this.send(Ve.ClaimMilestone,e,Ws)}getFriendsLeaderboard(e){return this.send(Ve.GetFriendsLeaderboard,e,Mi)}getLeaderboardsBatch(e){return this.send(Ve.GetLeaderboardsBatch,e,Ju)}getProgressBatch(e){return this.send(Ve.GetProgressBatch,e,Ks)}claimCycleRewardsBatch(e){return this.send(Ve.ClaimCycleRewardsBatch,e,Zu)}claimMilestonesBatch(e){return this.send(Ve.ClaimMilestonesBatch,e,Yu)}submitScoresBatch(e){return this.send(Ve.SubmitScoresBatch,e,Xu)}claimAllRewardsBatch(e){return this.send(Ve.ClaimAllRewardsBatch,e,ec)}getOverviewBatch(e){return this.send(Ve.GetOverviewBatch,e,tc)}};var xr=class extends L{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Lt.GetDefinitions,e,Js)}getActiveSeason(e){return this.send(Lt.GetActiveSeason,e,$s)}getUserState(e){return this.send(Lt.GetUserState,e,Go)}grantStatusTokens(e){return this.send(Lt.GrantStatusTokens,e,rc)}claimTierReward(e){return this.send(Lt.ClaimTierReward,e,Fo)}claimTierRewardsBatch(e){return this.send(Lt.ClaimTierRewardsBatch,e,oc)}};var br=class extends L{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Yt.GetDefinitions,e,dh)}getUserState(e){return this.send(Yt.GetUserState,e,hh)}activateTrial(e){return this.send(Yt.ActivateTrial,e,ar)}purchaseItemOrCurrency(e){return this.send(Yt.PurchaseWithResources,e,ar)}purchaseRealMoney(e){return this.send(Yt.PurchaseRealMoney,e,ar)}};var Dr=class extends L{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(Ne.GetCharacterDefinitions,e,en)}getUserCharacters(e){return this.send(Ne.GetUserCharacters,e,dc)}unlockCharacter(e){return this.send(Ne.UnlockCharacter,e,jo)}upgradeStatLevel(e){return this.send(Ne.UpgradeStatLevel,e,Vo)}upgradeCharacterLevel(e){return this.send(Ne.UpgradeCharacterLevel,e,No)}equipItems(e){return this.send(Ne.EquipItems,e,hc)}unequipItems(e){return this.send(Ne.UnequipItems,e,mc)}unequipAllCharacters(e){return this.send(Ne.UnequipAllCharacters,e,fc)}unlockCharactersBatch(e){return this.send(Ne.UnlockCharactersBatch,e,Sc)}upgradeCharacterLevelsBatch(e){return this.send(Ne.UpgradeCharacterLevelsBatch,e,xc)}upgradeStatLevelsBatch(e){return this.send(Ne.UpgradeStatLevelsBatch,e,bc)}unlockSkin(e){return this.send(Ne.UnlockSkin,e,gc)}equipSkin(e){return this.send(Ne.EquipSkin,e,yc)}unequipSkin(e){return this.send(Ne.UnequipSkin,e,Rc)}getCharacterSkins(e){return this.send(Ne.GetCharacterSkins,e,Cc)}};var Pr=class extends L{constructor(e){super(e,"Match");}createMatch(e){return this.send(Ct.CreateMatch,e,td)}updateMatch(e){return this.send(Ct.UpdateMatch,e,id)}cancelMatch(e){return this.send(Ct.CancelMatch,e,sd)}instantBattle(e){return this.send(Ct.InstantBattle,e,nd)}saveStrategy(e){return this.send(Ct.SaveStrategy,e,qe)}getMyMatches(e){return this.send(Ct.GetMyMatches,e,Ca)}getAvailableMatches(e){return this.send(Ct.GetAvailableMatches,e,Ca)}getDefinitions(e){return this.send(Ct.GetDefinitions,e,ld)}};var uP={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Lh=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),cP={None:"None",Min:"Min",Average:"Average",Max:"Max"},pP=zod.z.enum(["None","Min","Average","Max"]).catch("None"),dP={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},hP=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),mP={Clamp:"Clamp",Reject:"Reject"},fP=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),gP=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),yP=zod.z.object({Index:zod.z.number().nullish(),BurnedItemIDs:zod.z.array(zod.z.string()).nullish(),RolledCollectionID:zod.z.string().nullish(),UsedCollections:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Output:no.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(gP).nullish()}),Bh=zod.z.object({ServerTimeUtc:c,Type:Lh.nullish(),CraftID:zod.z.string(),CraftedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),InputRarity:zod.z.string().nullish(),OutputRarity:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:zod.z.array(yP).nullish()}),RP=zod.z.object({CraftID:zod.z.string().nullish(),Type:Lh.nullish(),CatalogID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),InputRarityID:zod.z.string().nullish(),OutputRarityID:zod.z.string().nullish(),RequiredItemCount:zod.z.number().nullish(),PriceOptions:ce.nullish(),OutputLevelMode:pP.nullish(),InputSelection:hP.nullish(),OutputLevelOverflow:fP.nullish()}).passthrough(),Qa=zod.z.object({Definitions:zod.z.record(zod.z.string(),RP).nullish()}).passthrough(),Gh=zod.z.object({ServerTimeUtc:c.nullish(),CraftDefinitions:Qa.nullish()}),Ir={GetDefinitions:"GetDefinitions",Craft:"Craft"};var vr=class extends L{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(Ir.GetDefinitions,e,Gh)}craft(e){return this.send(Ir.Craft,e,Bh)}};var CP=2e5,Tr=class extends L{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,rn,{timeoutMs:CP,autoRetry:false})}readGeneration(e,t){return this.send(e,t,rn,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Fe.GetDefinitions,e,zc)}generateText(e){return this.generate(Fe.GenerateText,e)}getText(e){return this.readGeneration(Fe.GetText,e)}generateImage(e){return this.generate(Fe.GenerateImage,e)}editImage(e){return this.generate(Fe.EditImage,e)}getImage(e){return this.readGeneration(Fe.GetImage,e)}generateVideo(e){return this.generate(Fe.GenerateVideo,e)}getVideo(e){return this.readGeneration(Fe.GetVideo,e)}generateAudio(e){return this.generate(Fe.GenerateAudio,e)}getAudio(e){return this.readGeneration(Fe.GetAudio,e)}generateMusic(e){return this.generate(Fe.GenerateMusic,e)}getMusic(e){return this.readGeneration(Fe.GetMusic,e)}generateThreeD(e){return this.generate(Fe.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Fe.GetThreeD,e)}listGenerations(e){return this.send(Fe.ListGenerations,e,wc)}getGeneration(e){return this.readGeneration(Fe.GetGeneration,e)}};var SP={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},xP=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),Fh=zod.z.object({}).passthrough().transform(r=>r),Pi=zod.z.object({CollectibleID:zod.z.string(),Rarity:zod.z.number().nullish(),IsSpecial:zod.z.boolean().nullish(),IsDuplicate:zod.z.boolean().nullish(),CollectionCurrencyConverted:zod.z.number().nullish()}),_h=zod.z.object({GrantedCollectibles:zod.z.array(Pi).nullish(),DuplicateCollectibles:zod.z.array(Pi).nullish(),CollectionCurrencyEarned:j.nullish()}),Vh=zod.z.object({OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(_h).nullish(),GrantedCollectibles:zod.z.array(Pi).nullish(),DuplicateCollectibles:zod.z.array(Pi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Nh=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(_h).nullish(),GrantedCollectibles:zod.z.array(Pi).nullish(),DuplicateCollectibles:zod.z.array(Pi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),jh=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ha=zod.z.object({SetID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),Wh=zod.z.array(Te(Ha)),Kh=zod.z.object({Resources:M.nullish(),Inventory:Q.nullish()}),bP=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:Ee.nullish(),OfferedCollectibleID:zod.z.string().nullish(),OfferedCollectibleIsSpecial:zod.z.boolean().nullish(),ReceiverUserID:zod.z.string().nullish(),RequestedCollectibleID:zod.z.string().nullish(),RequestedCollectibleIsSpecial:zod.z.boolean().nullish(),Status:xP.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RespondedAtUtc:c.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),Qh=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:c.nullish(),Resources:M.nullish()}),Hh=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),$h=zod.z.object({OfferID:zod.z.string(),ReceivedCollectibleID:zod.z.string().nullish(),ReceivedIsSpecial:zod.z.boolean().nullish(),SentCollectibleID:zod.z.string().nullish(),SentCollectibleIsSpecial:zod.z.boolean().nullish(),Transfer:zod.z.unknown().nullish()}),Jh=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),$a=zod.z.object({Offers:zod.z.array(bP).nullish()}),DP=zod.z.object({CollectibleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rarity:zod.z.number().nullish(),HasSpecialVersion:zod.z.boolean().nullish(),SortOrder:zod.z.number().nullish()}).passthrough(),PP=zod.z.object({SetID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SortOrder:zod.z.number().nullish(),Collectibles:zod.z.array(DP).nullish(),SetCompletionReward:H.nullish()}).passthrough(),IP=zod.z.object({CollectionID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SeasonChainID:zod.z.string().nullish(),Sets:zod.z.array(PP).nullish(),GrandPrize:H.nullish()}).passthrough(),Zh=zod.z.object({BonusRewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),vP=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:ce.nullish(),BonusRewardSlots:zod.z.array(bi).nullish(),PityRules:zod.z.array(Di).nullish(),Presets:Zh.nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectibleCount:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),GuaranteeMaxRarity:zod.z.boolean().nullish(),RarityWeights:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ColorTier:zod.z.number().nullish()}).passthrough(),TP=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),AP=zod.z.object({CollectionChestID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectionCurrencyCost:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),MinCollectibleCount:zod.z.number().nullish(),MaxCollectibleCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),BonusRewardSlots:zod.z.array(bi).nullish(),PityRules:zod.z.array(Di).nullish(),Presets:Zh.nullish(),Tier:zod.z.number().nullish()}).passthrough(),kP=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),wP=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),Ar=zod.z.object({Collections:zod.z.record(zod.z.string(),IP).nullish(),PackTypes:zod.z.record(zod.z.string(),vP).nullish(),CollectionChests:zod.z.array(AP).nullish(),DuplicateConversions:zod.z.array(TP).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(kP).nullish(),RewardPools:ur.nullish(),Settings:wP.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 kr=class extends L{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(je.GetDefinitions,e,Ar)}getUserState(e){return this.send(je.GetUserState,e,Fh)}openPack(e){return this.send(je.OpenPack,e,Vh)}openCollectionChest(e){return this.send(je.OpenCollectionChest,e,Nh)}useCollectibleJoker(e){return this.send(je.UseCollectibleJoker,e,jh)}claimSetReward(e){return this.send(je.ClaimSetReward,e,Ha)}claimSetRewardsBatch(e){return this.send(je.ClaimSetRewardsBatch,e,Wh)}claimGrandPrize(e){return this.send(je.ClaimGrandPrize,e,Kh)}sendTradeOffer(e){return this.send(je.SendTradeOffer,e,Qh)}cancelTradeOffer(e){return this.send(je.CancelTradeOffer,e,Hh)}acceptTradeOffer(e){return this.send(je.AcceptTradeOffer,e,$h)}declineTradeOffer(e){return this.send(je.DeclineTradeOffer,e,Jh)}getMyTradeOffers(e){return this.send(je.GetMyTradeOffers,e,$a)}getIncomingTradeOffers(e){return this.send(je.GetIncomingTradeOffers,e,$a)}};var wr=class extends L{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(ht.GetDefinitions,e,un)}getActiveEvent(e){return this.send(ht.GetActiveEvent,e,Ec)}getUserState(e){return this.send(ht.GetUserState,e,ln)}getGroupState(e){return this.send(ht.GetGroupState,e,Jo)}joinOrCreateGroup(e){return this.send(ht.JoinOrCreateGroup,e,Jo)}spin(e){return this.send(ht.Spin,e,qc)}claimObjectReward(e){return this.send(ht.ClaimObjectReward,e,Zo)}claimGrandPrize(e){return this.send(ht.ClaimGrandPrize,e,Zo)}leaveGroup(e){return this.send(ht.LeaveGroup,e,Lc)}};var zr=class extends L{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(Rt.GetDefinition,e,Hc)}getUserState(e){return this.send(Rt.GetUserState,e,$c)}getActiveDeals(e){return this.send(Rt.GetActiveDeals,e,dn)}dismissDeal(e){return this.send(Rt.DismissDeal,e,Zc)}executeNode(e){return this.send(Rt.ExecuteNode,e,Jc)}recordShow(e){return this.send(Rt.RecordShow,e,Yc)}claimMilestone(e){return this.send(Rt.ClaimMilestone,e,Xc)}claimMilestonesBatch(e){return this.send(Rt.ClaimMilestonesBatch,e,ep)}};var zP=zod.z.object({}).passthrough().transform(r=>r),MP=zod.z.object({FeatureKey:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Rate:zod.z.number().nullish(),Basis:zod.z.string().nullish(),SourceCurrencyID:zod.z.string().nullish(),TargetCurrencyID:zod.z.string().nullish(),MinSourceAmount:zod.z.number().nullish(),MaxRewardPerOperation:zod.z.number().nullish(),Limits:Ce.nullish()}).passthrough(),Ja=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:zod.z.record(zod.z.string(),Be).nullish(),SpendRewards:zod.z.array(MP).nullish(),Qualification:zod.z.object({}).passthrough().transform(r=>r).nullish()}).passthrough(),Za=zod.z.object({Pending:zod.z.boolean().nullish(),Qualified:zod.z.boolean().nullish(),Groups:zod.z.array(zod.z.object({GroupID:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Conditions:zod.z.array(zod.z.object({Type:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Current:zod.z.number().nullish(),Required:zod.z.number().nullish()}).passthrough()).nullish()}).passthrough()).nullish()}).passthrough(),Yh=zod.z.object({ReferralDefinitions:Ja.nullish()}).passthrough(),Xh=zod.z.object({Referral:zP.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:Za.nullish()}).passthrough(),em=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:Za.nullish()}).passthrough(),tm=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),QualificationPending:zod.z.boolean().nullish(),Qualification:Za.nullish()}).passthrough(),Ya=zod.z.object({RewardID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),im=gt(Ya),jt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var Mr=class extends L{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(jt.GetDefinitions,e,Yh)}getUserState(e){return this.send(jt.GetUserState,e,Xh)}activateReferralCode(e){return this.send(jt.ActivateReferralCode,e,tm)}claimInviteReward(e){return this.send(jt.ClaimInviteReward,e,Ya)}claimInviteRewardsBatch(e){return this.send(jt.ClaimInviteRewardsBatch,e,im)}checkQualification(e){return this.send(jt.CheckQualification,e,em)}};var Or=class extends L{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(tt.GetDefinitions,e,rp)}getMessages(e){return this.send(tt.GetMessages,e,op)}getUnreadCount(e){return this.send(tt.GetUnreadCount,e,fn)}readMessages(e){return this.send(tt.ReadMessages,e,ea)}claimReward(e){return this.send(tt.ClaimReward,e,gn)}claimRewardsBatch(e){return this.send(tt.ClaimRewardsBatch,e,gn)}claimAll(e){return this.send(tt.ClaimAll,e,gn)}deleteMessages(e){return this.send(tt.DeleteMessages,e,ea)}sendGift(e){return this.send(tt.SendGift,e,ap)}sendTransfer(e){return this.send(tt.SendTransfer,e,lp)}getGiftStatus(e){return this.send(tt.GetGiftStatus,e,up)}};var Er=class extends L{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Rn.RequestAdPermit,e,cp)}completeView(e){return this.send(Rn.CompleteView,e,pp)}};var Ur=class extends L{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Se.GetFriendsList,e,Ei)}getIncomingRequests(e){return this.send(Se.GetIncomingRequests,e,Ei)}getOutgoingRequests(e){return this.send(Se.GetOutgoingRequests,e,Ei)}getRecommendedFriends(e){return this.send(Se.GetRecommendedFriends,e,Ei)}sendFriendRequest(e){return this.send(Se.SendFriendRequest,e,Ui)}acceptFriendRequest(e){return this.send(Se.AcceptFriendRequest,e,Ui)}declineFriendRequest(e){return this.send(Se.DeclineFriendRequest,e,Ui)}removeFriend(e){return this.send(Se.RemoveFriend,e,Ui)}getInbox(e){return this.send(Se.GetInbox,e,hp)}markInboxSeen(e){return this.send(Se.MarkInboxSeen,e,qi)}getInboxUnread(e){return this.send(Se.GetInboxUnread,e,qi)}follow(e){return this.send(Se.Follow,e,Ft)}unfollow(e){return this.send(Se.Unfollow,e,Ft)}getFollowers(e){return this.send(Se.GetFollowers,e,xn)}getFollowing(e){return this.send(Se.GetFollowing,e,xn)}block(e){return this.send(Se.Block,e,Ft)}unblock(e){return this.send(Se.Unblock,e,Ft)}getBlocked(e){return this.send(Se.GetBlocked,e,xn)}react(e){return this.send(Se.React,e,Ft)}unreact(e){return this.send(Se.Unreact,e,Ft)}getMyReactions(e){return this.send(Se.GetMyReactions,e,fp)}getEntityStates(e){return this.send(Se.GetEntityStates,e,mp)}addComment(e){return this.send(Se.AddComment,e,bn)}editComment(e){return this.send(Se.EditComment,e,bn)}deleteComment(e){return this.send(Se.DeleteComment,e,yp)}getComments(e){return this.send(Se.GetComments,e,gp)}report(e){return this.send(Se.Report,e,Rp)}};var OP={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var ti=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),EP=zod.z.object({BoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ce.nullish(),Effect:ti.nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),qr=zod.z.object({Schedule:ye.nullish(),Gate:Z.nullish()}).passthrough(),Xa=zod.z.object({Availability:K.nullish(),Effects:K.nullish()}).passthrough(),UP=zod.z.object({ScheduledBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Effects:zod.z.array(ti).nullish(),Availability:qr.nullish(),Presets:Xa.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),qP=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(ti).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),LP=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Phases:zod.z.array(qP).nullish(),Availability:qr.nullish(),Presets:Xa.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),BP=zod.z.object({TriggeredBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Sources:zod.z.array(nt).nullish(),Effects:zod.z.array(ti).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:qr.nullish(),Presets:Xa.nullish()}).passthrough(),GP=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),FP=zod.z.object({Effects:zod.z.array(ti).nullish()}).passthrough(),_P=zod.z.object({Availability:zod.z.record(zod.z.string(),qr).nullish(),Effects:zod.z.record(zod.z.string(),FP).nullish()}).passthrough(),VP=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),GP).nullish()}).passthrough(),Lr=zod.z.object({Definitions:zod.z.record(zod.z.string(),EP).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),UP).nullish(),BoostChains:zod.z.record(zod.z.string(),LP).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),BP).nullish(),Settings:VP.nullish(),Presets:_P.nullish()}).passthrough(),sm=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:ti.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:c.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:c.nullish()}).passthrough();var nm=zod.z.object({ServerTimeUtc:c.nullish(),Active:zod.z.record(zod.z.string(),sm).nullish()}),rm=zod.z.object({ServerTimeUtc:c.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:sm.nullish(),Resources:M.nullish()}),NP={Scheduled:"Scheduled",Chain:"Chain"},jP=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),Effects:zod.z.array(ti).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),om=zod.z.object({ServerTimeUtc:c.nullish(),Windows:zod.z.array(jP).nullish()}),ii={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Br=class extends L{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(ii.GetDefinitions,e,Lr)}getActive(e){return this.send(ii.GetActive,e,nm)}getActiveWindows(e){return this.send(ii.GetActiveWindows,e,om)}activate(e){return this.send(ii.Activate,e,rm)}cleanupExpired(e){return this.send(ii.CleanupExpired,e,qe)}};var Gr=class extends L{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(mt.GetUserCustomDataDefinitions,e,vn)}getMyUserCustomData(e){return this.send(mt.GetMyUserCustomData,e,bp)}getPublicUserCustomDataOf(e){return this.send(mt.GetPublicUserCustomDataOf,e,la)}setPrivateData(e){return this.send(mt.SetPrivateData,e,ua)}setPublicData(e){return this.send(mt.SetPublicData,e,ua)}deleteKey(e){return this.send(mt.DeleteKey,e,qe)}batchSet(e){return this.send(mt.BatchSet,e,Dp)}batchDelete(e){return this.send(mt.BatchDelete,e,Pp)}batchGetPublicUserCustomDataOf(e){return this.send(mt.BatchGetPublicUserCustomDataOf,e,Ip)}};var WP={Static:"Static",Runtime:"Runtime"},KP={Public:"Public",Private:"Private"},QP=zod.z.enum(["Client","Server","System"]).catch("Client"),HP=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),$P=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:c.nullish(),Version:zod.z.number().nullish(),LastWriter:QP.nullish(),ExpiresAt:c.nullish()}).passthrough(),am=zod.z.record(zod.z.string(),$P),el=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:am.nullish(),Runtime:am.nullish(),NotModified:zod.z.boolean().nullish()}),JP=zod.z.object({KeyID:zod.z.string(),Scope:zod.z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:zod.z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:HP.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Fr=zod.z.object({Keys:zod.z.record(zod.z.string(),JP).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),Vi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var _r=class extends L{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Vi.GetTitleCustomDataDefinitions,e,Fr)}getPublicTitleData(e){return this.send(Vi.GetPublicTitleData,e,el)}getPublicTitleDataKeys(e){return this.send(Vi.GetPublicTitleDataKeys,e,el)}};var ZP={Fast:"Fast",Sequential:"Sequential"},YP={Instant:"Instant",Timed:"Timed"};var XP={Hit:"Hit",Blocked:"Blocked"},eI=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),tI=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:H.nullish()}).passthrough();var iI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:H.nullish()}).passthrough(),sI=zod.z.object({Reward:H.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough();zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(iI).nullish(),Rate:sI.nullish()}).passthrough();zod.z.object({PlayedCount:zod.z.number().nullish(),RewardsClaimedCount:zod.z.number().nullish(),InstantClaimsCount:zod.z.number().nullish(),EarlyClaimsCount:zod.z.number().nullish(),LateClaimsCount:zod.z.number().nullish(),AdViewsTotal:zod.z.number().nullish(),StatRewardClaimsCount:zod.z.number().nullish(),StatReportsClampedCount:zod.z.number().nullish(),StatReportsUnknownMetricCount:zod.z.number().nullish()}).passthrough();var lm=zod.z.object({}).passthrough().transform(r=>r),um=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),We=zod.z.object({Operation:M.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),nI=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),rI=zod.z.object({ShieldChance:zod.z.number().nullish(),DamagedBuildingChance:zod.z.number().nullish(),RankMultiplierMin:zod.z.number().nullish(),RankMultiplierMax:zod.z.number().nullish(),RankOffsetMin:zod.z.number().nullish(),RankOffsetMax:zod.z.number().nullish(),StageLevelSpread:zod.z.number().nullish()}).passthrough(),oI=zod.z.object({CostMatrixTemplatesByID:zod.z.record(zod.z.string(),zod.z.array(zod.z.array(zod.z.number()))).nullish(),PerBoardGrowth:zod.z.number().nullish(),VisualTemplateCycle:zod.z.array(zod.z.string()).nullish(),EconomyScaledResources:pe.nullish(),ScaleRaidStealWithEconomy:zod.z.boolean().nullish(),ScaleAttackRewardWithEconomy:zod.z.boolean().nullish(),AttackValueFromCostMatrix:zod.z.boolean().nullish(),AttackBlockedRewardFactor:zod.z.number().nullish(),ScaleVictimLossWithEconomy:zod.z.boolean().nullish(),ScaleVictimLossWithTier:zod.z.boolean().nullish(),SynthesizedBuildingSlots:zod.z.number().nullish(),SynthesizedBuildingMaxLevel:zod.z.number().nullish(),DifficultyGrowthPerBoard:zod.z.number().nullish()}).passthrough(),aI=zod.z.object({CostMatrix:zod.z.array(zod.z.array(zod.z.number())).nullish(),PerBoardGrowth:zod.z.number().nullish(),EconomyScale:zod.z.number().nullish(),ScaledResources:pe.nullish()}).passthrough(),cm=zod.z.object({SlotIndex:zod.z.number().nullish(),Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxLevel:zod.z.number().nullish(),MaxLevelReward:H.nullish()}).passthrough(),lI=zod.z.object({Index:zod.z.number().nullish(),Type:zod.z.string().nullish(),CustomTypeID:zod.z.string().nullish(),RandomActionAttackWeight:zod.z.number().nullish(),RandomActionRaidWeight:zod.z.number().nullish(),ChanceTableID:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),uI=zod.z.object({Tiles:zod.z.record(zod.z.string(),lI).nullish()}).passthrough(),cI=zod.z.object({Weight:zod.z.number().nullish(),Bonus:We.nullish(),Tag:zod.z.string().nullish()}).passthrough(),pI=zod.z.object({Weight:zod.z.number().nullish(),Tag:zod.z.string().nullish(),MinBonusCells:zod.z.number().nullish(),MaxBonusCells:zod.z.number().nullish(),BonusPool:zod.z.array(cI).nullish(),GuaranteedBonus:We.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),dI=zod.z.object({Variants:zod.z.array(pI).nullish()}).passthrough(),hI=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:We.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),mI=zod.z.object({Outcomes:zod.z.array(hI).nullish()}).passthrough(),pm=zod.z.object({PerAdMultiplierRange:um.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),fI=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:We.nullish()}).passthrough(),gI=zod.z.object({Tiers:zod.z.array(fI).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:We.nullish()}).passthrough(),yI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:We.nullish()}).passthrough(),RI=zod.z.object({Reward:We.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),CI=zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(yI).nullish(),Rate:RI.nullish()}).passthrough(),dm=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),CI).nullish()}).passthrough(),SI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:We.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ce.nullish(),Multipliers:pm.nullish(),Gradation:gI.nullish(),RunStats:dm.nullish()}).passthrough(),xI=zod.z.object({Choices:zod.z.array(SI).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),bI=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:We.nullish(),Tag:zod.z.string().nullish()}).passthrough(),DI=zod.z.object({OnPassStart:We.nullish(),OnTileLanding:zod.z.record(zod.z.string(),We).nullish(),OnAttack:zod.z.record(zod.z.string(),We).nullish(),OnRaid:zod.z.record(zod.z.string(),We).nullish(),OnBuild:We.nullish(),OnStageComplete:We.nullish(),OnAttackBonusDrops:zod.z.array(bI).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),mI).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),xI).nullish()}).passthrough(),hm=zod.z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(cm).nullish(),HeistGridBonusConfig:dI.nullish(),StageOperations:DI.nullish(),TileLandingMultiplier:um.nullish(),EconomyOverride:aI.nullish()}).passthrough(),PI=zod.z.object({Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BoardTemplateID:zod.z.string().nullish(),Buildings:zod.z.array(cm).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:hm.nullish()}).passthrough(),II=zod.z.object({AttackCooldownSeconds:zod.z.number().nullish(),RaidCooldownSeconds:zod.z.number().nullish(),MaxRecentTargets:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),LiveOpponentPoolSize:zod.z.number().nullish(),LiveOpponentPoolCacheSeconds:zod.z.number().nullish(),MaxLiveCandidateReads:zod.z.number().nullish(),VictimImmunitySeconds:zod.z.number().nullish()}).passthrough(),vI=zod.z.object({Enabled:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),MaxPerCatchUp:zod.z.number().nullish(),Chance:zod.z.number().nullish(),AttackWeight:zod.z.number().nullish(),RaidWeight:zod.z.number().nullish(),MinBoardStageLevel:zod.z.number().nullish(),RaidLossMultiplier:zod.z.number().nullish()}).passthrough(),Vr=zod.z.object({RollCurrencyID:zod.z.string().nullish(),ShieldCurrencyID:zod.z.string().nullish(),RaidMode:zod.z.string().nullish(),AllowedRollMultipliers:zod.z.array(zod.z.number()).nullish(),BoardTemplatesByID:zod.z.record(zod.z.string(),uI).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),hm).nullish(),StagesByLevel:zod.z.record(zod.z.string(),PI).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:oI.nullish(),Dice:nI.nullish(),Bots:rI.nullish(),Targeting:II.nullish(),BotRaids:vI.nullish()}).passthrough(),TI=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:c.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),Be).nullish(),GrandPrize:H.nullish()}).passthrough(),Nr=zod.z.object({Board:Vr.nullish(),CommunityChest:TI.nullish()}).passthrough(),mm=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),pe).nullish()}).passthrough(),AI=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:Ee.nullish(),TargetBuildingStates:zod.z.array(eI).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:mm.nullish()}).passthrough(),kI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:We.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ce.nullish(),Multipliers:pm.nullish(),RunStats:dm.nullish()}).passthrough(),wI=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(kI).nullish()}).passthrough(),zI=zod.z.object({GroupID:zod.z.string().nullish(),Delta:j.nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),fm=zod.z.object({UsedMultiplier:zod.z.number().nullish(),Steps:zod.z.number().nullish(),DiceValues:zod.z.array(zod.z.number()).nullish(),OldPosition:zod.z.number().nullish(),NewPosition:zod.z.number(),CyclesCompletedDelta:j.nullish(),LandedTileType:zod.z.string().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:AI.nullish(),SpecialModeOffer:wI.nullish(),CommunityChestContribution:zI.nullish()}).passthrough(),gm=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:Dt.nullish()}).passthrough(),tl=zod.z.object({Status:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),FoundSymbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),FoundBonus:H.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(tI).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:Dt.nullish(),RaidRewardPreview:mm.nullish()}).passthrough(),ym=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish()}).passthrough(),Rm=zod.z.object({Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish()}).passthrough(),Cm=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),MI=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),Sm=zod.z.object({FinalMultiplier:zod.z.number().nullish(),AdViewsUsed:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),IsEarlyClaim:zod.z.boolean().nullish(),ReachedTierIndex:zod.z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(MI).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),OI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},xm=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),EI={Active:"Active",Left:"Left",Replaced:"Replaced"},UI=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),qI=zod.z.object({CurrentProgress:j.nullish(),MaxProgress:j.nullish()}).passthrough(),LI=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ee.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:j.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),kl).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:UI.nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),bm=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(LI).nullish(),SharedProgress:qI.nullish(),Status:xm.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:zod.z.number().nullish()}).passthrough(),BI=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:xm.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:c.nullish()}).passthrough(),GI=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(BI).nullish()}).passthrough(),Dm=zod.z.object({ServerTimeUtc:c.nullish(),UserState:GI.nullish(),ActiveGroup:bm.nullish(),SecondsRemaining:j.nullish()}),Pm=zod.z.object({ServerTimeUtc:c.nullish(),Group:bm.nullish(),SecondsRemaining:j.nullish()}),il=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Im=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Le={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 FI={Mesh:"Mesh",Host:"Host"},sl=zod.z.enum(["Mesh","Host"]).catch("Mesh"),_I={ServerRelay:"ServerRelay",P2P:"P2P"},nl=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),VI={Public:"Public",Private:"Private"},NI=zod.z.enum(["Public","Private"]).catch("Public"),jI={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},WI=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),vm=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),KI=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Tm=zod.z.object({SystemState:KI.nullish(),DefaultTopology:sl.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:nl.nullish(),AllowCreatorChatOverride:zod.z.boolean().nullish(),MaxPlayersPerRoom:zod.z.number().nullish(),RoomTtlSeconds:zod.z.number().nullish(),MaxRoomLifetimeSeconds:zod.z.number().nullish(),HeartbeatIntervalMs:zod.z.number().nullish(),MemberTimeoutMs:zod.z.number().nullish(),MaxSignalPayloadBytes:zod.z.number().nullish(),MaxChatTextLength:zod.z.number().nullish(),RoomLogCap:zod.z.number().nullish(),VoiceEnabled:zod.z.boolean().nullish(),RecordVoices:zod.z.boolean().nullish(),IceServers:zod.z.array(vm).nullish()}).passthrough(),QI=zod.z.object({UserID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),Ready:zod.z.boolean().nullish(),State:zod.z.record(zod.z.string(),zod.z.string()).nullish(),JoinedAt:zod.z.number().nullish(),IsHost:zod.z.boolean().nullish(),LastSeenMs:zod.z.number().nullish()}).passthrough(),HI=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:sl.nullish(),ChatMode:nl.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),$I=zod.z.object({Seq:zod.z.number().nullish(),Type:WI.nullish(),FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Payload:zod.z.string().nullish(),Ts:zod.z.number().nullish()}).passthrough(),Ni=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:sl.nullish(),ChatMode:nl.nullish(),Visibility:NI.nullish(),Status:zod.z.string().nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),Members:zod.z.array(QI).nullish(),IceServers:zod.z.array(vm).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Am=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),km=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),rl=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),wm=zod.z.object({Rooms:zod.z.array(HI).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),zm=zod.z.object({Envelopes:zod.z.array($I).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),jr=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),$e={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 ol=zod.z.object({TitleCustomData:Fr.nullish(),Character:en.nullish(),Item:ir.nullish(),Currency:On.nullish(),Store:bs.nullish(),Lootbox:Na.nullish(),Quest:Zi.nullish(),TimedEvent:Gs.nullish(),Leaderboard:Qs.nullish(),Season:Js.nullish(),Reward:Wa.nullish(),Collection:Ar.nullish(),Craft:Qa.nullish(),DealOffer:Yo.nullish(),Premium:Fa.nullish(),TimedBoost:Lr.nullish(),CoopEvent:un.nullish(),GameLoop:Nr.nullish(),Match:Sa.nullish(),Experiment:Wd.nullish(),Blockchain:ha.nullish(),Marketplace:Ia.nullish(),Multiplayer:Tm.nullish(),UserCustomData:vn.nullish(),Referral:Ja.nullish(),Localization:th.nullish(),Analytics:Ed.nullish(),Social:Cp.nullish(),PlatformBridge:Sp.nullish()}).passthrough();var si={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Wr=class extends L{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(si.GetTitlePublicConfiguration,e,ol)}getTitlePublicConfigurationExcept(e){return this.send(si.GetTitlePublicConfigurationExcept,e,ol)}getCurrencyDefinitions(e){return this.send(si.GetCurrencyDefinitions,e,On)}getItemDefinitions(e){return this.send(si.GetItemDefinitions,e,ir)}getServerTime(e){return this.send(si.GetServerTime,e,qe)}};var Kr=class extends L{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Le.GetGameLoops,e,Nr)}getBoardDefinition(e,t=false){return this.send(Le.GetBoardDefinition,e,Vr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Le.GetBoardDefinitionForLevel,e,Vr,{silent:t})}getUserBoardState(e){return this.send(Le.GetUserBoardState,e,lm)}boardLoopRoll(e){return this.send(Le.BoardLoopRoll,e,fm)}boardLoopAttack(e){return this.send(Le.BoardLoopAttack,e,gm)}boardLoopRaid(e){return this.send(Le.BoardLoopRaid,e,tl)}boardLoopRaidFast(e){return this.send(Le.BoardLoopRaidFast,e,tl)}boardLoopBuild(e){return this.send(Le.BoardLoopBuild,e,ym)}boardSpecialChoose(e){return this.send(Le.BoardSpecialChoose,e,Rm)}boardSpecialApplyMultiplier(e){return this.send(Le.BoardSpecialApplyMultiplier,e,Cm)}boardSpecialClaim(e){return this.send(Le.BoardSpecialClaim,e,Sm)}getCommunityChestState(e){return this.send(Le.GetCommunityChestState,e,Dm)}joinOrCreateCommunityChest(e){return this.send(Le.JoinOrCreateCommunityChest,e,Pm)}claimCommunityChestMilestone(e){return this.send(Le.ClaimCommunityChestMilestone,e,il)}claimCommunityChestGrandPrize(e){return this.send(Le.ClaimCommunityChestGrandPrize,e,il)}leaveCommunityChest(e){return this.send(Le.LeaveCommunityChest,e,Im)}};var ZI={Live:"Live",Latest:"Latest",Specific:"Specific"},YI={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},XI=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),ev={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"},tv=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),iv=zod.z.object({Level:XI,Message:zod.z.string().nullish(),Data:Bt.nullish()}),sv=zod.z.object({Error:tv,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Mm=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:Bt.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(iv).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:sv.nullish()}),al={Execute:"Execute"};var Qr=class extends L{constructor(e){super(e,"CloudCode");}execute(e){return this.send(al.Execute,e,Mm)}};var Hr=class extends L{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(He.GetDefinitions,e,Vp)}getUserState(e){return this.send(He.GetUserState,e,Np)}depositToken(e){return this.send(He.DepositToken,e,jp)}depositNFT(e){return this.send(He.DepositNFT,e,Wp)}requestTokenWithdrawal(e){return this.send(He.RequestTokenWithdrawal,e,Kp)}requestNFTWithdrawal(e){return this.send(He.RequestNFTWithdrawal,e,Qp)}getTransactionHistory(e){return this.send(He.GetTransactionHistory,e,Hp)}retryWithdrawal(e){return this.send(He.RetryWithdrawal,e,$p)}confirmWithdrawal(e){return this.send(He.ConfirmWithdrawal,e,Jp)}donateToDeveloper(e){return this.send(He.DonateToDeveloper,e,ya)}donateToUsersPool(e){return this.send(He.DonateToUsersPool,e,ya)}getPlayAccess(e){return this.send(He.GetPlayAccess,e,Fp)}confirmPlayAccess(e){return this.send(He.ConfirmPlayAccess,e,_t)}};var $r=class extends L{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(ze.GetDefinitions,e,cd)}getGroupedOffers(e){return this.send(ze.GetGroupedOffers,e,pd)}getOffersByItem(e){return this.send(ze.GetOffersByItem,e,va)}getOffer(e){return this.send(ze.GetOffer,e,dd)}getBuyOrders(e){return this.send(ze.GetBuyOrders,e,va)}getMyState(e){return this.send(ze.GetMyState,e,Fn)}getHistory(e){return this.send(ze.GetHistory,e,md)}createListing(e){return this.send(ze.CreateListing,e,Gi)}cancelListing(e){return this.send(ze.CancelListing,e,lt)}buy(e){return this.send(ze.Buy,e,lt)}marketBuy(e){return this.send(ze.MarketBuy,e,lt)}marketSell(e){return this.send(ze.MarketSell,e,lt)}createAuction(e){return this.send(ze.CreateAuction,e,Gi)}placeBid(e){return this.send(ze.PlaceBid,e,hd)}claimAuction(e){return this.send(ze.ClaimAuction,e,lt)}createBuyOrder(e){return this.send(ze.CreateBuyOrder,e,Gi)}cancelBuyOrder(e){return this.send(ze.CancelBuyOrder,e,lt)}fillBuyOrder(e){return this.send(ze.FillBuyOrder,e,lt)}createDirectTrade(e){return this.send(ze.CreateDirectTrade,e,Gi)}respondDirectTrade(e){return this.send(ze.RespondDirectTrade,e,lt)}cancelDirectTrade(e){return this.send(ze.CancelDirectTrade,e,lt)}claimBack(e){return this.send(ze.ClaimBack,e,lt)}};var Jr=class extends L{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send($e.CreateRoom,e,Ni)}joinRoom(e){return this.send($e.JoinRoom,e,Ni)}leaveRoom(e,t=false){return this.send($e.LeaveRoom,e,rl,{keepalive:t})}listRooms(e){return this.send($e.ListRooms,e,wm)}getRoom(e){return this.send($e.GetRoom,e,Ni)}closeRoom(e){return this.send($e.CloseRoom,e,rl)}poll(e){return this.send($e.Poll,e,zm)}sendSignal(e){return this.send($e.SendSignal,e,jr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send($e.ClaimHost,e,Ni)}kickMember(e){return this.send($e.KickMember,e,Am)}unbanMember(e){return this.send($e.UnbanMember,e,km)}sendChat(e){return this.send($e.SendChat,e,jr)}setMemberState(e){return this.send($e.SetMemberState,e,jr)}};var nv={Free:"Free",Price:"Price",Holding:"Holding"},ll=zod.z.enum(["Free","Price","Holding"]).catch("Free"),rv={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},ov=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),av={All:"All",Any:"Any"},lv=zod.z.enum(["All","Any"]).catch("All"),uv={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},cv=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),pv={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},dv=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),hv={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Em=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),mv={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},fv={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},gv=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),yv=zod.z.object({Type:pi.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),MinLevel:zod.z.number().nullish()}).passthrough(),Rv=zod.z.object({Requirements:zod.z.array(yv).nullish(),Match:lv.nullish(),Mode:ov.nullish()}).passthrough(),Cv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:ll.nullish(),Price:pe.nullish(),Holding:Rv.nullish()}).passthrough(),Sv=zod.z.object({AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxBytes:zod.z.number().nullish(),MaxCount:zod.z.number().nullish(),Required:zod.z.boolean().nullish()}).passthrough(),xv=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),Sv).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(ll).nullish(),PricePolicy:Gn.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ce.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),bv=zod.z.object({Allowed:zod.z.array(Bi).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),Dv=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),Pv=zod.z.object({MaxTitleLength:zod.z.number().nullish(),MaxDescriptionLength:zod.z.number().nullish(),MaxTags:zod.z.number().nullish(),MaxTagLength:zod.z.number().nullish(),MaxMetadataKeys:zod.z.number().nullish(),MaxMetadataValueLength:zod.z.number().nullish(),MaxAccessOptions:zod.z.number().nullish(),ThumbnailMaxBytes:zod.z.number().nullish()}).passthrough(),Iv=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Schedule:ye.nullish(),Gate:Z.nullish(),Order:zod.z.number().nullish()}).passthrough(),vv=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:ye.nullish(),ContentTypes:zod.z.record(zod.z.string(),xv).nullish(),PricePolicy:Gn.nullish(),Commission:Pa.nullish(),HoldingPolicy:bv.nullish(),Moderation:Dv.nullish(),Limits:Pv.nullish(),Featured:zod.z.array(Iv).nullish()}).passthrough(),Tv=zod.z.object({Acquisitions:zod.z.number().nullish(),Downloads:zod.z.number().nullish(),Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),ReportCount:zod.z.number().nullish(),Remixes:zod.z.number().nullish()}).passthrough(),ni=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:Ee.nullish(),Title:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Metadata:zod.z.record(zod.z.string(),zod.z.string()).nullish(),ThumbnailUrl:zod.z.string().nullish(),Visibility:cv.nullish(),Access:zod.z.array(Cv).nullish(),Status:dv.nullish(),ModerationNote:zod.z.string().nullish(),Stats:Tv.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),PublishedAt:c.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),Av=zod.z.object({OptionID:zod.z.string().nullish(),Mode:ll.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),Um=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Order:zod.z.number().nullish()}).passthrough(),qm=zod.z.object({Definitions:vv.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish(),CanPublish:zod.z.record(zod.z.string(),zod.z.boolean()).nullish(),Collections:zod.z.array(Um).nullish()}).passthrough(),Zr=zod.z.object({Items:zod.z.array(ni).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Lm=zod.z.object({Content:ni.nullish(),AccessState:zod.z.array(Av).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),Bm=zod.z.object({Collection:Um.nullish(),Items:zod.z.array(ni).nullish()}).passthrough(),Gm=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:Ee.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(ni).nullish()}).passthrough(),Om=zod.z.object({Role:zod.z.string().nullish(),Index:zod.z.number().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish(),ServerCopy:zod.z.boolean().nullish()}).passthrough(),Fm=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(Om).nullish(),ThumbnailUpload:Om.nullish(),ExpiresAt:c.nullish()}).passthrough(),_m=zod.z.object({Content:ni.nullish(),Resources:M.nullish()}).passthrough(),ul=zod.z.object({Content:ni.nullish()}).passthrough(),Vm=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Em.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:Dt.nullish(),Resources:M.nullish(),CommissionTaken:pe.nullish()}).passthrough(),kv=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),Nm=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:gv.nullish(),Files:zod.z.array(kv).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:c.nullish()}).passthrough(),wv=zod.z.object({ContentID:zod.z.string().nullish(),Source:Em.nullish(),OptionID:zod.z.string().nullish(),PricePaid:pe.nullish(),AcquiredAt:c.nullish(),Content:ni.nullish()}).passthrough(),jm=zod.z.object({Licenses:zod.z.array(wv).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Ke={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 Yr=class extends L{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(Ke.GetDefinitions,e,qm)}browse(e){return this.send(Ke.Browse,e,Zr)}getContent(e){return this.send(Ke.GetContent,e,Lm)}getCollection(e){return this.send(Ke.GetCollection,e,Bm)}getCreatorProfile(e){return this.send(Ke.GetCreatorProfile,e,Gm)}beginUpload(e){return this.send(Ke.BeginUpload,e,Fm)}publish(e){return this.send(Ke.Publish,e,_m)}updateContent(e){return this.send(Ke.UpdateContent,e,ul)}unpublish(e){return this.send(Ke.Unpublish,e,ul)}getMyContent(e){return this.send(Ke.GetMyContent,e,Zr)}acquire(e){return this.send(Ke.Acquire,e,Vm)}getDownload(e){return this.send(Ke.GetDownload,e,Nm)}getMyLicenses(e){return this.send(Ke.GetMyLicenses,e,jm)}getMyFavorites(e){return this.send(Ke.GetMyFavorites,e,Zr)}};var Xr=class extends L{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,Sd,"defs")}get(e){return this.sendKeyed("Get",e,Aa,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,bd,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,ka,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Dd,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,wa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,wa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Pd,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,vd,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Id,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,Td,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,xd,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Ad,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,Aa,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,ka,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var eo=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;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.settings=ml(e),this.emitter=new Ti,this.platform=e.platform??new li,this.clientPlatform=e.clientPlatform??Tl(),this.acquisition=new Kt(this.platform),this.acquisition.capture(),this.playtime=new Ai(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new ns({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e.fetch,debugLogging:this.settings.debugLogging,throttleMs:e.throttleMs,maxRequestsPerSecond:e.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new ls(this.emitter),this.cache=new cs(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new ps(this.platform.storage,this.settings.titleID),this.api={authentication:new Zn(this),user:new Xn(this),currency:new er(this),item:new sr(this),store:new nr(this),purchase:new lr(this),lootbox:new pr(this),reward:new dr(this),quest:new Rr(this),tutorial:new hr(this),communityMarketing:new mr(this),chat:new fr(this),push:new gr(this),localization:new yr(this),timedEvent:new Cr(this),leaderboard:new Sr(this),season:new xr(this),premium:new br(this),character:new Dr(this),match:new Pr(this),craft:new vr(this),ai:new Tr(this),collection:new kr(this),coopEvent:new wr(this),dealOffer:new zr(this),referral:new Mr(this),mailbox:new Or(this),advertising:new Er(this),social:new Ur(this),timedBoost:new Br(this),userCustomData:new Gr(this),titleCustomData:new _r(this),title:new Wr(this),gameLoop:new Kr(this),cloudCode:new Qr(this),blockchain:new Hr(this),marketplace:new $r(this),multiplayer:new Jr(this),workshop:new Yr(this),dataCollections:new Xr(this),analytics:new $n(this),experiment:new Jn(this)},this.userService=new ys(this),this.cache.attachState(this.userService),this.auth=new hs(this),this.currency=new Cs(this),this.item=new Ss(this),this.store=new Ps(this),this.purchase=new Is(this),this.checkout=new vs(this),this.lootbox=new Ts(this),this.reward=new As(this),this.quest=new Bs(this),this.tutorial=new ws(this),this.communityMarketing=new zs(this),this.chat=new Es(this),this.push=new Us(this),this.localization=new Ls(this),this.timedEvent=new _s(this),this.leaderboard=new Hs(this),this.season=new Zs(this),this.premium=new Ys(this),this.character=new tn(this),this.match=new sn(this),this.craft=new nn(this),this.ai=new on(this),this.collection=new an(this),this.coopEvent=new cn(this),this.dealOffer=new hn(this),this.referral=new mn(this),this.mailbox=new yn(this),this.ads=new Sn(this),this.social=new Dn(this),this.timedBoost=new Pn(this),this.userCustomData=new Tn(this),this.titleCustomData=new An(this),this.title=new kn(this),this.gameLoop=new wn(this),this.cloudCode=new zn(this),this.blockchain=new Un(this),this.marketplace=new _n(this),this.multiplayer=new Vn(this),this.workshop=new Nn(this),this.dataCollections=new Wn(this),this.analytics=new Qn(this),this.experiments=new Hn(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.platform.getFullURL(),RelatedEntityID:G()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var to=class{ctx;constructor(e){this.ctx=new eo(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Nt(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(n,{...s,...i},zod.z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get platform(){return this.ctx.platform}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function Mv(r){return new to(r)}var Wm="idos_sso",Km="state",cl="idos:sso:state",Ov="https://idosgames.com/sso/",Ev=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],Uv=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function qv(){if(typeof window>"u")return false;let{origin:r}=window.location;return Ev.includes(r)||Uv.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function Lv(){if(typeof window>"u")return null;let r=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!r)return null;let e=new URLSearchParams(r),t=e.get(Wm);if(!t)return null;let i=e.get(Km)??"",s=Vv();return jv(e),Nv(),s&&i!==s?null:{code:t,state:i}}function Bv(r){if(typeof window>"u")return;let e=r.returnTo??Gv(),t=Fv();_v(t);let i=new URL(r.ssoUrl??Ov);i.searchParams.set("title",r.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function Gv(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function Fv(){let r=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(r);else for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*256);return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function _v(r){try{window.sessionStorage.setItem(cl,r);}catch{}}function Vv(){try{return window.sessionStorage.getItem(cl)}catch{return null}}function Nv(){try{window.sessionStorage.removeItem(cl);}catch{}}function jv(r){r.delete(Wm),r.delete(Km);let e=r.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var Wv={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 Kv(r,e="Something went wrong. Please try again."){return r?Wv[r]??r:e}function Qv(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function Hv(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function $v(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function Hm(r,e,t,i=1){if(!r)return e;let s=r.Base??e,n=Math.max(0,t-i),o;switch(r.Shape??"Flat"){case "PerStep":o=s+(r.PerStep??0)*n;break;case "PerStepRate":o=s*(1+(r.PerStepRate??0)*n);break;case "Geometric":o=s*Math.pow(1+(r.GrowthRate??0),n);break;case "Table":o=s*Qm(r,t,1);break;case "TableAbsolute":o=Qm(r,t,s);break;default:o=s;break}return Number.isNaN(o)?s:(r.MinResult!=null&&o<r.MinResult&&(o=r.MinResult),r.MaxResult!=null&&o>r.MaxResult&&(o=r.MaxResult),o)}function Jv(r,e,t=1){return Hm(r,1,e,t)}function Zv(r){if(!r)return false;switch(r.Shape??"Flat"){case "PerStep":return (r.PerStep??0)!==0;case "PerStepRate":return (r.PerStepRate??0)!==0;case "Geometric":return (r.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return $m(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function Yv(r){if(Number.isNaN(r)||r<=0)return 0;if(!Number.isFinite(r))return Number.MAX_SAFE_INTEGER;let e=Math.round(r);return Math.abs(r-e)<=1e-9*Math.max(1,Math.abs(r))?e:Math.ceil(r)}function $m(r){if(!r)return [];let e=[];for(let t of r)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function Qm(r,e,t){let i=$m(r.Points);if(i.length===0)return t;let s=null,n=null,o=null;for(let p of i)(o===null||p.AtStep>o.AtStep)&&(o=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=r.TailGrowthRate??0;return p===0?o.Value:o.Value*Math.pow(1+p,e-o.AtStep)}switch(r.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+p*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let h=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+h*(n.Value-s.Value)}let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,p)}default:return s.Value}}var Xv={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},pl=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),eT={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},tT=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),iT=zod.z.object({PlacementID:zod.z.string().nullish(),Type:pl.nullish(),Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),CreditsRewarded:zod.z.number().nullish(),AllowedProviderIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),sT=zod.z.object({DefaultCreditsPerView:zod.z.number().nullish(),MaxCreditsBalance:zod.z.number().nullish(),DailyCreditEarnCap:zod.z.number().nullish(),DailyViewCap:zod.z.number().nullish(),MinSecondsBetweenViews:zod.z.number().nullish()}).passthrough(),nT=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),rT=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:tT.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),oT=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),aT=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),lT=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),DisableInterstitials:zod.z.boolean().nullish(),DisableBanners:zod.z.boolean().nullish(),DisableAppOpen:zod.z.boolean().nullish()}).passthrough(),uT=zod.z.object({RequirePersonalizedAdsConsent:zod.z.boolean().nullish(),RequireTrackingConsent:zod.z.boolean().nullish(),CurrentPolicyVersion:zod.z.string().nullish(),RegulatedRegions:zod.z.array(zod.z.string()).nullish()}).passthrough(),cT=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),pT=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:pl.nullish()}).passthrough(),dT={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},hT=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),mT=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:hT.nullish(),Enabled:zod.z.boolean().nullish(),Priority:zod.z.number().nullish(),AndroidAppID:zod.z.string().nullish(),IosAppID:zod.z.string().nullish(),WebAppID:zod.z.string().nullish(),Units:zod.z.record(zod.z.string(),pT).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),iT).nullish(),Providers:zod.z.record(zod.z.string(),mT).nullish(),RewardedVideo:sT.nullish(),Interstitial:nT.nullish(),Banner:rT.nullish(),AppOpen:oT.nullish(),FrequencyCapping:aT.nullish(),PremiumAdReductions:zod.z.array(lT).nullish(),Consent:uT.nullish(),Verification:cT.nullish()}).passthrough();var fT=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),gT=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:c.nullish(),LastCompletedAt:c.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),yT=zod.z.object({Date:c.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),RT=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:c.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),CT=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:c.nullish(),ConsentRevokedAt:c.nullish()}).passthrough(),ST=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:pl.nullish(),IssuedAt:c.nullish(),ExpiresAt:c.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),xT=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:c.nullish()}).passthrough();zod.z.object({Credits:fT.nullish(),Placements:zod.z.record(zod.z.string(),gT).nullish(),Daily:yT.nullish(),Session:RT.nullish(),LastImpressionAt:c.nullish(),LastInterstitialAt:c.nullish(),LastRewardedAt:c.nullish(),LastAppOpenAt:c.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:c.nullish(),Consent:CT.nullish(),PendingRequests:zod.z.record(zod.z.string(),ST).nullish(),FraudFlags:xT.nullish(),UpdatedAt:c.nullish()}).passthrough();var Jm="idos_device_id",io=class{storage;constructor(e=new oi){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(Jm);return e||(e="noop-device",this.storage.setString(Jm,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};
|
|
2
|
-
exports.AIAction=Fe;exports.AIErrorCode=
|
|
1
|
+
'use strict';var zod=require('zod'),Ht=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Ht__default=/*#__PURE__*/_interopDefault(Ht);var Ti=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 ef(){let r=new Map;return {get:e=>r.get(e)??null,set:(e,t)=>{r.set(e,t);},remove:e=>{r.delete(e);}}}function fl(){return tf()??ef()}function tf(){try{let r=globalThis.localStorage;if(!r)return null;let e="__idos_probe__";return r.setItem(e,"1"),r.removeItem(e),{get:t=>{try{return r.getItem(t)}catch{return null}},set:(t,i)=>{try{r.setItem(t,i);}catch{try{r.removeItem(t);}catch{}}},remove:t=>{try{r.removeItem(t);}catch{}}}}catch{return null}}var gl="https://api.idosgames.com";function yl(r){return {titleID:r.titleID,titleTemplateID:r.titleTemplateID??"default",buildKey:r.buildKey??"",baseUrl:(r.baseUrl??gl).replace(/\/+$/,""),devBuild:r.devBuild??false,debugLogging:r.debugLogging??false,configStorage:r.configStorage??fl(),locale:r.locale??sf(),appVersion:r.appVersion??""}}function sf(){try{return globalThis.navigator?.language??""}catch{return ""}}var ri=class{getString(e){if(typeof localStorage>"u")return null;try{return localStorage.getItem(e)}catch{return null}}setString(e,t){if(!(typeof localStorage>"u"))try{localStorage.setItem(e,t);}catch{}}remove(e){if(!(typeof localStorage>"u"))try{localStorage.removeItem(e);}catch{}}},oi=class{map=new Map;getString(e){return this.map.get(e)??null}setString(e,t){this.map.set(e,t);}remove(e){this.map.delete(e);}};function ai(){return globalThis.Telegram?.WebApp??null}function G(){return crypto.randomUUID()}var Rl="idos_device_id",li=class{storage;constructor(e=new ri){this.storage=e;}getPlatform(){return ai()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=ai()?.initDataUnsafe?.start_param;return typeof e=="string"?e:null}getReferrer(){if(typeof document>"u")return null;let e=document.referrer;return e&&e.length>0?e:null}getTelegramInitDataRaw(){let e=ai()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(Rl);return e||(e=G(),this.storage.setString(Rl,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let t=ai();if(t?.openTelegramLink){t.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let t=ai();if(t?.openInvoice){t.openInvoice(e);return}typeof window<"u"&&window.open(e,"_blank");}async showAd(e){let t=globalThis;typeof t.showAd=="function"&&await t.showAd(e);}async copyToClipboard(e){typeof navigator<"u"&&navigator.clipboard&&await navigator.clipboard.writeText(e);}};var no="idos_acq",Cl=["gclid","fbclid","ttclid","msclkid","yclid"],nf=["ref","r"],rf=["ref_","ref-","ref=","r_","r-"];var Kt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();of(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=uf(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(no);}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=bl(xl(t));if(i)return i}return Wi(t)}readFromEnvironment(){let e={},t=xl(this.platform.getFullURL());Wt(e,"UtmSource",t.get("utm_source")),Wt(e,"UtmMedium",t.get("utm_medium")),Wt(e,"UtmCampaign",t.get("utm_campaign")),Wt(e,"UtmTerm",t.get("utm_term")),Wt(e,"UtmContent",t.get("utm_content")),Wt(e,"ClaimToken",t.get("idos_click"));for(let R of Cl){let B=t.get(R);if(B){e.ClickID=B;break}}let i=this.platform.getStartParameter()??"",s=lf(i);if(s){for(let R of af)Wt(e,R,s.get(Dl[R])??null);for(let R of Cl){let B=s.get(R);if(B){e.ClickID=B;break}}}let n=Wi(s?s.get("ref")??s.get("r")??"":i),o=bl(t),p=n||o;p&&(e.ReferralCode=p,e.ChannelHint=n?"telegram":"query");let h=this.platform.getReferrer?.();return h&&(e.Referrer=h),e}read(){try{let e=this.platform.storage.getString(no);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(no,JSON.stringify(e));}catch{}}};function of(r){return !!(r.UtmSource||r.UtmMedium||r.UtmCampaign||r.ClickID||r.Referrer||r.ReferralCode||r.ClaimToken)}function Wt(r,e,t){t&&(r[e]=t);}var Sl="a1_",Dl={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},af=Object.keys(Dl);function lf(r){let e=(r||"").trim();if(!e.startsWith(Sl))return null;let t=e.slice(Sl.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),n=Uint8Array.from(s,h=>h.charCodeAt(0)),o=new TextDecoder().decode(n),p=new URLSearchParams(o);return [...p.keys()].length>0?p:null}catch{return null}}function xl(r){try{let e=r.indexOf("?");return new URLSearchParams(e>=0?r.slice(e):"")}catch{return new URLSearchParams}}function bl(r){for(let e of nf){let t=r.get(e);if(t)return Wi(t)}return null}function Wi(r){let e=(r||"").trim();if(!e)return null;for(let t of rf)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function uf(r){let e=r||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var Pl="idos_usage_pending",Il="idos_usage_session",vl="idos_usage_closed_session",Tl="idos_usage_new_session",Al="idos_usage_last_activity",Ai=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(Pl),this.currentSessionSeconds=this.readNumber(Il),this.pendingClosedSessionSeconds=this.readNumber(vl),this.isNewSessionPending=this.readNumber(Tl)!==0;let e=this.readNumber(Al);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(Pl,this.pendingSeconds),this.writeNumber(Il,this.currentSessionSeconds),this.writeNumber(vl,this.pendingClosedSessionSeconds),this.writeNumber(Tl,this.isNewSessionPending?1:0),this.writeNumber(Al,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 ct={Virtual:"Virtual",Crypto:"Crypto"},ci=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),Ki={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase",PlatformCredits:"PlatformCredits"},pi=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase","PlatformCredits"]).catch("Item"),ft={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Qi=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),cf={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Hi=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),pf={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},$i=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),df={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},ki=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),ke={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function wl(){let r=globalThis,e=r.Capacitor?.getPlatform?.();if(e)return kl(e);let t=r.cordova?.platformId;return t?kl(t):r.navigator?.userAgent??""?ft.Web:ft.Unknown}function kl(r){let e=r.toLowerCase();return e==="android"?ft.Android:e==="ios"?ft.Ios:e==="web"?ft.Web:ft.Unknown}function _(r){return {ok:true,data:r}}function u(r,e){return {ok:false,reason:r,error:e}}var a=u("unauthorized","Not logged in.");function hf(r){return r.ok}function mf(r){return !r.ok}var j=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="string"?Number(r):r;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(r)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((r,e)=>{let t=typeof r=="number"?String(r):r.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(r)}`}),zod.z.NEVER):t}),c=zod.z.string();var ro=zod.z.object({Type:pi.nullish(),CurrencyID:zod.z.string().nullish(),Amount:j.nullish(),AmountUsd:zod.z.number().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ProductID:zod.z.string().nullish()}),ff=zod.z.object({Type:$i.nullish(),EntityID:zod.z.string()}),gf=zod.z.object({Address:ff.nullish(),Amount:j.nullish(),Source:zod.z.string().nullish()}),pe=zod.z.object({Entries:zod.z.array(ro).nullish(),EventTokens:zod.z.array(gf).nullish()}),zl=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:pe.nullish()}),H=zod.z.object({Standard:pe.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(zl).nullish()}),bt=zod.z.object({Standard:pe.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(zl).nullish()}),M=zod.z.object({Grant:H.nullish(),Consume:bt.nullish()}),Dt=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:pe.nullish()});var yf=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Rf={Completed:"Completed",Started:"Started",StepReached:"StepReached"},Cf=zod.z.object({FlowIDs:zod.z.array(zod.z.string()).nullish(),Mode:zod.z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:zod.z.string().nullish(),Negate:zod.z.boolean().nullish(),SkippedCountsAsCompleted:zod.z.boolean().nullish()}).passthrough(),Z=zod.z.object({Segments:zod.z.array(zod.z.string()).nullish(),MinPremiumTier:zod.z.number().nullish(),RequiredPremiumIDs:zod.z.array(zod.z.string()).nullish(),MinLevel:zod.z.number().nullish(),MaxLevel:zod.z.number().nullish(),Countries:zod.z.array(zod.z.string()).nullish(),RegisteredWithinDays:zod.z.number().nullish(),ActiveWithinDays:zod.z.number().nullish(),Experiment:yf.nullish(),Tutorial:Cf.nullish(),Platforms:zod.z.array(Qi).nullish()}).passthrough();var Ce=zod.z.object({TotalCap:zod.z.number().nullish(),DailyCap:zod.z.number().nullish(),DailyWeightCap:zod.z.number().nullish(),PerActivationCap:zod.z.number().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish()}).passthrough();var Sf=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),xf=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),bf=zod.z.object({AnchorUtc:zod.z.string().nullish(),MaxCycles:zod.z.number().nullish(),PauseBetweenPhasesSec:zod.z.number().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish()}).passthrough();zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();var Df=zod.z.object({Reset:zod.z.string().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:zod.z.string().nullish(),PauseBetweenCyclesSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough();zod.z.object({SourceType:zod.z.string().nullish(),TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var nt=zod.z.object({SourceType:zod.z.string().nullish(),BaseWeight:zod.z.number().nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish(),TileTypeFilter:zod.z.array(zod.z.string()).nullish(),TileIndexFilter:zod.z.array(zod.z.number()).nullish(),ChanceOutcomeFilter:zod.z.array(zod.z.string()).nullish(),OutcomeFilter:zod.z.array(zod.z.string()).nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Limits:Ce.nullish()}).passthrough(),ye=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:xf.nullish(),Chain:bf.nullish(),Cyclic:Df.nullish(),ActivationTriggers:zod.z.array(nt).nullish(),Relative:Sf.nullish()}).passthrough();var Pf={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},If=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),vf={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Tf=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),Af=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),_e=zod.z.object({Base:zod.z.number().nullish(),Shape:If.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(Af).nullish(),Interpolation:Tf.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var kf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:H.nullish()}).passthrough(),wf=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),oo=zod.z.object({Bundles:zod.z.array(kf).nullish(),Multipliers:zod.z.array(wf).nullish()}).passthrough();var zf=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Ji=zod.z.object({Source:zf.nullish(),SourceKey:zod.z.string().nullish(),Curve:_e.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:pe.nullish(),ExcludeRewards:pe.nullish()}).passthrough(),Ml=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),Be=zod.z.object({MilestoneID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredProgress:zod.z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:oo.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),di=zod.z.object({Milestones:zod.z.record(zod.z.string(),Be).nullish()}).passthrough();var K=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var Mf=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Qt=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxBalance:zod.z.number().nullish(),MaxPerGrant:zod.z.number().nullish(),DailyEarnCap:zod.z.number().nullish(),BurnOnEventEnd:zod.z.boolean().nullish(),BurnConversion:Mf.nullish()}).passthrough();var Of=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),Ol=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:Of.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),Q=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),Ol).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var Te=r=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:r.nullish()}),gt=r=>zod.z.object({ServerTimeUtc:c,Items:zod.z.array(Te(r)),Resources:M.nullish(),Inventory:Q.nullish()});var Ef={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},El=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Uf=zod.z.object({}).passthrough().transform(r=>r),qf=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:c.nullish(),CycleEndUtc:c.nullish(),PointsTotalEarned:j.nullish(),PointsCurrent:j.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),ao=zod.z.object({QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),ObjectiveID:zod.z.string().nullish(),NewValue:j.nullish(),ObjectiveCompleted:zod.z.boolean().nullish(),Status:El}),Ul=zod.z.object({State:Uf.nullish(),PointsTracks:zod.z.record(zod.z.string(),qf).nullish()}),lo=zod.z.object({ServerTimeUtc:c,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:El.nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),uo=zod.z.object({ServerTimeUtc:c,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:j.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),ql=zod.z.object({ServerTimeUtc:c,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ll=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(ao).nullish()}),Bl=zod.z.array(Te(lo)),Gl=zod.z.array(Te(uo)),Lf={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Bf=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Gf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Ff=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),Fl=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:Bf.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(nt).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),co=zod.z.object({Milestones:K.nullish(),Linking:K.nullish(),Availability:K.nullish(),Reward:K.nullish(),Objectives:K.nullish()}).passthrough(),_f=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),_l=zod.z.object({CycleIDs:zod.z.array(zod.z.string()).nullish(),GroupID:zod.z.string().nullish(),PhaseIDs:zod.z.array(zod.z.string()).nullish(),RequiredQuestIDs:zod.z.array(zod.z.string()).nullish(),PrerequisiteMode:Ff.nullish()}).passthrough(),Vl=zod.z.object({Schedule:ye.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),Nl=zod.z.object({Grant:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),Vf=zod.z.object({QuestID:zod.z.string().nullish(),Identity:_f.nullish(),Linking:_l.nullish(),Availability:Vl.nullish(),Objectives:zod.z.record(zod.z.string(),Fl).nullish(),Reward:Nl.nullish(),Presets:co.nullish()}).passthrough(),Nf=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:Z.nullish(),Reward:H.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),jf=zod.z.object({PhaseID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Gate:Z.nullish(),Milestones:zod.z.record(zod.z.string(),Be).nullish(),Presets:co.nullish(),PointsToken:Qt.nullish()}).passthrough(),Wf=zod.z.object({Milestones:zod.z.record(zod.z.string(),di).nullish(),Linking:zod.z.record(zod.z.string(),_l).nullish(),Availability:zod.z.record(zod.z.string(),Vl).nullish(),Reward:zod.z.record(zod.z.string(),Nl).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Fl)).nullish()}).passthrough(),Kf=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ye.nullish(),Milestones:zod.z.record(zod.z.string(),Be).nullish(),Gate:Z.nullish(),PointsToken:Qt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),Nf).nullish(),Phases:zod.z.record(zod.z.string(),jf).nullish(),Presets:co.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Yi=zod.z.object({Cycles:zod.z.record(zod.z.string(),Kf).nullish(),Quests:zod.z.record(zod.z.string(),Vf).nullish(),Presets:Wf.nullish()}).passthrough(),dt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var Qf={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},Hf=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),$f={Never:"Never",OnRequest:"OnRequest",Always:"Always"},Jf=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),Zf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},Yf=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),Xf={GameLoop:"GameLoop"},eg={Raid:"Raid",Attack:"Attack"},tg=zod.z.object({Title:zod.z.string().nullish(),TitleKey:zod.z.string().nullish(),Body:zod.z.string().nullish(),BodyKey:zod.z.string().nullish(),AnchorID:zod.z.string().nullish(),HighlightTarget:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),UiHint:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ig=zod.z.object({Mode:Hf.nullish(),Triggers:zod.z.array(nt).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),sg=zod.z.object({Grant:H.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),ng=zod.z.object({TileType:zod.z.string().nullish(),TileIndex:zod.z.number().nullish(),ChanceOutcomeID:zod.z.string().nullish(),RandomActionType:zod.z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),rg=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:ng.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),og=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),po=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:tg.nullish(),Completion:ig.nullish(),Effects:sg.nullish(),Script:rg.nullish(),Policy:og.nullish()}).passthrough(),ag=zod.z.object({DisplayName:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),Description:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),jl=zod.z.object({Schedule:ye.nullish(),Gate:Z.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:nt.nullish()}).passthrough(),Wl=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:Jf.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Kl=zod.z.object({Grant:H.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),lg=zod.z.object({Availability:K.nullish(),Policy:K.nullish(),Reward:K.nullish(),Steps:K.nullish()}).passthrough(),ug=zod.z.object({FlowID:zod.z.string().nullish(),Identity:ag.nullish(),Availability:jl.nullish(),Policy:Wl.nullish(),Steps:zod.z.record(zod.z.string(),po).nullish(),Reward:Kl.nullish(),Presets:lg.nullish()}).passthrough(),cg=zod.z.object({BlockingFlowIDs:zod.z.array(zod.z.string()).nullish(),BlockedModules:zod.z.array(zod.z.string()).nullish(),BlockedActions:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),BlockBeforeStart:zod.z.boolean().nullish(),SkipLiftsBlock:zod.z.boolean().nullish()}).passthrough(),pg=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:cg.nullish()}).passthrough(),dg=zod.z.object({Availability:zod.z.record(zod.z.string(),jl).nullish(),Policy:zod.z.record(zod.z.string(),Wl).nullish(),Reward:zod.z.record(zod.z.string(),Kl).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),po)).nullish()}).passthrough(),Ql=zod.z.object({Flows:zod.z.record(zod.z.string(),ug).nullish(),Settings:pg.nullish(),Presets:dg.nullish()}).passthrough(),hg=zod.z.object({}).passthrough().transform(r=>r),Hl=zod.z.object({FlowID:zod.z.string(),Status:Yf,CurrentStepID:zod.z.string().nullish(),CurrentStep:po.nullish(),TotalSteps:zod.z.number(),CompletedSteps:zod.z.number(),CanSkip:zod.z.boolean(),RewardClaimed:zod.z.boolean(),RewardPending:zod.z.boolean(),VariantID:zod.z.string().nullish()}).passthrough(),Xi=zod.z.object({State:hg.nullish(),Flows:zod.z.array(Hl).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),Et=zod.z.object({Flow:Hl.nullish()}).passthrough(),$l=zod.z.object({FlowID:zod.z.string().nullish(),Granted:M.nullish()}).passthrough(),Jl=zod.z.array(Te(Et)),Zl=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),rt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function es(r){return Array.isArray(r)?r.filter(e=>e!==null).map(es):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==null).map(([e,t])=>[e,es(t)])):r}var ts=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 is=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Yl(r){return r===429||r>=500&&r<=599}function ss(r,e=Math.random){let t=Math.min(500*Math.pow(2,r-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function Ut(r){return new Promise(e=>setTimeout(e,r))}var Xl=15e3;async function eu(r){try{let t=JSON.parse(await r.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(r.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function tu(r,e=Math.random){return r+10+Math.min(250,r*.2)*e()}function iu(r,e=Math.random){let t=r<=1?1500:r===2?4e3:6e3;return t+t*.1*e()}var ho=15,su=1e3,ns=class{constructor(e=ho,t=()=>Date.now(),i=Ut){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]>=su;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(su-(e-this.starts[0])+5);}}};var mg=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function mi(r){if(!r)return null;let e=mg.exec(r);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new Ht__default.default(i),o=new Ht__default.default(s),p=o.minus(Ht__default.default.max(n,0));return p.lte(0)?null:{currencyID:t,required:o.toNumber(),available:n.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var fg=12e3,gg=new Set(["RelatedEntityID"]);function yg(r,e){if(e===null||typeof e!="object"||Array.isArray(e))return r;let t={};for(let[i,s]of Object.entries(e))gg.has(i)||(t[i]=s);try{return `${r}|${JSON.stringify(t)}`}catch{return r}}var Rg=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(ao).nullish(),TutorialProgress:zod.z.array(Zl).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),rs=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new is;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 ts(e.throttleMs),this.pacer=new ns(e.maxRequestsPerSecond??ho),this.clientPlatform=e.clientPlatform??ft.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??yg(e,t);if(!this.throttler.tryAcquire(n))return u("throttled","Throttled");if(!this.inflight.add(n))return u("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,p=JSON.stringify(t),h=s.ticket??null,R=s.silent??!1,B=s.timeoutMs??fg,re=s.autoRetry??!0,xe=!1,le=!1,fe=0;for(;;){let xt;s.keepalive||await this.pacer.take();try{xt=await this.doFetch(o,p,h,B,s.keepalive??!1);}catch{if(re&&fe<3){fe++,await Ut(ss(fe));continue}return this.connectionFailure("Internet Connection Error",R)}let Ze=xt.status;if(Ze>=200&&Ze<300){let oe=!le&&this.cryptoTopUpHandler!==null,ve=await this.parseSuccess(xt,i,R,e,oe);if(!ve.ok&&oe){let de=mi(ve.error);if(de){if(le=!0,await this.runTopUp(de))continue;R||this.emitter.emit("error:global",ve.error);}}return ve}if(Ze===401){if(!xe&&this.sessionRefreshHandler){xe=!0;let oe=null;try{oe=await this.sessionRefreshHandler();}catch{oe=null;}if(oe){h=oe;continue}}return this.emitter.emit("auth:unauthorized",void 0),u("unauthorized","Unauthorized")}if(Yl(Ze)){let oe=Ze===429?await eu(xt):null;if(oe!==null&&oe>Xl)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(oe/1e3)} s`,R);if(re&&fe<3){fe++,await Ut(oe!==null?tu(oe):Ze===429?iu(fe):ss(fe));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Ze})`,R)}let Ii="";try{Ii=await xt.text();}catch{}if(Ze===409&&/operation in progress/i.test(Ii)&&re&&fe<3){fe++,await Ut(ss(fe));continue}return this.handleWebError(Ii,Ze,R)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let o=new AbortController,p=setTimeout(()=>{o.abort();},s);try{let h={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(h.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:h,signal:o.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,i,s,n=false){let o;try{o=await e.text();}catch{return this.globalError("Failed to read response body",i)}let p;try{p=JSON.parse(o);}catch{return this.globalError("JSON Parse Error",i)}let h=Rg.safeParse(p);if(!h.success)return this.globalError("Malformed response envelope",i);if(!h.data.Success){let le=h.data.Error??"Server returned Success=false",fe=n&&mi(le);return !i&&!fe&&this.emitter.emit("error:global",le),u("server",le)}let R=h.data.StateVersions;R&&Object.keys(R).length>0&&this.emitter.emit("user:stateVersions",{epoch:h.data.StateEpoch??null,versions:R});let B=h.data.QuestProgress;B&&B.length>0&&this.emitter.emit("quest:systemProgress",B);let re=h.data.TutorialProgress;re&&re.length>0&&this.emitter.emit("tutorial:systemProgress",re);let xe=t.safeParse(h.data.Data);if(!xe.success){let le=t.safeParse(es(h.data.Data));le.success&&(xe=le);}if(!xe.success){let le=`Validation error (${s}): ${xe.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",le),i||this.emitter.emit("error:global",le),u("validation",le)}return _(xe.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),u("server","PLAY_ACCESS_REQUIRED");s=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),u("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),u("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),u("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function fi(r){return (typeof r=="string"?r:r.toISOString()).slice(0,10)}function wi(r){return `${fi(r)}T00:00:00.000Z`}function nu(r){let e=new Date(r);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function ru(r,e){return new Date(r.getTime()+e*6e4).toISOString()}function go(r,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;r.InventoryV2??={};let n=r.InventoryV2,o=i.toISOString(),p=new Map,h=new Map,R=new Map,B=new Map,re=new Map,xe=new Map,le=new Map,fe=new Map,xt=e.Grant?.PremiumTiers??[],Ze=xt.length;for(let oe=0;;oe++){let ve,de;if(oe===0)ve=e.Grant?.Standard?.Entries,de=false;else if(oe-1<Ze)ve=xt[oe-1]?.Resources?.Entries,de=false;else if(oe===1+Ze)ve=e.Consume?.Standard?.Entries,de=true;else break;if(ve)for(let ue of ve){if(ue.Type==null)continue;let he=Math.max(0,ue.Amount??0);if(!(he<=0))switch(ue.Type){case "VirtualCurrency":{if(!ue.CurrencyID)continue;let me=de?h:p;me.set(ue.CurrencyID,(me.get(ue.CurrencyID)??0)+he);break}case "CryptoCurrency":{if(!ue.CurrencyID)continue;let me=de?B:R;me.set(ue.CurrencyID,(me.get(ue.CurrencyID)??new Ht__default.default(0)).plus(he));break}case "Item":{if(!ue.ItemID)continue;let me=Sg(t,ue.CatalogID,ue.ItemID),De=(me?me.IsStackable??true:true)?de?xe:re:de?fe:le;De.set(ue.ItemID,(De.get(ue.ItemID)??0)+he);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||h.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let oe of new Set([...p.keys(),...h.keys()])){let ve=p.get(oe)??0,de=h.get(oe)??0,ue=ve-de,he=n.VirtualCurrencies[oe];he?(he.Amount+=ue,he.UpdatedAt=o,he.Daily&&fi(he.Daily.PeriodStartUtc)===fi(i)?(he.Daily.Earned+=ve,he.Daily.Spent+=de):he.Daily={PeriodStartUtc:wi(i),Earned:ve,Spent:de}):n.VirtualCurrencies[oe]={Amount:ue,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:wi(i),Earned:ve,Spent:de}};}}if(s.ccChanged=R.size>0||B.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let oe of new Set([...R.keys(),...B.keys()])){let ve=R.get(oe)??new Ht__default.default(0),de=B.get(oe)??new Ht__default.default(0),ue=ve.minus(de),he=n.CryptoCurrencies[oe];he?(he.Amount=new Ht__default.default(he.Amount).plus(ue).toString(),he.UpdatedAt=o):n.CryptoCurrencies[oe]={Amount:ue.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(s.itemsChanged=re.size>0||xe.size>0||le.size>0||fe.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let oe=n.UnstackableItems,ve=new Set([...re.keys(),...xe.keys(),...le.keys(),...fe.keys()]);for(let de of ve){let ue=(re.get(de)??0)-(xe.get(de)??0),he=(le.get(de)??0)-(fe.get(de)??0),me=ue+he,st=n.Items[de];st?(ue!==0&&(st.StackableAmount+=ue),he!==0&&(st.UnstackableAmount+=he),me!==0&&(st.TotalAmount+=me)):n.Items[de]={StackableAmount:Math.max(0,ue),UnstackableAmount:Math.max(0,he),TotalAmount:Math.max(0,me)};}for(let[de,ue]of fe){if(ue<=0)continue;let he=Object.values(oe).filter(me=>me.ItemID===de&&me.EquippedSlot==null&&(me.ExpiresAt==null||new Date(me.ExpiresAt)>i)).sort(Cg).slice(0,ue).map(me=>me.ItemInstanceID);for(let me of he)delete oe[me];}for(let[de,ue]of le){let he=xg(t,de);for(let me=0;me<ue;me++){let st=G();oe[st]={ItemInstanceID:st,ItemID:de,CatalogID:he,RemainingUses:1,AcquiredAt:o};}}}r.EventToken??={};let Ii=r.EventToken;for(let oe=0;;oe++){let ve,de;if(oe===0)ve=e.Grant?.Standard?.EventTokens,de=false;else if(oe-1<Ze)ve=xt[oe-1]?.Resources?.EventTokens,de=false;else if(oe===1+Ze)ve=e.Consume?.Standard?.EventTokens,de=true;else break;if(!(!ve||ve.length===0))for(let ue of ve){let he=ue.Address;if(!he||he.Type==null)continue;let me=ue.Amount??0;if(me<=0)continue;let st=bg(Ii,he.Type);if(!st)continue;let De=st[he.EntityID];De||(De={},st[he.EntityID]=De),De.Balance??={Current:0,TotalEarned:0,TotalSpent:0},De.Daily??={Date:wi(i),TotalEarned:0},De.Meta??={};let vi=ue.Source&&ue.Source.length>0?ue.Source:"CustomAction";de?(De.Balance.Current-=me,De.Balance.TotalSpent+=me):(De.Balance.Current+=me,De.Balance.TotalEarned+=me,fi(De.Daily.Date)!==fi(i)&&(De.Daily={Date:wi(i),TotalEarned:0}),De.Daily.TotalEarned+=me,De.Daily.EarnedBySource??={},De.Daily.EarnedBySource[vi]=(De.Daily.EarnedBySource[vi]??0)+me,De.Daily.TriggersBySource??={},De.Daily.TriggersBySource[vi]=(De.Daily.TriggersBySource[vi]??0)+1,De.Daily.LastTriggerBySource??={},De.Daily.LastTriggerBySource[vi]=o,De.Meta.JoinedAtUtc||(De.Meta.JoinedAtUtc=o),De.Meta.LastEarnedAtUtc=o),s.tokensChanged=true;}}return s}function Cg(r,e){return r.AcquiredAt!==e.AcquiredAt?r.AcquiredAt<e.AcquiredAt?-1:1:r.ItemInstanceID===e.ItemInstanceID?0:r.ItemInstanceID<e.ItemInstanceID?-1:1}function Sg(r,e,t){let i=r?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let n=s.Items?.[t];if(n)return n}}}function xg(r,e){let t=r?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function bg(r,e){switch(e){case "TimedEvent":return r.TimedEvent??={};case "Quest":return r.Quest??={};case "Leaderboard":return r.Leaderboard??={};case "CoopEvent":return r.CoopEvent??={};case "Season":return r.Season??={};default:return null}}function ou(r,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},n=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let h of Object.values(s))h?.ItemID&&o.add(h.ItemID);for(let h of n){let R=r[h]?.ItemID;R&&o.add(R);}if(o.size===0)return i;let p=h=>n.has(h)||h in s;if(e){for(let[h,R]of Object.entries(e))h in r||p(h)||R&&o.has(R.ItemID)&&i.drop.push(h);for(let[h,R]of Object.entries(r))h in e||p(h)||R&&o.has(R.ItemID)&&(i.restore[h]=R);}return i}function yo(r,e){return r===e||r.startsWith(`${e}:`)}var as=class r{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){r.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];r.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){r.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let s=go(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let n=this.currentState,o={...n.InventoryV2?.UnstackableItems??{}},p=go(n,e,i,s),h=ou(o,n.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),B=t?.RemovedInstanceIDs??[],re=h.drop.length>0||Object.keys(h.restore).length>0||R.length>0||B.length>0;if(re){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let xe=n.InventoryV2.UnstackableItems;for(let le of h.drop)delete xe[le];for(let[le,fe]of Object.entries(h.restore))xe[le]=fe;for(let[le,fe]of R)xe[le]=fe;for(let le of B)delete xe[le];}this.emitResourceChanges(p,re);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof Ht__default.default?t:new Ht__default.default(t),p=s===void 0?new Ht__default.default(0):s instanceof Ht__default.default?s:new Ht__default.default(s),h=i??new Date().toISOString(),R=n[e];R?(R.Amount=new Ht__default.default(R.Amount).plus(o).toString(),p.isZero()||(R.Frozen=new Ht__default.default(R.Frozen??0).plus(p).toString()),R.UpdatedAt=h):n[e]={Amount:o.toString(),Frozen:p.toString(),CreatedAt:h,UpdatedAt:h},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,n=s[e];n||(n={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=n),n.TotalPurchases+=t,n.LastPurchasedAt=i,i>=n.DailyResetUtc?(n.DailyPurchases=t,n.DailyResetUtc=nu(i)):n.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let n=new Date().toISOString();for(let o of t)o.RuleID&&(s.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:n});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let n=s.Cycles[t];if(!n)return;n.Quests??={};let o=n.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let n=s.PermanentQuests[e]??={QuestID:e,Status:i};n.Status=i,i==="Claimed"&&(n.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,n=t[s]??={};n.Balance??={Current:0,TotalEarned:0,TotalSpent:0},n.Balance.Current=i.PointsCurrent??0,n.Balance.TotalEarned=i.PointsTotalEarned??0,n.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(n.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let n=s.Steps[i.StepID]??={StepID:i.StepID};n.Progress=i.Progress,i.Completed&&(n.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let n=t.Cycles[i.CycleID];if(!n)continue;n.Quests??={},s=n.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let n=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};n.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(n.Completed=true,n.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(yo(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[n,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((s?n!==s:!yo(n,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let n=this.activeEventsCache?.ActiveEvents;if(n)for(let o of n)o.Type!==e||o.TimedEventID!==t||s&&o.TokenEntityID&&o.TokenEntityID!==s||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,s){if(!e)return;let n=this.ensureLeaderboardProgress(e);(n.ScoreCycleVersion??0)<s&&(n.ScoreEarnedThisCycle=0,n.ClaimedMilestoneIDs=[],n.BracketID=null),n.CurrentScore=t,n.ScoreEarnedThisCycle=(n.ScoreEarnedThisCycle??0)+i,n.ScoreCycleVersion=s,n.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let s=false;for(let n of Object.values(i))for(let o of Object.values(n.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[s,n]of Object.entries(e.ChangedInstances??{}))t[s]=n,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e,t){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,t!=null&&(this.currentState.Referral.QualificationPending=t),this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(i)){let n=i[s];n&&n.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,s,n){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,p={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")o.Private??={},o.Private[t]=p;else if(e==="Public")o.Public??={},o.Public[t]=p;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let s=i.BuildingStates.find(n=>n.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},n=s.PendingWithdrawals??[];t.size>0&&(n=n.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!n.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(n=[...n,i]),s.PendingWithdrawals=n;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var ls=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 us=class{user;config;constructor(e){this.user=new as(e),this.config=new ls;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Dg(r){return r}var Pg=0,Ig=1500,vg=3,ps=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 _(void 0);let i=Date.now(),s=[],n=[];for(let h of new Set(e)){let R=this.rules.get(h);if(R&&(t?.force||R.needsServer(i))){s.push(this.runRule(h,R));continue}(t?.force||!this.state.isStateFresh(h,t?.maxAgeMs))&&n.push(h);}let p=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(_(void 0))])).find(h=>!h.ok);return p&&!p.ok?p:_(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();},Pg),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):_(void 0),n=s.ok?_(void 0):s;for(let o of t)o(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=cs(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let R=this.fresh(s,i?.maxAgeMs);if(R)return _(R.data);let B=this.loginFailures.get(s);if(B)return this.loginFailures.delete(s),B;let re=this.inflight.get(s);if(re)return re}let n=this.generation.get(s)??0,o=Date.now(),h=t().then(R=>{if(!R.ok)return R;let B=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:R.data,storedAt:B,expiresAt:Ro(e,R.data,B)}),R;let re=this.entries.get(s);if(re&&re.storedAt>=o)return R;let xe=Ro(e,R.data,B);return this.entries.set(s,{data:R.data,storedAt:B,expiresAt:Math.min(xe??1/0,B+Ig)}),R}).finally(()=>{this.inflight.get(s)===h&&this.inflight.delete(s);});return this.inflight.set(s,h),h}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let s=t.Key?t.Key:void 0,n=cs(i.view,s);if(!t.Success){this.loginFailures.set(n,u("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(n),i.apply(o.data,s),this.put(i.view,o.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let n=au({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>vg||this.used.set(au(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(cs(e,t))?.data}put(e,t,i){this.register(e);let s=cs(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:Ro(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 cs(r,e){return e===void 0?r.key:`${r.key}|${e}`}function au(r){return r.Key?`${r.Name}|${r.Key}`:r.Name}function Ro(r,e,t){let i=r.expiresAt?.(e)??null,s=r.ttlMs!==void 0?t+r.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var ds=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 Tg(e)?e:ke.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 Tg(r){return r!==null&&Object.values(ke).includes(r)}var Pt=["https://idosgames.com","https://www.idosgames.com"],hs="https://platform.idosgames.com",lu=/^[a-z0-9]{8}-preview\.idos\.games$/;function Co(r){return r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r.endsWith(".localhost")}function So(){if(typeof window>"u")return false;let r=window.location.hostname.toLowerCase();return lu.test(r)?true:Co(r)&&globalThis.__IDOS_PREVIEW__!=null}function zi(r){if(typeof window<"u"&&lu.test(window.location.hostname.toLowerCase()))return r===hs;if(Pt.includes(r))return true;if(typeof window>"u"||!Co(window.location.hostname))return false;try{return Co(new URL(r).hostname)}catch{return false}}var uu="IDOS_PLATFORM_WALLET_ACK",cu="PLATFORM_WALLET_UNAVAILABLE",Ag=5e3,kg=18e4;function wg(){if(zi(hs))return [hs];let r=[...Pt],e=window.location.ancestorOrigins?.[0];return e&&!r.includes(e)&&zi(e)&&r.push(e),r}function zg(){return `wallet-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function It(r,e,t,i={}){let s={ok:false,error:cu,data:{}};if(typeof window>"u"||window.self===window.top)return Promise.resolve(s);let n=window.parent;if(!n)return Promise.resolve(s);let o=zg(),p=i.answerTimeoutMs??kg;return new Promise(h=>{let R=false,B,re=le=>{R||(R=true,window.removeEventListener("message",xe),clearTimeout(B),h(le));},xe=le=>{if(!zi(le.origin))return;let fe=le.data;if(!(!fe||fe.requestId!==o)){if(fe.type===uu){clearTimeout(B),B=setTimeout(()=>re({ok:false,error:"TIMEOUT",data:{}}),p);return}fe.type===e&&re({ok:fe.ok===true,error:typeof fe.error=="string"?fe.error:void 0,data:fe});}};B=setTimeout(()=>re(s),Ag),window.addEventListener("message",xe);for(let le of wg())try{n.postMessage({type:r,requestId:o,...t},le);}catch{}})}var xo={request:"IDOS_PLATFORM_AUTH_REQUEST",response:"IDOS_PLATFORM_AUTH_RESPONSE"},Mg=30*6e4,bo="idos:platformSignIn:declined:";function Og(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}if(So())return false;let r=window.location.ancestorOrigins?.[0];if(r&&!Pt.includes(r))try{let e=new URL(r).hostname;if(e!=="localhost"&&e!=="127.0.0.1")return !1}catch{return false}return true}function Eg(){if(typeof window>"u"||!So())return false;try{return window.self!==window.top&&window.parent===window.top}catch{return false}}async function Do(r){let e=await It(xo.request,xo.response,{titleID:r,supports:["pgs"]},{answerTimeoutMs:Mg}),t=e.data.ticket;if(e.ok&&typeof t=="string"&&t.length>0)return {ticket:t};let i=e.data.code;return e.ok&&typeof i=="string"&&i.length>0?{code:i}:{error:e.error??"no_code"}}function Ug(r){try{window.localStorage.setItem(bo+r,"1");}catch{}}function qg(r){try{window.localStorage.removeItem(bo+r);}catch{}}function Lg(r){try{return window.localStorage.getItem(bo+r)==="1"}catch{return false}}var Bg=8,Gg=100,Fg=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,pu=["GameLoop"];function _g(r){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(r)}var ms=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=ke.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";platformGameSession=false;pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let s=this.authContext;if(!s)return a;let n=this.baseRequest();n.UserID=s.userID,n.ClientSessionTicket=s.clientSessionTicket,n.WalletAddress=e,n.NetworkID=t,i&&(n.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(n);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return a;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(ke.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return u("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ke.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(ke.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},_({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(ke.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?_(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(ke.Google)):i}async loginWithApple(e,t){if(!e?.trim())return u("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(ke.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(ke.Wallet)):n}async loginWithSsoCode(e){if(!e)return u("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.platform.getDeviceID(),t.Device=this.ctx.platform.getDeviceModel(),t.Platform=this.ctx.platform.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(ke.iDosGames)):i}async loginWithPlatformGameTicket(e){if(!e)return u("client","Platform game ticket is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.PlatformGameTicket=e;let i=await this.ctx.api.authentication.resolvePlatformGameSession(t);return i.ok?(this.applyAuthContext(i.data),this.platformGameSession=true,this.fetchAndApplyClientState(ke.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!==ke.None?e:ke.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"):(_g(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 ke.Email:return this.loginWithEmail(t,i);case ke.Device:case ke.None:return this.loginWithDeviceID();case ke.Telegram:return this.loginWithTelegram();default:return Promise.resolve(u("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;if(this.platformGameSession){this.refreshing=true;try{let t=await Do(this.ctx.settings.titleID);if(!t.ticket)return null;let i=this.baseRequest();i.PlatformGameTicket=t.ticket;let s=await this.ctx.api.authentication.resolvePlatformGameSession(i);return s.ok?(this.applyAuthContext(s.data),this.platformGameSession=!0,s.data.TitleClientSessionTicket):null}catch{return null}finally{this.refreshing=false;}}this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==ke.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===ke.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&&Fg.test(e)}static isValidPasswordLength(e){return e.length>=Bg&&e.length<=Gg}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.platformGameSession=false,this.sessionAuthType=ke.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.platformGameSession=false,this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e){let t=await this.ctx.userService.getClientStateExcept(pu,pu);return t.ok&&(this.sessionAuthType=e,this.rememberSession?(this.ctx.authStore.saveAuthType(e),this.ctx.authStore.saveRefreshToken(this.sessionRefreshToken)):this.ctx.authStore.clear(),this.ctx.emitter.emit("auth:loggedIn",void 0)),t}};var Vg="idos:cfg",gi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${du(t)}`:e&&e.length>0?`f:${du(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${Vg}:${this.titleId}:${e}`}};function du(r){return [...r].map(e=>e.toLowerCase()).sort().join(",")}var hu="idos:loc",yi=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 `${hu}:${this.titleId}:${e}`}versionsKey(){return `${hu}:${this.titleId}:versions`}};var Ng="idos:sec",fs=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf());if(!t)return {};let i=JSON.parse(t);return !i||typeof i!="object"||i.v!==e||!i.s||typeof i.s!="object"?{}:i.s}catch{return {}}}async write(e,t){try{let i={v:e,s:t};await this.storage.set(this.keyOf(),JSON.stringify(i));}catch{}}keyOf(){return `${Ng}:${this.titleId}`}};var jg="idos:state",gs=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 `${jg}:${this.titleId}:${e}`}};function Wg(r,e){if(!r)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return r;let i={};for(let[s,n]of Object.entries(r))t.has(s.toLowerCase())||(i[s]=n);return i}function Po(r,e,t,i){let s={...r??{}};if(!e||!t||!i)return s;for(let[n,o]of Object.entries(t))i[n]===o&&n in e&&(s[n]=e[n]);return s}function Kg(r){return {...r??{}}}function Io(r){return typeof r.StateEpoch=="string"&&r.StateEpoch.length>0?r.StateEpoch:null}var ys=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=Wg(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let n=Object.keys(this.versions);this.reset(e),this.notify(n);}return}let i=Date.now(),s=[];for(let[n,o]of Object.entries(t)){let p=this.versions[n];p!==o&&(p!==void 0&&o===p+1?(this.versions[n]=o,this.confirmedAt[n]=i):(delete this.versions[n],delete this.confirmedAt[n]),s.push(n),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=Kg(t);let s=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=s;this.dirty=true;let n=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&n.add(o);this.notify([...n]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[n,o]of Object.entries(t??{}))this.versions[n]!==o&&s.push(n),this.versions[n]=o,this.confirmedAt[n]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var mu=u("server","Title configuration is unavailable (CDN and API both failed)."),Rs=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),RelatedEntityID:G()}:null}get configCache(){return this.cache??=new gi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new yi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new fs(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new ys(new gs(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return a;let t=gi.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let n=await this.ctx.api.user.getClientState(e);if(!n.ok)return n;let o=await this.resolveTitleConfig(n.data,t,i,{Fields:e.TitleFields});return o==null?mu:(this.finishStateHandshake(n.data,s),await this.restoreSections(n.data.TitleConfigVersion,o),await this.applyClientState(n.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(n.data.Views),await this.applyLocalization(n.data.Localization),await this.flushState(s),n)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let n=this.stateStore.currentEpoch;n&&(e.KnownStateEpoch=n);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=Po(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=Io(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 o=await this.fetchConfigFromApi(s);return o!=null?(n&&await this.configCache.write(t,n,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return a;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=gi.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let p=await this.ctx.api.user.getClientStateExcept(i);if(!p.ok)return p;let h=await this.resolveTitleConfig(p.data,s,n,{ExcludeFields:t??[]});return h==null?mu:(this.finishStateHandshake(p.data,o),await this.restoreSections(p.data.TitleConfigVersion,h),await this.applyClientState(p.data,h,e,t),this.ctx.cache.acceptLoginViews(p.data.Views),await this.applyLocalization(p.data.Localization),await this.flushState(o),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,o]of Object.entries(await this.sectionCache.read(e)))i[n]==null&&(s[n]=o);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((n,o)=>{i[n]!=null||o==null||(s[n]=o,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let n=await this.fetchLocalizationFromApi(t,s?.v??0);return n??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let n=s.data;if(n.NotModified)return null;let o=n.Entries??{},p=n.Version??0,h=n.Locale??e;return p>0&&await this.localizationCache.write(h,p,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):a}async getUserState(e){let t=this.baseRequest();if(!t)return a;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let n=Po(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let o=i.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([R,B])=>o[R]!==B||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(n,p);let h=Io(s.data);return h&&(this.stateStore.afterSliceRead(h,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return a;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let s=this.baseRequest();if(!s)return a;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 a;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return a;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,s){let n=i?.includes("GameLoop")===true,o=s?.includes("GameLoop")===true,p=n?this.ctx.data.user.state?.GameLoop:void 0,h=o?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let R=this.ctx.data.user.state;n&&R&&R.GameLoop==null&&(R.GameLoop=p);let B=this.ctx.data.config.titlePublicConfiguration;o&&B&&B.GameLoop==null&&(B.GameLoop=h),this.ctx.emitter.emit("user:clientStateReceived",e);}};var Ss=class{constructor(e){this.ctx=e;}ctx;async convert(e,t,i,s,n,o){if(!t)return u("client","SourceID is required.");if(!s)return u("client","TargetID is required.");if(n<=0)return u("client","Amount must be positive.");if(e===i&&t===s)return u("client","Source and target must differ.");if(e===ct.Crypto||i===ct.Crypto)return u("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return a;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(n)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${s}_${G()}`},h=await this.ctx.api.currency.convert(p);if(h.ok){let R=h.data,B={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(B,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return h}async cryptoConvert(e,t,i,s,n,o){let p=n instanceof Ht__default.default?n:new Ht__default.default(n);if(!t)return u("client","SourceID is required.");if(!s)return u("client","TargetID is required.");if(p.lte(0))return u("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return u("client","Source and target must differ.");if(e===ct.Virtual&&i===ct.Virtual)return u("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ct.Virtual&&!p.isInteger())return u("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:p.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${s}_${G()}`},R=await this.ctx.api.currency.cryptoConvert(h);if(R.ok){let B=R.data,re=[],xe=[];if(B.SourceType===ct.Virtual&&re.push({Type:"VirtualCurrency",CurrencyID:B.SourceID,Amount:Math.trunc(Number(B.SourceSpent))}),B.TargetType===ct.Virtual&&xe.push({Type:"VirtualCurrency",CurrencyID:B.TargetID,Amount:Math.trunc(Number(B.TargetCredited))}),re.length>0||xe.length>0){let le={Consume:re.length>0?{Standard:{Entries:re}}:null,Grant:xe.length>0?{Standard:{Entries:xe}}:null};this.ctx.data.user.applyResourceOperation(le,this.ctx.data.config.itemDefinitions);}B.SourceType===ct.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(B.SourceID,new Ht__default.default(B.SourceSpent).negated(),B.ServerTimeUtc),B.TargetType===ct.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(B.TargetID,new Ht__default.default(B.TargetCredited),B.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",B);}return R}};var xs=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let s=e.trim();if(!s)return u("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${s}_${G()}`};t&&t.length>0&&(n.FodderInstanceIDs=[...t]);let o=await this.ctx.api.item.upgradeLevel(n);return o.ok&&(this.ctx.data.user.patchEquippedItemLevel(o.data.ItemInstanceID??s,o.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",o.data)),o}async upgradeLevelsBatch(e){if(!e||e.length===0)return u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let 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 fu=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:bt.nullish(),AllowedPlatforms:zod.z.array(Qi).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ce=zod.z.record(zod.z.string(),fu),Qg=zod.z.object({Store:Hi,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var Mi={Pending:"Pending",Confirmed:"Confirmed",Declined:"Declined",Completed:"Completed",Expired:"Expired"},vo=zod.z.object({ConfirmationID:zod.z.string(),Url:zod.z.string(),Status:zod.z.string(),PriceCredits:zod.z.number(),ExpiresAt:c}).passthrough(),gu=zod.z.object({Linked:zod.z.boolean(),Credits:zod.z.number(),TopUpUrl:zod.z.string().nullish()}).passthrough(),Hg={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"},To=zod.z.object({ServerTimeUtc:c,OfferID:zod.z.string(),Count:zod.z.number(),Resources:M.nullish(),Inventory:Q.nullish(),CreditsConfirmation:vo.nullish()}),yu=zod.z.array(Te(To)),$g=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:c,LastPurchasedAt:c}),Jg=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:c}),Ru=zod.z.object({Purchases:zod.z.record(zod.z.string(),$g).nullish(),Rotations:zod.z.record(zod.z.string(),Jg).nullish()}).passthrough().transform(r=>r),vt=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),bs=zod.z.object({Schedule:ye.nullish(),Gate:Z.nullish()}).passthrough(),Zg={Fixed:"Fixed",Title:"Title",Player:"Player"},Yg=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:Z.nullish()}).passthrough(),Cu=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(Yg).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),Xg=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Rotation:K.nullish()}).passthrough(),ey=zod.z.object({SlotID:zod.z.string().nullish(),Identity:vt.nullish(),Availability:bs.nullish(),Rotation:Cu.nullish(),Presets:Xg.nullish()}).passthrough(),ty=zod.z.object({Identity:K.nullish(),Availability:K.nullish()}).passthrough(),iy=zod.z.object({SectionID:zod.z.string().nullish(),Identity:vt.nullish(),Availability:bs.nullish(),Slots:zod.z.record(zod.z.string(),ey).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:ty.nullish()}).passthrough(),Su=zod.z.object({Sections:zod.z.record(zod.z.string(),iy).nullish()}).passthrough(),sy=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Layout:K.nullish()}).passthrough(),ny=zod.z.object({StoreID:zod.z.string().nullish(),Identity:vt.nullish(),Availability:bs.nullish(),Layout:Su.nullish(),Presets:sy.nullish()}).passthrough(),xu=zod.z.object({Options:ce.nullish(),CompareAt:zod.z.record(zod.z.string(),bt).nullish()}).passthrough(),bu=zod.z.object({Grant:H.nullish()}).passthrough(),Du=zod.z.object({Schedule:ye.nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),ry=zod.z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish(),Availability:K.nullish()}).passthrough(),oy=zod.z.object({OfferID:zod.z.string().nullish(),Identity:vt.nullish(),Pricing:xu.nullish(),Reward:bu.nullish(),Availability:Du.nullish(),Presets:ry.nullish()}).passthrough(),ay=zod.z.object({Identity:zod.z.record(zod.z.string(),vt).nullish(),Availability:zod.z.record(zod.z.string(),bs).nullish(),Layout:zod.z.record(zod.z.string(),Su).nullish(),Rotation:zod.z.record(zod.z.string(),Cu).nullish(),Pricing:zod.z.record(zod.z.string(),xu).nullish(),Reward:zod.z.record(zod.z.string(),bu).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Du).nullish()}).passthrough(),Ds=zod.z.object({Stores:zod.z.record(zod.z.string(),ny).nullish(),StoreOffers:zod.z.record(zod.z.string(),oy).nullish(),Presets:ay.nullish()}).passthrough(),ly=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:c.nullish()}).passthrough(),uy=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:bt.nullish(),CompareAtCost:bt.nullish(),DiscountPercent:zod.z.number().nullish(),IsFree:zod.z.boolean(),IsAdPaid:zod.z.boolean(),IsStorePaid:zod.z.boolean(),IsCreditsPaid:zod.z.boolean().nullish(),CreditsPrice:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),cy=zod.z.object({OfferID:zod.z.string(),Identity:vt.nullish(),PriceOptions:zod.z.array(uy).nullish(),Rewards:H.nullish(),State:ly.nullish()}).passthrough(),py=zod.z.object({SlotID:zod.z.string(),Identity:vt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:c.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:cy.nullish()}).passthrough(),dy=zod.z.object({SectionID:zod.z.string(),Identity:vt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(py).nullish()}).passthrough(),hy=zod.z.object({StoreID:zod.z.string(),Identity:vt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:c.nullish(),Sections:zod.z.array(dy).nullish()}).passthrough(),Ps=zod.z.object({ServerTimeUtc:c,Stores:zod.z.array(hy).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Tt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront",GetCreditsConfirmation:"GetCreditsConfirmation",GetCreditsBalance:"GetCreditsBalance"},my="OFFER_NOT_IN_ROTATION";var Ao={request:"IDOS_PLATFORM_TOPUP_REQUEST",response:"IDOS_PLATFORM_TOPUP_RESPONSE"},fy=15*6e4,gy=/^[a-z0-9]{8}-preview\.idos\.games$/;function $t(){if(typeof window>"u")return false;try{if(window.self===window.top||window.parent!==window.top)return !1}catch{return false}return !gy.test(window.location.hostname.toLowerCase())}async function ko(r){let e=await It(Ao.request,Ao.response,{titleID:r.titleID,userID:r.userID,currencyID:r.currencyID,amount:r.amount},{answerTimeoutMs:fy});return e.ok?{ok:true}:{ok:false,error:e.error}}var wo={request:"IDOS_PLATFORM_CREDITS_CONFIRM_REQUEST",response:"IDOS_PLATFORM_CREDITS_CONFIRM_RESPONSE"},yy=10*6e4;function zo(){return $t()}async function Mo(r){let e=await It(wo.request,wo.response,{titleID:r.titleID,confirmationID:r.confirmationID},{answerTimeoutMs:yy});return e.ok?{ok:true}:{ok:false,error:e.error}}var Pu="Store",Iu={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=null;for(let t of r.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},Is=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Iu,{schema:Ps,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return u("client","OfferID is required.");if(t<1)return u("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return a;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}_${G()}`},o=await this.ctx.api.store.purchase(n);if(o.ok&&!o.data.CreditsConfirmation){let p=o.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return o}async purchaseWithCredits(e,t=1,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,o=()=>this.purchase(e,t,{selectedOptionID:i.selectedOptionID,slot:i.slot,creditsConfirmationID:n.ConfirmationID});if(zo()){let R=await Mo({titleID:this.ctx.settings.titleID,confirmationID:n.ConfirmationID});if(R.ok)return await o();if(R.error==="DECLINED")return u("server","CREDITS_CONFIRMATION_DECLINED");if(R.error==="NOT_ENOUGH_CREDITS")return u("server","NOT_ENOUGH_CREDITS")}i.onConfirmation?.(n);let p=Math.max(1e3,i.pollMs??2500),h=Date.parse(n.ExpiresAt)+6e4;for(;;){if(i.signal?.aborted)return u("client","CREDITS_CONFIRMATION_CANCELLED");if(Date.now()>h)return u("server","CREDITS_CONFIRMATION_EXPIRED");await new Promise(re=>setTimeout(re,p));let R=await this.getCreditsConfirmation(n.ConfirmationID);if(!R.ok)continue;let B=R.data.Status;if(B!==Mi.Pending)return B===Mi.Declined?u("server","CREDITS_CONFIRMATION_DECLINED"):B===Mi.Expired?u("server","CREDITS_CONFIRMATION_EXPIRED"):await o()}}async getCreditsConfirmation(e){return this.ctx.auth.context?await this.ctx.api.store.getCreditsConfirmation({...this.ctx.buildAuthedBaseRequest(),CreditsConfirmationID:e}):a}async getCreditsBalance(){return this.ctx.auth.context?await this.ctx.api.store.getCreditsBalance({...this.ctx.buildAuthedBaseRequest()}):a}async purchaseBatch(e){if(!e||e.length===0)return u("client","purchases is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let 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(Pu,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Pu,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(Iu,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let 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 a;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var vs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?_(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return u("client","Receipt is required.");if(!this.ctx.auth.context)return a;let 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 u("client","productID is required.");if(!this.ctx.auth.context)return a;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 u("client","receipts is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let 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 vu=3,Ry=700,Ts=class{constructor(e){this.ctx=e;$t()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return mi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await ko({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<=vu;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===vu)break;await Ut(Ry);}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===Ki.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!==Ki.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",As=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),_(n)}let i=this.ctx.authedRequest();if(!i)return a;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 u("client","LootboxID is required.");if(t<1)return u("client","Count must be at least 1.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,RelatedEntityID:`lootbox_${e}_${i??"default"}_${G()}`},o=await this.ctx.api.lootbox.open(n);if(o.ok){let p=o.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 o}};var Oo="Reward";function Eo(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var ks=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Reward",{needsServer:()=>!t&&Object.values(e.cache.configSection(Oo)?.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(Oo,e);if(t){let n={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),_(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(Oo,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${G()}`},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(!Eo(e))return u("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${G()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let 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(!Eo(e))return u("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let 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(!Eo(e))return u("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${G()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let 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 ws="Tutorial",Au={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"]},zs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Au,{schema:Xi,apply:i=>this.applyUserTutorialState(i)});let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Tutorial",{needsServer:()=>!t&&Object.keys(e.cache.configSection(ws)?.Flows??{}).length>0,refresh:async()=>{let i=await this.getUserTutorialState();return i.ok&&(t=true),i}});}ctx;async getTutorialDefinitions(e){let t=this.ctx.cache.configSection(ws,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ws,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(Au,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${G()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return u("client","FlowID is required.");if(!t||t.length===0)return u("client","stepIDs is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${G()}`},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 u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${G()}`},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 u("client","FlowID is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:s},o=await t(n);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,s){let n=e?.trim(),o=t?.trim();if(!n)return u("client","FlowID is required.");if(!o)return u("client","StepID is required.");if(!this.ctx.auth.context)return a;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:o};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let h=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,R=await i(p);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(n,o,h,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(ws)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}};var Ms=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return a;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return u("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return u("client","campaignID is required.");if(!t)return u("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return a;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 a;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Ee=zod.z.object({Username:zod.z.string().nullish(),Country:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Premium:zod.z.boolean().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),BoardRank:zod.z.number().nullish()}).passthrough();var Cy={Global:"Global",Announcement:"Announcement",Group:"Group"},wu=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),Sy={None:"None",Language:"Language",Region:"Region"},xy=zod.z.enum(["None","Language","Region"]).catch("None"),by={Anyone:"Anyone",Friends:"Friends"},Dy=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),Py={Reject:"Reject",Mask:"Mask"},Iy=zod.z.enum(["Reject","Mask"]).catch("Reject"),vy={Player:"Player",Publisher:"Publisher",System:"System"},Ty=zod.z.enum(["Player","Publisher","System"]).catch("Player"),Ay={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var ky=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),zu=zod.z.object({Gate:Z.nullish(),Schedule:ye.nullish()}).passthrough(),Mu=zod.z.object({Gate:Z.nullish(),Limits:Ce.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Ou=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),wy=zod.z.object({Availability:K.nullish(),Write:K.nullish(),Retention:K.nullish()}).passthrough(),zy=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:ky.nullish(),Type:wu.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:xy.nullish(),Capacity:zod.z.number().nullish(),Availability:zu.nullish(),Write:Mu.nullish(),Retention:Ou.nullish(),Presets:wy.nullish()}).passthrough(),My=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:Z.nullish(),WhoCanMessage:Dy.nullish(),Limits:Ce.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),Oy=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:Iy.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:Ce.nullish()}).passthrough(),Ey=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),Uy=zod.z.object({Availability:zod.z.record(zod.z.string(),zu).nullish(),Write:zod.z.record(zod.z.string(),Mu).nullish(),Retention:zod.z.record(zod.z.string(),Ou).nullish()}).passthrough(),Eu=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),zy).nullish(),Direct:My.nullish(),Moderation:Oy.nullish(),Polling:Ey.nullish(),Presets:Uy.nullish()}).passthrough(),qy=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),ku=zod.z.object({LastAt:zod.z.string().nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:zod.z.string().nullish(),TotalCount:zod.z.number().nullish(),LastTextHash:zod.z.string().nullish()}).passthrough();zod.z.object({MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish(),Ignored:zod.z.array(zod.z.string()).nullish(),Channels:zod.z.record(zod.z.string(),qy).nullish(),Limits:zod.z.record(zod.z.string(),ku).nullish(),ReportLimits:ku.nullish()}).passthrough();var Uo=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),Os=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:Ee.nullish(),AuthorType:Ty.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),Ly=zod.z.object({ChannelID:zod.z.string().nullish(),RoomID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Type:wu.nullish(),CanWrite:zod.z.boolean().nullish(),WriteBlockedReason:zod.z.string().nullish(),SlowModeSeconds:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Es=zod.z.object({Channels:zod.z.array(Ly).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),By=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Os).nullish(),NextCursor:Uo.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Uu=zod.z.object({Rooms:zod.z.array(By).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),qu=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(Os).nullish(),NextBefore:Uo.nullish()}).passthrough(),Lu=zod.z.object({Message:Os.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),Bu=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ee.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Gy=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ee.nullish(),LastMessage:Os.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),Gu=zod.z.object({Conversations:zod.z.array(Gy).nullish()}).passthrough(),Ri=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:Uo.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),Fu=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.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 _u="Chat",Vu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Us=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Vu,{schema:Es,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(_u,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(_u,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(Vu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let 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)):a}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return a;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 a;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)):a}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):a}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let 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)):a}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):a}async reportMessage(e,t,i,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)):a}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):a}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):a}resetCursors(){this.cursors.clear();}};var Fy={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},_y=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),Vy={Player:"player",Title:"title",Creator:"creator"},Ci={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},Nu=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),Ny=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),qo=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:_y.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(Ny).nullish()}).passthrough(),ju=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(qo).nullish()}).passthrough(),At={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var jy="IDOS_PLATFORM_PUSH_REQUEST",Wy="IDOS_PLATFORM_PUSH_RESPONSE",Ky=12e4;function Wu(r){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let s=false,n=h=>{s||(s=true,window.removeEventListener("message",o),clearTimeout(p),i(h));},o=h=>{let R=h?.data;!R||R.type!==Wy||R.requestId!==t||Pt.includes(h.origin)&&n(R.ok===true);},p=setTimeout(()=>n(false),Ky);window.addEventListener("message",o);for(let h of Pt)try{e.postMessage({type:jy,requestId:t,titleID:r},h);}catch{}})}var qs=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),s=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,i.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return At.Unsupported;if(this.isEmbedded())return At.Embedded;if(!this.isSupported())return At.Unsupported;let t=Notification.permission;return t==="denied"?At.Blocked:t!=="granted"?At.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?At.Subscribed:At.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return u("client","Push notifications are not available for this title.");if(this.isEmbedded())return await Wu(this.ctx.settings.titleID)?_({Where:"portal",Subscription:null}):u("client","The portal did not complete the subscription.");if(!this.isSupported())return u("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return u("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:Qy(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return a;let h=o.toJSON();p.PushEndpoint=h.endpoint,p.PushP256dh=h.keys?.p256dh,p.PushAuth=h.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),_({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return a;if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return u("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):a}async unsubscribeByHash(e){if(!e)return u("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return a;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function Qy(r){let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return i}var Ls=Object.freeze({}),Bs=class{constructor(e){this.ctx=e;}ctx;table={...Ls};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new yi(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?Hy(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Ls},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return a;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:o}=i.data,p=null;if(o){let h=await this.loadTableFromApi(o);h.ok&&(p=h.data.table);}return this.table=n,this.fallbackTable=p,this.currentFallbackLocale=o,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:o,entryCount:Object.keys(n).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):a}reset(){this.table={...Ls},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:G()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return a;t.Locale=e;let i=await this.cache.read(Ku(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let n=s.data,o=n.Locale??Ku(e),p=n.Version??0;if(n.NotModified){let R=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:R?.t??{...Ls},fallbackLocale:n.FallbackLocale??null}}}let h=n.Entries??{};return p>0&&await this.cache.write(o,p,h),{ok:true,data:{locale:o,table:h,fallbackLocale:n.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let s=this.pluralCategory(i),n=`${e}.${s}`;if(this.lookup(n)!==void 0)return n;let o=`${e}.other`;return this.lookup(o)!==void 0?o:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function Hy(r,e){return r.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function Ku(r){return r.trim().replace(/_/g,"-").toLowerCase()}var Lo="Quest",$y={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:r=>{let e=Date.now(),t=null,i=[...Object.values(r.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(r.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let n=Date.parse(s??"");!Number.isNaN(n)&&n>e&&(t===null||n<t)&&(t=n);}return t}},Gs=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let s=e.cache.configSection(Lo)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(s)){let p=Date.parse(n[o]?.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(Lo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Lo,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read($y,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return a;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let 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 a;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let i=e.trim();if(!i)return u("client","QuestID is required.");if(!this.ctx.auth.context)return a;let s=t&&t.trim().length>0?t.trim():void 0,n={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${G()}`},o=await this.ctx.api.quest.claimQuestReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return u("client","quests is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let 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 u("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${G()}`},o=await this.ctx.api.quest.claimMilestoneReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let 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 u("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${G()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(n);if(o.ok){let p=o.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return u("client","MetricID is required.");if(t<0)return u("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},n=await this.ctx.api.quest.addQuestProgress(s);return n.ok&&(this.ctx.data.user.patchQuestProgressUpdates(n.data.Updates),this.ctx.emitter.emit("quest:progressAdded",n.data)),n}};var Qu=zod.z.object({}).passthrough().transform(r=>r);var Jy=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),Zy=zod.z.object({Schedule:zod.z.array(Jy).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),Yy=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:c.nullish(),NextBonusStartUtc:c.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),Xy=zod.z.object({Milestones:K.nullish()}).passthrough(),Bo=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Category:zod.z.string().nullish(),Token:Qt.nullish(),TokenSources:zod.z.array(nt).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),Be).nullish(),Presets:Xy.nullish(),BonusWindow:Zy.nullish()}).passthrough(),eR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:Bo.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),tR=zod.z.object({TimedEventID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Schedule:ye.nullish(),Content:Bo.nullish(),Events:zod.z.array(eR).nullish(),Gate:Z.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),iR=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),sR=zod.z.object({Milestones:zod.z.record(zod.z.string(),di).nullish()}).passthrough(),Fs=zod.z.object({Definitions:zod.z.record(zod.z.string(),tR).nullish(),Settings:iR.nullish(),Presets:sR.nullish()}).passthrough(),nR=zod.z.object({Type:ki,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:Bo.nullish(),Progress:Qu.nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:Be.nullish(),BonusWindow:Yy.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),_s=zod.z.object({ActiveEvents:zod.z.array(nR).nullish()}).passthrough(),Hu=zod.z.object({Tokens:zod.z.record(zod.z.string(),Qu).nullish()}),Go=zod.z.object({Type:ki.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),Fo=zod.z.object({Type:ki.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:M.nullish(),Inventory:Q.nullish()}),rR=zod.z.object({Type:ki.nullish(),LteID:zod.z.string().nullish(),Resources:M.nullish()}),_o=zod.z.array(Te(Fo)),$u=zod.z.array(Te(Go)),Ju=zod.z.array(Te(rR)),at={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Zu="TimedEvent",Yu={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:r=>{let e=null;for(let t of r.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Vs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Yu,{schema:_s,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(Yu,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(Zu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Zu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,s,n,o,p=1){if(!t)return u("client","LteID is required.");if(!i)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let h={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:o,RollMultiplier:p},R=await this.ctx.api.timedEvent.grantTokens(h);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",R.data)),R}async spendTokens(e,t,i){if(!t)return u("client","LteID is required.");if(i<=0)return u("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return a;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 u("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},n=await this.ctx.api.timedEvent.claimMilestone(s);if(n.ok){let o=n.data;this.ctx.data.user.applyResourcesWithDelta(o.Rewards,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,o.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",o);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return a;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return u("client","spends is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let 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 u("client","grants is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let 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 oR=zod.z.object({UserID:zod.z.string(),Score:j.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:c.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:Ee.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),Oi=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:j.nullish(),CycleEndUtc:c.nullish(),TopUsers:zod.z.array(oR).nullish(),BracketID:zod.z.string().nullish()}),aR=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:c.nullish(),ClaimDeadlineUtc:c.nullish(),MilestoneTokensEarned:j.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),Ns=zod.z.object({LeaderboardID:zod.z.string(),CurrentScore:j.nullish(),LastKnownRank:zod.z.number().nullish(),HasUnclaimedReward:zod.z.boolean().nullish(),UnclaimedRewardRank:zod.z.number().nullish(),ScoreEarnedThisCycle:j.nullish(),MilestoneTokensEarned:j.nullish(),TokenEntityID:zod.z.string().nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(aR).nullish()}),js=zod.z.object({LeaderboardID:zod.z.string(),NewScore:j,CycleVersion:zod.z.number()}),Ws=zod.z.object({ServerTimeUtc:c,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ks=zod.z.object({ServerTimeUtc:c,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),Xu=zod.z.array(Te(Oi)),Qs=zod.z.array(Te(Ns)),ec=zod.z.array(Te(Ws)),tc=zod.z.array(Te(Ks)),ic=zod.z.array(Te(js)),lR=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:Te(Ws).nullish(),Milestones:zod.z.array(Te(Ks)).nullish()}),sc=zod.z.array(lR),uR=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:Te(Oi).nullish(),Progress:Te(Ns).nullish()}),nc=zod.z.array(uR),cR=zod.z.string(),rc=zod.z.object({Rank:zod.z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:oo.nullish()}).passthrough(),pR=zod.z.object({RankRewards:zod.z.array(rc).nullish()}).passthrough(),dR=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),hR=zod.z.object({Milestones:K.nullish(),RankRewards:K.nullish()}).passthrough(),mR=zod.z.object({LeaderboardID:zod.z.string(),DisplayName:zod.z.string().nullish(),ScoreDisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsEnabled:zod.z.boolean().nullish(),ScoreAggregation:cR.nullish(),Schedule:ye.nullish(),ChainEvents:zod.z.array(dR).nullish(),Gate:Z.nullish(),TopUsersLimit:zod.z.number().nullish(),MinScoreToEnterTop:zod.z.number().nullish(),BracketSize:zod.z.number().nullish(),LinkedSeasonChainID:zod.z.string().nullish(),RankRewards:zod.z.array(rc).nullish(),Milestones:zod.z.record(zod.z.string(),Be).nullish(),Presets:hR.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(nt).nullish()}).passthrough(),fR=zod.z.object({Milestones:zod.z.record(zod.z.string(),di).nullish(),RankRewards:zod.z.record(zod.z.string(),pR).nullish()}).passthrough(),Hs=zod.z.object({Definitions:zod.z.record(zod.z.string(),mR).nullish(),Presets:fR.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 oc="Leaderboard",ac={key:"leaderboard.progress",login:"LeaderboardProgress",ttlMs:5*6e4,dependsOn:["Leaderboard","EventToken"],invalidateOn:["leaderboard:scoreSubmitted","leaderboard:scoresSubmittedBatch","leaderboard:cycleRewardClaimed","leaderboard:cycleRewardsClaimedBatch","leaderboard:milestoneClaimed","leaderboard:milestonesClaimedBatch","leaderboard:allRewardsClaimedBatch"]},$s=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ac,{schema:Qs,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(oc,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(oc,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return u("client","LeaderboardID is required.");if(t<=0)return u("client","Score must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},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 u("client","LeaderboardID is required.");if(!t)return u("client","SourceType is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},p=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(p.ok){let h=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),h.NewScore,h.NewScore,h.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",h);}return p}async claimCycleReward(e){if(!e)return u("client","LeaderboardID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let 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 u("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},n=await this.ctx.api.leaderboard.claimMilestone(s);if(n.ok){let o=n.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",o);}return n}async getFriendsLeaderboard(e){if(!e)return u("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(u("client","leaderboardIDs is required.")):this.ctx.cache.read(ac,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let 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 u("client","milestones is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let 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 u("client","scores is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let 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 u("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let n=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(n),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of s.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(n,o.Data.MilestoneID),o.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(o.Data.Resources,o.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return u("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return a;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let 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 Vo=zod.z.object({}).passthrough().transform(r=>r),Js=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>pc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:j.nullish(),UserState:Vo.nullish(),NextTier:zod.z.lazy(()=>cc).nullish()}).passthrough(),lc=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),AmountGranted:j.nullish(),NewStatusTokens:j.nullish(),OldTier:zod.z.number().nullish(),NewTier:zod.z.number(),TierUp:zod.z.boolean().nullish()}),No=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),uc=gt(No);var cc=zod.z.object({Tier:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RequiredTokens:j.nullish(),TierReachedReward:H.nullish()}).passthrough(),pc=zod.z.object({SeasonID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:j.nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(cc).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var gR=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ye.nullish(),Seasons:zod.z.array(pc).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:Z.nullish()}).passthrough(),Zs=zod.z.object({Chains:zod.z.record(zod.z.string(),gR).nullish()}).passthrough(),Lt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var dc="Season",hc={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:r=>{let e=Date.parse(r.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Ys=class{constructor(e){this.ctx=e;e.cache.bindLoginView(hc,{schema:Js,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(dc,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(dc,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(hc,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(u("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return u("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return u("client","SeasonChainID is required.");if(t<=0)return u("client","Amount must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${G()}`},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 u("client","SeasonChainID is required.");if(t<=0)return u("client","TierNumber must be positive.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${G()}`},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 u("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return u("client","TierNumbers is required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${G()}`},n=await this.ctx.api.season.claimTierRewardsBatch(s);if(n.ok){let o=n.data;for(let p of o.Items??[]){let h=p.Data?.TierNumber;p.Success&&typeof h=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,h);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return n}};var mc="Premium",Xs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(mc,e);if(t){let n={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",n),_(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(mc,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},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 u("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,RelatedEntityID:`premium_purchase_${e}_${t}`},o=await this.ctx.api.premium.purchaseItemOrCurrency(n);if(o.ok){let p=o.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 o}async purchaseRealMoney(e,t,i,s,n,o,p,h){if(!e||!t)return u("client","PremiumID and TransactionID are required.");if(!s||!n)return u("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return a;let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:o,PackageName:p,AppStoreEnvironment:h,RelatedEntityID:`premium_iap_${e}_${t}`},B=await this.ctx.api.premium.purchaseRealMoney(R);if(B.ok){let re=B.data;re.Premium&&this.ctx.data.user.applyPremium(re.Premium),this.ctx.data.user.applyResourceOperation(re.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",re);}return B}};var en=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:c.nullish()}),jo=zod.z.object({CharacterID:zod.z.string(),Level:zod.z.number().nullish(),Experience:j.nullish(),Power:zod.z.number().nullish(),StatLevels:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Equipment:zod.z.record(zod.z.string(),en).nullish(),UpdatedAt:c.nullish()}).passthrough(),fc=zod.z.object({Characters:zod.z.record(zod.z.string(),jo).nullish()}),Wo=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),Ko=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:M.nullish()}),gc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),en).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),yc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),yR=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Rc=zod.z.object({ServerTimeUtc:c,Characters:zod.z.record(zod.z.string(),yR).nullish(),Inventory:Q.nullish()}),Qo=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:M.nullish()}),Cc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:en.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Sc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:en.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),xc=zod.z.object({ServerTimeUtc:c,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:Q.nullish()}),RR=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:c.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:ce.nullish()}),CR=zod.z.object({CharacterID:zod.z.string(),CharacterOpen:zod.z.boolean().nullish(),DefaultSkinID:zod.z.string().nullish(),WornSkinID:zod.z.string().nullish(),Skins:zod.z.array(RR).nullish()}),bc=zod.z.object({ServerTimeUtc:c,Characters:zod.z.record(zod.z.string(),CR).nullish()}),Dc=gt(Qo),Pc=gt(Ko),Ic=gt(Wo),Ho=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),vc=zod.z.object({StatID:zod.z.string(),TypeID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish(),Weight:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:_e.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:_e.nullish(),RankCurve:_e.nullish(),Requirements:zod.z.array(Ho).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),SR=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Ho).nullish(),AllowedRarityIDs:zod.z.array(zod.z.string()).nullish(),AllowedItemTags:zod.z.array(zod.z.string()).nullish(),MinItemLevel:zod.z.number().nullish(),MaxItemLevel:zod.z.number().nullish()}).passthrough(),Tc=zod.z.object({Slots:zod.z.record(zod.z.string(),SR).nullish()}).passthrough(),Ac=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Lore:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),xR=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),bR=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:ce.nullish()}).passthrough(),DR=zod.z.object({Stats:K.nullish(),Levels:K.nullish(),Equipment:K.nullish()}).passthrough(),kc=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:_e.nullish()}).passthrough(),$o="@skin";function PR(r){return !!r&&r.startsWith("@")}var IR=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),vR=zod.z.object({PriceOptions:ce.nullish(),Schedule:ye.nullish(),Gate:Z.nullish()}).passthrough(),TR=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Ho).nullish()}).passthrough(),AR=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Ac.nullish(),Item:IR.nullish(),Sale:vR.nullish(),Requirements:TR.nullish()}).passthrough(),kR=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),AR).nullish()}).passthrough(),wR=zod.z.object({CharacterID:zod.z.string(),Identity:Ac.nullish(),Classification:xR.nullish(),Unlock:bR.nullish(),Presets:DR.nullish(),Equipment:Tc.nullish(),Stats:zod.z.record(zod.z.string(),vc).nullish(),RankLadder:kc.nullish(),RankStatCurve:_e.nullish(),StatMaxLevelCurve:_e.nullish(),Skins:kR.nullish()}).passthrough(),zR=zod.z.object({Stats:zod.z.record(zod.z.string(),vc).nullish()}).passthrough(),MR=zod.z.object({RankLadder:kc.nullish()}).passthrough(),OR=zod.z.object({Equipment:Tc.nullish()}).passthrough(),ER=zod.z.object({Stats:zod.z.record(zod.z.string(),zR).nullish(),Levels:zod.z.record(zod.z.string(),MR).nullish(),Equipment:zod.z.record(zod.z.string(),OR).nullish()}).passthrough(),tn=zod.z.object({Definitions:zod.z.record(zod.z.string(),wR).nullish(),Presets:ER.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"},UR="SKIN_ALREADY_OWNED";var Jo="Character",sn=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(Jo)?.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(Jo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Jo,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${G()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",n);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return u("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${G()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok){let o=n.data;this.ctx.data.user.patchCharacter(o.CharacterID,p=>{p.StatLevels??={},p.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(p.Power=o.Power),p.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return n}async upgradeCharacterLevel(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${G()}`,...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,o=>{o.Level=n.NewLevel,n.Power!=null&&(o.Power=n.Power),o.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",n);}return s}async equipItems(e,t){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;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 u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;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 a;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${G()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok){let o=n.data;this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),o.Equipped&&o.Equipment&&this.applySkinLocally(o.CharacterID,o.Equipment,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",o);}return n}async equipSkin(e,t,i){if(!e||!t)return u("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},n=await this.ctx.api.character.equipSkin(s);if(n.ok){let o=n.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return n}async unequipSkin(e){if(!e)return u("client","CharacterID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let 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)):a}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,$o,t??null),n.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return u("client","characterIDs is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,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 u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,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 u("client","upgrades is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,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 wc="Match",nn=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,o){let p=this.ctx.auth.context;if(!p)return a;let h={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:o,RelatedEntityID:`pvp_create_${p.userID}_${G()}`},R=await this.ctx.api.match.createMatch(h);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",R.data)),R}async updateMatch(e,t={}){if(!e)return u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},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 u("client","MatchID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,s){let n=this.ctx.auth.context;if(!n)return a;let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${G()}`},p=await this.ctx.api.match.instantBattle(o);if(p.ok){let h=p.data,R=this.ctx.data.config.itemDefinitions;if(h.Resources)this.ctx.data.user.applyResourceOperation(h.Resources,R);else if(h.ResourcesDual){let B=h.ResourcesDual;B.FromUserID===n.userID&&B.FromResult?this.ctx.data.user.applyResourceOperation(B.FromResult,R):B.ToUserID===n.userID&&B.ToResult&&this.ctx.data.user.applyResourceOperation(B.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",h);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let s=this.ctx.authedRequest();if(!s)return a;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 a;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(wc,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(wc,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var zc="Craft",rn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(zc,e);if(t){let n={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),_(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(zc,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n){if(!e)return u("client","CraftID is required.");let o=this.ctx.auth.context;if(!o)return a;let p={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,RelatedEntityID:`craft_${e}_${o.userID}_${G()}`},h=await this.ctx.api.craft.craft(p);return h.ok&&(this.ctx.data.user.applyResourcesWithDelta(h.data.Resources,h.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",h.data)),h}};var Bt=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(Bt),zod.z.record(zod.z.string(),Bt)]));var Gt={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Mc=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Jt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Ei(r){return r!==Jt.Pending&&r!==Jt.Running}var qR={Disabled:"AI_DISABLED",FeatureNotFound:"AI_FEATURE_NOT_FOUND",FeatureDisabled:"AI_FEATURE_DISABLED",WrongAction:"AI_WRONG_ACTION",NotAvailableForPlayer:"AI_NOT_AVAILABLE_FOR_PLAYER",FeatureClosed:"AI_FEATURE_CLOSED",LimitReached:"AI_LIMIT_REACHED",Cooldown:"AI_COOLDOWN",BadInput:"AI_BAD_INPUT",PromptRejected:"AI_PROMPT_REJECTED",Unavailable:"AI_UNAVAILABLE",GenerationFailed:"AI_GENERATION_FAILED",GenerationNotFound:"AI_GENERATION_NOT_FOUND"};function LR(r){return r?/\b(AI_[A-Z_]+)\s*:/.exec(r)?.[1]??null:null}var BR=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),GR=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),on=zod.z.object({GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Mc.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),Bt).nullish(),Assets:zod.z.array(BR).nullish(),Error:GR.nullish(),Charge:M.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reused:zod.z.boolean().nullish(),Reward:M.nullish(),Context:zod.z.record(zod.z.string(),Bt).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish()}),Oc=zod.z.object({Data:zod.z.array(on).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),FR=zod.z.object({Name:zod.z.string().nullish(),Type:zod.z.string().nullish(),Required:zod.z.boolean().nullish(),MaxLength:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish()}).passthrough(),_R=zod.z.object({Modality:Mc.nullish(),Async:zod.z.boolean().nullish(),Limits:Ce.nullish(),PriceOptions:ce.nullish(),Tags:zod.z.array(zod.z.string()).nullish(),HistoryMessages:zod.z.number().nullish(),MaxTokens:zod.z.number().nullish(),AllowImages:zod.z.boolean().nullish(),MaxInputImages:zod.z.number().nullish(),MaxInputImageBytes:zod.z.number().nullish(),AllowedImageTypes:zod.z.array(zod.z.string()).nullish(),MaxImages:zod.z.number().nullish(),AllowEdit:zod.z.boolean().nullish(),AllowReferenceImage:zod.z.boolean().nullish(),MaxPromptChars:zod.z.number().nullish(),LockBehavior:zod.z.boolean().nullish(),ImageSize:zod.z.string().nullish(),VideoSize:zod.z.string().nullish(),VideoSeconds:zod.z.number().nullish(),Voice:zod.z.string().nullish(),AudioFormat:zod.z.string().nullish(),MusicFormat:zod.z.string().nullish(),ThreeDOperation:zod.z.string().nullish(),ThreeDAnimations:zod.z.array(zod.z.string()).nullish(),Reward:H.nullish(),PromptVariables:zod.z.array(FR).nullish(),AllowFreePrompt:zod.z.boolean().nullish()}).passthrough(),Ec=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),_R).nullish()}).passthrough(),Fe={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",VR=/^[A-Za-z0-9_-]{1,128}$/,NR=2e3,jR=5e3,WR=30*6e4;function KR(r,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,r);e?.addEventListener("abort",i,{once:true});})}var an=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),_(t);let i=this.ctx.authedRequest();if(!i)return a;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)):a}async getGeneration(e){if(!e)return u("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):a}isTerminal(e){return Ei(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 u("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??WR),n=Math.max(1,t.intervalMs??NR),o=Math.max(n,t.maxIntervalMs??jR);for(;!Ei(i.Status);){if(t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");if(Date.now()+n>s)return u("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await KR(n,t.signal),t.signal?.aborted)return u("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(i);if(n=Math.min(o,Math.round(n*1.5)),!p.ok){if(p.reason==="connection")continue;return p}i=p.data,Ei(i.Status)||t.onUpdate?.(i);}return _(i)}pollFor(e){switch(e.Modality){case Gt.Text:return this.getText(e.GenerationID);case Gt.Image:return this.getImage(e.GenerationID);case Gt.Audio:return this.getAudio(e.GenerationID);case Gt.Music:return this.getMusic(e.GenerationID);case Gt.Video:return this.getVideo(e.GenerationID);case Gt.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,s){if(!e)return u("client","FeatureKey is required.");let n=i?.relatedEntityID;if(n!==void 0&&!VR.test(n))return u("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:n??G()},p=await s(o);return p.ok&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return u("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.GenerationID=e;let 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===Jt.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===Jt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Jt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var Zo="Collection",ln=class{constructor(e){this.ctx=e;let t=false;e.emitter.on("auth:loggedOut",()=>t=false),e.cache.defineStateRule("Collection",{needsServer:()=>{let i=e.cache.configSection(Zo),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(h=>!!h?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Zo,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Zo,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,s){let n=this.ctx.auth.context;if(!n)return a;let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${G()}`},p=await this.ctx.api.collection.openPack(o);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 a;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${G()}`},o=await this.ctx.api.collection.openCollectionChest(n);return o.ok&&(this.ctx.data.user.applyResourcesWithDelta(o.data.Resources,o.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",o.data)),o}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${G()}`},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 a;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${G()}`},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 u("client","sets is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let 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 a;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${G()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,n,o=false){let p=this.ctx.auth.context;if(!p)return a;let h={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${p.userID}_${s}_${G()}`},R=await this.ctx.api.collection.sendTradeOffer(h);return R.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",R.data)),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${G()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${G()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${G()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return a;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var QR=zod.z.object({}).passthrough().transform(r=>r),HR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},$R={Active:"Active",Left:"Left",Replaced:"Replaced"},JR=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),ZR=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ee.nullish(),BuildObjectsProgress:JR.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),YR=zod.z.object({Index:zod.z.number().nullish(),OwnerUserID:zod.z.string().nullish(),CurrentProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish(),IsCompleted:zod.z.boolean().nullish()}).passthrough(),XR=zod.z.object({Objects:zod.z.array(YR).nullish()}).passthrough(),qc=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CoopChainID:zod.z.string().nullish(),CoopEventID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),Members:zod.z.array(ZR).nullish(),BuildObjectsState:XR.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:zod.z.number().nullish()}).passthrough(),Lc=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>Bc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),eC=zod.z.string(),Yo=zod.z.object({DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Weight:zod.z.number().nullish(),MinProgress:zod.z.number().nullish(),MaxProgress:zod.z.number().nullish()}).passthrough(),tC=zod.z.object({Index:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxProgress:zod.z.number().nullish(),CompletionReward:H.nullish()}).passthrough(),iC=zod.z.object({Objects:zod.z.array(tC).nullish(),PriceOptions:ce.nullish(),SpinnerTable:zod.z.array(Yo).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),Bc=zod.z.object({CoopEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),EventType:eC.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:iC.nullish(),GrandPrize:H.nullish()}).passthrough(),sC=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:ye.nullish(),Events:zod.z.array(Bc).nullish(),Gate:Z.nullish()}).passthrough(),un=zod.z.object({ServerTimeUtc:c.nullish(),UserState:QR.nullish(),ActiveGroup:qc.nullish()}),Xo=zod.z.object({ServerTimeUtc:c.nullish(),Group:qc.nullish(),SecondsRemaining:j.nullish()}),Gc=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Resources:M.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:Yo.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(Yo).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),ea=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Fc=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),cn=zod.z.object({Chains:zod.z.record(zod.z.string(),sC).nullish()}).passthrough(),ht={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var _c="CoopEvent",Vc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},pn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Vc,{schema:un,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(_c,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(_c,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return u("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(Vc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return u("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return u("client","CoopChainID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let 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 u("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,RelatedEntityID:G()},o=await this.ctx.api.coopEvent.spin(n);return o.ok&&(this.ctx.data.user.applyResourceOperation(o.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",o.data)),o}async claimObjectReward(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return u("client","GroupID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var nC={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},rC={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},oC=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:c.nullish(),CompletedAtUtc:c.nullish(),LastExecutedAtUtc:c.nullish(),NextAvailableAtUtc:c.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),aC=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),Nc=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:c.nullish(),ExhaustedAtUtc:c.nullish(),ExpiredAtUtc:c.nullish(),DismissedAtUtc:c.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:c.nullish(),Nodes:zod.z.record(zod.z.string(),oC).nullish(),Tracks:zod.z.record(zod.z.string(),aC).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),lC=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:c.nullish(),ActiveOfferExpiresAtUtc:c.nullish(),ActiveOffer:Nc.nullish(),NextCycleStartsAtUtc:c.nullish(),LastUpdatedUtc:c.nullish(),DismissSkipAvailableAtUtc:c.nullish(),LastDismissedAtUtc:c.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),uC=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),cC=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:c.nullish(),LastActivatedAtUtc:c.nullish(),LastExhaustedAtUtc:c.nullish(),NodeCounts:zod.z.record(zod.z.string(),uC).nullish()}).passthrough(),pC=zod.z.object({Slots:zod.z.record(zod.z.string(),lC).nullish(),OfferHistory:zod.z.record(zod.z.string(),cC).nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),dC={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},hC={Eq:"Eq",Gte:"Gte",Lte:"Lte"},mC=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),dn=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),jc=zod.z.object({Schedule:ye.nullish(),Gate:Z.nullish()}).passthrough(),Wc=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),fC=zod.z.object({Identity:K.nullish(),Availability:K.nullish(),Behaviour:K.nullish()}).passthrough(),gC=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:dn.nullish(),Availability:jc.nullish(),Behaviour:Wc.nullish(),Queue:zod.z.array(mC).nullish(),Presets:fC.nullish()}).passthrough(),yC=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),RC=zod.z.object({RewardedVideo:yC.nullish()}).passthrough(),CC=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),SC=zod.z.object({Identity:K.nullish(),Graph:K.nullish(),Milestones:K.nullish()}).passthrough(),xC=zod.z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish()}).passthrough(),bC=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),DC=zod.z.object({TrackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),StartValue:zod.z.number().nullish(),MinValue:zod.z.number().nullish(),MaxValue:zod.z.number().nullish(),ClampToMin:zod.z.boolean().nullish(),ClampToMax:zod.z.boolean().nullish(),HiddenFromUI:zod.z.boolean().nullish()}).passthrough(),PC=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(CC).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),Kc=zod.z.object({Options:ce.nullish()}).passthrough(),Qc=zod.z.object({Grants:H.nullish(),TrackChanges:zod.z.array(bC).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),IC=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:dn.nullish(),Pricing:Kc.nullish(),Reward:Qc.nullish(),Action:RC.nullish(),UnlockRules:PC.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:Ce.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:xC.nullish()}).passthrough(),Hc=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(IC).nullish(),Tracks:zod.z.array(DC).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),$c=zod.z.object({Milestones:zod.z.record(zod.z.string(),Be).nullish(),ClaimMode:zod.z.string().nullish(),Token:Qt.nullish()}).passthrough(),Jc=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:dn.nullish(),Graph:Hc.nullish(),Milestones:$c.nullish(),Presets:SC.nullish()}).passthrough(),vC=zod.z.object({Identity:zod.z.record(zod.z.string(),dn).nullish(),Availability:zod.z.record(zod.z.string(),jc).nullish(),Behaviour:zod.z.record(zod.z.string(),Wc).nullish(),Graph:zod.z.record(zod.z.string(),Hc).nullish(),Milestones:zod.z.record(zod.z.string(),$c).nullish(),Pricing:zod.z.record(zod.z.string(),Kc).nullish(),Reward:zod.z.record(zod.z.string(),Qc).nullish()}).passthrough(),ta=zod.z.object({Slots:zod.z.record(zod.z.string(),gC).nullish(),Offers:zod.z.record(zod.z.string(),Jc).nullish(),Presets:vC.nullish()}).passthrough(),Zc=zod.z.object({DealOfferDefinitions:ta.nullish()}),Yc=zod.z.object({DealOffers:pC.nullish()}),TC=zod.z.object({EntityID:zod.z.string().nullish(),TotalEarned:zod.z.number().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),ReachedUnclaimedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),AC=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:Jc.nullish(),ActivationState:Nc.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:c.nullish(),Cost:bt.nullish(),Milestone:TC.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),hn=zod.z.object({Slots:zod.z.array(AC).nullish()}),Xc=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),ep=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),tp=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),Resources:M.nullish()}),ip=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),sp=zod.z.object({ServerTimeUtc:c.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Rt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var kC="DealOffer",np={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},mn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(np,{schema:hn,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(kC,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(np,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${G()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,s){if(!e||!t)return u("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return a;let n=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:n??`deal_exec_${e}_${t}_${G()}`},p=await this.ctx.api.dealOffer.executeNode(o);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 u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${G()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return u("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${G()}`},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 u("client","SlotID is required.");if(!this.ctx.auth.context)return a;let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${G()}`},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 rp="Referral",fn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(rp,e);if(t){let n={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",n),_(n)}let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(rp,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=Kt.parseReferralCode(e)?.toUpperCase();if(!t)return u("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},n=await this.ctx.api.referral.activateReferralCode(s);if(n.ok){let o=n.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID,o.QualificationPending),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return n}async claimInviteReward(e){let t=e.trim();if(!t)return u("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},n=await this.ctx.api.referral.claimInviteReward(s);if(n.ok){let o=n.data;o.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(o.RewardID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",o);}return n}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return u("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},n=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(n.ok){let o=n.data;for(let p of o.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return n}async checkQualification(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.referral.checkQualification(e);return t.ok&&t.data.Qualification&&!t.data.QualificationPending&&await this.getUserState(),t}async checkQualificationIfPending(){this.ctx.data.user.state?.Referral?.QualificationPending===true&&await this.checkQualification();}};var wC={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},op=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),zC={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},MC=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),OC={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},EC=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),tt={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},UC={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"},qC=100,LC=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),ap=zod.z.object({FeatureID:zod.z.string().nullish(),Args:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Url:zod.z.string().nullish(),Label:zod.z.string().nullish()}).passthrough(),BC=zod.z.object({Texts:zod.z.record(zod.z.string(),LC).nullish(),Category:op.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:ap.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),GC=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:pe.nullish(),Cost:pe.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:c.nullish(),SenderGate:Z.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),FC=zod.z.object({Type:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxAmountPerGift:zod.z.number().nullish()}).passthrough(),_C=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(FC).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:c.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:pe.nullish(),SenderGate:Z.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),lp=zod.z.object({Enabled:zod.z.boolean().nullish(),Capacity:zod.z.number().nullish(),RewardLetterDays:zod.z.number().nullish(),PlainLetterDays:zod.z.number().nullish(),ClaimedRetentionDays:zod.z.number().nullish(),DefaultLanguage:zod.z.string().nullish(),Templates:zod.z.record(zod.z.string(),BC).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),GC).nullish(),Transfer:_C.nullish()}).passthrough().nullish(),Integrations:zod.z.object({Leaderboard:zod.z.boolean().nullish(),CoopEvent:zod.z.boolean().nullish(),Season:zod.z.boolean().nullish(),Referral:zod.z.boolean().nullish()}).passthrough().nullish()}).passthrough(),VC=zod.z.object({MessageID:zod.z.string(),Source:MC,Category:op,TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:ap.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:H.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:c,ExpiresAt:c.nullish(),ReadAt:c.nullish(),ClaimedAt:c.nullish()}).passthrough(),NC=zod.z.object({MessageID:zod.z.string(),Module:EC,Key:zod.z.string(),TemplateID:zod.z.string().nullish(),Subject:zod.z.string().nullish(),Body:zod.z.string().nullish(),Language:zod.z.string().nullish(),TemplateParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish()}).passthrough(),ia=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),up=zod.z.object({ServerTimeUtc:c.nullish(),Messages:zod.z.array(VC).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(NC).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),gn=zod.z.object({ServerTimeUtc:c.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),sa=zod.z.object({ServerTimeUtc:c.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(ia).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),jC=zod.z.object({MessageID:zod.z.string(),Rewards:pe.nullish()}).passthrough(),yn=zod.z.object({ServerTimeUtc:c.nullish(),Claimed:zod.z.array(jC).default([]),Failed:zod.z.array(ia).default([]),Resources:M.nullish(),Inventory:Q.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),cp=zod.z.object({ServerTimeUtc:c.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(ia).default([]),Resources:M.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish()}).passthrough(),pp=zod.z.object({ServerTimeUtc:c.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),RecipientReceives:pe.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),dp=zod.z.object({ServerTimeUtc:c.nullish(),ResetsAt:c.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:c.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:c.nullish()}).passthrough().nullish()}).passthrough();var na="Mailbox",ra={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},Rn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ra,{schema:gn,apply:t=>this.emitCounters(t)});}ctx;request(e){return this.ctx.auth.context?{...this.ctx.buildAuthedBaseRequest(),...e}:null}emitCounters(e){if(e.UnreadCount==null||e.UnclaimedCount==null)return;let t={UnreadCount:e.UnreadCount,UnclaimedCount:e.UnclaimedCount};this.ctx.cache.put(ra,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(na)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(na,e);if(t)return _(t);let i=this.request();if(!i)return a;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(na,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 a;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(ra,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return a;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return a;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return u("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):a}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return u("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):a}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):a}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return a;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return u("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return u("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return a;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 u("client","RecipientUserID is required.");if(!i?.requestID?.trim())return u("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return a;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):a}};var Cn={RequestAdPermit:"RequestAdPermit",CompleteView:"CompleteView"},oa="idos-app",hp=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),Allowed:zod.z.boolean(),DenyReason:zod.z.string().nullish(),Message:zod.z.string().nullish(),RetryAfterSeconds:zod.z.number().nullish(),RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),AdUnitID:zod.z.string().nullish(),Type:zod.z.string().nullish(),ExpiresAtUtc:zod.z.string().nullish(),CreditsToAward:zod.z.number().nullish(),RequiresServerSideVerification:zod.z.boolean().nullish()}),mp=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),RequestID:zod.z.string().nullish(),Status:zod.z.string(),CreditsAwarded:zod.z.number().nullish(),RetryAfterSeconds:zod.z.number().nullish(),ExpiresAtUtc:zod.z.string().nullish(),AlreadyProcessed:zod.z.boolean().nullish(),GrantedWithoutSsv:zod.z.boolean().nullish(),Resources:M.nullish()});var aa={request:"IDOS_PLATFORM_AD_REQUEST",response:"IDOS_PLATFORM_AD_RESPONSE"},WC=5*6e4;function Sn(){return $t()}async function la(r){let e=await It(aa.request,aa.response,{titleID:r.titleID,userID:r.userID,requestID:r.requestID,placementID:r.placementID,adUnitID:r.adUnitID??null},{answerTimeoutMs:WC});return e.ok?{ok:true,via:e.data.via==="unit"?"unit":"ad"}:{ok:false,error:e.error}}var KC=new Set(["CANCELLED","DECLINED","CLOSED"]),QC=45e3,HC=r=>new Promise(e=>setTimeout(e,r)),xn=class{constructor(e){this.ctx=e;}ctx;get available(){return Sn()}async showRewarded(e){if(!Sn())return {status:"unavailable"};let t=this.ctx.authedRequest();if(!t||!t.UserID)return {status:"unavailable",reason:"NOT_LOGGED_IN"};let i=await this.ctx.api.advertising.requestAdPermit({...t,PlacementID:e});if(!i.ok)return {status:"unavailable",reason:i.error};let s=i.data;if(!s.Allowed)return {status:"denied",reason:s.DenyReason??void 0,retryAfterSeconds:s.RetryAfterSeconds??void 0};if(s.ProviderID!==oa||!s.RequestID)return {status:"unavailable",reason:"NO_WEB_ADS"};let n=await la({titleID:this.ctx.settings.titleID,userID:t.UserID,requestID:s.RequestID,placementID:e,adUnitID:s.AdUnitID});return n.ok?this.awaitReward(s.RequestID,n.via):{status:KC.has(n.error??"")?"cancelled":"unavailable",reason:n.error}}async awaitReward(e,t){let i=Date.now()+QC;for(;;){let s=this.ctx.authedRequest();if(!s)return {status:"pending",via:t};let n=await this.ctx.api.advertising.completeView({...s,RequestID:e});if(n.ok&&n.data.Status==="Granted")return this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),{status:"granted",creditsAwarded:n.data.CreditsAwarded??0,via:t};let o=Math.min(Math.max((n.ok?n.data.RetryAfterSeconds??2:3)*1e3,1e3),5e3);if(Date.now()+o>i)return {status:"pending",via:t,reason:n.ok?void 0:n.error};await HC(o);}}};var $C={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},JC={Title:"Title",Platform:"Platform"},fp=zod.z.object({UserID:zod.z.string(),PublicData:Ee.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),Ui=zod.z.object({Friends:zod.z.array(fp).nullish()}),ZC=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),qi=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:fp.nullish(),Counters:ZC.nullish()}),YC={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},XC={Like:"Like",Favorite:"Favorite"},eS={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},tS={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},iS={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},sS=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),nS=zod.z.object({Id:zod.z.string(),Verb:zod.z.string().nullish(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Count:zod.z.number().nullish(),LastActors:zod.z.array(sS).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),OccurredAt:c.nullish(),OwnerImpact:M.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),gp=zod.z.object({Items:zod.z.array(nS).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:c.nullish()}).passthrough(),Li=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:c.nullish()}).passthrough(),rS=zod.z.object({Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),Followers:zod.z.number().nullish(),Following:zod.z.number().nullish(),Comments:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Posts:zod.z.number().nullish(),Dislikes:zod.z.number().nullish()}).passthrough(),Ft=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:rS.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),yp=zod.z.object({Items:zod.z.array(Ft).nullish()}).passthrough(),ua={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},oS=zod.z.object({UserID:zod.z.string(),PublicData:Ee.nullish(),Mutual:zod.z.boolean().nullish(),Since:c.nullish()}).passthrough(),bn=zod.z.object({Items:zod.z.array(oS).nullish(),...ua}).passthrough(),aS=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:c.nullish()}).passthrough(),Rp=zod.z.object({Items:zod.z.array(aS).nullish(),...ua}).passthrough(),Dn=zod.z.object({CommentID:zod.z.string(),EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),ParentCommentID:zod.z.string().nullish(),AuthorUserID:zod.z.string().nullish(),AuthorPublicData:Ee.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:c.nullish(),EditedAt:c.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Cp=zod.z.object({Items:zod.z.array(Dn).nullish(),...ua,TotalCount:zod.z.number().nullish()}).passthrough(),Sp=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),xp=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),bp=zod.z.object({CommentsEnabled:zod.z.boolean().nullish(),CommentableTypes:zod.z.array(zod.z.string()).nullish(),CommentMaxLength:zod.z.number().nullish(),CommentMaxLinks:zod.z.number().nullish()}).passthrough(),lS="FRIENDS_FROM_PLATFORM",uS={Off:"Off",Default:"Default",Always:"Always"},cS={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Dp=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish(),Recording:zod.z.boolean().nullish()}).passthrough(),Se={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report"};var ca={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},Pn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ca,{schema:Li,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return a;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return u("client","TargetUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return u("client","RequesterUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return u("client","FriendUserID is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return a;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(ca,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(ca,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):a}async getEntityStates(e,t){if(!t?.length)return u("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):a}async addComment(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i?.trim())return u("client","Text is required.");n.Text=i,n.ParentCommentID=s;let o=await this.ctx.api.social.addComment(n);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return u("client","CommentID is required.");if(!t?.trim())return u("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return a;i.CommentID=e,i.Text=t;let 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 u("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let 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 u("client","ReportReason is required.");n.ReportReason=i,n.ReportComment=s;let o=await this.ctx.api.social.report(n);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,s){let n=this.targetRequest(t,i);if("ok"in n)return n;n.ReactionKind=s;let o=await this.ctx.api.social[e](n);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):a}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return u("client","EntityType is required.");if(!t)return u("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):a}};var Pp="TimedBoost";function pS(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var In=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Pp,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),_(t);let i=this.ctx.authedRequest();if(!i)return a;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Pp,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let i=e.trim();if(!pS(i))return u("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return a;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${G()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok){let o=n.data;if(o.ActivatedBoost){let p=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,p);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return n}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var wt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},dS={Client:"Client",Server:"Server",System:"System"},hS=zod.z.enum(["Client","Server","System"]).catch("Client"),mS=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:c.nullish(),Version:zod.z.number().nullish(),LastWriter:hS.nullish(),ExpiresAt:c.nullish()}).passthrough(),vn=zod.z.record(zod.z.string(),mS),Ip=zod.z.object({Version:zod.z.number().nullish(),Private:vn.nullish(),Public:vn.nullish(),ReadOnly:vn.nullish()}),pa=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:vn.nullish()}),da=zod.z.object({ServerTimeUtc:c.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:c.nullish()}),fS=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:c.nullish()}),vp=zod.z.object({ServerTimeUtc:c.nullish(),Results:zod.z.array(fS).nullish()}),Tp=zod.z.object({ServerTimeUtc:c.nullish(),DeletedCount:zod.z.number().nullish()}),Ap=zod.z.object({Results:zod.z.array(pa).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),gS={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},yS=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),RS=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:yS.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Tn=zod.z.object({Keys:zod.z.record(zod.z.string(),RS).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),mt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var CS="UserCustomData";function kp(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}var An=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(CS,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TargetUserID=t;let 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,wt.Private)}async setPublicData(e,t){return this.setData(e,t,wt.Public)}async setData(e,t,i){let s=e.trim();if(!kp(s))return u("client",'KeyID is required and must not contain "." or "$".');if(t==null)return u("client","Value is required.");if(!this.ctx.auth.context)return a;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(i===wt.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(p.ok){let h=p.data;this.ctx.data.user.patchUserCustomDataKey(i,h.KeyID,t,h.Version??0,h.ExpiresAt),this.ctx.emitter.emit(i===wt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",h);}return p}async deleteKey(e,t){let i=e.trim();if(!kp(i))return u("client",'KeyID is required and must not contain "." or "$".');if(t!==wt.Private&&t!==wt.Public)return u("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return a;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 u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let n=s.Bucket??wt.Private,o=e.find(p=>p.Bucket===n&&p.KeyID===s.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(n,s.KeyID,o.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return u("client","At least one item is required.");if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let 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 u("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var SS="TitleCustomDataDefinitions",wp=50;function xS(r){return r.length>0&&!r.includes(".")&&!r.includes("$")}function ha(r){if(r.ExpiresAt==null)return false;let e=Date.parse(r.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function bS(r){let e={};for(let[t,i]of Object.entries(r))ha(i)||(e[t]=i);return e}var kn=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(SS,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return a;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(n=>n.trim()).filter(n=>n.length>0);if(!t.length)return u("client","At least one KeyID is required.");if(t.some(n=>!xS(n)))return u("client",'KeyID must not contain "." or "$".');if(t.length>wp)return u("client",`At most ${wp} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return a;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&&!ha(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!ha(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=bS(this.runtimeCache),e.Runtime=this.runtimeCache):e.Runtime&&(this.runtimeCache=e.Runtime),e.RuntimeVersion!=null&&(this.lastRuntimeVersion=e.RuntimeVersion),this.ctx.emitter.emit("titleCustomData:publicDataLoaded",e);}};var wn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var DS=15,PS="GameLoop",zp="BoardDefinition",zn=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(PS,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(zp,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),_(i);let s=this.ctx.authedRequest();if(!s)return a;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(zp,n.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n.data)),n}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return u("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return a;i.StageLevel=e;let 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 a;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return u("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${G()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let n=s.data,o=ru(new Date,DS);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:o}:n.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:n.SpecialModeOffer.ModeID??void 0,Choices:n.SpecialModeOffer.Choices??void 0}});}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),n.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",n);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${G()}`},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 u("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardLoopRaid(s);if(n.ok){let o=n.data;o.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(o.RaidLayout,o.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(o)),this.ctx.emitter.emit("gameLoop:boardRaided",o);}else await this.getUserBoardState();return n}async boardLoopRaidFast(e){if(!e.length)return u("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${G()}`},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 u("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${G()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let n=s.data;n.StageComplete?this.ctx.data.user.patchBoardState(o=>{o.StageLevel=(o.StageLevel??1)+1,o.Position=0,o.Pending=null,o.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(n.BuiltIndex,o=>{n.NewLevel!=null&&(o.Level=n.NewLevel),o.IsDamaged=false,n.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",n);}return s}async boardSpecialChoose(e,t){if(!e)return u("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return a;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${G()}`},n=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(n.ok){let o=n.data;o.Mode==="Instant"||o.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(h=>{h.ChoiceID=e,h.ChosenMode=o.Mode??"Timed",h.StartedAtUtc=o.StartedAtUtc??null,h.DurationSeconds=o.DurationSeconds??null,h.AdViewsUsed=0;}),o.Operation&&this.ctx.data.user.applyResourcesWithDelta(o.Operation,o.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",o);}return n}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${G()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let n=s.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=n.AdViewsUsed??0,o.AccumulatedMultiplier=n.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",n);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return a;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${G()}`,...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 a;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return a;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return u("client","milestoneID is required.");if(!this.ctx.auth.context)return a;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},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 a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return a;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var Mn=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let n=e.trim();if(!n)return u("client","FunctionName is required.");if(!this.ctx.auth.context)return a;let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(o);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var Mp=zod.z.object({ServerTimeUtc:c,SourceType:ci,SourceID:zod.z.string(),TargetType:ci,TargetID:zod.z.string(),SourceSpent:j,FeeAmount:j,RateApplied:Y,TargetCredited:j}),Op=zod.z.object({ServerTimeUtc:c,SourceType:ci,SourceID:zod.z.string(),TargetType:ci,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),On={Convert:"Convert",CryptoConvert:"CryptoConvert"},IS={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},Ep=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),vS={Automatic:"Automatic",Manual:"Manual"},TS=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),AS=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),kS=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),wS=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),zS=zod.z.object({TargetCurrencyType:ci.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),Up=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:TS.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(zS).nullish()}).passthrough(),qp=zod.z.object({CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough(),MS=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:AS.nullish(),Recharge:kS.nullish(),Conversion:Up.nullish(),Permissions:wS.nullish(),Audit:qp.nullish(),Status:Ep.nullish()}).passthrough(),OS=zod.z.object({NetworkID:zod.z.string(),ContractAddress:zod.z.string().nullish(),Decimals:zod.z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),ES=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),US=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),qS=zod.z.object({Mode:zod.z.string().nullish(),FundingNetworkID:zod.z.string().nullish(),PerPlayerDailyTokens:zod.z.number().nullish(),TitleDailyTokens:zod.z.number().nullish(),RefuseOverCap:zod.z.boolean().nullish()}).passthrough(),ma=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),DisplayDecimals:zod.z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),UsdPriceRefreshMinutes:zod.z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:zod.z.array(OS).nullish(),Limits:ES.nullish(),Permissions:US.nullish(),Conversion:Up.nullish(),Audit:qp.nullish(),Status:Ep.nullish(),ServerGrantPolicy:qS.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),En=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),MS).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),ma).nullish()}).passthrough();var LS={EVM:"EVM",Solana:"Solana"},BS=zod.z.enum(["EVM","Solana"]).catch("EVM"),GS={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},FS=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),_S={Token:"Token",Nft:"Nft"},Lp=zod.z.enum(["Token","Nft"]).catch("Token"),VS={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},NS=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),jS={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},WS=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),KS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},fa=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),Bp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Un(r){let e=r?.trim();return e||Bp.GameTopUp}var QS={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},Gp=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),HS=zod.z.object({ContractAddress:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish()}).passthrough(),Fp=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),$S=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:BS.nullish(),ChainID:zod.z.number().nullish(),ChainTicker:zod.z.string().nullish(),RewardPoolAddress:zod.z.string().nullish(),VaultDepositAddress:zod.z.string().nullish(),ChainConfigVersion:zod.z.number().nullish(),RequiredConfirmations:zod.z.number().nullish(),DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Fp.nullish(),NftCollections:zod.z.array(HS).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),RpcUrl:zod.z.string().nullish(),GasPrice:zod.z.number().nullish(),NftBridgeAddress:zod.z.string().nullish(),SignatureEpoch:zod.z.number().nullish()}).passthrough(),JS=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:Fp.nullish()}).passthrough(),ZS=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),YS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},XS=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),_p=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:XS.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),ex=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish(),ShowOnLoginScreen:zod.z.boolean().nullish()}).passthrough(),tx={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Bi=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),ix=zod.z.object({Mode:Bi.nullish(),TokenGates:zod.z.array(_p).nullish()}).passthrough(),ga=zod.z.object({SystemState:JS.nullish(),Networks:zod.z.record(zod.z.string(),$S).nullish(),AccountSafety:ZS.nullish(),WalletLogin:ex.nullish(),PlayAccess:ix.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),sx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:c.nullish(),LastUsedAt:c.nullish(),LinkType:FS.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),Vp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:Lp.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),nx=zod.z.object({Status:NS.nullish(),Tier:WS.nullish(),VerifiedAt:c.nullish(),ExpiresAt:c.nullish(),RejectedAt:c.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),rx=zod.z.object({CurrencyID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:zod.z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),ox=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:zod.z.record(zod.z.string(),rx).nullish()}).passthrough(),ax=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),lx=zod.z.object({TotalDeposits:zod.z.number().nullish(),TotalWithdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),PerCollection:zod.z.record(zod.z.string(),ax).nullish()}).passthrough(),ux=zod.z.object({Tokens:ox.nullish(),Nfts:lx.nullish()}).passthrough(),ya=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),_t=zod.z.object({Granted:zod.z.boolean(),Mode:Bi.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:c.nullish(),Balances:zod.z.array(ya).nullish()}).passthrough(),cx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:c.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:c.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(ya).nullish()}).passthrough(),px=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),Np=zod.z.object({Mode:Bi.nullish(),TokenGates:zod.z.array(_p).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(px).nullish(),Status:_t.nullish()}).passthrough(),dx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:c.nullish(),LoggedInAt:c.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(ya).nullish()}).passthrough(),hx=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:c.nullish()}).passthrough(),mx=zod.z.object({Version:zod.z.number().nullish(),Stats:ux.nullish(),LinkedWallets:zod.z.record(zod.z.string(),sx).nullish(),LastWalletLogin:dx.nullish(),PlayAccess:cx.nullish(),PendingWithdrawals:zod.z.array(Vp).nullish(),Kyc:nx.nullish(),FirstActivityAt:c.nullish(),LastActivityAt:c.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(hx).nullish()}).passthrough(),fx=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:c}).passthrough(),Si=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),fx).nullish(),PendingAdded:Vp.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),gx=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough().transform(r=>r),yx=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Gp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:fa.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:c.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:c.nullish(),RefundCheckedAt:c.nullish()}).passthrough(),Rx=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:Gp.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:fa.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:c.nullish()}).passthrough(),jp=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Ra=zod.z.object({TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ContractAddress:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(jp).nullish(),Signature:zod.z.string().nullish()}).passthrough(),Ca=zod.z.object({Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),ProgramID:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(jp).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Wp=zod.z.object({Blockchain:ga.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),ma).nullish()}).passthrough(),Kp=zod.z.object({State:mx.nullish(),CryptoBalances:zod.z.record(zod.z.string(),gx).nullish()}).passthrough(),Qp=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:Si.nullish()}).passthrough(),Hp=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),$p=zod.z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:c.nullish(),EvmSignature:Ra.nullish(),SolanaSignature:Ca.nullish(),StateDelta:Si.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),Jp=zod.z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),EvmSignature:Ra.nullish(),SolanaSignature:Ca.nullish(),StateDelta:Si.nullish(),Inventory:Q.nullish()}).passthrough(),Zp=zod.z.object({TokenTransactions:zod.z.array(yx).nullish(),NFTTransactions:zod.z.array(Rx).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Sa=zod.z.object({ServerTimeUtc:c.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:zod.z.string().nullish()}).passthrough(),Yp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:Lp.nullish(),EvmSignature:Ra.nullish(),SolanaSignature:Ca.nullish()}).passthrough(),Xp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:fa.nullish(),StateDelta:Si.nullish()}).passthrough(),He={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",DepositToken:"DepositToken",DepositNFT:"DepositNFT",RequestTokenWithdrawal:"RequestTokenWithdrawal",RequestNFTWithdrawal:"RequestNFTWithdrawal",GetTransactionHistory:"GetTransactionHistory",RetryWithdrawal:"RetryWithdrawal",ConfirmWithdrawal:"ConfirmWithdrawal",DonateToDeveloper:"DonateToDeveloper",DonateToUsersPool:"DonateToUsersPool",GetPlayAccess:"GetPlayAccess",ConfirmPlayAccess:"ConfirmPlayAccess"};var Cx="Blockchain",ed="Blockchain:Definitions",qn=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(ed,e);if(t)return _(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return a;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(Cx,n.data.Blockchain),this.ctx.data.config.patchSection(ed,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 a;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let 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 u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let 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 u("client","CurrencyID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!s)return u("client","Amount is required.");let o=this.ctx.authedRequest();if(!o)return a;o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=s,o.Category=Un(n);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,i,s,n,o,p){if(!e)return u("client","ItemID is required.");if(!t)return u("client","NetworkID is required.");if(!i)return u("client","WalletAddress is required.");if(!s)return u("client","Amount is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.NetworkID=t,h.WalletAddress=i,h.Amount=s,h.Category=Un(n),o!==void 0&&(h.Level=o),p&&(h.ItemInstanceID=p);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(h);return R.ok&&(this.ctx.data.user.applyBlockchainStateDelta(R.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",R.data)),R}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return a;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return u("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return u("client","TitleTransactionID is required.");if(!t)return u("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.TitleTransactionID=e,i.TransactionHash=t;let 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 u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let 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 u("client","NetworkID is required.");if(!t)return u("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return a;i.NetworkID=e,i.TransactionHash=t;let 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 a;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var Sx={Head:"Head",Torso:"Torso",Legs:"Legs"},Ln=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),xx={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},xa=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),id=zod.z.object({AttackTarget:Ln,DefenseTarget:Ln});var bx=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),Dx=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:Ln.nullish(),DefenseZone:Ln.nullish(),HitType:bx.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),Px=zod.z.object({MaxHp:zod.z.number().nullish(),CurrentHp:zod.z.number().nullish(),Damage:zod.z.number().nullish(),AttackSpeed:zod.z.number().nullish(),CritChance:zod.z.number().nullish(),CritMultiplier:zod.z.number().nullish(),Armor:zod.z.number().nullish(),DodgeChance:zod.z.number().nullish()}).passthrough(),Ix=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),td=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:jo.nullish(),BattleStrategy:zod.z.array(id).nullish(),UnstackableItems:zod.z.record(zod.z.string(),Ix).nullish(),Stats:Px.nullish()}).passthrough(),vx=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:pe.nullish(),NetReward:pe.nullish(),BattleLog:zod.z.array(Dx).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:td.nullish(),P2BattleProfile:td.nullish()}).passthrough(),sd=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:c.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(id).nullish(),TargetUserID:zod.z.string().nullish(),Entry:pe.nullish(),CreationCostPaid:pe.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:c.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:c.nullish(),Status:xa.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:c.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:c.nullish()}).passthrough(),nd=zod.z.object({Status:xa,MatchID:zod.z.string(),Entry:pe.nullish(),Resources:M.nullish()}),rd=zod.z.object({Match:sd.nullish()}),od=zod.z.object({MatchID:zod.z.string(),Status:xa,Resources:M.nullish()}),ad=zod.z.object({Battle:vx.nullish(),Resources:M.nullish(),ResourcesDual:Dt.nullish()}),ba=zod.z.object({Matches:zod.z.array(sd).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),Ct={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var Tx=zod.z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var Ax=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),kx=zod.z.object({HealthStatID:zod.z.string().nullish(),DamageStatID:zod.z.string().nullish(),ArmorStatID:zod.z.string().nullish(),AttackSpeedStatID:zod.z.string().nullish(),CritChanceStatID:zod.z.string().nullish(),CritDamageStatID:zod.z.string().nullish(),DodgeStatID:zod.z.string().nullish(),AllMightStatID:zod.z.string().nullish()}).passthrough(),wx=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),zx=zod.z.object({MaxRounds:zod.z.number().nullish(),BlockDamageMultiplier:zod.z.number().nullish(),MinHitDamage:zod.z.number().nullish(),DefaultCritMultiplier:zod.z.number().nullish(),MaxCritChance:zod.z.number().nullish(),MaxDodgeChance:zod.z.number().nullish(),ArmorMode:wx.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),Mx=zod.z.object({Kind:Ax.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:_e.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),Ox=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(Mx).nullish()}).passthrough(),Zt=zod.z.object({Terms:zod.z.array(Ox).nullish()}).passthrough(),Ex=zod.z.object({Health:Zt.nullish(),Damage:Zt.nullish(),Armor:Zt.nullish(),AttackSpeed:Zt.nullish(),CritChance:Zt.nullish(),CritDamage:Zt.nullish(),Dodge:Zt.nullish()}).passthrough(),ld=zod.z.object({StatMapping:kx.nullish(),Combat:zx.nullish(),Formula:Ex.nullish()}).passthrough(),Ux=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),Gi=zod.z.object({Kind:Tx.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:$i.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),ud=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(Gi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),cd=zod.z.object({PriceOptions:ce.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:Ce.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),qx=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:Ux.nullish(),Entry:ud.nullish(),Creation:cd.nullish(),Settings:ld.nullish()}).passthrough(),Lx=zod.z.object({Rules:zod.z.record(zod.z.string(),qx).nullish(),Defaults:ld.nullish(),EntryDefaults:ud.nullish(),CreationDefaults:cd.nullish()}).passthrough(),Da=zod.z.object({InstantBattle:Lx.nullish()}).passthrough(),pd=Da;var Bx={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Pa=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),Gx={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Ia=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),Fx={Burn:"Burn",Ledger:"Ledger"},_x=zod.z.enum(["Burn","Ledger"]).catch("Burn"),Gn={Item:"Item",VirtualCurrency:"VirtualCurrency"},va=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),Vx=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish()}).passthrough(),Fn=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),AllowCryptoCurrency:zod.z.boolean().nullish(),Allowed:zod.z.array(Gi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Ta=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish(),Sink:_x.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),Vx).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),Nx=zod.z.object({AllowedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedCatalogIDs:zod.z.array(zod.z.string()).nullish(),DeniedItemIDs:zod.z.array(zod.z.string()).nullish(),AllowUnstackableWithState:zod.z.boolean().nullish(),AllowedCurrencyIDs:zod.z.array(zod.z.string()).nullish(),DeniedCurrencyIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),jx=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:Ce.nullish(),BuyLimits:Ce.nullish(),ListingFeeOptions:ce.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),Wx=zod.z.object({Enabled:zod.z.boolean().nullish(),MinDurationHours:zod.z.number().nullish(),MaxDurationHours:zod.z.number().nullish(),AntiSnipeWindowSeconds:zod.z.number().nullish(),AntiSnipeExtensionSeconds:zod.z.number().nullish(),MaxAntiSnipeExtensions:zod.z.number().nullish(),MinBidStepPercent:zod.z.number().nullish(),MinBidStepAbsolute:j.nullish(),BidLimits:Ce.nullish()}).passthrough(),Kx=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:Ce.nullish(),FillLimits:Ce.nullish()}).passthrough(),Qx=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:Ce.nullish()}).passthrough(),Hx=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),Aa=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:ye.nullish(),PricePolicy:Fn.nullish(),Commission:Ta.nullish(),Tradability:Nx.nullish(),Listings:jx.nullish(),Auctions:Wx.nullish(),BuyOrders:Kx.nullish(),DirectTrades:Qx.nullish(),Matching:Hx.nullish()}).passthrough(),dd=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:j.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:c.nullish()}).passthrough(),$x=zod.z.object({BidAxisType:pi.nullish(),BidCurrencyID:zod.z.string().nullish(),BidCatalogID:zod.z.string().nullish(),BidItemID:zod.z.string().nullish(),StartingBid:j.nullish(),CurrentBid:j.nullish(),CurrentBidderID:zod.z.string().nullish(),BidCount:zod.z.number().nullish(),ExtensionCount:zod.z.number().nullish(),PendingRefunds:zod.z.array(dd).nullish()}).passthrough(),Bn=zod.z.object({LastAt:c.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),Jx=zod.z.object({Create:Bn.nullish(),Buy:Bn.nullish(),Sell:Bn.nullish(),Bid:Bn.nullish()}).passthrough(),Zx=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),Yx=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:Zx.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(r=>r),zt=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Pa.nullish(),Status:Ia.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:Ee.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:va.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),GoodsInstances:zod.z.array(Yx).nullish(),Price:pe.nullish(),Auction:$x.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),Xx=zod.z.object({GoodsType:va.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(Pa,j).nullish()}).passthrough(),hd=zod.z.object({Definitions:Aa.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),ka=zod.z.object({Offers:zod.z.array(zt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),md=zod.z.object({Groups:zod.z.array(Xx).nullish()}).passthrough(),fd=zod.z.object({Offer:zt.nullish()}).passthrough(),lt=zod.z.object({OfferID:zod.z.string().nullish(),Status:Ia.nullish(),Settlement:Dt.nullish(),Resources:M.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Fi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:zt.nullish(),Resources:M.nullish(),Matched:zod.z.boolean().nullish(),Settlement:lt.nullish()}).passthrough(),gd=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:j.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish()}).passthrough(),_n=zod.z.object({MyOffers:zod.z.array(zt).nullish(),MyBids:zod.z.array(zt).nullish(),MyBuyOrders:zod.z.array(zt).nullish(),IncomingTrades:zod.z.array(zt).nullish(),OutgoingTrades:zod.z.array(zt).nullish(),Claimables:zod.z.array(zt).nullish(),DrainedRefunds:zod.z.array(dd).nullish(),Limits:Jx.nullish()}).passthrough(),eb=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Pa.nullish(),FinalStatus:Ia.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:va.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),PricePaid:pe.nullish(),CommissionTaken:pe.nullish(),CompletedAt:c.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),yd=zod.z.object({Entries:zod.z.array(eb).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),ze={GetDefinitions:"GetDefinitions",GetGroupedOffers:"GetGroupedOffers",GetOffersByItem:"GetOffersByItem",GetOffer:"GetOffer",GetBuyOrders:"GetBuyOrders",GetMyState:"GetMyState",GetHistory:"GetHistory",CreateListing:"CreateListing",CancelListing:"CancelListing",Buy:"Buy",MarketBuy:"MarketBuy",MarketSell:"MarketSell",CreateAuction:"CreateAuction",PlaceBid:"PlaceBid",ClaimAuction:"ClaimAuction",CreateBuyOrder:"CreateBuyOrder",CancelBuyOrder:"CancelBuyOrder",FillBuyOrder:"FillBuyOrder",CreateDirectTrade:"CreateDirectTrade",RespondDirectTrade:"RespondDirectTrade",CancelDirectTrade:"CancelDirectTrade",ClaimBack:"ClaimBack"};var tb="Marketplace",Rd={key:"marketplace.myState",login:"MarketplaceMyState",ttlMs:6e4,dependsOn:["Marketplace"],invalidateOn:["marketplace:listingCreated","marketplace:listingCancelled","marketplace:bought","marketplace:marketBought","marketplace:marketSold","marketplace:auctionCreated","marketplace:bidPlaced","marketplace:auctionClaimed","marketplace:buyOrderCreated","marketplace:buyOrderCancelled","marketplace:buyOrderFilled","marketplace:directTradeCreated","marketplace:directTradeResponded","marketplace:directTradeCancelled","marketplace:claimedBack"]},Vn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Rd,{schema:_n,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(tb,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,s=20){if(!e)return u("client","ItemID is required.");let n=this.ctx.authedRequest();if(!n)return a;n.ItemID=e,n.OfferTypeFilter=t,n.ContinuationToken=i,n.PageSize=s;let o=await this.ctx.api.marketplace.getOffersByItem(n);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let s=this.ctx.authedRequest();if(!s)return a;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(Rd,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return a;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let s=this.ctx.authedRequest();if(!s)return a;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let n=await this.ctx.api.marketplace.getHistory(s);return n.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",n.data),n}async createListing(e,t,i,s,n,o,p){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!s)return u("client","PriceBundle is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.PriceBundle=s,h.DurationHours=n,h.ItemInstanceIDs=o,h.SelectedOptionID=p;let R=await this.ctx.api.marketplace.createListing(h);return this.applyCreateOfferResult(R,"marketplace:listingCreated"),R}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return a;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return u("client","GoodsAmount must be positive.");if(!t)return u("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return a;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(s);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,s,n,o,p={}){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");let h=this.ctx.authedRequest();if(!h)return a;h.ItemID=e,h.CatalogID=t,h.GoodsAmount=i,h.BidAxisType=s,h.BidCurrencyID=p.bidCurrencyID,h.BidCatalogID=p.bidCatalogID,h.BidItemID=p.bidItemID,h.StartingBid=n,h.DurationHours=o,h.ItemInstanceIDs=p.itemInstanceIDs,h.SelectedOptionID=p.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(h);return this.applyCreateOfferResult(R,"marketplace:auctionCreated"),R}async placeBid(e,t){if(!e)return u("client","OfferID is required.");if(!t||t<=0)return u("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.BidAmount=t;let 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 u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,s,n){if(!e)return u("client","ItemID is required.");if(!t)return u("client","CatalogID is required.");if(!s)return u("client","PriceBundle is required.");let o=this.ctx.authedRequest();if(!o)return a;o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=s,o.DurationHours=n;let p=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return u("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,s,n){if(!e)return u("client","TargetUserID is required.");if(!t)return u("client","CatalogID is required.");if(!i)return u("client","ItemID is required.");let o=this.ctx.authedRequest();if(!o)return a;o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=s,o.RequestedBundle=n;let p=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return u("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.OfferID=e,i.Accept=t;let 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 a;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return u("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return a;s.OfferID=e;let n=await t(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,n.data)),n}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=Gn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=Gn.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):u("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var Nn=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return u("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode,i.Voice=t.voice;let 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 u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;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 u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;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 u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return a;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 u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.TargetUserID=t;let 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 a;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 u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return u("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return a;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return u("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.LastSeq=t;let 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 u("client","RoomID is required.");if(!t)return u("client","TargetUserID is required.");if(!i)return u("client","SignalKind is required.");let n=this.ctx.authedRequest();if(!n)return a;n.RoomID=e,n.TargetUserID=t,n.SignalKind=i,n.Payload=s;let o=await this.ctx.api.multiplayer.sendSignal(n);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return u("client","RoomID is required.");if(!t)return u("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return a;i.RoomID=e,i.ChatText=t;let 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 u("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return a;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 Cd=" (if the network is fine, the storage bucket has no CORS rule for this origin)",jn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return a;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.ParentContentID=e.parentContentID,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):a}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return u("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):a}async getCreatorProfile(e,t,i){if(!e)return u("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):a}async publish(e){if(!e.files||e.files.length===0)return u("client","At least one file is required.");let t=new Map,i=e.files.map((h,R)=>{if("sourceAssetUrl"in h)return {Role:h.role,ContentType:h.contentType,SourceAssetUrl:h.sourceAssetUrl};let B=Sd(h.data,h.contentType);return t.set(R,B),{Role:h.role,ContentType:h.contentType,Size:B.size}}),s=e.thumbnail?Sd(e.thumbnail.data,e.thumbnail.contentType):null,n=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,ParentContentID:e.contentID?void 0:e.parentContentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!n.ok)return n;let o=n.data.Uploads??[];for(let h=0;h<o.length;h++){let R=o[h];if(!R||R.ServerCopy||!R.Url)continue;let B=t.get(h);if(!B)return u("client",`No bytes for file #${h+1}.`);let re=await this.putBytes(R.Url,B,R.ContentType??B.type);if(!re.ok)return re}let p=n.data.ThumbnailUpload;if(p?.Url&&s){let h=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!h.ok)return h}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}):a}async publishUploaded(e){if(!e.ContentID)return u("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return a;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&(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)):a}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let 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 u("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 u("connection",`Download failed: ${n instanceof Error?n.message:String(n)}${Cd}`)}return _({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):a}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):a}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?_(!0):u("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return u("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${Cd}`)}}contentRequest(e){if(!e)return u("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):a}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function Sd(r,e){return r instanceof Blob?r:typeof r=="string"?new Blob([new TextEncoder().encode(r)],{type:e}):r instanceof Uint8Array?new Blob([r.slice().buffer],{type:e}):new Blob([r],{type:e})}var ib={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},sb=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),nb={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},xd=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),rb={Everyone:"Everyone",Owner:"Owner",Server:"Server"},bd=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),ob={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},ab=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),lb={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},ub=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),cb={Count:"Count",Sum:"Sum"},pb=zod.z.enum(["Count","Sum"]).catch("Count"),db={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},hb=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),mb={Strict:"Strict",Loose:"Loose"},fb=zod.z.enum(["Strict","Loose"]).catch("Strict"),gb=zod.z.object({Kind:ub,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),yb=zod.z.object({Type:xd,ItemType:xd.nullish(),Ref:gb.nullish(),Required:zod.z.boolean().optional(),Default:zod.z.string().nullish(),Min:zod.z.number().nullish(),Max:zod.z.number().nullish(),MaxLength:zod.z.number().nullish(),MaxItems:zod.z.number().nullish(),Enum:zod.z.array(zod.z.string()).nullish(),Unique:zod.z.boolean().optional(),UniqueIgnoreCase:zod.z.boolean().optional(),Indexed:zod.z.boolean().optional(),Visibility:bd.optional(),ClientWritable:zod.z.boolean().nullish(),Immutable:zod.z.boolean().optional(),Description:zod.z.string().nullish(),AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxFileBytes:zod.z.number().nullish()}),Rb=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Wn=zod.z.object({Mode:ab,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),Cb=zod.z.object({Read:zod.z.array(Wn).nullish(),Create:zod.z.array(Wn).nullish(),Update:zod.z.array(Wn).nullish(),Delete:zod.z.array(Wn).nullish()}),wa=zod.z.object({Cost:pe.nullish(),Grant:pe.nullish()}),Sb=zod.z.object({ID:zod.z.string(),SortKey:zod.z.string(),PartitionField:zod.z.string().nullish(),PageSize:zod.z.number().optional(),MaxItems:zod.z.number().optional(),PublishItems:zod.z.boolean().optional()}),xb=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Namespace:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Enabled:zod.z.boolean().nullish(),Kind:sb,Mode:fb.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),yb).nullish(),SortKeys:zod.z.array(Rb).nullish(),Access:Cb.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:hb.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:pb,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:bd.optional()})).nullish(),Economy:zod.z.object({OnCreate:wa.nullish(),OnUpdate:wa.nullish(),OnDelete:wa.nullish()}).nullish(),WriteGate:Z.nullish(),PublicViews:zod.z.array(Sb).nullish(),AnonymousSearch:zod.z.boolean().nullish(),Integrations:zod.z.object({QuestMetricOnCreate:zod.z.string().nullish(),QuestMetricOnUpdate:zod.z.string().nullish(),QuestMetricOnDelete:zod.z.string().nullish(),AnalyticsEventOnCreate:zod.z.string().nullish(),AnalyticsEventOnUpdate:zod.z.string().nullish(),AnalyticsEventOnDelete:zod.z.string().nullish(),TriggerOnCreate:zod.z.string().nullish(),TriggerOnUpdate:zod.z.string().nullish(),TriggerOnDelete:zod.z.string().nullish()}).nullish(),Moderation:zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish()}).nullish()}),Dd=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),xb).default({})}),bb=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),Pd=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),xi=zod.z.object({Collection:zod.z.string(),ItemID:zod.z.string(),OwnerUserID:zod.z.string().nullish(),Data:zod.z.record(zod.z.string(),zod.z.unknown()).default({}),Version:zod.z.number(),CreatedAt:zod.z.string(),UpdatedAt:zod.z.string(),ExpireAt:zod.z.string().nullish(),Expanded:zod.z.record(zod.z.string(),zod.z.unknown()).nullish(),Files:zod.z.record(zod.z.string(),bb).nullish()}),za=zod.z.object({Item:xi}),Id=zod.z.object({Items:zod.z.array(xi).default([]),Missing:zod.z.array(zod.z.string()).default([])}),Ma=zod.z.object({Items:zod.z.array(xi).default([]),NextCursor:zod.z.string().nullish()}),vd=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),Oa=zod.z.object({Item:xi,AlreadyExists:zod.z.boolean().optional(),Economy:M.nullish()}),Td=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:M.nullish()}),Ad=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),kd=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:xi.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),wd=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),zd=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),Md=zod.z.object({Version:zod.z.string(),Collection:zod.z.string(),View:zod.z.string(),SortKey:zod.z.string().nullish(),PageSize:zod.z.number(),UpdatedAt:zod.z.string(),BaseUrl:zod.z.string(),Partitions:zod.z.record(zod.z.string(),zod.z.object({Segment:zod.z.string(),Pages:zod.z.number(),Total:zod.z.number()})).default({})}),Od=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(xi).default([])}),Db={GetDefinitions:"GetDefinitions",Get:"Get",GetMany:"GetMany",Query:"Query",Count:"Count",Create:"Create",Update:"Update",Delete:"Delete",Batch:"Batch",GetCounter:"GetCounter",GetMyRoles:"GetMyRoles",BeginFileUpload:"BeginFileUpload"};var Pb=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,qd=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,Ua=100,Ed=25,Ud=100;function Ib(r,e,t){return {Field:r,Op:e,Value:t}}var Kn=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(a)}get(e,t,i={}){let s=it(e)??_i(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=it(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(o=>qd.test(o)))];return n.length?n.length>Ud?Promise.resolve(u("client",`At most ${Ud} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:n,Expand:i.expand})):Promise.resolve(u("client","At least one valid item id is required."))}query(e,t={},i={}){let s=it(e)??Ea(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.query({...n,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),n=[],o=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:o,Limit:t.Limit??Ua},i);if(!p.ok)return p;if(n.push(...p.data.Items),o=p.data.NextCursor??void 0,!o||n.length>=s)return _(n.slice(0,s))}}count(e,t={}){let i=it(e)??Ea(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=it(e)??(i.itemID?_i(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=it(e)??_i(t);return n?Promise.resolve(n):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=it(e)??_i(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(u("client","Operations are empty."));if(e.length>Ed)return Promise.resolve(u("client",`At most ${Ed} operations per batch.`));let t=e.map(i=>it(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=it(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=it(e);return n?Promise.resolve(n):t?s>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(u("client","File size must be positive.")):Promise.resolve(u("client","Field is required."))}async uploadFile(e,t,i,s={}){let n=s.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,n,i.size);if(!o.ok)return o;let p=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||n);return p.ok?o:p}async getPublicViews(e){let t=it(e);if(t)return t;let i=this.publicViews.get(e);if(i)return _(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 u("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(n,Md);if(!o.ok)return o;let p=o.data.Partitions[i.partition??""],h=Math.max(1,i.page??1);if(!p||h>p.Pages)return _({pointer:o.data,page:{Page:h,HasMore:false,Items:[]}});let R=await this.fetchJson(`${o.data.BaseUrl}${p.Segment}/page-${h}.json`,Od);return R.ok?_({pointer:o.data,page:R.data}):R}getPublic(e,t){let i=it(e)??_i(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=it(e)??Ea(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(a)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?_(!0):u("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return u("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 u("connection","Internet Connection Error")}if(!i.ok)return u("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return u("server","CDN answer is not JSON.")}let n=t.safeParse(s);return n.success?_(n.data):u("server","CDN answer has an unexpected shape.")}};function it(r){return Pb.test(r??"")?null:u("client",`Collection id '${r}' is invalid (letters, digits, '_', '-', ':').`)}function _i(r){return qd.test(r??"")?null:u("client",`Item id '${r}' is invalid.`)}function Ea(r){return r.Limit!=null&&(r.Limit<1||r.Limit>Ua)?u("client",`Limit must be 1..${Ua}.`):(r.Where?.length??0)>8?u("client","At most 8 filters per query."):null}var qa={Open:"Open",Declared:"Declared"},vb=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish(),Highlight:zod.z.number().nullish()}).passthrough(),Tb=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),Ld=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),vb).nullish(),Dimensions:zod.z.array(Tb).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),Vt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},St={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Qn=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Ab={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},kb=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),Bd=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(kb).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),La={LogEvents:"LogEvents"};function Gd(r,e=0){let t=r??"",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 o=/\bWindows NT (\d+\.\d+)/.exec(t);return o?{osName:"Windows",osVersion:o[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function Fd(r){let e=typeof navigator>"u"?void 0:navigator,t=Gd(e?.userAgent??"",e?.maxTouchPoints??0),i={};r.appVersion&&(i.AppVersion=r.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let s=r.locale||e?.language;return s&&(i.Language=s),i}var wb=25,zb=3e4,_d=1800*1e3,Vd=500,Mb=5,Ob=1e3,Eb=3600*1e3,Nd="idos_analytics_queue",Ba="idos_analytics_pending",Ga="idos_analytics_opt_out",jd="idos_analytics_first_open",Wd="idos_analytics_last_activity",Kd="idos_analytics_last_context",Qd="idos_analytics_owner",Hn=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!Qn.test(e)?u("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Ub(e)?u("client",`Event name "${e}" uses a reserved prefix (${St.reservedPrefixes.join(", ")}).`):(this.ctx.emitter.emit("analytics:logged",{name:e}),this.enqueue(e,t,i,false))}logScreenView(e,t){if(!e)return u("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Vt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return _(null);if(this.config()?.Enabled===false)return this.clear(),_(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return _(null);this.pending={BatchID:G(),Events:this.queue.splice(0,St.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=Mb)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(Ga);return}this.write(Ga,"1"),this.clear();}get isEnabled(){return this.read(Ga)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(Qd);e&&t&&t!==e&&this.clear(),e&&this.write(Qd,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},zb),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(Wd)??"0");this.read(jd)||(this.write(jd,new Date().toISOString()),this.enqueue(Vt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(Kd);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Vt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Vt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(Kd,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=_d)&&this.enqueue(Vt.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>=_d&&this.enqueue(Vt.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 _(null);let n=this.config();if(n?.Enabled===false)return _(null);if(s&&n?.AutomaticEvents===false)return _(null);if(n?.Events?.[e]?.Blocked)return u("client",`Event "${e}" is blocked by the title.`);if(!s&&n?.EventNaming?.toLowerCase()===qa.Declared.toLowerCase()&&!n.Events?.[e])return u("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return u("client","value must be a finite number.");let o=qb(t);if(o.error)return u("client",o.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(p.Params=o.params),i!==void 0&&(p.Value=i),this.queue.push(p),this.queue.length>Vd&&this.queue.splice(0,this.queue.length-Vd),this.touch(),this.persist(),this.started&&this.queue.length>=wb&&this.flush(),_(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},Ob));}dropStale(){let e=Date.now()-(St.maxEventAgeMs-Eb);this.queue=this.queue.filter(t=>{let i=t.ClientTimeUtc?Date.parse(t.ClientTimeUtc):NaN;return !Number.isFinite(i)||i>=e});}clear(){this.restore(),this.queue=[],this.pending=null,this.persist();}config(){return this.ctx.data.config.titlePublicConfiguration?.Analytics}clientContext(){return this.context??=Fd({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(Nd);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(Ba);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(Nd,this.queue),this.pending?this.writeJson(Ba,this.pending):this.remove(Ba);}touch(){this.write(Wd,String(Date.now()));}key(e){return `${e}:${this.ctx.settings.titleID}`}read(e){try{return this.ctx.platform.storage.getString(this.key(e))}catch{return null}}write(e,t){try{this.ctx.platform.storage.setString(this.key(e),t);}catch{}}remove(e){try{this.ctx.platform.storage.remove(this.key(e));}catch{}}readJson(e){let t=this.read(e);if(!t)return null;try{return JSON.parse(t)}catch{return null}}writeJson(e,t){this.write(e,JSON.stringify(t));}};function Ub(r){let e=r.toLowerCase();return St.reservedPrefixes.some(t=>e.startsWith(t))}function qb(r){if(!r)return {};let e=Object.keys(r);if(e.length===0)return {};if(e.length>St.maxParams)return {error:`Too many parameters: ${e.length}, max ${St.maxParams}.`};let t={};for(let i of e){if(!Qn.test(i))return {error:`Invalid parameter name "${i}".`};let s=r[i];typeof s=="string"?t[i]=s.length>St.maxStringValueLength?s.slice(0,St.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var Lb="idos_experiments",$n=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return a;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let n=Number(s);return s.trim()!==""&&Number.isFinite(n)?n:i}if(typeof i=="boolean"){let n=s.trim().toLowerCase();return n==="true"||n==="1"?true:n==="false"||n==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,n]of t){let o=this.views.get(s);(!o||o.VariantID!==n.VariantID||o.Status!==n.Status)&&i.push(n);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.platform.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.platform.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${Lb}:${this.ctx.settings.titleID}`}};function Nt(r,e,t,i){let n=`api/v2/${r&&r.length>0?r:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var L=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Nt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,s){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...s,ticket:t.ClientSessionTicket})}};var Jn=class extends L{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(La.LogEvents,e,Bd,{silent:true})}};var Bb=zod.z.object({VariantID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Weight:zod.z.number().nullish(),IsControl:zod.z.boolean().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Gb={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Fb=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),_b=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:ye.nullish(),Gate:Z.nullish(),Variants:zod.z.array(Bb).nullish(),Salt:zod.z.string().nullish(),LayerID:zod.z.string().nullish(),StickyAssignment:zod.z.boolean().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Goals:zod.z.array(Fb).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),Hd=zod.z.object({Experiments:zod.z.record(zod.z.string(),_b).nullish()}).passthrough(),Vb={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Nb=zod.z.object({ExperimentID:zod.z.string().nullish(),VariantID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$d=zod.z.object({Experiments:zod.z.array(Nb).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),Fa={GetExperiments:"GetExperiments"};var Zn=class extends L{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(Fa.GetExperiments,e,$d)}};var Jd=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:c.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:c,PlayAccess:_t.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:c.nullish()}),Zd=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:c,RefreshToken:zod.z.string(),RefreshTokenExpiration:c.nullish(),PlayAccess:_t.nullish()}),jb=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Yd=zod.z.object({Google:zod.z.object({Enabled:zod.z.boolean().nullish(),WebClientID:zod.z.string().nullish(),PlatformFallback:zod.z.boolean().nullish(),AndroidClientID:zod.z.string().nullish(),IosClientID:zod.z.string().nullish(),DesktopClientID:zod.z.string().nullish()}).passthrough().nullish(),Apple:zod.z.object({Enabled:zod.z.boolean().nullish(),BundleID:zod.z.string().nullish(),ServiceID:zod.z.string().nullish()}).passthrough().nullish(),PlayAccessMode:Bi.nullish(),WalletLoginNetworks:zod.z.array(zod.z.object({NetworkID:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough()).nullish(),ShowWalletLogin:zod.z.boolean().nullish(),NativeSso:jb.nullish()}).passthrough(),Xd=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:c.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:_t.nullish()}).passthrough(),eh=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:c.nullish(),PlayAccess:_t.nullish()}).passthrough(),th=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),qe=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:c.nullish()}),ih=zod.z.object({Message:zod.z.string(),ExpiresAt:c}),Ue={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",ResolvePlatformGameSession:"ResolvePlatformGameSession",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var Yn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Nt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,Jd,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ue.RefreshSession),e,Zd,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ue.GetAuthOptions),e,Yd,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Nt(this.ctx.settings.titleID,"Authentication",Ue.LinkWallet,e.UserID??""),e,Xd,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Nt(this.ctx.settings.titleID,"Authentication",Ue.UnlinkWallet,e.UserID??""),e,eh,{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)}resolvePlatformGameSession(e){return this.login(Ue.ResolvePlatformGameSession,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,qe,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ue.RequestWalletChallenge),e,ih,{ticket:null})}loginWithWallet(e){return this.login(Ue.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ue.ForgotPassword),e,qe,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ue.ResetPassword),e,qe,{ticket:null})}};var Wb={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},sh=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Kb=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),nh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),Kb).nullish(),MissingKeyMode:sh.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),Qb=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),rh=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:Qb.nullish()}).passthrough(),Xn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Hb=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),oh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:sh.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(Hb).nullish()}).passthrough(),ah=zod.z.object({RequestedLocale:zod.z.string().nullish(),Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),NotModified:zod.z.boolean().nullish(),Entries:zod.z.record(zod.z.string(),zod.z.string()).nullish(),FallbackLocale:zod.z.string().nullish(),FallbackVersion:zod.z.number().nullish()}).passthrough();var _a=zod.z.object({TitleConfigVersion:zod.z.string().nullish(),TitleConfigUrl:zod.z.string().nullish(),User:zod.z.unknown().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish(),Localization:rh.nullish(),Views:zod.z.array(zod.z.object({Name:zod.z.string(),Key:zod.z.string().nullish(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(r=>r),lh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(r=>r),uh=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),User:zod.z.unknown().nullish()}).passthrough().transform(r=>r),ch=zod.z.object({}).passthrough().transform(r=>r),ph=zod.z.object({}).passthrough().transform(r=>r),dh=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:c.nullish(),LastActiveAt:c.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),hh=zod.z.object({Username:zod.z.string()}),ut={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var er=class extends L{constructor(e){super(e,"User");}getClientState(e){return this.send(ut.GetClientState,e,_a)}getClientStateExcept(e){return this.send(ut.GetClientStateExcept,e,_a)}getStateVersions(e){return this.send(ut.GetStateVersions,e,lh)}getUserState(e){return this.send(ut.GetUserState,e,uh)}getInventory(e){return this.send(ut.GetInventory,e,ch)}getEventTokens(e){return this.send(ut.GetEventTokens,e,ph)}getUsageTime(e){return this.send(ut.GetUsageTime,e,dh)}addUsageTime(e){return this.send(ut.AddUsageTime,e,qe,{silent:true})}deleteUserAccount(e){return this.send(ut.DeleteUserAccount,e,qe)}changeUsername(e){return this.send(ut.ChangeUsername,e,hh)}};var tr=class extends L{constructor(e){super(e,"Currency");}convert(e){return this.send(On.Convert,e,Mp)}cryptoConvert(e){return this.send(On.CryptoConvert,e,Op)}};var $b=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),Va=zod.z.object({ServerTimeUtc:c,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:M.nullish(),FodderConsumed:zod.z.array($b).nullish()}),mh=zod.z.array(Te(Va)),ir={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Jb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},Zb=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Yb={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Xb=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),eD=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),tD=zod.z.object({Networks:zod.z.record(zod.z.string(),eD).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),iD=zod.z.object({FlatBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),PercentBonuses:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Power:zod.z.number().nullish()}).passthrough(),sD=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),UseRequirements:zod.z.record(zod.z.string(),zod.z.number()).nullish(),AllowedCharacterIDs:zod.z.array(zod.z.string()).nullish(),AllowedSlotIDs:zod.z.array(zod.z.string()).nullish(),IdleRateBonus:zod.z.number().nullish()}).passthrough(),nD=zod.z.object({ValuationMode:Zb.nullish(),WeightCurve:_e.nullish(),Selection:Xb.nullish()}).passthrough(),rD=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:ce.nullish(),CostCurve:_e.nullish(),FlatBonusCurve:_e.nullish(),PercentBonusCurve:_e.nullish(),PowerCurve:_e.nullish(),Fodder:nD.nullish()}).passthrough(),oD=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),aD=zod.z.object({ItemID:zod.z.string(),CatalogID:zod.z.string(),ItemClass:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish(),IsStackable:zod.z.boolean().nullish(),IsTradable:zod.z.boolean().nullish(),Weight:zod.z.number().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),NFT:tD.nullish(),Stats:iD.nullish(),Equipment:sD.nullish(),Upgrade:rD.nullish(),Metadata:oD.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),lD=zod.z.object({Items:zod.z.record(zod.z.string(),aD).nullish()}).passthrough(),sr=zod.z.object({Catalogs:zod.z.record(zod.z.string(),lD).nullish()}).passthrough();var nr=class extends L{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(ir.UpgradeLevel,e,Va)}upgradeLevelsBatch(e){return this.send(ir.UpgradeLevelsBatch,e,mh)}};var rr=class extends L{constructor(e){super(e,"Store");}purchase(e){return this.send(Tt.Purchase,e,To)}purchaseBatch(e){return this.send(Tt.PurchaseBatch,e,yu)}getDefinitions(e){return this.send(Tt.GetDefinitions,e,Ds)}getUserState(e){return this.send(Tt.GetUserState,e,Ru)}getStorefront(e){return this.send(Tt.GetStorefront,e,Ps)}getCreditsConfirmation(e){return this.send(Tt.GetCreditsConfirmation,e,vo)}getCreditsBalance(e){return this.send(Tt.GetCreditsBalance,e,gu)}};var uD={Apple:"Apple",Google:"Google"},or=zod.z.object({PremiumID:zod.z.string().nullish(),PurchaseDate:zod.z.string().nullish(),ExpirationDate:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),IsAutoRenewEnabled:zod.z.boolean().nullish()}).passthrough(),ar=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),or).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(r=>r),cD=zod.z.object({PremiumID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Tier:zod.z.number().nullish(),DurationDays:zod.z.number().nullish(),TrialDurationDays:zod.z.number().nullish(),PriceOptions:ce.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Na=zod.z.object({Definitions:zod.z.record(zod.z.string(),cD).nullish()}).passthrough(),fh=zod.z.object({Premium:Na.nullish()}),gh=zod.z.object({ServerTimeUtc:c.nullish(),Premium:ar.nullish()}),lr=zod.z.object({ServerTimeUtc:c.nullish(),Premium:ar.nullish(),Subscription:or.nullish(),Resources:M.nullish()}),Yt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var pD={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},dD=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),yh=zod.z.object({StartUtc:c.nullish(),EndUtc:c.nullish(),Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),ja=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),hD=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),mD=zod.z.object({Rewards:K.nullish(),Rules:K.nullish(),Refund:K.nullish()}).passthrough(),fD=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:dD.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:yh.nullish(),Refund:ja.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:hD.nullish(),Presets:mD.nullish()}).passthrough(),gD=zod.z.object({StoreID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),PackageName:zod.z.string().nullish(),VerificationMode:zod.z.string().nullish(),PlayPublicKey:zod.z.string().nullish(),RequireCertificateChain:zod.z.boolean().nullish(),SecretName:zod.z.string().nullish(),IssuerID:zod.z.string().nullish(),KeyID:zod.z.string().nullish(),AcknowledgePurchases:zod.z.boolean().nullish(),NotificationPackageName:zod.z.string().nullish()}).passthrough(),yD=zod.z.object({Rewards:H.nullish()}).passthrough(),RD=zod.z.object({Rules:yh.nullish()}).passthrough(),CD=zod.z.object({Refund:ja.nullish()}).passthrough(),SD=zod.z.object({Rewards:zod.z.record(zod.z.string(),yD).nullish(),Rules:zod.z.record(zod.z.string(),RD).nullish(),Refund:zod.z.record(zod.z.string(),CD).nullish()}).passthrough(),xD=zod.z.object({MaxPurchaseAgeDays:zod.z.number().nullish(),AllowSandbox:zod.z.boolean().nullish(),RequirePackageMatch:zod.z.boolean().nullish(),MaxReceiptsPerBatch:zod.z.number().nullish(),RefundCheckHorizonDays:zod.z.number().nullish(),RejectCrossUserReceipts:zod.z.boolean().nullish()}).passthrough(),bD=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),fD).nullish(),Stores:zod.z.record(zod.z.string(),gD).nullish(),Presets:SD.nullish(),Validation:xD.nullish(),Refund:ja.nullish()}).passthrough(),Rh=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:c.nullish(),LastPurchasedAt:c.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Ch=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:c.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:c.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:c.nullish()}).passthrough(),DD=zod.z.object({Products:zod.z.record(zod.z.string(),Rh).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Ch).nullish(),LastRefundCheckAt:c.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:c.nullish(),LastPurchaseAt:c.nullish()}).passthrough(),PD=zod.z.object({ProductID:zod.z.string(),Available:zod.z.boolean(),Owned:zod.z.boolean(),Blocked:zod.z.boolean(),Reason:zod.z.string().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Sh=zod.z.object({ServerTimeUtc:c,Purchase:bD.nullish(),Availability:zod.z.array(PD).nullish()}),xh=zod.z.object({ServerTimeUtc:c,Purchase:DD.nullish()}),ID={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},vD=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Wa=zod.z.object({ServerTimeUtc:c,Store:Hi.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:vD.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),ProductState:Rh.nullish(),Premium:ar.nullish(),Subscription:or.nullish(),SubscriptionMirror:Ch.nullish()}).passthrough(),bh=zod.z.object({ServerTimeUtc:c,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:c.nullish()}).passthrough(),Dh=gt(Wa),Xt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var ur=class extends L{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(Xt.GetDefinitions,e,Sh)}getUserState(e){return this.send(Xt.GetUserState,e,xh)}validatePurchase(e){return this.send(Xt.ValidatePurchase,e,Wa)}validatePurchasesBatch(e){return this.send(Xt.ValidatePurchasesBatch,e,Dh)}createTelegramInvoice(e){return this.send(Xt.CreateTelegramInvoice,e,bh)}};var TD=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Ph=zod.z.object({Reward:H.nullish(),Weight:zod.z.number().nullish(),AmountRange:TD.nullish()}).passthrough(),bi=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(Ph).nullish()}).passthrough(),Di=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(Ph).nullish()}).passthrough(),AD=zod.z.object({RewardSlots:zod.z.array(bi).nullish()}).passthrough(),kD=zod.z.object({PityRules:zod.z.array(Di).nullish()}).passthrough(),cr=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),AD).nullish(),PityPresets:zod.z.record(zod.z.string(),kD).nullish()}).passthrough();var wD=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),Ih=zod.z.object({ServerTimeUtc:c,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:zod.z.array(M).nullish(),TriggeredPity:zod.z.array(wD).nullish()}),zD=zod.z.object({RewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),MD=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:j.nullish()}).passthrough(),OD=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ce.nullish(),RewardSlots:zod.z.array(bi).nullish(),PityRules:zod.z.array(Di).nullish(),Presets:zD.nullish(),RewardMultiplier:Ji.nullish(),SupplyLimits:zod.z.array(MD).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),ED=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Ka=zod.z.object({Definitions:zod.z.record(zod.z.string(),OD).nullish(),RewardPools:cr.nullish(),Settings:ED.nullish()}).passthrough(),vh=zod.z.object({LootboxDefinitions:Ka.nullish()}),pr={GetDefinitions:"GetDefinitions",Open:"Open"};var dr=class extends L{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(pr.GetDefinitions,e,vh)}open(e){return this.send(pr.Open,e,Ih)}};var UD=zod.z.object({}).passthrough().transform(r=>r),qD=zod.z.object({}).passthrough().transform(r=>r),LD=zod.z.object({}).passthrough().transform(r=>r),BD=zod.z.object({}).passthrough().transform(r=>r),GD=zod.z.object({}).passthrough().transform(r=>r),Th=zod.z.object({ServerTimeUtc:c,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:UD,Resources:M.nullish(),Inventory:Q.nullish()}),Ah=zod.z.object({ServerTimeUtc:c,AccrualID:zod.z.string(),AccruedSeconds:j.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:qD,Resources:M.nullish(),Inventory:Q.nullish()}),kh=zod.z.object({ServerTimeUtc:c,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:LD,Resources:M.nullish(),Inventory:Q.nullish()}),wh=zod.z.object({ServerTimeUtc:c,ClaimID:zod.z.string(),ClaimState:BD,Resources:M.nullish(),Inventory:Q.nullish()}),zh=zod.z.object({Enabled:zod.z.boolean(),Multiplier:zod.z.number().nullish(),Progress:j.nullish(),Source:zod.z.string().nullish(),SourceKey:zod.z.string().nullish()}),FD=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),_D=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:H.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Vi=zod.z.object({Gate:Z.nullish(),Limits:Ce.nullish()}).passthrough(),Qa=zod.z.object({Availability:K.nullish()}).passthrough(),VD=zod.z.object({Availability:zod.z.record(zod.z.string(),Vi).nullish()}).passthrough(),ND=zod.z.object({CalendarID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Days:zod.z.array(_D).nullish(),IsLooping:zod.z.boolean().nullish(),MissBehavior:zod.z.string().nullish(),ResetByDays:zod.z.number().nullish(),MissThresholdMultiplier:zod.z.number().nullish(),ClaimMode:zod.z.string().nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),Availability:Vi.nullish(),Presets:Qa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),jD=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),WD=zod.z.object({BaseRatePerSecond:zod.z.number().nullish(),PowerCoefficient:zod.z.number().nullish(),BoardRankCoefficient:zod.z.number().nullish(),EquipmentBonusEnabled:zod.z.boolean().nullish(),EquipmentCharacterID:zod.z.string().nullish(),PremiumMultipliers:zod.z.array(jD).nullish()}).passthrough(),KD=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Vi.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),QD=zod.z.object({AccrualID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rate:WD.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:KD.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),HD=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:H.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),$D=zod.z.object({ComebackID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tiers:zod.z.array(HD).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Vi.nullish(),Presets:Qa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),JD=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),CooldownSeconds:zod.z.number().nullish(),MaxClaimsPerWindow:zod.z.number().nullish(),WindowSeconds:zod.z.number().nullish(),TotalClaimLimit:zod.z.number().nullish()}).passthrough(),ZD=zod.z.object({ClaimID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Mode:zod.z.string().nullish(),Rewards:H.nullish(),PremiumLimitOverrides:zod.z.array(JD).nullish(),Availability:Vi.nullish(),Presets:Qa.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),Ha=zod.z.object({TierRewards:FD.nullish(),MilestoneRewardMultiplier:Ji.nullish(),DailyCalendars:zod.z.record(zod.z.string(),ND).nullish(),IdleAccruals:zod.z.record(zod.z.string(),QD).nullish(),Comebacks:zod.z.record(zod.z.string(),$D).nullish(),Claims:zod.z.record(zod.z.string(),ZD).nullish(),Presets:VD.nullish()}).passthrough(),Mh=zod.z.object({RewardDefinitions:Ha.nullish()}),Oh=zod.z.object({Rewards:GD.nullish()}),Mt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var hr=class extends L{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Mt.GetRewardDefinitions,e,Mh)}getUserRewardsState(e){return this.send(Mt.GetUserRewardsState,e,Oh)}getMilestoneRewardMultiplier(e){return this.send(Mt.GetMilestoneRewardMultiplier,e,zh)}claimDailyReward(e){return this.send(Mt.ClaimDailyReward,e,Th)}collectIdleAccrual(e){return this.send(Mt.CollectIdleAccrual,e,Ah)}claimComebackReward(e){return this.send(Mt.ClaimComebackReward,e,kh)}claimReward(e){return this.send(Mt.ClaimReward,e,wh)}};var mr=class extends L{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(rt.GetTutorialDefinitions,e,Ql)}getUserTutorialState(e){return this.send(rt.GetUserTutorialState,e,Xi)}startFlow(e){return this.send(rt.StartFlow,e,Et)}reportStepShown(e){return this.send(rt.ReportStepShown,e,Et)}completeStep(e){return this.send(rt.CompleteStep,e,Et)}completeStepsBatch(e){return this.send(rt.CompleteStepsBatch,e,Jl)}skipStep(e){return this.send(rt.SkipStep,e,Et)}skipFlow(e){return this.send(rt.SkipFlow,e,Et)}claimFlowReward(e){return this.send(rt.ClaimFlowReward,e,$l)}resetFlow(e){return this.send(rt.ResetFlow,e,Et)}};var YD={Open:"Open",Application:"Application"},XD=zod.z.enum(["Open","Application"]).catch("Open"),eP={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Eh=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),tP={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},$a=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),iP={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var ei={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},sP=zod.z.object({CampaignID:zod.z.string().nullish(),DisplayNameKey:zod.z.string().nullish(),DescriptionKey:zod.z.string().nullish(),IconPath:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IsRunning:zod.z.boolean().nullish()}).passthrough(),Uh=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:XD.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:Eh.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(sP).nullish()}).passthrough(),nP=zod.z.object({Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),CountedMetrics:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ReachedMilestones:zod.z.array(zod.z.string()).nullish(),CappedBySubmissionLimit:zod.z.boolean().nullish(),CappedByCreatorLimit:zod.z.boolean().nullish(),NotPaidAsCopy:zod.z.boolean().nullish()}).passthrough(),rP=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:$a.nullish(),CurrencyID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),Earned:zod.z.number().nullish(),Mature:zod.z.number().nullish(),Granted:zod.z.number().nullish(),Paid:zod.z.number().nullish(),Overpaid:zod.z.number().nullish(),Claimable:zod.z.number().nullish(),BySubmission:zod.z.record(zod.z.string(),nP).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),oP=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:$a.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),qh=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(rP).nullish(),Payouts:zod.z.array(oP).nullish()}).passthrough(),Lh=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:$a.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),aP=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),lP=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenAddress:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),TokenId:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),Signature:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish(),Deadline:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Splits:zod.z.array(aP).nullish()}).passthrough(),uP=zod.z.object({Kind:zod.z.string().nullish(),Target:zod.z.string().nullish(),Required:zod.z.number().nullish(),Actual:zod.z.number().nullish(),Passed:zod.z.boolean().nullish()}).passthrough(),Bh=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:Eh.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(uP).nullish()}).passthrough(),cP=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),pP=zod.z.object({ProgramID:zod.z.string().nullish(),Mint:zod.z.string().nullish(),WalletAddress:zod.z.string().nullish(),Amount:zod.z.string().nullish(),BurnAmount:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),ExpiresAt:zod.z.string().nullish(),SignatureEpoch:zod.z.string().nullish(),Domain:zod.z.string().nullish(),Splits:zod.z.array(cP).nullish(),SignatureHex:zod.z.string().nullish(),Ed25519PublicKey:zod.z.string().nullish(),Ed25519Message:zod.z.string().nullish(),UserID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),Category:zod.z.string().nullish()}).passthrough(),Gh=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:zod.z.number().nullish(),NetAmountNative:zod.z.number().nullish(),BurnAmountNative:zod.z.number().nullish(),AmountUsd:zod.z.number().nullish(),ExpiresAt:zod.z.string().nullish(),EvmSignature:lP.nullish(),SolanaSignature:pP.nullish(),StateDelta:Si.nullish()}).passthrough();var fr=class extends L{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send(ei.GetCommunityMarketingState,e,Uh)}getEarnings(e){return this.send(ei.GetEarnings,e,qh)}claim(e){return this.send(ei.Claim,e,Lh)}checkJoinEligibility(e){return this.send(ei.CheckJoinEligibility,e,Bh)}withdrawCryptoReward(e){return this.send(ei.WithdrawCryptoReward,e,Gh)}};var gr=class extends L{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(Qe.GetChatDefinitions,e,Eu)}getChannels(e){return this.send(Qe.GetChannels,e,Es)}poll(e){return this.send(Qe.Poll,e,Uu)}getHistory(e){return this.send(Qe.GetHistory,e,qu)}getConversations(e){return this.send(Qe.GetConversations,e,Gu)}sendMessage(e){return this.send(Qe.SendMessage,e,Lu)}openDirectChannel(e){return this.send(Qe.OpenDirectChannel,e,Bu)}markRead(e){return this.send(Qe.MarkRead,e,Ri)}joinChannel(e){return this.send(Qe.JoinChannel,e,Ri)}leaveChannel(e){return this.send(Qe.LeaveChannel,e,Ri)}reportMessage(e){return this.send(Qe.ReportMessage,e,Fu)}ignoreUser(e){return this.send(Qe.IgnoreUser,e,Ri)}unignoreUser(e){return this.send(Qe.UnignoreUser,e,Ri)}};var yr=class extends L{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(Ci.GetPushConfig,e,Nu)}subscribePush(e){return this.send(Ci.SubscribePush,e,qo)}unsubscribePush(e){return this.send(Ci.UnsubscribePush,e,qe)}getPushSubscriptions(e){return this.send(Ci.GetPushSubscriptions,e,ju)}};var Rr=class extends L{constructor(e){super(e,"Localization");}send(e,t,i,s){let n=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${n}:${t.Locale}`:n,...s})}getLocalizationManifest(e){return this.send(Xn.GetLocalizationManifest,e,oh)}getLocalizationTable(e){return this.send(Xn.GetLocalizationTable,e,ah)}};var Cr=class extends L{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(dt.GetQuestDefinitions,e,Yi)}getUserQuestState(e){return this.send(dt.GetUserQuestState,e,Ul)}refreshQuestCycles(e){return this.send(dt.RefreshQuestCycles,e,qe)}claimQuestReward(e){return this.send(dt.ClaimQuestReward,e,lo)}claimQuestRewardsBatch(e){return this.send(dt.ClaimQuestRewardsBatch,e,Bl)}claimMilestoneReward(e){return this.send(dt.ClaimMilestoneReward,e,uo)}claimMilestoneRewardsBatch(e){return this.send(dt.ClaimMilestoneRewardsBatch,e,Gl)}claimGroupCompletionReward(e){return this.send(dt.ClaimGroupCompletionReward,e,ql)}addQuestProgress(e){return this.send(dt.AddQuestProgress,e,Ll)}};var Sr=class extends L{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(at.GetActiveEvents,e,_s)}getDefinitions(e){return this.send(at.GetDefinitions,e,Fs)}getUserLteState(e){return this.send(at.GetUserLteState,e,Hu)}grantTokens(e){return this.send(at.GrantTokens,e,M)}spendTokens(e){return this.send(at.SpendTokens,e,Go)}claimMilestone(e){return this.send(at.ClaimMilestone,e,Fo)}claimMilestonesBatch(e){return this.send(at.ClaimMilestonesBatch,e,_o)}claimAllMilestones(e){return this.send(at.ClaimAllMilestones,e,_o)}spendTokensBatch(e){return this.send(at.SpendTokensBatch,e,$u)}grantTokensBatch(e){return this.send(at.GrantTokensBatch,e,Ju)}};var xr=class extends L{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ve.GetDefinitions,e,Hs)}getLeaderboard(e){return this.send(Ve.GetLeaderboard,e,Oi)}getMyProgress(e){return this.send(Ve.GetMyProgress,e,Ns)}submitScore(e){return this.send(Ve.SubmitScore,e,js)}submitScoreFromSource(e){return this.send(Ve.SubmitScoreFromSource,e,js)}claimCycleReward(e){return this.send(Ve.ClaimCycleReward,e,Ws)}claimMilestone(e){return this.send(Ve.ClaimMilestone,e,Ks)}getFriendsLeaderboard(e){return this.send(Ve.GetFriendsLeaderboard,e,Oi)}getLeaderboardsBatch(e){return this.send(Ve.GetLeaderboardsBatch,e,Xu)}getProgressBatch(e){return this.send(Ve.GetProgressBatch,e,Qs)}claimCycleRewardsBatch(e){return this.send(Ve.ClaimCycleRewardsBatch,e,ec)}claimMilestonesBatch(e){return this.send(Ve.ClaimMilestonesBatch,e,tc)}submitScoresBatch(e){return this.send(Ve.SubmitScoresBatch,e,ic)}claimAllRewardsBatch(e){return this.send(Ve.ClaimAllRewardsBatch,e,sc)}getOverviewBatch(e){return this.send(Ve.GetOverviewBatch,e,nc)}};var br=class extends L{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Lt.GetDefinitions,e,Zs)}getActiveSeason(e){return this.send(Lt.GetActiveSeason,e,Js)}getUserState(e){return this.send(Lt.GetUserState,e,Vo)}grantStatusTokens(e){return this.send(Lt.GrantStatusTokens,e,lc)}claimTierReward(e){return this.send(Lt.ClaimTierReward,e,No)}claimTierRewardsBatch(e){return this.send(Lt.ClaimTierRewardsBatch,e,uc)}};var Dr=class extends L{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Yt.GetDefinitions,e,fh)}getUserState(e){return this.send(Yt.GetUserState,e,gh)}activateTrial(e){return this.send(Yt.ActivateTrial,e,lr)}purchaseItemOrCurrency(e){return this.send(Yt.PurchaseWithResources,e,lr)}purchaseRealMoney(e){return this.send(Yt.PurchaseRealMoney,e,lr)}};var Pr=class extends L{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(Ne.GetCharacterDefinitions,e,tn)}getUserCharacters(e){return this.send(Ne.GetUserCharacters,e,fc)}unlockCharacter(e){return this.send(Ne.UnlockCharacter,e,Qo)}upgradeStatLevel(e){return this.send(Ne.UpgradeStatLevel,e,Wo)}upgradeCharacterLevel(e){return this.send(Ne.UpgradeCharacterLevel,e,Ko)}equipItems(e){return this.send(Ne.EquipItems,e,gc)}unequipItems(e){return this.send(Ne.UnequipItems,e,yc)}unequipAllCharacters(e){return this.send(Ne.UnequipAllCharacters,e,Rc)}unlockCharactersBatch(e){return this.send(Ne.UnlockCharactersBatch,e,Dc)}upgradeCharacterLevelsBatch(e){return this.send(Ne.UpgradeCharacterLevelsBatch,e,Pc)}upgradeStatLevelsBatch(e){return this.send(Ne.UpgradeStatLevelsBatch,e,Ic)}unlockSkin(e){return this.send(Ne.UnlockSkin,e,Cc)}equipSkin(e){return this.send(Ne.EquipSkin,e,Sc)}unequipSkin(e){return this.send(Ne.UnequipSkin,e,xc)}getCharacterSkins(e){return this.send(Ne.GetCharacterSkins,e,bc)}};var Ir=class extends L{constructor(e){super(e,"Match");}createMatch(e){return this.send(Ct.CreateMatch,e,nd)}updateMatch(e){return this.send(Ct.UpdateMatch,e,rd)}cancelMatch(e){return this.send(Ct.CancelMatch,e,od)}instantBattle(e){return this.send(Ct.InstantBattle,e,ad)}saveStrategy(e){return this.send(Ct.SaveStrategy,e,qe)}getMyMatches(e){return this.send(Ct.GetMyMatches,e,ba)}getAvailableMatches(e){return this.send(Ct.GetAvailableMatches,e,ba)}getDefinitions(e){return this.send(Ct.GetDefinitions,e,pd)}};var dP={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},Fh=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),hP={None:"None",Min:"Min",Average:"Average",Max:"Max"},mP=zod.z.enum(["None","Min","Average","Max"]).catch("None"),fP={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},gP=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),yP={Clamp:"Clamp",Reject:"Reject"},RP=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),CP=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),SP=zod.z.object({Index:zod.z.number().nullish(),BurnedItemIDs:zod.z.array(zod.z.string()).nullish(),RolledCollectionID:zod.z.string().nullish(),UsedCollections:zod.z.record(zod.z.string(),zod.z.number()).nullish(),Output:ro.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(CP).nullish()}),_h=zod.z.object({ServerTimeUtc:c,Type:Fh.nullish(),CraftID:zod.z.string(),CraftedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),InputRarity:zod.z.string().nullish(),OutputRarity:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:zod.z.array(SP).nullish()}),xP=zod.z.object({CraftID:zod.z.string().nullish(),Type:Fh.nullish(),CatalogID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),InputRarityID:zod.z.string().nullish(),OutputRarityID:zod.z.string().nullish(),RequiredItemCount:zod.z.number().nullish(),PriceOptions:ce.nullish(),OutputLevelMode:mP.nullish(),InputSelection:gP.nullish(),OutputLevelOverflow:RP.nullish()}).passthrough(),Ja=zod.z.object({Definitions:zod.z.record(zod.z.string(),xP).nullish()}).passthrough(),Vh=zod.z.object({ServerTimeUtc:c.nullish(),CraftDefinitions:Ja.nullish()}),vr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var Tr=class extends L{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(vr.GetDefinitions,e,Vh)}craft(e){return this.send(vr.Craft,e,_h)}};var bP=2e5,Ar=class extends L{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,on,{timeoutMs:bP,autoRetry:false})}readGeneration(e,t){return this.send(e,t,on,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Fe.GetDefinitions,e,Ec)}generateText(e){return this.generate(Fe.GenerateText,e)}getText(e){return this.readGeneration(Fe.GetText,e)}generateImage(e){return this.generate(Fe.GenerateImage,e)}editImage(e){return this.generate(Fe.EditImage,e)}getImage(e){return this.readGeneration(Fe.GetImage,e)}generateVideo(e){return this.generate(Fe.GenerateVideo,e)}getVideo(e){return this.readGeneration(Fe.GetVideo,e)}generateAudio(e){return this.generate(Fe.GenerateAudio,e)}getAudio(e){return this.readGeneration(Fe.GetAudio,e)}generateMusic(e){return this.generate(Fe.GenerateMusic,e)}getMusic(e){return this.readGeneration(Fe.GetMusic,e)}generateThreeD(e){return this.generate(Fe.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Fe.GetThreeD,e)}listGenerations(e){return this.send(Fe.ListGenerations,e,Oc)}getGeneration(e){return this.readGeneration(Fe.GetGeneration,e)}};var DP={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},PP=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),Nh=zod.z.object({}).passthrough().transform(r=>r),Pi=zod.z.object({CollectibleID:zod.z.string(),Rarity:zod.z.number().nullish(),IsSpecial:zod.z.boolean().nullish(),IsDuplicate:zod.z.boolean().nullish(),CollectionCurrencyConverted:zod.z.number().nullish()}),jh=zod.z.object({GrantedCollectibles:zod.z.array(Pi).nullish(),DuplicateCollectibles:zod.z.array(Pi).nullish(),CollectionCurrencyEarned:j.nullish()}),Wh=zod.z.object({OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(jh).nullish(),GrantedCollectibles:zod.z.array(Pi).nullish(),DuplicateCollectibles:zod.z.array(Pi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Kh=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(jh).nullish(),GrantedCollectibles:zod.z.array(Pi).nullish(),DuplicateCollectibles:zod.z.array(Pi).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),Qh=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Za=zod.z.object({SetID:zod.z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),Hh=zod.z.array(Te(Za)),$h=zod.z.object({Resources:M.nullish(),Inventory:Q.nullish()}),IP=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:Ee.nullish(),OfferedCollectibleID:zod.z.string().nullish(),OfferedCollectibleIsSpecial:zod.z.boolean().nullish(),ReceiverUserID:zod.z.string().nullish(),RequestedCollectibleID:zod.z.string().nullish(),RequestedCollectibleIsSpecial:zod.z.boolean().nullish(),Status:PP.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RespondedAtUtc:c.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),Jh=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:c.nullish(),Resources:M.nullish()}),Zh=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),Yh=zod.z.object({OfferID:zod.z.string(),ReceivedCollectibleID:zod.z.string().nullish(),ReceivedIsSpecial:zod.z.boolean().nullish(),SentCollectibleID:zod.z.string().nullish(),SentCollectibleIsSpecial:zod.z.boolean().nullish(),Transfer:zod.z.unknown().nullish()}),Xh=zod.z.object({OfferID:zod.z.string(),Resources:M.nullish()}),Ya=zod.z.object({Offers:zod.z.array(IP).nullish()}),vP=zod.z.object({CollectibleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rarity:zod.z.number().nullish(),HasSpecialVersion:zod.z.boolean().nullish(),SortOrder:zod.z.number().nullish()}).passthrough(),TP=zod.z.object({SetID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SortOrder:zod.z.number().nullish(),Collectibles:zod.z.array(vP).nullish(),SetCompletionReward:H.nullish()}).passthrough(),AP=zod.z.object({CollectionID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),SeasonChainID:zod.z.string().nullish(),Sets:zod.z.array(TP).nullish(),GrandPrize:H.nullish()}).passthrough(),em=zod.z.object({BonusRewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),kP=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:ce.nullish(),BonusRewardSlots:zod.z.array(bi).nullish(),PityRules:zod.z.array(Di).nullish(),Presets:em.nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectibleCount:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),GuaranteeMaxRarity:zod.z.boolean().nullish(),RarityWeights:zod.z.record(zod.z.string(),zod.z.number()).nullish(),ColorTier:zod.z.number().nullish()}).passthrough(),wP=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),zP=zod.z.object({CollectionChestID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CollectionCurrencyCost:zod.z.number().nullish(),MaxOpenCount:zod.z.number().nullish(),MinCollectibleCount:zod.z.number().nullish(),MaxCollectibleCount:zod.z.number().nullish(),GuaranteedMinRarity:zod.z.number().nullish(),BonusRewardSlots:zod.z.array(bi).nullish(),PityRules:zod.z.array(Di).nullish(),Presets:em.nullish(),Tier:zod.z.number().nullish()}).passthrough(),MP=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),OP=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),kr=zod.z.object({Collections:zod.z.record(zod.z.string(),AP).nullish(),PackTypes:zod.z.record(zod.z.string(),kP).nullish(),CollectionChests:zod.z.array(zP).nullish(),DuplicateConversions:zod.z.array(wP).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(MP).nullish(),RewardPools:cr.nullish(),Settings:OP.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 wr=class extends L{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(je.GetDefinitions,e,kr)}getUserState(e){return this.send(je.GetUserState,e,Nh)}openPack(e){return this.send(je.OpenPack,e,Wh)}openCollectionChest(e){return this.send(je.OpenCollectionChest,e,Kh)}useCollectibleJoker(e){return this.send(je.UseCollectibleJoker,e,Qh)}claimSetReward(e){return this.send(je.ClaimSetReward,e,Za)}claimSetRewardsBatch(e){return this.send(je.ClaimSetRewardsBatch,e,Hh)}claimGrandPrize(e){return this.send(je.ClaimGrandPrize,e,$h)}sendTradeOffer(e){return this.send(je.SendTradeOffer,e,Jh)}cancelTradeOffer(e){return this.send(je.CancelTradeOffer,e,Zh)}acceptTradeOffer(e){return this.send(je.AcceptTradeOffer,e,Yh)}declineTradeOffer(e){return this.send(je.DeclineTradeOffer,e,Xh)}getMyTradeOffers(e){return this.send(je.GetMyTradeOffers,e,Ya)}getIncomingTradeOffers(e){return this.send(je.GetIncomingTradeOffers,e,Ya)}};var zr=class extends L{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(ht.GetDefinitions,e,cn)}getActiveEvent(e){return this.send(ht.GetActiveEvent,e,Lc)}getUserState(e){return this.send(ht.GetUserState,e,un)}getGroupState(e){return this.send(ht.GetGroupState,e,Xo)}joinOrCreateGroup(e){return this.send(ht.JoinOrCreateGroup,e,Xo)}spin(e){return this.send(ht.Spin,e,Gc)}claimObjectReward(e){return this.send(ht.ClaimObjectReward,e,ea)}claimGrandPrize(e){return this.send(ht.ClaimGrandPrize,e,ea)}leaveGroup(e){return this.send(ht.LeaveGroup,e,Fc)}};var Mr=class extends L{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(Rt.GetDefinition,e,Zc)}getUserState(e){return this.send(Rt.GetUserState,e,Yc)}getActiveDeals(e){return this.send(Rt.GetActiveDeals,e,hn)}dismissDeal(e){return this.send(Rt.DismissDeal,e,ep)}executeNode(e){return this.send(Rt.ExecuteNode,e,Xc)}recordShow(e){return this.send(Rt.RecordShow,e,tp)}claimMilestone(e){return this.send(Rt.ClaimMilestone,e,ip)}claimMilestonesBatch(e){return this.send(Rt.ClaimMilestonesBatch,e,sp)}};var EP=zod.z.object({}).passthrough().transform(r=>r),UP=zod.z.object({FeatureKey:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Rate:zod.z.number().nullish(),Basis:zod.z.string().nullish(),SourceCurrencyID:zod.z.string().nullish(),TargetCurrencyID:zod.z.string().nullish(),MinSourceAmount:zod.z.number().nullish(),MaxRewardPerOperation:zod.z.number().nullish(),Limits:Ce.nullish()}).passthrough(),Xa=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:zod.z.record(zod.z.string(),Be).nullish(),SpendRewards:zod.z.array(UP).nullish(),Qualification:zod.z.object({}).passthrough().transform(r=>r).nullish()}).passthrough(),el=zod.z.object({Pending:zod.z.boolean().nullish(),Qualified:zod.z.boolean().nullish(),Groups:zod.z.array(zod.z.object({GroupID:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Conditions:zod.z.array(zod.z.object({Type:zod.z.string().nullish(),Met:zod.z.boolean().nullish(),Current:zod.z.number().nullish(),Required:zod.z.number().nullish()}).passthrough()).nullish()}).passthrough()).nullish()}).passthrough(),tm=zod.z.object({ReferralDefinitions:Xa.nullish()}).passthrough(),im=zod.z.object({Referral:EP.nullish(),InviteUrl:zod.z.string().nullish(),Qualification:el.nullish()}).passthrough(),sm=zod.z.object({QualificationPending:zod.z.boolean().nullish(),Qualification:el.nullish()}).passthrough(),nm=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),QualificationPending:zod.z.boolean().nullish(),Qualification:el.nullish()}).passthrough(),tl=zod.z.object({RewardID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),rm=gt(tl),jt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch",CheckQualification:"CheckQualification"};var Or=class extends L{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(jt.GetDefinitions,e,tm)}getUserState(e){return this.send(jt.GetUserState,e,im)}activateReferralCode(e){return this.send(jt.ActivateReferralCode,e,nm)}claimInviteReward(e){return this.send(jt.ClaimInviteReward,e,tl)}claimInviteRewardsBatch(e){return this.send(jt.ClaimInviteRewardsBatch,e,rm)}checkQualification(e){return this.send(jt.CheckQualification,e,sm)}};var Er=class extends L{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(tt.GetDefinitions,e,lp)}getMessages(e){return this.send(tt.GetMessages,e,up)}getUnreadCount(e){return this.send(tt.GetUnreadCount,e,gn)}readMessages(e){return this.send(tt.ReadMessages,e,sa)}claimReward(e){return this.send(tt.ClaimReward,e,yn)}claimRewardsBatch(e){return this.send(tt.ClaimRewardsBatch,e,yn)}claimAll(e){return this.send(tt.ClaimAll,e,yn)}deleteMessages(e){return this.send(tt.DeleteMessages,e,sa)}sendGift(e){return this.send(tt.SendGift,e,cp)}sendTransfer(e){return this.send(tt.SendTransfer,e,pp)}getGiftStatus(e){return this.send(tt.GetGiftStatus,e,dp)}};var Ur=class extends L{constructor(e){super(e,"Advertising");}requestAdPermit(e){return this.send(Cn.RequestAdPermit,e,hp)}completeView(e){return this.send(Cn.CompleteView,e,mp)}};var qr=class extends L{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Se.GetFriendsList,e,Ui)}getIncomingRequests(e){return this.send(Se.GetIncomingRequests,e,Ui)}getOutgoingRequests(e){return this.send(Se.GetOutgoingRequests,e,Ui)}getRecommendedFriends(e){return this.send(Se.GetRecommendedFriends,e,Ui)}sendFriendRequest(e){return this.send(Se.SendFriendRequest,e,qi)}acceptFriendRequest(e){return this.send(Se.AcceptFriendRequest,e,qi)}declineFriendRequest(e){return this.send(Se.DeclineFriendRequest,e,qi)}removeFriend(e){return this.send(Se.RemoveFriend,e,qi)}getInbox(e){return this.send(Se.GetInbox,e,gp)}markInboxSeen(e){return this.send(Se.MarkInboxSeen,e,Li)}getInboxUnread(e){return this.send(Se.GetInboxUnread,e,Li)}follow(e){return this.send(Se.Follow,e,Ft)}unfollow(e){return this.send(Se.Unfollow,e,Ft)}getFollowers(e){return this.send(Se.GetFollowers,e,bn)}getFollowing(e){return this.send(Se.GetFollowing,e,bn)}block(e){return this.send(Se.Block,e,Ft)}unblock(e){return this.send(Se.Unblock,e,Ft)}getBlocked(e){return this.send(Se.GetBlocked,e,bn)}react(e){return this.send(Se.React,e,Ft)}unreact(e){return this.send(Se.Unreact,e,Ft)}getMyReactions(e){return this.send(Se.GetMyReactions,e,Rp)}getEntityStates(e){return this.send(Se.GetEntityStates,e,yp)}addComment(e){return this.send(Se.AddComment,e,Dn)}editComment(e){return this.send(Se.EditComment,e,Dn)}deleteComment(e){return this.send(Se.DeleteComment,e,Sp)}getComments(e){return this.send(Se.GetComments,e,Cp)}report(e){return this.send(Se.Report,e,xp)}};var qP={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var ti=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),LP=zod.z.object({BoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:ce.nullish(),Effect:ti.nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),Lr=zod.z.object({Schedule:ye.nullish(),Gate:Z.nullish()}).passthrough(),il=zod.z.object({Availability:K.nullish(),Effects:K.nullish()}).passthrough(),BP=zod.z.object({ScheduledBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Effects:zod.z.array(ti).nullish(),Availability:Lr.nullish(),Presets:il.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),GP=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(ti).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),FP=zod.z.object({ChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Phases:zod.z.array(GP).nullish(),Availability:Lr.nullish(),Presets:il.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),_P=zod.z.object({TriggeredBoostID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Sources:zod.z.array(nt).nullish(),Effects:zod.z.array(ti).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:Lr.nullish(),Presets:il.nullish()}).passthrough(),VP=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),NP=zod.z.object({Effects:zod.z.array(ti).nullish()}).passthrough(),jP=zod.z.object({Availability:zod.z.record(zod.z.string(),Lr).nullish(),Effects:zod.z.record(zod.z.string(),NP).nullish()}).passthrough(),WP=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),VP).nullish()}).passthrough(),Br=zod.z.object({Definitions:zod.z.record(zod.z.string(),LP).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),BP).nullish(),BoostChains:zod.z.record(zod.z.string(),FP).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),_P).nullish(),Settings:WP.nullish(),Presets:jP.nullish()}).passthrough(),om=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:ti.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:c.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:c.nullish()}).passthrough();var am=zod.z.object({ServerTimeUtc:c.nullish(),Active:zod.z.record(zod.z.string(),om).nullish()}),lm=zod.z.object({ServerTimeUtc:c.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:om.nullish(),Resources:M.nullish()}),KP={Scheduled:"Scheduled",Chain:"Chain"},QP=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),Effects:zod.z.array(ti).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),um=zod.z.object({ServerTimeUtc:c.nullish(),Windows:zod.z.array(QP).nullish()}),ii={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Gr=class extends L{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(ii.GetDefinitions,e,Br)}getActive(e){return this.send(ii.GetActive,e,am)}getActiveWindows(e){return this.send(ii.GetActiveWindows,e,um)}activate(e){return this.send(ii.Activate,e,lm)}cleanupExpired(e){return this.send(ii.CleanupExpired,e,qe)}};var Fr=class extends L{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(mt.GetUserCustomDataDefinitions,e,Tn)}getMyUserCustomData(e){return this.send(mt.GetMyUserCustomData,e,Ip)}getPublicUserCustomDataOf(e){return this.send(mt.GetPublicUserCustomDataOf,e,pa)}setPrivateData(e){return this.send(mt.SetPrivateData,e,da)}setPublicData(e){return this.send(mt.SetPublicData,e,da)}deleteKey(e){return this.send(mt.DeleteKey,e,qe)}batchSet(e){return this.send(mt.BatchSet,e,vp)}batchDelete(e){return this.send(mt.BatchDelete,e,Tp)}batchGetPublicUserCustomDataOf(e){return this.send(mt.BatchGetPublicUserCustomDataOf,e,Ap)}};var HP={Static:"Static",Runtime:"Runtime"},$P={Public:"Public",Private:"Private"},JP=zod.z.enum(["Client","Server","System"]).catch("Client"),ZP=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),YP=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:c.nullish(),Version:zod.z.number().nullish(),LastWriter:JP.nullish(),ExpiresAt:c.nullish()}).passthrough(),cm=zod.z.record(zod.z.string(),YP),sl=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:cm.nullish(),Runtime:cm.nullish(),NotModified:zod.z.boolean().nullish()}),XP=zod.z.object({KeyID:zod.z.string(),Scope:zod.z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:zod.z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:ZP.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),_r=zod.z.object({Keys:zod.z.record(zod.z.string(),XP).nullish(),DefaultMaxValueLengthBytes:zod.z.number().nullish(),DefaultTtlSeconds:zod.z.number().nullish(),MaxKeysPerBucket:zod.z.number().nullish(),MaxTotalSizeBytes:zod.z.number().nullish(),RejectUnregisteredKeys:zod.z.boolean().nullish()}).passthrough(),Ni={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var Vr=class extends L{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Ni.GetTitleCustomDataDefinitions,e,_r)}getPublicTitleData(e){return this.send(Ni.GetPublicTitleData,e,sl)}getPublicTitleDataKeys(e){return this.send(Ni.GetPublicTitleDataKeys,e,sl)}};var eI={Fast:"Fast",Sequential:"Sequential"},tI={Instant:"Instant",Timed:"Timed"};var iI={Hit:"Hit",Blocked:"Blocked"},sI=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),nI=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:H.nullish()}).passthrough();var rI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:H.nullish()}).passthrough(),oI=zod.z.object({Reward:H.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough();zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(rI).nullish(),Rate:oI.nullish()}).passthrough();zod.z.object({PlayedCount:zod.z.number().nullish(),RewardsClaimedCount:zod.z.number().nullish(),InstantClaimsCount:zod.z.number().nullish(),EarlyClaimsCount:zod.z.number().nullish(),LateClaimsCount:zod.z.number().nullish(),AdViewsTotal:zod.z.number().nullish(),StatRewardClaimsCount:zod.z.number().nullish(),StatReportsClampedCount:zod.z.number().nullish(),StatReportsUnknownMetricCount:zod.z.number().nullish()}).passthrough();var pm=zod.z.object({}).passthrough().transform(r=>r),dm=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),We=zod.z.object({Operation:M.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),aI=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),lI=zod.z.object({ShieldChance:zod.z.number().nullish(),DamagedBuildingChance:zod.z.number().nullish(),RankMultiplierMin:zod.z.number().nullish(),RankMultiplierMax:zod.z.number().nullish(),RankOffsetMin:zod.z.number().nullish(),RankOffsetMax:zod.z.number().nullish(),StageLevelSpread:zod.z.number().nullish()}).passthrough(),uI=zod.z.object({CostMatrixTemplatesByID:zod.z.record(zod.z.string(),zod.z.array(zod.z.array(zod.z.number()))).nullish(),PerBoardGrowth:zod.z.number().nullish(),VisualTemplateCycle:zod.z.array(zod.z.string()).nullish(),EconomyScaledResources:pe.nullish(),ScaleRaidStealWithEconomy:zod.z.boolean().nullish(),ScaleAttackRewardWithEconomy:zod.z.boolean().nullish(),AttackValueFromCostMatrix:zod.z.boolean().nullish(),AttackBlockedRewardFactor:zod.z.number().nullish(),ScaleVictimLossWithEconomy:zod.z.boolean().nullish(),ScaleVictimLossWithTier:zod.z.boolean().nullish(),SynthesizedBuildingSlots:zod.z.number().nullish(),SynthesizedBuildingMaxLevel:zod.z.number().nullish(),DifficultyGrowthPerBoard:zod.z.number().nullish()}).passthrough(),cI=zod.z.object({CostMatrix:zod.z.array(zod.z.array(zod.z.number())).nullish(),PerBoardGrowth:zod.z.number().nullish(),EconomyScale:zod.z.number().nullish(),ScaledResources:pe.nullish()}).passthrough(),hm=zod.z.object({SlotIndex:zod.z.number().nullish(),Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),MaxLevel:zod.z.number().nullish(),MaxLevelReward:H.nullish()}).passthrough(),pI=zod.z.object({Index:zod.z.number().nullish(),Type:zod.z.string().nullish(),CustomTypeID:zod.z.string().nullish(),RandomActionAttackWeight:zod.z.number().nullish(),RandomActionRaidWeight:zod.z.number().nullish(),ChanceTableID:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish(),Params:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),dI=zod.z.object({Tiles:zod.z.record(zod.z.string(),pI).nullish()}).passthrough(),hI=zod.z.object({Weight:zod.z.number().nullish(),Bonus:We.nullish(),Tag:zod.z.string().nullish()}).passthrough(),mI=zod.z.object({Weight:zod.z.number().nullish(),Tag:zod.z.string().nullish(),MinBonusCells:zod.z.number().nullish(),MaxBonusCells:zod.z.number().nullish(),BonusPool:zod.z.array(hI).nullish(),GuaranteedBonus:We.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),fI=zod.z.object({Variants:zod.z.array(mI).nullish()}).passthrough(),gI=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:We.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),yI=zod.z.object({Outcomes:zod.z.array(gI).nullish()}).passthrough(),mm=zod.z.object({PerAdMultiplierRange:dm.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),RI=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:We.nullish()}).passthrough(),CI=zod.z.object({Tiers:zod.z.array(RI).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:We.nullish()}).passthrough(),SI=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:We.nullish()}).passthrough(),xI=zod.z.object({Reward:We.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),bI=zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(SI).nullish(),Rate:xI.nullish()}).passthrough(),fm=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),bI).nullish()}).passthrough(),DI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:We.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ce.nullish(),Multipliers:mm.nullish(),Gradation:CI.nullish(),RunStats:fm.nullish()}).passthrough(),PI=zod.z.object({Choices:zod.z.array(DI).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),II=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:We.nullish(),Tag:zod.z.string().nullish()}).passthrough(),vI=zod.z.object({OnPassStart:We.nullish(),OnTileLanding:zod.z.record(zod.z.string(),We).nullish(),OnAttack:zod.z.record(zod.z.string(),We).nullish(),OnRaid:zod.z.record(zod.z.string(),We).nullish(),OnBuild:We.nullish(),OnStageComplete:We.nullish(),OnAttackBonusDrops:zod.z.array(II).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),yI).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),PI).nullish()}).passthrough(),gm=zod.z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(hm).nullish(),HeistGridBonusConfig:fI.nullish(),StageOperations:vI.nullish(),TileLandingMultiplier:dm.nullish(),EconomyOverride:cI.nullish()}).passthrough(),TI=zod.z.object({Name:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),BoardTemplateID:zod.z.string().nullish(),Buildings:zod.z.array(hm).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:gm.nullish()}).passthrough(),AI=zod.z.object({AttackCooldownSeconds:zod.z.number().nullish(),RaidCooldownSeconds:zod.z.number().nullish(),MaxRecentTargets:zod.z.number().nullish(),LiveOpponentActiveDays:zod.z.number().nullish(),LiveOpponentPoolSize:zod.z.number().nullish(),LiveOpponentPoolCacheSeconds:zod.z.number().nullish(),MaxLiveCandidateReads:zod.z.number().nullish(),VictimImmunitySeconds:zod.z.number().nullish()}).passthrough(),kI=zod.z.object({Enabled:zod.z.boolean().nullish(),IntervalSeconds:zod.z.number().nullish(),MaxPerCatchUp:zod.z.number().nullish(),Chance:zod.z.number().nullish(),AttackWeight:zod.z.number().nullish(),RaidWeight:zod.z.number().nullish(),MinBoardStageLevel:zod.z.number().nullish(),RaidLossMultiplier:zod.z.number().nullish()}).passthrough(),Nr=zod.z.object({RollCurrencyID:zod.z.string().nullish(),ShieldCurrencyID:zod.z.string().nullish(),RaidMode:zod.z.string().nullish(),AllowedRollMultipliers:zod.z.array(zod.z.number()).nullish(),BoardTemplatesByID:zod.z.record(zod.z.string(),dI).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),gm).nullish(),StagesByLevel:zod.z.record(zod.z.string(),TI).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:uI.nullish(),Dice:aI.nullish(),Bots:lI.nullish(),Targeting:AI.nullish(),BotRaids:kI.nullish()}).passthrough(),wI=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:c.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),Be).nullish(),GrandPrize:H.nullish()}).passthrough(),jr=zod.z.object({Board:Nr.nullish(),CommunityChest:wI.nullish()}).passthrough(),ym=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),pe).nullish()}).passthrough(),zI=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:Ee.nullish(),TargetBuildingStates:zod.z.array(sI).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:ym.nullish()}).passthrough(),MI=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:We.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:ce.nullish(),Multipliers:mm.nullish(),RunStats:fm.nullish()}).passthrough(),OI=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(MI).nullish()}).passthrough(),EI=zod.z.object({GroupID:zod.z.string().nullish(),Delta:j.nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),UnlockedMilestoneIDs:zod.z.array(zod.z.string()).nullish(),Completed:zod.z.boolean().nullish()}).passthrough(),Rm=zod.z.object({UsedMultiplier:zod.z.number().nullish(),Steps:zod.z.number().nullish(),DiceValues:zod.z.array(zod.z.number()).nullish(),OldPosition:zod.z.number().nullish(),NewPosition:zod.z.number(),CyclesCompletedDelta:j.nullish(),LandedTileType:zod.z.string().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:zI.nullish(),SpecialModeOffer:OI.nullish(),CommunityChestContribution:EI.nullish()}).passthrough(),Cm=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:Dt.nullish()}).passthrough(),nl=zod.z.object({Status:zod.z.string().nullish(),Outcome:zod.z.string().nullish(),FoundSymbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),FoundBonus:H.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(nI).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:Dt.nullish(),RaidRewardPreview:ym.nullish()}).passthrough(),Sm=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish()}).passthrough(),xm=zod.z.object({Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish()}).passthrough(),bm=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),UI=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),Dm=zod.z.object({FinalMultiplier:zod.z.number().nullish(),AdViewsUsed:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),IsEarlyClaim:zod.z.boolean().nullish(),ReachedTierIndex:zod.z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(UI).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),qI={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Pm=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),LI={Active:"Active",Left:"Left",Replaced:"Replaced"},BI=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),GI=zod.z.object({CurrentProgress:j.nullish(),MaxProgress:j.nullish()}).passthrough(),FI=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ee.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:j.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),Ml).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:BI.nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),Im=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(FI).nullish(),SharedProgress:GI.nullish(),Status:Pm.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:zod.z.number().nullish()}).passthrough(),_I=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:Pm.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:c.nullish()}).passthrough(),VI=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(_I).nullish()}).passthrough(),vm=zod.z.object({ServerTimeUtc:c.nullish(),UserState:VI.nullish(),ActiveGroup:Im.nullish(),SecondsRemaining:j.nullish()}),Tm=zod.z.object({ServerTimeUtc:c.nullish(),Group:Im.nullish(),SecondsRemaining:j.nullish()}),rl=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Am=zod.z.object({ServerTimeUtc:c.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Le={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 NI={Mesh:"Mesh",Host:"Host"},ol=zod.z.enum(["Mesh","Host"]).catch("Mesh"),jI={ServerRelay:"ServerRelay",P2P:"P2P"},al=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),WI={Public:"Public",Private:"Private"},KI=zod.z.enum(["Public","Private"]).catch("Public"),QI={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},HI=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),km=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),$I=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),wm=zod.z.object({SystemState:$I.nullish(),DefaultTopology:ol.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:al.nullish(),AllowCreatorChatOverride:zod.z.boolean().nullish(),MaxPlayersPerRoom:zod.z.number().nullish(),RoomTtlSeconds:zod.z.number().nullish(),MaxRoomLifetimeSeconds:zod.z.number().nullish(),HeartbeatIntervalMs:zod.z.number().nullish(),MemberTimeoutMs:zod.z.number().nullish(),MaxSignalPayloadBytes:zod.z.number().nullish(),MaxChatTextLength:zod.z.number().nullish(),RoomLogCap:zod.z.number().nullish(),VoiceEnabled:zod.z.boolean().nullish(),RecordVoices:zod.z.boolean().nullish(),IceServers:zod.z.array(km).nullish()}).passthrough(),JI=zod.z.object({UserID:zod.z.string().nullish(),Username:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish(),Level:zod.z.number().nullish(),Power:zod.z.number().nullish(),Ready:zod.z.boolean().nullish(),State:zod.z.record(zod.z.string(),zod.z.string()).nullish(),JoinedAt:zod.z.number().nullish(),IsHost:zod.z.boolean().nullish(),LastSeenMs:zod.z.number().nullish()}).passthrough(),ZI=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:ol.nullish(),ChatMode:al.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),YI=zod.z.object({Seq:zod.z.number().nullish(),Type:HI.nullish(),FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),Payload:zod.z.string().nullish(),Ts:zod.z.number().nullish()}).passthrough(),ji=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:ol.nullish(),ChatMode:al.nullish(),Visibility:KI.nullish(),Status:zod.z.string().nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Voice:zod.z.boolean().nullish(),Members:zod.z.array(JI).nullish(),IceServers:zod.z.array(km).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),zm=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),Mm=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),ll=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),Om=zod.z.object({Rooms:zod.z.array(ZI).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Em=zod.z.object({Envelopes:zod.z.array(YI).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Wr=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),$e={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 ul=zod.z.object({TitleCustomData:_r.nullish(),Character:tn.nullish(),Item:sr.nullish(),Currency:En.nullish(),Store:Ds.nullish(),Lootbox:Ka.nullish(),Quest:Yi.nullish(),TimedEvent:Fs.nullish(),Leaderboard:Hs.nullish(),Season:Zs.nullish(),Reward:Ha.nullish(),Collection:kr.nullish(),Craft:Ja.nullish(),DealOffer:ta.nullish(),Premium:Na.nullish(),TimedBoost:Br.nullish(),CoopEvent:cn.nullish(),GameLoop:jr.nullish(),Match:Da.nullish(),Experiment:Hd.nullish(),Blockchain:ga.nullish(),Marketplace:Aa.nullish(),Multiplayer:wm.nullish(),UserCustomData:Tn.nullish(),Referral:Xa.nullish(),Localization:nh.nullish(),Analytics:Ld.nullish(),Social:bp.nullish(),PlatformBridge:Dp.nullish()}).passthrough();var si={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Kr=class extends L{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(si.GetTitlePublicConfiguration,e,ul)}getTitlePublicConfigurationExcept(e){return this.send(si.GetTitlePublicConfigurationExcept,e,ul)}getCurrencyDefinitions(e){return this.send(si.GetCurrencyDefinitions,e,En)}getItemDefinitions(e){return this.send(si.GetItemDefinitions,e,sr)}getServerTime(e){return this.send(si.GetServerTime,e,qe)}};var Qr=class extends L{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(Le.GetGameLoops,e,jr)}getBoardDefinition(e,t=false){return this.send(Le.GetBoardDefinition,e,Nr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(Le.GetBoardDefinitionForLevel,e,Nr,{silent:t})}getUserBoardState(e){return this.send(Le.GetUserBoardState,e,pm)}boardLoopRoll(e){return this.send(Le.BoardLoopRoll,e,Rm)}boardLoopAttack(e){return this.send(Le.BoardLoopAttack,e,Cm)}boardLoopRaid(e){return this.send(Le.BoardLoopRaid,e,nl)}boardLoopRaidFast(e){return this.send(Le.BoardLoopRaidFast,e,nl)}boardLoopBuild(e){return this.send(Le.BoardLoopBuild,e,Sm)}boardSpecialChoose(e){return this.send(Le.BoardSpecialChoose,e,xm)}boardSpecialApplyMultiplier(e){return this.send(Le.BoardSpecialApplyMultiplier,e,bm)}boardSpecialClaim(e){return this.send(Le.BoardSpecialClaim,e,Dm)}getCommunityChestState(e){return this.send(Le.GetCommunityChestState,e,vm)}joinOrCreateCommunityChest(e){return this.send(Le.JoinOrCreateCommunityChest,e,Tm)}claimCommunityChestMilestone(e){return this.send(Le.ClaimCommunityChestMilestone,e,rl)}claimCommunityChestGrandPrize(e){return this.send(Le.ClaimCommunityChestGrandPrize,e,rl)}leaveCommunityChest(e){return this.send(Le.LeaveCommunityChest,e,Am)}};var ev={Live:"Live",Latest:"Latest",Specific:"Specific"},tv={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},iv=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),sv={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"},nv=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),rv=zod.z.object({Level:iv,Message:zod.z.string().nullish(),Data:Bt.nullish()}),ov=zod.z.object({Error:nv,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Um=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:Bt.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(rv).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:ov.nullish()}),cl={Execute:"Execute"};var Hr=class extends L{constructor(e){super(e,"CloudCode");}execute(e){return this.send(cl.Execute,e,Um)}};var $r=class extends L{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(He.GetDefinitions,e,Wp)}getUserState(e){return this.send(He.GetUserState,e,Kp)}depositToken(e){return this.send(He.DepositToken,e,Qp)}depositNFT(e){return this.send(He.DepositNFT,e,Hp)}requestTokenWithdrawal(e){return this.send(He.RequestTokenWithdrawal,e,$p)}requestNFTWithdrawal(e){return this.send(He.RequestNFTWithdrawal,e,Jp)}getTransactionHistory(e){return this.send(He.GetTransactionHistory,e,Zp)}retryWithdrawal(e){return this.send(He.RetryWithdrawal,e,Yp)}confirmWithdrawal(e){return this.send(He.ConfirmWithdrawal,e,Xp)}donateToDeveloper(e){return this.send(He.DonateToDeveloper,e,Sa)}donateToUsersPool(e){return this.send(He.DonateToUsersPool,e,Sa)}getPlayAccess(e){return this.send(He.GetPlayAccess,e,Np)}confirmPlayAccess(e){return this.send(He.ConfirmPlayAccess,e,_t)}};var Jr=class extends L{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(ze.GetDefinitions,e,hd)}getGroupedOffers(e){return this.send(ze.GetGroupedOffers,e,md)}getOffersByItem(e){return this.send(ze.GetOffersByItem,e,ka)}getOffer(e){return this.send(ze.GetOffer,e,fd)}getBuyOrders(e){return this.send(ze.GetBuyOrders,e,ka)}getMyState(e){return this.send(ze.GetMyState,e,_n)}getHistory(e){return this.send(ze.GetHistory,e,yd)}createListing(e){return this.send(ze.CreateListing,e,Fi)}cancelListing(e){return this.send(ze.CancelListing,e,lt)}buy(e){return this.send(ze.Buy,e,lt)}marketBuy(e){return this.send(ze.MarketBuy,e,lt)}marketSell(e){return this.send(ze.MarketSell,e,lt)}createAuction(e){return this.send(ze.CreateAuction,e,Fi)}placeBid(e){return this.send(ze.PlaceBid,e,gd)}claimAuction(e){return this.send(ze.ClaimAuction,e,lt)}createBuyOrder(e){return this.send(ze.CreateBuyOrder,e,Fi)}cancelBuyOrder(e){return this.send(ze.CancelBuyOrder,e,lt)}fillBuyOrder(e){return this.send(ze.FillBuyOrder,e,lt)}createDirectTrade(e){return this.send(ze.CreateDirectTrade,e,Fi)}respondDirectTrade(e){return this.send(ze.RespondDirectTrade,e,lt)}cancelDirectTrade(e){return this.send(ze.CancelDirectTrade,e,lt)}claimBack(e){return this.send(ze.ClaimBack,e,lt)}};var Zr=class extends L{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send($e.CreateRoom,e,ji)}joinRoom(e){return this.send($e.JoinRoom,e,ji)}leaveRoom(e,t=false){return this.send($e.LeaveRoom,e,ll,{keepalive:t})}listRooms(e){return this.send($e.ListRooms,e,Om)}getRoom(e){return this.send($e.GetRoom,e,ji)}closeRoom(e){return this.send($e.CloseRoom,e,ll)}poll(e){return this.send($e.Poll,e,Em)}sendSignal(e){return this.send($e.SendSignal,e,Wr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send($e.ClaimHost,e,ji)}kickMember(e){return this.send($e.KickMember,e,zm)}unbanMember(e){return this.send($e.UnbanMember,e,Mm)}sendChat(e){return this.send($e.SendChat,e,Wr)}setMemberState(e){return this.send($e.SetMemberState,e,Wr)}};var av={Free:"Free",Price:"Price",Holding:"Holding"},pl=zod.z.enum(["Free","Price","Holding"]).catch("Free"),lv={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},uv=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),cv={All:"All",Any:"Any"},pv=zod.z.enum(["All","Any"]).catch("All"),dv={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},hv=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),mv={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},fv=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),gv={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Lm=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),yv={New:"New",Popular:"Popular",MostLiked:"MostLiked",MostRemixed:"MostRemixed"},Rv={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},Cv=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),Sv=zod.z.object({Type:pi.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),MinLevel:zod.z.number().nullish()}).passthrough(),xv=zod.z.object({Requirements:zod.z.array(Sv).nullish(),Match:pv.nullish(),Mode:uv.nullish()}).passthrough(),bv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:pl.nullish(),Price:pe.nullish(),Holding:xv.nullish()}).passthrough(),Dv=zod.z.object({AllowedMimeTypes:zod.z.array(zod.z.string()).nullish(),MaxBytes:zod.z.number().nullish(),MaxCount:zod.z.number().nullish(),Required:zod.z.boolean().nullish()}).passthrough(),Pv=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),Dv).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(pl).nullish(),PricePolicy:Fn.nullish(),PublishGate:Z.nullish(),PublishFeeOptions:ce.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),Iv=zod.z.object({Allowed:zod.z.array(Gi).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),vv=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),Tv=zod.z.object({MaxTitleLength:zod.z.number().nullish(),MaxDescriptionLength:zod.z.number().nullish(),MaxTags:zod.z.number().nullish(),MaxTagLength:zod.z.number().nullish(),MaxMetadataKeys:zod.z.number().nullish(),MaxMetadataValueLength:zod.z.number().nullish(),MaxAccessOptions:zod.z.number().nullish(),ThumbnailMaxBytes:zod.z.number().nullish()}).passthrough(),Av=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Schedule:ye.nullish(),Gate:Z.nullish(),Order:zod.z.number().nullish()}).passthrough(),kv=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:Z.nullish(),Schedule:ye.nullish(),ContentTypes:zod.z.record(zod.z.string(),Pv).nullish(),PricePolicy:Fn.nullish(),Commission:Ta.nullish(),HoldingPolicy:Iv.nullish(),Moderation:vv.nullish(),Limits:Tv.nullish(),Featured:zod.z.array(Av).nullish()}).passthrough(),wv=zod.z.object({Acquisitions:zod.z.number().nullish(),Downloads:zod.z.number().nullish(),Likes:zod.z.number().nullish(),Favorites:zod.z.number().nullish(),ReportCount:zod.z.number().nullish(),Remixes:zod.z.number().nullish()}).passthrough(),ni=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:Ee.nullish(),Title:zod.z.string().nullish(),Description:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish(),Metadata:zod.z.record(zod.z.string(),zod.z.string()).nullish(),ThumbnailUrl:zod.z.string().nullish(),Visibility:hv.nullish(),Access:zod.z.array(bv).nullish(),Status:fv.nullish(),ModerationNote:zod.z.string().nullish(),Stats:wv.nullish(),Revision:zod.z.number().nullish(),ParentContentID:zod.z.string().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),PublishedAt:c.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),zv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:pl.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),Bm=zod.z.object({CollectionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Description:zod.z.string().nullish(),ContentIDs:zod.z.array(zod.z.string()).nullish(),Order:zod.z.number().nullish()}).passthrough(),Gm=zod.z.object({Definitions:kv.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish(),CanPublish:zod.z.record(zod.z.string(),zod.z.boolean()).nullish(),Collections:zod.z.array(Bm).nullish()}).passthrough(),Yr=zod.z.object({Items:zod.z.array(ni).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Fm=zod.z.object({Content:ni.nullish(),AccessState:zod.z.array(zv).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),_m=zod.z.object({Collection:Bm.nullish(),Items:zod.z.array(ni).nullish()}).passthrough(),Vm=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:Ee.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(ni).nullish()}).passthrough(),qm=zod.z.object({Role:zod.z.string().nullish(),Index:zod.z.number().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish(),ServerCopy:zod.z.boolean().nullish()}).passthrough(),Nm=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array(qm).nullish(),ThumbnailUpload:qm.nullish(),ExpiresAt:c.nullish()}).passthrough(),jm=zod.z.object({Content:ni.nullish(),Resources:M.nullish()}).passthrough(),dl=zod.z.object({Content:ni.nullish()}).passthrough(),Wm=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Lm.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:Dt.nullish(),Resources:M.nullish(),CommissionTaken:pe.nullish()}).passthrough(),Mv=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),Km=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:Cv.nullish(),Files:zod.z.array(Mv).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:c.nullish()}).passthrough(),Ov=zod.z.object({ContentID:zod.z.string().nullish(),Source:Lm.nullish(),OptionID:zod.z.string().nullish(),PricePaid:pe.nullish(),AcquiredAt:c.nullish(),Content:ni.nullish()}).passthrough(),Qm=zod.z.object({Licenses:zod.z.array(Ov).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Ke={GetDefinitions:"GetDefinitions",Browse:"Browse",GetContent:"GetContent",GetCollection:"GetCollection",GetCreatorProfile:"GetCreatorProfile",BeginUpload:"BeginUpload",Publish:"Publish",UpdateContent:"UpdateContent",Unpublish:"Unpublish",GetMyContent:"GetMyContent",Acquire:"Acquire",GetDownload:"GetDownload",GetMyLicenses:"GetMyLicenses",GetMyFavorites:"GetMyFavorites"};var Xr=class extends L{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(Ke.GetDefinitions,e,Gm)}browse(e){return this.send(Ke.Browse,e,Yr)}getContent(e){return this.send(Ke.GetContent,e,Fm)}getCollection(e){return this.send(Ke.GetCollection,e,_m)}getCreatorProfile(e){return this.send(Ke.GetCreatorProfile,e,Vm)}beginUpload(e){return this.send(Ke.BeginUpload,e,Nm)}publish(e){return this.send(Ke.Publish,e,jm)}updateContent(e){return this.send(Ke.UpdateContent,e,dl)}unpublish(e){return this.send(Ke.Unpublish,e,dl)}getMyContent(e){return this.send(Ke.GetMyContent,e,Yr)}acquire(e){return this.send(Ke.Acquire,e,Wm)}getDownload(e){return this.send(Ke.GetDownload,e,Km)}getMyLicenses(e){return this.send(Ke.GetMyLicenses,e,Qm)}getMyFavorites(e){return this.send(Ke.GetMyFavorites,e,Yr)}};var eo=class extends L{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,Dd,"defs")}get(e){return this.sendKeyed("Get",e,za,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Id,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,Ma,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,vd,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,Oa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,Oa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Td,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,kd,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Ad,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,wd,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,Pd,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,zd,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,za,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,Ma,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var to=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;ads;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.settings=yl(e),this.emitter=new Ti,this.platform=e.platform??new li,this.clientPlatform=e.clientPlatform??wl(),this.acquisition=new Kt(this.platform),this.acquisition.capture(),this.playtime=new Ai(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear(),this.referral.checkQualificationIfPending().catch(()=>{});}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new rs({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e.fetch,debugLogging:this.settings.debugLogging,throttleMs:e.throttleMs,maxRequestsPerSecond:e.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new us(this.emitter),this.cache=new ps(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new ds(this.platform.storage,this.settings.titleID),this.api={authentication:new Yn(this),user:new er(this),currency:new tr(this),item:new nr(this),store:new rr(this),purchase:new ur(this),lootbox:new dr(this),reward:new hr(this),quest:new Cr(this),tutorial:new mr(this),communityMarketing:new fr(this),chat:new gr(this),push:new yr(this),localization:new Rr(this),timedEvent:new Sr(this),leaderboard:new xr(this),season:new br(this),premium:new Dr(this),character:new Pr(this),match:new Ir(this),craft:new Tr(this),ai:new Ar(this),collection:new wr(this),coopEvent:new zr(this),dealOffer:new Mr(this),referral:new Or(this),mailbox:new Er(this),advertising:new Ur(this),social:new qr(this),timedBoost:new Gr(this),userCustomData:new Fr(this),titleCustomData:new Vr(this),title:new Kr(this),gameLoop:new Qr(this),cloudCode:new Hr(this),blockchain:new $r(this),marketplace:new Jr(this),multiplayer:new Zr(this),workshop:new Xr(this),dataCollections:new eo(this),analytics:new Jn(this),experiment:new Zn(this)},this.userService=new Rs(this),this.cache.attachState(this.userService),this.auth=new ms(this),this.currency=new Ss(this),this.item=new xs(this),this.store=new Is(this),this.purchase=new vs(this),this.checkout=new Ts(this),this.lootbox=new As(this),this.reward=new ks(this),this.quest=new Gs(this),this.tutorial=new zs(this),this.communityMarketing=new Ms(this),this.chat=new Us(this),this.push=new qs(this),this.localization=new Bs(this),this.timedEvent=new Vs(this),this.leaderboard=new $s(this),this.season=new Ys(this),this.premium=new Xs(this),this.character=new sn(this),this.match=new nn(this),this.craft=new rn(this),this.ai=new an(this),this.collection=new ln(this),this.coopEvent=new pn(this),this.dealOffer=new mn(this),this.referral=new fn(this),this.mailbox=new Rn(this),this.ads=new xn(this),this.social=new Pn(this),this.timedBoost=new In(this),this.userCustomData=new An(this),this.titleCustomData=new kn(this),this.title=new wn(this),this.gameLoop=new zn(this),this.cloudCode=new Mn(this),this.blockchain=new qn(this),this.marketplace=new Vn(this),this.multiplayer=new Nn(this),this.workshop=new jn(this),this.dataCollections=new Kn(this),this.analytics=new Hn(this),this.experiments=new $n(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.platform.getFullURL(),RelatedEntityID:G()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var io=class{ctx;constructor(e){this.ctx=new to(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Nt(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(n,{...s,...i},zod.z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get ads(){return this.ctx.ads}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get platform(){return this.ctx.platform}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function Uv(r){return new io(r)}var Hm="idos_sso",$m="state",hl="idos:sso:state",qv="https://idosgames.com/sso/",Lv=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],Bv=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function Gv(){if(typeof window>"u")return false;let{origin:r}=window.location;return Lv.includes(r)||Bv.test(r)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function Fv(){if(typeof window>"u")return null;let r=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!r)return null;let e=new URLSearchParams(r),t=e.get(Hm);if(!t)return null;let i=e.get($m)??"",s=Wv();return Qv(e),Kv(),s&&i!==s?null:{code:t,state:i}}function _v(r){if(typeof window>"u")return;let e=r.returnTo??Vv(),t=Nv();jv(t);let i=new URL(r.ssoUrl??qv);i.searchParams.set("title",r.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function Vv(){let{origin:r,pathname:e,search:t}=window.location;return `${r}${e}${t}`}function Nv(){let r=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(r);else for(let e=0;e<r.length;e++)r[e]=Math.floor(Math.random()*256);return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function jv(r){try{window.sessionStorage.setItem(hl,r);}catch{}}function Wv(){try{return window.sessionStorage.getItem(hl)}catch{return null}}function Kv(){try{window.sessionStorage.removeItem(hl);}catch{}}function Qv(r){r.delete(Hm),r.delete($m);let e=r.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var Hv={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 $v(r,e="Something went wrong. Please try again."){return r?Hv[r]??r:e}function Jv(r,e){return !!r?.Claims?.[e]?.ClaimedAt}function Zv(r){let e=r?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function Yv(r,e){return r?.Claims?.[e]?.PremiumTiers??[]}function Zm(r,e,t,i=1){if(!r)return e;let s=r.Base??e,n=Math.max(0,t-i),o;switch(r.Shape??"Flat"){case "PerStep":o=s+(r.PerStep??0)*n;break;case "PerStepRate":o=s*(1+(r.PerStepRate??0)*n);break;case "Geometric":o=s*Math.pow(1+(r.GrowthRate??0),n);break;case "Table":o=s*Jm(r,t,1);break;case "TableAbsolute":o=Jm(r,t,s);break;default:o=s;break}return Number.isNaN(o)?s:(r.MinResult!=null&&o<r.MinResult&&(o=r.MinResult),r.MaxResult!=null&&o>r.MaxResult&&(o=r.MaxResult),o)}function Xv(r,e,t=1){return Zm(r,1,e,t)}function eT(r){if(!r)return false;switch(r.Shape??"Flat"){case "PerStep":return (r.PerStep??0)!==0;case "PerStepRate":return (r.PerStepRate??0)!==0;case "Geometric":return (r.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return Ym(r.Points).length>0;default:return r.MinResult!=null||r.MaxResult!=null}}function tT(r){if(Number.isNaN(r)||r<=0)return 0;if(!Number.isFinite(r))return Number.MAX_SAFE_INTEGER;let e=Math.round(r);return Math.abs(r-e)<=1e-9*Math.max(1,Math.abs(r))?e:Math.ceil(r)}function Ym(r){if(!r)return [];let e=[];for(let t of r)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function Jm(r,e,t){let i=Ym(r.Points);if(i.length===0)return t;let s=null,n=null,o=null;for(let p of i)(o===null||p.AtStep>o.AtStep)&&(o=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=r.TailGrowthRate??0;return p===0?o.Value:o.Value*Math.pow(1+p,e-o.AtStep)}switch(r.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+p*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let h=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+h*(n.Value-s.Value)}let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,p)}default:return s.Value}}var iT={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},ml=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),sT={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},nT=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),rT=zod.z.object({PlacementID:zod.z.string().nullish(),Type:ml.nullish(),Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),CreditsRewarded:zod.z.number().nullish(),AllowedProviderIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),oT=zod.z.object({DefaultCreditsPerView:zod.z.number().nullish(),MaxCreditsBalance:zod.z.number().nullish(),DailyCreditEarnCap:zod.z.number().nullish(),DailyViewCap:zod.z.number().nullish(),MinSecondsBetweenViews:zod.z.number().nullish()}).passthrough(),aT=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),lT=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:nT.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),uT=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),cT=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),pT=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),DisableInterstitials:zod.z.boolean().nullish(),DisableBanners:zod.z.boolean().nullish(),DisableAppOpen:zod.z.boolean().nullish()}).passthrough(),dT=zod.z.object({RequirePersonalizedAdsConsent:zod.z.boolean().nullish(),RequireTrackingConsent:zod.z.boolean().nullish(),CurrentPolicyVersion:zod.z.string().nullish(),RegulatedRegions:zod.z.array(zod.z.string()).nullish()}).passthrough(),hT=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),mT=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:ml.nullish()}).passthrough(),fT={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},gT=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),yT=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:gT.nullish(),Enabled:zod.z.boolean().nullish(),Priority:zod.z.number().nullish(),AndroidAppID:zod.z.string().nullish(),IosAppID:zod.z.string().nullish(),WebAppID:zod.z.string().nullish(),Units:zod.z.record(zod.z.string(),mT).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),rT).nullish(),Providers:zod.z.record(zod.z.string(),yT).nullish(),RewardedVideo:oT.nullish(),Interstitial:aT.nullish(),Banner:lT.nullish(),AppOpen:uT.nullish(),FrequencyCapping:cT.nullish(),PremiumAdReductions:zod.z.array(pT).nullish(),Consent:dT.nullish(),Verification:hT.nullish()}).passthrough();var RT=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),CT=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:c.nullish(),LastCompletedAt:c.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),ST=zod.z.object({Date:c.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),xT=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:c.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),bT=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:c.nullish(),ConsentRevokedAt:c.nullish()}).passthrough(),DT=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:ml.nullish(),IssuedAt:c.nullish(),ExpiresAt:c.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),PT=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:c.nullish()}).passthrough();zod.z.object({Credits:RT.nullish(),Placements:zod.z.record(zod.z.string(),CT).nullish(),Daily:ST.nullish(),Session:xT.nullish(),LastImpressionAt:c.nullish(),LastInterstitialAt:c.nullish(),LastRewardedAt:c.nullish(),LastAppOpenAt:c.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:c.nullish(),Consent:bT.nullish(),PendingRequests:zod.z.record(zod.z.string(),DT).nullish(),FraudFlags:PT.nullish(),UpdatedAt:c.nullish()}).passthrough();var Xm="idos_device_id",so=class{storage;constructor(e=new oi){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(Xm);return e||(e="noop-device",this.storage.setString(Xm,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};
|
|
2
|
+
exports.AIAction=Fe;exports.AIErrorCode=qR;exports.AIGenerationStatus=Jt;exports.AIModality=Gt;exports.AcquisitionCapture=Kt;exports.AdProviderKind=fT;exports.AdType=iT;exports.AdvertisingAction=Cn;exports.AnalyticsAction=La;exports.AnalyticsDropReason=Ab;exports.AnalyticsEventNaming=qa;exports.AnalyticsLimits=St;exports.AttackOutcome=iI;exports.AuthType=ke;exports.AuthenticationAction=Ue;exports.AutomaticEvent=Vt;exports.BannerPosition=sT;exports.BlockchainAction=He;exports.BlockchainNetworkType=LS;exports.BlockchainOperationCategory=Bp;exports.BlockchainTransactionStatus=KS;exports.BlockchainTransactionType=_S;exports.BodyPart=Sx;exports.BoostWindowKind=KP;exports.BrowserPlatformAdapter=li;exports.BrowserStorage=ri;exports.CharacterAction=Ne;exports.ChatAction=Qe;exports.ChatAuthorType=vy;exports.ChatBlockedTermAction=Py;exports.ChatChannelType=Cy;exports.ChatDirectAudience=by;exports.ChatPartitioning=Sy;exports.ChatReportReason=Ay;exports.ClientPlatform=ft;exports.CloudCodeAction=cl;exports.CloudCodeErrorCode=sv;exports.CloudCodeLogLevel=tv;exports.CloudCodeRevisionSelection=ev;exports.CollectionAction=je;exports.CommissionSink=Fx;exports.CommunityChestMemberStatus=LI;exports.CommunityChestStatus=qI;exports.CommunityCreatorStatus=eP;exports.CommunityMarketingAction=ei;exports.CommunityMetricKind=iP;exports.CommunityParticipationMode=YD;exports.CommunityPayoutCurrencyKind=tP;exports.ConversionRateMode=vS;exports.CoopEventAction=ht;exports.CoopGroupStatus=HR;exports.CoopMemberStatus=$R;exports.CraftAction=vr;exports.CraftInputSelectionMode=fP;exports.CraftOutputLevelMode=hP;exports.CraftOutputLevelOverflow=yP;exports.CraftType=dP;exports.CreditsConfirmationStatus=Mi;exports.CreditsError=Hg;exports.CurrencyAction=On;exports.CurrencyStatus=IS;exports.CurrencyType=ct;exports.CurveInterpolation=vf;exports.CurveShape=Pf;exports.CustomDataBucket=wt;exports.CustomDataValueType=gS;exports.CustomDataWriter=dS;exports.DEFAULT_BASE_URL=gl;exports.DataAccessMode=ob;exports.DataCollectionKind=ib;exports.DataCollectionSchemaMode=mb;exports.DataCollectionsAction=Db;exports.DataCounterKind=cb;exports.DataFieldType=nb;exports.DataFieldVisibility=rb;exports.DataOwnerDeletedPolicy=db;exports.DataRefKind=lb;exports.DealComparisonOperator=hC;exports.DealNodeRuntimeStatus=rC;exports.DealNodeType=dC;exports.DealOfferAction=Rt;exports.DealOfferActivationStatus=nC;exports.EVENT_NAME_PATTERN=Qn;exports.EnvelopeType=QI;exports.EventTokenType=pf;exports.ExperimentAction=Fa;exports.ExperimentGoalKind=Gb;exports.FRIENDS_FROM_PLATFORM=lS;exports.FodderSelectionMode=Yb;exports.FodderValuationMode=Jb;exports.FriendActionStatus=$C;exports.FriendSource=JC;exports.GameLoopAction=Le;exports.IDosGamesClient=io;exports.IapProductType=pD;exports.IapPurchaseStatus=ID;exports.IapStoreValues=cf;exports.ItemAction=ir;exports.KycStatus=VS;exports.KycTier=jS;exports.LeaderboardAction=Ve;exports.LocalizationAction=Xn;exports.LocalizationMissingKeyMode=Wb;exports.LootboxAction=pr;exports.MAILBOX_COUNTER_CAP=qC;exports.MailboxAction=tt;exports.MailboxCategory=wC;exports.MailboxErrors=UC;exports.MailboxLetterSource=zC;exports.MailboxRewardModule=OC;exports.MarketGoodsType=Gn;exports.MarketOfferStatus=Gx;exports.MarketOfferType=Bx;exports.MarketplaceAction=ze;exports.MatchAction=Ct;exports.MatchStatus=xx;exports.MemoryStorage=oi;exports.MultiplayerAction=$e;exports.MultiplayerChatMode=jI;exports.MultiplayerTopology=NI;exports.NoopPlatformAdapter=so;exports.OFFER_NOT_IN_ROTATION=my;exports.PLATFORM_AD_MESSAGES=aa;exports.PLATFORM_AD_PROVIDER=oa;exports.PLATFORM_BRIDGE_ACK=uu;exports.PLATFORM_CREDITS_CONFIRM_MESSAGES=wo;exports.PLATFORM_ORIGINS=Pt;exports.PLATFORM_PAGE_UNAVAILABLE=cu;exports.PLATFORM_SIGN_IN_MESSAGES=xo;exports.PLATFORM_TOPUP_MESSAGES=Ao;exports.PlatformFriendsMode=cS;exports.PlatformProfileMode=uS;exports.PlayAccessMode=tx;exports.PlayerExperimentStatus=Vb;exports.PlaytimeTracker=Ai;exports.PremiumAction=Yt;exports.PurchaseAction=Xt;exports.PushAction=Ci;exports.PushPermissionState=At;exports.PushTopic=Vy;exports.PushTransport=Fy;exports.QuestAction=dt;exports.QuestObjectiveSource=Lf;exports.QuestPrerequisiteMode=Gf;exports.QuestStatus=Ef;exports.RaidMode=eI;exports.ReferralAction=jt;exports.ResourceEntryType=Ki;exports.RewardAction=Mt;exports.RoomVisibility=WI;exports.SKIN_ALREADY_OWNED=UR;exports.SKIN_SLOT=$o;exports.ScheduleMode=df;exports.SeasonAction=Lt;exports.SocialAction=Se;exports.SocialContentStatus=tS;exports.SocialEntityType=YC;exports.SocialInboxVerb=iS;exports.SocialReactionKind=XC;exports.SocialReportReason=eS;exports.SpecialChoiceMode=tI;exports.StoreAction=Tt;exports.StoreRotationMode=Zg;exports.StoreType=uD;exports.TimedBoostAction=ii;exports.TimedBoostStackingPolicy=qP;exports.TimedEventAction=at;exports.TitleAction=si;exports.TitleCustomDataAction=Ni;exports.TitleDataBucket=$P;exports.TitleDataScope=HP;exports.TradeOfferStatus=DP;exports.TransactionDirection=QS;exports.TutorialAction=rt;exports.TutorialBoardAction=eg;exports.TutorialFlowStatus=Zf;exports.TutorialGateMode=Rf;exports.TutorialRestartPolicy=$f;exports.TutorialScriptModule=Xf;exports.TutorialStepCompletionMode=Qf;exports.TypedEmitter=Ti;exports.UserAction=ut;exports.UserCustomDataAction=mt;exports.WalletGateBalanceSource=YS;exports.WalletLinkType=GS;exports.WorkshopAccessMode=av;exports.WorkshopAccessVia=Rv;exports.WorkshopAction=Ke;exports.WorkshopContentStatus=mv;exports.WorkshopHoldingMatch=cv;exports.WorkshopHoldingMode=lv;exports.WorkshopLicenseSource=gv;exports.WorkshopSort=yv;exports.WorkshopVisibility=dv;exports.askPlatformPage=It;exports.authErrorText=$v;exports.beginSsoRedirect=_v;exports.canUsePlatformAds=Sn;exports.canUsePlatformCreditsConfirm=zo;exports.canUsePlatformSignIn=Og;exports.canUsePlatformTopUp=$t;exports.canUsePreviewSignIn=Eg;exports.claimedMilestoneIDs=Zv;exports.clearPlatformSignInDeclined=qg;exports.createIDosGamesClient=Uv;exports.cryptoShortfallFromError=mi;exports.curveMultiplier=Xv;exports.defineView=Dg;exports.describeUserAgent=Gd;exports.evaluateCurve=Zm;exports.grantedPremiumTiers=Yv;exports.isAIGenerationTerminal=Ei;exports.isCurveConfigured=eT;exports.isFail=mf;exports.isMilestoneClaimed=Jv;exports.isOk=hf;exports.isPlatformParentOrigin=zi;exports.isPlatformSignInDeclined=Lg;exports.isReservedSlot=PR;exports.isSsoAvailable=Gv;exports.markPlatformSignInDeclined=Ug;exports.normalizeBlockchainCategory=Un;exports.parseAIErrorCode=LR;exports.readSsoCodeFromUrl=Fv;exports.requestPlatformAd=la;exports.requestPlatformCreditsConfirm=Mo;exports.requestPlatformSignIn=Do;exports.requestPlatformTopUp=ko;exports.roundAmount=tT;exports.where=Ib;exports.zPaymentProof=Qg;exports.zPriceOption=fu;exports.zPriceOptions=ce;
|