@idosgames/core 0.21.0 → 0.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var zod=require('zod'),Nt=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Nt__default=/*#__PURE__*/_interopDefault(Nt);var Si=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,n=>{i(),t(n);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let n of [...i])n(t);}removeAllListeners(){this.listeners.clear();}};function hm(){let a=new Map;return {get:e=>a.get(e)??null,set:(e,t)=>{a.set(e,t);},remove:e=>{a.delete(e);}}}function Na(){return mm()??hm()}function mm(){try{let a=globalThis.localStorage;if(!a)return null;let e="__idos_probe__";return a.setItem(e,"1"),a.removeItem(e),{get:t=>{try{return a.getItem(t)}catch{return null}},set:(t,i)=>{try{a.setItem(t,i);}catch{try{a.removeItem(t);}catch{}}},remove:t=>{try{a.removeItem(t);}catch{}}}}catch{return null}}var Va="https://api.idosgames.com";function Fa(a){return {titleID:a.titleID,titleTemplateID:a.titleTemplateID??"default",buildKey:a.buildKey??"",baseUrl:(a.baseUrl??Va).replace(/\/+$/,""),devBuild:a.devBuild??false,debugLogging:a.debugLogging??false,configStorage:a.configStorage??Na(),locale:a.locale??fm(),appVersion:a.appVersion??""}}function fm(){try{return globalThis.navigator?.language??""}catch{return ""}}var Xt=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{}}},ei=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 ti(){return globalThis.Telegram?.WebApp??null}function q(){return crypto.randomUUID()}var ja="idos_device_id",ii=class{storage;constructor(e=new Xt){this.storage=e;}getPlatform(){return ti()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=ti()?.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=ti()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(ja);return e||(e=q(),this.storage.setString(ja,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let t=ti();if(t?.openTelegramLink){t.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let t=ti();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 _r="idos_acq",Wa=["gclid","fbclid","ttclid","msclkid","yclid"],gm=["ref","r"],ym=["ref_","ref-","ref=","r_","r-"];var Lt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();Rm(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},n=xm(this.platform.getDeviceModel());return n&&(i.OsVersion=n),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(_r);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let i=Qa(Ka(t));if(i)return i}return qi(t)}readFromEnvironment(){let e={},t=Ka(this.platform.getFullURL());qt(e,"UtmSource",t.get("utm_source")),qt(e,"UtmMedium",t.get("utm_medium")),qt(e,"UtmCampaign",t.get("utm_campaign")),qt(e,"UtmTerm",t.get("utm_term")),qt(e,"UtmContent",t.get("utm_content")),qt(e,"ClaimToken",t.get("idos_click"));for(let R of Wa){let V=t.get(R);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",n=Sm(i);if(n){for(let R of Cm)qt(e,R,n.get(Ha[R])??null);for(let R of Wa){let V=n.get(R);if(V){e.ClickID=V;break}}}let s=qi(n?n.get("ref")??n.get("r")??"":i),o=Qa(t),c=s||o;c&&(e.ReferralCode=c,e.ChannelHint=s?"telegram":"query");let d=this.platform.getReferrer?.();return d&&(e.Referrer=d),e}read(){try{let e=this.platform.storage.getString(_r);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.platform.storage.setString(_r,JSON.stringify(e));}catch{}}};function Rm(a){return !!(a.UtmSource||a.UtmMedium||a.UtmCampaign||a.ClickID||a.Referrer||a.ReferralCode||a.ClaimToken)}function qt(a,e,t){t&&(a[e]=t);}var _a="a1_",Ha={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},Cm=Object.keys(Ha);function Sm(a){let e=(a||"").trim();if(!e.startsWith(_a))return null;let t=e.slice(_a.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(i+"=".repeat((4-i.length%4)%4)),s=Uint8Array.from(n,d=>d.charCodeAt(0)),o=new TextDecoder().decode(s),c=new URLSearchParams(o);return [...c.keys()].length>0?c:null}catch{return null}}function Ka(a){try{let e=a.indexOf("?");return new URLSearchParams(e>=0?a.slice(e):"")}catch{return new URLSearchParams}}function Qa(a){for(let e of gm){let t=a.get(e);if(t)return qi(t)}return null}function qi(a){let e=(a||"").trim();if(!e)return null;for(let t of ym)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function xm(a){let e=a||"",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 $a="idos_usage_pending",Ja="idos_usage_session",Za="idos_usage_closed_session",Ya="idos_usage_new_session",Xa="idos_usage_last_activity",xi=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($a),this.currentSessionSeconds=this.readNumber(Ja),this.pendingClosedSessionSeconds=this.readNumber(Za),this.isNewSessionPending=this.readNumber(Ya)!==0;let e=this.readNumber(Xa);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($a,this.pendingSeconds),this.writeNumber(Ja,this.currentSessionSeconds),this.writeNumber(Za,this.pendingClosedSessionSeconds),this.writeNumber(Ya,this.isNewSessionPending?1:0),this.writeNumber(Xa,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 lt={Virtual:"Virtual",Crypto:"Crypto"},si=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),Li={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase"},ri=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase"]).catch("Item"),ht={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Gi=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),bm={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Ni=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),Dm={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Vi=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),Pm={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},bi=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),Te={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function tl(){let a=globalThis,e=a.Capacitor?.getPlatform?.();if(e)return el(e);let t=a.cordova?.platformId;return t?el(t):a.navigator?.userAgent??""?ht.Web:ht.Unknown}function el(a){let e=a.toLowerCase();return e==="android"?ht.Android:e==="ios"?ht.Ios:e==="web"?ht.Web:ht.Unknown}function G(a){return {ok:true,data:a}}function r(a,e){return {ok:false,reason:a,error:e}}function vm(a){return a.ok}function Im(a){return !a.ok}var j=zod.z.union([zod.z.number(),zod.z.string()]).transform((a,e)=>{let t=typeof a=="string"?Number(a):a;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(a)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((a,e)=>{let t=typeof a=="number"?String(a):a.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(a)}`}),zod.z.NEVER):t}),u=zod.z.string();var Kr=zod.z.object({Type:ri.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()}),zm=zod.z.object({Type:Vi.nullish(),EntityID:zod.z.string()}),Tm=zod.z.object({Address:zm.nullish(),Amount:j.nullish(),Source:zod.z.string().nullish()}),ae=zod.z.object({Entries:zod.z.array(Kr).nullish(),EventTokens:zod.z.array(Tm).nullish()}),il=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:ae.nullish()}),Q=zod.z.object({Standard:ae.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(il).nullish()}),Ct=zod.z.object({Standard:ae.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(il).nullish()}),w=zod.z.object({Grant:Q.nullish(),Consume:Ct.nullish()}),St=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:w.nullish(),ToResult:w.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:ae.nullish()});var km=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Am={Completed:"Completed",Started:"Started",StepReached:"StepReached"},wm=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(),$=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:km.nullish(),Tutorial:wm.nullish(),Platforms:zod.z.array(Gi).nullish()}).passthrough();var fe=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 Mm=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Om=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Um=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 Em=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 it=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:fe.nullish()}).passthrough(),de=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:Om.nullish(),Chain:Um.nullish(),Cyclic:Em.nullish(),ActivationTriggers:zod.z.array(it).nullish(),Relative:Mm.nullish()}).passthrough();var Bm={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},qm=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Lm={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Gm=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),Nm=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Le=zod.z.object({Base:zod.z.number().nullish(),Shape:qm.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(Nm).nullish(),Interpolation:Gm.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var Vm=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:Q.nullish()}).passthrough(),Fm=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),Qr=zod.z.object({Bundles:zod.z.array(Vm).nullish(),Multipliers:zod.z.array(Fm).nullish()}).passthrough();var jm=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Fi=zod.z.object({Source:jm.nullish(),SourceKey:zod.z.string().nullish(),Curve:Le.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:ae.nullish(),ExcludeRewards:ae.nullish()}).passthrough(),nl=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),Ee=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:Q.nullish(),BonusRewards:Q.nullish(),SeasonTierRewards:Qr.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),oi=zod.z.object({Milestones:zod.z.record(zod.z.string(),Ee).nullish()}).passthrough();var _=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var Wm=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Gt=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:Wm.nullish()}).passthrough();var _m=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),sl=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),EquippedSlot:_m.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(a=>a),K=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),sl).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var be=a=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:a.nullish()}),mt=a=>zod.z.object({ServerTimeUtc:u,Items:zod.z.array(be(a)),Resources:w.nullish(),Inventory:K.nullish()});var Km={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},rl=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Qm=zod.z.object({}).passthrough().transform(a=>a),Hm=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:u.nullish(),CycleEndUtc:u.nullish(),PointsTotalEarned:j.nullish(),PointsCurrent:j.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:Ee.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Hr=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:rl}),ol=zod.z.object({State:Qm.nullish(),PointsTracks:zod.z.record(zod.z.string(),Hm).nullish()}),$r=zod.z.object({ServerTimeUtc:u,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:rl.nullish(),Resources:w.nullish(),Inventory:K.nullish()}),Jr=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:j.nullish(),Resources:w.nullish(),Inventory:K.nullish(),NextMilestone:Ee.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),al=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),ll=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(Hr).nullish()}),ul=zod.z.array(be($r)),cl=zod.z.array(be(Jr)),$m={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Jm=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Zm={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Ym=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),pl=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:Jm.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(it).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),Zr=zod.z.object({Milestones:_.nullish(),Linking:_.nullish(),Availability:_.nullish(),Reward:_.nullish(),Objectives:_.nullish()}).passthrough(),Xm=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(),dl=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:Ym.nullish()}).passthrough(),hl=zod.z.object({Schedule:de.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:$.nullish(),Limits:fe.nullish()}).passthrough(),ml=zod.z.object({Grant:Q.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),ef=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Xm.nullish(),Linking:dl.nullish(),Availability:hl.nullish(),Objectives:zod.z.record(zod.z.string(),pl).nullish(),Reward:ml.nullish(),Presets:Zr.nullish()}).passthrough(),tf=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:$.nullish(),Reward:Q.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),nf=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:$.nullish(),Milestones:zod.z.record(zod.z.string(),Ee).nullish(),Presets:Zr.nullish(),PointsToken:Gt.nullish()}).passthrough(),sf=zod.z.object({Milestones:zod.z.record(zod.z.string(),oi).nullish(),Linking:zod.z.record(zod.z.string(),dl).nullish(),Availability:zod.z.record(zod.z.string(),hl).nullish(),Reward:zod.z.record(zod.z.string(),ml).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),pl)).nullish()}).passthrough(),rf=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:de.nullish(),Milestones:zod.z.record(zod.z.string(),Ee).nullish(),Gate:$.nullish(),PointsToken:Gt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),tf).nullish(),Phases:zod.z.record(zod.z.string(),nf).nullish(),Presets:Zr.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Wi=zod.z.object({Cycles:zod.z.record(zod.z.string(),rf).nullish(),Quests:zod.z.record(zod.z.string(),ef).nullish(),Presets:sf.nullish()}).passthrough(),ct={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var of={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},af=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),lf={Never:"Never",OnRequest:"OnRequest",Always:"Always"},uf=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),cf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},pf=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),df={GameLoop:"GameLoop"},hf={Raid:"Raid",Attack:"Attack"},mf=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(),ff=zod.z.object({Mode:af.nullish(),Triggers:zod.z.array(it).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),gf=zod.z.object({Grant:Q.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),yf=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(),Rf=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:yf.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),Cf=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),Yr=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:mf.nullish(),Completion:ff.nullish(),Effects:gf.nullish(),Script:Rf.nullish(),Policy:Cf.nullish()}).passthrough(),Sf=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(),fl=zod.z.object({Schedule:de.nullish(),Gate:$.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:it.nullish()}).passthrough(),gl=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:uf.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),yl=zod.z.object({Grant:Q.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),xf=zod.z.object({Availability:_.nullish(),Policy:_.nullish(),Reward:_.nullish(),Steps:_.nullish()}).passthrough(),bf=zod.z.object({FlowID:zod.z.string().nullish(),Identity:Sf.nullish(),Availability:fl.nullish(),Policy:gl.nullish(),Steps:zod.z.record(zod.z.string(),Yr).nullish(),Reward:yl.nullish(),Presets:xf.nullish()}).passthrough(),Df=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(),Pf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:Df.nullish()}).passthrough(),vf=zod.z.object({Availability:zod.z.record(zod.z.string(),fl).nullish(),Policy:zod.z.record(zod.z.string(),gl).nullish(),Reward:zod.z.record(zod.z.string(),yl).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Yr)).nullish()}).passthrough(),Rl=zod.z.object({Flows:zod.z.record(zod.z.string(),bf).nullish(),Settings:Pf.nullish(),Presets:vf.nullish()}).passthrough(),If=zod.z.object({}).passthrough().transform(a=>a),Cl=zod.z.object({FlowID:zod.z.string(),Status:pf,CurrentStepID:zod.z.string().nullish(),CurrentStep:Yr.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(),_i=zod.z.object({State:If.nullish(),Flows:zod.z.array(Cl).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),kt=zod.z.object({Flow:Cl.nullish()}).passthrough(),Sl=zod.z.object({FlowID:zod.z.string().nullish(),Granted:w.nullish()}).passthrough(),xl=zod.z.array(be(kt)),bl=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),nt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Ki(a){return Array.isArray(a)?a.filter(e=>e!==null).map(Ki):a!==null&&typeof a=="object"?Object.fromEntries(Object.entries(a).filter(([,e])=>e!==null).map(([e,t])=>[e,Ki(t)])):a}var Qi=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var Hi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Dl(a){return a===429||a>=500&&a<=599}function $i(a,e=Math.random){let t=Math.min(500*Math.pow(2,a-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function li(a){return new Promise(e=>setTimeout(e,a))}function Pl(a,e=Math.random){let t=a<=1?1500:a===2?4e3:6e3;return t+t*.1*e()}var Xr=15,vl=1e3,Ji=class{constructor(e=Xr,t=()=>Date.now(),i=li){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]>=vl;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(vl-(e-this.starts[0])+5);}}};var zf=12e3,Tf=new Set(["RelatedEntityID"]);function kf(a,e){if(e===null||typeof e!="object"||Array.isArray(e))return a;let t={};for(let[i,n]of Object.entries(e))Tf.has(i)||(t[i]=n);try{return `${a}|${JSON.stringify(t)}`}catch{return a}}var Af=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(Hr).nullish(),TutorialProgress:zod.z.array(bl).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),Zi=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Hi;pacer;inFlightRequests=0;sessionRefreshHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new Qi(e.throttleMs),this.pacer=new Ji(e.maxRequestsPerSecond??Xr),this.clientPlatform=e.clientPlatform??ht.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}async post(e,t,i,n={}){let s=n.throttleKey??kf(e,t);if(!this.throttler.tryAcquire(s))return r("throttled","Throttled");if(!this.inflight.add(s))return r("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,c=JSON.stringify(t),d=n.ticket??null,R=n.silent??!1,V=n.timeoutMs??zf,se=n.autoRetry??!0,me=!1,xe=0;for(;;){let He;n.keepalive||await this.pacer.take();try{He=await this.doFetch(o,c,d,V,n.keepalive??!1);}catch{if(se&&xe<3){xe++,await li($i(xe));continue}return this.connectionFailure("Internet Connection Error",R)}let et=He.status;if(et>=200&&et<300)return await this.parseSuccess(He,i,R,e);if(et===401){if(!me&&this.sessionRefreshHandler){me=!0;let Yt=null;try{Yt=await this.sessionRefreshHandler();}catch{Yt=null;}if(Yt){d=Yt;continue}}return this.emitter.emit("auth:unauthorized",void 0),r("unauthorized","Unauthorized")}if(Dl(et)){if(se&&xe<3){xe++,await li(et===429?Pl(xe):$i(xe));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${et})`,R)}let zt="";try{zt=await He.text();}catch{}if(et===409&&/operation in progress/i.test(zt)&&se&&xe<3){xe++,await li($i(xe));continue}return this.handleWebError(zt,et,R)}}finally{this.inflight.remove(s),this.lowerBusy();}}async doFetch(e,t,i,n,s=false){let o=new AbortController,c=setTimeout(()=>{o.abort();},n);try{let d={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(d.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:d,signal:o.signal,...s?{keepalive:!0}:{}})}finally{clearTimeout(c);}}async parseSuccess(e,t,i,n){let s;try{s=await e.text();}catch{return this.globalError("Failed to read response body",i)}let o;try{o=JSON.parse(s);}catch{return this.globalError("JSON Parse Error",i)}let c=Af.safeParse(o);if(!c.success)return this.globalError("Malformed response envelope",i);if(!c.data.Success){let me=c.data.Error??"Server returned Success=false";return i||this.emitter.emit("error:global",me),r("server",me)}let d=c.data.StateVersions;d&&Object.keys(d).length>0&&this.emitter.emit("user:stateVersions",{epoch:c.data.StateEpoch??null,versions:d});let R=c.data.QuestProgress;R&&R.length>0&&this.emitter.emit("quest:systemProgress",R);let V=c.data.TutorialProgress;V&&V.length>0&&this.emitter.emit("tutorial:systemProgress",V);let se=t.safeParse(c.data.Data);if(!se.success){let me=t.safeParse(Ki(c.data.Data));me.success&&(se=me);}if(!se.success){let me=`Validation error (${n}): ${se.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",me),i||this.emitter.emit("error:global",me),r("validation",me)}return G(se.data)}handleWebError(e,t,i){let n=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),r("server","PLAY_ACCESS_REQUIRED");n=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{n=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",n),r("server",n)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),r("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),r("server",e)}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 ui(a){return (typeof a=="string"?a:a.toISOString()).slice(0,10)}function Di(a){return `${ui(a)}T00:00:00.000Z`}function Il(a){let e=new Date(a);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function zl(a,e){return new Date(a.getTime()+e*6e4).toISOString()}function to(a,e,t,i){let n={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return n;a.InventoryV2??={};let s=a.InventoryV2,o=i.toISOString(),c=new Map,d=new Map,R=new Map,V=new Map,se=new Map,me=new Map,xe=new Map,He=new Map,et=e.Grant?.PremiumTiers??[],zt=et.length;for(let De=0;;De++){let we,ce;if(De===0)we=e.Grant?.Standard?.Entries,ce=false;else if(De-1<zt)we=et[De-1]?.Resources?.Entries,ce=false;else if(De===1+zt)we=e.Consume?.Standard?.Entries,ce=true;else break;if(we)for(let re of we){if(re.Type==null)continue;let le=Math.max(0,re.Amount??0);if(!(le<=0))switch(re.Type){case "VirtualCurrency":{if(!re.CurrencyID)continue;let ue=ce?d:c;ue.set(re.CurrencyID,(ue.get(re.CurrencyID)??0)+le);break}case "CryptoCurrency":{if(!re.CurrencyID)continue;let ue=ce?V:R;ue.set(re.CurrencyID,(ue.get(re.CurrencyID)??new Nt__default.default(0)).plus(le));break}case "Item":{if(!re.ItemID)continue;let ue=Mf(t,re.CatalogID,re.ItemID),Re=(ue?ue.IsStackable??true:true)?ce?me:se:ce?He:xe;Re.set(re.ItemID,(Re.get(re.ItemID)??0)+le);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(n.vcChanged=c.size>0||d.size>0,n.vcChanged){s.VirtualCurrencies??={};for(let De of new Set([...c.keys(),...d.keys()])){let we=c.get(De)??0,ce=d.get(De)??0,re=we-ce,le=s.VirtualCurrencies[De];le?(le.Amount+=re,le.UpdatedAt=o,le.Daily&&ui(le.Daily.PeriodStartUtc)===ui(i)?(le.Daily.Earned+=we,le.Daily.Spent+=ce):le.Daily={PeriodStartUtc:Di(i),Earned:we,Spent:ce}):s.VirtualCurrencies[De]={Amount:re,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:Di(i),Earned:we,Spent:ce}};}}if(n.ccChanged=R.size>0||V.size>0,n.ccChanged){s.CryptoCurrencies??={};for(let De of new Set([...R.keys(),...V.keys()])){let we=R.get(De)??new Nt__default.default(0),ce=V.get(De)??new Nt__default.default(0),re=we.minus(ce),le=s.CryptoCurrencies[De];le?(le.Amount=new Nt__default.default(le.Amount).plus(re).toString(),le.UpdatedAt=o):s.CryptoCurrencies[De]={Amount:re.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(n.itemsChanged=se.size>0||me.size>0||xe.size>0||He.size>0,n.itemsChanged){s.Items??={},s.UnstackableItems??={};let De=s.UnstackableItems,we=new Set([...se.keys(),...me.keys(),...xe.keys(),...He.keys()]);for(let ce of we){let re=(se.get(ce)??0)-(me.get(ce)??0),le=(xe.get(ce)??0)-(He.get(ce)??0),ue=re+le,tt=s.Items[ce];tt?(re!==0&&(tt.StackableAmount+=re),le!==0&&(tt.UnstackableAmount+=le),ue!==0&&(tt.TotalAmount+=ue)):s.Items[ce]={StackableAmount:Math.max(0,re),UnstackableAmount:Math.max(0,le),TotalAmount:Math.max(0,ue)};}for(let[ce,re]of He){if(re<=0)continue;let le=Object.values(De).filter(ue=>ue.ItemID===ce&&ue.EquippedSlot==null&&(ue.ExpiresAt==null||new Date(ue.ExpiresAt)>i)).sort(wf).slice(0,re).map(ue=>ue.ItemInstanceID);for(let ue of le)delete De[ue];}for(let[ce,re]of xe){let le=Of(t,ce);for(let ue=0;ue<re;ue++){let tt=q();De[tt]={ItemInstanceID:tt,ItemID:ce,CatalogID:le,RemainingUses:1,AcquiredAt:o};}}}a.EventToken??={};let Yt=a.EventToken;for(let De=0;;De++){let we,ce;if(De===0)we=e.Grant?.Standard?.EventTokens,ce=false;else if(De-1<zt)we=et[De-1]?.Resources?.EventTokens,ce=false;else if(De===1+zt)we=e.Consume?.Standard?.EventTokens,ce=true;else break;if(!(!we||we.length===0))for(let re of we){let le=re.Address;if(!le||le.Type==null)continue;let ue=re.Amount??0;if(ue<=0)continue;let tt=Uf(Yt,le.Type);if(!tt)continue;let Re=tt[le.EntityID];Re||(Re={},tt[le.EntityID]=Re),Re.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Re.Daily??={Date:Di(i),TotalEarned:0},Re.Meta??={};let Ci=re.Source&&re.Source.length>0?re.Source:"CustomAction";ce?(Re.Balance.Current-=ue,Re.Balance.TotalSpent+=ue):(Re.Balance.Current+=ue,Re.Balance.TotalEarned+=ue,ui(Re.Daily.Date)!==ui(i)&&(Re.Daily={Date:Di(i),TotalEarned:0}),Re.Daily.TotalEarned+=ue,Re.Daily.EarnedBySource??={},Re.Daily.EarnedBySource[Ci]=(Re.Daily.EarnedBySource[Ci]??0)+ue,Re.Daily.TriggersBySource??={},Re.Daily.TriggersBySource[Ci]=(Re.Daily.TriggersBySource[Ci]??0)+1,Re.Daily.LastTriggerBySource??={},Re.Daily.LastTriggerBySource[Ci]=o,Re.Meta.JoinedAtUtc||(Re.Meta.JoinedAtUtc=o),Re.Meta.LastEarnedAtUtc=o),n.tokensChanged=true;}}return n}function wf(a,e){return a.AcquiredAt!==e.AcquiredAt?a.AcquiredAt<e.AcquiredAt?-1:1:a.ItemInstanceID===e.ItemInstanceID?0:a.ItemInstanceID<e.ItemInstanceID?-1:1}function Mf(a,e,t){let i=a?.Catalogs;if(i){if(e){let n=i[e]?.Items?.[t];if(n)return n}for(let n of Object.values(i)){let s=n.Items?.[t];if(s)return s}}}function Of(a,e){let t=a?.Catalogs;if(t){for(let[i,n]of Object.entries(t))if(n.Items&&e in n.Items)return i}}function Uf(a,e){switch(e){case "TimedEvent":return a.TimedEvent??={};case "Quest":return a.Quest??={};case "Leaderboard":return a.Leaderboard??={};case "CoopEvent":return a.CoopEvent??={};case "Season":return a.Season??={};default:return null}}function Tl(a,e,t){let i={drop:[],restore:{}};if(!t)return i;let n=t.ChangedInstances??{},s=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let d of Object.values(n))d?.ItemID&&o.add(d.ItemID);for(let d of s){let R=a[d]?.ItemID;R&&o.add(R);}if(o.size===0)return i;let c=d=>s.has(d)||d in n;if(e){for(let[d,R]of Object.entries(e))d in a||c(d)||R&&o.has(R.ItemID)&&i.drop.push(d);for(let[d,R]of Object.entries(a))d in e||c(d)||R&&o.has(R.ItemID)&&(i.restore[d]=R);}return i}function io(a,e){return a===e||a.startsWith(`${e}:`)}var Xi=class a{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){a.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];a.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){a.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let n=to(this.currentState,e,t,i);this.emitResourceChanges(n,false);}applyResourcesWithDelta(e,t,i,n=new Date){if(!this.currentState)return;let s=this.currentState,o={...s.InventoryV2?.UnstackableItems??{}},c=to(s,e,i,n),d=Tl(o,s.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],se=d.drop.length>0||Object.keys(d.restore).length>0||R.length>0||V.length>0;if(se){s.InventoryV2??={},s.InventoryV2.UnstackableItems??={};let me=s.InventoryV2.UnstackableItems;for(let xe of d.drop)delete me[xe];for(let[xe,He]of Object.entries(d.restore))me[xe]=He;for(let[xe,He]of R)me[xe]=He;for(let xe of V)delete me[xe];}this.emitResourceChanges(c,se);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,n){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let s=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof Nt__default.default?t:new Nt__default.default(t),c=n===void 0?new Nt__default.default(0):n instanceof Nt__default.default?n:new Nt__default.default(n),d=i??new Date().toISOString(),R=s[e];R?(R.Amount=new Nt__default.default(R.Amount).plus(o).toString(),c.isZero()||(R.Frozen=new Nt__default.default(R.Frozen??0).plus(c).toString()),R.UpdatedAt=d):s[e]={Amount:o.toString(),Frozen:c.toString(),CreatedAt:d,UpdatedAt:d},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let n=this.currentState.Store.Purchases,s=n[e];s||(s={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},n[e]=s),s.TotalPurchases+=t,s.LastPurchasedAt=i,i>=s.DailyResetUtc?(s.DailyPurchases=t,s.DailyResetUtc=Il(i)):s.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let n=this.currentState.Lootbox??={};if(n.Pity??={},t){let s=new Date().toISOString();for(let o of t)o.RuleID&&(n.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:s});}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 n=this.currentState.Quest;if(t){n.Cycles??={};let s=n.Cycles[t];if(!s)return;s.Quests??={};let o=s.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {n.PermanentQuests??={};let s=n.PermanentQuests[e]??={QuestID:e,Status:i};s.Status=i,i==="Claimed"&&(s.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let n=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,s=t[n]??={};s.Balance??={Current:0,TotalEarned:0,TotalSpent:0},s.Balance.Current=i.PointsCurrent??0,s.Balance.TotalEarned=i.PointsTotalEarned??0,s.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(s.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let n=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};n.Steps??={};let s=n.Steps[i.StepID]??={StepID:i.StepID};s.Progress=i.Progress,i.Completed&&(s.CompletedAtUtc??=new Date().toISOString(),n.CurrentStepID===i.StepID&&(n.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let n;if(!i.CycleID)t.PermanentQuests??={},n=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let s=t.Cycles[i.CycleID];if(!s)continue;s.Quests??={},n=s.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(n.Status=i.Status,i.ObjectiveID){n.Objectives??={};let s=n.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};s.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(s.Completed=true,s.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(n.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,n]of Object.entries(t))if(io(i,e)&&n)return n;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,n){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[s,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((n?s!==n:!io(s,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,n),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,n){let s=this.activeEventsCache?.ActiveEvents;if(s)for(let o of s)o.Type!==e||o.TimedEventID!==t||n&&o.TokenEntityID&&o.TokenEntityID!==n||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,n){if(!e)return;let s=this.ensureLeaderboardProgress(e);(s.ScoreCycleVersion??0)<n&&(s.ScoreEarnedThisCycle=0,s.ClaimedMilestoneIDs=[],s.BracketID=null),s.CurrentScore=t,s.ScoreEarnedThisCycle=(s.ScoreEarnedThisCycle??0)+i,s.ScoreCycleVersion=n,s.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let n=false;for(let s of Object.values(i))for(let o of Object.values(s.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,n=true);n&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,n=i[e];n||(n={CharacterID:e},i[e]=n),t(n),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let n=this.currentState?.Character?.Characters?.[e];n&&(n.Equipment??={},i===null?delete n.Equipment[t]:n.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[n,s]of Object.entries(e.ChangedInstances??{}))t[n]=s,i=true;for(let n of e.RemovedInstanceIDs??[])n in t&&(delete t[n],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let n=this.currentState.CoopEvent??={MyObjectIndex:-1};n.ActiveGroupID=e,n.ActiveCoopEventID=t,n.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let n of Object.keys(i)){let s=i[n];s&&s.BoostID===e.BoostID&&n!==e.InstanceID&&delete i[n];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,n,s){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,c={Value:i,UpdatedAt:new Date().toISOString(),Version:n,LastWriter:"Client",ExpiresAt:s??null};if(e==="Private")o.Private??={},o.Private[t]=c;else if(e==="Public")o.Public??={},o.Public[t]=c;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let n=i.BuildingStates.find(s=>s.SlotIndex===e);n||(n={SlotIndex:e},i.BuildingStates.push(n)),t(n),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let n=this.ensureBoard().Pending;n&&(e&&(n.RaidLayout=e),t>=0&&(n.OpenedIndices??=[],n.OpenedIndices.includes(t)||n.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let n of Object.values(e.CryptoBalances??{}))n?.CurrencyID&&this.patchCryptoCurrencyDelta(n.CurrencyID,n.AmountDelta,n.UpdatedAt,n.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let n=this.currentState.Blockchain??={},s=n.PendingWithdrawals??[];t.size>0&&(s=s.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!s.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(s=[...s,i]),n.PendingWithdrawals=s;}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 en=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);}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 tn=class{user;config;constructor(e){this.user=new Xi(e),this.config=new en;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Ef(a){return a}var Bf=0,qf=1500,Lf=3,sn=class{constructor(e,t,i=null,n="",s="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=n;this.loginMode=s;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}async ensureState(e,t){if(!this.state)return G(void 0);let i=Date.now(),n=[],s=[];for(let d of new Set(e)){let R=this.rules.get(d);if(R&&(t?.force||R.needsServer(i))){n.push(this.runRule(d,R));continue}(t?.force||!this.state.isStateFresh(d,t?.maxAgeMs))&&s.push(d);}let c=(await Promise.all([...n,s.length>0?this.queueSlice(s):Promise.resolve(G(void 0))])).find(d=>!d.ok);return c&&!c.ok?c:G(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let n=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,n),n}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},Bf),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(n=>i=n);try{let n=this.state?await this.state.readStateSlice(e):G(void 0),s=n.ok?G(void 0):n;for(let o of t)o(s);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let n=nn(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let R=this.fresh(n,i?.maxAgeMs);if(R)return G(R.data);let V=this.loginFailures.get(n);if(V)return this.loginFailures.delete(n),V;let se=this.inflight.get(n);if(se)return se}let s=this.generation.get(n)??0,o=Date.now(),d=t().then(R=>{if(!R.ok)return R;let V=Date.now();if((this.generation.get(n)??0)===s)return this.entries.set(n,{data:R.data,storedAt:V,expiresAt:no(e,R.data,V)}),R;let se=this.entries.get(n);if(se&&se.storedAt>=o)return R;let me=no(e,R.data,V);return this.entries.set(n,{data:R.data,storedAt:V,expiresAt:Math.min(me??1/0,V+qf)}),R}).finally(()=>{this.inflight.get(n)===d&&this.inflight.delete(n);});return this.inflight.set(n,d),d}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let n=t.Key?t.Key:void 0,s=nn(i.view,n);if(!t.Success){this.loginFailures.set(s,r("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(s),i.apply(o.data,n),this.put(i.view,o.data,n));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let n=e.login;this.loadUsed().then(()=>{let s=kl({Name:n,Key:t});this.used.get(s)?.n!==this.session&&(this.used.set(s,{Name:n,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>Lf||this.used.set(kl(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(n=>n&&typeof n.Name=="string"&&typeof n.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(nn(e,t))?.data}put(e,t,i){this.register(e);let n=nn(e,i);this.bump(n);let s=Date.now();this.entries.set(n,{data:t,storedAt:s,expiresAt:no(e,t,s)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let n of [...this.entries.keys(),...this.inflight.keys()])(n===i||n.startsWith(`${i}|`))&&this.drop(n);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let n=Date.now();if(!(i.expiresAt!==null&&n>=i.expiresAt)&&!(t!==void 0&&n-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(n=>t.has(n))&&this.invalidate(i);}};function nn(a,e){return e===void 0?a.key:`${a.key}|${e}`}function kl(a){return a.Key?`${a.Name}|${a.Key}`:a.Name}function no(a,e,t){let i=a.expiresAt?.(e)??null,n=a.ttlMs!==void 0?t+a.ttlMs:null;return i!==null&&n!==null?Math.min(i,n):i??n}var rn=class{constructor(e,t){this.storage=e;this.authTypeKey=`Saved_AuthType_${t}`,this.emailKey=`Saved_Auth_Email_${t}`,this.passwordKey=`Saved_Auth_Password_${t}`,this.refreshTokenKey=`Saved_Auth_RefreshToken_${t}`;}storage;authTypeKey;emailKey;passwordKey;refreshTokenKey;get lastAuthType(){let e=this.storage.getString(this.authTypeKey);return Gf(e)?e:Te.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 Gf(a){return a!==null&&Object.values(Te).includes(a)}var Nf=8,Vf=100,Ff=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,Al=["GameLoop"];function jf(a){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(a)}var on=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=Te.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let n=this.authContext;if(!n)return r("unauthorized","Not logged in.");let s=this.baseRequest();s.UserID=n.userID,s.ClientSessionTicket=n.clientSessionTicket,s.WalletAddress=e,s.NetworkID=t,i&&(s.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(s);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return r("unauthorized","Not logged in.");let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let n=await this.ctx.api.authentication.unlinkWallet(i);return n.ok&&n.data.PlayAccess&&this.setPlayAccess(n.data.PlayAccess),n}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.platform.getDeviceID(),e.Device=this.ctx.platform.getDeviceModel(),e.Platform=this.ctx.platform.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(Te.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return r("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(Te.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let n=await this.ctx.api.authentication.loginWithEmail(i);if(!n.ok)return n;this.applyAuthContext(n.data);let s=await this.fetchAndApplyClientState(Te.Email);return s.ok&&this.keepEmailCredentials(e,t),s}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.platform.getDeviceID(),i.Device=this.ctx.platform.getDeviceModel(),i.Platform=this.ctx.platform.getPlatform();let n=await this.ctx.api.authentication.registerWithEmail(i);return n.ok?(this.pendingRegistration={email:e,password:t},G({codeTtlMinutes:n.data.CodeTtlMinutes??0,resendCooldownSeconds:n.data.ResendCooldownSeconds??0})):n}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let n=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!n.ok)return n;this.applyAuthContext(n.data);let s=await this.fetchAndApplyClientState(Te.Email);return s.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,s}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?G(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(Te.Google)):i}async loginWithApple(e,t){if(!e?.trim())return r("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let n=await this.ctx.api.authentication.loginWithApple(i);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Te.Apple)):n}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.WalletAddress=e,n.NetworkID=t,n.WalletSignature=i,n.Platform=this.ctx.platform.getPlatform(),n.Device=this.ctx.platform.getDeviceModel(),n.DeviceID=this.ctx.platform.getDeviceID();let s=await this.ctx.api.authentication.loginWithWallet(n);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(Te.Wallet)):s}async loginWithSsoCode(e){if(!e)return r("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(Te.iDosGames)):i}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.Email=e,n.ResetToken=t,n.Password=i,this.ctx.api.authentication.resetPassword(n)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==Te.None?e:Te.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let n=await this.ctx.api.authentication.refreshSession(i);return n.ok?(this.applyRefresh(n.data),"ok"):(jf(n.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case Te.Email:return this.loginWithEmail(t,i);case Te.Device:case Te.None:return this.loginWithDeviceID();case Te.Telegram:return this.loginWithTelegram();default:return Promise.resolve(r("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==Te.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===Te.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&&Ff.test(e)}static isValidPasswordLength(e){return e.length>=Nf&&e.length<=Vf}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.sessionAuthType=Te.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e){let t=await this.ctx.userService.getClientStateExcept(Al,Al);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 Wf="idos:cfg",ci=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${wl(t)}`:e&&e.length>0?`f:${wl(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${Wf}:${this.titleId}:${e}`}};function wl(a){return [...a].map(e=>e.toLowerCase()).sort().join(",")}var Ml="idos:loc",pi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(n)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[n,s]of Object.entries(t))typeof s=="number"&&s>0&&(i[n]=s);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 `${Ml}:${this.titleId}:${e}`}versionsKey(){return `${Ml}:${this.titleId}:versions`}};var _f="idos:sec",an=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 `${_f}:${this.titleId}`}};var Kf="idos:state",ln=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,n){if(!(!e||!t))try{let s={e:t,v:i,s:n};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}keyOf(e){return `${Kf}:${this.titleId}:${e}`}};function Qf(a,e){if(!a)return;let t=new Set((e??[]).map(n=>n.trim().toLowerCase()));if(t.size===0)return a;let i={};for(let[n,s]of Object.entries(a))t.has(n.toLowerCase())||(i[n]=s);return i}function so(a,e,t,i){let n={...a??{}};if(!e||!t||!i)return n;for(let[s,o]of Object.entries(t))i[s]===o&&s in e&&(n[s]=e[s]);return n}function Hf(a){return {...a??{}}}function ro(a){return typeof a.StateEpoch=="string"&&a.StateEpoch.length>0?a.StateEpoch:null}var un=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let n=this.confirmedAt[e];return n===void 0?false:t===void 0||i-n<=t}versionsFor(e){if(!this.epoch)return;let t=Qf(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 s=Object.keys(this.versions);this.reset(e),this.notify(s);}return}let i=Date.now(),n=[];for(let[s,o]of Object.entries(t)){let c=this.versions[s];c!==o&&(c!==void 0&&o===c+1?(this.versions[s]=o,this.confirmedAt[s]=i):(delete this.versions[s],delete this.confirmedAt[s]),n.push(s),this.dirty=true);}this.notify(n);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=Hf(t);let n=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=n;this.dirty=true;let s=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&s.add(o);this.notify([...s]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),n=[];for(let[s,o]of Object.entries(t??{}))this.versions[s]!==o&&n.push(s),this.versions[s]=o,this.confirmedAt[s]=i;this.dirty=true,this.notify(n);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Ol=r("server","Title configuration is unavailable (CDN and API both failed)."),cn=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:q()}:null}get configCache(){return this.cache??=new ci(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new pi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new an(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;get stateStore(){return this.versionStore??=new un(new ln(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)}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=ci.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let n=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let s=await this.ctx.api.user.getClientState(e);if(!s.ok)return s;let o=await this.resolveTitleConfig(s.data,t,i,{Fields:e.TitleFields});return o==null?Ol:(this.finishStateHandshake(s.data,n),await this.restoreSections(s.data.TitleConfigVersion,o),await this.applyClientState(s.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(s.data.Views),await this.applyLocalization(s.data.Localization),await this.flushState(n),s)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let n=this.stateStore.versionsFor(t);if(n){e.KnownStateVersions=n;let s=this.stateStore.currentEpoch;s&&(e.KnownStateEpoch=s);}return {userId:i,cached:this.stateStore.cachedState,sent:n}}finishStateHandshake(e,t){let i=so(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let n=ro(e);!n||!t.userId||this.stateStore.afterFullRead(n,e.StateVersions);}async resolveTitleConfig(e,t,i,n){let s=e.TitleConfigVersion;if(i&&s&&i.v===s)return i.c;if(e.TitleConfigUrl){let c=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(c!=null)return s&&await this.configCache.write(t,s,c),c}let o=await this.fetchConfigFromApi(n);return o!=null?(s&&await this.configCache.write(t,s,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},n=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return n.ok?n.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.ExcludeFields=e,i.ExcludeTitleFields=t;let n=ci.scopeOf(null,t??[]),s=await this.configCache.read(n);s&&(i.KnownTitleConfigVersion=s.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let c=await this.ctx.api.user.getClientStateExcept(i);if(!c.ok)return c;let d=await this.resolveTitleConfig(c.data,n,s,{ExcludeFields:t??[]});return d==null?Ol:(this.finishStateHandshake(c.data,o),await this.restoreSections(c.data.TitleConfigVersion,d),await this.applyClientState(c.data,d,e,t),this.ctx.cache.acceptLoginViews(c.data.Views),await this.applyLocalization(c.data.Localization),await this.flushState(o),c)}async restoreSections(e,t){if(!e){this.ctx.data.config.setSectionSink(null);return}let i=t,n={};for(let[s,o]of Object.entries(await this.sectionCache.read(e)))i[s]==null&&(n[s]=o);this.ctx.data.config.restoreSections(n),this.ctx.data.config.setSectionSink((s,o)=>{i[s]!=null||o==null||(n[s]=o,this.sectionCache.write(e,n));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let n=await this.localizationCache.read(t);if(i<=0)return n?.t??null;if(n&&n.v===i)return n.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let s=await this.fetchLocalizationFromApi(t,n?.v??0);return s??n?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let n=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!n.ok)return null;let s=n.data;if(s.NotModified)return null;let o=s.Entries??{},c=s.Version??0,d=s.Locale??e;return c>0&&await this.localizationCache.write(d,c,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):r("unauthorized","Not logged in.")}async getUserState(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),n=await this.ctx.api.user.getUserState(t);if(!n.ok)return n;let s=so(n.data.User,i.cached,i.sent,n.data.StateVersions);n.data.User=s;let o=i.sent??{},c=Object.entries(n.data.StateVersions??{}).filter(([R,V])=>o[R]!==V||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(s,c);let d=ro(n.data);return d&&(this.stateStore.afterSliceRead(d,n.data.StateVersions),await this.flushState(i)),n}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.UsageTime=e,n.IsNewSession=t,n.SessionDurationSeconds=i;let s=await this.ctx.api.user.addUsageTime(n);return s.ok&&this.ctx.emitter.emit("user:usageTimeAdded",s.data),s}async deleteUserAccount(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,n){let s=i?.includes("GameLoop")===true,o=n?.includes("GameLoop")===true,c=s?this.ctx.data.user.state?.GameLoop:void 0,d=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;s&&R&&R.GameLoop==null&&(R.GameLoop=c);let V=this.ctx.data.config.titlePublicConfiguration;o&&V&&V.GameLoop==null&&(V.GameLoop=d),this.ctx.emitter.emit("user:clientStateReceived",e);}};var dn=class{constructor(e){this.ctx=e;}ctx;async convert(e,t,i,n,s,o){if(!t)return r("client","SourceID is required.");if(!n)return r("client","TargetID is required.");if(s<=0)return r("client","Amount must be positive.");if(e===i&&t===n)return r("client","Source and target must differ.");if(e===lt.Crypto||i===lt.Crypto)return r("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let c={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:String(Math.trunc(s)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${n}_${q()}`},d=await this.ctx.api.currency.convert(c);if(d.ok){let R=d.data,V={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.SourceID,Amount:R.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.TargetID,Amount:R.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return d}async cryptoConvert(e,t,i,n,s,o){let c=s instanceof Nt__default.default?s:new Nt__default.default(s);if(!t)return r("client","SourceID is required.");if(!n)return r("client","TargetID is required.");if(c.lte(0))return r("client","SourceAmount must be a positive decimal.");if(e===i&&t===n)return r("client","Source and target must differ.");if(e===lt.Virtual&&i===lt.Virtual)return r("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===lt.Virtual&&!c.isInteger())return r("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let d={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:c.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${n}_${q()}`},R=await this.ctx.api.currency.cryptoConvert(d);if(R.ok){let V=R.data,se=[],me=[];if(V.SourceType===lt.Virtual&&se.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===lt.Virtual&&me.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),se.length>0||me.length>0){let xe={Consume:se.length>0?{Standard:{Entries:se}}:null,Grant:me.length>0?{Standard:{Entries:me}}:null};this.ctx.data.user.applyResourceOperation(xe,this.ctx.data.config.itemDefinitions);}V.SourceType===lt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new Nt__default.default(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===lt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new Nt__default.default(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return R}};var hn=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let n=e.trim();if(!n)return r("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:n,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${n}_${q()}`};t&&t.length>0&&(s.FodderInstanceIDs=[...t]);let o=await this.ctx.api.item.upgradeLevel(s);return o.ok&&(this.ctx.data.user.patchEquippedItemLevel(o.data.ItemInstanceID??n,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 r("client","upgrades is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let n of i.data)n.Success&&n.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(n.Data.ItemInstanceID,n.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var Ul=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:Ct.nullish(),AllowedPlatforms:zod.z.array(Gi).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),oe=zod.z.record(zod.z.string(),Ul),$f=zod.z.object({Store:Ni,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var oo=zod.z.object({ServerTimeUtc:u,OfferID:zod.z.string(),Count:zod.z.number(),Resources:w.nullish(),Inventory:K.nullish()}),El=zod.z.array(be(oo)),Jf=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:u,LastPurchasedAt:u}),Zf=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:u}),Bl=zod.z.object({Purchases:zod.z.record(zod.z.string(),Jf).nullish(),Rotations:zod.z.record(zod.z.string(),Zf).nullish()}).passthrough().transform(a=>a),xt=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(),mn=zod.z.object({Schedule:de.nullish(),Gate:$.nullish()}).passthrough(),Yf={Fixed:"Fixed",Title:"Title",Player:"Player"},Xf=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:$.nullish()}).passthrough(),ql=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(Xf).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),eg=zod.z.object({Identity:_.nullish(),Availability:_.nullish(),Rotation:_.nullish()}).passthrough(),tg=zod.z.object({SlotID:zod.z.string().nullish(),Identity:xt.nullish(),Availability:mn.nullish(),Rotation:ql.nullish(),Presets:eg.nullish()}).passthrough(),ig=zod.z.object({Identity:_.nullish(),Availability:_.nullish()}).passthrough(),ng=zod.z.object({SectionID:zod.z.string().nullish(),Identity:xt.nullish(),Availability:mn.nullish(),Slots:zod.z.record(zod.z.string(),tg).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:ig.nullish()}).passthrough(),Ll=zod.z.object({Sections:zod.z.record(zod.z.string(),ng).nullish()}).passthrough(),sg=zod.z.object({Identity:_.nullish(),Availability:_.nullish(),Layout:_.nullish()}).passthrough(),rg=zod.z.object({StoreID:zod.z.string().nullish(),Identity:xt.nullish(),Availability:mn.nullish(),Layout:Ll.nullish(),Presets:sg.nullish()}).passthrough(),Gl=zod.z.object({Options:oe.nullish(),CompareAt:zod.z.record(zod.z.string(),Ct).nullish()}).passthrough(),Nl=zod.z.object({Grant:Q.nullish()}).passthrough(),Vl=zod.z.object({Schedule:de.nullish(),Gate:$.nullish(),Limits:fe.nullish()}).passthrough(),og=zod.z.object({Identity:_.nullish(),Pricing:_.nullish(),Reward:_.nullish(),Availability:_.nullish()}).passthrough(),ag=zod.z.object({OfferID:zod.z.string().nullish(),Identity:xt.nullish(),Pricing:Gl.nullish(),Reward:Nl.nullish(),Availability:Vl.nullish(),Presets:og.nullish()}).passthrough(),lg=zod.z.object({Identity:zod.z.record(zod.z.string(),xt).nullish(),Availability:zod.z.record(zod.z.string(),mn).nullish(),Layout:zod.z.record(zod.z.string(),Ll).nullish(),Rotation:zod.z.record(zod.z.string(),ql).nullish(),Pricing:zod.z.record(zod.z.string(),Gl).nullish(),Reward:zod.z.record(zod.z.string(),Nl).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Vl).nullish()}).passthrough(),fn=zod.z.object({Stores:zod.z.record(zod.z.string(),rg).nullish(),StoreOffers:zod.z.record(zod.z.string(),ag).nullish(),Presets:lg.nullish()}).passthrough(),ug=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:u.nullish()}).passthrough(),cg=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:Ct.nullish(),CompareAtCost:Ct.nullish(),DiscountPercent:zod.z.number().nullish(),IsFree:zod.z.boolean(),IsAdPaid:zod.z.boolean(),IsStorePaid:zod.z.boolean(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),pg=zod.z.object({OfferID:zod.z.string(),Identity:xt.nullish(),PriceOptions:zod.z.array(cg).nullish(),Rewards:Q.nullish(),State:ug.nullish()}).passthrough(),dg=zod.z.object({SlotID:zod.z.string(),Identity:xt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:u.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:pg.nullish()}).passthrough(),hg=zod.z.object({SectionID:zod.z.string(),Identity:xt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(dg).nullish()}).passthrough(),mg=zod.z.object({StoreID:zod.z.string(),Identity:xt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:u.nullish(),Sections:zod.z.array(hg).nullish()}).passthrough(),gn=zod.z.object({ServerTimeUtc:u,Stores:zod.z.array(mg).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Vt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront"},fg="OFFER_NOT_IN_ROTATION";var Fl="Store",jl={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:a=>{let e=null;for(let t of a.Stores??[])for(let i of t.Sections??[])for(let n of i.Slots??[]){let s=Date.parse(n.RefreshesAtUtc??"");!Number.isNaN(s)&&(e===null||s<e)&&(e=s);}return e}},yn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(jl,{schema:gn,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return r("client","OfferID is required.");if(t<1)return r("client","Count must be at least 1.");let n=this.ctx.auth.context;if(!n)return r("unauthorized","Not logged in.");let s={...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,RelatedEntityID:`store_buy_${e}_${n.userID}_${q()}`},o=await this.ctx.api.store.purchase(s);if(o.ok){let c=o.data;this.ctx.data.user.patchStorePurchase(e,t,c.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",c);}return o}async purchaseBatch(e){if(!e||e.length===0)return r("client","purchases is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let n=false;for(let s of i.data)!s.Success||!s.Data||!s.Data.OfferID||(this.ctx.data.user.patchStorePurchase(s.Data.OfferID,s.Data.Count,s.Data.ServerTimeUtc),!n&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(Fl,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.store.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Fl,n.data),this.ctx.emitter.emit("store:definitionsLoaded",n.data)),n}getStorefront(e){return this.ctx.cache.read(jl,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let n of i.Slots??[]){let s=n.RefreshesAtUtc;s&&(e===null||Date.parse(s)<Date.parse(e))&&(e=s);}return e}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Rn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?G(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return r("client","Receipt is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},s=await this.ctx.api.purchase.validatePurchase(n);return s.ok&&this.applyValidation(s.data),s}async buyWithTelegramStars(e,t){if(!e)return r("client","productID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},n=await this.ctx.api.purchase.createTelegramInvoice(i);return n.ok&&t?.open!==false&&this.ctx.platform.openInvoice(n.data.InvoiceLink),n}async validatePurchasesBatch(e){if(!e||e.length===0)return r("client","receipts is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let n of i.data.Items)n.Success&&n.Data&&this.applyValidation(n.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Cn=class{constructor(e){this.ctx=e;}ctx;get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t)if(i?.Type===Li.Purchase&&i.ProductID)return i.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t){if(i?.Type!==Li.CryptoCurrency||!i.CurrencyID)continue;let n=Number(i.Amount??0);if(!(n>0))continue;let s=this.cryptoBalance(i.CurrencyID);return s>=n?null:{currencyID:i.CurrencyID,required:n,available:s,missing:n-s}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var Wl="Lootbox",Sn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Wl,e);if(t){let s={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),G(s)}let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.lootbox.getDefinitions(i);if(n.ok){let s=n.data.LootboxDefinitions;s&&(this.ctx.data.config.patchSection(Wl,s),this.ctx.emitter.emit("lootbox:definitionsLoaded",s));}return n}async open(e,t,i,n){if(!e)return r("client","LootboxID is required.");if(t<1)return r("client","Count must be at least 1.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:n,RelatedEntityID:`lootbox_${e}_${i??"default"}_${q()}`},o=await this.ctx.api.lootbox.open(s);if(o.ok){let c=o.data;c.TriggeredPity&&c.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,c.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",c);}return o}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var ao="Reward";function lo(a){return a.length>0&&!a.includes(".")&&!a.includes("$")}var xn=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(ao)?.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(ao,e);if(t){let s={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),G(s)}let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.reward.getRewardDefinitions(i);if(n.ok){let s=n.data.RewardDefinitions;s&&(this.ctx.data.config.patchSection(ao,s),this.ctx.emitter.emit("reward:definitionsLoaded",s));}return n}async getUserRewardsState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${q()}`},n=await this.ctx.api.reward.claimDailyReward(i);if(n.ok){let s=n.data;this.ctx.data.user.patchDailyCalendarState(s.CalendarID,s.DailyState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",s);}return n}async collectIdleAccrual(e){if(!lo(e))return r("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${q()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let n=i.data;this.ctx.data.user.patchIdleAccrualState(n.AccrualID,n.IdleState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",n);}return i}async claimComebackReward(e){if(!lo(e))return r("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${q()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchComebackState(n.ComebackID,n.ComebackState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",n);}return i}async claimReward(e){if(!lo(e))return r("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${q()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchClaimRewardState(n.ClaimID,n.ClaimState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",n);}return i}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var bn="Tutorial",_l={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"]},Dn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(_l,{schema:_i,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(bn)?.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(bn,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.tutorial.getTutorialDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(bn,n.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",n.data)),n}getUserTutorialState(e=true,t){return this.ctx.cache.read(_l,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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}_${q()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return r("client","FlowID is required.");if(!t||t.length===0)return r("client","stepIDs is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${q()}`},s=await this.ctx.api.tutorial.completeStepsBatch(n);return s.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",s.data)),s}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 r("client","FlowID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${q()}`},n=await this.ctx.api.tutorial.claimFlowReward(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",n.data)),n}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let n=e?.trim();if(!n)return r("client","FlowID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),FlowID:n},o=await t(s);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,n){let s=e?.trim(),o=t?.trim();if(!s)return r("client","FlowID is required.");if(!o)return r("client","StepID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let c={...this.ctx.buildAuthedBaseRequest(),FlowID:s,StepID:o};n?.relatedEntityID&&(c.RelatedEntityID=n.relatedEntityID);let d=this.ctx.data.user.state?.Tutorial?.Flows?.[s]?.RewardClaimed===true,R=await i(c);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(s,o,d,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,i,n){return !i&&n.Flow?.RewardClaimed===true?true:n.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(bn)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Pn=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","campaignID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","campaignID is required.");if(!t)return r("client","walletAddress is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.CampaignID=e,n.WalletAddress=t,i&&(n.Amount=i);let s=await this.ctx.api.communityMarketing.withdrawCryptoReward(n);return s.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",s.data),s}async checkJoinEligibility(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Ae=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 gg={Global:"Global",Announcement:"Announcement",Group:"Group"},Ql=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),yg={None:"None",Language:"Language",Region:"Region"},Rg=zod.z.enum(["None","Language","Region"]).catch("None"),Cg={Anyone:"Anyone",Friends:"Friends"},Sg=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),xg={Reject:"Reject",Mask:"Mask"},bg=zod.z.enum(["Reject","Mask"]).catch("Reject"),Dg={Player:"Player",Publisher:"Publisher",System:"System"},Pg=zod.z.enum(["Player","Publisher","System"]).catch("Player"),vg={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Ig=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),Hl=zod.z.object({Gate:$.nullish(),Schedule:de.nullish()}).passthrough(),$l=zod.z.object({Gate:$.nullish(),Limits:fe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Jl=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),zg=zod.z.object({Availability:_.nullish(),Write:_.nullish(),Retention:_.nullish()}).passthrough(),Tg=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:Ig.nullish(),Type:Ql.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:Rg.nullish(),Capacity:zod.z.number().nullish(),Availability:Hl.nullish(),Write:$l.nullish(),Retention:Jl.nullish(),Presets:zg.nullish()}).passthrough(),kg=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:$.nullish(),WhoCanMessage:Sg.nullish(),Limits:fe.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),Ag=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:bg.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:fe.nullish()}).passthrough(),wg=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),Mg=zod.z.object({Availability:zod.z.record(zod.z.string(),Hl).nullish(),Write:zod.z.record(zod.z.string(),$l).nullish(),Retention:zod.z.record(zod.z.string(),Jl).nullish()}).passthrough(),Zl=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),Tg).nullish(),Direct:kg.nullish(),Moderation:Ag.nullish(),Polling:wg.nullish(),Presets:Mg.nullish()}).passthrough(),Og=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),Kl=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(),Og).nullish(),Limits:zod.z.record(zod.z.string(),Kl).nullish(),ReportLimits:Kl.nullish()}).passthrough();var uo=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),vn=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:Ae.nullish(),AuthorType:Pg.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),Ug=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:Ql.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(),In=zod.z.object({Channels:zod.z.array(Ug).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),Eg=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(vn).nullish(),NextCursor:uo.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Yl=zod.z.object({Rooms:zod.z.array(Eg).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Xl=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(vn).nullish(),NextBefore:uo.nullish()}).passthrough(),eu=zod.z.object({Message:vn.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),tu=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ae.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Bg=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ae.nullish(),LastMessage:vn.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),iu=zod.z.object({Conversations:zod.z.array(Bg).nullish()}).passthrough(),di=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:uo.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),nu=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),We={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 su="Chat",ru={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},zn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ru,{schema:In,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(su,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.chat.getChatDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(su,n.data),this.ctx.emitter.emit("chat:definitionsLoaded",n.data)),n}getChannels(e,t){return this.ctx.cache.read(ru,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let n of i.data.Rooms??[])n.NextCursor&&n.RoomID&&this.cursors.set(n.RoomID,n.NextCursor),n.Messages&&n.Messages.length>0&&this.ctx.emitter.emit("chat:messages",n);return i}async getHistory(e,t,i){let n=this.baseRequest();return n?(n.RoomID=e,t&&(n.Before=t),i&&(n.Limit=i),this.ctx.api.chat.getHistory(n)):r("unauthorized","Not logged in.")}async sendMessage(e,t,i){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.ChannelID=e,n.Text=t,i&&(n.Locale=i);let s=await this.ctx.api.chat.sendMessage(n);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async sendDirect(e,t){let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.Text=t;let n=await this.ctx.api.chat.sendMessage(i);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async openDirectChannel(e){let t=this.baseRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):r("unauthorized","Not logged in.")}async getConversations(){let e=this.baseRequest();return e?this.ctx.api.chat.getConversations(e):r("unauthorized","Not logged in.")}async markRead(e,t){let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let n=await this.ctx.api.chat.markRead(i);return n.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),n}async joinChannel(e){let t=this.baseRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):r("unauthorized","Not logged in.")}async leaveChannel(e){let t=this.baseRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):r("unauthorized","Not logged in.")}async reportMessage(e,t,i,n){let s=this.baseRequest();return s?(s.RoomID=e,s.MessageID=t,s.Reason=i,n&&(s.Comment=n),this.ctx.api.chat.reportMessage(s)):r("unauthorized","Not logged in.")}async ignoreUser(e){let t=this.baseRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):r("unauthorized","Not logged in.")}async unignoreUser(e){let t=this.baseRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):r("unauthorized","Not logged in.")}resetCursors(){this.cursors.clear();}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var qg={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},Lg=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),Gg={Player:"player",Title:"title",Creator:"creator"},hi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},ou=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),Ng=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),co=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:Lg.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(Ng).nullish()}).passthrough(),au=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(co).nullish()}).passthrough(),bt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var Pi=["https://idosgames.com","https://www.idosgames.com"];function lu(a){return a==="localhost"||a==="127.0.0.1"||a==="[::1]"||a.endsWith(".localhost")}function Vg(a){if(Pi.includes(a))return true;if(typeof window>"u"||!lu(window.location.hostname))return false;try{return lu(new URL(a).hostname)}catch{return false}}var Fg="IDOS_PLATFORM_PUSH_REQUEST",jg="IDOS_PLATFORM_PUSH_RESPONSE",Wg=12e4;function uu(a){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let n=false,s=d=>{n||(n=true,window.removeEventListener("message",o),clearTimeout(c),i(d));},o=d=>{let R=d?.data;!R||R.type!==jg||R.requestId!==t||Pi.includes(d.origin)&&s(R.ok===true);},c=setTimeout(()=>s(false),Wg);window.addEventListener("message",o);for(let d of Pi)try{e.postMessage({type:Fg,requestId:t,titleID:a},d);}catch{}})}var Tn=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.baseRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),n=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=n,i.ok&&this.ctx.emitter.emit("push:configLoaded",n),n}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return bt.Unsupported;if(this.isEmbedded())return bt.Embedded;if(!this.isSupported())return bt.Unsupported;let t=Notification.permission;return t==="denied"?bt.Blocked:t!=="granted"?bt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?bt.Subscribed:bt.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return r("client","Push notifications are not available for this title.");if(this.isEmbedded())return await uu(this.ctx.settings.titleID)?G({Where:"portal",Subscription:null}):r("client","The portal did not complete the subscription.");if(!this.isSupported())return r("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return r("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let n=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await n.pushManager.getSubscription()??await n.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:_g(t.PublicKey)}),c=this.baseRequest();if(!c)return r("unauthorized","Not logged in.");let d=o.toJSON();c.PushEndpoint=d.endpoint,c.PushP256dh=d.keys?.p256dh,c.PushAuth=d.keys?.auth,c.PushTransport="WebPush",c.PushLocale=e.locale??navigator.language,c.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(c);return R.ok?(this.ctx.emitter.emit("push:subscribed",R.data),G({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");if(this.isSupported()){let n=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();n&&(e.PushEndpoint=n.endpoint,await n.unsubscribe());}if(!e.PushEndpoint)return r("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.baseRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):r("unauthorized","Not logged in.")}async unsubscribeByHash(e){if(!e)return r("client","endpointHash is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};function _g(a){let e=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(a.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),n=new Uint8Array(i);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return i}var kn=Object.freeze({}),An=class{constructor(e){this.ctx=e;}ctx;table={...kn};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new pi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),n=this.lookup(i)??this.lookup(e);return n===void 0?this.onMissing(e):t?Kg(n,t):n}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...kn},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return r("unauthorized","Not logged in.");let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:n,table:s,fallbackLocale:o}=i.data,c=null;if(o){let d=await this.loadTableFromApi(o);d.ok&&(c=d.data.table);}return this.table=s,this.fallbackTable=c,this.currentFallbackLocale=o,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:o,entryCount:Object.keys(s).length}),{ok:true,data:n}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):r("unauthorized","Not logged in.")}reset(){this.table={...kn},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:q()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.Locale=e;let i=await this.cache.read(cu(e));i&&(t.KnownVersion=i.v);let n=await this.ctx.api.localization.getLocalizationTable(t);if(!n.ok)return n;let s=n.data,o=s.Locale??cu(e),c=s.Version??0;if(s.NotModified){let R=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:R?.t??{...kn},fallbackLocale:s.FallbackLocale??null}}}let d=s.Entries??{};return c>0&&await this.cache.write(o,c,d),{ok:true,data:{locale:o,table:d,fallbackLocale:s.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let n=this.pluralCategory(i),s=`${e}.${n}`;if(this.lookup(s)!==void 0)return s;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 Kg(a,e){return a.replace(/\{(\w+)\}/g,(t,i)=>{let n=e[i];return n===void 0?t:String(n)})}function cu(a){return a.trim().replace(/_/g,"-").toLowerCase()}var po="Quest",wn=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let n=e.cache.configSection(po)?.Cycles;if(!n)return false;let s=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(n)){let c=Date.parse(s[o]?.CycleEndUtc??"");if(Number.isNaN(c)){if(t===0)return true}else if(c<=i&&t<c)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true);return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(po,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.quest.getQuestDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(po,n.data),this.ctx.emitter.emit("quest:definitionsLoaded",n.data)),n}async getUserQuestState(e=true){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let n=i.data.State??{};this.ctx.data.user.applyQuest(n),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",n);}return i}async refreshQuestCycles(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","QuestID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n=t&&t.trim().length>0?t.trim():void 0,s={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:n,RelatedEntityID:`quest_claim_${n??""}_${i}_${q()}`},o=await this.ctx.api.quest.claimQuestReward(s);if(o.ok){let c=o.data;this.ctx.data.user.patchQuestStatus(c.QuestID,c.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",c);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return r("client","quests is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let n=false;for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchQuestStatus(s.Data.QuestID,s.Data.CycleID,"Claimed"),!n&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return r("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:n,RelatedEntityID:`milestone_claim_${i}_${n}_${q()}`},o=await this.ctx.api.quest.claimMilestoneReward(s);if(o.ok){let c=o.data;this.ctx.data.user.patchMilestoneClaimed(c.CycleID,c.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",c);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return r("client","milestones is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let n=false;for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchMilestoneClaimed(s.Data.CycleID,s.Data.MilestoneID),!n&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return r("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:n,RelatedEntityID:`group_completion_${i}_${n}_${q()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(s);if(o.ok){let c=o.data;this.ctx.data.user.patchGroupCompletionClaimed(c.CycleID,c.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",c);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return r("client","MetricID is required.");if(t<0)return r("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},s=await this.ctx.api.quest.addQuestProgress(n);return s.ok&&(this.ctx.data.user.patchQuestProgressUpdates(s.data.Updates),this.ctx.emitter.emit("quest:progressAdded",s.data)),s}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var pu=zod.z.object({}).passthrough().transform(a=>a);var Qg=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),Hg=zod.z.object({Schedule:zod.z.array(Qg).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),$g=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:u.nullish(),NextBonusStartUtc:u.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),Jg=zod.z.object({Milestones:_.nullish()}).passthrough(),ho=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:Gt.nullish(),TokenSources:zod.z.array(it).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),Ee).nullish(),Presets:Jg.nullish(),BonusWindow:Hg.nullish()}).passthrough(),Zg=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:ho.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Yg=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:de.nullish(),Content:ho.nullish(),Events:zod.z.array(Zg).nullish(),Gate:$.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Xg=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),ey=zod.z.object({Milestones:zod.z.record(zod.z.string(),oi).nullish()}).passthrough(),Mn=zod.z.object({Definitions:zod.z.record(zod.z.string(),Yg).nullish(),Settings:Xg.nullish(),Presets:ey.nullish()}).passthrough(),ty=zod.z.object({Type:bi,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:ho.nullish(),Progress:pu.nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:Ee.nullish(),BonusWindow:$g.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),On=zod.z.object({ActiveEvents:zod.z.array(ty).nullish()}).passthrough(),du=zod.z.object({Tokens:zod.z.record(zod.z.string(),pu).nullish()}),mo=zod.z.object({Type:bi.nullish(),LteID:zod.z.string().nullish(),Resources:w.nullish()}),fo=zod.z.object({Type:bi.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:w.nullish(),Inventory:K.nullish()}),iy=zod.z.object({Type:bi.nullish(),LteID:zod.z.string().nullish(),Resources:w.nullish()}),go=zod.z.array(be(fo)),hu=zod.z.array(be(mo)),mu=zod.z.array(be(iy)),rt={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var fu="TimedEvent",gu={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:a=>{let e=null;for(let t of a.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Un=class{constructor(e){this.ctx=e;e.cache.bindLoginView(gu,{schema:On,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(gu,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(fu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.timedEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(fu,n.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",n.data)),n}async getUserLteState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,n,s,o,c=1){if(!t)return r("client","LteID is required.");if(!i)return r("client","SourceType is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let d={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:n,AmountOverride:s,SourceParams:o,RollMultiplier:c},R=await this.ctx.api.timedEvent.grantTokens(d);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",R.data)),R}async spendTokens(e,t,i){if(!t)return r("client","LteID is required.");if(i<=0)return r("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},s=await this.ctx.api.timedEvent.spendTokens(n);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",s.data)),s}async claimMilestone(e,t,i){if(!t||!i)return r("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},s=await this.ctx.api.timedEvent.claimMilestone(n);if(s.ok){let o=s.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 s}async claimMilestonesBatch(e){if(!e||e.length===0)return r("client","milestones is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","spends is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let n=false;for(let s of i.data)!n&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(s.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return r("client","grants is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let n=false;for(let s of i.data)!n&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(s.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let n=i.Data;n.Type&&n.LteID&&n.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(n.Type,n.LteID,n.MilestoneID,n.TokenEntityID),!t&&n.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(n.Rewards,n.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var ny=zod.z.object({UserID:zod.z.string(),Score:j.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:u.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:Ae.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),vi=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:j.nullish(),CycleEndUtc:u.nullish(),TopUsers:zod.z.array(ny).nullish(),BracketID:zod.z.string().nullish()}),sy=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),MilestoneTokensEarned:j.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),En=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:Ee.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(sy).nullish()}),Bn=zod.z.object({LeaderboardID:zod.z.string(),NewScore:j,CycleVersion:zod.z.number()}),qn=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),Ln=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:w.nullish(),Inventory:K.nullish()}),yu=zod.z.array(be(vi)),Gn=zod.z.array(be(En)),Ru=zod.z.array(be(qn)),Cu=zod.z.array(be(Ln)),Su=zod.z.array(be(Bn)),ry=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:be(qn).nullish(),Milestones:zod.z.array(be(Ln)).nullish()}),xu=zod.z.array(ry),oy=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:be(vi).nullish(),Progress:be(En).nullish()}),bu=zod.z.array(oy),ay=zod.z.string(),Du=zod.z.object({Rank:zod.z.string().nullish(),Rewards:Q.nullish(),SeasonTierRewards:Qr.nullish()}).passthrough(),ly=zod.z.object({RankRewards:zod.z.array(Du).nullish()}).passthrough(),uy=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),cy=zod.z.object({Milestones:_.nullish(),RankRewards:_.nullish()}).passthrough(),py=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:ay.nullish(),Schedule:de.nullish(),ChainEvents:zod.z.array(uy).nullish(),Gate:$.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(Du).nullish(),Milestones:zod.z.record(zod.z.string(),Ee).nullish(),Presets:cy.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(it).nullish()}).passthrough(),dy=zod.z.object({Milestones:zod.z.record(zod.z.string(),oi).nullish(),RankRewards:zod.z.record(zod.z.string(),ly).nullish()}).passthrough(),Nn=zod.z.object({Definitions:zod.z.record(zod.z.string(),py).nullish(),Presets:dy.nullish()}).passthrough(),Ge={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 Pu="Leaderboard",vu={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"]},Vn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(vu,{schema:Gn,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Pu,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.leaderboard.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Pu,n.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",n.data)),n}async getLeaderboard(e){if(!e)return r("client","LeaderboardID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","LeaderboardID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","LeaderboardID is required.");if(t<=0)return r("client","Score must be positive.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},n=await this.ctx.api.leaderboard.submitScore(i);if(n.ok){let s=n.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),s.NewScore,t,s.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",s);}return n}async submitScoreFromSource(e,t,i,n,s=1){if(!e)return r("client","LeaderboardID is required.");if(!t)return r("client","SourceType is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:n,RollMultiplier:s},c=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(c.ok){let d=c.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),d.NewScore,d.NewScore,d.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",d);}return c}async claimCycleReward(e){if(!e)return r("client","LeaderboardID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",n);}return i}async claimMilestone(e,t,i){if(!e||!t)return r("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},s=await this.ctx.api.leaderboard.claimMilestone(n);if(s.ok){let o=s.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 s}async getFriendsLeaderboard(e){if(!e)return r("client","LeaderboardID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","leaderboardIDs is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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(r("client","leaderboardIDs is required.")):this.ctx.cache.read(vu,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(n.Data.LeaderboardID)),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return r("client","milestones is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(n.Data.LeaderboardID),n.Data.MilestoneID),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return r("client","scores is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(n.Data.LeaderboardID),n.Data.NewScore,n.Data.NewScore,n.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return r("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let n of i.data){let s=this.cycleDocID(n.LeaderboardID);n.CycleReward?.Success&&n.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(s),n.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.CycleReward.Data.Resources,n.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of n.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(s,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 r("client","leaderboardIDs is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let n of i.data)n.Progress?.Success&&n.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(n.LeaderboardID),n.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var yo=zod.z.object({}).passthrough().transform(a=>a),Fn=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>ku).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:j.nullish(),UserState:yo.nullish(),NextTier:zod.z.lazy(()=>Tu).nullish()}).passthrough(),Iu=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()}),Ro=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:w.nullish(),Inventory:K.nullish()}),zu=mt(Ro);var Tu=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:Q.nullish()}).passthrough(),ku=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(Tu).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var hy=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:de.nullish(),Seasons:zod.z.array(ku).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:$.nullish()}).passthrough(),jn=zod.z.object({Chains:zod.z.record(zod.z.string(),hy).nullish()}).passthrough(),wt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Au="Season",wu={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:a=>{let e=Date.parse(a.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Wn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(wu,{schema:Fn,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Au,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.season.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Au,n.data),this.ctx.emitter.emit("season:definitionsLoaded",n.data)),n}getActiveSeason(e,t){return e?this.ctx.cache.read(wu,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(r("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","SeasonChainID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","SeasonChainID is required.");if(t<=0)return r("client","Amount must be positive.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${q()}`},n=await this.ctx.api.season.grantStatusTokens(i);return n.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,n.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",n.data)),n}async claimTierReward(e,t){if(!e)return r("client","SeasonChainID is required.");if(t<=0)return r("client","TierNumber must be positive.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${q()}`},n=await this.ctx.api.season.claimTierReward(i);if(n.ok){let s=n.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",s);}return n}async claimTierRewardsBatch(e,t){if(!e)return r("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return r("client","TierNumbers is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${q()}`},s=await this.ctx.api.season.claimTierRewardsBatch(n);if(s.ok){let o=s.data;for(let c of o.Items??[]){let d=c.Data?.TierNumber;c.Success&&typeof d=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,d);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return s}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Mu="Premium",_n=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Mu,e);if(t){let s={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",s),G(s)}let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.premium.getDefinitions(i);return n.ok&&n.data.Premium&&(this.ctx.data.config.patchSection(Mu,n.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",n.data)),n}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},n=await this.ctx.api.premium.activateTrial(i);return n.ok&&(n.data.Premium&&this.ctx.data.user.applyPremium(n.data.Premium),this.ctx.emitter.emit("premium:trialActivated",n.data)),n}async purchaseItemOrCurrency(e,t,i="Default",n=1){if(!e||!t)return r("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:n,RelatedEntityID:`premium_purchase_${e}_${t}`},o=await this.ctx.api.premium.purchaseItemOrCurrency(s);if(o.ok){let c=o.data;c.Premium&&this.ctx.data.user.applyPremium(c.Premium),this.ctx.data.user.applyResourceOperation(c.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",c);}return o}async purchaseRealMoney(e,t,i,n,s,o,c,d){if(!e||!t)return r("client","PremiumID and TransactionID are required.");if(!n||!s)return r("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:n,ReceiptData:s,PurchaseToken:o,PackageName:c,AppStoreEnvironment:d,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(R);if(V.ok){let se=V.data;se.Premium&&this.ctx.data.user.applyPremium(se.Premium),this.ctx.data.user.applyResourceOperation(se.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",se);}return V}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Kn=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:u.nullish()}),Co=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(),Kn).nullish(),UpdatedAt:u.nullish()}).passthrough(),Ou=zod.z.object({Characters:zod.z.record(zod.z.string(),Co).nullish()}),So=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:w.nullish()}),xo=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:w.nullish()}),Uu=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Kn).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Eu=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),my=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Bu=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),my).nullish(),Inventory:K.nullish()}),bo=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:w.nullish()}),qu=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:w.nullish(),Inventory:K.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:Kn.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Lu=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Kn.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Gu=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),fy=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:u.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:oe.nullish()}),gy=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(fy).nullish()}),Nu=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),gy).nullish()}),Vu=mt(bo),Fu=mt(xo),ju=mt(So),Do=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),Wu=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:oe.nullish(),CostCurve:Le.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Le.nullish(),RankCurve:Le.nullish(),Requirements:zod.z.array(Do).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),yy=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Do).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(),_u=zod.z.object({Slots:zod.z.record(zod.z.string(),yy).nullish()}).passthrough(),Ku=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(),Ry=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),Cy=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:oe.nullish()}).passthrough(),Sy=zod.z.object({Stats:_.nullish(),Levels:_.nullish(),Equipment:_.nullish()}).passthrough(),Qu=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:Le.nullish()}).passthrough(),Po="@skin";function xy(a){return !!a&&a.startsWith("@")}var by=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),Dy=zod.z.object({PriceOptions:oe.nullish(),Schedule:de.nullish(),Gate:$.nullish()}).passthrough(),Py=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Do).nullish()}).passthrough(),vy=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Ku.nullish(),Item:by.nullish(),Sale:Dy.nullish(),Requirements:Py.nullish()}).passthrough(),Iy=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),vy).nullish()}).passthrough(),zy=zod.z.object({CharacterID:zod.z.string(),Identity:Ku.nullish(),Classification:Ry.nullish(),Unlock:Cy.nullish(),Presets:Sy.nullish(),Equipment:_u.nullish(),Stats:zod.z.record(zod.z.string(),Wu).nullish(),RankLadder:Qu.nullish(),RankStatCurve:Le.nullish(),StatMaxLevelCurve:Le.nullish(),Skins:Iy.nullish()}).passthrough(),Ty=zod.z.object({Stats:zod.z.record(zod.z.string(),Wu).nullish()}).passthrough(),ky=zod.z.object({RankLadder:Qu.nullish()}).passthrough(),Ay=zod.z.object({Equipment:_u.nullish()}).passthrough(),wy=zod.z.object({Stats:zod.z.record(zod.z.string(),Ty).nullish(),Levels:zod.z.record(zod.z.string(),ky).nullish(),Equipment:zod.z.record(zod.z.string(),Ay).nullish()}).passthrough(),Qn=zod.z.object({Definitions:zod.z.record(zod.z.string(),zy).nullish(),Presets:wy.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"},My="SKIN_ALREADY_OWNED";var vo="Character",Hn=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(vo)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([n,s])=>s?.Unlock?.UnlockedByDefault===true&&!i[s.CharacterID??n])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(vo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.character.getCharacterDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(vo,n.data),this.ctx.emitter.emit("character:definitionsLoaded",n.data)),n}async getUserCharacters(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","CharacterID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${q()}`},n=await this.ctx.api.character.unlockCharacter(i);if(n.ok){let s=n.data;this.ctx.data.user.patchCharacter(s.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},s.Power!=null&&(o.Power=s.Power),o.UpdatedAt=s.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(s.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",s);}return n}async upgradeStatLevel(e,t,i){if(!e||!t)return r("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${q()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},s=await this.ctx.api.character.upgradeStatLevel(n);if(s.ok){let o=s.data;this.ctx.data.user.patchCharacter(o.CharacterID,c=>{c.StatLevels??={},c.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(c.Power=o.Power),c.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return s}async upgradeCharacterLevel(e,t){if(!e)return r("client","CharacterID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${q()}`,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},n=await this.ctx.api.character.upgradeCharacterLevel(i);if(n.ok){let s=n.data;this.ctx.data.user.patchCharacter(s.CharacterID,o=>{o.Level=s.NewLevel,s.Power!=null&&(o.Power=s.Power),o.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(s.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",s);}return n}async equipItems(e,t){if(!e)return r("client","CharacterID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},n=await this.ctx.api.character.equipItems(i);return n.ok&&(this.applyEquipChangesLocally(e,n.data),this.ctx.emitter.emit("character:itemsEquipped",n.data)),n}async unequipItems(e,t){if(!e)return r("client","CharacterID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},n=await this.ctx.api.character.unequipItems(i);if(n.ok){let s=n.data;this.applyUnequipChangesLocally(e,s),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:s.ClearedSlotIDs??[],power:s.Power??null});}return n}async unequipAllCharacters(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${q()}`},s=await this.ctx.api.character.unlockSkin(n);if(s.ok){let o=s.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 s}async equipSkin(e,t,i){if(!e||!t)return r("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},s=await this.ctx.api.character.equipSkin(n);if(s.ok){let o=s.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return s}async unequipSkin(e){if(!e)return r("client","CharacterID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let n=i.data;n.Cleared&&(this.applyInventoryDelta(n.Inventory),this.applySkinLocally(n.CharacterID,null,n.Power,n.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",n);}return i}async getCharacterSkins(e){let t=this.baseRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):r("unauthorized","Not logged in.")}applySkinLocally(e,t,i,n){let s=this.ctx.data.user;s.patchCharacterEquipment(e,Po,t??null),s.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=n;});}async unlockCharactersBatch(e){if(!e||e.length===0)return r("client","characterIDs is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,s=>{s.Level??=1,s.StatLevels??={},s.Equipment??={},n.Power!=null&&(s.Power=n.Power),s.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return r("client","upgrades is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,s=>{s.Level=n.NewLevel,n.Power!=null&&(s.Power=n.Power),s.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(s.StatLevels??={},s.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return r("client","upgrades is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,s=>{s.StatLevels??={},s.StatLevels[n.StatID]=n.StatLevel,n.Power!=null&&(s.Power=n.Power),s.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[n,s]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,n,s);i.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let s of i)n.patchCharacterEquipment(e,s,null);n.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,n]of Object.entries(e.Characters??{})){for(let s of n.ClearedSlotIDs??[])t.patchCharacterEquipment(i,s,null);t.patchCharacter(i,s=>{n.Power!=null&&(s.Power=n.Power),s.UpdatedAt=e.ServerTimeUtc;});}}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Hu="Match",$n=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,n,s,o){let c=this.ctx.auth.context;if(!c)return r("unauthorized","Not logged in.");let d={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:n,TargetUserID:s,SelectedOptionID:o,RelatedEntityID:`pvp_create_${c.userID}_${q()}`},R=await this.ctx.api.match.createMatch(d);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 r("client","MatchID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},n=await this.ctx.api.match.updateMatch(i);return n.ok&&this.ctx.emitter.emit("match:updated",n.data),n}async cancelMatch(e){if(!e)return r("client","MatchID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,n){let s=this.ctx.auth.context;if(!s)return r("unauthorized","Not logged in.");let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:n,RelatedEntityID:`pvp_battle_${e}_${q()}`},c=await this.ctx.api.match.instantBattle(o);if(c.ok){let d=c.data,R=this.ctx.data.config.itemDefinitions;if(d.Resources)this.ctx.data.user.applyResourceOperation(d.Resources,R);else if(d.ResourcesDual){let V=d.ResourcesDual;V.FromUserID===s.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,R):V.ToUserID===s.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",d);}return c}async saveStrategy(e){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.Page=e,n.PageSize=t,n.Statuses=i;let s=await this.ctx.api.match.getMyMatches(n);return s.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",s.data),s}async getAvailableMatches(e=0,t=20,i=false){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.Page=e,n.PageSize=t,n.OnlyPublic=i;let s=await this.ctx.api.match.getAvailableMatches(n);return s.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",s.data),s}async getDefinitions(e){let t=this.ctx.cache.configSection(Hu,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.match.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Hu,n.data),this.ctx.emitter.emit("match:definitionsLoaded",n.data)),n}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var $u="Craft",Jn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection($u,e);if(t){let s={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),G(s)}let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.craft.getDefinitions(i);return n.ok&&n.data.CraftDefinitions&&(this.ctx.data.config.patchSection($u,n.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",n.data.CraftDefinitions)),n}async craft(e,t,i=1,n,s){if(!e)return r("client","CraftID is required.");let o=this.ctx.auth.context;if(!o)return r("unauthorized","Not logged in.");let c={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:n,InputInstanceIDs:s,RelatedEntityID:`craft_${e}_${o.userID}_${q()}`},d=await this.ctx.api.craft.craft(c);return d.ok&&(this.ctx.data.user.applyResourcesWithDelta(d.data.Resources,d.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",d.data)),d}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Mt=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(Mt),zod.z.record(zod.z.string(),Mt)]));var Ot={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Ju=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Ft={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Ii(a){return a!==Ft.Pending&&a!==Ft.Running}var Oy={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 Uy(a){return a?/\b(AI_[A-Z_]+)\s*:/.exec(a)?.[1]??null:null}var Ey=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),By=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),Zn=zod.z.object({GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Ju.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),Mt).nullish(),Assets:zod.z.array(Ey).nullish(),Error:By.nullish(),Charge:w.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reward:w.nullish(),Context:zod.z.record(zod.z.string(),Mt).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish()}),Zu=zod.z.object({Data:zod.z.array(Zn).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),qy=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(),Ly=zod.z.object({Modality:Ju.nullish(),Async:zod.z.boolean().nullish(),Limits:fe.nullish(),PriceOptions:oe.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:Q.nullish(),PromptVariables:zod.z.array(qy).nullish(),AllowFreePrompt:zod.z.boolean().nullish()}).passthrough(),Yu=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),Ly).nullish()}).passthrough(),qe={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 Xu="AI",Gy=/^[A-Za-z0-9_-]{1,128}$/,Ny=2e3,Vy=5e3,Fy=30*6e4;function jy(a,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(n),e?.removeEventListener("abort",i),t();},n=setTimeout(i,a);e?.addEventListener("abort",i,{once:true});})}var Yn=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(Xu,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.ai.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Xu,n.data),this.ctx.emitter.emit("ai:definitionsLoaded",n.data)),n}generateText(e,t,i){return this.generate(e,{Text:t},i,n=>this.ctx.api.ai.generateText(n))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,n=>this.ctx.api.ai.generateImage(n))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,n=>this.ctx.api.ai.editImage(n))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,n=>this.ctx.api.ai.generateVideo(n))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,n=>this.ctx.api.ai.generateAudio(n))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,n=>this.ctx.api.ai.generateMusic(n))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,n=>this.ctx.api.ai.generateThreeD(n))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.baseRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):r("unauthorized","Not logged in.")}async getGeneration(e){if(!e)return r("client","GenerationID is required.");let t=this.baseRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):r("unauthorized","Not logged in.")}isTerminal(e){return Ii(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let c=await this.getGeneration(e);if(!c.ok)return c;i=c.data;}else {if(!e?.GenerationID)return r("client","GenerationID is required.");i=e;}let n=Date.now()+(t.timeoutMs??Fy),s=Math.max(1,t.intervalMs??Ny),o=Math.max(s,t.maxIntervalMs??Vy);for(;!Ii(i.Status);){if(t.signal?.aborted)return r("client","Stopped waiting: the wait was aborted.");if(Date.now()+s>n)return r("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await jy(s,t.signal),t.signal?.aborted)return r("client","Stopped waiting: the wait was aborted.");let c=await this.pollFor(i);if(s=Math.min(o,Math.round(s*1.5)),!c.ok){if(c.reason==="connection")continue;return c}i=c.data,Ii(i.Status)||t.onUpdate?.(i);}return G(i)}pollFor(e){switch(e.Modality){case Ot.Text:return this.getText(e.GenerationID);case Ot.Image:return this.getImage(e.GenerationID);case Ot.Audio:return this.getAudio(e.GenerationID);case Ot.Music:return this.getMusic(e.GenerationID);case Ot.Video:return this.getVideo(e.GenerationID);case Ot.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,n){if(!e)return r("client","FeatureKey is required.");let s=i?.relatedEntityID;if(s!==void 0&&!Gy.test(s))return r("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:s??q()},c=await n(o);return c.ok&&(await this.reconcileCharge(c.data,true),this.emitView(c.data)),c}async poll(e,t){if(!e)return r("client","GenerationID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.GenerationID=e;let n=await t(i);return n.ok&&(await this.reconcileCharge(n.data,false),this.emitView(n.data)),n}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Ft.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===Ft.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Ft.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Io="Collection",Xn=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(Io),n=Object.keys(i?.Collections??{});if(n.length===0||t)return false;let s=e.cache.configSection("Season");return Object.values(s?.Chains??{}).some(c=>(c?.Seasons??[]).some(d=>!!d?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==n[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Io,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.collection.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Io,n.data),this.ctx.emitter.emit("collection:definitionsLoaded",n.data)),n}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,n){let s=this.ctx.auth.context;if(!s)return r("unauthorized","Not logged in.");let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,RelatedEntityID:`open_pack_${e}_${t}_${s.userID}_${q()}`},c=await this.ctx.api.collection.openPack(o);return c.ok&&(this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",c.data)),c}async openCollectionChest(e,t,i=1){let n=this.ctx.auth.context;if(!n)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${n.userID}_${q()}`},o=await this.ctx.api.collection.openCollectionChest(s);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 r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${q()}`},s=await this.ctx.api.collection.useCollectibleJoker(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",s.data)),s}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${q()}`},s=await this.ctx.api.collection.claimSetReward(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",s.data)),s}async claimSetRewardsBatch(e){if(!e||e.length===0)return r("client","sets is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let n=false;for(let s of i.data)!n&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${q()}`},n=await this.ctx.api.collection.claimGrandPrize(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",n.data)),n}async sendTradeOffer(e,t,i,n,s,o=false){let c=this.ctx.auth.context;if(!c)return r("unauthorized","Not logged in.");let d={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:n,RequestedCollectibleID:s,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${c.userID}_${n}_${q()}`},R=await this.ctx.api.collection.sendTradeOffer(d);return R.ok&&this.ctx.emitter.emit("collection:tradeOfferSent",R.data),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${q()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${q()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${q()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data),i}async getMyTradeOffers(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Wy=zod.z.object({}).passthrough().transform(a=>a),_y={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Ky={Active:"Active",Left:"Left",Replaced:"Replaced"},Qy=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),Hy=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ae.nullish(),BuildObjectsProgress:Qy.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),$y=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(),Jy=zod.z.object({Objects:zod.z.array($y).nullish()}).passthrough(),ec=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(Hy).nullish(),BuildObjectsState:Jy.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),tc=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>ic).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),Zy=zod.z.string(),zo=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(),Yy=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:Q.nullish()}).passthrough(),Xy=zod.z.object({Objects:zod.z.array(Yy).nullish(),PriceOptions:oe.nullish(),SpinnerTable:zod.z.array(zo).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),ic=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:Zy.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:Xy.nullish(),GrandPrize:Q.nullish()}).passthrough(),eR=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:de.nullish(),Events:zod.z.array(ic).nullish(),Gate:$.nullish()}).passthrough(),es=zod.z.object({ServerTimeUtc:u.nullish(),UserState:Wy.nullish(),ActiveGroup:ec.nullish()}),To=zod.z.object({ServerTimeUtc:u.nullish(),Group:ec.nullish(),SecondsRemaining:j.nullish()}),nc=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Resources:w.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:zo.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(zo).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),ko=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),sc=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),ts=zod.z.object({Chains:zod.z.record(zod.z.string(),eR).nullish()}).passthrough(),pt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var rc="CoopEvent",oc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},is=class{constructor(e){this.ctx=e;e.cache.bindLoginView(oc,{schema:es,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(rc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.coopEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(rc,n.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",n.data)),n}async getActiveEvent(e){if(!e)return r("client","CoopChainID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(oc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","GroupID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","CoopChainID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let n=i.data.Group;n&&this.ctx.data.user.patchCoopEventActiveGroup(n.GroupID??null,n.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,n){if(!e||!t)return r("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:n,RelatedEntityID:q()},o=await this.ctx.api.coopEvent.spin(s);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 r("client","GroupID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("client","GroupID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");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}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var tR={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},iR={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},nR=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:u.nullish(),CompletedAtUtc:u.nullish(),LastExecutedAtUtc:u.nullish(),NextAvailableAtUtc:u.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),sR=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),ac=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:u.nullish(),ExhaustedAtUtc:u.nullish(),ExpiredAtUtc:u.nullish(),DismissedAtUtc:u.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:u.nullish(),Nodes:zod.z.record(zod.z.string(),nR).nullish(),Tracks:zod.z.record(zod.z.string(),sR).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),rR=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:u.nullish(),ActiveOfferExpiresAtUtc:u.nullish(),ActiveOffer:ac.nullish(),NextCycleStartsAtUtc:u.nullish(),LastUpdatedUtc:u.nullish(),DismissSkipAvailableAtUtc:u.nullish(),LastDismissedAtUtc:u.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),oR=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),aR=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:u.nullish(),LastActivatedAtUtc:u.nullish(),LastExhaustedAtUtc:u.nullish(),NodeCounts:zod.z.record(zod.z.string(),oR).nullish()}).passthrough(),lR=zod.z.object({Slots:zod.z.record(zod.z.string(),rR).nullish(),OfferHistory:zod.z.record(zod.z.string(),aR).nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),uR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},cR={Eq:"Eq",Gte:"Gte",Lte:"Lte"},pR=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),ns=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(),lc=zod.z.object({Schedule:de.nullish(),Gate:$.nullish()}).passthrough(),uc=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),dR=zod.z.object({Identity:_.nullish(),Availability:_.nullish(),Behaviour:_.nullish()}).passthrough(),hR=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:ns.nullish(),Availability:lc.nullish(),Behaviour:uc.nullish(),Queue:zod.z.array(pR).nullish(),Presets:dR.nullish()}).passthrough(),mR=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),fR=zod.z.object({RewardedVideo:mR.nullish()}).passthrough(),gR=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),yR=zod.z.object({Identity:_.nullish(),Graph:_.nullish(),Milestones:_.nullish()}).passthrough(),RR=zod.z.object({Identity:_.nullish(),Pricing:_.nullish(),Reward:_.nullish()}).passthrough(),CR=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),SR=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(),xR=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(gR).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),cc=zod.z.object({Options:oe.nullish()}).passthrough(),pc=zod.z.object({Grants:Q.nullish(),TrackChanges:zod.z.array(CR).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),bR=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:ns.nullish(),Pricing:cc.nullish(),Reward:pc.nullish(),Action:fR.nullish(),UnlockRules:xR.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:fe.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:RR.nullish()}).passthrough(),dc=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(bR).nullish(),Tracks:zod.z.array(SR).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),hc=zod.z.object({Milestones:zod.z.record(zod.z.string(),Ee).nullish(),ClaimMode:zod.z.string().nullish(),Token:Gt.nullish()}).passthrough(),mc=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:ns.nullish(),Graph:dc.nullish(),Milestones:hc.nullish(),Presets:yR.nullish()}).passthrough(),DR=zod.z.object({Identity:zod.z.record(zod.z.string(),ns).nullish(),Availability:zod.z.record(zod.z.string(),lc).nullish(),Behaviour:zod.z.record(zod.z.string(),uc).nullish(),Graph:zod.z.record(zod.z.string(),dc).nullish(),Milestones:zod.z.record(zod.z.string(),hc).nullish(),Pricing:zod.z.record(zod.z.string(),cc).nullish(),Reward:zod.z.record(zod.z.string(),pc).nullish()}).passthrough(),Ao=zod.z.object({Slots:zod.z.record(zod.z.string(),hR).nullish(),Offers:zod.z.record(zod.z.string(),mc).nullish(),Presets:DR.nullish()}).passthrough(),fc=zod.z.object({DealOfferDefinitions:Ao.nullish()}),gc=zod.z.object({DealOffers:lR.nullish()}),PR=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(),vR=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:mc.nullish(),ActivationState:ac.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:u.nullish(),Cost:Ct.nullish(),Milestone:PR.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),ss=zod.z.object({Slots:zod.z.array(vR).nullish()}),yc=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),Rc=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:w.nullish()}),Cc=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:w.nullish()}),Sc=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),xc=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:w.nullish(),Inventory:K.nullish()}),gt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var IR="DealOffer",bc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},rs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(bc,{schema:ss,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(IR,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(bc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","SlotID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${q()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,n){if(!e||!t)return r("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,RelatedEntityID:s??`deal_exec_${e}_${t}_${q()}`},c=await this.ctx.api.dealOffer.executeNode(o);return c.ok&&(c.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",c.data)),c}async recordShow(e){if(!e)return r("client","SlotID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${q()}`},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 r("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${q()}`},n=await this.ctx.api.dealOffer.claimMilestone(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",n.data)),n}async claimMilestonesBatch(e,t){if(!e)return r("client","SlotID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${q()}`},s=await this.ctx.api.dealOffer.claimMilestonesBatch(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",s.data)),s}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Dc="Referral",os=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Dc,e);if(t){let s={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",s),G(s)}let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.referral.getDefinitions(i);return n.ok&&n.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Dc,n.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",n.data)),n}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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=Lt.parseReferralCode(e)?.toUpperCase();if(!t)return r("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},s=await this.ctx.api.referral.activateReferralCode(n);if(s.ok){let o=s.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return s}async claimInviteReward(e){let t=e.trim();if(!t)return r("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},s=await this.ctx.api.referral.claimInviteReward(n);if(s.ok){let o=s.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 s}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return r("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},s=await this.ctx.api.referral.claimInviteRewardsBatch(n);if(s.ok){let o=s.data;for(let c of o.Items??[])c.Success&&c.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(c.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return s}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var zR={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Pc=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),TR={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},kR=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),AR={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},wR=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),Ye={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},MR={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"},OR=100,UR=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),vc=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(),ER=zod.z.object({Texts:zod.z.record(zod.z.string(),UR).nullish(),Category:Pc.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:vc.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),BR=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:ae.nullish(),Cost:ae.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),SenderGate:$.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),qR=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(),LR=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(qR).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:ae.nullish(),SenderGate:$.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),Ic=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(),ER).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),BR).nullish(),Transfer:LR.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(),GR=zod.z.object({MessageID:zod.z.string(),Source:kR,Category:Pc,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:vc.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:Q.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:u,ExpiresAt:u.nullish(),ReadAt:u.nullish(),ClaimedAt:u.nullish()}).passthrough(),NR=zod.z.object({MessageID:zod.z.string(),Module:wR,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:Q.nullish()}).passthrough(),wo=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),zc=zod.z.object({ServerTimeUtc:u.nullish(),Messages:zod.z.array(GR).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(NR).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),as=zod.z.object({ServerTimeUtc:u.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Mo=zod.z.object({ServerTimeUtc:u.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(wo).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),VR=zod.z.object({MessageID:zod.z.string(),Rewards:ae.nullish()}).passthrough(),ls=zod.z.object({ServerTimeUtc:u.nullish(),Claimed:zod.z.array(VR).default([]),Failed:zod.z.array(wo).default([]),Resources:w.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Tc=zod.z.object({ServerTimeUtc:u.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(wo).default([]),Resources:w.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough(),kc=zod.z.object({ServerTimeUtc:u.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:u.nullish(),Resources:w.nullish(),RecipientReceives:ae.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),Ac=zod.z.object({ServerTimeUtc:u.nullish(),ResetsAt:u.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:u.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough().nullish()}).passthrough();var Oo="Mailbox",Uo={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},us=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Uo,{schema:as,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(Uo,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Oo)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Oo,e);if(t)return G(t);let i=this.request();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.mailbox.getDefinitions(i);return n.ok&&this.ctx.data.config.patchSection(Oo,n.data),n}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return r("unauthorized","Not logged in.");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(Uo,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");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 r("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):r("unauthorized","Not logged in.")}async claimRewards(e){let t=(e??[]).map(n=>n?.trim()).filter(Boolean);if(t.length===0)return r("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):r("unauthorized","Not logged in.")}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):r("unauthorized","Not logged in.")}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 r("unauthorized","Not logged in.");let n=await this.ctx.api.mailbox.deleteMessages(i);return n.ok&&this.emitCounters(n.data),n}async sendGift(e,t){if(!e?.trim())return r("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return r("client","Recipients are required.");let n=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!n)return r("unauthorized","Not logged in.");let s=await this.ctx.api.mailbox.sendGift(n);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",s.data)),s}async sendTransfer(e,t,i){if(!e?.trim())return r("client","RecipientUserID is required.");if(!i?.requestID?.trim())return r("client","requestID is required.");let n=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!n)return r("unauthorized","Not logged in.");let s=await this.ctx.api.mailbox.sendTransfer(n);return s.ok&&(s.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(s.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",s.data)),s}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):r("unauthorized","Not logged in.")}};var FR={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},jR={Title:"Title",Platform:"Platform"},wc=zod.z.object({UserID:zod.z.string(),PublicData:Ae.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),zi=zod.z.object({Friends:zod.z.array(wc).nullish()}),WR=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),Ti=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:wc.nullish(),Counters:WR.nullish()}),_R={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},KR={Like:"Like",Favorite:"Favorite"},QR={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},HR={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},$R={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},JR=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),ZR=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(JR).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),OccurredAt:u.nullish(),OwnerImpact:w.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),Mc=zod.z.object({Items:zod.z.array(ZR).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),ki=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),YR=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(),Ut=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:YR.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),Oc=zod.z.object({Items:zod.z.array(Ut).nullish()}).passthrough(),Eo={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},XR=zod.z.object({UserID:zod.z.string(),PublicData:Ae.nullish(),Mutual:zod.z.boolean().nullish(),Since:u.nullish()}).passthrough(),cs=zod.z.object({Items:zod.z.array(XR).nullish(),...Eo}).passthrough(),eC=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:u.nullish()}).passthrough(),Uc=zod.z.object({Items:zod.z.array(eC).nullish(),...Eo}).passthrough(),ps=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:Ae.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:u.nullish(),EditedAt:u.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Ec=zod.z.object({Items:zod.z.array(ps).nullish(),...Eo,TotalCount:zod.z.number().nullish()}).passthrough(),Bc=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),qc=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),Lc=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(),tC="FRIENDS_FROM_PLATFORM",iC={Off:"Off",Default:"Default",Always:"Always"},nC={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Gc=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish()}).passthrough(),ge={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 Bo={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},ds=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Bo,{schema:ki,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","TargetUserID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("client","RequesterUserID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("client","RequesterUserID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("client","FriendUserID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");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(Bo,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(Bo,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.baseRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):r("unauthorized","Not logged in.")}async getEntityStates(e,t){if(!t?.length)return r("client","EntityIDs are required.");let i=this.baseRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):r("unauthorized","Not logged in.")}async addComment(e,t,i,n){let s=this.targetRequest(e,t);if("ok"in s)return s;if(!i?.trim())return r("client","Text is required.");s.Text=i,s.ParentCommentID=n;let o=await this.ctx.api.social.addComment(s);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return r("client","CommentID is required.");if(!t?.trim())return r("client","Text is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.CommentID=e,i.Text=t;let n=await this.ctx.api.social.editComment(i);return n.ok&&this.ctx.emitter.emit("social:commentEdited",n.data),n}async deleteComment(e){if(!e)return r("client","CommentID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let n=this.targetRequest(e,t);return "ok"in n?n:(n.ParentCommentID=i.parentCommentID,this.applyPage(n,i.cursor,i.limit),this.ctx.api.social.getComments(n))}async report(e,t,i,n){let s=this.targetRequest(e,t);if("ok"in s)return s;if(!i)return r("client","ReportReason is required.");s.ReportReason=i,s.ReportComment=n;let o=await this.ctx.api.social.report(s);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,n){let s=this.targetRequest(t,i);if("ok"in s)return s;s.ReactionKind=n;let o=await this.ctx.api.social[e](s);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let n=this.baseRequest();return n?(this.applyPage(n,t,i),this.ctx.api.social[e](n)):r("unauthorized","Not logged in.")}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 r("client","EntityType is required.");if(!t)return r("client","EntityID is required.");let i=this.baseRequest();return i?(i.EntityType=e,i.EntityID=t,i):r("unauthorized","Not logged in.")}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Nc="TimedBoost";function sC(a){return a.length>0&&!a.includes(".")&&!a.includes("$")}var hs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Nc,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.timedBoost.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Nc,n.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",n.data)),n}async getActive(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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(!sC(i))return r("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${q()}`},s=await this.ctx.api.timedBoost.activate(n);if(s.ok){let o=s.data;if(o.ActivatedBoost){let c=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,c);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return s}async cleanupExpired(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Pt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},rC={Client:"Client",Server:"Server",System:"System"},oC=zod.z.enum(["Client","Server","System"]).catch("Client"),aC=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:oC.nullish(),ExpiresAt:u.nullish()}).passthrough(),ms=zod.z.record(zod.z.string(),aC),Vc=zod.z.object({Version:zod.z.number().nullish(),Private:ms.nullish(),Public:ms.nullish(),ReadOnly:ms.nullish()}),qo=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:ms.nullish()}),Lo=zod.z.object({ServerTimeUtc:u.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),lC=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),Fc=zod.z.object({ServerTimeUtc:u.nullish(),Results:zod.z.array(lC).nullish()}),jc=zod.z.object({ServerTimeUtc:u.nullish(),DeletedCount:zod.z.number().nullish()}),Wc=zod.z.object({Results:zod.z.array(qo).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),uC={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},cC=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),pC=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:cC.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),fs=zod.z.object({Keys:zod.z.record(zod.z.string(),pC).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(),dt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var dC="UserCustomData";function _c(a){return a.length>0&&!a.includes(".")&&!a.includes("$")}var gs=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(dC,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","TargetUserID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.TargetUserID=t;let n=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return n.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",n.data),n}async setPrivateData(e,t){return this.setData(e,t,Pt.Private)}async setPublicData(e,t){return this.setData(e,t,Pt.Public)}async setData(e,t,i){let n=e.trim();if(!_c(n))return r("client",'KeyID is required and must not contain "." or "$".');if(t==null)return r("client","Value is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Value:t},c=await(i===Pt.Private?this.ctx.api.userCustomData.setPrivateData(s):this.ctx.api.userCustomData.setPublicData(s));if(c.ok){let d=c.data;this.ctx.data.user.patchUserCustomDataKey(i,d.KeyID,t,d.Version??0,d.ExpiresAt),this.ctx.emitter.emit(i===Pt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",d);}return c}async deleteKey(e,t){let i=e.trim();if(!_c(i))return r("client",'KeyID is required and must not contain "." or "$".');if(t!==Pt.Private&&t!==Pt.Public)return r("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},s=await this.ctx.api.userCustomData.deleteKey(n);return s.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),s}async batchSet(e){if(!e.length)return r("client","At least one item is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let n of i.data.Results??[]){let s=n.Bucket??Pt.Private,o=e.find(c=>c.Bucket===s&&c.KeyID===n.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(s,n.KeyID,o.Value,n.Version??0,n.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return r("client","At least one item is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let n of e)this.ctx.data.user.removeUserCustomDataKey(n.Bucket,n.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return r("client","At least one target user id is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var hC="TitleCustomDataDefinitions",Kc=50;function mC(a){return a.length>0&&!a.includes(".")&&!a.includes("$")}function Go(a){if(a.ExpiresAt==null)return false;let e=Date.parse(a.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function fC(a){let e={};for(let[t,i]of Object.entries(a))Go(i)||(e[t]=i);return e}var ys=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(hC,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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(s=>s.trim()).filter(s=>s.length>0);if(!t.length)return r("client","At least one KeyID is required.");if(t.some(s=>!mC(s)))return r("client",'KeyID must not contain "." or "$".');if(t.length>Kc)return r("client",`At most ${Kc} keys per call \u2014 request them in chunks.`);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.KeyIDs=t;let n=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return n.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",n.data),n}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Go(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Go(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=fC(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);}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Rs=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var gC=15,yC="GameLoop",RC="BoardDefinition",Cs=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(yC,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");let i=await this.ctx.api.gameLoop.getBoardDefinition(t,e);return i.ok&&(this.ctx.data.config.patchSection(RC,i.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i.data)),i}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return r("client","stageLevel must be > 0.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.StageLevel=e;let n=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return n.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",n.data),n}async getUserBoardState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${q()}`},n=await this.ctx.api.gameLoop.boardLoopRoll(i);if(n.ok){let s=n.data,o=zl(new Date,gC);this.ctx.data.user.patchBoardState(c=>{c.Position=s.NewPosition,c.CyclesCompleted=(c.CyclesCompleted??0)+(s.CyclesCompletedDelta??0),c.LastRollAtUtc=new Date().toISOString(),s.ActionRequired&&s.ActionData?c.Pending={Type:s.ActionRequired,TargetUserID:s.ActionData.TargetUserID,TargetPublicData:s.ActionData.PublicData,TargetBuildingStates:s.ActionData.TargetBuildingStates??void 0,TargetHasShield:s.ActionData.TargetHasShield??void 0,RollMultiplier:s.UsedMultiplier??1,ExpiresAtUtc:o}:s.SpecialModeOffer&&(c.Pending={Type:"SPECIAL",RollMultiplier:s.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:s.SpecialModeOffer.ModeID??void 0,Choices:s.SpecialModeOffer.Choices??void 0}});}),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),s.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",s);}return n}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${q()}`},n=await this.ctx.api.gameLoop.boardLoopAttack(i);if(n.ok){let s=n.data;this.ctx.data.user.clearBoardPending(),s.IsBotTarget&&s.Operation?this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs):!s.IsBotTarget&&s.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(s.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",s);}else await this.getUserBoardState();return n}async boardLoopRaid(e,t){if(e<0||e>11)return r("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${q()}`},s=await this.ctx.api.gameLoop.boardLoopRaid(n);if(s.ok){let o=s.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 s}async boardLoopRaidFast(e){if(!e.length)return r("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${q()}`},n=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(n.ok){let s=n.data;s.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(s)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",s);}else await this.getUserBoardState();return n}async boardLoopBuild(e){if(e<0)return r("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${q()}`},n=await this.ctx.api.gameLoop.boardLoopBuild(i);if(n.ok){let s=n.data;s.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(s.BuiltIndex,o=>{s.NewLevel!=null&&(o.Level=s.NewLevel),o.IsDamaged=false,s.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",s);}return n}async boardSpecialChoose(e,t){if(!e)return r("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${q()}`},s=await this.ctx.api.gameLoop.boardSpecialChoose(n);if(s.ok){let o=s.data;o.Mode==="Instant"||o.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(d=>{d.ChoiceID=e,d.ChosenMode=o.Mode??"Timed",d.StartedAtUtc=o.StartedAtUtc??null,d.DurationSeconds=o.DurationSeconds??null,d.AdViewsUsed=0;}),o.Operation&&this.ctx.data.user.applyResourcesWithDelta(o.Operation,o.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",o);}return s}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${q()}`},n=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(n.ok){let s=n.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=s.AdViewsUsed??0,o.AccumulatedMultiplier=s.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",s);}return n}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${q()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},n=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(n.ok){let s=n.data;this.ctx.data.user.clearBoardPending(),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",s);}return n}async getCommunityChestState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");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 r("client","milestoneID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},n=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",n.data)),n}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");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);}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Ss=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,n){let s=e.trim();if(!s)return r("client","FunctionName is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:s,FunctionParameter:t,RevisionSelection:i,SpecificRevision:n},c=await this.ctx.api.cloudCode.execute(o);return c.ok&&this.ctx.emitter.emit("cloudCode:executed",c.data),c}};var Qc=zod.z.object({ServerTimeUtc:u,SourceType:si,SourceID:zod.z.string(),TargetType:si,TargetID:zod.z.string(),SourceSpent:j,FeeAmount:j,RateApplied:Y,TargetCredited:j}),Hc=zod.z.object({ServerTimeUtc:u,SourceType:si,SourceID:zod.z.string(),TargetType:si,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),xs={Convert:"Convert",CryptoConvert:"CryptoConvert"},CC={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},$c=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),SC={Automatic:"Automatic",Manual:"Manual"},xC=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),bC=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:u.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),DC=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),PC=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),vC=zod.z.object({TargetCurrencyType:si.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),Jc=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:xC.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(vC).nullish()}).passthrough(),Zc=zod.z.object({CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough(),IC=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:bC.nullish(),Recharge:DC.nullish(),Conversion:Jc.nullish(),Permissions:PC.nullish(),Audit:Zc.nullish(),Status:$c.nullish()}).passthrough(),zC=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(),TC=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),kC=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),AC=zod.z.object({Mode:zod.z.string().nullish(),FundingNetworkID:zod.z.string().nullish(),PerPlayerDailyTokens:zod.z.number().nullish(),TitleDailyTokens:zod.z.number().nullish()}).passthrough(),No=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:u.nullish(),DeveloperDepositSharePercent:Y.nullish(),CommunityMarketingDepositSharePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),Networks:zod.z.array(zC).nullish(),Limits:TC.nullish(),Permissions:kC.nullish(),Conversion:Jc.nullish(),Audit:Zc.nullish(),Status:$c.nullish(),ServerGrantPolicy:AC.nullish()}).passthrough(),bs=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),IC).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),No).nullish()}).passthrough();var wC={EVM:"EVM",Solana:"Solana"},MC=zod.z.enum(["EVM","Solana"]).catch("EVM"),OC={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},UC=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),EC={Token:"Token",Nft:"Nft"},Yc=zod.z.enum(["Token","Nft"]).catch("Token"),BC={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},qC=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),LC={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},GC=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),NC={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Vo=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),Xc={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Ds(a){let e=a?.trim();return e||Xc.GameTopUp}var VC={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},ep=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),FC=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(),tp=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),jC=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:MC.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:tp.nullish(),NftCollections:zod.z.array(FC).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(),WC=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:tp.nullish()}).passthrough(),_C=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),KC={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},QC=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),ip=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:QC.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),HC=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish()}).passthrough(),$C={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Ai=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),JC=zod.z.object({Mode:Ai.nullish(),TokenGates:zod.z.array(ip).nullish()}).passthrough(),Fo=zod.z.object({SystemState:WC.nullish(),Networks:zod.z.record(zod.z.string(),jC).nullish(),AccountSafety:_C.nullish(),WalletLogin:HC.nullish(),PlayAccess:JC.nullish(),IframeAllowedHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),ZC=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:u.nullish(),LastUsedAt:u.nullish(),LinkType:UC.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),np=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:Yc.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),YC=zod.z.object({Status:qC.nullish(),Tier:GC.nullish(),VerifiedAt:u.nullish(),ExpiresAt:u.nullish(),RejectedAt:u.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),XC=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:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),eS=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(),XC).nullish()}).passthrough(),tS=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),iS=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(),tS).nullish()}).passthrough(),nS=zod.z.object({Tokens:eS.nullish(),Nfts:iS.nullish()}).passthrough(),jo=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Et=zod.z.object({Granted:zod.z.boolean(),Mode:Ai.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:u.nullish(),Balances:zod.z.array(jo).nullish()}).passthrough(),sS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:u.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:u.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(jo).nullish()}).passthrough(),rS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),sp=zod.z.object({Mode:Ai.nullish(),TokenGates:zod.z.array(ip).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(rS).nullish(),Status:Et.nullish()}).passthrough(),oS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:u.nullish(),LoggedInAt:u.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(jo).nullish()}).passthrough(),aS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:u.nullish()}).passthrough(),lS=zod.z.object({Version:zod.z.number().nullish(),Stats:nS.nullish(),LinkedWallets:zod.z.record(zod.z.string(),ZC).nullish(),LastWalletLogin:oS.nullish(),PlayAccess:sS.nullish(),PendingWithdrawals:zod.z.array(np).nullish(),Kyc:YC.nullish(),FirstActivityAt:u.nullish(),LastActivityAt:u.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(aS).nullish()}).passthrough(),uS=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:u}).passthrough(),mi=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),uS).nullish(),PendingAdded:np.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),cS=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough().transform(a=>a),pS=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:ep.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Vo.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:u.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:u.nullish(),RefundCheckedAt:u.nullish()}).passthrough(),dS=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:ep.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Vo.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:u.nullish()}).passthrough(),rp=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Wo=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(rp).nullish(),Signature:zod.z.string().nullish()}).passthrough(),_o=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(rp).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(),op=zod.z.object({Blockchain:Fo.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),No).nullish()}).passthrough(),ap=zod.z.object({State:lS.nullish(),CryptoBalances:zod.z.record(zod.z.string(),cS).nullish()}).passthrough(),lp=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:mi.nullish()}).passthrough(),up=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:w.nullish(),Inventory:K.nullish()}).passthrough(),cp=zod.z.object({ServerTimeUtc:u.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:u.nullish(),EvmSignature:Wo.nullish(),SolanaSignature:_o.nullish(),StateDelta:mi.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),pp=zod.z.object({ServerTimeUtc:u.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:w.nullish(),EvmSignature:Wo.nullish(),SolanaSignature:_o.nullish(),StateDelta:mi.nullish(),Inventory:K.nullish()}).passthrough(),dp=zod.z.object({TokenTransactions:zod.z.array(pS).nullish(),NFTTransactions:zod.z.array(dS).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ko=zod.z.object({ServerTimeUtc:u.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(),hp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:Yc.nullish(),EvmSignature:Wo.nullish(),SolanaSignature:_o.nullish()}).passthrough(),mp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:Vo.nullish(),StateDelta:mi.nullish()}).passthrough(),_e={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 hS="Blockchain",Ps=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.blockchain.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(hS,t.data.Blockchain),this.ctx.emitter.emit("blockchain:definitionsLoaded",t.data)),t}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","NetworkID is required.");if(!t)return r("client","TransactionHash is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositToken(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",n.data)),n}async depositNFT(e,t){if(!e)return r("client","NetworkID is required.");if(!t)return r("client","TransactionHash is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositNFT(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",n.data)),n}async requestTokenWithdrawal(e,t,i,n,s){if(!e)return r("client","CurrencyID is required.");if(!t)return r("client","NetworkID is required.");if(!i)return r("client","WalletAddress is required.");if(!n)return r("client","Amount is required.");let o=this.baseRequest();if(!o)return r("unauthorized","Not logged in.");o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=n,o.Category=Ds(s);let c=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return c.ok&&(this.ctx.data.user.applyBlockchainStateDelta(c.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",c.data)),c}async requestNFTWithdrawal(e,t,i,n,s,o,c){if(!e)return r("client","ItemID is required.");if(!t)return r("client","NetworkID is required.");if(!i)return r("client","WalletAddress is required.");if(!n)return r("client","Amount is required.");let d=this.baseRequest();if(!d)return r("unauthorized","Not logged in.");d.ItemID=e,d.NetworkID=t,d.WalletAddress=i,d.Amount=n,d.Category=Ds(s),o!==void 0&&(d.Level=o),c&&(d.ItemInstanceID=c);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(d);return R.ok&&(this.ctx.data.user.applyBlockchainStateDelta(R.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",R.data)),R}async getTransactionHistory(e=50){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","TitleTransactionID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","TitleTransactionID is required.");if(!t)return r("client","On-chain TransactionHash is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.TitleTransactionID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.confirmWithdrawal(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",n.data)),n}async donateToDeveloper(e,t){if(!e)return r("client","NetworkID is required.");if(!t)return r("client","TransactionHash is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToDeveloper(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",n.data),n}async donateToUsersPool(e,t){if(!e)return r("client","NetworkID is required.");if(!t)return r("client","TransactionHash is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToUsersPool(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",n.data),n}async getPlayAccess(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var mS={Head:"Head",Torso:"Torso",Legs:"Legs"},vs=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),fS={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},Qo=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),gp=zod.z.object({AttackTarget:vs,DefenseTarget:vs});var gS=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),yS=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:vs.nullish(),DefenseZone:vs.nullish(),HitType:gS.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),RS=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(),CS=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(a=>a),fp=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:Co.nullish(),BattleStrategy:zod.z.array(gp).nullish(),UnstackableItems:zod.z.record(zod.z.string(),CS).nullish(),Stats:RS.nullish()}).passthrough(),SS=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:ae.nullish(),NetReward:ae.nullish(),BattleLog:zod.z.array(yS).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:fp.nullish(),P2BattleProfile:fp.nullish()}).passthrough(),yp=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:u.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(gp).nullish(),TargetUserID:zod.z.string().nullish(),Entry:ae.nullish(),CreationCostPaid:ae.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:u.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:u.nullish(),Status:Qo.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:u.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:u.nullish()}).passthrough(),Rp=zod.z.object({Status:Qo,MatchID:zod.z.string(),Entry:ae.nullish(),Resources:w.nullish()}),Cp=zod.z.object({Match:yp.nullish()}),Sp=zod.z.object({MatchID:zod.z.string(),Status:Qo,Resources:w.nullish()}),xp=zod.z.object({Battle:SS.nullish(),Resources:w.nullish(),ResourcesDual:St.nullish()}),Ho=zod.z.object({Matches:zod.z.array(yp).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),yt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var xS=zod.z.enum(["VirtualCurrency","Item","EventToken"]).catch("VirtualCurrency");var bS=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),DS=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(),PS=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),vS=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:PS.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),IS=zod.z.object({Kind:bS.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Le.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),zS=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(IS).nullish()}).passthrough(),jt=zod.z.object({Terms:zod.z.array(zS).nullish()}).passthrough(),TS=zod.z.object({Health:jt.nullish(),Damage:jt.nullish(),Armor:jt.nullish(),AttackSpeed:jt.nullish(),CritChance:jt.nullish(),CritDamage:jt.nullish(),Dodge:jt.nullish()}).passthrough(),bp=zod.z.object({StatMapping:DS.nullish(),Combat:vS.nullish(),Formula:TS.nullish()}).passthrough(),kS=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),wi=zod.z.object({Kind:xS.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:Vi.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),Dp=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),Allowed:zod.z.array(wi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Pp=zod.z.object({PriceOptions:oe.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:fe.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),AS=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:kS.nullish(),Entry:Dp.nullish(),Creation:Pp.nullish(),Settings:bp.nullish()}).passthrough(),wS=zod.z.object({Rules:zod.z.record(zod.z.string(),AS).nullish(),Defaults:bp.nullish(),EntryDefaults:Dp.nullish(),CreationDefaults:Pp.nullish()}).passthrough(),$o=zod.z.object({InstantBattle:wS.nullish()}).passthrough(),vp=$o;var MS={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Jo=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),OS={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Zo=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),US={Burn:"Burn",Ledger:"Ledger"},ES=zod.z.enum(["Burn","Ledger"]).catch("Burn"),zs={Item:"Item",VirtualCurrency:"VirtualCurrency"},Yo=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),BS=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish()}).passthrough(),Ts=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),Allowed:zod.z.array(wi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Xo=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish(),Sink:ES.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),BS).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),qS=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(),LS=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:fe.nullish(),BuyLimits:fe.nullish(),ListingFeeOptions:oe.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),GS=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:fe.nullish()}).passthrough(),NS=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:fe.nullish(),FillLimits:fe.nullish()}).passthrough(),VS=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:fe.nullish()}).passthrough(),FS=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),ea=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:$.nullish(),Schedule:de.nullish(),PricePolicy:Ts.nullish(),Commission:Xo.nullish(),Tradability:qS.nullish(),Listings:LS.nullish(),Auctions:GS.nullish(),BuyOrders:NS.nullish(),DirectTrades:VS.nullish(),Matching:FS.nullish()}).passthrough(),Ip=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:j.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:u.nullish()}).passthrough(),jS=zod.z.object({BidAxisType:ri.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(Ip).nullish()}).passthrough(),Is=zod.z.object({LastAt:u.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),WS=zod.z.object({Create:Is.nullish(),Buy:Is.nullish(),Sell:Is.nullish(),Bid:Is.nullish()}).passthrough(),_S=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),KS=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),EquippedSlot:_S.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(a=>a),vt=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Jo.nullish(),Status:Zo.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:Ae.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:Yo.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),GoodsInstances:zod.z.array(KS).nullish(),Price:ae.nullish(),Auction:jS.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),QS=zod.z.object({GoodsType:Yo.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(Jo,j).nullish()}).passthrough(),zp=zod.z.object({Definitions:ea.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),ta=zod.z.object({Offers:zod.z.array(vt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Tp=zod.z.object({Groups:zod.z.array(QS).nullish()}).passthrough(),kp=zod.z.object({Offer:vt.nullish()}).passthrough(),ot=zod.z.object({OfferID:zod.z.string().nullish(),Status:Zo.nullish(),Settlement:St.nullish(),Resources:w.nullish(),CommissionTaken:ae.nullish()}).passthrough(),Mi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:vt.nullish(),Resources:w.nullish(),Matched:zod.z.boolean().nullish(),Settlement:ot.nullish()}).passthrough(),Ap=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:j.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:w.nullish()}).passthrough(),ks=zod.z.object({MyOffers:zod.z.array(vt).nullish(),MyBids:zod.z.array(vt).nullish(),MyBuyOrders:zod.z.array(vt).nullish(),IncomingTrades:zod.z.array(vt).nullish(),OutgoingTrades:zod.z.array(vt).nullish(),Claimables:zod.z.array(vt).nullish(),DrainedRefunds:zod.z.array(Ip).nullish(),Limits:WS.nullish()}).passthrough(),HS=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Jo.nullish(),FinalStatus:Zo.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:Yo.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),PricePaid:ae.nullish(),CommissionTaken:ae.nullish(),CompletedAt:u.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),wp=zod.z.object({Entries:zod.z.array(HS).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),ve={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 $S="Marketplace",Mp={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"]},As=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Mp,{schema:ks,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection($S,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,n=20){if(!e)return r("client","ItemID is required.");let s=this.baseRequest();if(!s)return r("unauthorized","Not logged in.");s.ItemID=e,s.OfferTypeFilter=t,s.ContinuationToken=i,s.PageSize=n;let o=await this.ctx.api.marketplace.getOffersByItem(s);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return r("client","OfferID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.ItemID=e,n.ContinuationToken=t,n.PageSize=i;let s=await this.ctx.api.marketplace.getBuyOrders(n);return s.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",s.data),s}getMyState(e,t){return this.ctx.cache.read(Mp,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");i&&(n.HistoryFilter=i),n.ContinuationToken=e,n.PageSize=t;let s=await this.ctx.api.marketplace.getHistory(n);return s.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",s.data),s}async createListing(e,t,i,n,s,o,c){if(!e)return r("client","ItemID is required.");if(!t)return r("client","CatalogID is required.");if(!n)return r("client","PriceBundle is required.");let d=this.baseRequest();if(!d)return r("unauthorized","Not logged in.");d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.PriceBundle=n,d.DurationHours=s,d.ItemInstanceIDs=o,d.SelectedOptionID=c;let R=await this.ctx.api.marketplace.createListing(d);return this.applyCreateOfferResult(R,"marketplace:listingCreated"),R}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return r("client","OfferID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","GoodsAmount must be positive.");if(!t)return r("client","PriceBundle is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");let s=this.applyGoodsSelector(n,i);if(s)return s;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return r("client","GoodsAmount must be positive.");if(!t)return r("client","PriceBundle is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");let s=this.applyGoodsSelector(n,i);if(s)return s;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,n,s,o,c={}){if(!e)return r("client","ItemID is required.");if(!t)return r("client","CatalogID is required.");let d=this.baseRequest();if(!d)return r("unauthorized","Not logged in.");d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.BidAxisType=n,d.BidCurrencyID=c.bidCurrencyID,d.BidCatalogID=c.bidCatalogID,d.BidItemID=c.bidItemID,d.StartingBid=s,d.DurationHours=o,d.ItemInstanceIDs=c.itemInstanceIDs,d.SelectedOptionID=c.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(d);return this.applyCreateOfferResult(R,"marketplace:auctionCreated"),R}async placeBid(e,t){if(!e)return r("client","OfferID is required.");if(!t||t<=0)return r("client","BidAmount must be positive.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.OfferID=e,i.BidAmount=t;let n=await this.ctx.api.marketplace.placeBid(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",n.data)),n}async claimAuction(e){if(!e)return r("client","OfferID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,n,s){if(!e)return r("client","ItemID is required.");if(!t)return r("client","CatalogID is required.");if(!n)return r("client","PriceBundle is required.");let o=this.baseRequest();if(!o)return r("unauthorized","Not logged in.");o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=n,o.DurationHours=s;let c=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(c,"marketplace:buyOrderCreated"),c}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return r("client","OfferID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,n,s){if(!e)return r("client","TargetUserID is required.");if(!t)return r("client","CatalogID is required.");if(!i)return r("client","ItemID is required.");let o=this.baseRequest();if(!o)return r("unauthorized","Not logged in.");o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=n,o.RequestedBundle=s;let c=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(c,"marketplace:directTradeCreated"),c}async respondDirectTrade(e,t){if(!e)return r("client","OfferID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.OfferID=e,i.Accept=t;let n=await this.ctx.api.marketplace.respondDirectTrade(i);return n.ok&&(t&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",n.data)),n}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","OfferID is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.OfferID=e;let s=await t(n);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,s.data)),s}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=zs.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=zs.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):r("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);}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var ws=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return r("client","RoomName is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");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;let n=await this.ctx.api.multiplayer.createRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",n.data),n}async joinRoom(e,t){if(!e)return r("client","RoomID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.JoinCode=t;let n=await this.ctx.api.multiplayer.joinRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",n.data),n}async leaveRoom(e,t={}){if(!e)return r("client","RoomID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.SuccessorUserID=t.successorUserID;let n=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",n.data),n}async claimHost(e){if(!e)return r("client","RoomID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","RoomID is required.");if(!t)return r("client","TargetUserID is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.RoomID=e,n.TargetUserID=t,n.Ban=i;let s=await this.ctx.api.multiplayer.kickMember(n);return s.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",s.data),s}async unbanMember(e,t){if(!e)return r("client","RoomID is required.");if(!t)return r("client","TargetUserID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.TargetUserID=t;let n=await this.ctx.api.multiplayer.unbanMember(i);return n.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",n.data),n}async listRooms(e=0,t=20){let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.Page=e,i.PageSize=t;let n=await this.ctx.api.multiplayer.listRooms(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",n.data),n}async getRoom(e){if(!e)return r("client","RoomID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","RoomID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","RoomID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.LastSeq=t;let n=await this.ctx.api.multiplayer.poll(i);return n.ok&&this.ctx.emitter.emit("multiplayer:polled",n.data),n}async sendSignal(e,t,i,n){if(!e)return r("client","RoomID is required.");if(!t)return r("client","TargetUserID is required.");if(!i)return r("client","SignalKind is required.");let s=this.baseRequest();if(!s)return r("unauthorized","Not logged in.");s.RoomID=e,s.TargetUserID=t,s.SignalKind=i,s.Payload=n;let o=await this.ctx.api.multiplayer.sendSignal(s);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return r("client","RoomID is required.");if(!t)return r("client","ChatText is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.ChatText=t;let n=await this.ctx.api.multiplayer.sendChat(i);return n.ok&&this.ctx.emitter.emit("multiplayer:chatSent",n.data),n}async setMemberState(e,t,i){if(!e)return r("client","RoomID is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.RoomID=e,n.Ready=t,n.MemberState=i;let s=await this.ctx.api.multiplayer.setMemberState(n);return s.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",s.data),s}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Op=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Ms=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();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.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):r("unauthorized","Not logged in.")}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 r("client","CollectionID is required.");let t=this.baseRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):r("unauthorized","Not logged in.")}async getCreatorProfile(e,t,i){if(!e)return r("client","CreatorUserID is required.");let n=this.baseRequest();return n?(n.CreatorUserID=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getCreatorProfile(n)):r("unauthorized","Not logged in.")}async publish(e){if(!e.files||e.files.length===0)return r("client","At least one file is required.");let t=new Map,i=e.files.map((d,R)=>{if("sourceAssetUrl"in d)return {Role:d.role,ContentType:d.contentType,SourceAssetUrl:d.sourceAssetUrl};let V=Up(d.data,d.contentType);return t.set(R,V),{Role:d.role,ContentType:d.contentType,Size:V.size}}),n=e.thumbnail?Up(e.thumbnail.data,e.thumbnail.contentType):null,s=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,Files:i,Thumbnail:e.thumbnail&&n?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:n.size}:void 0});if(!s.ok)return s;let o=s.data.Uploads??[];for(let d=0;d<o.length;d++){let R=o[d];if(!R||R.ServerCopy||!R.Url)continue;let V=t.get(d);if(!V)return r("client",`No bytes for file #${d+1}.`);let se=await this.putBytes(R.Url,V,R.ContentType??V.type);if(!se.ok)return se}let c=s.data.ThumbnailUpload;if(c?.Url&&n){let d=await this.putBytes(c.Url,n,c.ContentType??n.type);if(!d.ok)return d}return this.publishUploaded({ContentID:s.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.baseRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):r("unauthorized","Not logged in.")}async publishUploaded(e){if(!e.ContentID)return r("client","ContentID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 n=await this.ctx.api.workshop.updateContent(i);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let n=this.baseRequest();return n?(n.ContentType=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getMyContent(n)):r("unauthorized","Not logged in.")}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let n=await this.ctx.api.workshop.acquire(i);return n.ok&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",n.data)),n}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let n of t.data.Files??[])if(n.Url)try{let s=await this.ctx.fetchImpl(n.Url);if(!s.ok)return r("connection",`Download failed (HTTP ${s.status}).`);i.push({role:n.Role??"main",contentType:n.ContentType??"application/octet-stream",data:await s.arrayBuffer()});}catch(s){return r("connection",`Download failed: ${s instanceof Error?s.message:String(s)}${Op}`)}return G({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.baseRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):r("unauthorized","Not logged in.")}async getMyFavorites(e,t){let i=this.baseRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):r("unauthorized","Not logged in.")}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?G(!0):r("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return r("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}${Op}`)}}contentRequest(e){if(!e)return r("client","ContentID is required.");let t=this.baseRequest();return t?(t.ContentID=e,t):r("unauthorized","Not logged in.")}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);}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};function Up(a,e){return a instanceof Blob?a:typeof a=="string"?new Blob([new TextEncoder().encode(a)],{type:e}):a instanceof Uint8Array?new Blob([a.slice().buffer],{type:e}):new Blob([a],{type:e})}var JS={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},ZS=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),YS={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Ep=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),XS={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Bp=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),ex={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},tx=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),ix={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},nx=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),sx={Count:"Count",Sum:"Sum"},rx=zod.z.enum(["Count","Sum"]).catch("Count"),ox={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},ax=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),lx={Strict:"Strict",Loose:"Loose"},ux=zod.z.enum(["Strict","Loose"]).catch("Strict"),cx=zod.z.object({Kind:nx,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),px=zod.z.object({Type:Ep,ItemType:Ep.nullish(),Ref:cx.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:Bp.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()}),dx=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Os=zod.z.object({Mode:tx,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),hx=zod.z.object({Read:zod.z.array(Os).nullish(),Create:zod.z.array(Os).nullish(),Update:zod.z.array(Os).nullish(),Delete:zod.z.array(Os).nullish()}),ia=zod.z.object({Cost:ae.nullish(),Grant:ae.nullish()}),mx=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()}),fx=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:ZS,Mode:ux.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),px).nullish(),SortKeys:zod.z.array(dx).nullish(),Access:hx.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:ax.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:rx,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:Bp.optional()})).nullish(),Economy:zod.z.object({OnCreate:ia.nullish(),OnUpdate:ia.nullish(),OnDelete:ia.nullish()}).nullish(),WriteGate:$.nullish(),PublicViews:zod.z.array(mx).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()}),qp=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),fx).default({})}),gx=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),Lp=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),fi=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(),gx).nullish()}),na=zod.z.object({Item:fi}),Gp=zod.z.object({Items:zod.z.array(fi).default([]),Missing:zod.z.array(zod.z.string()).default([])}),sa=zod.z.object({Items:zod.z.array(fi).default([]),NextCursor:zod.z.string().nullish()}),Np=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),ra=zod.z.object({Item:fi,AlreadyExists:zod.z.boolean().optional(),Economy:w.nullish()}),Vp=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:w.nullish()}),Fp=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),jp=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:fi.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),Wp=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),_p=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),Kp=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({})}),Qp=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(fi).default([])}),yx={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 Rx=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Jp=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,aa=100,Hp=25,$p=100;function Cx(a,e,t){return {Field:a,Op:e,Value:t}}var Us=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(r("unauthorized","Not logged in."))}get(e,t,i={}){let n=Xe(e)??Oi(t);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.get({...s,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let n=Xe(e);if(n)return Promise.resolve(n);let s=[...new Set(t.filter(o=>Jp.test(o)))];return s.length?s.length>$p?Promise.resolve(r("client",`At most ${$p} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:s,Expand:i.expand})):Promise.resolve(r("client","At least one valid item id is required."))}query(e,t={},i={}){let n=Xe(e)??oa(t);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.query({...s,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let n=Math.max(1,i.maxItems??500),s=[],o=t.Cursor;for(;;){let c=await this.query(e,{...t,Cursor:o,Limit:t.Limit??aa},i);if(!c.ok)return c;if(s.push(...c.data.Items),o=c.data.NextCursor??void 0,!o||s.length>=n)return G(s.slice(0,n))}}count(e,t={}){let i=Xe(e)??oa(t);return i?Promise.resolve(i):this.call(n=>this.ctx.api.dataCollections.count({...n,Collection:e,Query:t}))}create(e,t,i={}){let n=Xe(e)??(i.itemID?Oi(i.itemID):null);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.create({...s,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,n={}){let s=Xe(e)??Oi(t);return s?Promise.resolve(s):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:n.expectedVersion}))}set(e,t,i,n={}){return this.update(e,t,{Set:i},n)}increment(e,t,i,n=1){return this.update(e,t,{Inc:{[i]:n}})}delete(e,t,i={}){let n=Xe(e)??Oi(t);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.delete({...s,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(r("client","Operations are empty."));if(e.length>Hp)return Promise.resolve(r("client",`At most ${Hp} operations per batch.`));let t=e.map(i=>Xe(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let n=Xe(e);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.getCounter({...s,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,n){let s=Xe(e);return s?Promise.resolve(s):t?n>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:n})):Promise.resolve(r("client","File size must be positive.")):Promise.resolve(r("client","Field is required."))}async uploadFile(e,t,i,n={}){let s=n.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,s,i.size);if(!o.ok)return o;let c=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||s);return c.ok?o:c}async getPublicViews(e){let t=Xe(e);if(t)return t;let i=this.publicViews.get(e);if(i)return G(i);let n=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return n.ok&&this.publicViews.set(e,n.data),n}async readPublicView(e,t,i={}){let n=await this.getPublicViews(e);if(!n.ok)return n;let s=n.data.Views[t];if(!s)return r("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(s,Kp);if(!o.ok)return o;let c=o.data.Partitions[i.partition??""],d=Math.max(1,i.page??1);if(!c||d>c.Pages)return G({pointer:o.data,page:{Page:d,HasMore:false,Items:[]}});let R=await this.fetchJson(`${o.data.BaseUrl}${c.Segment}/page-${d}.json`,Qp);return R.ok?G({pointer:o.data,page:R.data}):R}getPublic(e,t){let i=Xe(e)??Oi(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=Xe(e)??oa(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(r("unauthorized","Not logged in."))}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?G(!0):r("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return r("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return r("connection","Internet Connection Error")}if(!i.ok)return r("server",`CDN answered ${i.status}.`);let n;try{n=await i.json();}catch{return r("server","CDN answer is not JSON.")}let s=t.safeParse(n);return s.success?G(s.data):r("server","CDN answer has an unexpected shape.")}};function Xe(a){return Rx.test(a??"")?null:r("client",`Collection id '${a}' is invalid (letters, digits, '_', '-', ':').`)}function Oi(a){return Jp.test(a??"")?null:r("client",`Item id '${a}' is invalid.`)}function oa(a){return a.Limit!=null&&(a.Limit<1||a.Limit>aa)?r("client",`Limit must be 1..${aa}.`):(a.Where?.length??0)>8?r("client","At most 8 filters per query."):null}var la={Open:"Open",Declared:"Declared"},Sx=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),xx=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),Zp=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Sx).nullish(),Dimensions:zod.z.array(xx).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),Bt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Rt={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Es=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,bx={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},Dx=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),Yp=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(Dx).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),ua={LogEvents:"LogEvents"};function Xp(a,e=0){let t=a??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let c=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:c==="iPad"?"tablet":"phone",deviceModel:c}}let n=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(n){let c=(n[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:n[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:c&&c!=="K"&&c!=="wv"?c:void 0}}let s=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(s)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(s[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 ed(a){let e=typeof navigator>"u"?void 0:navigator,t=Xp(e?.userAgent??"",e?.maxTouchPoints??0),i={};a.appVersion&&(i.AppVersion=a.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let n=a.locale||e?.language;return n&&(i.Language=n),i}var Px=25,vx=3e4,td=1800*1e3,id=500,Ix=5,zx=1e3,Tx=3600*1e3,nd="idos_analytics_queue",ca="idos_analytics_pending",pa="idos_analytics_opt_out",sd="idos_analytics_first_open",rd="idos_analytics_last_activity",od="idos_analytics_last_context",ad="idos_analytics_owner",Bs=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!Es.test(e)?r("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):kx(e)?r("client",`Event name "${e}" uses a reserved prefix (${Rt.reservedPrefixes.join(", ")}).`):this.enqueue(e,t,i,false)}logScreenView(e,t){if(!e)return r("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Bt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return G(null);if(this.config()?.Enabled===false)return this.clear(),G(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return G(null);this.pending={BatchID:q(),Events:this.queue.splice(0,Rt.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return r("unauthorized","Not logged in.");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>=Ix)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(pa);return}this.write(pa,"1"),this.clear();}get isEnabled(){return this.read(pa)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(ad);e&&t&&t!==e&&this.clear(),e&&this.write(ad,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},vx),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(rd)??"0");this.read(sd)||(this.write(sd,new Date().toISOString()),this.enqueue(Bt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(od);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Bt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Bt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(od,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=td)&&this.enqueue(Bt.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>=td&&this.enqueue(Bt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,n){if(!this.isEnabled||this.disabledByServer)return G(null);let s=this.config();if(s?.Enabled===false)return G(null);if(n&&s?.AutomaticEvents===false)return G(null);if(s?.Events?.[e]?.Blocked)return r("client",`Event "${e}" is blocked by the title.`);if(!n&&s?.EventNaming?.toLowerCase()===la.Declared.toLowerCase()&&!s.Events?.[e])return r("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return r("client","value must be a finite number.");let o=Ax(t);if(o.error)return r("client",o.error);this.restore();let c={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(c.Params=o.params),i!==void 0&&(c.Value=i),this.queue.push(c),this.queue.length>id&&this.queue.splice(0,this.queue.length-id),this.touch(),this.persist(),this.started&&this.queue.length>=Px&&this.flush(),G(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},zx));}dropStale(){let e=Date.now()-(Rt.maxEventAgeMs-Tx);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??=ed({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(ca);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(ca,this.pending):this.remove(ca);}touch(){this.write(rd,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 kx(a){let e=a.toLowerCase();return Rt.reservedPrefixes.some(t=>e.startsWith(t))}function Ax(a){if(!a)return {};let e=Object.keys(a);if(e.length===0)return {};if(e.length>Rt.maxParams)return {error:`Too many parameters: ${e.length}, max ${Rt.maxParams}.`};let t={};for(let i of e){if(!Es.test(i))return {error:`Invalid parameter name "${i}".`};let n=a[i];typeof n=="string"?t[i]=n.length>Rt.maxStringValueLength?n.slice(0,Rt.maxStringValueLength):n:typeof n=="number"?Number.isFinite(n)&&(t[i]=n):typeof n=="boolean"&&(t[i]=n);}return {params:t}}var wx="idos_experiments",qs=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 r("unauthorized","Not logged in.");let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let n=this.getParams(e)[t];if(n===void 0)return i;if(typeof i=="number"){let s=Number(n);return n.trim()!==""&&Number.isFinite(s)?s:i}if(typeof i=="boolean"){let s=n.trim().toLowerCase();return s==="true"||s==="1"?true:s==="false"||s==="0"?false:i}return n}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let n of e.Experiments??[])n?.ExperimentID&&t.set(n.ExperimentID,n);let i=[];for(let[n,s]of t){let o=this.views.get(n);(!o||o.VariantID!==s.VariantID||o.Status!==s.Status)&&i.push(s);}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 `${wx}:${this.ctx.settings.titleID}`}};function E(a,e,t,i){let s=`api/v2/${a&&a.length>0?a:"0"}/Client/${e}/${t}`;return i==null?s:`${s}/${i}`}var Ls=class{constructor(e){this.ctx=e;}ctx;logEvents(e){let t=E(this.ctx.settings.titleID,"Analytics",ua.LogEvents,e.UserID??"");return this.ctx.transport.post(t,e,Yp,{ticket:e.ClientSessionTicket,silent:true})}};var Mx=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(),Ox={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Ux=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),Ex=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:de.nullish(),Gate:$.nullish(),Variants:zod.z.array(Mx).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(Ux).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),ld=zod.z.object({Experiments:zod.z.record(zod.z.string(),Ex).nullish()}).passthrough(),Bx={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},qx=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(),ud=zod.z.object({Experiments:zod.z.array(qx).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),da={GetExperiments:"GetExperiments"};var Gs=class{constructor(e){this.ctx=e;}ctx;getExperiments(e){let t=E(this.ctx.settings.titleID,"Experiment",da.GetExperiments,e.UserID??"");return this.ctx.transport.post(t,e,ud,{ticket:e.ClientSessionTicket})}};var cd=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:u.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,PlayAccess:Et.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:u.nullish()}),pd=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,RefreshToken:zod.z.string(),RefreshTokenExpiration:u.nullish(),PlayAccess:Et.nullish()}),Lx=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),dd=zod.z.object({Google:zod.z.object({Enabled:zod.z.boolean().nullish(),WebClientID:zod.z.string().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:Ai.nullish(),WalletLoginNetworks:zod.z.array(zod.z.object({NetworkID:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough()).nullish(),NativeSso:Lx.nullish()}).passthrough(),hd=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:u.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:Et.nullish()}).passthrough(),md=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:u.nullish(),PlayAccess:Et.nullish()}).passthrough(),fd=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Me=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:u.nullish()}),gd=zod.z.object({Message:zod.z.string(),ExpiresAt:u}),Oe={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var Ns=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return E(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,cd,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Oe.RefreshSession),e,pd,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Oe.GetAuthOptions),e,dd,{ticket:null})}linkWallet(e){return this.ctx.transport.post(E(this.ctx.settings.titleID,"Authentication",Oe.LinkWallet,e.UserID??""),e,hd,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(E(this.ctx.settings.titleID,"Authentication",Oe.UnlinkWallet,e.UserID??""),e,md,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Oe.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Oe.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Oe.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Oe.LoginWithGoogle,e)}loginWithApple(e){return this.login(Oe.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Oe.LoginWithSsoCode,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Oe.RegisterWithEmail),e,fd,{ticket:null})}confirmEmailRegistration(e){return this.login(Oe.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Oe.ResendVerificationCode),e,Me,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Oe.RequestWalletChallenge),e,gd,{ticket:null})}loginWithWallet(e){return this.login(Oe.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Oe.ForgotPassword),e,Me,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Oe.ResetPassword),e,Me,{ticket:null})}};var Gx={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},yd=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Nx=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),Rd=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),Nx).nullish(),MissingKeyMode:yd.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),Vx=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),Cd=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:Vx.nullish()}).passthrough(),Vs={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Fx=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),Sd=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:yd.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(Fx).nullish()}).passthrough(),xd=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 ha=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:Cd.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(a=>a),bd=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(a=>a),Dd=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(a=>a),Pd=zod.z.object({}).passthrough().transform(a=>a),vd=zod.z.object({}).passthrough().transform(a=>a),Id=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:u.nullish(),LastActiveAt:u.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),zd=zod.z.object({Username:zod.z.string()}),at={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Fs=class{constructor(e){this.ctx=e;}ctx;endpoint(e,t){return E(this.ctx.settings.titleID,"User",e,t??"")}getClientState(e){return this.ctx.transport.post(this.endpoint(at.GetClientState,e.UserID),e,ha,{ticket:e.ClientSessionTicket})}getClientStateExcept(e){return this.ctx.transport.post(this.endpoint(at.GetClientStateExcept,e.UserID),e,ha,{ticket:e.ClientSessionTicket})}getStateVersions(e){return this.ctx.transport.post(this.endpoint(at.GetStateVersions,e.UserID),e,bd,{ticket:e.ClientSessionTicket})}getUserState(e){return this.ctx.transport.post(this.endpoint(at.GetUserState,e.UserID),e,Dd,{ticket:e.ClientSessionTicket})}getInventory(e){return this.ctx.transport.post(this.endpoint(at.GetInventory,e.UserID),e,Pd,{ticket:e.ClientSessionTicket})}getEventTokens(e){return this.ctx.transport.post(this.endpoint(at.GetEventTokens,e.UserID),e,vd,{ticket:e.ClientSessionTicket})}getUsageTime(e){return this.ctx.transport.post(this.endpoint(at.GetUsageTime,e.UserID),e,Id,{ticket:e.ClientSessionTicket})}addUsageTime(e){return this.ctx.transport.post(this.endpoint(at.AddUsageTime,e.UserID),e,Me,{ticket:e.ClientSessionTicket,silent:true})}deleteUserAccount(e){return this.ctx.transport.post(this.endpoint(at.DeleteUserAccount,e.UserID),e,Me,{ticket:e.ClientSessionTicket})}changeUsername(e){return this.ctx.transport.post(this.endpoint(at.ChangeUsername,e.UserID),e,zd,{ticket:e.ClientSessionTicket})}};var js=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Currency",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}convert(e){return this.send(xs.Convert,e,Qc)}cryptoConvert(e){return this.send(xs.CryptoConvert,e,Hc)}};var jx=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),ma=zod.z.object({ServerTimeUtc:u,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:w.nullish(),FodderConsumed:zod.z.array(jx).nullish()}),Td=zod.z.array(be(ma)),Ws={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Wx={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},_x=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Kx={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Qx=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Hx=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),$x=zod.z.object({Networks:zod.z.record(zod.z.string(),Hx).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),Jx=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(),Zx=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(),Yx=zod.z.object({ValuationMode:_x.nullish(),WeightCurve:Le.nullish(),Selection:Qx.nullish()}).passthrough(),Xx=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:Le.nullish(),FlatBonusCurve:Le.nullish(),PercentBonusCurve:Le.nullish(),PowerCurve:Le.nullish(),Fodder:Yx.nullish()}).passthrough(),eb=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),tb=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:$x.nullish(),Stats:Jx.nullish(),Equipment:Zx.nullish(),Upgrade:Xx.nullish(),Metadata:eb.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),ib=zod.z.object({Items:zod.z.record(zod.z.string(),tb).nullish()}).passthrough(),_s=zod.z.object({Catalogs:zod.z.record(zod.z.string(),ib).nullish()}).passthrough();var Ks=class{constructor(e){this.ctx=e;}ctx;upgradeLevel(e){let t=E(this.ctx.settings.titleID,"Item",Ws.UpgradeLevel,e.UserID??"");return this.ctx.transport.post(t,e,ma,{ticket:e.ClientSessionTicket})}upgradeLevelsBatch(e){let t=E(this.ctx.settings.titleID,"Item",Ws.UpgradeLevelsBatch,e.UserID??"");return this.ctx.transport.post(t,e,Td,{ticket:e.ClientSessionTicket})}};var Qs=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Store",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}purchase(e){return this.send(Vt.Purchase,e,oo)}purchaseBatch(e){return this.send(Vt.PurchaseBatch,e,El)}getDefinitions(e){return this.send(Vt.GetDefinitions,e,fn)}getUserState(e){return this.send(Vt.GetUserState,e,Bl)}getStorefront(e){return this.send(Vt.GetStorefront,e,gn)}};var nb={Apple:"Apple",Google:"Google"},Hs=zod.z.object({PremiumID:zod.z.string().nullish(),PurchaseDate:zod.z.string().nullish(),ExpirationDate:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),IsAutoRenewEnabled:zod.z.boolean().nullish()}).passthrough(),$s=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),Hs).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(a=>a),sb=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:oe.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),fa=zod.z.object({Definitions:zod.z.record(zod.z.string(),sb).nullish()}).passthrough(),kd=zod.z.object({Premium:fa.nullish()}),Ad=zod.z.object({ServerTimeUtc:u.nullish(),Premium:$s.nullish()}),Js=zod.z.object({ServerTimeUtc:u.nullish(),Premium:$s.nullish(),Subscription:Hs.nullish(),Resources:w.nullish()}),Wt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var rb={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},ob=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),wd=zod.z.object({StartUtc:u.nullish(),EndUtc:u.nullish(),Gate:$.nullish(),Limits:fe.nullish()}).passthrough(),ga=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),ab=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:Q.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),lb=zod.z.object({Rewards:_.nullish(),Rules:_.nullish(),Refund:_.nullish()}).passthrough(),ub=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:ob.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:Q.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:wd.nullish(),Refund:ga.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:ab.nullish(),Presets:lb.nullish()}).passthrough(),cb=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(),pb=zod.z.object({Rewards:Q.nullish()}).passthrough(),db=zod.z.object({Rules:wd.nullish()}).passthrough(),hb=zod.z.object({Refund:ga.nullish()}).passthrough(),mb=zod.z.object({Rewards:zod.z.record(zod.z.string(),pb).nullish(),Rules:zod.z.record(zod.z.string(),db).nullish(),Refund:zod.z.record(zod.z.string(),hb).nullish()}).passthrough(),fb=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(),gb=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),ub).nullish(),Stores:zod.z.record(zod.z.string(),cb).nullish(),Presets:mb.nullish(),Validation:fb.nullish(),Refund:ga.nullish()}).passthrough(),Md=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:u.nullish(),LastPurchasedAt:u.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Od=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:u.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:u.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:u.nullish()}).passthrough(),yb=zod.z.object({Products:zod.z.record(zod.z.string(),Md).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Od).nullish(),LastRefundCheckAt:u.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:u.nullish(),LastPurchaseAt:u.nullish()}).passthrough(),Rb=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(),Ud=zod.z.object({ServerTimeUtc:u,Purchase:gb.nullish(),Availability:zod.z.array(Rb).nullish()}),Ed=zod.z.object({ServerTimeUtc:u,Purchase:yb.nullish()}),Cb={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},Sb=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),ya=zod.z.object({ServerTimeUtc:u,Store:Ni.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:Sb.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:w.nullish(),Inventory:K.nullish(),ProductState:Md.nullish(),Premium:$s.nullish(),Subscription:Hs.nullish(),SubscriptionMirror:Od.nullish()}).passthrough(),Bd=zod.z.object({ServerTimeUtc:u,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:u.nullish()}).passthrough(),qd=mt(ya),_t={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var Zs=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Purchase",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(_t.GetDefinitions,e,Ud)}getUserState(e){return this.send(_t.GetUserState,e,Ed)}validatePurchase(e){return this.send(_t.ValidatePurchase,e,ya)}validatePurchasesBatch(e){return this.send(_t.ValidatePurchasesBatch,e,qd)}createTelegramInvoice(e){return this.send(_t.CreateTelegramInvoice,e,Bd)}};var xb=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Ld=zod.z.object({Reward:Q.nullish(),Weight:zod.z.number().nullish(),AmountRange:xb.nullish()}).passthrough(),gi=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(Ld).nullish()}).passthrough(),yi=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(Ld).nullish()}).passthrough(),bb=zod.z.object({RewardSlots:zod.z.array(gi).nullish()}).passthrough(),Db=zod.z.object({PityRules:zod.z.array(yi).nullish()}).passthrough(),Ys=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),bb).nullish(),PityPresets:zod.z.record(zod.z.string(),Db).nullish()}).passthrough();var Pb=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),Gd=zod.z.object({ServerTimeUtc:u,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:w.nullish(),Inventory:K.nullish(),Results:zod.z.array(w).nullish(),TriggeredPity:zod.z.array(Pb).nullish()}),vb=zod.z.object({RewardSlots:_.nullish(),PityRules:_.nullish()}).passthrough(),Ib=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:j.nullish()}).passthrough(),zb=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:oe.nullish(),RewardSlots:zod.z.array(gi).nullish(),PityRules:zod.z.array(yi).nullish(),Presets:vb.nullish(),RewardMultiplier:Fi.nullish(),SupplyLimits:zod.z.array(Ib).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),Tb=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Ra=zod.z.object({Definitions:zod.z.record(zod.z.string(),zb).nullish(),RewardPools:Ys.nullish(),Settings:Tb.nullish()}).passthrough(),Nd=zod.z.object({LootboxDefinitions:Ra.nullish()}),Xs={GetDefinitions:"GetDefinitions",Open:"Open"};var er=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Lootbox",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Xs.GetDefinitions,e,Nd)}open(e){return this.send(Xs.Open,e,Gd)}};var kb=zod.z.object({}).passthrough().transform(a=>a),Ab=zod.z.object({}).passthrough().transform(a=>a),wb=zod.z.object({}).passthrough().transform(a=>a),Mb=zod.z.object({}).passthrough().transform(a=>a),Ob=zod.z.object({}).passthrough().transform(a=>a),Vd=zod.z.object({ServerTimeUtc:u,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:kb,Resources:w.nullish(),Inventory:K.nullish()}),Fd=zod.z.object({ServerTimeUtc:u,AccrualID:zod.z.string(),AccruedSeconds:j.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:Ab,Resources:w.nullish(),Inventory:K.nullish()}),jd=zod.z.object({ServerTimeUtc:u,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:wb,Resources:w.nullish(),Inventory:K.nullish()}),Wd=zod.z.object({ServerTimeUtc:u,ClaimID:zod.z.string(),ClaimState:Mb,Resources:w.nullish(),Inventory:K.nullish()}),_d=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()}),Ub=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),Eb=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:Q.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ui=zod.z.object({Gate:$.nullish(),Limits:fe.nullish()}).passthrough(),Ca=zod.z.object({Availability:_.nullish()}).passthrough(),Bb=zod.z.object({Availability:zod.z.record(zod.z.string(),Ui).nullish()}).passthrough(),qb=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(Eb).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:Ui.nullish(),Presets:Ca.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),Lb=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),Gb=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(Lb).nullish()}).passthrough(),Nb=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Ui.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Vb=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:Gb.nullish(),Rewards:Q.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:Nb.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),Fb=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:Q.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),jb=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(Fb).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Ui.nullish(),Presets:Ca.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),Wb=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(),_b=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:Q.nullish(),PremiumLimitOverrides:zod.z.array(Wb).nullish(),Availability:Ui.nullish(),Presets:Ca.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),Sa=zod.z.object({TierRewards:Ub.nullish(),MilestoneRewardMultiplier:Fi.nullish(),DailyCalendars:zod.z.record(zod.z.string(),qb).nullish(),IdleAccruals:zod.z.record(zod.z.string(),Vb).nullish(),Comebacks:zod.z.record(zod.z.string(),jb).nullish(),Claims:zod.z.record(zod.z.string(),_b).nullish(),Presets:Bb.nullish()}).passthrough(),Kd=zod.z.object({RewardDefinitions:Sa.nullish()}),Qd=zod.z.object({Rewards:Ob.nullish()}),It={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var tr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Reward",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getRewardDefinitions(e){return this.send(It.GetRewardDefinitions,e,Kd)}getUserRewardsState(e){return this.send(It.GetUserRewardsState,e,Qd)}getMilestoneRewardMultiplier(e){return this.send(It.GetMilestoneRewardMultiplier,e,_d)}claimDailyReward(e){return this.send(It.ClaimDailyReward,e,Vd)}collectIdleAccrual(e){return this.send(It.CollectIdleAccrual,e,Fd)}claimComebackReward(e){return this.send(It.ClaimComebackReward,e,jd)}claimReward(e){return this.send(It.ClaimReward,e,Wd)}};var ir=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Tutorial",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getTutorialDefinitions(e){return this.send(nt.GetTutorialDefinitions,e,Rl)}getUserTutorialState(e){return this.send(nt.GetUserTutorialState,e,_i)}startFlow(e){return this.send(nt.StartFlow,e,kt)}reportStepShown(e){return this.send(nt.ReportStepShown,e,kt)}completeStep(e){return this.send(nt.CompleteStep,e,kt)}completeStepsBatch(e){return this.send(nt.CompleteStepsBatch,e,xl)}skipStep(e){return this.send(nt.SkipStep,e,kt)}skipFlow(e){return this.send(nt.SkipFlow,e,kt)}claimFlowReward(e){return this.send(nt.ClaimFlowReward,e,Sl)}resetFlow(e){return this.send(nt.ResetFlow,e,kt)}};var Kb={Open:"Open",Application:"Application"},Qb=zod.z.enum(["Open","Application"]).catch("Open"),Hb={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Hd=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),$b={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},xa=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),Jb={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var Kt={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},Zb=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(),$d=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:Qb.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:Hd.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(Zb).nullish()}).passthrough(),Yb=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(),Xb=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:xa.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(),Yb).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),eD=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:xa.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),Jd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(Xb).nullish(),Payouts:zod.z.array(eD).nullish()}).passthrough(),Zd=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:xa.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),tD=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),iD=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(tD).nullish()}).passthrough(),nD=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(),Yd=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:Hd.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(nD).nullish()}).passthrough(),sD=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),rD=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(sD).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(),Xd=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:iD.nullish(),SolanaSignature:rD.nullish(),StateDelta:mi.nullish()}).passthrough();var nr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"CommunityMarketing",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getCommunityMarketingState(e){return this.send(Kt.GetCommunityMarketingState,e,$d)}getEarnings(e){return this.send(Kt.GetEarnings,e,Jd)}claim(e){return this.send(Kt.Claim,e,Zd)}checkJoinEligibility(e){return this.send(Kt.CheckJoinEligibility,e,Yd)}withdrawCryptoReward(e){return this.send(Kt.WithdrawCryptoReward,e,Xd)}};var sr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Chat",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getChatDefinitions(e){return this.send(We.GetChatDefinitions,e,Zl)}getChannels(e){return this.send(We.GetChannels,e,In)}poll(e){return this.send(We.Poll,e,Yl)}getHistory(e){return this.send(We.GetHistory,e,Xl)}getConversations(e){return this.send(We.GetConversations,e,iu)}sendMessage(e){return this.send(We.SendMessage,e,eu)}openDirectChannel(e){return this.send(We.OpenDirectChannel,e,tu)}markRead(e){return this.send(We.MarkRead,e,di)}joinChannel(e){return this.send(We.JoinChannel,e,di)}leaveChannel(e){return this.send(We.LeaveChannel,e,di)}reportMessage(e){return this.send(We.ReportMessage,e,nu)}ignoreUser(e){return this.send(We.IgnoreUser,e,di)}unignoreUser(e){return this.send(We.UnignoreUser,e,di)}};var rr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Push",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getPushConfig(e){return this.send(hi.GetPushConfig,e,ou)}subscribePush(e){return this.send(hi.SubscribePush,e,co)}unsubscribePush(e){return this.send(hi.UnsubscribePush,e,Me)}getPushSubscriptions(e){return this.send(hi.GetPushSubscriptions,e,au)}};var or=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Localization",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket,throttleKey:t.Locale?`${n}:${t.Locale}`:n})}getLocalizationManifest(e){return this.send(Vs.GetLocalizationManifest,e,Sd)}getLocalizationTable(e){return this.send(Vs.GetLocalizationTable,e,xd)}};var ar=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Quest",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getQuestDefinitions(e){return this.send(ct.GetQuestDefinitions,e,Wi)}getUserQuestState(e){return this.send(ct.GetUserQuestState,e,ol)}refreshQuestCycles(e){return this.send(ct.RefreshQuestCycles,e,Me)}claimQuestReward(e){return this.send(ct.ClaimQuestReward,e,$r)}claimQuestRewardsBatch(e){return this.send(ct.ClaimQuestRewardsBatch,e,ul)}claimMilestoneReward(e){return this.send(ct.ClaimMilestoneReward,e,Jr)}claimMilestoneRewardsBatch(e){return this.send(ct.ClaimMilestoneRewardsBatch,e,cl)}claimGroupCompletionReward(e){return this.send(ct.ClaimGroupCompletionReward,e,al)}addQuestProgress(e){return this.send(ct.AddQuestProgress,e,ll)}};var lr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"TimedEvent",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getActiveEvents(e){return this.send(rt.GetActiveEvents,e,On)}getDefinitions(e){return this.send(rt.GetDefinitions,e,Mn)}getUserLteState(e){return this.send(rt.GetUserLteState,e,du)}grantTokens(e){return this.send(rt.GrantTokens,e,w)}spendTokens(e){return this.send(rt.SpendTokens,e,mo)}claimMilestone(e){return this.send(rt.ClaimMilestone,e,fo)}claimMilestonesBatch(e){return this.send(rt.ClaimMilestonesBatch,e,go)}claimAllMilestones(e){return this.send(rt.ClaimAllMilestones,e,go)}spendTokensBatch(e){return this.send(rt.SpendTokensBatch,e,hu)}grantTokensBatch(e){return this.send(rt.GrantTokensBatch,e,mu)}};var ur=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Leaderboard",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Ge.GetDefinitions,e,Nn)}getLeaderboard(e){return this.send(Ge.GetLeaderboard,e,vi)}getMyProgress(e){return this.send(Ge.GetMyProgress,e,En)}submitScore(e){return this.send(Ge.SubmitScore,e,Bn)}submitScoreFromSource(e){return this.send(Ge.SubmitScoreFromSource,e,Bn)}claimCycleReward(e){return this.send(Ge.ClaimCycleReward,e,qn)}claimMilestone(e){return this.send(Ge.ClaimMilestone,e,Ln)}getFriendsLeaderboard(e){return this.send(Ge.GetFriendsLeaderboard,e,vi)}getLeaderboardsBatch(e){return this.send(Ge.GetLeaderboardsBatch,e,yu)}getProgressBatch(e){return this.send(Ge.GetProgressBatch,e,Gn)}claimCycleRewardsBatch(e){return this.send(Ge.ClaimCycleRewardsBatch,e,Ru)}claimMilestonesBatch(e){return this.send(Ge.ClaimMilestonesBatch,e,Cu)}submitScoresBatch(e){return this.send(Ge.SubmitScoresBatch,e,Su)}claimAllRewardsBatch(e){return this.send(Ge.ClaimAllRewardsBatch,e,xu)}getOverviewBatch(e){return this.send(Ge.GetOverviewBatch,e,bu)}};var cr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Season",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(wt.GetDefinitions,e,jn)}getActiveSeason(e){return this.send(wt.GetActiveSeason,e,Fn)}getUserState(e){return this.send(wt.GetUserState,e,yo)}grantStatusTokens(e){return this.send(wt.GrantStatusTokens,e,Iu)}claimTierReward(e){return this.send(wt.ClaimTierReward,e,Ro)}claimTierRewardsBatch(e){return this.send(wt.ClaimTierRewardsBatch,e,zu)}};var pr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Premium",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Wt.GetDefinitions,e,kd)}getUserState(e){return this.send(Wt.GetUserState,e,Ad)}activateTrial(e){return this.send(Wt.ActivateTrial,e,Js)}purchaseItemOrCurrency(e){return this.send(Wt.PurchaseWithResources,e,Js)}purchaseRealMoney(e){return this.send(Wt.PurchaseRealMoney,e,Js)}};var dr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Character",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getCharacterDefinitions(e){return this.send(Ne.GetCharacterDefinitions,e,Qn)}getUserCharacters(e){return this.send(Ne.GetUserCharacters,e,Ou)}unlockCharacter(e){return this.send(Ne.UnlockCharacter,e,bo)}upgradeStatLevel(e){return this.send(Ne.UpgradeStatLevel,e,So)}upgradeCharacterLevel(e){return this.send(Ne.UpgradeCharacterLevel,e,xo)}equipItems(e){return this.send(Ne.EquipItems,e,Uu)}unequipItems(e){return this.send(Ne.UnequipItems,e,Eu)}unequipAllCharacters(e){return this.send(Ne.UnequipAllCharacters,e,Bu)}unlockCharactersBatch(e){return this.send(Ne.UnlockCharactersBatch,e,Vu)}upgradeCharacterLevelsBatch(e){return this.send(Ne.UpgradeCharacterLevelsBatch,e,Fu)}upgradeStatLevelsBatch(e){return this.send(Ne.UpgradeStatLevelsBatch,e,ju)}unlockSkin(e){return this.send(Ne.UnlockSkin,e,qu)}equipSkin(e){return this.send(Ne.EquipSkin,e,Lu)}unequipSkin(e){return this.send(Ne.UnequipSkin,e,Gu)}getCharacterSkins(e){return this.send(Ne.GetCharacterSkins,e,Nu)}};var hr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Match",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}createMatch(e){return this.send(yt.CreateMatch,e,Rp)}updateMatch(e){return this.send(yt.UpdateMatch,e,Cp)}cancelMatch(e){return this.send(yt.CancelMatch,e,Sp)}instantBattle(e){return this.send(yt.InstantBattle,e,xp)}saveStrategy(e){return this.send(yt.SaveStrategy,e,Me)}getMyMatches(e){return this.send(yt.GetMyMatches,e,Ho)}getAvailableMatches(e){return this.send(yt.GetAvailableMatches,e,Ho)}getDefinitions(e){return this.send(yt.GetDefinitions,e,vp)}};var oD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},eh=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),aD={None:"None",Min:"Min",Average:"Average",Max:"Max"},lD=zod.z.enum(["None","Min","Average","Max"]).catch("None"),uD={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},cD=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),pD={Clamp:"Clamp",Reject:"Reject"},dD=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),hD=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),mD=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:Kr.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(hD).nullish()}),th=zod.z.object({ServerTimeUtc:u,Type:eh.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:w.nullish(),Inventory:K.nullish(),Results:zod.z.array(mD).nullish()}),fD=zod.z.object({CraftID:zod.z.string().nullish(),Type:eh.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:oe.nullish(),OutputLevelMode:lD.nullish(),InputSelection:cD.nullish(),OutputLevelOverflow:dD.nullish()}).passthrough(),ba=zod.z.object({Definitions:zod.z.record(zod.z.string(),fD).nullish()}).passthrough(),ih=zod.z.object({ServerTimeUtc:u.nullish(),CraftDefinitions:ba.nullish()}),mr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var fr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Craft",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(mr.GetDefinitions,e,ih)}craft(e){return this.send(mr.Craft,e,th)}};var gD=2e5,gr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i,n={}){let s=E(this.ctx.settings.titleID,"AI",e,t.UserID??"");return this.ctx.transport.post(s,t,i,{...n,ticket:t.ClientSessionTicket})}generate(e,t){return this.send(e,t,Zn,{timeoutMs:gD,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Zn,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(qe.GetDefinitions,e,Yu)}generateText(e){return this.generate(qe.GenerateText,e)}getText(e){return this.readGeneration(qe.GetText,e)}generateImage(e){return this.generate(qe.GenerateImage,e)}editImage(e){return this.generate(qe.EditImage,e)}getImage(e){return this.readGeneration(qe.GetImage,e)}generateVideo(e){return this.generate(qe.GenerateVideo,e)}getVideo(e){return this.readGeneration(qe.GetVideo,e)}generateAudio(e){return this.generate(qe.GenerateAudio,e)}getAudio(e){return this.readGeneration(qe.GetAudio,e)}generateMusic(e){return this.generate(qe.GenerateMusic,e)}getMusic(e){return this.readGeneration(qe.GetMusic,e)}generateThreeD(e){return this.generate(qe.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(qe.GetThreeD,e)}listGenerations(e){return this.send(qe.ListGenerations,e,Zu)}getGeneration(e){return this.readGeneration(qe.GetGeneration,e)}};var yD={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},RD=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),nh=zod.z.object({}).passthrough().transform(a=>a),Ri=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()}),sh=zod.z.object({GrantedCollectibles:zod.z.array(Ri).nullish(),DuplicateCollectibles:zod.z.array(Ri).nullish(),CollectionCurrencyEarned:j.nullish()}),rh=zod.z.object({OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(sh).nullish(),GrantedCollectibles:zod.z.array(Ri).nullish(),DuplicateCollectibles:zod.z.array(Ri).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:w.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),oh=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(sh).nullish(),GrantedCollectibles:zod.z.array(Ri).nullish(),DuplicateCollectibles:zod.z.array(Ri).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),Resources:w.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),ah=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),Da=zod.z.object({SetID:zod.z.string(),Resources:w.nullish(),Inventory:K.nullish()}),lh=zod.z.array(be(Da)),uh=zod.z.object({Resources:w.nullish(),Inventory:K.nullish()}),CD=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:Ae.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:RD.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RespondedAtUtc:u.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),ch=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:u.nullish(),Resources:w.nullish()}),ph=zod.z.object({OfferID:zod.z.string(),Resources:w.nullish()}),dh=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()}),hh=zod.z.object({OfferID:zod.z.string(),Resources:w.nullish()}),Pa=zod.z.object({Offers:zod.z.array(CD).nullish()}),SD=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(),xD=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(SD).nullish(),SetCompletionReward:Q.nullish()}).passthrough(),bD=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(xD).nullish(),GrandPrize:Q.nullish()}).passthrough(),mh=zod.z.object({BonusRewardSlots:_.nullish(),PityRules:_.nullish()}).passthrough(),DD=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:oe.nullish(),BonusRewardSlots:zod.z.array(gi).nullish(),PityRules:zod.z.array(yi).nullish(),Presets:mh.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(),PD=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),vD=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(gi).nullish(),PityRules:zod.z.array(yi).nullish(),Presets:mh.nullish(),Tier:zod.z.number().nullish()}).passthrough(),ID=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),zD=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),yr=zod.z.object({Collections:zod.z.record(zod.z.string(),bD).nullish(),PackTypes:zod.z.record(zod.z.string(),DD).nullish(),CollectionChests:zod.z.array(vD).nullish(),DuplicateConversions:zod.z.array(PD).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(ID).nullish(),RewardPools:Ys.nullish(),Settings:zD.nullish()}).passthrough(),Ve={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var Rr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Collection",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Ve.GetDefinitions,e,yr)}getUserState(e){return this.send(Ve.GetUserState,e,nh)}openPack(e){return this.send(Ve.OpenPack,e,rh)}openCollectionChest(e){return this.send(Ve.OpenCollectionChest,e,oh)}useCollectibleJoker(e){return this.send(Ve.UseCollectibleJoker,e,ah)}claimSetReward(e){return this.send(Ve.ClaimSetReward,e,Da)}claimSetRewardsBatch(e){return this.send(Ve.ClaimSetRewardsBatch,e,lh)}claimGrandPrize(e){return this.send(Ve.ClaimGrandPrize,e,uh)}sendTradeOffer(e){return this.send(Ve.SendTradeOffer,e,ch)}cancelTradeOffer(e){return this.send(Ve.CancelTradeOffer,e,ph)}acceptTradeOffer(e){return this.send(Ve.AcceptTradeOffer,e,dh)}declineTradeOffer(e){return this.send(Ve.DeclineTradeOffer,e,hh)}getMyTradeOffers(e){return this.send(Ve.GetMyTradeOffers,e,Pa)}getIncomingTradeOffers(e){return this.send(Ve.GetIncomingTradeOffers,e,Pa)}};var Cr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"CoopEvent",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(pt.GetDefinitions,e,ts)}getActiveEvent(e){return this.send(pt.GetActiveEvent,e,tc)}getUserState(e){return this.send(pt.GetUserState,e,es)}getGroupState(e){return this.send(pt.GetGroupState,e,To)}joinOrCreateGroup(e){return this.send(pt.JoinOrCreateGroup,e,To)}spin(e){return this.send(pt.Spin,e,nc)}claimObjectReward(e){return this.send(pt.ClaimObjectReward,e,ko)}claimGrandPrize(e){return this.send(pt.ClaimGrandPrize,e,ko)}leaveGroup(e){return this.send(pt.LeaveGroup,e,sc)}};var Sr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"DealOffer",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinition(e){return this.send(gt.GetDefinition,e,fc)}getUserState(e){return this.send(gt.GetUserState,e,gc)}getActiveDeals(e){return this.send(gt.GetActiveDeals,e,ss)}dismissDeal(e){return this.send(gt.DismissDeal,e,Rc)}executeNode(e){return this.send(gt.ExecuteNode,e,yc)}recordShow(e){return this.send(gt.RecordShow,e,Cc)}claimMilestone(e){return this.send(gt.ClaimMilestone,e,Sc)}claimMilestonesBatch(e){return this.send(gt.ClaimMilestonesBatch,e,xc)}};var TD=zod.z.object({}).passthrough().transform(a=>a),kD=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:fe.nullish()}).passthrough(),va=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:Q.nullish(),InviteRewards:zod.z.record(zod.z.string(),Ee).nullish(),SpendRewards:zod.z.array(kD).nullish()}).passthrough(),fh=zod.z.object({ReferralDefinitions:va.nullish()}).passthrough(),gh=zod.z.object({Referral:TD.nullish(),InviteUrl:zod.z.string().nullish()}).passthrough(),yh=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:w.nullish(),Inventory:K.nullish()}).passthrough(),Ia=zod.z.object({RewardID:zod.z.string().nullish(),Resources:w.nullish(),Inventory:K.nullish()}).passthrough(),Rh=mt(Ia),Qt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch"};var xr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Referral",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Qt.GetDefinitions,e,fh)}getUserState(e){return this.send(Qt.GetUserState,e,gh)}activateReferralCode(e){return this.send(Qt.ActivateReferralCode,e,yh)}claimInviteReward(e){return this.send(Qt.ClaimInviteReward,e,Ia)}claimInviteRewardsBatch(e){return this.send(Qt.ClaimInviteRewardsBatch,e,Rh)}};var br=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Mailbox",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Ye.GetDefinitions,e,Ic)}getMessages(e){return this.send(Ye.GetMessages,e,zc)}getUnreadCount(e){return this.send(Ye.GetUnreadCount,e,as)}readMessages(e){return this.send(Ye.ReadMessages,e,Mo)}claimReward(e){return this.send(Ye.ClaimReward,e,ls)}claimRewardsBatch(e){return this.send(Ye.ClaimRewardsBatch,e,ls)}claimAll(e){return this.send(Ye.ClaimAll,e,ls)}deleteMessages(e){return this.send(Ye.DeleteMessages,e,Mo)}sendGift(e){return this.send(Ye.SendGift,e,Tc)}sendTransfer(e){return this.send(Ye.SendTransfer,e,kc)}getGiftStatus(e){return this.send(Ye.GetGiftStatus,e,Ac)}};var Dr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Social",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getFriendsList(e){return this.send(ge.GetFriendsList,e,zi)}getIncomingRequests(e){return this.send(ge.GetIncomingRequests,e,zi)}getOutgoingRequests(e){return this.send(ge.GetOutgoingRequests,e,zi)}getRecommendedFriends(e){return this.send(ge.GetRecommendedFriends,e,zi)}sendFriendRequest(e){return this.send(ge.SendFriendRequest,e,Ti)}acceptFriendRequest(e){return this.send(ge.AcceptFriendRequest,e,Ti)}declineFriendRequest(e){return this.send(ge.DeclineFriendRequest,e,Ti)}removeFriend(e){return this.send(ge.RemoveFriend,e,Ti)}getInbox(e){return this.send(ge.GetInbox,e,Mc)}markInboxSeen(e){return this.send(ge.MarkInboxSeen,e,ki)}getInboxUnread(e){return this.send(ge.GetInboxUnread,e,ki)}follow(e){return this.send(ge.Follow,e,Ut)}unfollow(e){return this.send(ge.Unfollow,e,Ut)}getFollowers(e){return this.send(ge.GetFollowers,e,cs)}getFollowing(e){return this.send(ge.GetFollowing,e,cs)}block(e){return this.send(ge.Block,e,Ut)}unblock(e){return this.send(ge.Unblock,e,Ut)}getBlocked(e){return this.send(ge.GetBlocked,e,cs)}react(e){return this.send(ge.React,e,Ut)}unreact(e){return this.send(ge.Unreact,e,Ut)}getMyReactions(e){return this.send(ge.GetMyReactions,e,Uc)}getEntityStates(e){return this.send(ge.GetEntityStates,e,Oc)}addComment(e){return this.send(ge.AddComment,e,ps)}editComment(e){return this.send(ge.EditComment,e,ps)}deleteComment(e){return this.send(ge.DeleteComment,e,Bc)}getComments(e){return this.send(ge.GetComments,e,Ec)}report(e){return this.send(ge.Report,e,qc)}};var AD={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Ht=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),wD=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:oe.nullish(),Effect:Ht.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(),Pr=zod.z.object({Schedule:de.nullish(),Gate:$.nullish()}).passthrough(),za=zod.z.object({Availability:_.nullish(),Effects:_.nullish()}).passthrough(),MD=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(Ht).nullish(),Availability:Pr.nullish(),Presets:za.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),OD=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(Ht).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),UD=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(OD).nullish(),Availability:Pr.nullish(),Presets:za.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ED=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(it).nullish(),Effects:zod.z.array(Ht).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:Pr.nullish(),Presets:za.nullish()}).passthrough(),BD=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),qD=zod.z.object({Effects:zod.z.array(Ht).nullish()}).passthrough(),LD=zod.z.object({Availability:zod.z.record(zod.z.string(),Pr).nullish(),Effects:zod.z.record(zod.z.string(),qD).nullish()}).passthrough(),GD=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),BD).nullish()}).passthrough(),vr=zod.z.object({Definitions:zod.z.record(zod.z.string(),wD).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),MD).nullish(),BoostChains:zod.z.record(zod.z.string(),UD).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),ED).nullish(),Settings:GD.nullish(),Presets:LD.nullish()}).passthrough(),Ch=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:Ht.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:u.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:u.nullish()}).passthrough();var Sh=zod.z.object({ServerTimeUtc:u.nullish(),Active:zod.z.record(zod.z.string(),Ch).nullish()}),xh=zod.z.object({ServerTimeUtc:u.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:Ch.nullish(),Resources:w.nullish()}),ND={Scheduled:"Scheduled",Chain:"Chain"},VD=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),Effects:zod.z.array(Ht).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),bh=zod.z.object({ServerTimeUtc:u.nullish(),Windows:zod.z.array(VD).nullish()}),$t={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Ir=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"TimedBoost",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send($t.GetDefinitions,e,vr)}getActive(e){return this.send($t.GetActive,e,Sh)}getActiveWindows(e){return this.send($t.GetActiveWindows,e,bh)}activate(e){return this.send($t.Activate,e,xh)}cleanupExpired(e){return this.send($t.CleanupExpired,e,Me)}};var zr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"UserCustomData",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getUserCustomDataDefinitions(e){return this.send(dt.GetUserCustomDataDefinitions,e,fs)}getMyUserCustomData(e){return this.send(dt.GetMyUserCustomData,e,Vc)}getPublicUserCustomDataOf(e){return this.send(dt.GetPublicUserCustomDataOf,e,qo)}setPrivateData(e){return this.send(dt.SetPrivateData,e,Lo)}setPublicData(e){return this.send(dt.SetPublicData,e,Lo)}deleteKey(e){return this.send(dt.DeleteKey,e,Me)}batchSet(e){return this.send(dt.BatchSet,e,Fc)}batchDelete(e){return this.send(dt.BatchDelete,e,jc)}batchGetPublicUserCustomDataOf(e){return this.send(dt.BatchGetPublicUserCustomDataOf,e,Wc)}};var FD={Static:"Static",Runtime:"Runtime"},jD={Public:"Public",Private:"Private"},WD=zod.z.enum(["Client","Server","System"]).catch("Client"),_D=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),KD=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:WD.nullish(),ExpiresAt:u.nullish()}).passthrough(),Dh=zod.z.record(zod.z.string(),KD),Ta=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:Dh.nullish(),Runtime:Dh.nullish(),NotModified:zod.z.boolean().nullish()}),QD=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:_D.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Tr=zod.z.object({Keys:zod.z.record(zod.z.string(),QD).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(),Ei={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var kr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"TitleCustomData",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getTitleCustomDataDefinitions(e){return this.send(Ei.GetTitleCustomDataDefinitions,e,Tr)}getPublicTitleData(e){return this.send(Ei.GetPublicTitleData,e,Ta)}getPublicTitleDataKeys(e){return this.send(Ei.GetPublicTitleDataKeys,e,Ta)}};var HD={Fast:"Fast",Sequential:"Sequential"},$D={Instant:"Instant",Timed:"Timed"};var JD={Hit:"Hit",Blocked:"Blocked"},ZD=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),YD=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:Q.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Q.nullish()}).passthrough();var XD=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Q.nullish()}).passthrough(),eP=zod.z.object({Reward:Q.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(XD).nullish(),Rate:eP.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 Ph=zod.z.object({}).passthrough().transform(a=>a),vh=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Fe=zod.z.object({Operation:w.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),tP=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),iP=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(),nP=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:ae.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(),sP=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:ae.nullish()}).passthrough(),Ih=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:Q.nullish()}).passthrough(),rP=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(),oP=zod.z.object({Tiles:zod.z.record(zod.z.string(),rP).nullish()}).passthrough(),aP=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Fe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),lP=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(aP).nullish(),GuaranteedBonus:Fe.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),uP=zod.z.object({Variants:zod.z.array(lP).nullish()}).passthrough(),cP=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:Fe.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),pP=zod.z.object({Outcomes:zod.z.array(cP).nullish()}).passthrough(),zh=zod.z.object({PerAdMultiplierRange:vh.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),dP=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Fe.nullish()}).passthrough(),hP=zod.z.object({Tiers:zod.z.array(dP).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Fe.nullish()}).passthrough(),mP=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Fe.nullish()}).passthrough(),fP=zod.z.object({Reward:Fe.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),gP=zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(mP).nullish(),Rate:fP.nullish()}).passthrough(),Th=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),gP).nullish()}).passthrough(),yP=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Fe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:oe.nullish(),Multipliers:zh.nullish(),Gradation:hP.nullish(),RunStats:Th.nullish()}).passthrough(),RP=zod.z.object({Choices:zod.z.array(yP).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),CP=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Fe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),SP=zod.z.object({OnPassStart:Fe.nullish(),OnTileLanding:zod.z.record(zod.z.string(),Fe).nullish(),OnAttack:zod.z.record(zod.z.string(),Fe).nullish(),OnRaid:zod.z.record(zod.z.string(),Fe).nullish(),OnBuild:Fe.nullish(),OnStageComplete:Fe.nullish(),OnAttackBonusDrops:zod.z.array(CP).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),pP).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),RP).nullish()}).passthrough(),kh=zod.z.object({BaseAttackReward:Q.nullish(),BaseRaidReward:Q.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Ih).nullish(),HeistGridBonusConfig:uP.nullish(),StageOperations:SP.nullish(),TileLandingMultiplier:vh.nullish(),EconomyOverride:sP.nullish()}).passthrough(),xP=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(Ih).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:kh.nullish()}).passthrough(),bP=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(),DP=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(),Ar=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(),oP).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),kh).nullish(),StagesByLevel:zod.z.record(zod.z.string(),xP).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:nP.nullish(),Dice:tP.nullish(),Bots:iP.nullish(),Targeting:bP.nullish(),BotRaids:DP.nullish()}).passthrough(),PP=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:u.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),Ee).nullish(),GrandPrize:Q.nullish()}).passthrough(),wr=zod.z.object({Board:Ar.nullish(),CommunityChest:PP.nullish()}).passthrough(),Ah=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),ae).nullish()}).passthrough(),vP=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:Ae.nullish(),TargetBuildingStates:zod.z.array(ZD).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:Ah.nullish()}).passthrough(),IP=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Fe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:oe.nullish(),Multipliers:zh.nullish(),RunStats:Th.nullish()}).passthrough(),zP=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(IP).nullish()}).passthrough(),TP=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(),wh=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:w.nullish(),Inventory:K.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:vP.nullish(),SpecialModeOffer:zP.nullish(),CommunityChestContribution:TP.nullish()}).passthrough(),Mh=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:w.nullish(),Inventory:K.nullish(),DualResult:St.nullish()}).passthrough(),ka=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:Q.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(YD).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:w.nullish(),Inventory:K.nullish(),DualResult:St.nullish(),RaidRewardPreview:Ah.nullish()}).passthrough(),Oh=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:w.nullish(),Inventory:K.nullish()}).passthrough(),Uh=zod.z.object({Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:w.nullish(),Inventory:K.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish()}).passthrough(),Eh=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),kP=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),Bh=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:w.nullish(),Inventory:K.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(kP).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:Q.nullish()}).passthrough(),AP={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},qh=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),wP={Active:"Active",Left:"Left",Replaced:"Replaced"},MP=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),OP=zod.z.object({CurrentProgress:j.nullish(),MaxProgress:j.nullish()}).passthrough(),UP=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ae.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:j.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),nl).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:MP.nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),Lh=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(UP).nullish(),SharedProgress:OP.nullish(),Status:qh.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),EP=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:qh.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:u.nullish()}).passthrough(),BP=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(EP).nullish()}).passthrough(),Gh=zod.z.object({ServerTimeUtc:u.nullish(),UserState:BP.nullish(),ActiveGroup:Lh.nullish(),SecondsRemaining:j.nullish()}),Nh=zod.z.object({ServerTimeUtc:u.nullish(),Group:Lh.nullish(),SecondsRemaining:j.nullish()}),Aa=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),Vh=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Ue={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 qP={Mesh:"Mesh",Host:"Host"},wa=zod.z.enum(["Mesh","Host"]).catch("Mesh"),LP={ServerRelay:"ServerRelay",P2P:"P2P"},Ma=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),GP={Public:"Public",Private:"Private"},NP=zod.z.enum(["Public","Private"]).catch("Public"),VP={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},FP=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Fh=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),jP=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),jh=zod.z.object({SystemState:jP.nullish(),DefaultTopology:wa.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:Ma.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(),IceServers:zod.z.array(Fh).nullish()}).passthrough(),WP=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(),_P=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:wa.nullish(),ChatMode:Ma.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),KP=zod.z.object({Seq:zod.z.number().nullish(),Type:FP.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(),Bi=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:wa.nullish(),ChatMode:Ma.nullish(),Visibility:NP.nullish(),Status:zod.z.string().nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Members:zod.z.array(WP).nullish(),IceServers:zod.z.array(Fh).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Wh=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),_h=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),Oa=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),Kh=zod.z.object({Rooms:zod.z.array(_P).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Qh=zod.z.object({Envelopes:zod.z.array(KP).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Mr=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),Ke={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 Ua=zod.z.object({TitleCustomData:Tr.nullish(),Character:Qn.nullish(),Item:_s.nullish(),Currency:bs.nullish(),Store:fn.nullish(),Lootbox:Ra.nullish(),Quest:Wi.nullish(),TimedEvent:Mn.nullish(),Leaderboard:Nn.nullish(),Season:jn.nullish(),Reward:Sa.nullish(),Collection:yr.nullish(),Craft:ba.nullish(),DealOffer:Ao.nullish(),Premium:fa.nullish(),TimedBoost:vr.nullish(),CoopEvent:ts.nullish(),GameLoop:wr.nullish(),Match:$o.nullish(),Experiment:ld.nullish(),Blockchain:Fo.nullish(),Marketplace:ea.nullish(),Multiplayer:jh.nullish(),UserCustomData:fs.nullish(),Referral:va.nullish(),Localization:Rd.nullish(),Analytics:Zp.nullish(),Social:Lc.nullish(),PlatformBridge:Gc.nullish()}).passthrough();var Jt={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Or=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Title",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getTitlePublicConfiguration(e){return this.send(Jt.GetTitlePublicConfiguration,e,Ua)}getTitlePublicConfigurationExcept(e){return this.send(Jt.GetTitlePublicConfigurationExcept,e,Ua)}getCurrencyDefinitions(e){return this.send(Jt.GetCurrencyDefinitions,e,bs)}getItemDefinitions(e){return this.send(Jt.GetItemDefinitions,e,_s)}getServerTime(e){return this.send(Jt.GetServerTime,e,Me)}};var Ur=class{constructor(e){this.ctx=e;}ctx;send(e,t,i,n=false){let s=E(this.ctx.settings.titleID,"GameLoop",e,t.UserID??"");return this.ctx.transport.post(s,t,i,{ticket:t.ClientSessionTicket,silent:n})}getGameLoops(e){return this.send(Ue.GetGameLoops,e,wr)}getBoardDefinition(e,t=false){return this.send(Ue.GetBoardDefinition,e,Ar,t)}getBoardDefinitionForLevel(e,t=false){return this.send(Ue.GetBoardDefinitionForLevel,e,Ar,t)}getUserBoardState(e){return this.send(Ue.GetUserBoardState,e,Ph)}boardLoopRoll(e){return this.send(Ue.BoardLoopRoll,e,wh)}boardLoopAttack(e){return this.send(Ue.BoardLoopAttack,e,Mh)}boardLoopRaid(e){return this.send(Ue.BoardLoopRaid,e,ka)}boardLoopRaidFast(e){return this.send(Ue.BoardLoopRaidFast,e,ka)}boardLoopBuild(e){return this.send(Ue.BoardLoopBuild,e,Oh)}boardSpecialChoose(e){return this.send(Ue.BoardSpecialChoose,e,Uh)}boardSpecialApplyMultiplier(e){return this.send(Ue.BoardSpecialApplyMultiplier,e,Eh)}boardSpecialClaim(e){return this.send(Ue.BoardSpecialClaim,e,Bh)}getCommunityChestState(e){return this.send(Ue.GetCommunityChestState,e,Gh)}joinOrCreateCommunityChest(e){return this.send(Ue.JoinOrCreateCommunityChest,e,Nh)}claimCommunityChestMilestone(e){return this.send(Ue.ClaimCommunityChestMilestone,e,Aa)}claimCommunityChestGrandPrize(e){return this.send(Ue.ClaimCommunityChestGrandPrize,e,Aa)}leaveCommunityChest(e){return this.send(Ue.LeaveCommunityChest,e,Vh)}};var HP={Live:"Live",Latest:"Latest",Specific:"Specific"},$P={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},JP=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),ZP={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"},YP=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),XP=zod.z.object({Level:JP,Message:zod.z.string().nullish(),Data:Mt.nullish()}),ev=zod.z.object({Error:YP,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Hh=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:Mt.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(XP).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:ev.nullish()}),Ea={Execute:"Execute"};var Er=class{constructor(e){this.ctx=e;}ctx;execute(e){let t=E(this.ctx.settings.titleID,"CloudCode",Ea.Execute,e.UserID??"");return this.ctx.transport.post(t,e,Hh,{ticket:e.ClientSessionTicket})}};var Br=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Blockchain",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(_e.GetDefinitions,e,op)}getUserState(e){return this.send(_e.GetUserState,e,ap)}depositToken(e){return this.send(_e.DepositToken,e,lp)}depositNFT(e){return this.send(_e.DepositNFT,e,up)}requestTokenWithdrawal(e){return this.send(_e.RequestTokenWithdrawal,e,cp)}requestNFTWithdrawal(e){return this.send(_e.RequestNFTWithdrawal,e,pp)}getTransactionHistory(e){return this.send(_e.GetTransactionHistory,e,dp)}retryWithdrawal(e){return this.send(_e.RetryWithdrawal,e,hp)}confirmWithdrawal(e){return this.send(_e.ConfirmWithdrawal,e,mp)}donateToDeveloper(e){return this.send(_e.DonateToDeveloper,e,Ko)}donateToUsersPool(e){return this.send(_e.DonateToUsersPool,e,Ko)}getPlayAccess(e){return this.send(_e.GetPlayAccess,e,sp)}confirmPlayAccess(e){return this.send(_e.ConfirmPlayAccess,e,Et)}};var qr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Marketplace",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(ve.GetDefinitions,e,zp)}getGroupedOffers(e){return this.send(ve.GetGroupedOffers,e,Tp)}getOffersByItem(e){return this.send(ve.GetOffersByItem,e,ta)}getOffer(e){return this.send(ve.GetOffer,e,kp)}getBuyOrders(e){return this.send(ve.GetBuyOrders,e,ta)}getMyState(e){return this.send(ve.GetMyState,e,ks)}getHistory(e){return this.send(ve.GetHistory,e,wp)}createListing(e){return this.send(ve.CreateListing,e,Mi)}cancelListing(e){return this.send(ve.CancelListing,e,ot)}buy(e){return this.send(ve.Buy,e,ot)}marketBuy(e){return this.send(ve.MarketBuy,e,ot)}marketSell(e){return this.send(ve.MarketSell,e,ot)}createAuction(e){return this.send(ve.CreateAuction,e,Mi)}placeBid(e){return this.send(ve.PlaceBid,e,Ap)}claimAuction(e){return this.send(ve.ClaimAuction,e,ot)}createBuyOrder(e){return this.send(ve.CreateBuyOrder,e,Mi)}cancelBuyOrder(e){return this.send(ve.CancelBuyOrder,e,ot)}fillBuyOrder(e){return this.send(ve.FillBuyOrder,e,ot)}createDirectTrade(e){return this.send(ve.CreateDirectTrade,e,Mi)}respondDirectTrade(e){return this.send(ve.RespondDirectTrade,e,ot)}cancelDirectTrade(e){return this.send(ve.CancelDirectTrade,e,ot)}claimBack(e){return this.send(ve.ClaimBack,e,ot)}};var Lr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i,n={}){let s=E(this.ctx.settings.titleID,"Multiplayer",e,t.UserID??"");return this.ctx.transport.post(s,t,i,{ticket:t.ClientSessionTicket,...n})}createRoom(e){return this.send(Ke.CreateRoom,e,Bi)}joinRoom(e){return this.send(Ke.JoinRoom,e,Bi)}leaveRoom(e,t=false){return this.send(Ke.LeaveRoom,e,Oa,{keepalive:t})}listRooms(e){return this.send(Ke.ListRooms,e,Kh)}getRoom(e){return this.send(Ke.GetRoom,e,Bi)}closeRoom(e){return this.send(Ke.CloseRoom,e,Oa)}poll(e){return this.send(Ke.Poll,e,Qh)}sendSignal(e){return this.send(Ke.SendSignal,e,Mr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(Ke.ClaimHost,e,Bi)}kickMember(e){return this.send(Ke.KickMember,e,Wh)}unbanMember(e){return this.send(Ke.UnbanMember,e,_h)}sendChat(e){return this.send(Ke.SendChat,e,Mr)}setMemberState(e){return this.send(Ke.SetMemberState,e,Mr)}};var tv={Free:"Free",Price:"Price",Holding:"Holding"},Ba=zod.z.enum(["Free","Price","Holding"]).catch("Free"),iv={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},nv=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),sv={All:"All",Any:"Any"},rv=zod.z.enum(["All","Any"]).catch("All"),ov={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},av=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),lv={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},uv=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),cv={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Jh=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),pv={New:"New",Popular:"Popular",MostLiked:"MostLiked"},dv={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},hv=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),mv=zod.z.object({Type:ri.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(),fv=zod.z.object({Requirements:zod.z.array(mv).nullish(),Match:rv.nullish(),Mode:nv.nullish()}).passthrough(),gv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Ba.nullish(),Price:ae.nullish(),Holding:fv.nullish()}).passthrough(),yv=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(),Rv=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),yv).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(Ba).nullish(),PricePolicy:Ts.nullish(),PublishGate:$.nullish(),PublishFeeOptions:oe.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),Cv=zod.z.object({Allowed:zod.z.array(wi).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),Sv=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),xv=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(),bv=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:de.nullish(),Gate:$.nullish(),Order:zod.z.number().nullish()}).passthrough(),Dv=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:$.nullish(),Schedule:de.nullish(),ContentTypes:zod.z.record(zod.z.string(),Rv).nullish(),PricePolicy:Ts.nullish(),Commission:Xo.nullish(),HoldingPolicy:Cv.nullish(),Moderation:Sv.nullish(),Limits:xv.nullish(),Featured:zod.z.array(bv).nullish()}).passthrough(),Pv=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()}).passthrough(),Zt=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:Ae.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:av.nullish(),Access:zod.z.array(gv).nullish(),Status:uv.nullish(),ModerationNote:zod.z.string().nullish(),Stats:Pv.nullish(),Revision:zod.z.number().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),PublishedAt:u.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),vv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Ba.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),Zh=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(),Yh=zod.z.object({Definitions:Dv.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(Zh).nullish()}).passthrough(),Gr=zod.z.object({Items:zod.z.array(Zt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Xh=zod.z.object({Content:Zt.nullish(),AccessState:zod.z.array(vv).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),em=zod.z.object({Collection:Zh.nullish(),Items:zod.z.array(Zt).nullish()}).passthrough(),tm=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:Ae.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(Zt).nullish()}).passthrough(),$h=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(),im=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array($h).nullish(),ThumbnailUpload:$h.nullish(),ExpiresAt:u.nullish()}).passthrough(),nm=zod.z.object({Content:Zt.nullish(),Resources:w.nullish()}).passthrough(),qa=zod.z.object({Content:Zt.nullish()}).passthrough(),sm=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Jh.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:St.nullish(),Resources:w.nullish(),CommissionTaken:ae.nullish()}).passthrough(),Iv=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),rm=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:hv.nullish(),Files:zod.z.array(Iv).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:u.nullish()}).passthrough(),zv=zod.z.object({ContentID:zod.z.string().nullish(),Source:Jh.nullish(),OptionID:zod.z.string().nullish(),PricePaid:ae.nullish(),AcquiredAt:u.nullish(),Content:Zt.nullish()}).passthrough(),om=zod.z.object({Licenses:zod.z.array(zv).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),je={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 Nr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Workshop",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(je.GetDefinitions,e,Yh)}browse(e){return this.send(je.Browse,e,Gr)}getContent(e){return this.send(je.GetContent,e,Xh)}getCollection(e){return this.send(je.GetCollection,e,em)}getCreatorProfile(e){return this.send(je.GetCreatorProfile,e,tm)}beginUpload(e){return this.send(je.BeginUpload,e,im)}publish(e){return this.send(je.Publish,e,nm)}updateContent(e){return this.send(je.UpdateContent,e,qa)}unpublish(e){return this.send(je.Unpublish,e,qa)}getMyContent(e){return this.send(je.GetMyContent,e,Gr)}acquire(e){return this.send(je.Acquire,e,sm)}getDownload(e){return this.send(je.GetDownload,e,rm)}getMyLicenses(e){return this.send(je.GetMyLicenses,e,om)}getMyFavorites(e){return this.send(je.GetMyFavorites,e,Gr)}};var Vr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i,n){let s=E(this.ctx.settings.titleID,"DataCollections",e,t.UserID??"");return this.ctx.transport.post(s,t,i,{ticket:t.ClientSessionTicket,throttleKey:`${s}|${n}`})}sendPublic(e,t,i,n){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${n}`})}getDefinitions(e){return this.send("GetDefinitions",e,qp,"defs")}get(e){return this.send("Get",e,na,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.send("GetMany",e,Gp,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.send("Query",e,sa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.send("Count",e,Np,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.send("Create",e,ra,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.send("Update",e,ra,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.send("Delete",e,Vp,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.send("Batch",e,jp,e.RelatedEntityID??"batch")}getCounter(e){return this.send("GetCounter",e,Fp,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.send("GetMyRoles",e,Wp,"roles")}beginFileUpload(e){return this.send("BeginFileUpload",e,Lp,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,_p,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,na,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,sa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Fr=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.settings=Fa(e),this.emitter=new Si,this.platform=e.platform??new ii,this.clientPlatform=e.clientPlatform??tl(),this.acquisition=new Lt(this.platform),this.acquisition.capture(),this.playtime=new xi(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear();}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new Zi({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 tn(this.emitter),this.cache=new sn(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new rn(this.platform.storage,this.settings.titleID),this.api={authentication:new Ns(this),user:new Fs(this),currency:new js(this),item:new Ks(this),store:new Qs(this),purchase:new Zs(this),lootbox:new er(this),reward:new tr(this),quest:new ar(this),tutorial:new ir(this),communityMarketing:new nr(this),chat:new sr(this),push:new rr(this),localization:new or(this),timedEvent:new lr(this),leaderboard:new ur(this),season:new cr(this),premium:new pr(this),character:new dr(this),match:new hr(this),craft:new fr(this),ai:new gr(this),collection:new Rr(this),coopEvent:new Cr(this),dealOffer:new Sr(this),referral:new xr(this),mailbox:new br(this),social:new Dr(this),timedBoost:new Ir(this),userCustomData:new zr(this),titleCustomData:new kr(this),title:new Or(this),gameLoop:new Ur(this),cloudCode:new Er(this),blockchain:new Br(this),marketplace:new qr(this),multiplayer:new Lr(this),workshop:new Nr(this),dataCollections:new Vr(this),analytics:new Ls(this),experiment:new Gs(this)},this.userService=new cn(this),this.cache.attachState(this.userService),this.auth=new on(this),this.currency=new dn(this),this.item=new hn(this),this.store=new yn(this),this.purchase=new Rn(this),this.checkout=new Cn(this),this.lootbox=new Sn(this),this.reward=new xn(this),this.quest=new wn(this),this.tutorial=new Dn(this),this.communityMarketing=new Pn(this),this.chat=new zn(this),this.push=new Tn(this),this.localization=new An(this),this.timedEvent=new Un(this),this.leaderboard=new Vn(this),this.season=new Wn(this),this.premium=new _n(this),this.character=new Hn(this),this.match=new $n(this),this.craft=new Jn(this),this.ai=new Yn(this),this.collection=new Xn(this),this.coopEvent=new is(this),this.dealOffer=new rs(this),this.referral=new os(this),this.mailbox=new us(this),this.social=new ds(this),this.timedBoost=new hs(this),this.userCustomData=new gs(this),this.titleCustomData=new ys(this),this.title=new Rs(this),this.gameLoop=new Cs(this),this.cloudCode=new Ss(this),this.blockchain=new Ps(this),this.marketplace=new As(this),this.multiplayer=new ws(this),this.workshop=new Ms(this),this.dataCollections=new Us(this),this.analytics=new Bs(this),this.experiments=new qs(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:q()}}};var jr=class{ctx;constructor(e){this.ctx=new Fr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let n=this.ctx.buildAuthedBaseRequest(),s=E(this.ctx.settings.titleID,e,t,n.UserID??"");return this.ctx.transport.post(s,{...n,...i},zod.z.unknown(),{ticket:n.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get platform(){return this.ctx.platform}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function kv(a){return new jr(a)}var am="idos_sso",lm="state",La="idos:sso:state",Av="https://idosgames.com/sso/";function wv(){if(typeof window>"u")return null;let a=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!a)return null;let e=new URLSearchParams(a),t=e.get(am);if(!t)return null;let i=e.get(lm)??"",n=Bv();return Lv(e),qv(),n&&i!==n?null:{code:t,state:i}}function Mv(a){if(typeof window>"u")return;let e=a.returnTo??Ov(),t=Uv();Ev(t);let i=new URL(a.ssoUrl??Av);i.searchParams.set("title",a.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function Ov(){let{origin:a,pathname:e,search:t}=window.location;return `${a}${e}${t}`}function Uv(){let a=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(a);else for(let e=0;e<a.length;e++)a[e]=Math.floor(Math.random()*256);return Array.from(a,e=>e.toString(16).padStart(2,"0")).join("")}function Ev(a){try{window.sessionStorage.setItem(La,a);}catch{}}function Bv(){try{return window.sessionStorage.getItem(La)}catch{return null}}function qv(){try{window.sessionStorage.removeItem(La);}catch{}}function Lv(a){a.delete(am),a.delete(lm);let e=a.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}function Gv(a,e){return !!a?.Claims?.[e]?.ClaimedAt}function Nv(a){let e=a?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function Vv(a,e){return a?.Claims?.[e]?.PremiumTiers??[]}function cm(a,e,t,i=1){if(!a)return e;let n=a.Base??e,s=Math.max(0,t-i),o;switch(a.Shape??"Flat"){case "PerStep":o=n+(a.PerStep??0)*s;break;case "PerStepRate":o=n*(1+(a.PerStepRate??0)*s);break;case "Geometric":o=n*Math.pow(1+(a.GrowthRate??0),s);break;case "Table":o=n*um(a,t,1);break;case "TableAbsolute":o=um(a,t,n);break;default:o=n;break}return Number.isNaN(o)?n:(a.MinResult!=null&&o<a.MinResult&&(o=a.MinResult),a.MaxResult!=null&&o>a.MaxResult&&(o=a.MaxResult),o)}function Fv(a,e,t=1){return cm(a,1,e,t)}function jv(a){if(!a)return false;switch(a.Shape??"Flat"){case "PerStep":return (a.PerStep??0)!==0;case "PerStepRate":return (a.PerStepRate??0)!==0;case "Geometric":return (a.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return pm(a.Points).length>0;default:return a.MinResult!=null||a.MaxResult!=null}}function Wv(a){if(Number.isNaN(a)||a<=0)return 0;if(!Number.isFinite(a))return Number.MAX_SAFE_INTEGER;let e=Math.round(a);return Math.abs(a-e)<=1e-9*Math.max(1,Math.abs(a))?e:Math.ceil(a)}function pm(a){if(!a)return [];let e=[];for(let t of a)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function um(a,e,t){let i=pm(a.Points);if(i.length===0)return t;let n=null,s=null,o=null;for(let c of i)(o===null||c.AtStep>o.AtStep)&&(o=c),c.AtStep<=e&&(n===null||c.AtStep>=n.AtStep)&&(n=c),c.AtStep>e&&(s===null||c.AtStep<s.AtStep)&&(s=c);if(n===null)return t;if(s===null){let c=a.TailGrowthRate??0;return c===0?o.Value:o.Value*Math.pow(1+c,e-o.AtStep)}switch(a.Interpolation??"Step"){case "Linear":{let c=(e-n.AtStep)/(s.AtStep-n.AtStep);return n.Value+c*(s.Value-n.Value)}case "Geometric":{if(n.Value<=0||s.Value<=0){let d=(e-n.AtStep)/(s.AtStep-n.AtStep);return n.Value+d*(s.Value-n.Value)}let c=(e-n.AtStep)/(s.AtStep-n.AtStep);return n.Value*Math.pow(s.Value/n.Value,c)}default:return n.Value}}var _v={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Ga=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),Kv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Qv=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),Hv=zod.z.object({PlacementID:zod.z.string().nullish(),Type:Ga.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(),$v=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(),Jv=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),Zv=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:Qv.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),Yv=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),Xv=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),eI=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(),tI=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(),iI=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),nI=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:Ga.nullish()}).passthrough(),sI={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},rI=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),oI=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:rI.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(),nI).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),Hv).nullish(),Providers:zod.z.record(zod.z.string(),oI).nullish(),RewardedVideo:$v.nullish(),Interstitial:Jv.nullish(),Banner:Zv.nullish(),AppOpen:Yv.nullish(),FrequencyCapping:Xv.nullish(),PremiumAdReductions:zod.z.array(eI).nullish(),Consent:tI.nullish(),Verification:iI.nullish()}).passthrough();var aI=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),lI=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:u.nullish(),LastCompletedAt:u.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),uI=zod.z.object({Date:u.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),cI=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:u.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),pI=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:u.nullish(),ConsentRevokedAt:u.nullish()}).passthrough(),dI=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:Ga.nullish(),IssuedAt:u.nullish(),ExpiresAt:u.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),hI=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:u.nullish()}).passthrough();zod.z.object({Credits:aI.nullish(),Placements:zod.z.record(zod.z.string(),lI).nullish(),Daily:uI.nullish(),Session:cI.nullish(),LastImpressionAt:u.nullish(),LastInterstitialAt:u.nullish(),LastRewardedAt:u.nullish(),LastAppOpenAt:u.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:u.nullish(),Consent:pI.nullish(),PendingRequests:zod.z.record(zod.z.string(),dI).nullish(),FraudFlags:hI.nullish(),UpdatedAt:u.nullish()}).passthrough();var dm="idos_device_id",Wr=class{storage;constructor(e=new ei){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(dm);return e||(e="noop-device",this.storage.setString(dm,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};
1
+ 'use strict';var zod=require('zod'),Nt=require('decimal.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Nt__default=/*#__PURE__*/_interopDefault(Nt);var Si=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,n=>{i(),t(n);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let n of [...i])n(t);}removeAllListeners(){this.listeners.clear();}};function hm(){let a=new Map;return {get:e=>a.get(e)??null,set:(e,t)=>{a.set(e,t);},remove:e=>{a.delete(e);}}}function Na(){return mm()??hm()}function mm(){try{let a=globalThis.localStorage;if(!a)return null;let e="__idos_probe__";return a.setItem(e,"1"),a.removeItem(e),{get:t=>{try{return a.getItem(t)}catch{return null}},set:(t,i)=>{try{a.setItem(t,i);}catch{try{a.removeItem(t);}catch{}}},remove:t=>{try{a.removeItem(t);}catch{}}}}catch{return null}}var Va="https://api.idosgames.com";function Fa(a){return {titleID:a.titleID,titleTemplateID:a.titleTemplateID??"default",buildKey:a.buildKey??"",baseUrl:(a.baseUrl??Va).replace(/\/+$/,""),devBuild:a.devBuild??false,debugLogging:a.debugLogging??false,configStorage:a.configStorage??Na(),locale:a.locale??fm(),appVersion:a.appVersion??""}}function fm(){try{return globalThis.navigator?.language??""}catch{return ""}}var Xt=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{}}},ei=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 ti(){return globalThis.Telegram?.WebApp??null}function q(){return crypto.randomUUID()}var ja="idos_device_id",ii=class{storage;constructor(e=new Xt){this.storage=e;}getPlatform(){return ti()?.platform??"Web"}getFullURL(){return typeof location<"u"?location.href:""}getStartParameter(){let e=ti()?.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=ti()?.initData;return e&&e.length>0?e:null}getDeviceID(){let e=this.storage.getString(ja);return e||(e=q(),this.storage.setString(ja,e)),e}getDeviceModel(){return typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:"Web"}shareLink(e){let t=ti();if(t?.openTelegramLink){t.openTelegramLink(e);return}typeof window<"u"&&window.open(e,"_blank");}openInvoice(e){let t=ti();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 _r="idos_acq",Wa=["gclid","fbclid","ttclid","msclkid","yclid"],gm=["ref","r"],ym=["ref_","ref-","ref=","r_","r-"];var Lt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();Rm(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},n=xm(this.platform.getDeviceModel());return n&&(i.OsVersion=n),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(_r);}static detectDevicePlatform(e){let t=(e||"").toLowerCase();return t.includes("android")?"Android":/iphone|ipad|ipod/.test(t)?"iOS":"Web"}static parseReferralCode(e){if(!e)return null;let t=e.trim();if(!t)return null;if(t.includes("://")||t.includes("?")){let i=Qa(Ka(t));if(i)return i}return qi(t)}readFromEnvironment(){let e={},t=Ka(this.platform.getFullURL());qt(e,"UtmSource",t.get("utm_source")),qt(e,"UtmMedium",t.get("utm_medium")),qt(e,"UtmCampaign",t.get("utm_campaign")),qt(e,"UtmTerm",t.get("utm_term")),qt(e,"UtmContent",t.get("utm_content")),qt(e,"ClaimToken",t.get("idos_click"));for(let R of Wa){let V=t.get(R);if(V){e.ClickID=V;break}}let i=this.platform.getStartParameter()??"",n=Sm(i);if(n){for(let R of Cm)qt(e,R,n.get(Ha[R])??null);for(let R of Wa){let V=n.get(R);if(V){e.ClickID=V;break}}}let s=qi(n?n.get("ref")??n.get("r")??"":i),o=Qa(t),c=s||o;c&&(e.ReferralCode=c,e.ChannelHint=s?"telegram":"query");let d=this.platform.getReferrer?.();return d&&(e.Referrer=d),e}read(){try{let e=this.platform.storage.getString(_r);if(!e)return null;let t=JSON.parse(e);return !t?.signal||typeof t.capturedAt!="number"?null:Date.now()-t.capturedAt>2592e6?(this.clear(),null):t}catch{return null}}store(e){try{this.platform.storage.setString(_r,JSON.stringify(e));}catch{}}};function Rm(a){return !!(a.UtmSource||a.UtmMedium||a.UtmCampaign||a.ClickID||a.Referrer||a.ReferralCode||a.ClaimToken)}function qt(a,e,t){t&&(a[e]=t);}var _a="a1_",Ha={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},Cm=Object.keys(Ha);function Sm(a){let e=(a||"").trim();if(!e.startsWith(_a))return null;let t=e.slice(_a.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(i+"=".repeat((4-i.length%4)%4)),s=Uint8Array.from(n,d=>d.charCodeAt(0)),o=new TextDecoder().decode(s),c=new URLSearchParams(o);return [...c.keys()].length>0?c:null}catch{return null}}function Ka(a){try{let e=a.indexOf("?");return new URLSearchParams(e>=0?a.slice(e):"")}catch{return new URLSearchParams}}function Qa(a){for(let e of gm){let t=a.get(e);if(t)return qi(t)}return null}function qi(a){let e=(a||"").trim();if(!e)return null;for(let t of ym)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function xm(a){let e=a||"",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 $a="idos_usage_pending",Ja="idos_usage_session",Za="idos_usage_closed_session",Ya="idos_usage_new_session",Xa="idos_usage_last_activity",xi=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($a),this.currentSessionSeconds=this.readNumber(Ja),this.pendingClosedSessionSeconds=this.readNumber(Za),this.isNewSessionPending=this.readNumber(Ya)!==0;let e=this.readNumber(Xa);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($a,this.pendingSeconds),this.writeNumber(Ja,this.currentSessionSeconds),this.writeNumber(Za,this.pendingClosedSessionSeconds),this.writeNumber(Ya,this.isNewSessionPending?1:0),this.writeNumber(Xa,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 lt={Virtual:"Virtual",Crypto:"Crypto"},si=zod.z.enum(["Virtual","Crypto"]).catch("Virtual"),Li={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase"},ri=zod.z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase"]).catch("Item"),ht={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Gi=zod.z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),bm={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Ni=zod.z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),Dm={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Vi=zod.z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),Pm={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},bi=zod.z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),Te={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function tl(){let a=globalThis,e=a.Capacitor?.getPlatform?.();if(e)return el(e);let t=a.cordova?.platformId;return t?el(t):a.navigator?.userAgent??""?ht.Web:ht.Unknown}function el(a){let e=a.toLowerCase();return e==="android"?ht.Android:e==="ios"?ht.Ios:e==="web"?ht.Web:ht.Unknown}function G(a){return {ok:true,data:a}}function r(a,e){return {ok:false,reason:a,error:e}}function vm(a){return a.ok}function Im(a){return !a.ok}var j=zod.z.union([zod.z.number(),zod.z.string()]).transform((a,e)=>{let t=typeof a=="string"?Number(a):a;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(a)}`}),zod.z.NEVER)}),Y=zod.z.union([zod.z.number(),zod.z.string()]).transform((a,e)=>{let t=typeof a=="number"?String(a):a.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:zod.z.ZodIssueCode.custom,message:`Invalid decimal: ${String(a)}`}),zod.z.NEVER):t}),u=zod.z.string();var Kr=zod.z.object({Type:ri.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()}),zm=zod.z.object({Type:Vi.nullish(),EntityID:zod.z.string()}),Tm=zod.z.object({Address:zm.nullish(),Amount:j.nullish(),Source:zod.z.string().nullish()}),ae=zod.z.object({Entries:zod.z.array(Kr).nullish(),EventTokens:zod.z.array(Tm).nullish()}),il=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Resources:ae.nullish()}),Q=zod.z.object({Standard:ae.nullish(),PremiumBonuses:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(il).nullish()}),Ct=zod.z.object({Standard:ae.nullish(),PremiumDiscounts:zod.z.array(zod.z.unknown()).nullish(),PremiumTiers:zod.z.array(il).nullish()}),w=zod.z.object({Grant:Q.nullish(),Consume:Ct.nullish()}),St=zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),FromResult:w.nullish(),ToResult:w.nullish()});zod.z.object({FromUserID:zod.z.string().nullish(),ToUserID:zod.z.string().nullish(),Transferred:ae.nullish()});var km=zod.z.object({ExperimentID:zod.z.string().nullish(),Variants:zod.z.array(zod.z.string()).nullish()}).passthrough(),Am={Completed:"Completed",Started:"Started",StepReached:"StepReached"},wm=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(),$=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:km.nullish(),Tutorial:wm.nullish(),Platforms:zod.z.array(Gi).nullish()}).passthrough();var fe=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 Mm=zod.z.object({OffsetSecondsFromParentStart:zod.z.number().nullish(),DurationSeconds:zod.z.number().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Om=zod.z.object({StartUtc:zod.z.string().nullish(),EndUtc:zod.z.string().nullish(),AllowEarningAfterEnd:zod.z.boolean().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),Um=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 Em=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 it=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:fe.nullish()}).passthrough(),de=zod.z.object({Mode:zod.z.string().nullish(),IsActive:zod.z.boolean().nullish(),Scheduled:Om.nullish(),Chain:Um.nullish(),Cyclic:Em.nullish(),ActivationTriggers:zod.z.array(it).nullish(),Relative:Mm.nullish()}).passthrough();var Bm={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},qm=zod.z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Lm={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Gm=zod.z.enum(["Step","Linear","Geometric"]).catch("Step"),Nm=zod.z.object({AtStep:zod.z.number().nullish(),Value:zod.z.number().nullish()}).passthrough(),Le=zod.z.object({Base:zod.z.number().nullish(),Shape:qm.nullish(),PerStep:zod.z.number().nullish(),PerStepRate:zod.z.number().nullish(),GrowthRate:zod.z.number().nullish(),Points:zod.z.array(Nm).nullish(),Interpolation:Gm.nullish(),TailGrowthRate:zod.z.number().nullish(),MinResult:zod.z.number().nullish(),MaxResult:zod.z.number().nullish()}).passthrough();var Vm=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Rewards:Q.nullish()}).passthrough(),Fm=zod.z.object({SeasonChainID:zod.z.string().nullish(),MinSeasonTier:zod.z.number().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),Qr=zod.z.object({Bundles:zod.z.array(Vm).nullish(),Multipliers:zod.z.array(Fm).nullish()}).passthrough();var jm=zod.z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Fi=zod.z.object({Source:jm.nullish(),SourceKey:zod.z.string().nullish(),Curve:Le.nullish(),Anchor:zod.z.number().nullish(),IncludeRewards:ae.nullish(),ExcludeRewards:ae.nullish()}).passthrough(),nl=zod.z.object({ClaimedAt:zod.z.string().nullish(),PremiumTiers:zod.z.array(zod.z.string()).nullish(),Unlocked:zod.z.boolean().nullish()}).passthrough(),Ee=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:Q.nullish(),BonusRewards:Q.nullish(),SeasonTierRewards:Qr.nullish(),SortOrder:zod.z.number().nullish(),IsFeatured:zod.z.boolean().nullish()}).passthrough(),oi=zod.z.object({Milestones:zod.z.record(zod.z.string(),Ee).nullish()}).passthrough();var _=zod.z.object({PresetID:zod.z.string().nullish(),Remove:zod.z.array(zod.z.string()).nullish()}).passthrough();var Wm=zod.z.object({TargetCurrencyID:zod.z.string().nullish(),Rate:zod.z.number().nullish(),MaxConvertAmount:zod.z.number().nullish()}).passthrough(),Gt=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:Wm.nullish()}).passthrough();var _m=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),sl=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),EquippedSlot:_m.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(a=>a),K=zod.z.object({ChangedInstances:zod.z.record(zod.z.string(),sl).nullish(),RemovedInstanceIDs:zod.z.array(zod.z.string()).nullish()});var be=a=>zod.z.object({Id:zod.z.string(),Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:a.nullish()}),mt=a=>zod.z.object({ServerTimeUtc:u,Items:zod.z.array(be(a)),Resources:w.nullish(),Inventory:K.nullish()});var Km={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},rl=zod.z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),Qm=zod.z.object({}).passthrough().transform(a=>a),Hm=zod.z.object({CycleID:zod.z.string(),InstanceKey:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),CycleStartUtc:u.nullish(),CycleEndUtc:u.nullish(),PointsTotalEarned:j.nullish(),PointsCurrent:j.nullish(),ClaimedPointMilestoneIDs:zod.z.array(zod.z.string()).nullish(),NextMilestone:Ee.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),Hr=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:rl}),ol=zod.z.object({State:Qm.nullish(),PointsTracks:zod.z.record(zod.z.string(),Hm).nullish()}),$r=zod.z.object({ServerTimeUtc:u,QuestID:zod.z.string(),CycleID:zod.z.string().nullish(),NewStatus:rl.nullish(),Resources:w.nullish(),Inventory:K.nullish()}),Jr=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),MilestoneID:zod.z.string(),PointsTotalEarned:j.nullish(),Resources:w.nullish(),Inventory:K.nullish(),NextMilestone:Ee.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish()}),al=zod.z.object({ServerTimeUtc:u,CycleID:zod.z.string(),GroupCompletionID:zod.z.string(),GroupID:zod.z.string().nullish(),CompletedGroupQuests:zod.z.number().nullish(),RequiredGroupQuests:zod.z.number().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),ll=zod.z.object({MetricID:zod.z.string(),Updates:zod.z.array(Hr).nullish()}),ul=zod.z.array(be($r)),cl=zod.z.array(be(Jr)),$m={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},Jm=zod.z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),Zm={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},Ym=zod.z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),pl=zod.z.object({ObjectiveID:zod.z.string().nullish(),Source:Jm.nullish(),MaxProgressPerCall:zod.z.number().nullish(),MetricID:zod.z.string().nullish(),Triggers:zod.z.array(it).nullish(),TargetValue:zod.z.number().nullish(),AggregationMethod:zod.z.string().nullish()}).passthrough(),Zr=zod.z.object({Milestones:_.nullish(),Linking:_.nullish(),Availability:_.nullish(),Reward:_.nullish(),Objectives:_.nullish()}).passthrough(),Xm=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(),dl=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:Ym.nullish()}).passthrough(),hl=zod.z.object({Schedule:de.nullish(),AccrueProgressWhenLocked:zod.z.boolean().nullish(),Gate:$.nullish(),Limits:fe.nullish()}).passthrough(),ml=zod.z.object({Grant:Q.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),ef=zod.z.object({QuestID:zod.z.string().nullish(),Identity:Xm.nullish(),Linking:dl.nullish(),Availability:hl.nullish(),Objectives:zod.z.record(zod.z.string(),pl).nullish(),Reward:ml.nullish(),Presets:Zr.nullish()}).passthrough(),tf=zod.z.object({CompletionID:zod.z.string().nullish(),GroupID:zod.z.string().nullish(),RequiredCompletedQuests:zod.z.number().nullish(),Gate:$.nullish(),Reward:Q.nullish(),PointsReward:zod.z.number().nullish()}).passthrough(),nf=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:$.nullish(),Milestones:zod.z.record(zod.z.string(),Ee).nullish(),Presets:Zr.nullish(),PointsToken:Gt.nullish()}).passthrough(),sf=zod.z.object({Milestones:zod.z.record(zod.z.string(),oi).nullish(),Linking:zod.z.record(zod.z.string(),dl).nullish(),Availability:zod.z.record(zod.z.string(),hl).nullish(),Reward:zod.z.record(zod.z.string(),ml).nullish(),Objectives:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),pl)).nullish()}).passthrough(),rf=zod.z.object({CycleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:de.nullish(),Milestones:zod.z.record(zod.z.string(),Ee).nullish(),Gate:$.nullish(),PointsToken:Gt.nullish(),GroupCompletions:zod.z.record(zod.z.string(),tf).nullish(),Phases:zod.z.record(zod.z.string(),nf).nullish(),Presets:Zr.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Wi=zod.z.object({Cycles:zod.z.record(zod.z.string(),rf).nullish(),Quests:zod.z.record(zod.z.string(),ef).nullish(),Presets:sf.nullish()}).passthrough(),ct={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var of={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},af=zod.z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),lf={Never:"Never",OnRequest:"OnRequest",Always:"Always"},uf=zod.z.enum(["Never","OnRequest","Always"]).catch("Never"),cf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},pf=zod.z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),df={GameLoop:"GameLoop"},hf={Raid:"Raid",Attack:"Attack"},mf=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(),ff=zod.z.object({Mode:af.nullish(),Triggers:zod.z.array(it).nullish(),TargetValue:zod.z.number().nullish(),RequireAllTriggers:zod.z.boolean().nullish()}).passthrough(),gf=zod.z.object({Grant:Q.nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),yf=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(),Rf=zod.z.object({Module:zod.z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:yf.nullish(),MaxUses:zod.z.number().nullish()}).passthrough(),Cf=zod.z.object({Skippable:zod.z.boolean().nullish(),TimeoutSeconds:zod.z.number().nullish()}).passthrough(),Yr=zod.z.object({StepID:zod.z.string().nullish(),Order:zod.z.number().nullish(),Identity:mf.nullish(),Completion:ff.nullish(),Effects:gf.nullish(),Script:Rf.nullish(),Policy:Cf.nullish()}).passthrough(),Sf=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(),fl=zod.z.object({Schedule:de.nullish(),Gate:$.nullish(),RequiredFlowIDs:zod.z.array(zod.z.string()).nullish(),AutoStart:zod.z.boolean().nullish(),StartTrigger:it.nullish()}).passthrough(),gl=zod.z.object({Skippable:zod.z.boolean().nullish(),SkippableFromOrder:zod.z.number().nullish(),RestartPolicy:uf.nullish(),ExpireAfterSeconds:zod.z.number().nullish(),IsBlocking:zod.z.boolean().nullish(),UnlockFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),yl=zod.z.object({Grant:Q.nullish(),AutoClaim:zod.z.boolean().nullish()}).passthrough(),xf=zod.z.object({Availability:_.nullish(),Policy:_.nullish(),Reward:_.nullish(),Steps:_.nullish()}).passthrough(),bf=zod.z.object({FlowID:zod.z.string().nullish(),Identity:Sf.nullish(),Availability:fl.nullish(),Policy:gl.nullish(),Steps:zod.z.record(zod.z.string(),Yr).nullish(),Reward:yl.nullish(),Presets:xf.nullish()}).passthrough(),Df=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(),Pf=zod.z.object({IsEnabled:zod.z.boolean().nullish(),MaxActiveFlows:zod.z.number().nullish(),Blocking:Df.nullish()}).passthrough(),vf=zod.z.object({Availability:zod.z.record(zod.z.string(),fl).nullish(),Policy:zod.z.record(zod.z.string(),gl).nullish(),Reward:zod.z.record(zod.z.string(),yl).nullish(),Steps:zod.z.record(zod.z.string(),zod.z.record(zod.z.string(),Yr)).nullish()}).passthrough(),Rl=zod.z.object({Flows:zod.z.record(zod.z.string(),bf).nullish(),Settings:Pf.nullish(),Presets:vf.nullish()}).passthrough(),If=zod.z.object({}).passthrough().transform(a=>a),Cl=zod.z.object({FlowID:zod.z.string(),Status:pf,CurrentStepID:zod.z.string().nullish(),CurrentStep:Yr.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(),_i=zod.z.object({State:If.nullish(),Flows:zod.z.array(Cl).nullish(),UnlockedFeatures:zod.z.array(zod.z.string()).nullish()}).passthrough(),kt=zod.z.object({Flow:Cl.nullish()}).passthrough(),Sl=zod.z.object({FlowID:zod.z.string().nullish(),Granted:w.nullish()}).passthrough(),xl=zod.z.array(be(kt)),bl=zod.z.object({FlowID:zod.z.string(),StepID:zod.z.string(),Progress:zod.z.number(),Target:zod.z.number(),Completed:zod.z.boolean()}).passthrough(),nt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Ki(a){return Array.isArray(a)?a.filter(e=>e!==null).map(Ki):a!==null&&typeof a=="object"?Object.fromEntries(Object.entries(a).filter(([,e])=>e!==null).map(([e,t])=>[e,Ki(t)])):a}var Qi=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var Hi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Dl(a){return a===429||a>=500&&a<=599}function $i(a,e=Math.random){let t=Math.min(500*Math.pow(2,a-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function li(a){return new Promise(e=>setTimeout(e,a))}function Pl(a,e=Math.random){let t=a<=1?1500:a===2?4e3:6e3;return t+t*.1*e()}var Xr=15,vl=1e3,Ji=class{constructor(e=Xr,t=()=>Date.now(),i=li){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]>=vl;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(vl-(e-this.starts[0])+5);}}};var zf=12e3,Tf=new Set(["RelatedEntityID"]);function kf(a,e){if(e===null||typeof e!="object"||Array.isArray(e))return a;let t={};for(let[i,n]of Object.entries(e))Tf.has(i)||(t[i]=n);try{return `${a}|${JSON.stringify(t)}`}catch{return a}}var Af=zod.z.object({Success:zod.z.boolean(),Error:zod.z.string().nullish(),Data:zod.z.unknown().optional(),QuestProgress:zod.z.array(Hr).nullish(),TutorialProgress:zod.z.array(bl).nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish(),StateEpoch:zod.z.string().nullish()}).passthrough(),Zi=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Hi;pacer;inFlightRequests=0;sessionRefreshHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new Qi(e.throttleMs),this.pacer=new Ji(e.maxRequestsPerSecond??Xr),this.clientPlatform=e.clientPlatform??ht.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}async post(e,t,i,n={}){let s=n.throttleKey??kf(e,t);if(!this.throttler.tryAcquire(s))return r("throttled","Throttled");if(!this.inflight.add(s))return r("throttled","Duplicate request skipped");this.raiseBusy();try{let o=`${this.baseUrl}/${e}`,c=JSON.stringify(t),d=n.ticket??null,R=n.silent??!1,V=n.timeoutMs??zf,se=n.autoRetry??!0,me=!1,xe=0;for(;;){let He;n.keepalive||await this.pacer.take();try{He=await this.doFetch(o,c,d,V,n.keepalive??!1);}catch{if(se&&xe<3){xe++,await li($i(xe));continue}return this.connectionFailure("Internet Connection Error",R)}let et=He.status;if(et>=200&&et<300)return await this.parseSuccess(He,i,R,e);if(et===401){if(!me&&this.sessionRefreshHandler){me=!0;let Yt=null;try{Yt=await this.sessionRefreshHandler();}catch{Yt=null;}if(Yt){d=Yt;continue}}return this.emitter.emit("auth:unauthorized",void 0),r("unauthorized","Unauthorized")}if(Dl(et)){if(se&&xe<3){xe++,await li(et===429?Pl(xe):$i(xe));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${et})`,R)}let zt="";try{zt=await He.text();}catch{}if(et===409&&/operation in progress/i.test(zt)&&se&&xe<3){xe++,await li($i(xe));continue}return this.handleWebError(zt,et,R)}}finally{this.inflight.remove(s),this.lowerBusy();}}async doFetch(e,t,i,n,s=false){let o=new AbortController,c=setTimeout(()=>{o.abort();},n);try{let d={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(d.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:d,signal:o.signal,...s?{keepalive:!0}:{}})}finally{clearTimeout(c);}}async parseSuccess(e,t,i,n){let s;try{s=await e.text();}catch{return this.globalError("Failed to read response body",i)}let o;try{o=JSON.parse(s);}catch{return this.globalError("JSON Parse Error",i)}let c=Af.safeParse(o);if(!c.success)return this.globalError("Malformed response envelope",i);if(!c.data.Success){let me=c.data.Error??"Server returned Success=false";return i||this.emitter.emit("error:global",me),r("server",me)}let d=c.data.StateVersions;d&&Object.keys(d).length>0&&this.emitter.emit("user:stateVersions",{epoch:c.data.StateEpoch??null,versions:d});let R=c.data.QuestProgress;R&&R.length>0&&this.emitter.emit("quest:systemProgress",R);let V=c.data.TutorialProgress;V&&V.length>0&&this.emitter.emit("tutorial:systemProgress",V);let se=t.safeParse(c.data.Data);if(!se.success){let me=t.safeParse(Ki(c.data.Data));me.success&&(se=me);}if(!se.success){let me=`Validation error (${n}): ${se.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",me),i||this.emitter.emit("error:global",me),r("validation",me)}return G(se.data)}handleWebError(e,t,i){let n=`HTTP ${t}`;if(e)try{let o=JSON.parse(e)?.Error;if(t===403&&o==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),r("server","PLAY_ACCESS_REQUIRED");n=typeof o=="string"&&o.length>0?`HTTP ${t}: ${o}`:`HTTP ${t}: ${e}`;}catch{n=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",n),r("server",n)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),r("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),r("server",e)}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 ui(a){return (typeof a=="string"?a:a.toISOString()).slice(0,10)}function Di(a){return `${ui(a)}T00:00:00.000Z`}function Il(a){let e=new Date(a);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function zl(a,e){return new Date(a.getTime()+e*6e4).toISOString()}function to(a,e,t,i){let n={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return n;a.InventoryV2??={};let s=a.InventoryV2,o=i.toISOString(),c=new Map,d=new Map,R=new Map,V=new Map,se=new Map,me=new Map,xe=new Map,He=new Map,et=e.Grant?.PremiumTiers??[],zt=et.length;for(let De=0;;De++){let we,ce;if(De===0)we=e.Grant?.Standard?.Entries,ce=false;else if(De-1<zt)we=et[De-1]?.Resources?.Entries,ce=false;else if(De===1+zt)we=e.Consume?.Standard?.Entries,ce=true;else break;if(we)for(let re of we){if(re.Type==null)continue;let le=Math.max(0,re.Amount??0);if(!(le<=0))switch(re.Type){case "VirtualCurrency":{if(!re.CurrencyID)continue;let ue=ce?d:c;ue.set(re.CurrencyID,(ue.get(re.CurrencyID)??0)+le);break}case "CryptoCurrency":{if(!re.CurrencyID)continue;let ue=ce?V:R;ue.set(re.CurrencyID,(ue.get(re.CurrencyID)??new Nt__default.default(0)).plus(le));break}case "Item":{if(!re.ItemID)continue;let ue=Mf(t,re.CatalogID,re.ItemID),Re=(ue?ue.IsStackable??true:true)?ce?me:se:ce?He:xe;Re.set(re.ItemID,(Re.get(re.ItemID)??0)+le);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(n.vcChanged=c.size>0||d.size>0,n.vcChanged){s.VirtualCurrencies??={};for(let De of new Set([...c.keys(),...d.keys()])){let we=c.get(De)??0,ce=d.get(De)??0,re=we-ce,le=s.VirtualCurrencies[De];le?(le.Amount+=re,le.UpdatedAt=o,le.Daily&&ui(le.Daily.PeriodStartUtc)===ui(i)?(le.Daily.Earned+=we,le.Daily.Spent+=ce):le.Daily={PeriodStartUtc:Di(i),Earned:we,Spent:ce}):s.VirtualCurrencies[De]={Amount:re,CreatedAt:o,UpdatedAt:o,Daily:{PeriodStartUtc:Di(i),Earned:we,Spent:ce}};}}if(n.ccChanged=R.size>0||V.size>0,n.ccChanged){s.CryptoCurrencies??={};for(let De of new Set([...R.keys(),...V.keys()])){let we=R.get(De)??new Nt__default.default(0),ce=V.get(De)??new Nt__default.default(0),re=we.minus(ce),le=s.CryptoCurrencies[De];le?(le.Amount=new Nt__default.default(le.Amount).plus(re).toString(),le.UpdatedAt=o):s.CryptoCurrencies[De]={Amount:re.toString(),Frozen:"0",CreatedAt:o,UpdatedAt:o};}}if(n.itemsChanged=se.size>0||me.size>0||xe.size>0||He.size>0,n.itemsChanged){s.Items??={},s.UnstackableItems??={};let De=s.UnstackableItems,we=new Set([...se.keys(),...me.keys(),...xe.keys(),...He.keys()]);for(let ce of we){let re=(se.get(ce)??0)-(me.get(ce)??0),le=(xe.get(ce)??0)-(He.get(ce)??0),ue=re+le,tt=s.Items[ce];tt?(re!==0&&(tt.StackableAmount+=re),le!==0&&(tt.UnstackableAmount+=le),ue!==0&&(tt.TotalAmount+=ue)):s.Items[ce]={StackableAmount:Math.max(0,re),UnstackableAmount:Math.max(0,le),TotalAmount:Math.max(0,ue)};}for(let[ce,re]of He){if(re<=0)continue;let le=Object.values(De).filter(ue=>ue.ItemID===ce&&ue.EquippedSlot==null&&(ue.ExpiresAt==null||new Date(ue.ExpiresAt)>i)).sort(wf).slice(0,re).map(ue=>ue.ItemInstanceID);for(let ue of le)delete De[ue];}for(let[ce,re]of xe){let le=Of(t,ce);for(let ue=0;ue<re;ue++){let tt=q();De[tt]={ItemInstanceID:tt,ItemID:ce,CatalogID:le,RemainingUses:1,AcquiredAt:o};}}}a.EventToken??={};let Yt=a.EventToken;for(let De=0;;De++){let we,ce;if(De===0)we=e.Grant?.Standard?.EventTokens,ce=false;else if(De-1<zt)we=et[De-1]?.Resources?.EventTokens,ce=false;else if(De===1+zt)we=e.Consume?.Standard?.EventTokens,ce=true;else break;if(!(!we||we.length===0))for(let re of we){let le=re.Address;if(!le||le.Type==null)continue;let ue=re.Amount??0;if(ue<=0)continue;let tt=Uf(Yt,le.Type);if(!tt)continue;let Re=tt[le.EntityID];Re||(Re={},tt[le.EntityID]=Re),Re.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Re.Daily??={Date:Di(i),TotalEarned:0},Re.Meta??={};let Ci=re.Source&&re.Source.length>0?re.Source:"CustomAction";ce?(Re.Balance.Current-=ue,Re.Balance.TotalSpent+=ue):(Re.Balance.Current+=ue,Re.Balance.TotalEarned+=ue,ui(Re.Daily.Date)!==ui(i)&&(Re.Daily={Date:Di(i),TotalEarned:0}),Re.Daily.TotalEarned+=ue,Re.Daily.EarnedBySource??={},Re.Daily.EarnedBySource[Ci]=(Re.Daily.EarnedBySource[Ci]??0)+ue,Re.Daily.TriggersBySource??={},Re.Daily.TriggersBySource[Ci]=(Re.Daily.TriggersBySource[Ci]??0)+1,Re.Daily.LastTriggerBySource??={},Re.Daily.LastTriggerBySource[Ci]=o,Re.Meta.JoinedAtUtc||(Re.Meta.JoinedAtUtc=o),Re.Meta.LastEarnedAtUtc=o),n.tokensChanged=true;}}return n}function wf(a,e){return a.AcquiredAt!==e.AcquiredAt?a.AcquiredAt<e.AcquiredAt?-1:1:a.ItemInstanceID===e.ItemInstanceID?0:a.ItemInstanceID<e.ItemInstanceID?-1:1}function Mf(a,e,t){let i=a?.Catalogs;if(i){if(e){let n=i[e]?.Items?.[t];if(n)return n}for(let n of Object.values(i)){let s=n.Items?.[t];if(s)return s}}}function Of(a,e){let t=a?.Catalogs;if(t){for(let[i,n]of Object.entries(t))if(n.Items&&e in n.Items)return i}}function Uf(a,e){switch(e){case "TimedEvent":return a.TimedEvent??={};case "Quest":return a.Quest??={};case "Leaderboard":return a.Leaderboard??={};case "CoopEvent":return a.CoopEvent??={};case "Season":return a.Season??={};default:return null}}function Tl(a,e,t){let i={drop:[],restore:{}};if(!t)return i;let n=t.ChangedInstances??{},s=new Set(t.RemovedInstanceIDs??[]),o=new Set;for(let d of Object.values(n))d?.ItemID&&o.add(d.ItemID);for(let d of s){let R=a[d]?.ItemID;R&&o.add(R);}if(o.size===0)return i;let c=d=>s.has(d)||d in n;if(e){for(let[d,R]of Object.entries(e))d in a||c(d)||R&&o.has(R.ItemID)&&i.drop.push(d);for(let[d,R]of Object.entries(a))d in e||c(d)||R&&o.has(R.ItemID)&&(i.restore[d]=R);}return i}function io(a,e){return a===e||a.startsWith(`${e}:`)}var Xi=class a{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){a.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];a.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){a.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let n=to(this.currentState,e,t,i);this.emitResourceChanges(n,false);}applyResourcesWithDelta(e,t,i,n=new Date){if(!this.currentState)return;let s=this.currentState,o={...s.InventoryV2?.UnstackableItems??{}},c=to(s,e,i,n),d=Tl(o,s.InventoryV2?.UnstackableItems,t),R=Object.entries(t?.ChangedInstances??{}),V=t?.RemovedInstanceIDs??[],se=d.drop.length>0||Object.keys(d.restore).length>0||R.length>0||V.length>0;if(se){s.InventoryV2??={},s.InventoryV2.UnstackableItems??={};let me=s.InventoryV2.UnstackableItems;for(let xe of d.drop)delete me[xe];for(let[xe,He]of Object.entries(d.restore))me[xe]=He;for(let[xe,He]of R)me[xe]=He;for(let xe of V)delete me[xe];}this.emitResourceChanges(c,se);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,n){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let s=this.currentState.InventoryV2.CryptoCurrencies,o=t instanceof Nt__default.default?t:new Nt__default.default(t),c=n===void 0?new Nt__default.default(0):n instanceof Nt__default.default?n:new Nt__default.default(n),d=i??new Date().toISOString(),R=s[e];R?(R.Amount=new Nt__default.default(R.Amount).plus(o).toString(),c.isZero()||(R.Frozen=new Nt__default.default(R.Frozen??0).plus(c).toString()),R.UpdatedAt=d):s[e]={Amount:o.toString(),Frozen:c.toString(),CreatedAt:d,UpdatedAt:d},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let n=this.currentState.Store.Purchases,s=n[e];s||(s={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},n[e]=s),s.TotalPurchases+=t,s.LastPurchasedAt=i,i>=s.DailyResetUtc?(s.DailyPurchases=t,s.DailyResetUtc=Il(i)):s.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let n=this.currentState.Lootbox??={};if(n.Pity??={},t){let s=new Date().toISOString();for(let o of t)o.RuleID&&(n.Pity[`${e}:${o.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:s});}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 n=this.currentState.Quest;if(t){n.Cycles??={};let s=n.Cycles[t];if(!s)return;s.Quests??={};let o=s.Quests[e]??={QuestID:e,Status:i};o.Status=i,i==="Claimed"&&(o.ClaimedAtUtc??=new Date().toISOString());}else {n.PermanentQuests??={};let s=n.PermanentQuests[e]??={QuestID:e,Status:i};s.Status=i,i==="Claimed"&&(s.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let n=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,s=t[n]??={};s.Balance??={Current:0,TotalEarned:0,TotalSpent:0},s.Balance.Current=i.PointsCurrent??0,s.Balance.TotalEarned=i.PointsTotalEarned??0,s.Milestone??={};for(let o of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(s.Milestone,o);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let n=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};n.Steps??={};let s=n.Steps[i.StepID]??={StepID:i.StepID};s.Progress=i.Progress,i.Completed&&(s.CompletedAtUtc??=new Date().toISOString(),n.CurrentStepID===i.StepID&&(n.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let n;if(!i.CycleID)t.PermanentQuests??={},n=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let s=t.Cycles[i.CycleID];if(!s)continue;s.Quests??={},n=s.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(n.Status=i.Status,i.ObjectiveID){n.Objectives??={};let s=n.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};s.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(s.Completed=true,s.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(n.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,n]of Object.entries(t))if(io(i,e)&&n)return n;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,n){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[s,o]of Object.entries(this.currentState.EventToken.TimedEvent))o&&((n?s!==n:!io(s,t))||this.markMilestoneClaimed(o.Milestone??(o.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,n),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,n){let s=this.activeEventsCache?.ActiveEvents;if(s)for(let o of s)o.Type!==e||o.TimedEventID!==t||n&&o.TokenEntityID&&o.TokenEntityID!==n||(o.Progress??={},this.markMilestoneClaimed(o.Progress.Milestone??(o.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,n){if(!e)return;let s=this.ensureLeaderboardProgress(e);(s.ScoreCycleVersion??0)<n&&(s.ScoreEarnedThisCycle=0,s.ClaimedMilestoneIDs=[],s.BracketID=null),s.CurrentScore=t,s.ScoreEarnedThisCycle=(s.ScoreEarnedThisCycle??0)+i,s.ScoreCycleVersion=n,s.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let n=false;for(let s of Object.values(i))for(let o of Object.values(s.Equipment??{}))o?.ItemInstanceID===e&&(o.Level=t,n=true);n&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,n=i[e];n||(n={CharacterID:e},i[e]=n),t(n),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let n=this.currentState?.Character?.Characters?.[e];n&&(n.Equipment??={},i===null?delete n.Equipment[t]:n.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[n,s]of Object.entries(e.ChangedInstances??{}))t[n]=s,i=true;for(let n of e.RemovedInstanceIDs??[])n in t&&(delete t[n],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let n=this.currentState.CoopEvent??={MyObjectIndex:-1};n.ActiveGroupID=e,n.ActiveCoopEventID=t,n.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let n of Object.keys(i)){let s=i[n];s&&s.BoostID===e.BoostID&&n!==e.InstanceID&&delete i[n];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,n,s){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let o=this.currentState.CustomData,c={Value:i,UpdatedAt:new Date().toISOString(),Version:n,LastWriter:"Client",ExpiresAt:s??null};if(e==="Private")o.Private??={},o.Private[t]=c;else if(e==="Public")o.Public??={},o.Public[t]=c;else return;o.Version=(o.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let n=i.BuildingStates.find(s=>s.SlotIndex===e);n||(n={SlotIndex:e},i.BuildingStates.push(n)),t(n),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let n=this.ensureBoard().Pending;n&&(e&&(n.RaidLayout=e),t>=0&&(n.OpenedIndices??=[],n.OpenedIndices.includes(t)||n.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let n of Object.values(e.CryptoBalances??{}))n?.CurrencyID&&this.patchCryptoCurrencyDelta(n.CurrencyID,n.AmountDelta,n.UpdatedAt,n.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let n=this.currentState.Blockchain??={},s=n.PendingWithdrawals??[];t.size>0&&(s=s.filter(o=>!o.TitleTransactionID||!t.has(o.TitleTransactionID))),i&&!s.some(o=>o.TitleTransactionID===i.TitleTransactionID)&&(s=[...s,i]),n.PendingWithdrawals=s;}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 en=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);}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 tn=class{user;config;constructor(e){this.user=new Xi(e),this.config=new en;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Ef(a){return a}var Bf=0,qf=1500,Lf=3,sn=class{constructor(e,t,i=null,n="",s="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=n;this.loginMode=s;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}async ensureState(e,t){if(!this.state)return G(void 0);let i=Date.now(),n=[],s=[];for(let d of new Set(e)){let R=this.rules.get(d);if(R&&(t?.force||R.needsServer(i))){n.push(this.runRule(d,R));continue}(t?.force||!this.state.isStateFresh(d,t?.maxAgeMs))&&s.push(d);}let c=(await Promise.all([...n,s.length>0?this.queueSlice(s):Promise.resolve(G(void 0))])).find(d=>!d.ok);return c&&!c.ok?c:G(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let n=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,n),n}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},Bf),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(n=>i=n);try{let n=this.state?await this.state.readStateSlice(e):G(void 0),s=n.ok?G(void 0):n;for(let o of t)o(s);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let n=nn(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let R=this.fresh(n,i?.maxAgeMs);if(R)return G(R.data);let V=this.loginFailures.get(n);if(V)return this.loginFailures.delete(n),V;let se=this.inflight.get(n);if(se)return se}let s=this.generation.get(n)??0,o=Date.now(),d=t().then(R=>{if(!R.ok)return R;let V=Date.now();if((this.generation.get(n)??0)===s)return this.entries.set(n,{data:R.data,storedAt:V,expiresAt:no(e,R.data,V)}),R;let se=this.entries.get(n);if(se&&se.storedAt>=o)return R;let me=no(e,R.data,V);return this.entries.set(n,{data:R.data,storedAt:V,expiresAt:Math.min(me??1/0,V+qf)}),R}).finally(()=>{this.inflight.get(n)===d&&this.inflight.delete(n);});return this.inflight.set(n,d),d}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let n=t.Key?t.Key:void 0,s=nn(i.view,n);if(!t.Success){this.loginFailures.set(s,r("server",t.Error??"View failed."));continue}let o=i.schema.safeParse(t.Data);o.success&&(this.loginFailures.delete(s),i.apply(o.data,n),this.put(i.view,o.data,n));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let n=e.login;this.loadUsed().then(()=>{let s=kl({Name:n,Key:t});this.used.get(s)?.n!==this.session&&(this.used.set(s,{Name:n,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>Lf||this.used.set(kl(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(n=>n&&typeof n.Name=="string"&&typeof n.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(nn(e,t))?.data}put(e,t,i){this.register(e);let n=nn(e,i);this.bump(n);let s=Date.now();this.entries.set(n,{data:t,storedAt:s,expiresAt:no(e,t,s)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let n of [...this.entries.keys(),...this.inflight.keys()])(n===i||n.startsWith(`${i}|`))&&this.drop(n);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let n=Date.now();if(!(i.expiresAt!==null&&n>=i.expiresAt)&&!(t!==void 0&&n-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(n=>t.has(n))&&this.invalidate(i);}};function nn(a,e){return e===void 0?a.key:`${a.key}|${e}`}function kl(a){return a.Key?`${a.Name}|${a.Key}`:a.Name}function no(a,e,t){let i=a.expiresAt?.(e)??null,n=a.ttlMs!==void 0?t+a.ttlMs:null;return i!==null&&n!==null?Math.min(i,n):i??n}var rn=class{constructor(e,t){this.storage=e;this.authTypeKey=`Saved_AuthType_${t}`,this.emailKey=`Saved_Auth_Email_${t}`,this.passwordKey=`Saved_Auth_Password_${t}`,this.refreshTokenKey=`Saved_Auth_RefreshToken_${t}`;}storage;authTypeKey;emailKey;passwordKey;refreshTokenKey;get lastAuthType(){let e=this.storage.getString(this.authTypeKey);return Gf(e)?e:Te.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 Gf(a){return a!==null&&Object.values(Te).includes(a)}var Nf=8,Vf=100,Ff=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,Al=["GameLoop"];function jf(a){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(a)}var on=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=Te.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let n=this.authContext;if(!n)return r("unauthorized","Not logged in.");let s=this.baseRequest();s.UserID=n.userID,s.ClientSessionTicket=n.clientSessionTicket,s.WalletAddress=e,s.NetworkID=t,i&&(s.WalletSignature=i);let o=await this.ctx.api.authentication.linkWallet(s);return o.ok&&o.data.PlayAccess&&this.setPlayAccess(o.data.PlayAccess),o}async unlinkWallet(e){let t=this.authContext;if(!t)return r("unauthorized","Not logged in.");let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let n=await this.ctx.api.authentication.unlinkWallet(i);return n.ok&&n.data.PlayAccess&&this.setPlayAccess(n.data.PlayAccess),n}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.platform.getDeviceID(),e.Device=this.ctx.platform.getDeviceModel(),e.Platform=this.ctx.platform.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(Te.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return r("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(Te.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let n=await this.ctx.api.authentication.loginWithEmail(i);if(!n.ok)return n;this.applyAuthContext(n.data);let s=await this.fetchAndApplyClientState(Te.Email);return s.ok&&this.keepEmailCredentials(e,t),s}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.platform.getDeviceID(),i.Device=this.ctx.platform.getDeviceModel(),i.Platform=this.ctx.platform.getPlatform();let n=await this.ctx.api.authentication.registerWithEmail(i);return n.ok?(this.pendingRegistration={email:e,password:t},G({codeTtlMinutes:n.data.CodeTtlMinutes??0,resendCooldownSeconds:n.data.ResendCooldownSeconds??0})):n}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let n=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!n.ok)return n;this.applyAuthContext(n.data);let s=await this.fetchAndApplyClientState(Te.Email);return s.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,s}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?G(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(Te.Google)):i}async loginWithApple(e,t){if(!e?.trim())return r("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let n=await this.ctx.api.authentication.loginWithApple(i);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Te.Apple)):n}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();n.WalletAddress=e,n.NetworkID=t,n.WalletSignature=i,n.Platform=this.ctx.platform.getPlatform(),n.Device=this.ctx.platform.getDeviceModel(),n.DeviceID=this.ctx.platform.getDeviceID();let s=await this.ctx.api.authentication.loginWithWallet(n);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(Te.Wallet)):s}async loginWithSsoCode(e){if(!e)return r("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(Te.iDosGames)):i}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let n=this.baseRequest();return n.Email=e,n.ResetToken=t,n.Password=i,this.ctx.api.authentication.resetPassword(n)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==Te.None?e:Te.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let n=await this.ctx.api.authentication.refreshSession(i);return n.ok?(this.applyRefresh(n.data),"ok"):(jf(n.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case Te.Email:return this.loginWithEmail(t,i);case Te.Device:case Te.None:return this.loginWithDeviceID();case Te.Telegram:return this.loginWithTelegram();default:return Promise.resolve(r("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==Te.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===Te.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&&Ff.test(e)}static isValidPasswordLength(e){return e.length>=Nf&&e.length<=Vf}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.sessionAuthType=Te.None,this.sessionEmail="",this.sessionPassword="",this.sessionRefreshToken="";}applyAuthContext(e){this.authContext={userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration,platformUserID:e.PlatformUserID??void 0,platformAuthToken:e.PlatformAuthToken??void 0,platformAuthTokenExpiration:e.PlatformAuthTokenExpiration??void 0},this.sessionRefreshToken=e.RefreshToken??"",this.setPlayAccess(e.PlayAccess??null);}async fetchAndApplyClientState(e){let t=await this.ctx.userService.getClientStateExcept(Al,Al);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 Wf="idos:cfg",ci=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${wl(t)}`:e&&e.length>0?`f:${wl(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${Wf}:${this.titleId}:${e}`}};function wl(a){return [...a].map(e=>e.toLowerCase()).sort().join(",")}var Ml="idos:loc",pi=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let n={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(n)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[n,s]of Object.entries(t))typeof s=="number"&&s>0&&(i[n]=s);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 `${Ml}:${this.titleId}:${e}`}versionsKey(){return `${Ml}:${this.titleId}:versions`}};var _f="idos:sec",an=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 `${_f}:${this.titleId}`}};var Kf="idos:state",ln=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,n){if(!(!e||!t))try{let s={e:t,v:i,s:n};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}keyOf(e){return `${Kf}:${this.titleId}:${e}`}};function Qf(a,e){if(!a)return;let t=new Set((e??[]).map(n=>n.trim().toLowerCase()));if(t.size===0)return a;let i={};for(let[n,s]of Object.entries(a))t.has(n.toLowerCase())||(i[n]=s);return i}function so(a,e,t,i){let n={...a??{}};if(!e||!t||!i)return n;for(let[s,o]of Object.entries(t))i[s]===o&&s in e&&(n[s]=e[s]);return n}function Hf(a){return {...a??{}}}function ro(a){return typeof a.StateEpoch=="string"&&a.StateEpoch.length>0?a.StateEpoch:null}var un=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let n=this.confirmedAt[e];return n===void 0?false:t===void 0||i-n<=t}versionsFor(e){if(!this.epoch)return;let t=Qf(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 s=Object.keys(this.versions);this.reset(e),this.notify(s);}return}let i=Date.now(),n=[];for(let[s,o]of Object.entries(t)){let c=this.versions[s];c!==o&&(c!==void 0&&o===c+1?(this.versions[s]=o,this.confirmedAt[s]=i):(delete this.versions[s],delete this.confirmedAt[s]),n.push(s),this.dirty=true);}this.notify(n);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=Hf(t);let n=Date.now();this.confirmedAt={};for(let o of Object.keys(this.versions))this.confirmedAt[o]=n;this.dirty=true;let s=new Set;for(let o of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[o]!==this.versions[o]&&s.add(o);this.notify([...s]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),n=[];for(let[s,o]of Object.entries(t??{}))this.versions[s]!==o&&n.push(s),this.versions[s]=o,this.confirmedAt[s]=i;this.dirty=true,this.notify(n);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Ol=r("server","Title configuration is unavailable (CDN and API both failed)."),cn=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:q()}:null}get configCache(){return this.cache??=new ci(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new pi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new an(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;get stateStore(){return this.versionStore??=new un(new ln(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)}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=ci.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let n=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let s=await this.ctx.api.user.getClientState(e);if(!s.ok)return s;let o=await this.resolveTitleConfig(s.data,t,i,{Fields:e.TitleFields});return o==null?Ol:(this.finishStateHandshake(s.data,n),await this.restoreSections(s.data.TitleConfigVersion,o),await this.applyClientState(s.data,o,void 0,void 0),this.ctx.cache.acceptLoginViews(s.data.Views),await this.applyLocalization(s.data.Localization),await this.flushState(n),s)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let n=this.stateStore.versionsFor(t);if(n){e.KnownStateVersions=n;let s=this.stateStore.currentEpoch;s&&(e.KnownStateEpoch=s);}return {userId:i,cached:this.stateStore.cachedState,sent:n}}finishStateHandshake(e,t){let i=so(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let n=ro(e);!n||!t.userId||this.stateStore.afterFullRead(n,e.StateVersions);}async resolveTitleConfig(e,t,i,n){let s=e.TitleConfigVersion;if(i&&s&&i.v===s)return i.c;if(e.TitleConfigUrl){let c=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(c!=null)return s&&await this.configCache.write(t,s,c),c}let o=await this.fetchConfigFromApi(n);return o!=null?(s&&await this.configCache.write(t,s,o),o):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},n=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return n.ok?n.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.ExcludeFields=e,i.ExcludeTitleFields=t;let n=ci.scopeOf(null,t??[]),s=await this.configCache.read(n);s&&(i.KnownTitleConfigVersion=s.v),await this.prepareLocalization(i);let o=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let c=await this.ctx.api.user.getClientStateExcept(i);if(!c.ok)return c;let d=await this.resolveTitleConfig(c.data,n,s,{ExcludeFields:t??[]});return d==null?Ol:(this.finishStateHandshake(c.data,o),await this.restoreSections(c.data.TitleConfigVersion,d),await this.applyClientState(c.data,d,e,t),this.ctx.cache.acceptLoginViews(c.data.Views),await this.applyLocalization(c.data.Localization),await this.flushState(o),c)}async restoreSections(e,t){if(!e){this.ctx.data.config.setSectionSink(null);return}let i=t,n={};for(let[s,o]of Object.entries(await this.sectionCache.read(e)))i[s]==null&&(n[s]=o);this.ctx.data.config.restoreSections(n),this.ctx.data.config.setSectionSink((s,o)=>{i[s]!=null||o==null||(n[s]=o,this.sectionCache.write(e,n));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let n=await this.localizationCache.read(t);if(i<=0)return n?.t??null;if(n&&n.v===i)return n.t;if(e.Url){let o=await this.fetchLocalizationFromCdn(e.Url);if(o!=null)return await this.localizationCache.write(t,i,o),o}let s=await this.fetchLocalizationFromApi(t,n?.v??0);return s??n?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let n=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!n.ok)return null;let s=n.data;if(s.NotModified)return null;let o=s.Entries??{},c=s.Version??0,d=s.Locale??e;return c>0&&await this.localizationCache.write(d,c,o),o}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):r("unauthorized","Not logged in.")}async getUserState(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),n=await this.ctx.api.user.getUserState(t);if(!n.ok)return n;let s=so(n.data.User,i.cached,i.sent,n.data.StateVersions);n.data.User=s;let o=i.sent??{},c=Object.entries(n.data.StateVersions??{}).filter(([R,V])=>o[R]!==V||this.ctx.data.user.state?.[R]===void 0).map(([R])=>R);this.ctx.data.user.applyUserStateContainers(s,c);let d=ro(n.data);return d&&(this.stateStore.afterSliceRead(d,n.data.StateVersions),await this.flushState(i)),n}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.UsageTime=e,n.IsNewSession=t,n.SessionDurationSeconds=i;let s=await this.ctx.api.user.addUsageTime(n);return s.ok&&this.ctx.emitter.emit("user:usageTimeAdded",s.data),s}async deleteUserAccount(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,n){let s=i?.includes("GameLoop")===true,o=n?.includes("GameLoop")===true,c=s?this.ctx.data.user.state?.GameLoop:void 0,d=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;s&&R&&R.GameLoop==null&&(R.GameLoop=c);let V=this.ctx.data.config.titlePublicConfiguration;o&&V&&V.GameLoop==null&&(V.GameLoop=d),this.ctx.emitter.emit("user:clientStateReceived",e);}};var dn=class{constructor(e){this.ctx=e;}ctx;async convert(e,t,i,n,s,o){if(!t)return r("client","SourceID is required.");if(!n)return r("client","TargetID is required.");if(s<=0)return r("client","Amount must be positive.");if(e===i&&t===n)return r("client","Source and target must differ.");if(e===lt.Crypto||i===lt.Crypto)return r("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let c={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:String(Math.trunc(s)),TransactionID:o&&o.length>0?o:`convert_${e}_${t}_to_${i}_${n}_${q()}`},d=await this.ctx.api.currency.convert(c);if(d.ok){let R=d.data,V={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.SourceID,Amount:R.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:R.TargetID,Amount:R.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(V,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",R);}return d}async cryptoConvert(e,t,i,n,s,o){let c=s instanceof Nt__default.default?s:new Nt__default.default(s);if(!t)return r("client","SourceID is required.");if(!n)return r("client","TargetID is required.");if(c.lte(0))return r("client","SourceAmount must be a positive decimal.");if(e===i&&t===n)return r("client","Source and target must differ.");if(e===lt.Virtual&&i===lt.Virtual)return r("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===lt.Virtual&&!c.isInteger())return r("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let d={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:n,SourceAmount:c.toString(),TransactionID:o&&o.length>0?o:`crypto_convert_${e}_${t}_to_${i}_${n}_${q()}`},R=await this.ctx.api.currency.cryptoConvert(d);if(R.ok){let V=R.data,se=[],me=[];if(V.SourceType===lt.Virtual&&se.push({Type:"VirtualCurrency",CurrencyID:V.SourceID,Amount:Math.trunc(Number(V.SourceSpent))}),V.TargetType===lt.Virtual&&me.push({Type:"VirtualCurrency",CurrencyID:V.TargetID,Amount:Math.trunc(Number(V.TargetCredited))}),se.length>0||me.length>0){let xe={Consume:se.length>0?{Standard:{Entries:se}}:null,Grant:me.length>0?{Standard:{Entries:me}}:null};this.ctx.data.user.applyResourceOperation(xe,this.ctx.data.config.itemDefinitions);}V.SourceType===lt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.SourceID,new Nt__default.default(V.SourceSpent).negated(),V.ServerTimeUtc),V.TargetType===lt.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(V.TargetID,new Nt__default.default(V.TargetCredited),V.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",V);}return R}};var hn=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let n=e.trim();if(!n)return r("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:n,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${n}_${q()}`};t&&t.length>0&&(s.FodderInstanceIDs=[...t]);let o=await this.ctx.api.item.upgradeLevel(s);return o.ok&&(this.ctx.data.user.patchEquippedItemLevel(o.data.ItemInstanceID??n,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 r("client","upgrades is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let n of i.data)n.Success&&n.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(n.Data.ItemInstanceID,n.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var Ul=zod.z.object({OptionID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Cost:Ct.nullish(),AllowedPlatforms:zod.z.array(Gi).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),oe=zod.z.record(zod.z.string(),Ul),$f=zod.z.object({Store:Ni,Receipt:zod.z.string(),Signature:zod.z.string().nullish()}).passthrough();var oo=zod.z.object({ServerTimeUtc:u,OfferID:zod.z.string(),Count:zod.z.number(),Resources:w.nullish(),Inventory:K.nullish()}),El=zod.z.array(be(oo)),Jf=zod.z.object({OfferID:zod.z.string(),TotalPurchases:zod.z.number(),DailyPurchases:zod.z.number(),DailyResetUtc:u,LastPurchasedAt:u}),Zf=zod.z.object({SlotKey:zod.z.string(),InstanceKey:zod.z.string(),OfferID:zod.z.string().nullish(),Purchases:zod.z.number(),LastPurchasedAt:u}),Bl=zod.z.object({Purchases:zod.z.record(zod.z.string(),Jf).nullish(),Rotations:zod.z.record(zod.z.string(),Zf).nullish()}).passthrough().transform(a=>a),xt=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(),mn=zod.z.object({Schedule:de.nullish(),Gate:$.nullish()}).passthrough(),Yf={Fixed:"Fixed",Title:"Title",Player:"Player"},Xf=zod.z.object({OfferID:zod.z.string().nullish(),Weight:zod.z.number().nullish(),Gate:$.nullish()}).passthrough(),ql=zod.z.object({Mode:zod.z.string().nullish(),OfferID:zod.z.string().nullish(),Pool:zod.z.array(Xf).nullish(),Salt:zod.z.string().nullish(),PerInstanceCap:zod.z.number().nullish()}).passthrough(),eg=zod.z.object({Identity:_.nullish(),Availability:_.nullish(),Rotation:_.nullish()}).passthrough(),tg=zod.z.object({SlotID:zod.z.string().nullish(),Identity:xt.nullish(),Availability:mn.nullish(),Rotation:ql.nullish(),Presets:eg.nullish()}).passthrough(),ig=zod.z.object({Identity:_.nullish(),Availability:_.nullish()}).passthrough(),ng=zod.z.object({SectionID:zod.z.string().nullish(),Identity:xt.nullish(),Availability:mn.nullish(),Slots:zod.z.record(zod.z.string(),tg).nullish(),UniqueOffersInSection:zod.z.boolean().nullish(),Presets:ig.nullish()}).passthrough(),Ll=zod.z.object({Sections:zod.z.record(zod.z.string(),ng).nullish()}).passthrough(),sg=zod.z.object({Identity:_.nullish(),Availability:_.nullish(),Layout:_.nullish()}).passthrough(),rg=zod.z.object({StoreID:zod.z.string().nullish(),Identity:xt.nullish(),Availability:mn.nullish(),Layout:Ll.nullish(),Presets:sg.nullish()}).passthrough(),Gl=zod.z.object({Options:oe.nullish(),CompareAt:zod.z.record(zod.z.string(),Ct).nullish()}).passthrough(),Nl=zod.z.object({Grant:Q.nullish()}).passthrough(),Vl=zod.z.object({Schedule:de.nullish(),Gate:$.nullish(),Limits:fe.nullish()}).passthrough(),og=zod.z.object({Identity:_.nullish(),Pricing:_.nullish(),Reward:_.nullish(),Availability:_.nullish()}).passthrough(),ag=zod.z.object({OfferID:zod.z.string().nullish(),Identity:xt.nullish(),Pricing:Gl.nullish(),Reward:Nl.nullish(),Availability:Vl.nullish(),Presets:og.nullish()}).passthrough(),lg=zod.z.object({Identity:zod.z.record(zod.z.string(),xt).nullish(),Availability:zod.z.record(zod.z.string(),mn).nullish(),Layout:zod.z.record(zod.z.string(),Ll).nullish(),Rotation:zod.z.record(zod.z.string(),ql).nullish(),Pricing:zod.z.record(zod.z.string(),Gl).nullish(),Reward:zod.z.record(zod.z.string(),Nl).nullish(),OfferAvailability:zod.z.record(zod.z.string(),Vl).nullish()}).passthrough(),fn=zod.z.object({Stores:zod.z.record(zod.z.string(),rg).nullish(),StoreOffers:zod.z.record(zod.z.string(),ag).nullish(),Presets:lg.nullish()}).passthrough(),ug=zod.z.object({PurchasedTotal:zod.z.number(),PurchasedToday:zod.z.number(),PurchasedThisRotation:zod.z.number(),RemainingTotal:zod.z.number().nullish(),RemainingToday:zod.z.number().nullish(),IsFirstPurchaseAvailable:zod.z.boolean(),SoldOut:zod.z.boolean(),AvailableAtUtc:u.nullish()}).passthrough(),cg=zod.z.object({OptionID:zod.z.string(),Name:zod.z.string().nullish(),Cost:Ct.nullish(),CompareAtCost:Ct.nullish(),DiscountPercent:zod.z.number().nullish(),IsFree:zod.z.boolean(),IsAdPaid:zod.z.boolean(),IsStorePaid:zod.z.boolean(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),pg=zod.z.object({OfferID:zod.z.string(),Identity:xt.nullish(),PriceOptions:zod.z.array(cg).nullish(),Rewards:Q.nullish(),State:ug.nullish()}).passthrough(),dg=zod.z.object({SlotID:zod.z.string(),Identity:xt.nullish(),SortOrder:zod.z.number(),RotationMode:zod.z.string().nullish(),RotationInstanceKey:zod.z.string().nullish(),RefreshesAtUtc:u.nullish(),RemainingThisRotation:zod.z.number().nullish(),Offer:pg.nullish()}).passthrough(),hg=zod.z.object({SectionID:zod.z.string(),Identity:xt.nullish(),SortOrder:zod.z.number(),Slots:zod.z.array(dg).nullish()}).passthrough(),mg=zod.z.object({StoreID:zod.z.string(),Identity:xt.nullish(),SortOrder:zod.z.number(),ScheduleInstanceKey:zod.z.string().nullish(),ExpiresAtUtc:u.nullish(),Sections:zod.z.array(hg).nullish()}).passthrough(),gn=zod.z.object({ServerTimeUtc:u,Stores:zod.z.array(mg).nullish(),AdCreditBalance:zod.z.number()}).passthrough(),Vt={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront"},fg="OFFER_NOT_IN_ROTATION";var Fl="Store",jl={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:a=>{let e=null;for(let t of a.Stores??[])for(let i of t.Sections??[])for(let n of i.Slots??[]){let s=Date.parse(n.RefreshesAtUtc??"");!Number.isNaN(s)&&(e===null||s<e)&&(e=s);}return e}},yn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(jl,{schema:gn,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return r("client","OfferID is required.");if(t<1)return r("client","Count must be at least 1.");let n=this.ctx.auth.context;if(!n)return r("unauthorized","Not logged in.");let s={...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,RelatedEntityID:`store_buy_${e}_${n.userID}_${q()}`},o=await this.ctx.api.store.purchase(s);if(o.ok){let c=o.data;this.ctx.data.user.patchStorePurchase(e,t,c.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",c);}return o}async purchaseBatch(e){if(!e||e.length===0)return r("client","purchases is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let n=false;for(let s of i.data)!s.Success||!s.Data||!s.Data.OfferID||(this.ctx.data.user.patchStorePurchase(s.Data.OfferID,s.Data.Count,s.Data.ServerTimeUtc),!n&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(Fl,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.store.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Fl,n.data),this.ctx.emitter.emit("store:definitionsLoaded",n.data)),n}getStorefront(e){return this.ctx.cache.read(jl,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let n of i.Slots??[]){let s=n.RefreshesAtUtc;s&&(e===null||Date.parse(s)<Date.parse(e))&&(e=s);}return e}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Rn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?G(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return r("client","Receipt is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},s=await this.ctx.api.purchase.validatePurchase(n);return s.ok&&this.applyValidation(s.data),s}async buyWithTelegramStars(e,t){if(!e)return r("client","productID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},n=await this.ctx.api.purchase.createTelegramInvoice(i);return n.ok&&t?.open!==false&&this.ctx.platform.openInvoice(n.data.InvoiceLink),n}async validatePurchasesBatch(e){if(!e||e.length===0)return r("client","receipts is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let n of i.data.Items)n.Success&&n.Data&&this.applyValidation(n.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Cn=class{constructor(e){this.ctx=e;}ctx;get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t)if(i?.Type===Li.Purchase&&i.ProductID)return i.ProductID;return null}cryptoShortfallOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t){if(i?.Type!==Li.CryptoCurrency||!i.CurrencyID)continue;let n=Number(i.Amount??0);if(!(n>0))continue;let s=this.cryptoBalance(i.CurrencyID);return s>=n?null:{currencyID:i.CurrencyID,required:n,available:s,missing:n-s}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var Wl="Lootbox",Sn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Wl,e);if(t){let s={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),G(s)}let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.lootbox.getDefinitions(i);if(n.ok){let s=n.data.LootboxDefinitions;s&&(this.ctx.data.config.patchSection(Wl,s),this.ctx.emitter.emit("lootbox:definitionsLoaded",s));}return n}async open(e,t,i,n){if(!e)return r("client","LootboxID is required.");if(t<1)return r("client","Count must be at least 1.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:n,RelatedEntityID:`lootbox_${e}_${i??"default"}_${q()}`},o=await this.ctx.api.lootbox.open(s);if(o.ok){let c=o.data;c.TriggeredPity&&c.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,c.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",c);}return o}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var ao="Reward";function lo(a){return a.length>0&&!a.includes(".")&&!a.includes("$")}var xn=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(ao)?.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(ao,e);if(t){let s={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),G(s)}let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.reward.getRewardDefinitions(i);if(n.ok){let s=n.data.RewardDefinitions;s&&(this.ctx.data.config.patchSection(ao,s),this.ctx.emitter.emit("reward:definitionsLoaded",s));}return n}async getUserRewardsState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${q()}`},n=await this.ctx.api.reward.claimDailyReward(i);if(n.ok){let s=n.data;this.ctx.data.user.patchDailyCalendarState(s.CalendarID,s.DailyState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",s);}return n}async collectIdleAccrual(e){if(!lo(e))return r("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${q()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let n=i.data;this.ctx.data.user.patchIdleAccrualState(n.AccrualID,n.IdleState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",n);}return i}async claimComebackReward(e){if(!lo(e))return r("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${q()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchComebackState(n.ComebackID,n.ComebackState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",n);}return i}async claimReward(e){if(!lo(e))return r("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${q()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchClaimRewardState(n.ClaimID,n.ClaimState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",n);}return i}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var bn="Tutorial",_l={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"]},Dn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(_l,{schema:_i,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(bn)?.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(bn,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.tutorial.getTutorialDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(bn,n.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",n.data)),n}getUserTutorialState(e=true,t){return this.ctx.cache.read(_l,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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}_${q()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return r("client","FlowID is required.");if(!t||t.length===0)return r("client","stepIDs is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${q()}`},s=await this.ctx.api.tutorial.completeStepsBatch(n);return s.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",s.data)),s}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 r("client","FlowID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${q()}`},n=await this.ctx.api.tutorial.claimFlowReward(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",n.data)),n}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let n=e?.trim();if(!n)return r("client","FlowID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),FlowID:n},o=await t(s);return o.ok&&(this.applyFlowView(o.data),this.ctx.emitter.emit(i.event,o.data)),o}async stepCall(e,t,i,n){let s=e?.trim(),o=t?.trim();if(!s)return r("client","FlowID is required.");if(!o)return r("client","StepID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let c={...this.ctx.buildAuthedBaseRequest(),FlowID:s,StepID:o};n?.relatedEntityID&&(c.RelatedEntityID=n.relatedEntityID);let d=this.ctx.data.user.state?.Tutorial?.Flows?.[s]?.RewardClaimed===true,R=await i(c);return R.ok&&(this.applyFlowView(R.data),this.mayHavePaid(s,o,d,R.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",R.data)),R}mayHavePaid(e,t,i,n){return !i&&n.Flow?.RewardClaimed===true?true:n.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(bn)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Pn=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","campaignID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","campaignID is required.");if(!t)return r("client","walletAddress is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.CampaignID=e,n.WalletAddress=t,i&&(n.Amount=i);let s=await this.ctx.api.communityMarketing.withdrawCryptoReward(n);return s.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",s.data),s}async checkJoinEligibility(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Ae=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 gg={Global:"Global",Announcement:"Announcement",Group:"Group"},Ql=zod.z.enum(["Global","Announcement","Group"]).catch("Global"),yg={None:"None",Language:"Language",Region:"Region"},Rg=zod.z.enum(["None","Language","Region"]).catch("None"),Cg={Anyone:"Anyone",Friends:"Friends"},Sg=zod.z.enum(["Anyone","Friends"]).catch("Anyone"),xg={Reject:"Reject",Mask:"Mask"},bg=zod.z.enum(["Reject","Mask"]).catch("Reject"),Dg={Player:"Player",Publisher:"Publisher",System:"System"},Pg=zod.z.enum(["Player","Publisher","System"]).catch("Player"),vg={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};zod.z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Ig=zod.z.object({DisplayNameKey:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),IconPath:zod.z.string().nullish(),JoinedByDefault:zod.z.boolean().nullish()}).passthrough(),Hl=zod.z.object({Gate:$.nullish(),Schedule:de.nullish()}).passthrough(),$l=zod.z.object({Gate:$.nullish(),Limits:fe.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Jl=zod.z.object({HotTailSize:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish()}).passthrough(),zg=zod.z.object({Availability:_.nullish(),Write:_.nullish(),Retention:_.nullish()}).passthrough(),Tg=zod.z.object({ChannelID:zod.z.string().nullish(),Identity:Ig.nullish(),Type:Ql.nullish(),GroupSource:zod.z.string().nullish(),Partitioning:Rg.nullish(),Capacity:zod.z.number().nullish(),Availability:Hl.nullish(),Write:$l.nullish(),Retention:Jl.nullish(),Presets:zg.nullish()}).passthrough(),kg=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Gate:$.nullish(),WhoCanMessage:Sg.nullish(),Limits:fe.nullish(),MaxLength:zod.z.number().nullish(),HistoryHours:zod.z.number().nullish(),MaxConversations:zod.z.number().nullish()}).passthrough(),Ag=zod.z.object({BlockedTerms:zod.z.array(zod.z.string()).nullish(),BlockedTermAction:bg.nullish(),MaxIgnoreListSize:zod.z.number().nullish(),ReportsEnabled:zod.z.boolean().nullish(),ReportLimits:fe.nullish()}).passthrough(),wg=zod.z.object({MinIntervalSeconds:zod.z.number().nullish(),MaxMessagesPerPoll:zod.z.number().nullish(),MaxHistoryPageSize:zod.z.number().nullish()}).passthrough(),Mg=zod.z.object({Availability:zod.z.record(zod.z.string(),Hl).nullish(),Write:zod.z.record(zod.z.string(),$l).nullish(),Retention:zod.z.record(zod.z.string(),Jl).nullish()}).passthrough(),Zl=zod.z.object({IsEnabled:zod.z.boolean().nullish(),Channels:zod.z.record(zod.z.string(),Tg).nullish(),Direct:kg.nullish(),Moderation:Ag.nullish(),Polling:wg.nullish(),Presets:Mg.nullish()}).passthrough(),Og=zod.z.object({LastReadAt:zod.z.string().nullish(),LastReadMessageID:zod.z.string().nullish(),Left:zod.z.boolean().nullish()}).passthrough(),Kl=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(),Og).nullish(),Limits:zod.z.record(zod.z.string(),Kl).nullish(),ReportLimits:Kl.nullish()}).passthrough();var uo=zod.z.object({RoomID:zod.z.string().nullish(),SentAt:zod.z.string().nullish(),MessageID:zod.z.string().nullish()}).passthrough(),vn=zod.z.object({RoomID:zod.z.string().nullish(),ChannelID:zod.z.string().nullish(),MessageID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderProfile:Ae.nullish(),AuthorType:Pg.nullish(),Text:zod.z.string().nullish(),SentAt:zod.z.string().nullish()}).passthrough(),Ug=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:Ql.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(),In=zod.z.object({Channels:zod.z.array(Ug).nullish(),PollIntervalSeconds:zod.z.number().nullish(),MutedUntil:zod.z.string().nullish(),MuteReason:zod.z.string().nullish()}).passthrough(),Eg=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(vn).nullish(),NextCursor:uo.nullish(),UnreadCount:zod.z.number().nullish(),ServedFromDatabase:zod.z.boolean().nullish()}).passthrough(),Yl=zod.z.object({Rooms:zod.z.array(Eg).nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),Xl=zod.z.object({RoomID:zod.z.string().nullish(),Messages:zod.z.array(vn).nullish(),NextBefore:uo.nullish()}).passthrough(),eu=zod.z.object({Message:vn.nullish(),Moderated:zod.z.boolean().nullish()}).passthrough(),tu=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ae.nullish(),MaxLength:zod.z.number().nullish()}).passthrough(),Bg=zod.z.object({RoomID:zod.z.string().nullish(),PeerUserID:zod.z.string().nullish(),PeerProfile:Ae.nullish(),LastMessage:vn.nullish(),UnreadCount:zod.z.number().nullish(),LastReadAt:zod.z.string().nullish()}).passthrough(),iu=zod.z.object({Conversations:zod.z.array(Bg).nullish()}).passthrough(),di=zod.z.object({Ignored:zod.z.array(zod.z.string()).nullish(),Cursor:uo.nullish(),Joined:zod.z.boolean().nullish()}).passthrough(),nu=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish()}).passthrough(),We={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 su="Chat",ru={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},zn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ru,{schema:In,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(su,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.chat.getChatDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(su,n.data),this.ctx.emitter.emit("chat:definitionsLoaded",n.data)),n}getChannels(e,t){return this.ctx.cache.read(ru,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let n of i.data.Rooms??[])n.NextCursor&&n.RoomID&&this.cursors.set(n.RoomID,n.NextCursor),n.Messages&&n.Messages.length>0&&this.ctx.emitter.emit("chat:messages",n);return i}async getHistory(e,t,i){let n=this.baseRequest();return n?(n.RoomID=e,t&&(n.Before=t),i&&(n.Limit=i),this.ctx.api.chat.getHistory(n)):r("unauthorized","Not logged in.")}async sendMessage(e,t,i){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.ChannelID=e,n.Text=t,i&&(n.Locale=i);let s=await this.ctx.api.chat.sendMessage(n);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async sendDirect(e,t){let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.Text=t;let n=await this.ctx.api.chat.sendMessage(i);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async openDirectChannel(e){let t=this.baseRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):r("unauthorized","Not logged in.")}async getConversations(){let e=this.baseRequest();return e?this.ctx.api.chat.getConversations(e):r("unauthorized","Not logged in.")}async markRead(e,t){let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let n=await this.ctx.api.chat.markRead(i);return n.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),n}async joinChannel(e){let t=this.baseRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):r("unauthorized","Not logged in.")}async leaveChannel(e){let t=this.baseRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):r("unauthorized","Not logged in.")}async reportMessage(e,t,i,n){let s=this.baseRequest();return s?(s.RoomID=e,s.MessageID=t,s.Reason=i,n&&(s.Comment=n),this.ctx.api.chat.reportMessage(s)):r("unauthorized","Not logged in.")}async ignoreUser(e){let t=this.baseRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):r("unauthorized","Not logged in.")}async unignoreUser(e){let t=this.baseRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):r("unauthorized","Not logged in.")}resetCursors(){this.cursors.clear();}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var qg={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},Lg=zod.z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),Gg={Player:"player",Title:"title",Creator:"creator"},hi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},ou=zod.z.object({Configured:zod.z.boolean().nullish(),PublicKey:zod.z.string().nullish()}).passthrough(),Ng=zod.z.object({TitleID:zod.z.string().nullish(),Topic:zod.z.string().nullish()}).passthrough(),co=zod.z.object({EndpointHash:zod.z.string().nullish(),Transport:Lg.nullish(),Locale:zod.z.string().nullish(),Topics:zod.z.array(Ng).nullish()}).passthrough(),au=zod.z.object({Configured:zod.z.boolean().nullish(),Subscriptions:zod.z.array(co).nullish()}).passthrough(),bt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var Pi=["https://idosgames.com","https://www.idosgames.com"];function lu(a){return a==="localhost"||a==="127.0.0.1"||a==="[::1]"||a.endsWith(".localhost")}function Vg(a){if(Pi.includes(a))return true;if(typeof window>"u"||!lu(window.location.hostname))return false;try{return lu(new URL(a).hostname)}catch{return false}}var Fg="IDOS_PLATFORM_PUSH_REQUEST",jg="IDOS_PLATFORM_PUSH_RESPONSE",Wg=12e4;function uu(a){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let n=false,s=d=>{n||(n=true,window.removeEventListener("message",o),clearTimeout(c),i(d));},o=d=>{let R=d?.data;!R||R.type!==jg||R.requestId!==t||Pi.includes(d.origin)&&s(R.ok===true);},c=setTimeout(()=>s(false),Wg);window.addEventListener("message",o);for(let d of Pi)try{e.postMessage({type:Fg,requestId:t,titleID:a},d);}catch{}})}var Tn=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.baseRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),n=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=n,i.ok&&this.ctx.emitter.emit("push:configLoaded",n),n}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return bt.Unsupported;if(this.isEmbedded())return bt.Embedded;if(!this.isSupported())return bt.Unsupported;let t=Notification.permission;return t==="denied"?bt.Blocked:t!=="granted"?bt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?bt.Subscribed:bt.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return r("client","Push notifications are not available for this title.");if(this.isEmbedded())return await uu(this.ctx.settings.titleID)?G({Where:"portal",Subscription:null}):r("client","The portal did not complete the subscription.");if(!this.isSupported())return r("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return r("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let n=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let o=await n.pushManager.getSubscription()??await n.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:_g(t.PublicKey)}),c=this.baseRequest();if(!c)return r("unauthorized","Not logged in.");let d=o.toJSON();c.PushEndpoint=d.endpoint,c.PushP256dh=d.keys?.p256dh,c.PushAuth=d.keys?.auth,c.PushTransport="WebPush",c.PushLocale=e.locale??navigator.language,c.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let R=await this.ctx.api.push.subscribePush(c);return R.ok?(this.ctx.emitter.emit("push:subscribed",R.data),G({Where:"game",Subscription:R.data})):R}async unsubscribe(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");if(this.isSupported()){let n=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();n&&(e.PushEndpoint=n.endpoint,await n.unsubscribe());}if(!e.PushEndpoint)return r("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.baseRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):r("unauthorized","Not logged in.")}async unsubscribeByHash(e){if(!e)return r("client","endpointHash is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};function _g(a){let e=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(a.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),n=new Uint8Array(i);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return i}var kn=Object.freeze({}),An=class{constructor(e){this.ctx=e;}ctx;table={...kn};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new pi(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),n=this.lookup(i)??this.lookup(e);return n===void 0?this.onMissing(e):t?Kg(n,t):n}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...kn},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return r("unauthorized","Not logged in.");let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:n,table:s,fallbackLocale:o}=i.data,c=null;if(o){let d=await this.loadTableFromApi(o);d.ok&&(c=d.data.table);}return this.table=s,this.fallbackTable=c,this.currentFallbackLocale=o,this.setLocaleInternal(n),this.ctx.emitter.emit("localization:changed",{locale:n,fallbackLocale:o,entryCount:Object.keys(s).length}),{ok:true,data:n}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):r("unauthorized","Not logged in.")}reset(){this.table={...kn},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:q()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.Locale=e;let i=await this.cache.read(cu(e));i&&(t.KnownVersion=i.v);let n=await this.ctx.api.localization.getLocalizationTable(t);if(!n.ok)return n;let s=n.data,o=s.Locale??cu(e),c=s.Version??0;if(s.NotModified){let R=i??await this.cache.read(o);return {ok:true,data:{locale:o,table:R?.t??{...kn},fallbackLocale:s.FallbackLocale??null}}}let d=s.Entries??{};return c>0&&await this.cache.write(o,c,d),{ok:true,data:{locale:o,table:d,fallbackLocale:s.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let n=this.pluralCategory(i),s=`${e}.${n}`;if(this.lookup(s)!==void 0)return s;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 Kg(a,e){return a.replace(/\{(\w+)\}/g,(t,i)=>{let n=e[i];return n===void 0?t:String(n)})}function cu(a){return a.trim().replace(/_/g,"-").toLowerCase()}var po="Quest",wn=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let n=e.cache.configSection(po)?.Cycles;if(!n)return false;let s=e.data.user.state?.Quest?.Cycles??{};for(let o of Object.keys(n)){let c=Date.parse(s[o]?.CycleEndUtc??"");if(Number.isNaN(c)){if(t===0)return true}else if(c<=i&&t<c)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true);return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(po,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.quest.getQuestDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(po,n.data),this.ctx.emitter.emit("quest:definitionsLoaded",n.data)),n}async getUserQuestState(e=true){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let n=i.data.State??{};this.ctx.data.user.applyQuest(n),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",n);}return i}async refreshQuestCycles(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","QuestID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n=t&&t.trim().length>0?t.trim():void 0,s={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:n,RelatedEntityID:`quest_claim_${n??""}_${i}_${q()}`},o=await this.ctx.api.quest.claimQuestReward(s);if(o.ok){let c=o.data;this.ctx.data.user.patchQuestStatus(c.QuestID,c.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",c);}return o}async claimQuestRewardsBatch(e){if(!e||e.length===0)return r("client","quests is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let n=false;for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchQuestStatus(s.Data.QuestID,s.Data.CycleID,"Claimed"),!n&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return r("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:n,RelatedEntityID:`milestone_claim_${i}_${n}_${q()}`},o=await this.ctx.api.quest.claimMilestoneReward(s);if(o.ok){let c=o.data;this.ctx.data.user.patchMilestoneClaimed(c.CycleID,c.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",c);}return o}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return r("client","milestones is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let n=false;for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchMilestoneClaimed(s.Data.CycleID,s.Data.MilestoneID),!n&&s.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),n=t.trim();if(!i||!n)return r("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:n,RelatedEntityID:`group_completion_${i}_${n}_${q()}`},o=await this.ctx.api.quest.claimGroupCompletionReward(s);if(o.ok){let c=o.data;this.ctx.data.user.patchGroupCompletionClaimed(c.CycleID,c.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(c.Resources,c.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",c);}return o}async addQuestProgress(e,t){let i=e.trim();if(!i)return r("client","MetricID is required.");if(t<0)return r("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},s=await this.ctx.api.quest.addQuestProgress(n);return s.ok&&(this.ctx.data.user.patchQuestProgressUpdates(s.data.Updates),this.ctx.emitter.emit("quest:progressAdded",s.data)),s}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var pu=zod.z.object({}).passthrough().transform(a=>a);var Qg=zod.z.object({Order:zod.z.number().nullish(),Type:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),BonusMultiplier:zod.z.number().nullish()}).passthrough(),Hg=zod.z.object({Schedule:zod.z.array(Qg).nullish(),RepeatCycle:zod.z.boolean().nullish(),MaxCycles:zod.z.number().nullish()}).passthrough(),$g=zod.z.object({IsActive:zod.z.boolean().nullish(),CurrentPhaseEndUtc:u.nullish(),NextBonusStartUtc:u.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentPhaseIndex:zod.z.number().nullish(),ActiveBonusMultiplier:zod.z.number().nullish()}).passthrough(),Jg=zod.z.object({Milestones:_.nullish()}).passthrough(),ho=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:Gt.nullish(),TokenSources:zod.z.array(it).nullish(),ClaimMode:zod.z.string().nullish(),Milestones:zod.z.record(zod.z.string(),Ee).nullish(),Presets:Jg.nullish(),BonusWindow:Hg.nullish()}).passthrough(),Zg=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Content:ho.nullish(),ClaimGraceHours:zod.z.number().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Yg=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:de.nullish(),Content:ho.nullish(),Events:zod.z.array(Zg).nullish(),Gate:$.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Xg=zod.z.object({MaxConcurrentEvents:zod.z.number().nullish()}).passthrough(),ey=zod.z.object({Milestones:zod.z.record(zod.z.string(),oi).nullish()}).passthrough(),Mn=zod.z.object({Definitions:zod.z.record(zod.z.string(),Yg).nullish(),Settings:Xg.nullish(),Presets:ey.nullish()}).passthrough(),ty=zod.z.object({Type:bi,TimedEventID:zod.z.string(),CurrentChainedEventID:zod.z.string().nullish(),Content:ho.nullish(),Progress:pu.nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),CanEarn:zod.z.boolean().nullish(),CanClaim:zod.z.boolean().nullish(),NextMilestone:Ee.nullish(),BonusWindow:$g.nullish(),CurrentCycleIndex:zod.z.number().nullish(),CurrentEventOrder:zod.z.number().nullish(),TotalEventsInChain:zod.z.number().nullish(),TokenEntityID:zod.z.string().nullish()}).passthrough(),On=zod.z.object({ActiveEvents:zod.z.array(ty).nullish()}).passthrough(),du=zod.z.object({Tokens:zod.z.record(zod.z.string(),pu).nullish()}),mo=zod.z.object({Type:bi.nullish(),LteID:zod.z.string().nullish(),Resources:w.nullish()}),fo=zod.z.object({Type:bi.nullish(),LteID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),TokenEntityID:zod.z.string().nullish(),Rewards:w.nullish(),Inventory:K.nullish()}),iy=zod.z.object({Type:bi.nullish(),LteID:zod.z.string().nullish(),Resources:w.nullish()}),go=zod.z.array(be(fo)),hu=zod.z.array(be(mo)),mu=zod.z.array(be(iy)),rt={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var fu="TimedEvent",gu={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:a=>{let e=null;for(let t of a.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Un=class{constructor(e){this.ctx=e;e.cache.bindLoginView(gu,{schema:On,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(gu,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(fu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.timedEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(fu,n.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",n.data)),n}async getUserLteState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,n,s,o,c=1){if(!t)return r("client","LteID is required.");if(!i)return r("client","SourceType is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let d={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:n,AmountOverride:s,SourceParams:o,RollMultiplier:c},R=await this.ctx.api.timedEvent.grantTokens(d);return R.ok&&(this.ctx.data.user.applyResourceOperation(R.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",R.data)),R}async spendTokens(e,t,i){if(!t)return r("client","LteID is required.");if(i<=0)return r("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},s=await this.ctx.api.timedEvent.spendTokens(n);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",s.data)),s}async claimMilestone(e,t,i){if(!t||!i)return r("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},s=await this.ctx.api.timedEvent.claimMilestone(n);if(s.ok){let o=s.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 s}async claimMilestonesBatch(e){if(!e||e.length===0)return r("client","milestones is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","spends is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let n=false;for(let s of i.data)!n&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(s.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return r("client","grants is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let n=false;for(let s of i.data)!n&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(s.Data.Resources,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let n=i.Data;n.Type&&n.LteID&&n.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(n.Type,n.LteID,n.MilestoneID,n.TokenEntityID),!t&&n.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(n.Rewards,n.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var ny=zod.z.object({UserID:zod.z.string(),Score:j.nullish(),Rank:zod.z.number().nullish(),LastScoreUpdateUtc:u.nullish(),IpHash:zod.z.string().nullish(),PublicProfile:Ae.nullish(),SeasonTierAtCycleEnd:zod.z.number().nullish()}).passthrough(),vi=zod.z.object({LeaderboardID:zod.z.string(),CycleVersion:zod.z.number().nullish(),TotalParticipants:j.nullish(),CycleEndUtc:u.nullish(),TopUsers:zod.z.array(ny).nullish(),BracketID:zod.z.string().nullish()}),sy=zod.z.object({CycleKey:zod.z.string().nullish(),CycleEndUtc:u.nullish(),ClaimDeadlineUtc:u.nullish(),MilestoneTokensEarned:j.nullish(),ClaimableMilestoneIDs:zod.z.array(zod.z.string()).nullish(),CycleIndex:zod.z.number().nullish(),ChainedEventID:zod.z.string().nullish()}).passthrough(),En=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:Ee.nullish(),HasUnclaimedMilestone:zod.z.boolean().nullish(),GrantedPremiumTiers:zod.z.record(zod.z.string(),zod.z.array(zod.z.string())).nullish(),ClaimableGraceCycles:zod.z.array(sy).nullish()}),Bn=zod.z.object({LeaderboardID:zod.z.string(),NewScore:j,CycleVersion:zod.z.number()}),qn=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),Rank:zod.z.number().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),Ln=zod.z.object({ServerTimeUtc:u,LeaderboardID:zod.z.string(),MilestoneID:zod.z.string(),Resources:w.nullish(),Inventory:K.nullish()}),yu=zod.z.array(be(vi)),Gn=zod.z.array(be(En)),Ru=zod.z.array(be(qn)),Cu=zod.z.array(be(Ln)),Su=zod.z.array(be(Bn)),ry=zod.z.object({LeaderboardID:zod.z.string(),CycleReward:be(qn).nullish(),Milestones:zod.z.array(be(Ln)).nullish()}),xu=zod.z.array(ry),oy=zod.z.object({LeaderboardID:zod.z.string(),Leaderboard:be(vi).nullish(),Progress:be(En).nullish()}),bu=zod.z.array(oy),ay=zod.z.string(),Du=zod.z.object({Rank:zod.z.string().nullish(),Rewards:Q.nullish(),SeasonTierRewards:Qr.nullish()}).passthrough(),ly=zod.z.object({RankRewards:zod.z.array(Du).nullish()}).passthrough(),uy=zod.z.object({ChainedEventID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),ClaimGraceHours:zod.z.number().nullish()}).passthrough(),cy=zod.z.object({Milestones:_.nullish(),RankRewards:_.nullish()}).passthrough(),py=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:ay.nullish(),Schedule:de.nullish(),ChainEvents:zod.z.array(uy).nullish(),Gate:$.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(Du).nullish(),Milestones:zod.z.record(zod.z.string(),Ee).nullish(),Presets:cy.nullish(),MilestoneClaimMode:zod.z.string().nullish(),MilestoneClaimGraceHours:zod.z.number().nullish(),ScoreSources:zod.z.array(it).nullish()}).passthrough(),dy=zod.z.object({Milestones:zod.z.record(zod.z.string(),oi).nullish(),RankRewards:zod.z.record(zod.z.string(),ly).nullish()}).passthrough(),Nn=zod.z.object({Definitions:zod.z.record(zod.z.string(),py).nullish(),Presets:dy.nullish()}).passthrough(),Ge={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 Pu="Leaderboard",vu={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"]},Vn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(vu,{schema:Gn,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Pu,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.leaderboard.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Pu,n.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",n.data)),n}async getLeaderboard(e){if(!e)return r("client","LeaderboardID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","LeaderboardID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","LeaderboardID is required.");if(t<=0)return r("client","Score must be positive.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},n=await this.ctx.api.leaderboard.submitScore(i);if(n.ok){let s=n.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),s.NewScore,t,s.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",s);}return n}async submitScoreFromSource(e,t,i,n,s=1){if(!e)return r("client","LeaderboardID is required.");if(!t)return r("client","SourceType is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let o={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:n,RollMultiplier:s},c=await this.ctx.api.leaderboard.submitScoreFromSource(o);if(c.ok){let d=c.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),d.NewScore,d.NewScore,d.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",d);}return c}async claimCycleReward(e){if(!e)return r("client","LeaderboardID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let n=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",n);}return i}async claimMilestone(e,t,i){if(!e||!t)return r("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},s=await this.ctx.api.leaderboard.claimMilestone(n);if(s.ok){let o=s.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 s}async getFriendsLeaderboard(e){if(!e)return r("client","LeaderboardID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","leaderboardIDs is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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(r("client","leaderboardIDs is required.")):this.ctx.cache.read(vu,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(n.Data.LeaderboardID)),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return r("client","milestones is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(n.Data.LeaderboardID),n.Data.MilestoneID),n.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return r("client","scores is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let n of i.data)!n.Success||!n.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(n.Data.LeaderboardID),n.Data.NewScore,n.Data.NewScore,n.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return r("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let n of i.data){let s=this.cycleDocID(n.LeaderboardID);n.CycleReward?.Success&&n.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(s),n.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.CycleReward.Data.Resources,n.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let o of n.Milestones??[])!o.Success||!o.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(s,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 r("client","leaderboardIDs is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let n of i.data)n.Progress?.Success&&n.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(n.LeaderboardID),n.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var yo=zod.z.object({}).passthrough().transform(a=>a),Fn=zod.z.object({SeasonChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),Season:zod.z.lazy(()=>ku).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:j.nullish(),UserState:yo.nullish(),NextTier:zod.z.lazy(()=>Tu).nullish()}).passthrough(),Iu=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()}),Ro=zod.z.object({SeasonChainID:zod.z.string(),CurrentSeasonID:zod.z.string().nullish(),TierNumber:zod.z.number(),Resources:w.nullish(),Inventory:K.nullish()}),zu=mt(Ro);var Tu=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:Q.nullish()}).passthrough(),ku=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(Tu).nullish(),LinkedCollectionID:zod.z.string().nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough();var hy=zod.z.object({SeasonChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:de.nullish(),Seasons:zod.z.array(ku).nullish(),GrantTokensAccessMode:zod.z.string().nullish(),Gate:$.nullish()}).passthrough(),jn=zod.z.object({Chains:zod.z.record(zod.z.string(),hy).nullish()}).passthrough(),wt={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Au="Season",wu={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:a=>{let e=Date.parse(a.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},Wn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(wu,{schema:Fn,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Au,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.season.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Au,n.data),this.ctx.emitter.emit("season:definitionsLoaded",n.data)),n}getActiveSeason(e,t){return e?this.ctx.cache.read(wu,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(r("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","SeasonChainID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","SeasonChainID is required.");if(t<=0)return r("client","Amount must be positive.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${q()}`},n=await this.ctx.api.season.grantStatusTokens(i);return n.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,n.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",n.data)),n}async claimTierReward(e,t){if(!e)return r("client","SeasonChainID is required.");if(t<=0)return r("client","TierNumber must be positive.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${q()}`},n=await this.ctx.api.season.claimTierReward(i);if(n.ok){let s=n.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",s);}return n}async claimTierRewardsBatch(e,t){if(!e)return r("client","SeasonChainID is required.");let i=(t??[]).filter(o=>o>0);if(i.length===0)return r("client","TierNumbers is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${q()}`},s=await this.ctx.api.season.claimTierRewardsBatch(n);if(s.ok){let o=s.data;for(let c of o.Items??[]){let d=c.Data?.TierNumber;c.Success&&typeof d=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,d);}this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",o);}return s}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Mu="Premium",_n=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Mu,e);if(t){let s={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",s),G(s)}let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.premium.getDefinitions(i);return n.ok&&n.data.Premium&&(this.ctx.data.config.patchSection(Mu,n.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",n.data)),n}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},n=await this.ctx.api.premium.activateTrial(i);return n.ok&&(n.data.Premium&&this.ctx.data.user.applyPremium(n.data.Premium),this.ctx.emitter.emit("premium:trialActivated",n.data)),n}async purchaseItemOrCurrency(e,t,i="Default",n=1){if(!e||!t)return r("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:n,RelatedEntityID:`premium_purchase_${e}_${t}`},o=await this.ctx.api.premium.purchaseItemOrCurrency(s);if(o.ok){let c=o.data;c.Premium&&this.ctx.data.user.applyPremium(c.Premium),this.ctx.data.user.applyResourceOperation(c.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",c);}return o}async purchaseRealMoney(e,t,i,n,s,o,c,d){if(!e||!t)return r("client","PremiumID and TransactionID are required.");if(!n||!s)return r("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let R={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:n,ReceiptData:s,PurchaseToken:o,PackageName:c,AppStoreEnvironment:d,RelatedEntityID:`premium_iap_${e}_${t}`},V=await this.ctx.api.premium.purchaseRealMoney(R);if(V.ok){let se=V.data;se.Premium&&this.ctx.data.user.applyPremium(se.Premium),this.ctx.data.user.applyResourceOperation(se.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",se);}return V}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Kn=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),ItemInstanceID:zod.z.string().nullish(),Level:zod.z.number().nullish(),EquippedAt:u.nullish()}),Co=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(),Kn).nullish(),UpdatedAt:u.nullish()}).passthrough(),Ou=zod.z.object({Characters:zod.z.record(zod.z.string(),Co).nullish()}),So=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),StatID:zod.z.string(),StatLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:w.nullish()}),xo=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),NewLevel:zod.z.number(),Power:zod.z.number().nullish(),Resources:w.nullish()}),Uu=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Equipment:zod.z.record(zod.z.string(),Kn).nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Eu=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),my=zod.z.object({ClearedSlotIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish()}),Bu=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),my).nullish(),Inventory:K.nullish()}),bo=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Power:zod.z.number().nullish(),Resources:w.nullish()}),qu=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Resources:w.nullish(),Inventory:K.nullish(),Equipped:zod.z.boolean().nullish(),EquipError:zod.z.string().nullish(),Equipment:Kn.nullish(),Power:zod.z.number().nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish()}),Lu=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),SkinID:zod.z.string(),Equipped:Kn.nullish(),ReplacedInstanceIDs:zod.z.array(zod.z.string()).nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),Gu=zod.z.object({ServerTimeUtc:u,CharacterID:zod.z.string(),Cleared:zod.z.boolean().nullish(),Power:zod.z.number().nullish(),Inventory:K.nullish()}),fy=zod.z.object({SkinID:zod.z.string(),IsDefault:zod.z.boolean().nullish(),Misconfigured:zod.z.string().nullish(),Owned:zod.z.boolean().nullish(),OwnedCopies:zod.z.number().nullish(),IsWorn:zod.z.boolean().nullish(),MeetsRequirements:zod.z.boolean().nullish(),SoldDirectly:zod.z.boolean().nullish(),OnSale:zod.z.boolean().nullish(),SaleEndsAtUtc:u.nullish(),GateOpen:zod.z.boolean().nullish(),Purchasable:zod.z.boolean().nullish(),PriceOptions:oe.nullish()}),gy=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(fy).nullish()}),Nu=zod.z.object({ServerTimeUtc:u,Characters:zod.z.record(zod.z.string(),gy).nullish()}),Vu=mt(bo),Fu=mt(xo),ju=mt(So),Do=zod.z.object({RequiredStatID:zod.z.string(),RequiredLevel:zod.z.number()}).passthrough(),Wu=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:oe.nullish(),CostCurve:Le.nullish(),BaseStatValue:zod.z.number().nullish(),ValueCurve:Le.nullish(),RankCurve:Le.nullish(),Requirements:zod.z.array(Do).nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),yy=zod.z.object({SlotID:zod.z.string(),MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Do).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(),_u=zod.z.object({Slots:zod.z.record(zod.z.string(),yy).nullish()}).passthrough(),Ku=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(),Ry=zod.z.object({ClassID:zod.z.string().nullish(),RarityID:zod.z.string().nullish(),Tags:zod.z.array(zod.z.string()).nullish()}).passthrough(),Cy=zod.z.object({UnlockedByDefault:zod.z.boolean().nullish(),PriceOptions:oe.nullish()}).passthrough(),Sy=zod.z.object({Stats:_.nullish(),Levels:_.nullish(),Equipment:_.nullish()}).passthrough(),Qu=zod.z.object({MaxRank:zod.z.number().nullish(),FirstPaidRank:zod.z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:Le.nullish()}).passthrough(),Po="@skin";function xy(a){return !!a&&a.startsWith("@")}var by=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string()}).passthrough(),Dy=zod.z.object({PriceOptions:oe.nullish(),Schedule:de.nullish(),Gate:$.nullish()}).passthrough(),Py=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),StatRequirements:zod.z.array(Do).nullish()}).passthrough(),vy=zod.z.object({SkinID:zod.z.string().nullish(),Identity:Ku.nullish(),Item:by.nullish(),Sale:Dy.nullish(),Requirements:Py.nullish()}).passthrough(),Iy=zod.z.object({DefaultSkinID:zod.z.string().nullish(),Definitions:zod.z.record(zod.z.string(),vy).nullish()}).passthrough(),zy=zod.z.object({CharacterID:zod.z.string(),Identity:Ku.nullish(),Classification:Ry.nullish(),Unlock:Cy.nullish(),Presets:Sy.nullish(),Equipment:_u.nullish(),Stats:zod.z.record(zod.z.string(),Wu).nullish(),RankLadder:Qu.nullish(),RankStatCurve:Le.nullish(),StatMaxLevelCurve:Le.nullish(),Skins:Iy.nullish()}).passthrough(),Ty=zod.z.object({Stats:zod.z.record(zod.z.string(),Wu).nullish()}).passthrough(),ky=zod.z.object({RankLadder:Qu.nullish()}).passthrough(),Ay=zod.z.object({Equipment:_u.nullish()}).passthrough(),wy=zod.z.object({Stats:zod.z.record(zod.z.string(),Ty).nullish(),Levels:zod.z.record(zod.z.string(),ky).nullish(),Equipment:zod.z.record(zod.z.string(),Ay).nullish()}).passthrough(),Qn=zod.z.object({Definitions:zod.z.record(zod.z.string(),zy).nullish(),Presets:wy.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"},My="SKIN_ALREADY_OWNED";var vo="Character",Hn=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(vo)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([n,s])=>s?.Unlock?.UnlockedByDefault===true&&!i[s.CharacterID??n])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(vo,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.character.getCharacterDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(vo,n.data),this.ctx.emitter.emit("character:definitionsLoaded",n.data)),n}async getUserCharacters(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","CharacterID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${q()}`},n=await this.ctx.api.character.unlockCharacter(i);if(n.ok){let s=n.data;this.ctx.data.user.patchCharacter(s.CharacterID,o=>{o.Level??=1,o.StatLevels??={},o.Equipment??={},s.Power!=null&&(o.Power=s.Power),o.UpdatedAt=s.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(s.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",s);}return n}async upgradeStatLevel(e,t,i){if(!e||!t)return r("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${q()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},s=await this.ctx.api.character.upgradeStatLevel(n);if(s.ok){let o=s.data;this.ctx.data.user.patchCharacter(o.CharacterID,c=>{c.StatLevels??={},c.StatLevels[o.StatID]=o.StatLevel,o.Power!=null&&(c.Power=o.Power),c.UpdatedAt=o.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",o);}return s}async upgradeCharacterLevel(e,t){if(!e)return r("client","CharacterID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${q()}`,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},n=await this.ctx.api.character.upgradeCharacterLevel(i);if(n.ok){let s=n.data;this.ctx.data.user.patchCharacter(s.CharacterID,o=>{o.Level=s.NewLevel,s.Power!=null&&(o.Power=s.Power),o.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(o.StatLevels??={},o.Equipment??={});}),this.ctx.data.user.applyResourceOperation(s.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",s);}return n}async equipItems(e,t){if(!e)return r("client","CharacterID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},n=await this.ctx.api.character.equipItems(i);return n.ok&&(this.applyEquipChangesLocally(e,n.data),this.ctx.emitter.emit("character:itemsEquipped",n.data)),n}async unequipItems(e,t){if(!e)return r("client","CharacterID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},n=await this.ctx.api.character.unequipItems(i);if(n.ok){let s=n.data;this.applyUnequipChangesLocally(e,s),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:s.ClearedSlotIDs??[],power:s.Power??null});}return n}async unequipAllCharacters(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${q()}`},s=await this.ctx.api.character.unlockSkin(n);if(s.ok){let o=s.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 s}async equipSkin(e,t,i){if(!e||!t)return r("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},s=await this.ctx.api.character.equipSkin(n);if(s.ok){let o=s.data;this.applyInventoryDelta(o.Inventory),this.applySkinLocally(o.CharacterID,o.Equipped??null,o.Power,o.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",o);}return s}async unequipSkin(e){if(!e)return r("client","CharacterID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let n=i.data;n.Cleared&&(this.applyInventoryDelta(n.Inventory),this.applySkinLocally(n.CharacterID,null,n.Power,n.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",n);}return i}async getCharacterSkins(e){let t=this.baseRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):r("unauthorized","Not logged in.")}applySkinLocally(e,t,i,n){let s=this.ctx.data.user;s.patchCharacterEquipment(e,Po,t??null),s.patchCharacter(e,o=>{i!=null&&(o.Power=i),o.UpdatedAt=n;});}async unlockCharactersBatch(e){if(!e||e.length===0)return r("client","characterIDs is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,s=>{s.Level??=1,s.StatLevels??={},s.Equipment??={},n.Power!=null&&(s.Power=n.Power),s.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return r("client","upgrades is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,s=>{s.Level=n.NewLevel,n.Power!=null&&(s.Power=n.Power),s.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(s.StatLevels??={},s.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return r("client","upgrades is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,n=>{this.ctx.data.user.patchCharacter(n.CharacterID,s=>{s.StatLevels??={},s.StatLevels[n.StatID]=n.StatLevel,n.Power!=null&&(s.Power=n.Power),s.UpdatedAt=n.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[n,s]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,n,s);i.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let n=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let s of i)n.patchCharacterEquipment(e,s,null);n.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,n]of Object.entries(e.Characters??{})){for(let s of n.ClearedSlotIDs??[])t.patchCharacterEquipment(i,s,null);t.patchCharacter(i,s=>{n.Power!=null&&(s.Power=n.Power),s.UpdatedAt=e.ServerTimeUtc;});}}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Hu="Match",$n=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,n,s,o){let c=this.ctx.auth.context;if(!c)return r("unauthorized","Not logged in.");let d={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:n,TargetUserID:s,SelectedOptionID:o,RelatedEntityID:`pvp_create_${c.userID}_${q()}`},R=await this.ctx.api.match.createMatch(d);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 r("client","MatchID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},n=await this.ctx.api.match.updateMatch(i);return n.ok&&this.ctx.emitter.emit("match:updated",n.data),n}async cancelMatch(e){if(!e)return r("client","MatchID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,n){let s=this.ctx.auth.context;if(!s)return r("unauthorized","Not logged in.");let o={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:n,RelatedEntityID:`pvp_battle_${e}_${q()}`},c=await this.ctx.api.match.instantBattle(o);if(c.ok){let d=c.data,R=this.ctx.data.config.itemDefinitions;if(d.Resources)this.ctx.data.user.applyResourceOperation(d.Resources,R);else if(d.ResourcesDual){let V=d.ResourcesDual;V.FromUserID===s.userID&&V.FromResult?this.ctx.data.user.applyResourceOperation(V.FromResult,R):V.ToUserID===s.userID&&V.ToResult&&this.ctx.data.user.applyResourceOperation(V.ToResult,R);}this.ctx.emitter.emit("match:instantBattleCompleted",d);}return c}async saveStrategy(e){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.Page=e,n.PageSize=t,n.Statuses=i;let s=await this.ctx.api.match.getMyMatches(n);return s.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",s.data),s}async getAvailableMatches(e=0,t=20,i=false){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.Page=e,n.PageSize=t,n.OnlyPublic=i;let s=await this.ctx.api.match.getAvailableMatches(n);return s.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",s.data),s}async getDefinitions(e){let t=this.ctx.cache.configSection(Hu,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.match.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Hu,n.data),this.ctx.emitter.emit("match:definitionsLoaded",n.data)),n}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var $u="Craft",Jn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection($u,e);if(t){let s={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),G(s)}let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.craft.getDefinitions(i);return n.ok&&n.data.CraftDefinitions&&(this.ctx.data.config.patchSection($u,n.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",n.data.CraftDefinitions)),n}async craft(e,t,i=1,n,s){if(!e)return r("client","CraftID is required.");let o=this.ctx.auth.context;if(!o)return r("unauthorized","Not logged in.");let c={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:n,InputInstanceIDs:s,RelatedEntityID:`craft_${e}_${o.userID}_${q()}`},d=await this.ctx.api.craft.craft(c);return d.ok&&(this.ctx.data.user.applyResourcesWithDelta(d.data.Resources,d.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",d.data)),d}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Mt=zod.z.lazy(()=>zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null(),zod.z.array(Mt),zod.z.record(zod.z.string(),Mt)]));var Ot={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Ju=zod.z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Ft={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Ii(a){return a!==Ft.Pending&&a!==Ft.Running}var Oy={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 Uy(a){return a?/\b(AI_[A-Z_]+)\s*:/.exec(a)?.[1]??null:null}var Ey=zod.z.object({Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Variant:zod.z.string().nullish()}),By=zod.z.object({Code:zod.z.string().nullish(),Message:zod.z.string().nullish()}),Zn=zod.z.object({GenerationID:zod.z.string(),FeatureKey:zod.z.string().nullish(),Modality:Ju.nullish(),Status:zod.z.string(),Progress:zod.z.number().nullish(),OutputText:zod.z.string().nullish(),OutputJson:zod.z.record(zod.z.string(),Mt).nullish(),Assets:zod.z.array(Ey).nullish(),Error:By.nullish(),Charge:w.nullish(),PlayerRefunded:zod.z.boolean().nullish(),Reward:w.nullish(),Context:zod.z.record(zod.z.string(),Mt).nullish(),PaymentSettled:zod.z.boolean().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish()}),Zu=zod.z.object({Data:zod.z.array(Zn).nullish(),Skip:zod.z.number().nullish(),Limit:zod.z.number().nullish()}),qy=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(),Ly=zod.z.object({Modality:Ju.nullish(),Async:zod.z.boolean().nullish(),Limits:fe.nullish(),PriceOptions:oe.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:Q.nullish(),PromptVariables:zod.z.array(qy).nullish(),AllowFreePrompt:zod.z.boolean().nullish()}).passthrough(),Yu=zod.z.object({Enabled:zod.z.boolean().nullish(),Features:zod.z.record(zod.z.string(),Ly).nullish()}).passthrough(),qe={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 Xu="AI",Gy=/^[A-Za-z0-9_-]{1,128}$/,Ny=2e3,Vy=5e3,Fy=30*6e4;function jy(a,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(n),e?.removeEventListener("abort",i),t();},n=setTimeout(i,a);e?.addEventListener("abort",i,{once:true});})}var Yn=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(Xu,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.ai.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Xu,n.data),this.ctx.emitter.emit("ai:definitionsLoaded",n.data)),n}generateText(e,t,i){return this.generate(e,{Text:t},i,n=>this.ctx.api.ai.generateText(n))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,n=>this.ctx.api.ai.generateImage(n))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,n=>this.ctx.api.ai.editImage(n))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,n=>this.ctx.api.ai.generateVideo(n))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,n=>this.ctx.api.ai.generateAudio(n))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,n=>this.ctx.api.ai.generateMusic(n))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,n=>this.ctx.api.ai.generateThreeD(n))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.baseRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):r("unauthorized","Not logged in.")}async getGeneration(e){if(!e)return r("client","GenerationID is required.");let t=this.baseRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):r("unauthorized","Not logged in.")}isTerminal(e){return Ii(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let c=await this.getGeneration(e);if(!c.ok)return c;i=c.data;}else {if(!e?.GenerationID)return r("client","GenerationID is required.");i=e;}let n=Date.now()+(t.timeoutMs??Fy),s=Math.max(1,t.intervalMs??Ny),o=Math.max(s,t.maxIntervalMs??Vy);for(;!Ii(i.Status);){if(t.signal?.aborted)return r("client","Stopped waiting: the wait was aborted.");if(Date.now()+s>n)return r("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await jy(s,t.signal),t.signal?.aborted)return r("client","Stopped waiting: the wait was aborted.");let c=await this.pollFor(i);if(s=Math.min(o,Math.round(s*1.5)),!c.ok){if(c.reason==="connection")continue;return c}i=c.data,Ii(i.Status)||t.onUpdate?.(i);}return G(i)}pollFor(e){switch(e.Modality){case Ot.Text:return this.getText(e.GenerationID);case Ot.Image:return this.getImage(e.GenerationID);case Ot.Audio:return this.getAudio(e.GenerationID);case Ot.Music:return this.getMusic(e.GenerationID);case Ot.Video:return this.getVideo(e.GenerationID);case Ot.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,n){if(!e)return r("client","FeatureKey is required.");let s=i?.relatedEntityID;if(s!==void 0&&!Gy.test(s))return r("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let o={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:s??q()},c=await n(o);return c.ok&&(await this.reconcileCharge(c.data,true),this.emitView(c.data)),c}async poll(e,t){if(!e)return r("client","GenerationID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.GenerationID=e;let n=await t(i);return n.ok&&(await this.reconcileCharge(n.data,false),this.emitView(n.data)),n}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Ft.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===Ft.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Ft.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Io="Collection",Xn=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(Io),n=Object.keys(i?.Collections??{});if(n.length===0||t)return false;let s=e.cache.configSection("Season");return Object.values(s?.Chains??{}).some(c=>(c?.Seasons??[]).some(d=>!!d?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==n[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Io,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.collection.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Io,n.data),this.ctx.emitter.emit("collection:definitionsLoaded",n.data)),n}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,n){let s=this.ctx.auth.context;if(!s)return r("unauthorized","Not logged in.");let o={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,RelatedEntityID:`open_pack_${e}_${t}_${s.userID}_${q()}`},c=await this.ctx.api.collection.openPack(o);return c.ok&&(this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",c.data)),c}async openCollectionChest(e,t,i=1){let n=this.ctx.auth.context;if(!n)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${n.userID}_${q()}`},o=await this.ctx.api.collection.openCollectionChest(s);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 r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${q()}`},s=await this.ctx.api.collection.useCollectibleJoker(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",s.data)),s}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${q()}`},s=await this.ctx.api.collection.claimSetReward(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",s.data)),s}async claimSetRewardsBatch(e){if(!e||e.length===0)return r("client","sets is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let n=false;for(let s of i.data)!n&&s.Success&&s.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions),n=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${q()}`},n=await this.ctx.api.collection.claimGrandPrize(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",n.data)),n}async sendTradeOffer(e,t,i,n,s,o=false){let c=this.ctx.auth.context;if(!c)return r("unauthorized","Not logged in.");let d={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:n,RequestedCollectibleID:s,RequestedCollectibleIsSpecial:o,RelatedEntityID:`trade_send_${c.userID}_${n}_${q()}`},R=await this.ctx.api.collection.sendTradeOffer(d);return R.ok&&this.ctx.emitter.emit("collection:tradeOfferSent",R.data),R}async cancelTradeOffer(e){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${q()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${q()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${q()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data),i}async getMyTradeOffers(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Wy=zod.z.object({}).passthrough().transform(a=>a),_y={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Ky={Active:"Active",Left:"Left",Replaced:"Replaced"},Qy=zod.z.object({ObjectIndex:zod.z.number().nullish(),ObjectCompletionRewardClaimed:zod.z.boolean().nullish()}).passthrough(),Hy=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ae.nullish(),BuildObjectsProgress:Qy.nullish(),IsBot:zod.z.boolean().nullish(),SpinsCount:zod.z.number().nullish(),TokensSpent:zod.z.number().nullish(),MemberStatus:zod.z.string().nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),$y=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(),Jy=zod.z.object({Objects:zod.z.array($y).nullish()}).passthrough(),ec=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(Hy).nullish(),BuildObjectsState:Jy.nullish(),Status:zod.z.string().nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),tc=zod.z.object({CoopChainID:zod.z.string(),CycleIndex:zod.z.number().nullish(),EventOrder:zod.z.number().nullish(),EventDef:zod.z.lazy(()=>ic).nullish(),ComputedStartUtc:u.nullish(),ComputedEndUtc:u.nullish(),SecondsRemaining:zod.z.number().nullish()}).passthrough(),Zy=zod.z.string(),zo=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(),Yy=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:Q.nullish()}).passthrough(),Xy=zod.z.object({Objects:zod.z.array(Yy).nullish(),PriceOptions:oe.nullish(),SpinnerTable:zod.z.array(zo).nullish(),MaxSpinsPerCall:zod.z.number().nullish()}).passthrough(),ic=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:Zy.nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),BuildObjects:Xy.nullish(),GrandPrize:Q.nullish()}).passthrough(),eR=zod.z.object({CoopChainID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Schedule:de.nullish(),Events:zod.z.array(ic).nullish(),Gate:$.nullish()}).passthrough(),es=zod.z.object({ServerTimeUtc:u.nullish(),UserState:Wy.nullish(),ActiveGroup:ec.nullish()}),To=zod.z.object({ServerTimeUtc:u.nullish(),Group:ec.nullish(),SecondsRemaining:j.nullish()}),nc=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Resources:w.nullish(),ObjectIndex:zod.z.number().nullish(),Sector:zo.nullish(),RequestedSpins:zod.z.number().nullish(),SpinsUsed:zod.z.number().nullish(),Sectors:zod.z.array(zo).nullish(),ProgressDelta:zod.z.number().nullish(),NewProgress:j.nullish(),MaxProgress:j.nullish(),ObjectCompleted:zod.z.boolean().nullish(),AllObjectsCompleted:zod.z.boolean().nullish()}),ko=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),sc=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),ts=zod.z.object({Chains:zod.z.record(zod.z.string(),eR).nullish()}).passthrough(),pt={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var rc="CoopEvent",oc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},is=class{constructor(e){this.ctx=e;e.cache.bindLoginView(oc,{schema:es,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(rc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.coopEvent.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(rc,n.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",n.data)),n}async getActiveEvent(e){if(!e)return r("client","CoopChainID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(oc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","GroupID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","CoopChainID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let n=i.data.Group;n&&this.ctx.data.user.patchCoopEventActiveGroup(n.GroupID??null,n.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,n){if(!e||!t)return r("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:n,RelatedEntityID:q()},o=await this.ctx.api.coopEvent.spin(s);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 r("client","GroupID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("client","GroupID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");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}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var tR={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},iR={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},nR=zod.z.object({NodeID:zod.z.string().nullish(),Status:zod.z.string().nullish(),ExecutionCount:zod.z.number().nullish(),UnlockedAtUtc:u.nullish(),CompletedAtUtc:u.nullish(),LastExecutedAtUtc:u.nullish(),NextAvailableAtUtc:u.nullish(),LastExecutionRefID:zod.z.string().nullish()}).passthrough(),sR=zod.z.object({TrackID:zod.z.string().nullish(),CurrentValue:zod.z.number().nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),ac=zod.z.object({OfferID:zod.z.string().nullish(),InstanceKey:zod.z.string().nullish(),SourceOfferVersion:zod.z.number().nullish(),Status:zod.z.string().nullish(),ActivatedAtUtc:u.nullish(),ExhaustedAtUtc:u.nullish(),ExpiredAtUtc:u.nullish(),DismissedAtUtc:u.nullish(),ShowCount:zod.z.number().nullish(),LastShownAtUtc:u.nullish(),Nodes:zod.z.record(zod.z.string(),nR).nullish(),Tracks:zod.z.record(zod.z.string(),sR).nullish(),SelectedChoiceNodeID:zod.z.string().nullish()}).passthrough(),rR=zod.z.object({SlotID:zod.z.string().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),ActiveOfferID:zod.z.string().nullish(),ActiveOfferStartedAtUtc:u.nullish(),ActiveOfferExpiresAtUtc:u.nullish(),ActiveOffer:ac.nullish(),NextCycleStartsAtUtc:u.nullish(),LastUpdatedUtc:u.nullish(),DismissSkipAvailableAtUtc:u.nullish(),LastDismissedAtUtc:u.nullish(),ActiveScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),oR=zod.z.object({TotalExecutions:zod.z.number().nullish(),DailyExecutions:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),aR=zod.z.object({TotalActivations:zod.z.number().nullish(),TotalExhausted:zod.z.number().nullish(),TotalExpired:zod.z.number().nullish(),TotalDismissed:zod.z.number().nullish(),TotalShows:zod.z.number().nullish(),LastShownAtUtc:u.nullish(),LastActivatedAtUtc:u.nullish(),LastExhaustedAtUtc:u.nullish(),NodeCounts:zod.z.record(zod.z.string(),oR).nullish()}).passthrough(),lR=zod.z.object({Slots:zod.z.record(zod.z.string(),rR).nullish(),OfferHistory:zod.z.record(zod.z.string(),aR).nullish(),LastUpdatedUtc:u.nullish()}).passthrough(),uR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},cR={Eq:"Eq",Gte:"Gte",Lte:"Lte"},pR=zod.z.object({Order:zod.z.number().nullish(),OfferID:zod.z.string().nullish(),DurationSec:zod.z.number().nullish(),DelayBeforeActivationSec:zod.z.number().nullish()}).passthrough(),ns=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(),lc=zod.z.object({Schedule:de.nullish(),Gate:$.nullish()}).passthrough(),uc=zod.z.object({AllowDismissSkip:zod.z.boolean().nullish(),DismissSkipDelaySec:zod.z.number().nullish()}).passthrough(),dR=zod.z.object({Identity:_.nullish(),Availability:_.nullish(),Behaviour:_.nullish()}).passthrough(),hR=zod.z.object({SlotID:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Identity:ns.nullish(),Availability:lc.nullish(),Behaviour:uc.nullish(),Queue:zod.z.array(pR).nullish(),Presets:dR.nullish()}).passthrough(),mR=zod.z.object({ViewsRequiredToComplete:zod.z.number().nullish(),MaxViewsPerActivation:zod.z.number().nullish(),GrantRewardsPerView:zod.z.boolean().nullish()}).passthrough(),fR=zod.z.object({RewardedVideo:mR.nullish()}).passthrough(),gR=zod.z.object({TrackID:zod.z.string().nullish(),Operator:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),yR=zod.z.object({Identity:_.nullish(),Graph:_.nullish(),Milestones:_.nullish()}).passthrough(),RR=zod.z.object({Identity:_.nullish(),Pricing:_.nullish(),Reward:_.nullish()}).passthrough(),CR=zod.z.object({TrackID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),RespectBounds:zod.z.boolean().nullish()}).passthrough(),SR=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(),xR=zod.z.object({RequiredCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredAnyCompletedNodeIDs:zod.z.array(zod.z.string()).nullish(),RequiredTracks:zod.z.array(gR).nullish(),VisibleWhileLocked:zod.z.boolean().nullish()}).passthrough(),cc=zod.z.object({Options:oe.nullish()}).passthrough(),pc=zod.z.object({Grants:Q.nullish(),TrackChanges:zod.z.array(CR).nullish(),MilestonePoints:zod.z.number().nullish()}).passthrough(),bR=zod.z.object({NodeID:zod.z.string().nullish(),Type:zod.z.string().nullish(),Identity:ns.nullish(),Pricing:cc.nullish(),Reward:pc.nullish(),Action:fR.nullish(),UnlockRules:xR.nullish(),NextNodeIDs:zod.z.array(zod.z.string()).nullish(),ChoiceGroupID:zod.z.string().nullish(),Limits:fe.nullish(),HideWhenCompleted:zod.z.boolean().nullish(),ExhaustOfferOnComplete:zod.z.boolean().nullish(),Presets:RR.nullish()}).passthrough(),dc=zod.z.object({RootNodeIDs:zod.z.array(zod.z.string()).nullish(),Nodes:zod.z.array(bR).nullish(),Tracks:zod.z.array(SR).nullish(),ExhaustedWhenAllTerminalNodesCompleted:zod.z.boolean().nullish()}).passthrough(),hc=zod.z.object({Milestones:zod.z.record(zod.z.string(),Ee).nullish(),ClaimMode:zod.z.string().nullish(),Token:Gt.nullish()}).passthrough(),mc=zod.z.object({OfferID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Enabled:zod.z.boolean().nullish(),Identity:ns.nullish(),Graph:dc.nullish(),Milestones:hc.nullish(),Presets:yR.nullish()}).passthrough(),DR=zod.z.object({Identity:zod.z.record(zod.z.string(),ns).nullish(),Availability:zod.z.record(zod.z.string(),lc).nullish(),Behaviour:zod.z.record(zod.z.string(),uc).nullish(),Graph:zod.z.record(zod.z.string(),dc).nullish(),Milestones:zod.z.record(zod.z.string(),hc).nullish(),Pricing:zod.z.record(zod.z.string(),cc).nullish(),Reward:zod.z.record(zod.z.string(),pc).nullish()}).passthrough(),Ao=zod.z.object({Slots:zod.z.record(zod.z.string(),hR).nullish(),Offers:zod.z.record(zod.z.string(),mc).nullish(),Presets:DR.nullish()}).passthrough(),fc=zod.z.object({DealOfferDefinitions:Ao.nullish()}),gc=zod.z.object({DealOffers:lR.nullish()}),PR=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(),vR=zod.z.object({SlotID:zod.z.string().nullish(),SortOrder:zod.z.number().nullish(),QueueIndex:zod.z.number().nullish(),CycleIndex:zod.z.number().nullish(),OfferDef:mc.nullish(),ActivationState:ac.nullish(),IsNewActivation:zod.z.boolean().nullish(),ComputedExpiresAtUtc:u.nullish(),Cost:Ct.nullish(),Milestone:PR.nullish(),ScheduleInstanceKey:zod.z.string().nullish()}).passthrough(),ss=zod.z.object({Slots:zod.z.array(vR).nullish()}),yc=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),NodeID:zod.z.string().nullish(),NodeCompleted:zod.z.boolean().nullish(),OfferExhausted:zod.z.boolean().nullish(),Idempotent:zod.z.boolean().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),Rc=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:w.nullish()}),Cc=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),Resources:w.nullish()}),Sc=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),xc=zod.z.object({ServerTimeUtc:u.nullish(),SlotID:zod.z.string().nullish(),ClaimedIDs:zod.z.array(zod.z.string()).nullish(),Rejected:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Resources:w.nullish(),Inventory:K.nullish()}),gt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var IR="DealOffer",bc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},rs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(bc,{schema:ss,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(IR,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(bc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","SlotID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${q()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,n){if(!e||!t)return r("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s=i&&i.trim().length>0?i.trim():void 0,o={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:n?.selectedOptionID,Payment:n?.payment,RelatedEntityID:s??`deal_exec_${e}_${t}_${q()}`},c=await this.ctx.api.dealOffer.executeNode(o);return c.ok&&(c.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(c.data.Resources,c.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",c.data)),c}async recordShow(e){if(!e)return r("client","SlotID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${q()}`},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 r("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${q()}`},n=await this.ctx.api.dealOffer.claimMilestone(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",n.data)),n}async claimMilestonesBatch(e,t){if(!e)return r("client","SlotID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i=[...new Set(t.map(o=>o.trim()).filter(o=>o.length>0))],n={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${q()}`},s=await this.ctx.api.dealOffer.claimMilestonesBatch(n);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",s.data)),s}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Dc="Referral",os=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Dc,e);if(t){let s={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",s),G(s)}let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.referral.getDefinitions(i);return n.ok&&n.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Dc,n.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",n.data)),n}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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=Lt.parseReferralCode(e)?.toUpperCase();if(!t)return r("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},s=await this.ctx.api.referral.activateReferralCode(n);if(s.ok){let o=s.data;o.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(o.ReferrerUserID),this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",o);}return s}async claimInviteReward(e){let t=e.trim();if(!t)return r("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},s=await this.ctx.api.referral.claimInviteReward(n);if(s.ok){let o=s.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 s}async claimInviteRewardsBatch(e){let t=(e??[]).map(o=>o?.trim()).filter(Boolean);if(t.length===0)return r("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},s=await this.ctx.api.referral.claimInviteRewardsBatch(n);if(s.ok){let o=s.data;for(let c of o.Items??[])c.Success&&c.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(c.Id);this.ctx.data.user.applyResourcesWithDelta(o.Resources,o.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",o);}return s}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var zR={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Pc=zod.z.enum(["System","Reward","Gift","Social"]).catch("System"),TR={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},kR=zod.z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),AR={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},wR=zod.z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),Ye={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},MR={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"},OR=100,UR=zod.z.object({Subject:zod.z.string().nullish(),Body:zod.z.string().nullish()}).passthrough(),vc=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(),ER=zod.z.object({Texts:zod.z.record(zod.z.string(),UR).nullish(),Category:Pc.nullish(),Icon:zod.z.string().nullish(),Banner:zod.z.string().nullish(),Link:vc.nullish(),SenderName:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),BR=zod.z.object({Enabled:zod.z.boolean().nullish(),Grant:ae.nullish(),Cost:ae.nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),SenderGate:$.nullish(),TemplateID:zod.z.string().nullish(),ExpirationDays:zod.z.number().nullish()}).passthrough(),qR=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(),LR=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedResources:zod.z.array(qR).nullish(),MaxEntriesPerGift:zod.z.number().nullish(),IntervalSeconds:zod.z.number().nullish(),AnchorUtc:u.nullish(),FeePercent:zod.z.number().nullish(),FeeCost:ae.nullish(),SenderGate:$.nullish(),ExpirationDays:zod.z.number().nullish(),TemplateID:zod.z.string().nullish()}).passthrough(),Ic=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(),ER).nullish(),Gifts:zod.z.object({Social:zod.z.record(zod.z.string(),BR).nullish(),Transfer:LR.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(),GR=zod.z.object({MessageID:zod.z.string(),Source:kR,Category:Pc,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:vc.nullish(),SenderName:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderAvatarUrl:zod.z.string().nullish(),SenderNote:zod.z.string().nullish(),Rewards:Q.nullish(),HasRewards:zod.z.boolean().nullish(),IsTransfer:zod.z.boolean().nullish(),SentAt:u,ExpiresAt:u.nullish(),ReadAt:u.nullish(),ClaimedAt:u.nullish()}).passthrough(),NR=zod.z.object({MessageID:zod.z.string(),Module:wR,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:Q.nullish()}).passthrough(),wo=zod.z.object({ID:zod.z.string(),Error:zod.z.string().nullish()}).passthrough(),zc=zod.z.object({ServerTimeUtc:u.nullish(),Messages:zod.z.array(GR).default([]),NextCursor:zod.z.string().nullish(),PendingRewards:zod.z.array(NR).nullish(),UnreadCount:zod.z.number().nullish(),UnclaimedCount:zod.z.number().nullish(),DeliveredNow:zod.z.number().nullish()}).passthrough(),as=zod.z.object({ServerTimeUtc:u.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Mo=zod.z.object({ServerTimeUtc:u.nullish(),AffectedCount:zod.z.number().default(0),Failed:zod.z.array(wo).default([]),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),VR=zod.z.object({MessageID:zod.z.string(),Rewards:ae.nullish()}).passthrough(),ls=zod.z.object({ServerTimeUtc:u.nullish(),Claimed:zod.z.array(VR).default([]),Failed:zod.z.array(wo).default([]),Resources:w.nullish(),Inventory:K.nullish(),UnreadCount:zod.z.number().default(0),UnclaimedCount:zod.z.number().default(0)}).passthrough(),Tc=zod.z.object({ServerTimeUtc:u.nullish(),GiftID:zod.z.string().nullish(),Sent:zod.z.array(zod.z.string()).default([]),Failed:zod.z.array(wo).default([]),Resources:w.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough(),kc=zod.z.object({ServerTimeUtc:u.nullish(),MessageID:zod.z.string().nullish(),ExpiresAt:u.nullish(),Resources:w.nullish(),RecipientReceives:ae.nullish(),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish(),IdempotentReplay:zod.z.boolean().nullish()}).passthrough(),Ac=zod.z.object({ServerTimeUtc:u.nullish(),ResetsAt:u.nullish(),Social:zod.z.record(zod.z.string(),zod.z.object({IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ReceivedInPeriod:zod.z.number().default(0),SentTo:zod.z.array(zod.z.string()).default([]),ResetsAt:u.nullish()}).passthrough()).default({}),Transfer:zod.z.object({Enabled:zod.z.boolean().default(false),IntervalSeconds:zod.z.number().default(86400),SentInPeriod:zod.z.number().default(0),RemainingInPeriod:zod.z.number().default(0),ResetsAt:u.nullish()}).passthrough().nullish()}).passthrough();var Oo="Mailbox",Uo={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},us=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Uo,{schema:as,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(Uo,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Oo)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Oo,e);if(t)return G(t);let i=this.request();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.mailbox.getDefinitions(i);return n.ok&&this.ctx.data.config.patchSection(Oo,n.data),n}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return r("unauthorized","Not logged in.");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(Uo,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");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 r("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):r("unauthorized","Not logged in.")}async claimRewards(e){let t=(e??[]).map(n=>n?.trim()).filter(Boolean);if(t.length===0)return r("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):r("unauthorized","Not logged in.")}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):r("unauthorized","Not logged in.")}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 r("unauthorized","Not logged in.");let n=await this.ctx.api.mailbox.deleteMessages(i);return n.ok&&this.emitCounters(n.data),n}async sendGift(e,t){if(!e?.trim())return r("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return r("client","Recipients are required.");let n=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!n)return r("unauthorized","Not logged in.");let s=await this.ctx.api.mailbox.sendGift(n);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",s.data)),s}async sendTransfer(e,t,i){if(!e?.trim())return r("client","RecipientUserID is required.");if(!i?.requestID?.trim())return r("client","requestID is required.");let n=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!n)return r("unauthorized","Not logged in.");let s=await this.ctx.api.mailbox.sendTransfer(n);return s.ok&&(s.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(s.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",s.data)),s}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):r("unauthorized","Not logged in.")}};var FR={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},jR={Title:"Title",Platform:"Platform"},wc=zod.z.object({UserID:zod.z.string(),PublicData:Ae.nullish(),Source:zod.z.enum(["Title","Platform"]).nullish()}),zi=zod.z.object({Friends:zod.z.array(wc).nullish()}),WR=zod.z.object({FriendsCount:zod.z.number().nullish(),IncomingRequestsCount:zod.z.number().nullish(),OutgoingRequestsCount:zod.z.number().nullish()}),Ti=zod.z.object({TargetUserID:zod.z.string().nullish(),Status:zod.z.string().nullish(),Target:wc.nullish(),Counters:WR.nullish()}),_R={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},KR={Like:"Like",Favorite:"Favorite"},QR={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},HR={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},$R={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},JR=zod.z.object({Key:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),AvatarUrl:zod.z.string().nullish()}).passthrough(),ZR=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(JR).nullish(),Payload:zod.z.object({Title:zod.z.string().nullish(),Excerpt:zod.z.string().nullish(),ImageUrl:zod.z.string().nullish()}).passthrough().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),OccurredAt:u.nullish(),OwnerImpact:w.nullish(),IsBlocked:zod.z.boolean().nullish(),TargetObjectName:zod.z.string().nullish()}).passthrough(),Mc=zod.z.object({Items:zod.z.array(ZR).nullish(),HasMore:zod.z.boolean().nullish(),NextBeforeUpdatedAt:zod.z.string().nullish(),NextBeforeID:zod.z.string().nullish(),UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),ki=zod.z.object({UnreadCount:zod.z.number().nullish(),SeenAt:u.nullish()}).passthrough(),YR=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(),Ut=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Counts:YR.nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish(),Following:zod.z.boolean().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),Oc=zod.z.object({Items:zod.z.array(Ut).nullish()}).passthrough(),Eo={HasMore:zod.z.boolean().nullish(),NextCursorAt:zod.z.string().nullish(),NextCursorID:zod.z.string().nullish()},XR=zod.z.object({UserID:zod.z.string(),PublicData:Ae.nullish(),Mutual:zod.z.boolean().nullish(),Since:u.nullish()}).passthrough(),cs=zod.z.object({Items:zod.z.array(XR).nullish(),...Eo}).passthrough(),eC=zod.z.object({EntityType:zod.z.string().nullish(),EntityID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),At:u.nullish()}).passthrough(),Uc=zod.z.object({Items:zod.z.array(eC).nullish(),...Eo}).passthrough(),ps=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:Ae.nullish(),Text:zod.z.string().nullish(),Status:zod.z.string().nullish(),Pinned:zod.z.boolean().nullish(),CreatedAt:u.nullish(),EditedAt:u.nullish(),Likes:zod.z.number().nullish(),Replies:zod.z.number().nullish(),Liked:zod.z.boolean().nullish(),IsMine:zod.z.boolean().nullish()}).passthrough(),Ec=zod.z.object({Items:zod.z.array(ps).nullish(),...Eo,TotalCount:zod.z.number().nullish()}).passthrough(),Bc=zod.z.object({CommentID:zod.z.string().nullish(),Deleted:zod.z.boolean().nullish()}).passthrough(),qc=zod.z.object({ReportID:zod.z.string().nullish(),AlreadyReported:zod.z.boolean().nullish(),AutoHidden:zod.z.boolean().nullish()}).passthrough(),Lc=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(),tC="FRIENDS_FROM_PLATFORM",iC={Off:"Off",Default:"Default",Always:"Always"},nC={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Gc=zod.z.object({Profile:zod.z.enum(["Off","Default","Always"]).nullish(),Friends:zod.z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish()}).passthrough(),ge={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 Bo={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},ds=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Bo,{schema:ki,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","TargetUserID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("client","RequesterUserID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("client","RequesterUserID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("client","FriendUserID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");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(Bo,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(Bo,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.baseRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):r("unauthorized","Not logged in.")}async getEntityStates(e,t){if(!t?.length)return r("client","EntityIDs are required.");let i=this.baseRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):r("unauthorized","Not logged in.")}async addComment(e,t,i,n){let s=this.targetRequest(e,t);if("ok"in s)return s;if(!i?.trim())return r("client","Text is required.");s.Text=i,s.ParentCommentID=n;let o=await this.ctx.api.social.addComment(s);return o.ok&&this.ctx.emitter.emit("social:commentAdded",o.data),o}async editComment(e,t){if(!e)return r("client","CommentID is required.");if(!t?.trim())return r("client","Text is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.CommentID=e,i.Text=t;let n=await this.ctx.api.social.editComment(i);return n.ok&&this.ctx.emitter.emit("social:commentEdited",n.data),n}async deleteComment(e){if(!e)return r("client","CommentID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let n=this.targetRequest(e,t);return "ok"in n?n:(n.ParentCommentID=i.parentCommentID,this.applyPage(n,i.cursor,i.limit),this.ctx.api.social.getComments(n))}async report(e,t,i,n){let s=this.targetRequest(e,t);if("ok"in s)return s;if(!i)return r("client","ReportReason is required.");s.ReportReason=i,s.ReportComment=n;let o=await this.ctx.api.social.report(s);return o.ok&&this.ctx.emitter.emit("social:reported",o.data),o}async mutate(e,t,i,n){let s=this.targetRequest(t,i);if("ok"in s)return s;s.ReactionKind=n;let o=await this.ctx.api.social[e](s);return o.ok&&this.ctx.emitter.emit("social:entityStateChanged",o.data),o}async page(e,t,i){let n=this.baseRequest();return n?(this.applyPage(n,t,i),this.ctx.api.social[e](n)):r("unauthorized","Not logged in.")}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 r("client","EntityType is required.");if(!t)return r("client","EntityID is required.");let i=this.baseRequest();return i?(i.EntityType=e,i.EntityID=t,i):r("unauthorized","Not logged in.")}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Nc="TimedBoost";function sC(a){return a.length>0&&!a.includes(".")&&!a.includes("$")}var hs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Nc,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),G(t);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");let n=await this.ctx.api.timedBoost.getDefinitions(i);return n.ok&&(this.ctx.data.config.patchSection(Nc,n.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",n.data)),n}async getActive(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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(!sC(i))return r("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${q()}`},s=await this.ctx.api.timedBoost.activate(n);if(s.ok){let o=s.data;if(o.ActivatedBoost){let c=o.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(o.ActivatedBoost,c);}this.ctx.data.user.applyResourceOperation(o.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",o);}return s}async cleanupExpired(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Pt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},rC={Client:"Client",Server:"Server",System:"System"},oC=zod.z.enum(["Client","Server","System"]).catch("Client"),aC=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:oC.nullish(),ExpiresAt:u.nullish()}).passthrough(),ms=zod.z.record(zod.z.string(),aC),Vc=zod.z.object({Version:zod.z.number().nullish(),Private:ms.nullish(),Public:ms.nullish(),ReadOnly:ms.nullish()}),qo=zod.z.object({UserID:zod.z.string().nullish(),Version:zod.z.number().nullish(),Public:ms.nullish()}),Lo=zod.z.object({ServerTimeUtc:u.nullish(),Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),lC=zod.z.object({Bucket:zod.z.string().nullish(),KeyID:zod.z.string(),Version:zod.z.number().nullish(),ExpiresAt:u.nullish()}),Fc=zod.z.object({ServerTimeUtc:u.nullish(),Results:zod.z.array(lC).nullish()}),jc=zod.z.object({ServerTimeUtc:u.nullish(),DeletedCount:zod.z.number().nullish()}),Wc=zod.z.object({Results:zod.z.array(qo).nullish(),NotFoundUserIDs:zod.z.array(zod.z.string()).nullish()}),uC={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},cC=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),pC=zod.z.object({KeyID:zod.z.string(),Bucket:zod.z.string().nullish(),ValueType:cC.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),fs=zod.z.object({Keys:zod.z.record(zod.z.string(),pC).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(),dt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var dC="UserCustomData";function _c(a){return a.length>0&&!a.includes(".")&&!a.includes("$")}var gs=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(dC,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","TargetUserID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.TargetUserID=t;let n=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return n.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",n.data),n}async setPrivateData(e,t){return this.setData(e,t,Pt.Private)}async setPublicData(e,t){return this.setData(e,t,Pt.Public)}async setData(e,t,i){let n=e.trim();if(!_c(n))return r("client",'KeyID is required and must not contain "." or "$".');if(t==null)return r("client","Value is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let s={...this.ctx.buildAuthedBaseRequest(),KeyID:n,Value:t},c=await(i===Pt.Private?this.ctx.api.userCustomData.setPrivateData(s):this.ctx.api.userCustomData.setPublicData(s));if(c.ok){let d=c.data;this.ctx.data.user.patchUserCustomDataKey(i,d.KeyID,t,d.Version??0,d.ExpiresAt),this.ctx.emitter.emit(i===Pt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",d);}return c}async deleteKey(e,t){let i=e.trim();if(!_c(i))return r("client",'KeyID is required and must not contain "." or "$".');if(t!==Pt.Private&&t!==Pt.Public)return r("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},s=await this.ctx.api.userCustomData.deleteKey(n);return s.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),s}async batchSet(e){if(!e.length)return r("client","At least one item is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let n of i.data.Results??[]){let s=n.Bucket??Pt.Private,o=e.find(c=>c.Bucket===s&&c.KeyID===n.KeyID);o&&this.ctx.data.user.patchUserCustomDataKey(s,n.KeyID,o.Value,n.Version??0,n.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return r("client","At least one item is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let n of e)this.ctx.data.user.removeUserCustomDataKey(n.Bucket,n.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return r("client","At least one target user id is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var hC="TitleCustomDataDefinitions",Kc=50;function mC(a){return a.length>0&&!a.includes(".")&&!a.includes("$")}function Go(a){if(a.ExpiresAt==null)return false;let e=Date.parse(a.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function fC(a){let e={};for(let[t,i]of Object.entries(a))Go(i)||(e[t]=i);return e}var ys=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(hC,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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(s=>s.trim()).filter(s=>s.length>0);if(!t.length)return r("client","At least one KeyID is required.");if(t.some(s=>!mC(s)))return r("client",'KeyID must not contain "." or "$".');if(t.length>Kc)return r("client",`At most ${Kc} keys per call \u2014 request them in chunks.`);let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.KeyIDs=t;let n=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return n.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",n.data),n}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Go(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Go(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=fC(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);}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Rs=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var gC=15,yC="GameLoop",RC="BoardDefinition",Cs=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(yC,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");let i=await this.ctx.api.gameLoop.getBoardDefinition(t,e);return i.ok&&(this.ctx.data.config.patchSection(RC,i.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i.data)),i}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return r("client","stageLevel must be > 0.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.StageLevel=e;let n=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return n.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",n.data),n}async getUserBoardState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${q()}`},n=await this.ctx.api.gameLoop.boardLoopRoll(i);if(n.ok){let s=n.data,o=zl(new Date,gC);this.ctx.data.user.patchBoardState(c=>{c.Position=s.NewPosition,c.CyclesCompleted=(c.CyclesCompleted??0)+(s.CyclesCompletedDelta??0),c.LastRollAtUtc=new Date().toISOString(),s.ActionRequired&&s.ActionData?c.Pending={Type:s.ActionRequired,TargetUserID:s.ActionData.TargetUserID,TargetPublicData:s.ActionData.PublicData,TargetBuildingStates:s.ActionData.TargetBuildingStates??void 0,TargetHasShield:s.ActionData.TargetHasShield??void 0,RollMultiplier:s.UsedMultiplier??1,ExpiresAtUtc:o}:s.SpecialModeOffer&&(c.Pending={Type:"SPECIAL",RollMultiplier:s.UsedMultiplier??1,ExpiresAtUtc:o,Special:{ModeID:s.SpecialModeOffer.ModeID??void 0,Choices:s.SpecialModeOffer.Choices??void 0}});}),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),s.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",s);}return n}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${q()}`},n=await this.ctx.api.gameLoop.boardLoopAttack(i);if(n.ok){let s=n.data;this.ctx.data.user.clearBoardPending(),s.IsBotTarget&&s.Operation?this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs):!s.IsBotTarget&&s.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(s.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",s);}else await this.getUserBoardState();return n}async boardLoopRaid(e,t){if(e<0||e>11)return r("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${q()}`},s=await this.ctx.api.gameLoop.boardLoopRaid(n);if(s.ok){let o=s.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 s}async boardLoopRaidFast(e){if(!e.length)return r("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${q()}`},n=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(n.ok){let s=n.data;s.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(s)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",s);}else await this.getUserBoardState();return n}async boardLoopBuild(e){if(e<0)return r("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${q()}`},n=await this.ctx.api.gameLoop.boardLoopBuild(i);if(n.ok){let s=n.data;s.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(s.BuiltIndex,o=>{s.NewLevel!=null&&(o.Level=s.NewLevel),o.IsDamaged=false,s.MaxLevelRewardClaimed&&(o.MaxLevelRewardClaimed=true);}),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",s);}return n}async boardSpecialChoose(e,t){if(!e)return r("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return r("unauthorized","Not logged in.");let n={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${q()}`},s=await this.ctx.api.gameLoop.boardSpecialChoose(n);if(s.ok){let o=s.data;o.Mode==="Instant"||o.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(d=>{d.ChoiceID=e,d.ChosenMode=o.Mode??"Timed",d.StartedAtUtc=o.StartedAtUtc??null,d.DurationSeconds=o.DurationSeconds??null,d.AdViewsUsed=0;}),o.Operation&&this.ctx.data.user.applyResourcesWithDelta(o.Operation,o.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",o);}return s}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${q()}`},n=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(n.ok){let s=n.data;this.ctx.data.user.patchBoardSpecialPending(o=>{o.AdViewsUsed=s.AdViewsUsed??0,o.AccumulatedMultiplier=s.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",s);}return n}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${q()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},n=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(n.ok){let s=n.data;this.ctx.data.user.clearBoardPending(),s.Operation&&this.ctx.data.user.applyResourcesWithDelta(s.Operation,s.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",s);}return n}async getCommunityChestState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");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 r("client","milestoneID is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},n=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",n.data)),n}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");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 r("unauthorized","Not logged in.");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);}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Ss=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,n){let s=e.trim();if(!s)return r("client","FunctionName is required.");if(!this.ctx.auth.context)return r("unauthorized","Not logged in.");let o={...this.ctx.buildAuthedBaseRequest(),FunctionName:s,FunctionParameter:t,RevisionSelection:i,SpecificRevision:n},c=await this.ctx.api.cloudCode.execute(o);return c.ok&&this.ctx.emitter.emit("cloudCode:executed",c.data),c}};var Qc=zod.z.object({ServerTimeUtc:u,SourceType:si,SourceID:zod.z.string(),TargetType:si,TargetID:zod.z.string(),SourceSpent:j,FeeAmount:j,RateApplied:Y,TargetCredited:j}),Hc=zod.z.object({ServerTimeUtc:u,SourceType:si,SourceID:zod.z.string(),TargetType:si,TargetID:zod.z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),xs={Convert:"Convert",CryptoConvert:"CryptoConvert"},CC={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},$c=zod.z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),SC={Automatic:"Automatic",Manual:"Manual"},xC=zod.z.enum(["Automatic","Manual"]).catch("Automatic"),bC=zod.z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:u.nullish(),InitialDeposit:zod.z.number().nullish(),MinBalance:zod.z.number().nullish(),MaxBalance:zod.z.number().nullish(),DailyEarnLimit:zod.z.number().nullish(),DailySpendLimit:zod.z.number().nullish()}).passthrough(),DC=zod.z.object({Rate:zod.z.number().nullish(),Max:zod.z.number().nullish(),Period:zod.z.number().nullish()}).passthrough(),PC=zod.z.object({IsTradable:zod.z.boolean().nullish(),IsPurchasable:zod.z.boolean().nullish(),IsRefundable:zod.z.boolean().nullish()}).passthrough(),vC=zod.z.object({TargetCurrencyType:si.nullish(),TargetCurrencyID:zod.z.string(),Rate:Y.nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish(),DailyLimit:zod.z.number().nullish()}).passthrough(),Jc=zod.z.object({Enabled:zod.z.boolean().nullish(),RateMode:xC.nullish(),Fee:zod.z.number().nullish(),Targets:zod.z.array(vC).nullish()}).passthrough(),Zc=zod.z.object({CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough(),IC=zod.z.object({CurrencyID:zod.z.string(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Economy:bC.nullish(),Recharge:DC.nullish(),Conversion:Jc.nullish(),Permissions:PC.nullish(),Audit:Zc.nullish(),Status:$c.nullish()}).passthrough(),zC=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(),TC=zod.z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),kC=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),SpendableInGame:zod.z.boolean().nullish(),ConvertibleToVirtual:zod.z.boolean().nullish()}).passthrough(),AC=zod.z.object({Mode:zod.z.string().nullish(),FundingNetworkID:zod.z.string().nullish(),PerPlayerDailyTokens:zod.z.number().nullish(),TitleDailyTokens:zod.z.number().nullish()}).passthrough(),No=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:u.nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),Networks:zod.z.array(zC).nullish(),Limits:TC.nullish(),Permissions:kC.nullish(),Conversion:Jc.nullish(),Audit:Zc.nullish(),Status:$c.nullish(),ServerGrantPolicy:AC.nullish(),UnbackedRewardCurrencyID:zod.z.string().nullish()}).passthrough(),bs=zod.z.object({VirtualCurrencies:zod.z.record(zod.z.string(),IC).nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),No).nullish()}).passthrough();var wC={EVM:"EVM",Solana:"Solana"},MC=zod.z.enum(["EVM","Solana"]).catch("EVM"),OC={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},UC=zod.z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),EC={Token:"Token",Nft:"Nft"},Yc=zod.z.enum(["Token","Nft"]).catch("Token"),BC={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},qC=zod.z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),LC={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},GC=zod.z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),NC={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},Vo=zod.z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),Xc={GameTopUp:"game_topup",CommunityReward:"community_reward"};function Ds(a){let e=a?.trim();return e||Xc.GameTopUp}var VC={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},ep=zod.z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),FC=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(),tp=zod.z.object({Ios:zod.z.boolean().nullish(),Android:zod.z.boolean().nullish(),Web:zod.z.boolean().nullish()}).passthrough(),jC=zod.z.object({NetworkID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Type:MC.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:tp.nullish(),NftCollections:zod.z.array(FC).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(),WC=zod.z.object({DepositsEnabled:zod.z.boolean().nullish(),WithdrawalsEnabled:zod.z.boolean().nullish(),NftDepositsEnabled:zod.z.boolean().nullish(),NftWithdrawalsEnabled:zod.z.boolean().nullish(),PlatformOverrides:tp.nullish()}).passthrough(),_C=zod.z.object({MinAccountAgeDays:zod.z.number().nullish(),MultiAccountCheckEnabled:zod.z.boolean().nullish(),BanOnSharedWithdrawalAddress:zod.z.boolean().nullish(),PendingWithdrawalTtlHours:zod.z.number().nullish()}).passthrough(),KC={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},QC=zod.z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),ip=zod.z.object({Enabled:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:QC.nullish(),DenyMessage:zod.z.string().nullish()}).passthrough(),HC=zod.z.object({Enabled:zod.z.boolean().nullish(),WalletConnectProjectId:zod.z.string().nullish()}).passthrough(),$C={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},Ai=zod.z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),JC=zod.z.object({Mode:Ai.nullish(),TokenGates:zod.z.array(ip).nullish()}).passthrough(),Fo=zod.z.object({SystemState:WC.nullish(),Networks:zod.z.record(zod.z.string(),jC).nullish(),AccountSafety:_C.nullish(),WalletLogin:HC.nullish(),PlayAccess:JC.nullish(),IframeConnectHosts:zod.z.array(zod.z.string()).nullish()}).passthrough(),ZC=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),LinkedAt:u.nullish(),LastUsedAt:u.nullish(),LinkType:UC.nullish(),IsSignatureVerified:zod.z.boolean().nullish()}).passthrough(),np=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Type:Yc.nullish(),NetworkID:zod.z.string().nullish(),AssetID:zod.z.string().nullish(),Amount:Y.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),YC=zod.z.object({Status:qC.nullish(),Tier:GC.nullish(),VerifiedAt:u.nullish(),ExpiresAt:u.nullish(),RejectedAt:u.nullish(),ProviderReference:zod.z.string().nullish(),RejectionReason:zod.z.string().nullish()}).passthrough(),XC=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:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),eS=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(),XC).nullish()}).passthrough(),tS=zod.z.object({NetworkID:zod.z.string().nullish(),ItemCatalogID:zod.z.string().nullish(),Deposits:zod.z.number().nullish(),Withdrawals:zod.z.number().nullish(),FailedWithdrawals:zod.z.number().nullish(),RejectedDeposits:zod.z.number().nullish(),FirstDepositAt:u.nullish(),LastDepositAt:u.nullish(),FirstWithdrawalAt:u.nullish(),LastWithdrawalAt:u.nullish()}).passthrough(),iS=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(),tS).nullish()}).passthrough(),nS=zod.z.object({Tokens:eS.nullish(),Nfts:iS.nullish()}).passthrough(),jo=zod.z.object({CurrencyID:zod.z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Et=zod.z.object({Granted:zod.z.boolean(),Mode:Ai.nullish(),Error:zod.z.string().nullish(),WalletRequired:zod.z.boolean().nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),GrantedUntil:u.nullish(),Balances:zod.z.array(jo).nullish()}).passthrough(),sS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:u.nullish(),Passed:zod.z.boolean().nullish(),GrantedUntil:u.nullish(),Error:zod.z.string().nullish(),Balances:zod.z.array(jo).nullish()}).passthrough(),rS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CanUnlink:zod.z.boolean().nullish()}).passthrough(),sp=zod.z.object({Mode:Ai.nullish(),TokenGates:zod.z.array(ip).nullish(),WalletLoginEnabled:zod.z.boolean().nullish(),CanLinkWallet:zod.z.boolean().nullish(),WalletsFromPlatformProfile:zod.z.boolean().nullish(),LinkedWallets:zod.z.array(rS).nullish(),Status:Et.nullish()}).passthrough(),oS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CheckedAt:u.nullish(),LoggedInAt:u.nullish(),GatePassed:zod.z.boolean().nullish(),GatedBalances:zod.z.array(jo).nullish()}).passthrough(),aS=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),UnlinkedAt:u.nullish()}).passthrough(),lS=zod.z.object({Version:zod.z.number().nullish(),Stats:nS.nullish(),LinkedWallets:zod.z.record(zod.z.string(),ZC).nullish(),LastWalletLogin:oS.nullish(),PlayAccess:sS.nullish(),PendingWithdrawals:zod.z.array(np).nullish(),Kyc:YC.nullish(),FirstActivityAt:u.nullish(),LastActivityAt:u.nullish(),IsFlagged:zod.z.boolean().nullish(),FlagReason:zod.z.string().nullish(),UnlinkedWallets:zod.z.array(aS).nullish()}).passthrough(),uS=zod.z.object({CurrencyID:zod.z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:u}).passthrough(),mi=zod.z.object({CryptoBalances:zod.z.record(zod.z.string(),uS).nullish(),PendingAdded:np.nullish(),PendingRemovedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),cS=zod.z.object({Amount:Y,Frozen:Y,CreatedAt:u.nullish(),UpdatedAt:u.nullish()}).passthrough().transform(a=>a),pS=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:ep.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Vo.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:u.nullish(),BurnAmount:zod.z.number().nullish(),RefundedAt:u.nullish(),RefundCheckedAt:u.nullish()}).passthrough(),dS=zod.z.object({ID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),UserID:zod.z.string().nullish(),TransactionHash:zod.z.string().nullish(),Nonce:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ChainType:zod.z.string().nullish(),ChainID:zod.z.number().nullish(),Direction:ep.nullish(),From:zod.z.string().nullish(),To:zod.z.string().nullish(),Amount:Y.nullish(),Status:Vo.nullish(),SignatureData:zod.z.string().nullish(),CompletedAt:u.nullish(),ExpiresAt:u.nullish(),FailReason:zod.z.string().nullish(),Reason:zod.z.string().nullish(),Category:zod.z.string().nullish(),NFTID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),SkinID:zod.z.string().nullish(),TemplateID:zod.z.string().nullish(),DataType:zod.z.string().nullish(),TitleDeletedAt:u.nullish()}).passthrough(),rp=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),Wo=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(rp).nullish(),Signature:zod.z.string().nullish()}).passthrough(),_o=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(rp).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(),op=zod.z.object({Blockchain:Fo.nullish(),CryptoCurrencies:zod.z.record(zod.z.string(),No).nullish()}).passthrough(),ap=zod.z.object({State:lS.nullish(),CryptoBalances:zod.z.record(zod.z.string(),cS).nullish()}).passthrough(),lp=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),CurrencyID:zod.z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:mi.nullish()}).passthrough(),up=zod.z.object({ServerTimeUtc:u.nullish(),TransactionHash:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),Resources:w.nullish(),Inventory:K.nullish()}).passthrough(),cp=zod.z.object({ServerTimeUtc:u.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:u.nullish(),EvmSignature:Wo.nullish(),SolanaSignature:_o.nullish(),StateDelta:mi.nullish(),ChainID:zod.z.number().nullish()}).passthrough(),pp=zod.z.object({ServerTimeUtc:u.nullish(),TitleTransactionID:zod.z.string().nullish(),NetworkID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),NftTokenID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:w.nullish(),EvmSignature:Wo.nullish(),SolanaSignature:_o.nullish(),StateDelta:mi.nullish(),Inventory:K.nullish()}).passthrough(),dp=zod.z.object({TokenTransactions:zod.z.array(pS).nullish(),NFTTransactions:zod.z.array(dS).nullish(),RefundedIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Ko=zod.z.object({ServerTimeUtc:u.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(),hp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),Kind:Yc.nullish(),EvmSignature:Wo.nullish(),SolanaSignature:_o.nullish()}).passthrough(),mp=zod.z.object({TitleTransactionID:zod.z.string().nullish(),OnChainTxHash:zod.z.string().nullish(),Status:Vo.nullish(),StateDelta:mi.nullish()}).passthrough(),_e={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 hS="Blockchain",Ps=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.blockchain.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(hS,t.data.Blockchain),this.ctx.emitter.emit("blockchain:definitionsLoaded",t.data)),t}async getUserState(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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 r("client","NetworkID is required.");if(!t)return r("client","TransactionHash is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositToken(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",n.data)),n}async depositNFT(e,t){if(!e)return r("client","NetworkID is required.");if(!t)return r("client","TransactionHash is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.depositNFT(i);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",n.data)),n}async requestTokenWithdrawal(e,t,i,n,s){if(!e)return r("client","CurrencyID is required.");if(!t)return r("client","NetworkID is required.");if(!i)return r("client","WalletAddress is required.");if(!n)return r("client","Amount is required.");let o=this.baseRequest();if(!o)return r("unauthorized","Not logged in.");o.CurrencyID=e,o.NetworkID=t,o.WalletAddress=i,o.Amount=n,o.Category=Ds(s);let c=await this.ctx.api.blockchain.requestTokenWithdrawal(o);return c.ok&&(this.ctx.data.user.applyBlockchainStateDelta(c.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",c.data)),c}async requestNFTWithdrawal(e,t,i,n,s,o,c){if(!e)return r("client","ItemID is required.");if(!t)return r("client","NetworkID is required.");if(!i)return r("client","WalletAddress is required.");if(!n)return r("client","Amount is required.");let d=this.baseRequest();if(!d)return r("unauthorized","Not logged in.");d.ItemID=e,d.NetworkID=t,d.WalletAddress=i,d.Amount=n,d.Category=Ds(s),o!==void 0&&(d.Level=o),c&&(d.ItemInstanceID=c);let R=await this.ctx.api.blockchain.requestNFTWithdrawal(d);return R.ok&&(this.ctx.data.user.applyBlockchainStateDelta(R.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(R.data.Resources,R.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",R.data)),R}async getTransactionHistory(e=50){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","TitleTransactionID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","TitleTransactionID is required.");if(!t)return r("client","On-chain TransactionHash is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.TitleTransactionID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.confirmWithdrawal(i);return n.ok&&(this.ctx.data.user.applyBlockchainStateDelta(n.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",n.data)),n}async donateToDeveloper(e,t){if(!e)return r("client","NetworkID is required.");if(!t)return r("client","TransactionHash is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToDeveloper(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",n.data),n}async donateToUsersPool(e,t){if(!e)return r("client","NetworkID is required.");if(!t)return r("client","TransactionHash is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.NetworkID=e,i.TransactionHash=t;let n=await this.ctx.api.blockchain.donateToUsersPool(i);return n.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",n.data),n}async getPlayAccess(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();if(!t)return r("unauthorized","Not logged in.");e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var mS={Head:"Head",Torso:"Torso",Legs:"Legs"},vs=zod.z.enum(["Head","Torso","Legs"]).catch("Head"),fS={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},Qo=zod.z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),gp=zod.z.object({AttackTarget:vs,DefenseTarget:vs});var gS=zod.z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),yS=zod.z.object({RoundIndex:zod.z.number().nullish(),AttackerID:zod.z.string().nullish(),DefenderID:zod.z.string().nullish(),AttackZone:vs.nullish(),DefenseZone:vs.nullish(),HitType:gS.nullish(),DamageDealt:zod.z.number().nullish(),DefenderHpRemaining:zod.z.number().nullish()}).passthrough(),RS=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(),CS=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(a=>a),fp=zod.z.object({UserID:zod.z.string().nullish(),SelectedCharacterID:zod.z.string().nullish(),SelectedCharacter:Co.nullish(),BattleStrategy:zod.z.array(gp).nullish(),UnstackableItems:zod.z.record(zod.z.string(),CS).nullish(),Stats:RS.nullish()}).passthrough(),SS=zod.z.object({WinnerUserID:zod.z.string().nullish(),LoserUserID:zod.z.string().nullish(),Entry:ae.nullish(),NetReward:ae.nullish(),BattleLog:zod.z.array(yS).nullish(),IsDraw:zod.z.boolean().nullish(),P1BattleProfile:fp.nullish(),P2BattleProfile:fp.nullish()}).passthrough(),yp=zod.z.object({MatchID:zod.z.string(),TitleID:zod.z.string().nullish(),RuleID:zod.z.string().nullish(),CreatedAt:u.nullish(),CreatorID:zod.z.string().nullish(),CreatorCharacterID:zod.z.string().nullish(),CreatorStrategy:zod.z.array(gp).nullish(),TargetUserID:zod.z.string().nullish(),Entry:ae.nullish(),CreationCostPaid:ae.nullish(),RefundCreationCostOnCancel:zod.z.boolean().nullish(),ExpiresAt:u.nullish(),JoinedByUserID:zod.z.string().nullish(),JoinedByCharacterID:zod.z.string().nullish(),JoinedAt:u.nullish(),Status:Qo.nullish(),WinnerUserID:zod.z.string().nullish(),CompletedAt:u.nullish(),IsRewardDistributed:zod.z.boolean().nullish(),RewardDistributedAt:u.nullish()}).passthrough(),Rp=zod.z.object({Status:Qo,MatchID:zod.z.string(),Entry:ae.nullish(),Resources:w.nullish()}),Cp=zod.z.object({Match:yp.nullish()}),Sp=zod.z.object({MatchID:zod.z.string(),Status:Qo,Resources:w.nullish()}),xp=zod.z.object({Battle:SS.nullish(),Resources:w.nullish(),ResourcesDual:St.nullish()}),Ho=zod.z.object({Matches:zod.z.array(yp).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}),yt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var xS=zod.z.enum(["VirtualCurrency","Item","EventToken"]).catch("VirtualCurrency");var bS=zod.z.enum(["Constant","Variable","Curve"]).catch("Constant"),DS=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(),PS=zod.z.enum(["Flat","PercentReduction"]).catch("Flat"),vS=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:PS.nullish(),MaxArmorReduction:zod.z.number().nullish()}).passthrough(),IS=zod.z.object({Kind:bS.nullish(),Constant:zod.z.number().nullish(),VariableID:zod.z.string().nullish(),Argument:zod.z.string().nullish(),Curve:Le.nullish(),OnePlus:zod.z.boolean().nullish()}).passthrough(),zS=zod.z.object({Coefficient:zod.z.number().nullish(),Factors:zod.z.array(IS).nullish()}).passthrough(),jt=zod.z.object({Terms:zod.z.array(zS).nullish()}).passthrough(),TS=zod.z.object({Health:jt.nullish(),Damage:jt.nullish(),Armor:jt.nullish(),AttackSpeed:jt.nullish(),CritChance:jt.nullish(),CritDamage:jt.nullish(),Dodge:jt.nullish()}).passthrough(),bp=zod.z.object({StatMapping:DS.nullish(),Combat:vS.nullish(),Formula:TS.nullish()}).passthrough(),kS=zod.z.object({BurnRate:zod.z.number().nullish()}).passthrough(),wi=zod.z.object({Kind:xS.nullish(),CurrencyID:zod.z.string().nullish(),CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),TokenType:Vi.nullish(),EntityID:zod.z.string().nullish(),MinAmount:zod.z.number().nullish(),MaxAmount:zod.z.number().nullish()}).passthrough(),Dp=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),Allowed:zod.z.array(wi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Pp=zod.z.object({PriceOptions:oe.nullish(),RefundCostOnCancel:zod.z.boolean().nullish(),MaxOpenMatches:zod.z.number().nullish(),OfferLifetimeSeconds:zod.z.number().nullish(),Limits:fe.nullish(),AllowPrivateMatches:zod.z.boolean().nullish(),MaxMatchesPerOpponentPerDay:zod.z.number().nullish()}).passthrough(),AS=zod.z.object({RuleID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Economy:kS.nullish(),Entry:Dp.nullish(),Creation:Pp.nullish(),Settings:bp.nullish()}).passthrough(),wS=zod.z.object({Rules:zod.z.record(zod.z.string(),AS).nullish(),Defaults:bp.nullish(),EntryDefaults:Dp.nullish(),CreationDefaults:Pp.nullish()}).passthrough(),$o=zod.z.object({InstantBattle:wS.nullish()}).passthrough(),vp=$o;var MS={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Jo=zod.z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),OS={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Zo=zod.z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),US={Burn:"Burn",Ledger:"Ledger"},ES=zod.z.enum(["Burn","Ledger"]).catch("Burn"),zs={Item:"Item",VirtualCurrency:"VirtualCurrency"},Yo=zod.z.enum(["Item","VirtualCurrency"]).catch("Item"),BS=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish()}).passthrough(),Ts=zod.z.object({AllowVirtualCurrency:zod.z.boolean().nullish(),AllowItems:zod.z.boolean().nullish(),AllowEventTokens:zod.z.boolean().nullish(),Allowed:zod.z.array(wi).nullish(),MaxPositions:zod.z.number().nullish()}).passthrough(),Xo=zod.z.object({Percent:zod.z.number().nullish(),MinPerPosition:j.nullish(),Sink:ES.nullish(),LedgerAccountID:zod.z.string().nullish(),PerCatalogOverrides:zod.z.record(zod.z.string(),BS).nullish(),ApplyToDirectTrades:zod.z.boolean().nullish()}).passthrough(),qS=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(),LS=zod.z.object({Enabled:zod.z.boolean().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),MaxActiveListings:zod.z.number().nullish(),CreateLimits:fe.nullish(),BuyLimits:fe.nullish(),ListingFeeOptions:oe.nullish(),RefundListingFeeOnCancel:zod.z.boolean().nullish()}).passthrough(),GS=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:fe.nullish()}).passthrough(),NS=zod.z.object({Enabled:zod.z.boolean().nullish(),MaxActiveOrders:zod.z.number().nullish(),AllowedDurationsHours:zod.z.array(zod.z.number()).nullish(),CreateLimits:fe.nullish(),FillLimits:fe.nullish()}).passthrough(),VS=zod.z.object({Enabled:zod.z.boolean().nullish(),OfferExpirationHours:zod.z.number().nullish(),MaxPendingOutgoing:zod.z.number().nullish(),AllowGifts:zod.z.boolean().nullish(),CreateLimits:fe.nullish()}).passthrough(),FS=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),ea=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:$.nullish(),Schedule:de.nullish(),PricePolicy:Ts.nullish(),Commission:Xo.nullish(),Tradability:qS.nullish(),Listings:LS.nullish(),Auctions:GS.nullish(),BuyOrders:NS.nullish(),DirectTrades:VS.nullish(),Matching:FS.nullish()}).passthrough(),Ip=zod.z.object({BidIndex:zod.z.number().nullish(),UserID:zod.z.string().nullish(),Amount:j.nullish(),Settled:zod.z.boolean().nullish(),SettledAt:u.nullish()}).passthrough(),jS=zod.z.object({BidAxisType:ri.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(Ip).nullish()}).passthrough(),Is=zod.z.object({LastAt:u.nullish(),DailyCount:zod.z.number().nullish(),DailyResetUtc:u.nullish()}).passthrough(),WS=zod.z.object({Create:Is.nullish(),Buy:Is.nullish(),Sell:Is.nullish(),Bid:Is.nullish()}).passthrough(),_S=zod.z.object({CharacterID:zod.z.string().nullish(),SlotID:zod.z.string().nullish()}).passthrough(),KS=zod.z.object({ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Quantity:zod.z.number().nullish(),RemainingUses:zod.z.number().nullish(),Level:zod.z.number().nullish(),AcquiredAt:u,ExpiresAt:u.nullish(),EquippedSlot:_S.nullish(),CustomData:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough().transform(a=>a),vt=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Jo.nullish(),Status:Zo.nullish(),CreatorUserID:zod.z.string().nullish(),CreatorPublicData:Ae.nullish(),TargetUserID:zod.z.string().nullish(),GoodsType:Yo.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),GoodsInstances:zod.z.array(KS).nullish(),Price:ae.nullish(),Auction:jS.nullish(),CreatedAt:u.nullish(),ExpiresAt:u.nullish()}).passthrough(),QS=zod.z.object({GoodsType:Yo.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),CountsByType:zod.z.partialRecord(Jo,j).nullish()}).passthrough(),zp=zod.z.object({Definitions:ea.nullish(),IsOpenNow:zod.z.boolean().nullish(),GatePassed:zod.z.boolean().nullish()}).passthrough(),ta=zod.z.object({Offers:zod.z.array(vt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Tp=zod.z.object({Groups:zod.z.array(QS).nullish()}).passthrough(),kp=zod.z.object({Offer:vt.nullish()}).passthrough(),ot=zod.z.object({OfferID:zod.z.string().nullish(),Status:Zo.nullish(),Settlement:St.nullish(),Resources:w.nullish(),CommissionTaken:ae.nullish()}).passthrough(),Mi=zod.z.object({OfferID:zod.z.string().nullish(),Offer:vt.nullish(),Resources:w.nullish(),Matched:zod.z.boolean().nullish(),Settlement:ot.nullish()}).passthrough(),Ap=zod.z.object({OfferID:zod.z.string().nullish(),CurrentBid:j.nullish(),BidCount:zod.z.number().nullish(),ExpiresAt:u.nullish(),Resources:w.nullish()}).passthrough(),ks=zod.z.object({MyOffers:zod.z.array(vt).nullish(),MyBids:zod.z.array(vt).nullish(),MyBuyOrders:zod.z.array(vt).nullish(),IncomingTrades:zod.z.array(vt).nullish(),OutgoingTrades:zod.z.array(vt).nullish(),Claimables:zod.z.array(vt).nullish(),DrainedRefunds:zod.z.array(Ip).nullish(),Limits:WS.nullish()}).passthrough(),HS=zod.z.object({OfferID:zod.z.string().nullish(),OfferType:Jo.nullish(),FinalStatus:Zo.nullish(),SellerUserID:zod.z.string().nullish(),BuyerUserID:zod.z.string().nullish(),GoodsType:Yo.nullish(),GoodsCatalogID:zod.z.string().nullish(),GoodsItemID:zod.z.string().nullish(),GoodsCurrencyID:zod.z.string().nullish(),GoodsAmount:j.nullish(),PricePaid:ae.nullish(),CommissionTaken:ae.nullish(),CompletedAt:u.nullish(),MyRole:zod.z.string().nullish()}).passthrough(),wp=zod.z.object({Entries:zod.z.array(HS).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),ve={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 $S="Marketplace",Mp={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"]},As=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Mp,{schema:ks,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection($S,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,n=20){if(!e)return r("client","ItemID is required.");let s=this.baseRequest();if(!s)return r("unauthorized","Not logged in.");s.ItemID=e,s.OfferTypeFilter=t,s.ContinuationToken=i,s.PageSize=n;let o=await this.ctx.api.marketplace.getOffersByItem(s);return o.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",o.data),o}async getOffer(e){if(!e)return r("client","OfferID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.ItemID=e,n.ContinuationToken=t,n.PageSize=i;let s=await this.ctx.api.marketplace.getBuyOrders(n);return s.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",s.data),s}getMyState(e,t){return this.ctx.cache.read(Mp,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");i&&(n.HistoryFilter=i),n.ContinuationToken=e,n.PageSize=t;let s=await this.ctx.api.marketplace.getHistory(n);return s.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",s.data),s}async createListing(e,t,i,n,s,o,c){if(!e)return r("client","ItemID is required.");if(!t)return r("client","CatalogID is required.");if(!n)return r("client","PriceBundle is required.");let d=this.baseRequest();if(!d)return r("unauthorized","Not logged in.");d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.PriceBundle=n,d.DurationHours=s,d.ItemInstanceIDs=o,d.SelectedOptionID=c;let R=await this.ctx.api.marketplace.createListing(d);return this.applyCreateOfferResult(R,"marketplace:listingCreated"),R}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return r("client","OfferID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","GoodsAmount must be positive.");if(!t)return r("client","PriceBundle is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");let s=this.applyGoodsSelector(n,i);if(s)return s;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketBuy(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",o.data)),o}async marketSell(e,t,i){if(!e||e<=0)return r("client","GoodsAmount must be positive.");if(!t)return r("client","PriceBundle is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");let s=this.applyGoodsSelector(n,i);if(s)return s;n.GoodsAmount=e,n.PriceBundle=t;let o=await this.ctx.api.marketplace.marketSell(n);return o.ok&&(this.applyDualPartySettlement(o.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",o.data)),o}async createAuction(e,t,i,n,s,o,c={}){if(!e)return r("client","ItemID is required.");if(!t)return r("client","CatalogID is required.");let d=this.baseRequest();if(!d)return r("unauthorized","Not logged in.");d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.BidAxisType=n,d.BidCurrencyID=c.bidCurrencyID,d.BidCatalogID=c.bidCatalogID,d.BidItemID=c.bidItemID,d.StartingBid=s,d.DurationHours=o,d.ItemInstanceIDs=c.itemInstanceIDs,d.SelectedOptionID=c.selectedOptionID;let R=await this.ctx.api.marketplace.createAuction(d);return this.applyCreateOfferResult(R,"marketplace:auctionCreated"),R}async placeBid(e,t){if(!e)return r("client","OfferID is required.");if(!t||t<=0)return r("client","BidAmount must be positive.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.OfferID=e,i.BidAmount=t;let n=await this.ctx.api.marketplace.placeBid(i);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",n.data)),n}async claimAuction(e){if(!e)return r("client","OfferID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,n,s){if(!e)return r("client","ItemID is required.");if(!t)return r("client","CatalogID is required.");if(!n)return r("client","PriceBundle is required.");let o=this.baseRequest();if(!o)return r("unauthorized","Not logged in.");o.ItemID=e,o.CatalogID=t,o.GoodsAmount=i,o.PriceBundle=n,o.DurationHours=s;let c=await this.ctx.api.marketplace.createBuyOrder(o);return this.applyCreateOfferResult(c,"marketplace:buyOrderCreated"),c}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return r("client","OfferID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,n,s){if(!e)return r("client","TargetUserID is required.");if(!t)return r("client","CatalogID is required.");if(!i)return r("client","ItemID is required.");let o=this.baseRequest();if(!o)return r("unauthorized","Not logged in.");o.TargetUserID=e,o.CatalogID=t,o.ItemID=i,o.ItemInstanceIDs=n,o.RequestedBundle=s;let c=await this.ctx.api.marketplace.createDirectTrade(o);return this.applyCreateOfferResult(c,"marketplace:directTradeCreated"),c}async respondDirectTrade(e,t){if(!e)return r("client","OfferID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.OfferID=e,i.Accept=t;let n=await this.ctx.api.marketplace.respondDirectTrade(i);return n.ok&&(t&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",n.data)),n}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","OfferID is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.OfferID=e;let s=await t(n);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,s.data)),s}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=zs.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=zs.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):r("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);}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var ws=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return r("client","RoomName is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");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;let n=await this.ctx.api.multiplayer.createRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",n.data),n}async joinRoom(e,t){if(!e)return r("client","RoomID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.JoinCode=t;let n=await this.ctx.api.multiplayer.joinRoom(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",n.data),n}async leaveRoom(e,t={}){if(!e)return r("client","RoomID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.SuccessorUserID=t.successorUserID;let n=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return n.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",n.data),n}async claimHost(e){if(!e)return r("client","RoomID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","RoomID is required.");if(!t)return r("client","TargetUserID is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.RoomID=e,n.TargetUserID=t,n.Ban=i;let s=await this.ctx.api.multiplayer.kickMember(n);return s.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",s.data),s}async unbanMember(e,t){if(!e)return r("client","RoomID is required.");if(!t)return r("client","TargetUserID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.TargetUserID=t;let n=await this.ctx.api.multiplayer.unbanMember(i);return n.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",n.data),n}async listRooms(e=0,t=20){let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.Page=e,i.PageSize=t;let n=await this.ctx.api.multiplayer.listRooms(i);return n.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",n.data),n}async getRoom(e){if(!e)return r("client","RoomID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","RoomID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 r("client","RoomID is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.LastSeq=t;let n=await this.ctx.api.multiplayer.poll(i);return n.ok&&this.ctx.emitter.emit("multiplayer:polled",n.data),n}async sendSignal(e,t,i,n){if(!e)return r("client","RoomID is required.");if(!t)return r("client","TargetUserID is required.");if(!i)return r("client","SignalKind is required.");let s=this.baseRequest();if(!s)return r("unauthorized","Not logged in.");s.RoomID=e,s.TargetUserID=t,s.SignalKind=i,s.Payload=n;let o=await this.ctx.api.multiplayer.sendSignal(s);return o.ok&&this.ctx.emitter.emit("multiplayer:signalSent",o.data),o}async sendChat(e,t){if(!e)return r("client","RoomID is required.");if(!t)return r("client","ChatText is required.");let i=this.baseRequest();if(!i)return r("unauthorized","Not logged in.");i.RoomID=e,i.ChatText=t;let n=await this.ctx.api.multiplayer.sendChat(i);return n.ok&&this.ctx.emitter.emit("multiplayer:chatSent",n.data),n}async setMemberState(e,t,i){if(!e)return r("client","RoomID is required.");let n=this.baseRequest();if(!n)return r("unauthorized","Not logged in.");n.RoomID=e,n.Ready=t,n.MemberState=i;let s=await this.ctx.api.multiplayer.setMemberState(n);return s.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",s.data),s}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};var Op=" (if the network is fine, the storage bucket has no CORS rule for this origin)",Ms=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.baseRequest();if(!e)return r("unauthorized","Not logged in.");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.baseRequest();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.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):r("unauthorized","Not logged in.")}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 r("client","CollectionID is required.");let t=this.baseRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):r("unauthorized","Not logged in.")}async getCreatorProfile(e,t,i){if(!e)return r("client","CreatorUserID is required.");let n=this.baseRequest();return n?(n.CreatorUserID=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getCreatorProfile(n)):r("unauthorized","Not logged in.")}async publish(e){if(!e.files||e.files.length===0)return r("client","At least one file is required.");let t=new Map,i=e.files.map((d,R)=>{if("sourceAssetUrl"in d)return {Role:d.role,ContentType:d.contentType,SourceAssetUrl:d.sourceAssetUrl};let V=Up(d.data,d.contentType);return t.set(R,V),{Role:d.role,ContentType:d.contentType,Size:V.size}}),n=e.thumbnail?Up(e.thumbnail.data,e.thumbnail.contentType):null,s=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,Files:i,Thumbnail:e.thumbnail&&n?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:n.size}:void 0});if(!s.ok)return s;let o=s.data.Uploads??[];for(let d=0;d<o.length;d++){let R=o[d];if(!R||R.ServerCopy||!R.Url)continue;let V=t.get(d);if(!V)return r("client",`No bytes for file #${d+1}.`);let se=await this.putBytes(R.Url,V,R.ContentType??V.type);if(!se.ok)return se}let c=s.data.ThumbnailUpload;if(c?.Url&&n){let d=await this.putBytes(c.Url,n,c.ContentType??n.type);if(!d.ok)return d}return this.publishUploaded({ContentID:s.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.baseRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):r("unauthorized","Not logged in.")}async publishUploaded(e){if(!e.ContentID)return r("client","ContentID is required.");let t=this.baseRequest();if(!t)return r("unauthorized","Not logged in.");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 n=await this.ctx.api.workshop.updateContent(i);return n.ok&&this.ctx.emitter.emit("workshop:updated",n.data),n}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let n=this.baseRequest();return n?(n.ContentType=e,n.ContinuationToken=t,n.PageSize=i,this.ctx.api.workshop.getMyContent(n)):r("unauthorized","Not logged in.")}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let n=await this.ctx.api.workshop.acquire(i);return n.ok&&(n.data.Settlement?this.applyDualPartySettlement(n.data.Settlement):this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",n.data)),n}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let n of t.data.Files??[])if(n.Url)try{let s=await this.ctx.fetchImpl(n.Url);if(!s.ok)return r("connection",`Download failed (HTTP ${s.status}).`);i.push({role:n.Role??"main",contentType:n.ContentType??"application/octet-stream",data:await s.arrayBuffer()});}catch(s){return r("connection",`Download failed: ${s instanceof Error?s.message:String(s)}${Op}`)}return G({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.baseRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):r("unauthorized","Not logged in.")}async getMyFavorites(e,t){let i=this.baseRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):r("unauthorized","Not logged in.")}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?G(!0):r("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return r("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}${Op}`)}}contentRequest(e){if(!e)return r("client","ContentID is required.");let t=this.baseRequest();return t?(t.ContentID=e,t):r("unauthorized","Not logged in.")}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);}baseRequest(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}};function Up(a,e){return a instanceof Blob?a:typeof a=="string"?new Blob([new TextEncoder().encode(a)],{type:e}):a instanceof Uint8Array?new Blob([a.slice().buffer],{type:e}):new Blob([a],{type:e})}var JS={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},ZS=zod.z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),YS={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Ep=zod.z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),XS={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Bp=zod.z.enum(["Everyone","Owner","Server"]).catch("Everyone"),ex={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},tx=zod.z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),ix={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},nx=zod.z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),sx={Count:"Count",Sum:"Sum"},rx=zod.z.enum(["Count","Sum"]).catch("Count"),ox={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},ax=zod.z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),lx={Strict:"Strict",Loose:"Loose"},ux=zod.z.enum(["Strict","Loose"]).catch("Strict"),cx=zod.z.object({Kind:nx,Collection:zod.z.string().nullish(),Validate:zod.z.boolean().nullish()}),px=zod.z.object({Type:Ep,ItemType:Ep.nullish(),Ref:cx.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:Bp.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()}),dx=zod.z.object({ID:zod.z.string(),Components:zod.z.array(zod.z.object({Field:zod.z.string(),Descending:zod.z.boolean().optional()})).default([])}),Os=zod.z.object({Mode:tx,Role:zod.z.string().nullish(),MembersField:zod.z.string().nullish()}),hx=zod.z.object({Read:zod.z.array(Os).nullish(),Create:zod.z.array(Os).nullish(),Update:zod.z.array(Os).nullish(),Delete:zod.z.array(Os).nullish()}),ia=zod.z.object({Cost:ae.nullish(),Grant:ae.nullish()}),mx=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()}),fx=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:ZS,Mode:ux.optional(),SchemaVersion:zod.z.number().optional(),Fields:zod.z.record(zod.z.string(),px).nullish(),SortKeys:zod.z.array(dx).nullish(),Access:hx.nullish(),Limits:zod.z.object({MaxItemBytes:zod.z.number().nullish(),MaxItemsPerOwner:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish()}).nullish(),OnOwnerDeleted:ax.optional(),Counters:zod.z.array(zod.z.object({ID:zod.z.string(),Kind:rx,SumField:zod.z.string().nullish(),GroupBy:zod.z.string().nullish(),Visibility:Bp.optional()})).nullish(),Economy:zod.z.object({OnCreate:ia.nullish(),OnUpdate:ia.nullish(),OnDelete:ia.nullish()}).nullish(),WriteGate:$.nullish(),PublicViews:zod.z.array(mx).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()}),qp=zod.z.object({Enabled:zod.z.boolean().optional(),Collections:zod.z.record(zod.z.string(),fx).default({})}),gx=zod.z.object({FileID:zod.z.string(),Url:zod.z.string(),ContentType:zod.z.string().nullish(),Size:zod.z.number()}),Lp=zod.z.object({FileID:zod.z.string(),UploadUrl:zod.z.string(),ContentType:zod.z.string(),MaxBytes:zod.z.number(),ExpiresAt:zod.z.string()}),fi=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(),gx).nullish()}),na=zod.z.object({Item:fi}),Gp=zod.z.object({Items:zod.z.array(fi).default([]),Missing:zod.z.array(zod.z.string()).default([])}),sa=zod.z.object({Items:zod.z.array(fi).default([]),NextCursor:zod.z.string().nullish()}),Np=zod.z.object({Count:zod.z.number(),Capped:zod.z.boolean().optional()}),ra=zod.z.object({Item:fi,AlreadyExists:zod.z.boolean().optional(),Economy:w.nullish()}),Vp=zod.z.object({ItemID:zod.z.string(),Deleted:zod.z.boolean(),Economy:w.nullish()}),Fp=zod.z.object({CounterID:zod.z.string(),Group:zod.z.unknown().optional(),Value:zod.z.number()}),jp=zod.z.object({Results:zod.z.array(zod.z.object({Op:zod.z.string(),Collection:zod.z.string(),ItemID:zod.z.string(),Item:fi.nullish(),Deleted:zod.z.boolean().optional()})).default([])}),Wp=zod.z.object({Roles:zod.z.array(zod.z.string()).default([])}),_p=zod.z.object({Views:zod.z.record(zod.z.string(),zod.z.string()).default({}),ItemUrlTemplate:zod.z.string().nullish()}),Kp=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({})}),Qp=zod.z.object({Page:zod.z.number(),HasMore:zod.z.boolean(),Items:zod.z.array(fi).default([])}),yx={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 Rx=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Jp=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,aa=100,Hp=25,$p=100;function Cx(a,e,t){return {Field:a,Op:e,Value:t}}var Us=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(r("unauthorized","Not logged in."))}get(e,t,i={}){let n=Xe(e)??Oi(t);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.get({...s,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let n=Xe(e);if(n)return Promise.resolve(n);let s=[...new Set(t.filter(o=>Jp.test(o)))];return s.length?s.length>$p?Promise.resolve(r("client",`At most ${$p} ids per call.`)):this.call(o=>this.ctx.api.dataCollections.getMany({...o,Collection:e,ItemIDs:s,Expand:i.expand})):Promise.resolve(r("client","At least one valid item id is required."))}query(e,t={},i={}){let n=Xe(e)??oa(t);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.query({...s,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let n=Math.max(1,i.maxItems??500),s=[],o=t.Cursor;for(;;){let c=await this.query(e,{...t,Cursor:o,Limit:t.Limit??aa},i);if(!c.ok)return c;if(s.push(...c.data.Items),o=c.data.NextCursor??void 0,!o||s.length>=n)return G(s.slice(0,n))}}count(e,t={}){let i=Xe(e)??oa(t);return i?Promise.resolve(i):this.call(n=>this.ctx.api.dataCollections.count({...n,Collection:e,Query:t}))}create(e,t,i={}){let n=Xe(e)??(i.itemID?Oi(i.itemID):null);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.create({...s,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,n={}){let s=Xe(e)??Oi(t);return s?Promise.resolve(s):this.call(o=>this.ctx.api.dataCollections.update({...o,Collection:e,ItemID:t,Update:i,ExpectedVersion:n.expectedVersion}))}set(e,t,i,n={}){return this.update(e,t,{Set:i},n)}increment(e,t,i,n=1){return this.update(e,t,{Inc:{[i]:n}})}delete(e,t,i={}){let n=Xe(e)??Oi(t);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.delete({...s,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(r("client","Operations are empty."));if(e.length>Hp)return Promise.resolve(r("client",`At most ${Hp} operations per batch.`));let t=e.map(i=>Xe(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let n=Xe(e);return n?Promise.resolve(n):this.call(s=>this.ctx.api.dataCollections.getCounter({...s,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,n){let s=Xe(e);return s?Promise.resolve(s):t?n>0?this.call(o=>this.ctx.api.dataCollections.beginFileUpload({...o,Collection:e,Field:t,ContentType:i,FileSize:n})):Promise.resolve(r("client","File size must be positive.")):Promise.resolve(r("client","Field is required."))}async uploadFile(e,t,i,n={}){let s=n.contentType||i.type||"application/octet-stream",o=await this.beginFileUpload(e,t,s,i.size);if(!o.ok)return o;let c=await this.putBytes(o.data.UploadUrl,i,o.data.ContentType||s);return c.ok?o:c}async getPublicViews(e){let t=Xe(e);if(t)return t;let i=this.publicViews.get(e);if(i)return G(i);let n=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return n.ok&&this.publicViews.set(e,n.data),n}async readPublicView(e,t,i={}){let n=await this.getPublicViews(e);if(!n.ok)return n;let s=n.data.Views[t];if(!s)return r("client",`Collection '${e}' has no public view '${t}'.`);let o=await this.fetchJson(s,Kp);if(!o.ok)return o;let c=o.data.Partitions[i.partition??""],d=Math.max(1,i.page??1);if(!c||d>c.Pages)return G({pointer:o.data,page:{Page:d,HasMore:false,Items:[]}});let R=await this.fetchJson(`${o.data.BaseUrl}${c.Segment}/page-${d}.json`,Qp);return R.ok?G({pointer:o.data,page:R.data}):R}getPublic(e,t){let i=Xe(e)??Oi(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=Xe(e)??oa(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(r("unauthorized","Not logged in."))}async putBytes(e,t,i){try{let n=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return n.ok?G(!0):r("connection",`Upload failed (HTTP ${n.status}).`)}catch(n){return r("connection",`Upload failed: ${n instanceof Error?n.message:String(n)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return r("connection","Internet Connection Error")}if(!i.ok)return r("server",`CDN answered ${i.status}.`);let n;try{n=await i.json();}catch{return r("server","CDN answer is not JSON.")}let s=t.safeParse(n);return s.success?G(s.data):r("server","CDN answer has an unexpected shape.")}};function Xe(a){return Rx.test(a??"")?null:r("client",`Collection id '${a}' is invalid (letters, digits, '_', '-', ':').`)}function Oi(a){return Jp.test(a??"")?null:r("client",`Item id '${a}' is invalid.`)}function oa(a){return a.Limit!=null&&(a.Limit<1||a.Limit>aa)?r("client",`Limit must be 1..${aa}.`):(a.Where?.length??0)>8?r("client","At most 8 filters per query."):null}var la={Open:"Open",Declared:"Declared"},Sx=zod.z.object({DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),Blocked:zod.z.boolean().nullish()}).passthrough(),xx=zod.z.object({ParamName:zod.z.string().nullish(),DisplayName:zod.z.string().nullish()}).passthrough(),Zp=zod.z.object({Enabled:zod.z.boolean().nullish(),EventNaming:zod.z.string().nullish(),Events:zod.z.record(zod.z.string(),Sx).nullish(),Dimensions:zod.z.array(xx).nullish(),RetentionDays:zod.z.number().nullish(),AutomaticEvents:zod.z.boolean().nullish()}).passthrough(),Bt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Rt={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Es=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,bx={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},Dx=zod.z.object({Index:zod.z.number().nullish(),Name:zod.z.string().nullish(),Reason:zod.z.string().nullish()}).passthrough(),Yp=zod.z.object({Accepted:zod.z.number().nullish(),Dropped:zod.z.array(Dx).nullish(),Duplicate:zod.z.boolean().nullish(),Disabled:zod.z.boolean().nullish()}).passthrough(),ua={LogEvents:"LogEvents"};function Xp(a,e=0){let t=a??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let c=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:c==="iPad"?"tablet":"phone",deviceModel:c}}let n=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(n){let c=(n[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:n[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:c&&c!=="K"&&c!=="wv"?c:void 0}}let s=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(s)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(s[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 ed(a){let e=typeof navigator>"u"?void 0:navigator,t=Xp(e?.userAgent??"",e?.maxTouchPoints??0),i={};a.appVersion&&(i.AppVersion=a.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let n=a.locale||e?.language;return n&&(i.Language=n),i}var Px=25,vx=3e4,td=1800*1e3,id=500,Ix=5,zx=1e3,Tx=3600*1e3,nd="idos_analytics_queue",ca="idos_analytics_pending",pa="idos_analytics_opt_out",sd="idos_analytics_first_open",rd="idos_analytics_last_activity",od="idos_analytics_last_context",ad="idos_analytics_owner",Bs=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!Es.test(e)?r("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):kx(e)?r("client",`Event name "${e}" uses a reserved prefix (${Rt.reservedPrefixes.join(", ")}).`):this.enqueue(e,t,i,false)}logScreenView(e,t){if(!e)return r("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Bt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return G(null);if(this.config()?.Enabled===false)return this.clear(),G(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return G(null);this.pending={BatchID:q(),Events:this.queue.splice(0,Rt.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return r("unauthorized","Not logged in.");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>=Ix)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(pa);return}this.write(pa,"1"),this.clear();}get isEnabled(){return this.read(pa)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(ad);e&&t&&t!==e&&this.clear(),e&&this.write(ad,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},vx),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(rd)??"0");this.read(sd)||(this.write(sd,new Date().toISOString()),this.enqueue(Bt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(od);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Bt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Bt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(od,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=td)&&this.enqueue(Bt.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>=td&&this.enqueue(Bt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,n){if(!this.isEnabled||this.disabledByServer)return G(null);let s=this.config();if(s?.Enabled===false)return G(null);if(n&&s?.AutomaticEvents===false)return G(null);if(s?.Events?.[e]?.Blocked)return r("client",`Event "${e}" is blocked by the title.`);if(!n&&s?.EventNaming?.toLowerCase()===la.Declared.toLowerCase()&&!s.Events?.[e])return r("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return r("client","value must be a finite number.");let o=Ax(t);if(o.error)return r("client",o.error);this.restore();let c={Name:e,ClientTimeUtc:new Date().toISOString()};return o.params&&(c.Params=o.params),i!==void 0&&(c.Value=i),this.queue.push(c),this.queue.length>id&&this.queue.splice(0,this.queue.length-id),this.touch(),this.persist(),this.started&&this.queue.length>=Px&&this.flush(),G(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},zx));}dropStale(){let e=Date.now()-(Rt.maxEventAgeMs-Tx);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??=ed({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(ca);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(ca,this.pending):this.remove(ca);}touch(){this.write(rd,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 kx(a){let e=a.toLowerCase();return Rt.reservedPrefixes.some(t=>e.startsWith(t))}function Ax(a){if(!a)return {};let e=Object.keys(a);if(e.length===0)return {};if(e.length>Rt.maxParams)return {error:`Too many parameters: ${e.length}, max ${Rt.maxParams}.`};let t={};for(let i of e){if(!Es.test(i))return {error:`Invalid parameter name "${i}".`};let n=a[i];typeof n=="string"?t[i]=n.length>Rt.maxStringValueLength?n.slice(0,Rt.maxStringValueLength):n:typeof n=="number"?Number.isFinite(n)&&(t[i]=n):typeof n=="boolean"&&(t[i]=n);}return {params:t}}var wx="idos_experiments",qs=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 r("unauthorized","Not logged in.");let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let n=this.getParams(e)[t];if(n===void 0)return i;if(typeof i=="number"){let s=Number(n);return n.trim()!==""&&Number.isFinite(s)?s:i}if(typeof i=="boolean"){let s=n.trim().toLowerCase();return s==="true"||s==="1"?true:s==="false"||s==="0"?false:i}return n}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let n of e.Experiments??[])n?.ExperimentID&&t.set(n.ExperimentID,n);let i=[];for(let[n,s]of t){let o=this.views.get(n);(!o||o.VariantID!==s.VariantID||o.Status!==s.Status)&&i.push(s);}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 `${wx}:${this.ctx.settings.titleID}`}};function E(a,e,t,i){let s=`api/v2/${a&&a.length>0?a:"0"}/Client/${e}/${t}`;return i==null?s:`${s}/${i}`}var Ls=class{constructor(e){this.ctx=e;}ctx;logEvents(e){let t=E(this.ctx.settings.titleID,"Analytics",ua.LogEvents,e.UserID??"");return this.ctx.transport.post(t,e,Yp,{ticket:e.ClientSessionTicket,silent:true})}};var Mx=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(),Ox={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Ux=zod.z.object({MetricID:zod.z.string().nullish(),Kind:zod.z.string().nullish(),EventName:zod.z.string().nullish(),IsPrimary:zod.z.boolean().nullish()}).passthrough(),Ex=zod.z.object({ExperimentID:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Description:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Schedule:de.nullish(),Gate:$.nullish(),Variants:zod.z.array(Mx).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(Ux).nullish(),ActivationEvent:zod.z.string().nullish(),RolloutVariantID:zod.z.string().nullish()}).passthrough(),ld=zod.z.object({Experiments:zod.z.record(zod.z.string(),Ex).nullish()}).passthrough(),Bx={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},qx=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(),ud=zod.z.object({Experiments:zod.z.array(qx).nullish(),IsAbTestingAvailable:zod.z.boolean().nullish()}).passthrough(),da={GetExperiments:"GetExperiments"};var Gs=class{constructor(e){this.ctx=e;}ctx;getExperiments(e){let t=E(this.ctx.settings.titleID,"Experiment",da.GetExperiments,e.UserID??"");return this.ctx.transport.post(t,e,ud,{ticket:e.ClientSessionTicket})}};var cd=zod.z.object({PlatformUserID:zod.z.string().nullish(),PlatformAuthToken:zod.z.string().nullish(),PlatformAuthTokenExpiration:u.nullish(),TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,PlayAccess:Et.nullish(),RefreshToken:zod.z.string().nullish(),RefreshTokenExpiration:u.nullish()}),pd=zod.z.object({TitleUserID:zod.z.string(),TitleClientSessionTicket:zod.z.string(),TitleClientSessionTicketExpiration:u,RefreshToken:zod.z.string(),RefreshTokenExpiration:u.nullish(),PlayAccess:Et.nullish()}),Lx=zod.z.object({ReturnMode:zod.z.string().nullish(),UrlScheme:zod.z.string().nullish(),UserCodeSupported:zod.z.boolean().nullish(),PollIntervalSeconds:zod.z.number().nullish()}).passthrough(),dd=zod.z.object({Google:zod.z.object({Enabled:zod.z.boolean().nullish(),WebClientID:zod.z.string().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:Ai.nullish(),WalletLoginNetworks:zod.z.array(zod.z.object({NetworkID:zod.z.string().nullish(),Type:zod.z.string().nullish()}).passthrough()).nullish(),NativeSso:Lx.nullish()}).passthrough(),hd=zod.z.object({Linked:zod.z.boolean().nullish(),Challenge:zod.z.string().nullish(),ExpiresAt:u.nullish(),NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),PlayAccess:Et.nullish()}).passthrough(),md=zod.z.object({NetworkID:zod.z.string().nullish(),Address:zod.z.string().nullish(),CooldownUntil:u.nullish(),PlayAccess:Et.nullish()}).passthrough(),fd=zod.z.object({CodeTtlMinutes:zod.z.number().nullish(),ResendCooldownSeconds:zod.z.number().nullish()}),Me=zod.z.object({IsCompleted:zod.z.boolean().nullish(),ServerTime:u.nullish()}),gd=zod.z.object({Message:zod.z.string(),ExpiresAt:u}),Oe={LoginWithDeviceID:"LoginWithDeviceID",LoginWithTelegram:"LoginWithTelegram",LoginWithEmail:"LoginWithEmail",LoginWithGoogle:"LoginWithGoogle",LoginWithApple:"LoginWithApple",LoginWithSsoCode:"LoginWithSsoCode",RegisterWithEmail:"RegisterWithEmail",ConfirmEmailRegistration:"ConfirmEmailRegistration",ResendVerificationCode:"ResendVerificationCode",RequestWalletChallenge:"RequestWalletChallenge",LoginWithWallet:"LoginWithWallet",GetAuthOptions:"GetAuthOptions",RefreshSession:"RefreshSession",LinkWallet:"LinkWallet",UnlinkWallet:"UnlinkWallet",ForgotPassword:"ForgotPassword",ResetPassword:"ResetPassword"};var Ns=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return E(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,cd,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Oe.RefreshSession),e,pd,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Oe.GetAuthOptions),e,dd,{ticket:null})}linkWallet(e){return this.ctx.transport.post(E(this.ctx.settings.titleID,"Authentication",Oe.LinkWallet,e.UserID??""),e,hd,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(E(this.ctx.settings.titleID,"Authentication",Oe.UnlinkWallet,e.UserID??""),e,md,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Oe.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Oe.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Oe.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Oe.LoginWithGoogle,e)}loginWithApple(e){return this.login(Oe.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Oe.LoginWithSsoCode,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Oe.RegisterWithEmail),e,fd,{ticket:null})}confirmEmailRegistration(e){return this.login(Oe.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Oe.ResendVerificationCode),e,Me,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Oe.RequestWalletChallenge),e,gd,{ticket:null})}loginWithWallet(e){return this.login(Oe.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Oe.ForgotPassword),e,Me,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Oe.ResetPassword),e,Me,{ticket:null})}};var Gx={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},yd=zod.z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Nx=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),IsEnabled:zod.z.boolean().nullish(),Order:zod.z.number().nullish()}).passthrough(),Rd=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),Locales:zod.z.record(zod.z.string(),Nx).nullish(),MissingKeyMode:yd.nullish(),MaxEntriesPerLocale:zod.z.number().nullish(),MaxValueLengthBytes:zod.z.number().nullish()}).passthrough(),Vx=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish()}).passthrough(),Cd=zod.z.object({Locale:zod.z.string().nullish(),Version:zod.z.number().nullish(),Url:zod.z.string().nullish(),Fallback:Vx.nullish()}).passthrough(),Vs={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Fx=zod.z.object({Locale:zod.z.string().nullish(),DisplayName:zod.z.string().nullish(),Order:zod.z.number().nullish(),Version:zod.z.number().nullish()}).passthrough(),Sd=zod.z.object({IsEnabled:zod.z.boolean().nullish(),DefaultLocale:zod.z.string().nullish(),MissingKeyMode:yd.nullish(),ResolvedLocale:zod.z.string().nullish(),Locales:zod.z.array(Fx).nullish()}).passthrough(),xd=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 ha=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:Cd.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(a=>a),bd=zod.z.object({StateEpoch:zod.z.string().nullish(),StateVersions:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough().transform(a=>a),Dd=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(a=>a),Pd=zod.z.object({}).passthrough().transform(a=>a),vd=zod.z.object({}).passthrough().transform(a=>a),Id=zod.z.object({Today:zod.z.number(),Yesterday:zod.z.number(),CurrentWeek:zod.z.number(),CurrentMonth:zod.z.number(),Total:zod.z.number(),TotalSessions:zod.z.number(),FirstActiveAt:u.nullish(),LastActiveAt:u.nullish(),LongestSessionEverSeconds:zod.z.number().nullish(),CurrentWeekActiveHoursMask:zod.z.number().nullish(),CurrentMonthActiveHoursMask:zod.z.number().nullish(),ReactivationCount:zod.z.number().nullish(),History:zod.z.record(zod.z.string(),zod.z.unknown()).nullish()}).passthrough(),zd=zod.z.object({Username:zod.z.string()}),at={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Fs=class{constructor(e){this.ctx=e;}ctx;endpoint(e,t){return E(this.ctx.settings.titleID,"User",e,t??"")}getClientState(e){return this.ctx.transport.post(this.endpoint(at.GetClientState,e.UserID),e,ha,{ticket:e.ClientSessionTicket})}getClientStateExcept(e){return this.ctx.transport.post(this.endpoint(at.GetClientStateExcept,e.UserID),e,ha,{ticket:e.ClientSessionTicket})}getStateVersions(e){return this.ctx.transport.post(this.endpoint(at.GetStateVersions,e.UserID),e,bd,{ticket:e.ClientSessionTicket})}getUserState(e){return this.ctx.transport.post(this.endpoint(at.GetUserState,e.UserID),e,Dd,{ticket:e.ClientSessionTicket})}getInventory(e){return this.ctx.transport.post(this.endpoint(at.GetInventory,e.UserID),e,Pd,{ticket:e.ClientSessionTicket})}getEventTokens(e){return this.ctx.transport.post(this.endpoint(at.GetEventTokens,e.UserID),e,vd,{ticket:e.ClientSessionTicket})}getUsageTime(e){return this.ctx.transport.post(this.endpoint(at.GetUsageTime,e.UserID),e,Id,{ticket:e.ClientSessionTicket})}addUsageTime(e){return this.ctx.transport.post(this.endpoint(at.AddUsageTime,e.UserID),e,Me,{ticket:e.ClientSessionTicket,silent:true})}deleteUserAccount(e){return this.ctx.transport.post(this.endpoint(at.DeleteUserAccount,e.UserID),e,Me,{ticket:e.ClientSessionTicket})}changeUsername(e){return this.ctx.transport.post(this.endpoint(at.ChangeUsername,e.UserID),e,zd,{ticket:e.ClientSessionTicket})}};var js=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Currency",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}convert(e){return this.send(xs.Convert,e,Qc)}cryptoConvert(e){return this.send(xs.CryptoConvert,e,Hc)}};var jx=zod.z.object({ItemInstanceID:zod.z.string(),Units:zod.z.number(),Level:zod.z.number()}),ma=zod.z.object({ServerTimeUtc:u,ItemInstanceID:zod.z.string(),ItemID:zod.z.string(),CatalogID:zod.z.string().nullish(),Level:zod.z.number(),Resources:w.nullish(),FodderConsumed:zod.z.array(jx).nullish()}),Td=zod.z.array(be(ma)),Ws={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},Wx={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},_x=zod.z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),Kx={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},Qx=zod.z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),Hx=zod.z.object({ContractAddress:zod.z.string().nullish(),TokenID:zod.z.string().nullish(),TokenStandard:zod.z.string().nullish(),MaxLevel:zod.z.number().nullish()}).passthrough(),$x=zod.z.object({Networks:zod.z.record(zod.z.string(),Hx).nullish(),MetadataUrl:zod.z.string().nullish()}).passthrough(),Jx=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(),Zx=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(),Yx=zod.z.object({ValuationMode:_x.nullish(),WeightCurve:Le.nullish(),Selection:Qx.nullish()}).passthrough(),Xx=zod.z.object({MaxLevel:zod.z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:Le.nullish(),FlatBonusCurve:Le.nullish(),PercentBonusCurve:Le.nullish(),PowerCurve:Le.nullish(),Fodder:Yx.nullish()}).passthrough(),eb=zod.z.object({RarityID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),AuthorID:zod.z.string().nullish()}).passthrough(),tb=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:$x.nullish(),Stats:Jx.nullish(),Equipment:Zx.nullish(),Upgrade:Xx.nullish(),Metadata:eb.nullish(),ExpirationDurationSeconds:zod.z.number().nullish(),MaxSupply:zod.z.number().nullish()}).passthrough(),ib=zod.z.object({Items:zod.z.record(zod.z.string(),tb).nullish()}).passthrough(),_s=zod.z.object({Catalogs:zod.z.record(zod.z.string(),ib).nullish()}).passthrough();var Ks=class{constructor(e){this.ctx=e;}ctx;upgradeLevel(e){let t=E(this.ctx.settings.titleID,"Item",Ws.UpgradeLevel,e.UserID??"");return this.ctx.transport.post(t,e,ma,{ticket:e.ClientSessionTicket})}upgradeLevelsBatch(e){let t=E(this.ctx.settings.titleID,"Item",Ws.UpgradeLevelsBatch,e.UserID??"");return this.ctx.transport.post(t,e,Td,{ticket:e.ClientSessionTicket})}};var Qs=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Store",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}purchase(e){return this.send(Vt.Purchase,e,oo)}purchaseBatch(e){return this.send(Vt.PurchaseBatch,e,El)}getDefinitions(e){return this.send(Vt.GetDefinitions,e,fn)}getUserState(e){return this.send(Vt.GetUserState,e,Bl)}getStorefront(e){return this.send(Vt.GetStorefront,e,gn)}};var nb={Apple:"Apple",Google:"Google"},Hs=zod.z.object({PremiumID:zod.z.string().nullish(),PurchaseDate:zod.z.string().nullish(),ExpirationDate:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),IsAutoRenewEnabled:zod.z.boolean().nullish()}).passthrough(),$s=zod.z.object({Subscriptions:zod.z.record(zod.z.string(),Hs).nullish(),ActivatedTrialIDs:zod.z.array(zod.z.string()).nullish(),MaxActiveTier:zod.z.number().nullish()}).passthrough().transform(a=>a),sb=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:oe.nullish(),Benefits:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),fa=zod.z.object({Definitions:zod.z.record(zod.z.string(),sb).nullish()}).passthrough(),kd=zod.z.object({Premium:fa.nullish()}),Ad=zod.z.object({ServerTimeUtc:u.nullish(),Premium:$s.nullish()}),Js=zod.z.object({ServerTimeUtc:u.nullish(),Premium:$s.nullish(),Subscription:Hs.nullish(),Resources:w.nullish()}),Wt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var rb={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},ob=zod.z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),wd=zod.z.object({StartUtc:u.nullish(),EndUtc:u.nullish(),Gate:$.nullish(),Limits:fe.nullish()}).passthrough(),ga=zod.z.object({ResourceAction:zod.z.string().nullish(),RevokeEntitlement:zod.z.boolean().nullish(),BlockFuturePurchases:zod.z.boolean().nullish()}).passthrough(),ab=zod.z.object({PremiumID:zod.z.string().nullish(),RenewalRewards:Q.nullish(),FallbackDurationDays:zod.z.number().nullish(),RevokeOnRefund:zod.z.boolean().nullish()}).passthrough(),lb=zod.z.object({Rewards:_.nullish(),Rules:_.nullish(),Refund:_.nullish()}).passthrough(),ub=zod.z.object({ProductID:zod.z.string().nullish(),Name:zod.z.string().nullish(),Type:ob.nullish(),Enabled:zod.z.boolean().nullish(),StoreProductIDs:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Rewards:Q.nullish(),PriceUsdCents:zod.z.number().nullish(),TelegramStarsPrice:zod.z.number().nullish(),Rules:wd.nullish(),Refund:ga.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish(),Subscription:ab.nullish(),Presets:lb.nullish()}).passthrough(),cb=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(),pb=zod.z.object({Rewards:Q.nullish()}).passthrough(),db=zod.z.object({Rules:wd.nullish()}).passthrough(),hb=zod.z.object({Refund:ga.nullish()}).passthrough(),mb=zod.z.object({Rewards:zod.z.record(zod.z.string(),pb).nullish(),Rules:zod.z.record(zod.z.string(),db).nullish(),Refund:zod.z.record(zod.z.string(),hb).nullish()}).passthrough(),fb=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(),gb=zod.z.object({Enabled:zod.z.boolean().nullish(),Products:zod.z.record(zod.z.string(),ub).nullish(),Stores:zod.z.record(zod.z.string(),cb).nullish(),Presets:mb.nullish(),Validation:fb.nullish(),Refund:ga.nullish()}).passthrough(),Md=zod.z.object({ProductID:zod.z.string().nullish(),TotalPurchases:zod.z.number().nullish(),DailyPurchases:zod.z.number().nullish(),DailyResetUtc:u.nullish(),LastPurchasedAt:u.nullish(),Owned:zod.z.boolean().nullish(),Refunded:zod.z.boolean().nullish(),PurchaseBlocked:zod.z.boolean().nullish(),Store:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish()}).passthrough(),Od=zod.z.object({ProductID:zod.z.string().nullish(),PremiumID:zod.z.string().nullish(),Store:zod.z.string().nullish(),OriginalTransactionID:zod.z.string().nullish(),LastTransactionID:zod.z.string().nullish(),ExpiresAt:u.nullish(),AutoRenew:zod.z.boolean().nullish(),Status:zod.z.string().nullish(),RenewalCount:zod.z.number().nullish(),LastStoreCheckAt:u.nullish(),LastStoreCheckError:zod.z.string().nullish(),UpdatedAt:u.nullish()}).passthrough(),yb=zod.z.object({Products:zod.z.record(zod.z.string(),Md).nullish(),LifetimeSpendUsdCents:zod.z.number().nullish(),Subscriptions:zod.z.record(zod.z.string(),Od).nullish(),LastRefundCheckAt:u.nullish(),TotalPurchases:zod.z.number().nullish(),FirstPurchaseAt:u.nullish(),LastPurchaseAt:u.nullish()}).passthrough(),Rb=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(),Ud=zod.z.object({ServerTimeUtc:u,Purchase:gb.nullish(),Availability:zod.z.array(Rb).nullish()}),Ed=zod.z.object({ServerTimeUtc:u,Purchase:yb.nullish()}),Cb={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},Sb=zod.z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),ya=zod.z.object({ServerTimeUtc:u,Store:Ni.nullish(),ProductID:zod.z.string().nullish(),TransactionID:zod.z.string().nullish(),Status:Sb.nullish(),Granted:zod.z.boolean().nullish(),Quantity:zod.z.number().nullish(),Resources:w.nullish(),Inventory:K.nullish(),ProductState:Md.nullish(),Premium:$s.nullish(),Subscription:Hs.nullish(),SubscriptionMirror:Od.nullish()}).passthrough(),Bd=zod.z.object({ServerTimeUtc:u,ProductID:zod.z.string().nullish(),Stars:zod.z.number().nullish(),InvoiceLink:zod.z.string(),ExpiresAt:u.nullish()}).passthrough(),qd=mt(ya),_t={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var Zs=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Purchase",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(_t.GetDefinitions,e,Ud)}getUserState(e){return this.send(_t.GetUserState,e,Ed)}validatePurchase(e){return this.send(_t.ValidatePurchase,e,ya)}validatePurchasesBatch(e){return this.send(_t.ValidatePurchasesBatch,e,qd)}createTelegramInvoice(e){return this.send(_t.CreateTelegramInvoice,e,Bd)}};var xb=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Ld=zod.z.object({Reward:Q.nullish(),Weight:zod.z.number().nullish(),AmountRange:xb.nullish()}).passthrough(),gi=zod.z.object({SlotID:zod.z.string().nullish(),MinRolls:zod.z.number().nullish(),MaxRolls:zod.z.number().nullish(),Pool:zod.z.array(Ld).nullish()}).passthrough(),yi=zod.z.object({RuleID:zod.z.string().nullish(),Threshold:zod.z.number().nullish(),Pool:zod.z.array(Ld).nullish()}).passthrough(),bb=zod.z.object({RewardSlots:zod.z.array(gi).nullish()}).passthrough(),Db=zod.z.object({PityRules:zod.z.array(yi).nullish()}).passthrough(),Ys=zod.z.object({SlotPresets:zod.z.record(zod.z.string(),bb).nullish(),PityPresets:zod.z.record(zod.z.string(),Db).nullish()}).passthrough();var Pb=zod.z.object({RuleID:zod.z.string(),BoxIndex:zod.z.number().nullish()}),Gd=zod.z.object({ServerTimeUtc:u,LootboxID:zod.z.string(),OpenedCount:zod.z.number().nullish(),SelectedOptionID:zod.z.string().nullish(),Resources:w.nullish(),Inventory:K.nullish(),Results:zod.z.array(w).nullish(),TriggeredPity:zod.z.array(Pb).nullish()}),vb=zod.z.object({RewardSlots:_.nullish(),PityRules:_.nullish()}).passthrough(),Ib=zod.z.object({CatalogID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),MaxDrops:j.nullish()}).passthrough(),zb=zod.z.object({LootboxID:zod.z.string(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),PriceOptions:oe.nullish(),RewardSlots:zod.z.array(gi).nullish(),PityRules:zod.z.array(yi).nullish(),Presets:vb.nullish(),RewardMultiplier:Fi.nullish(),SupplyLimits:zod.z.array(Ib).nullish(),MaxOpenCount:zod.z.number().nullish()}).passthrough(),Tb=zod.z.object({MaxOpenCount:zod.z.number().nullish()}).passthrough(),Ra=zod.z.object({Definitions:zod.z.record(zod.z.string(),zb).nullish(),RewardPools:Ys.nullish(),Settings:Tb.nullish()}).passthrough(),Nd=zod.z.object({LootboxDefinitions:Ra.nullish()}),Xs={GetDefinitions:"GetDefinitions",Open:"Open"};var er=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Lootbox",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Xs.GetDefinitions,e,Nd)}open(e){return this.send(Xs.Open,e,Gd)}};var kb=zod.z.object({}).passthrough().transform(a=>a),Ab=zod.z.object({}).passthrough().transform(a=>a),wb=zod.z.object({}).passthrough().transform(a=>a),Mb=zod.z.object({}).passthrough().transform(a=>a),Ob=zod.z.object({}).passthrough().transform(a=>a),Vd=zod.z.object({ServerTimeUtc:u,CalendarID:zod.z.string(),DayNumber:zod.z.number().nullish(),DailyState:kb,Resources:w.nullish(),Inventory:K.nullish()}),Fd=zod.z.object({ServerTimeUtc:u,AccrualID:zod.z.string(),AccruedSeconds:j.nullish(),AppliedRatePerSecond:zod.z.number().nullish(),IdleState:Ab,Resources:w.nullish(),Inventory:K.nullish()}),jd=zod.z.object({ServerTimeUtc:u,ComebackID:zod.z.string(),ClaimedTierIndex:zod.z.number().nullish(),ComebackState:wb,Resources:w.nullish(),Inventory:K.nullish()}),Wd=zod.z.object({ServerTimeUtc:u,ClaimID:zod.z.string(),ClaimState:Mb,Resources:w.nullish(),Inventory:K.nullish()}),_d=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()}),Ub=zod.z.object({RewardMode:zod.z.string().nullish(),RewardStackLowerTiers:zod.z.boolean().nullish()}).passthrough(),Eb=zod.z.object({DayNumber:zod.z.number().nullish(),Rewards:Q.nullish(),IsMilestone:zod.z.boolean().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),Ui=zod.z.object({Gate:$.nullish(),Limits:fe.nullish()}).passthrough(),Ca=zod.z.object({Availability:_.nullish()}).passthrough(),Bb=zod.z.object({Availability:zod.z.record(zod.z.string(),Ui).nullish()}).passthrough(),qb=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(Eb).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:Ui.nullish(),Presets:Ca.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),Lb=zod.z.object({MinPremiumTier:zod.z.number().nullish(),RequiredPremiumID:zod.z.string().nullish(),Multiplier:zod.z.number().nullish()}).passthrough(),Gb=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(Lb).nullish()}).passthrough(),Nb=zod.z.object({MinCharacterLevel:zod.z.number().nullish(),RequirementsCharacterID:zod.z.string().nullish(),Availability:Ui.nullish(),RequiredItemIDs:zod.z.array(zod.z.string()).nullish(),RequiredEquippedItemIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Vb=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:Gb.nullish(),Rewards:Q.nullish(),MaxAccumulationSeconds:zod.z.number().nullish(),MinClaimSeconds:zod.z.number().nullish(),Requirements:Nb.nullish(),FirstClaimMode:zod.z.string().nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),Fb=zod.z.object({MinAbsenceSeconds:zod.z.number().nullish(),Rewards:Q.nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),jb=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(Fb).nullish(),ClaimCooldownSeconds:zod.z.number().nullish(),ClaimWindowSeconds:zod.z.number().nullish(),TrackPresenceOnRead:zod.z.boolean().nullish(),Availability:Ui.nullish(),Presets:Ca.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),Wb=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(),_b=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:Q.nullish(),PremiumLimitOverrides:zod.z.array(Wb).nullish(),Availability:Ui.nullish(),Presets:Ca.nullish(),AvailableFromUtc:zod.z.string().nullish(),AvailableUntilUtc:zod.z.string().nullish()}).passthrough(),Sa=zod.z.object({TierRewards:Ub.nullish(),MilestoneRewardMultiplier:Fi.nullish(),DailyCalendars:zod.z.record(zod.z.string(),qb).nullish(),IdleAccruals:zod.z.record(zod.z.string(),Vb).nullish(),Comebacks:zod.z.record(zod.z.string(),jb).nullish(),Claims:zod.z.record(zod.z.string(),_b).nullish(),Presets:Bb.nullish()}).passthrough(),Kd=zod.z.object({RewardDefinitions:Sa.nullish()}),Qd=zod.z.object({Rewards:Ob.nullish()}),It={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var tr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Reward",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getRewardDefinitions(e){return this.send(It.GetRewardDefinitions,e,Kd)}getUserRewardsState(e){return this.send(It.GetUserRewardsState,e,Qd)}getMilestoneRewardMultiplier(e){return this.send(It.GetMilestoneRewardMultiplier,e,_d)}claimDailyReward(e){return this.send(It.ClaimDailyReward,e,Vd)}collectIdleAccrual(e){return this.send(It.CollectIdleAccrual,e,Fd)}claimComebackReward(e){return this.send(It.ClaimComebackReward,e,jd)}claimReward(e){return this.send(It.ClaimReward,e,Wd)}};var ir=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Tutorial",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getTutorialDefinitions(e){return this.send(nt.GetTutorialDefinitions,e,Rl)}getUserTutorialState(e){return this.send(nt.GetUserTutorialState,e,_i)}startFlow(e){return this.send(nt.StartFlow,e,kt)}reportStepShown(e){return this.send(nt.ReportStepShown,e,kt)}completeStep(e){return this.send(nt.CompleteStep,e,kt)}completeStepsBatch(e){return this.send(nt.CompleteStepsBatch,e,xl)}skipStep(e){return this.send(nt.SkipStep,e,kt)}skipFlow(e){return this.send(nt.SkipFlow,e,kt)}claimFlowReward(e){return this.send(nt.ClaimFlowReward,e,Sl)}resetFlow(e){return this.send(nt.ResetFlow,e,kt)}};var Kb={Open:"Open",Application:"Application"},Qb=zod.z.enum(["Open","Application"]).catch("Open"),Hb={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Hd=zod.z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),$b={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},xa=zod.z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),Jb={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};zod.z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var Kt={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},Zb=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(),$d=zod.z.object({IsEnabled:zod.z.boolean().nullish(),CreatorPortalUrl:zod.z.string().nullish(),ParticipationMode:Qb.nullish(),IsCreator:zod.z.boolean().nullish(),CreatorStatus:Hd.nullish(),VerificationCode:zod.z.string().nullish(),TeamID:zod.z.string().nullish(),Campaigns:zod.z.array(Zb).nullish()}).passthrough(),Yb=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(),Xb=zod.z.object({CampaignID:zod.z.string().nullish(),CurrencyKind:xa.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(),Yb).nullish(),ComputedAt:zod.z.string().nullish()}).passthrough(),eD=zod.z.object({PayoutID:zod.z.string().nullish(),CampaignID:zod.z.string().nullish(),Amount:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:xa.nullish(),NetworkID:zod.z.string().nullish(),PaidAt:zod.z.string().nullish()}).passthrough(),Jd=zod.z.object({ServerTimeUtc:zod.z.string().nullish(),HoldDays:zod.z.number().nullish(),Campaigns:zod.z.array(Xb).nullish(),Payouts:zod.z.array(eD).nullish()}).passthrough(),Zd=zod.z.object({CampaignID:zod.z.string().nullish(),PayoutID:zod.z.string().nullish(),Claimed:zod.z.number().nullish(),CurrencyID:zod.z.string().nullish(),CurrencyKind:xa.nullish(),NetworkID:zod.z.string().nullish(),RemainingFraction:zod.z.number().nullish(),IdempotentReplay:zod.z.boolean().nullish(),Message:zod.z.string().nullish()}).passthrough(),tD=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.string().nullish()}).passthrough(),iD=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(tD).nullish()}).passthrough(),nD=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(),Yd=zod.z.object({Passed:zod.z.boolean().nullish(),Approved:zod.z.boolean().nullish(),Status:Hd.nullish(),WalletMissing:zod.z.boolean().nullish(),WalletConnectAllowed:zod.z.boolean().nullish(),Conditions:zod.z.array(nD).nullish()}).passthrough(),sD=zod.z.object({To:zod.z.string().nullish(),Amount:zod.z.union([zod.z.string(),zod.z.number()]).nullish()}).passthrough(),rD=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(sD).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(),Xd=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:iD.nullish(),SolanaSignature:rD.nullish(),StateDelta:mi.nullish()}).passthrough();var nr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"CommunityMarketing",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getCommunityMarketingState(e){return this.send(Kt.GetCommunityMarketingState,e,$d)}getEarnings(e){return this.send(Kt.GetEarnings,e,Jd)}claim(e){return this.send(Kt.Claim,e,Zd)}checkJoinEligibility(e){return this.send(Kt.CheckJoinEligibility,e,Yd)}withdrawCryptoReward(e){return this.send(Kt.WithdrawCryptoReward,e,Xd)}};var sr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Chat",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getChatDefinitions(e){return this.send(We.GetChatDefinitions,e,Zl)}getChannels(e){return this.send(We.GetChannels,e,In)}poll(e){return this.send(We.Poll,e,Yl)}getHistory(e){return this.send(We.GetHistory,e,Xl)}getConversations(e){return this.send(We.GetConversations,e,iu)}sendMessage(e){return this.send(We.SendMessage,e,eu)}openDirectChannel(e){return this.send(We.OpenDirectChannel,e,tu)}markRead(e){return this.send(We.MarkRead,e,di)}joinChannel(e){return this.send(We.JoinChannel,e,di)}leaveChannel(e){return this.send(We.LeaveChannel,e,di)}reportMessage(e){return this.send(We.ReportMessage,e,nu)}ignoreUser(e){return this.send(We.IgnoreUser,e,di)}unignoreUser(e){return this.send(We.UnignoreUser,e,di)}};var rr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Push",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getPushConfig(e){return this.send(hi.GetPushConfig,e,ou)}subscribePush(e){return this.send(hi.SubscribePush,e,co)}unsubscribePush(e){return this.send(hi.UnsubscribePush,e,Me)}getPushSubscriptions(e){return this.send(hi.GetPushSubscriptions,e,au)}};var or=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Localization",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket,throttleKey:t.Locale?`${n}:${t.Locale}`:n})}getLocalizationManifest(e){return this.send(Vs.GetLocalizationManifest,e,Sd)}getLocalizationTable(e){return this.send(Vs.GetLocalizationTable,e,xd)}};var ar=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Quest",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getQuestDefinitions(e){return this.send(ct.GetQuestDefinitions,e,Wi)}getUserQuestState(e){return this.send(ct.GetUserQuestState,e,ol)}refreshQuestCycles(e){return this.send(ct.RefreshQuestCycles,e,Me)}claimQuestReward(e){return this.send(ct.ClaimQuestReward,e,$r)}claimQuestRewardsBatch(e){return this.send(ct.ClaimQuestRewardsBatch,e,ul)}claimMilestoneReward(e){return this.send(ct.ClaimMilestoneReward,e,Jr)}claimMilestoneRewardsBatch(e){return this.send(ct.ClaimMilestoneRewardsBatch,e,cl)}claimGroupCompletionReward(e){return this.send(ct.ClaimGroupCompletionReward,e,al)}addQuestProgress(e){return this.send(ct.AddQuestProgress,e,ll)}};var lr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"TimedEvent",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getActiveEvents(e){return this.send(rt.GetActiveEvents,e,On)}getDefinitions(e){return this.send(rt.GetDefinitions,e,Mn)}getUserLteState(e){return this.send(rt.GetUserLteState,e,du)}grantTokens(e){return this.send(rt.GrantTokens,e,w)}spendTokens(e){return this.send(rt.SpendTokens,e,mo)}claimMilestone(e){return this.send(rt.ClaimMilestone,e,fo)}claimMilestonesBatch(e){return this.send(rt.ClaimMilestonesBatch,e,go)}claimAllMilestones(e){return this.send(rt.ClaimAllMilestones,e,go)}spendTokensBatch(e){return this.send(rt.SpendTokensBatch,e,hu)}grantTokensBatch(e){return this.send(rt.GrantTokensBatch,e,mu)}};var ur=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Leaderboard",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Ge.GetDefinitions,e,Nn)}getLeaderboard(e){return this.send(Ge.GetLeaderboard,e,vi)}getMyProgress(e){return this.send(Ge.GetMyProgress,e,En)}submitScore(e){return this.send(Ge.SubmitScore,e,Bn)}submitScoreFromSource(e){return this.send(Ge.SubmitScoreFromSource,e,Bn)}claimCycleReward(e){return this.send(Ge.ClaimCycleReward,e,qn)}claimMilestone(e){return this.send(Ge.ClaimMilestone,e,Ln)}getFriendsLeaderboard(e){return this.send(Ge.GetFriendsLeaderboard,e,vi)}getLeaderboardsBatch(e){return this.send(Ge.GetLeaderboardsBatch,e,yu)}getProgressBatch(e){return this.send(Ge.GetProgressBatch,e,Gn)}claimCycleRewardsBatch(e){return this.send(Ge.ClaimCycleRewardsBatch,e,Ru)}claimMilestonesBatch(e){return this.send(Ge.ClaimMilestonesBatch,e,Cu)}submitScoresBatch(e){return this.send(Ge.SubmitScoresBatch,e,Su)}claimAllRewardsBatch(e){return this.send(Ge.ClaimAllRewardsBatch,e,xu)}getOverviewBatch(e){return this.send(Ge.GetOverviewBatch,e,bu)}};var cr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Season",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(wt.GetDefinitions,e,jn)}getActiveSeason(e){return this.send(wt.GetActiveSeason,e,Fn)}getUserState(e){return this.send(wt.GetUserState,e,yo)}grantStatusTokens(e){return this.send(wt.GrantStatusTokens,e,Iu)}claimTierReward(e){return this.send(wt.ClaimTierReward,e,Ro)}claimTierRewardsBatch(e){return this.send(wt.ClaimTierRewardsBatch,e,zu)}};var pr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Premium",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Wt.GetDefinitions,e,kd)}getUserState(e){return this.send(Wt.GetUserState,e,Ad)}activateTrial(e){return this.send(Wt.ActivateTrial,e,Js)}purchaseItemOrCurrency(e){return this.send(Wt.PurchaseWithResources,e,Js)}purchaseRealMoney(e){return this.send(Wt.PurchaseRealMoney,e,Js)}};var dr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Character",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getCharacterDefinitions(e){return this.send(Ne.GetCharacterDefinitions,e,Qn)}getUserCharacters(e){return this.send(Ne.GetUserCharacters,e,Ou)}unlockCharacter(e){return this.send(Ne.UnlockCharacter,e,bo)}upgradeStatLevel(e){return this.send(Ne.UpgradeStatLevel,e,So)}upgradeCharacterLevel(e){return this.send(Ne.UpgradeCharacterLevel,e,xo)}equipItems(e){return this.send(Ne.EquipItems,e,Uu)}unequipItems(e){return this.send(Ne.UnequipItems,e,Eu)}unequipAllCharacters(e){return this.send(Ne.UnequipAllCharacters,e,Bu)}unlockCharactersBatch(e){return this.send(Ne.UnlockCharactersBatch,e,Vu)}upgradeCharacterLevelsBatch(e){return this.send(Ne.UpgradeCharacterLevelsBatch,e,Fu)}upgradeStatLevelsBatch(e){return this.send(Ne.UpgradeStatLevelsBatch,e,ju)}unlockSkin(e){return this.send(Ne.UnlockSkin,e,qu)}equipSkin(e){return this.send(Ne.EquipSkin,e,Lu)}unequipSkin(e){return this.send(Ne.UnequipSkin,e,Gu)}getCharacterSkins(e){return this.send(Ne.GetCharacterSkins,e,Nu)}};var hr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Match",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}createMatch(e){return this.send(yt.CreateMatch,e,Rp)}updateMatch(e){return this.send(yt.UpdateMatch,e,Cp)}cancelMatch(e){return this.send(yt.CancelMatch,e,Sp)}instantBattle(e){return this.send(yt.InstantBattle,e,xp)}saveStrategy(e){return this.send(yt.SaveStrategy,e,Me)}getMyMatches(e){return this.send(yt.GetMyMatches,e,Ho)}getAvailableMatches(e){return this.send(yt.GetAvailableMatches,e,Ho)}getDefinitions(e){return this.send(yt.GetDefinitions,e,vp)}};var oD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},eh=zod.z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),aD={None:"None",Min:"Min",Average:"Average",Max:"Max"},lD=zod.z.enum(["None","Min","Average","Max"]).catch("None"),uD={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},cD=zod.z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),pD={Clamp:"Clamp",Reject:"Reject"},dD=zod.z.enum(["Clamp","Reject"]).catch("Clamp"),hD=zod.z.object({ItemInstanceID:zod.z.string().nullish(),ItemID:zod.z.string().nullish(),Level:zod.z.number().nullish(),Units:zod.z.number().nullish()}),mD=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:Kr.nullish(),OutputLevel:zod.z.number().nullish(),BurnedInstances:zod.z.array(hD).nullish()}),th=zod.z.object({ServerTimeUtc:u,Type:eh.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:w.nullish(),Inventory:K.nullish(),Results:zod.z.array(mD).nullish()}),fD=zod.z.object({CraftID:zod.z.string().nullish(),Type:eh.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:oe.nullish(),OutputLevelMode:lD.nullish(),InputSelection:cD.nullish(),OutputLevelOverflow:dD.nullish()}).passthrough(),ba=zod.z.object({Definitions:zod.z.record(zod.z.string(),fD).nullish()}).passthrough(),ih=zod.z.object({ServerTimeUtc:u.nullish(),CraftDefinitions:ba.nullish()}),mr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var fr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Craft",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(mr.GetDefinitions,e,ih)}craft(e){return this.send(mr.Craft,e,th)}};var gD=2e5,gr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i,n={}){let s=E(this.ctx.settings.titleID,"AI",e,t.UserID??"");return this.ctx.transport.post(s,t,i,{...n,ticket:t.ClientSessionTicket})}generate(e,t){return this.send(e,t,Zn,{timeoutMs:gD,autoRetry:false})}readGeneration(e,t){return this.send(e,t,Zn,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(qe.GetDefinitions,e,Yu)}generateText(e){return this.generate(qe.GenerateText,e)}getText(e){return this.readGeneration(qe.GetText,e)}generateImage(e){return this.generate(qe.GenerateImage,e)}editImage(e){return this.generate(qe.EditImage,e)}getImage(e){return this.readGeneration(qe.GetImage,e)}generateVideo(e){return this.generate(qe.GenerateVideo,e)}getVideo(e){return this.readGeneration(qe.GetVideo,e)}generateAudio(e){return this.generate(qe.GenerateAudio,e)}getAudio(e){return this.readGeneration(qe.GetAudio,e)}generateMusic(e){return this.generate(qe.GenerateMusic,e)}getMusic(e){return this.readGeneration(qe.GetMusic,e)}generateThreeD(e){return this.generate(qe.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(qe.GetThreeD,e)}listGenerations(e){return this.send(qe.ListGenerations,e,Zu)}getGeneration(e){return this.readGeneration(qe.GetGeneration,e)}};var yD={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},RD=zod.z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),nh=zod.z.object({}).passthrough().transform(a=>a),Ri=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()}),sh=zod.z.object({GrantedCollectibles:zod.z.array(Ri).nullish(),DuplicateCollectibles:zod.z.array(Ri).nullish(),CollectionCurrencyEarned:j.nullish()}),rh=zod.z.object({OpenedCount:zod.z.number().nullish(),Packs:zod.z.array(sh).nullish(),GrantedCollectibles:zod.z.array(Ri).nullish(),DuplicateCollectibles:zod.z.array(Ri).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),NewlyCompletedSetIDs:zod.z.array(zod.z.string()).nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:w.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),oh=zod.z.object({OpenedCount:zod.z.number().nullish(),Chests:zod.z.array(sh).nullish(),GrantedCollectibles:zod.z.array(Ri).nullish(),DuplicateCollectibles:zod.z.array(Ri).nullish(),CollectionCurrencyEarned:j.nullish(),NewCollectionCurrencyBalance:j.nullish(),Resources:w.nullish(),Inventory:K.nullish(),TriggeredPity:zod.z.array(zod.z.unknown()).nullish()}),ah=zod.z.object({GrantedCollectibleID:zod.z.string().nullish(),NewlyCompletedSetID:zod.z.string().nullish(),CollectionJustCompleted:zod.z.boolean().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),Da=zod.z.object({SetID:zod.z.string(),Resources:w.nullish(),Inventory:K.nullish()}),lh=zod.z.array(be(Da)),uh=zod.z.object({Resources:w.nullish(),Inventory:K.nullish()}),CD=zod.z.object({OfferID:zod.z.string(),TitleID:zod.z.string().nullish(),CollectionID:zod.z.string().nullish(),SenderUserID:zod.z.string().nullish(),SenderPublicData:Ae.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:RD.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RespondedAtUtc:u.nullish(),DeclineReason:zod.z.string().nullish(),IsSpecialTradeEvent:zod.z.boolean().nullish(),SpecialTradeEventID:zod.z.string().nullish()}).passthrough(),ch=zod.z.object({OfferID:zod.z.string(),ExpiresAtUtc:u.nullish(),Resources:w.nullish()}),ph=zod.z.object({OfferID:zod.z.string(),Resources:w.nullish()}),dh=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()}),hh=zod.z.object({OfferID:zod.z.string(),Resources:w.nullish()}),Pa=zod.z.object({Offers:zod.z.array(CD).nullish()}),SD=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(),xD=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(SD).nullish(),SetCompletionReward:Q.nullish()}).passthrough(),bD=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(xD).nullish(),GrandPrize:Q.nullish()}).passthrough(),mh=zod.z.object({BonusRewardSlots:_.nullish(),PityRules:_.nullish()}).passthrough(),DD=zod.z.object({PackTypeID:zod.z.string().nullish(),PriceOptions:oe.nullish(),BonusRewardSlots:zod.z.array(gi).nullish(),PityRules:zod.z.array(yi).nullish(),Presets:mh.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(),PD=zod.z.object({Rarity:zod.z.number().nullish(),CollectionCurrencyGranted:zod.z.number().nullish()}).passthrough(),vD=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(gi).nullish(),PityRules:zod.z.array(yi).nullish(),Presets:mh.nullish(),Tier:zod.z.number().nullish()}).passthrough(),ID=zod.z.object({SpecialTradeEventID:zod.z.string().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),AllowedSpecialCollectibleIDs:zod.z.array(zod.z.string()).nullish(),SpecialTradeEventDailyTradeLimit:zod.z.number().nullish()}).passthrough(),zD=zod.z.object({MaxPackOpenCount:zod.z.number().nullish(),MaxChestOpenCount:zod.z.number().nullish()}).passthrough(),yr=zod.z.object({Collections:zod.z.record(zod.z.string(),bD).nullish(),PackTypes:zod.z.record(zod.z.string(),DD).nullish(),CollectionChests:zod.z.array(vD).nullish(),DuplicateConversions:zod.z.array(PD).nullish(),DailyTradeLimit:zod.z.number().nullish(),CollectibleJokerCatalogID:zod.z.string().nullish(),CollectibleJokerItemID:zod.z.string().nullish(),SpecialTradeEvents:zod.z.array(ID).nullish(),RewardPools:Ys.nullish(),Settings:zD.nullish()}).passthrough(),Ve={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",OpenPack:"OpenPack",OpenCollectionChest:"OpenCollectionChest",UseCollectibleJoker:"UseCollectibleJoker",ClaimSetReward:"ClaimSetReward",ClaimSetRewardsBatch:"ClaimSetRewardsBatch",ClaimGrandPrize:"ClaimGrandPrize",SendTradeOffer:"SendTradeOffer",CancelTradeOffer:"CancelTradeOffer",AcceptTradeOffer:"AcceptTradeOffer",DeclineTradeOffer:"DeclineTradeOffer",GetMyTradeOffers:"GetMyTradeOffers",GetIncomingTradeOffers:"GetIncomingTradeOffers"};var Rr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Collection",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Ve.GetDefinitions,e,yr)}getUserState(e){return this.send(Ve.GetUserState,e,nh)}openPack(e){return this.send(Ve.OpenPack,e,rh)}openCollectionChest(e){return this.send(Ve.OpenCollectionChest,e,oh)}useCollectibleJoker(e){return this.send(Ve.UseCollectibleJoker,e,ah)}claimSetReward(e){return this.send(Ve.ClaimSetReward,e,Da)}claimSetRewardsBatch(e){return this.send(Ve.ClaimSetRewardsBatch,e,lh)}claimGrandPrize(e){return this.send(Ve.ClaimGrandPrize,e,uh)}sendTradeOffer(e){return this.send(Ve.SendTradeOffer,e,ch)}cancelTradeOffer(e){return this.send(Ve.CancelTradeOffer,e,ph)}acceptTradeOffer(e){return this.send(Ve.AcceptTradeOffer,e,dh)}declineTradeOffer(e){return this.send(Ve.DeclineTradeOffer,e,hh)}getMyTradeOffers(e){return this.send(Ve.GetMyTradeOffers,e,Pa)}getIncomingTradeOffers(e){return this.send(Ve.GetIncomingTradeOffers,e,Pa)}};var Cr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"CoopEvent",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(pt.GetDefinitions,e,ts)}getActiveEvent(e){return this.send(pt.GetActiveEvent,e,tc)}getUserState(e){return this.send(pt.GetUserState,e,es)}getGroupState(e){return this.send(pt.GetGroupState,e,To)}joinOrCreateGroup(e){return this.send(pt.JoinOrCreateGroup,e,To)}spin(e){return this.send(pt.Spin,e,nc)}claimObjectReward(e){return this.send(pt.ClaimObjectReward,e,ko)}claimGrandPrize(e){return this.send(pt.ClaimGrandPrize,e,ko)}leaveGroup(e){return this.send(pt.LeaveGroup,e,sc)}};var Sr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"DealOffer",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinition(e){return this.send(gt.GetDefinition,e,fc)}getUserState(e){return this.send(gt.GetUserState,e,gc)}getActiveDeals(e){return this.send(gt.GetActiveDeals,e,ss)}dismissDeal(e){return this.send(gt.DismissDeal,e,Rc)}executeNode(e){return this.send(gt.ExecuteNode,e,yc)}recordShow(e){return this.send(gt.RecordShow,e,Cc)}claimMilestone(e){return this.send(gt.ClaimMilestone,e,Sc)}claimMilestonesBatch(e){return this.send(gt.ClaimMilestonesBatch,e,xc)}};var TD=zod.z.object({}).passthrough().transform(a=>a),kD=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:fe.nullish()}).passthrough(),va=zod.z.object({IsEnabled:zod.z.boolean().nullish(),ActivationReward:Q.nullish(),InviteRewards:zod.z.record(zod.z.string(),Ee).nullish(),SpendRewards:zod.z.array(kD).nullish()}).passthrough(),fh=zod.z.object({ReferralDefinitions:va.nullish()}).passthrough(),gh=zod.z.object({Referral:TD.nullish(),InviteUrl:zod.z.string().nullish()}).passthrough(),yh=zod.z.object({ReferralCode:zod.z.string().nullish(),ReferrerUserID:zod.z.string().nullish(),IsFirstActivation:zod.z.boolean().nullish(),Resources:w.nullish(),Inventory:K.nullish()}).passthrough(),Ia=zod.z.object({RewardID:zod.z.string().nullish(),Resources:w.nullish(),Inventory:K.nullish()}).passthrough(),Rh=mt(Ia),Qt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch"};var xr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Referral",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Qt.GetDefinitions,e,fh)}getUserState(e){return this.send(Qt.GetUserState,e,gh)}activateReferralCode(e){return this.send(Qt.ActivateReferralCode,e,yh)}claimInviteReward(e){return this.send(Qt.ClaimInviteReward,e,Ia)}claimInviteRewardsBatch(e){return this.send(Qt.ClaimInviteRewardsBatch,e,Rh)}};var br=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Mailbox",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(Ye.GetDefinitions,e,Ic)}getMessages(e){return this.send(Ye.GetMessages,e,zc)}getUnreadCount(e){return this.send(Ye.GetUnreadCount,e,as)}readMessages(e){return this.send(Ye.ReadMessages,e,Mo)}claimReward(e){return this.send(Ye.ClaimReward,e,ls)}claimRewardsBatch(e){return this.send(Ye.ClaimRewardsBatch,e,ls)}claimAll(e){return this.send(Ye.ClaimAll,e,ls)}deleteMessages(e){return this.send(Ye.DeleteMessages,e,Mo)}sendGift(e){return this.send(Ye.SendGift,e,Tc)}sendTransfer(e){return this.send(Ye.SendTransfer,e,kc)}getGiftStatus(e){return this.send(Ye.GetGiftStatus,e,Ac)}};var Dr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Social",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getFriendsList(e){return this.send(ge.GetFriendsList,e,zi)}getIncomingRequests(e){return this.send(ge.GetIncomingRequests,e,zi)}getOutgoingRequests(e){return this.send(ge.GetOutgoingRequests,e,zi)}getRecommendedFriends(e){return this.send(ge.GetRecommendedFriends,e,zi)}sendFriendRequest(e){return this.send(ge.SendFriendRequest,e,Ti)}acceptFriendRequest(e){return this.send(ge.AcceptFriendRequest,e,Ti)}declineFriendRequest(e){return this.send(ge.DeclineFriendRequest,e,Ti)}removeFriend(e){return this.send(ge.RemoveFriend,e,Ti)}getInbox(e){return this.send(ge.GetInbox,e,Mc)}markInboxSeen(e){return this.send(ge.MarkInboxSeen,e,ki)}getInboxUnread(e){return this.send(ge.GetInboxUnread,e,ki)}follow(e){return this.send(ge.Follow,e,Ut)}unfollow(e){return this.send(ge.Unfollow,e,Ut)}getFollowers(e){return this.send(ge.GetFollowers,e,cs)}getFollowing(e){return this.send(ge.GetFollowing,e,cs)}block(e){return this.send(ge.Block,e,Ut)}unblock(e){return this.send(ge.Unblock,e,Ut)}getBlocked(e){return this.send(ge.GetBlocked,e,cs)}react(e){return this.send(ge.React,e,Ut)}unreact(e){return this.send(ge.Unreact,e,Ut)}getMyReactions(e){return this.send(ge.GetMyReactions,e,Uc)}getEntityStates(e){return this.send(ge.GetEntityStates,e,Oc)}addComment(e){return this.send(ge.AddComment,e,ps)}editComment(e){return this.send(ge.EditComment,e,ps)}deleteComment(e){return this.send(ge.DeleteComment,e,Bc)}getComments(e){return this.send(ge.GetComments,e,Ec)}report(e){return this.send(ge.Report,e,qc)}};var AD={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Ht=zod.z.object({Target:zod.z.string().nullish(),Operation:zod.z.string().nullish(),Value:zod.z.number().nullish()}).passthrough(),wD=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:oe.nullish(),Effect:Ht.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(),Pr=zod.z.object({Schedule:de.nullish(),Gate:$.nullish()}).passthrough(),za=zod.z.object({Availability:_.nullish(),Effects:_.nullish()}).passthrough(),MD=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(Ht).nullish(),Availability:Pr.nullish(),Presets:za.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),OD=zod.z.object({ChainedBoostID:zod.z.string().nullish(),Order:zod.z.number().nullish(),DurationSec:zod.z.number().nullish(),Effects:zod.z.array(Ht).nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),UD=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(OD).nullish(),Availability:Pr.nullish(),Presets:za.nullish(),CustomParams:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),ED=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(it).nullish(),Effects:zod.z.array(Ht).nullish(),DurationSeconds:zod.z.number().nullish(),Charges:zod.z.number().nullish(),StackingPolicy:zod.z.string().nullish(),MaxActiveInstances:zod.z.number().nullish(),Availability:Pr.nullish(),Presets:za.nullish()}).passthrough(),BD=zod.z.object({MaxAddPercent:zod.z.number().nullish(),MaxMultiply:zod.z.number().nullish(),MaxAddFlat:zod.z.number().nullish()}).passthrough(),qD=zod.z.object({Effects:zod.z.array(Ht).nullish()}).passthrough(),LD=zod.z.object({Availability:zod.z.record(zod.z.string(),Pr).nullish(),Effects:zod.z.record(zod.z.string(),qD).nullish()}).passthrough(),GD=zod.z.object({StackingCaps:zod.z.record(zod.z.string(),BD).nullish()}).passthrough(),vr=zod.z.object({Definitions:zod.z.record(zod.z.string(),wD).nullish(),ScheduledBoosts:zod.z.record(zod.z.string(),MD).nullish(),BoostChains:zod.z.record(zod.z.string(),UD).nullish(),TriggeredBoosts:zod.z.record(zod.z.string(),ED).nullish(),Settings:GD.nullish(),Presets:LD.nullish()}).passthrough(),Ch=zod.z.object({InstanceID:zod.z.string(),BoostID:zod.z.string(),ActivatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),RemainingCharges:zod.z.number().nullish(),EffectSnapshot:Ht.nullish(),SourceType:zod.z.string().nullish(),SourceRef:zod.z.string().nullish()}).passthrough();zod.z.object({Date:u.nullish(),DailyCount:zod.z.number().nullish(),LastFiredUtc:u.nullish()}).passthrough();var Sh=zod.z.object({ServerTimeUtc:u.nullish(),Active:zod.z.record(zod.z.string(),Ch).nullish()}),xh=zod.z.object({ServerTimeUtc:u.nullish(),BoostID:zod.z.string().nullish(),StackingPolicy:zod.z.string().nullish(),ActivatedBoost:Ch.nullish(),Resources:w.nullish()}),ND={Scheduled:"Scheduled",Chain:"Chain"},VD=zod.z.object({Kind:zod.z.string().nullish(),SourceID:zod.z.string().nullish(),PhaseID:zod.z.string().nullish(),CycleIndex:zod.z.number().nullish(),PhaseOrder:zod.z.number().nullish(),StartUtc:u.nullish(),EndUtc:u.nullish(),Effects:zod.z.array(Ht).nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish()}).passthrough(),bh=zod.z.object({ServerTimeUtc:u.nullish(),Windows:zod.z.array(VD).nullish()}),$t={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Ir=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"TimedBoost",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send($t.GetDefinitions,e,vr)}getActive(e){return this.send($t.GetActive,e,Sh)}getActiveWindows(e){return this.send($t.GetActiveWindows,e,bh)}activate(e){return this.send($t.Activate,e,xh)}cleanupExpired(e){return this.send($t.CleanupExpired,e,Me)}};var zr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"UserCustomData",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getUserCustomDataDefinitions(e){return this.send(dt.GetUserCustomDataDefinitions,e,fs)}getMyUserCustomData(e){return this.send(dt.GetMyUserCustomData,e,Vc)}getPublicUserCustomDataOf(e){return this.send(dt.GetPublicUserCustomDataOf,e,qo)}setPrivateData(e){return this.send(dt.SetPrivateData,e,Lo)}setPublicData(e){return this.send(dt.SetPublicData,e,Lo)}deleteKey(e){return this.send(dt.DeleteKey,e,Me)}batchSet(e){return this.send(dt.BatchSet,e,Fc)}batchDelete(e){return this.send(dt.BatchDelete,e,jc)}batchGetPublicUserCustomDataOf(e){return this.send(dt.BatchGetPublicUserCustomDataOf,e,Wc)}};var FD={Static:"Static",Runtime:"Runtime"},jD={Public:"Public",Private:"Private"},WD=zod.z.enum(["Client","Server","System"]).catch("Client"),_D=zod.z.enum(["String","Int","Bool","Json"]).catch("String"),KD=zod.z.object({Value:zod.z.string().nullish(),UpdatedAt:u.nullish(),Version:zod.z.number().nullish(),LastWriter:WD.nullish(),ExpiresAt:u.nullish()}).passthrough(),Dh=zod.z.record(zod.z.string(),KD),Ta=zod.z.object({StaticVersion:zod.z.number().nullish(),RuntimeVersion:zod.z.number().nullish(),Static:Dh.nullish(),Runtime:Dh.nullish(),NotModified:zod.z.boolean().nullish()}),QD=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:_D.nullish(),MaxValueLengthBytes:zod.z.number().nullish(),TtlSeconds:zod.z.number().nullish(),DefaultValue:zod.z.string().nullish(),Description:zod.z.string().nullish()}).passthrough(),Tr=zod.z.object({Keys:zod.z.record(zod.z.string(),QD).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(),Ei={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var kr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"TitleCustomData",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getTitleCustomDataDefinitions(e){return this.send(Ei.GetTitleCustomDataDefinitions,e,Tr)}getPublicTitleData(e){return this.send(Ei.GetPublicTitleData,e,Ta)}getPublicTitleDataKeys(e){return this.send(Ei.GetPublicTitleDataKeys,e,Ta)}};var HD={Fast:"Fast",Sequential:"Sequential"},$D={Instant:"Instant",Timed:"Timed"};var JD={Hit:"Hit",Blocked:"Blocked"},ZD=zod.z.object({SlotIndex:zod.z.number(),Level:zod.z.number().nullish(),IsDamaged:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish()}).passthrough(),YD=zod.z.object({Symbol:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),OnOpenBonus:Q.nullish(),BonusTag:zod.z.string().nullish()}).passthrough();zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Q.nullish()}).passthrough();var XD=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Q.nullish()}).passthrough(),eP=zod.z.object({Reward:Q.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(XD).nullish(),Rate:eP.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 Ph=zod.z.object({}).passthrough().transform(a=>a),vh=zod.z.object({Min:zod.z.number().nullish(),Max:zod.z.number().nullish()}).passthrough(),Fe=zod.z.object({Operation:w.nullish(),ScaleWithRollMultiplier:zod.z.boolean().nullish()}).passthrough(),tP=zod.z.object({Count:zod.z.number().nullish(),Sides:zod.z.number().nullish()}).passthrough(),iP=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(),nP=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:ae.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(),sP=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:ae.nullish()}).passthrough(),Ih=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:Q.nullish()}).passthrough(),rP=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(),oP=zod.z.object({Tiles:zod.z.record(zod.z.string(),rP).nullish()}).passthrough(),aP=zod.z.object({Weight:zod.z.number().nullish(),Bonus:Fe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),lP=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(aP).nullish(),GuaranteedBonus:Fe.nullish(),IsJackpot:zod.z.boolean().nullish(),JackpotFinalMultiplier:zod.z.number().nullish(),JackpotSymbolDistribution:zod.z.record(zod.z.string(),zod.z.number()).nullish()}).passthrough(),uP=zod.z.object({Variants:zod.z.array(lP).nullish()}).passthrough(),cP=zod.z.object({Weight:zod.z.number().nullish(),OutcomeID:zod.z.string().nullish(),Reward:Fe.nullish(),ForceAction:zod.z.string().nullish(),SpecialModeID:zod.z.string().nullish()}).passthrough(),pP=zod.z.object({Outcomes:zod.z.array(cP).nullish()}).passthrough(),zh=zod.z.object({PerAdMultiplierRange:vh.nullish(),MaxAdViews:zod.z.number().nullish(),AdCreditCost:zod.z.number().nullish(),FormulaKind:zod.z.string().nullish(),ApplyMultiplierOnEarlyClaim:zod.z.boolean().nullish()}).passthrough(),dP=zod.z.object({ElapsedSeconds:zod.z.number().nullish(),Reward:Fe.nullish()}).passthrough(),hP=zod.z.object({Tiers:zod.z.array(dP).nullish(),TierMode:zod.z.string().nullish(),BelowFirstTierReward:Fe.nullish()}).passthrough(),mP=zod.z.object({RequiredValue:zod.z.number().nullish(),Reward:Fe.nullish()}).passthrough(),fP=zod.z.object({Reward:Fe.nullish(),MetricPerReward:zod.z.number().nullish(),MaxRewardUnits:zod.z.number().nullish()}).passthrough(),gP=zod.z.object({MetricID:zod.z.string().nullish(),MaxValuePerClaim:zod.z.number().nullish(),TierMode:zod.z.string().nullish(),ApplyClaimMultiplier:zod.z.boolean().nullish(),Tiers:zod.z.array(mP).nullish(),Rate:fP.nullish()}).passthrough(),Th=zod.z.object({MetricsByID:zod.z.record(zod.z.string(),gP).nullish()}).passthrough(),yP=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Fe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:oe.nullish(),Multipliers:zh.nullish(),Gradation:hP.nullish(),RunStats:Th.nullish()}).passthrough(),RP=zod.z.object({Choices:zod.z.array(yP).nullish(),OfferExpireSeconds:zod.z.number().nullish(),ClaimExpireSeconds:zod.z.number().nullish()}).passthrough(),CP=zod.z.object({Chance:zod.z.number().nullish(),RequiredOutcome:zod.z.string().nullish(),Reward:Fe.nullish(),Tag:zod.z.string().nullish()}).passthrough(),SP=zod.z.object({OnPassStart:Fe.nullish(),OnTileLanding:zod.z.record(zod.z.string(),Fe).nullish(),OnAttack:zod.z.record(zod.z.string(),Fe).nullish(),OnRaid:zod.z.record(zod.z.string(),Fe).nullish(),OnBuild:Fe.nullish(),OnStageComplete:Fe.nullish(),OnAttackBonusDrops:zod.z.array(CP).nullish(),ChanceTablesByID:zod.z.record(zod.z.string(),pP).nullish(),SpecialModesByID:zod.z.record(zod.z.string(),RP).nullish()}).passthrough(),kh=zod.z.object({BaseAttackReward:Q.nullish(),BaseRaidReward:Q.nullish(),MaxRollMultiplier:zod.z.number().nullish(),MaxShields:zod.z.number().nullish(),Buildings:zod.z.array(Ih).nullish(),HeistGridBonusConfig:uP.nullish(),StageOperations:SP.nullish(),TileLandingMultiplier:vh.nullish(),EconomyOverride:sP.nullish()}).passthrough(),xP=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(Ih).nullish(),StageTemplateID:zod.z.string().nullish(),CostMatrixTemplateID:zod.z.string().nullish(),UnitValue:zod.z.number().nullish(),Override:kh.nullish()}).passthrough(),bP=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(),DP=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(),Ar=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(),oP).nullish(),StageTemplatesByID:zod.z.record(zod.z.string(),kh).nullish(),StagesByLevel:zod.z.record(zod.z.string(),xP).nullish(),SoftCurrencyID:zod.z.string().nullish(),ProceduralEconomy:nP.nullish(),Dice:tP.nullish(),Bots:iP.nullish(),Targeting:bP.nullish(),BotRaids:DP.nullish()}).passthrough(),PP=zod.z.object({IsActive:zod.z.boolean().nullish(),DisplayName:zod.z.string().nullish(),AssetPaths:zod.z.record(zod.z.string(),zod.z.string()).nullish(),AnchorUtc:u.nullish(),RoundDurationSec:zod.z.number().nullish(),PauseBetweenRoundsSec:zod.z.number().nullish(),MaxRounds:zod.z.number().nullish(),PartnerCount:zod.z.number().nullish(),MatchmakingTimeoutMinutes:zod.z.number().nullish(),MemberGracePeriodMinutes:zod.z.number().nullish(),ContributionMin:zod.z.number().nullish(),ContributionMax:zod.z.number().nullish(),ScaleContributionWithRollMultiplier:zod.z.boolean().nullish(),MaxProgress:zod.z.number().nullish(),Milestones:zod.z.record(zod.z.string(),Ee).nullish(),GrandPrize:Q.nullish()}).passthrough(),wr=zod.z.object({Board:Ar.nullish(),CommunityChest:PP.nullish()}).passthrough(),Ah=zod.z.object({AttackerGainByOutcome:zod.z.record(zod.z.string(),ae).nullish()}).passthrough(),vP=zod.z.object({TargetUserID:zod.z.string().nullish(),IsBot:zod.z.boolean().nullish(),PublicData:Ae.nullish(),TargetBuildingStates:zod.z.array(ZD).nullish(),TargetHasShield:zod.z.boolean().nullish(),TargetStageLevel:zod.z.number().nullish(),RaidRewardPreview:Ah.nullish()}).passthrough(),IP=zod.z.object({ChoiceID:zod.z.string().nullish(),Mode:zod.z.string().nullish(),Reward:Fe.nullish(),DurationSeconds:zod.z.number().nullish(),PriceOptions:oe.nullish(),Multipliers:zh.nullish(),RunStats:Th.nullish()}).passthrough(),zP=zod.z.object({ModeID:zod.z.string().nullish(),Choices:zod.z.array(IP).nullish()}).passthrough(),TP=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(),wh=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:w.nullish(),Inventory:K.nullish(),ActionRequired:zod.z.string().nullish(),ActionData:vP.nullish(),SpecialModeOffer:zP.nullish(),CommunityChestContribution:TP.nullish()}).passthrough(),Mh=zod.z.object({Outcome:zod.z.string().nullish(),IsBotTarget:zod.z.boolean().nullish(),BuildingIndexHit:zod.z.number().nullish(),Operation:w.nullish(),Inventory:K.nullish(),DualResult:St.nullish()}).passthrough(),ka=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:Q.nullish(),OpenedIndex:zod.z.number().nullish(),AttemptsLeft:zod.z.number().nullish(),RaidLayout:zod.z.array(YD).nullish(),HeistVariantTag:zod.z.string().nullish(),IsJackpot:zod.z.boolean().nullish(),Operation:w.nullish(),Inventory:K.nullish(),DualResult:St.nullish(),RaidRewardPreview:Ah.nullish()}).passthrough(),Oh=zod.z.object({BuiltIndex:zod.z.number(),NewLevel:zod.z.number().nullish(),StageComplete:zod.z.boolean().nullish(),MaxLevelRewardClaimed:zod.z.boolean().nullish(),Operation:w.nullish(),Inventory:K.nullish()}).passthrough(),Uh=zod.z.object({Mode:zod.z.union([zod.z.string(),zod.z.number()]).nullish(),Operation:w.nullish(),Inventory:K.nullish(),DurationSeconds:zod.z.number().nullish(),StartedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish()}).passthrough(),Eh=zod.z.object({AdViewsUsed:zod.z.number().nullish(),RolledMultiplier:zod.z.number().nullish(),AccumulatedMultiplier:zod.z.number().nullish(),RemainingAdViews:zod.z.number().nullish()}).passthrough(),kP=zod.z.object({MetricID:zod.z.string().nullish(),ReachedTierIndex:zod.z.number().nullish(),RequiredValue:zod.z.number().nullish(),RewardUnits:zod.z.number().nullish()}).passthrough(),Bh=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:w.nullish(),Inventory:K.nullish(),AcceptedRunStats:zod.z.record(zod.z.string(),zod.z.number()).nullish(),RunStatAwards:zod.z.array(kP).nullish(),RunStatsClamped:zod.z.boolean().nullish(),RunStatGrant:Q.nullish()}).passthrough(),AP={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},qh=zod.z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),wP={Active:"Active",Left:"Left",Replaced:"Replaced"},MP=zod.z.enum(["Active","Left","Replaced"]).catch("Active"),OP=zod.z.object({CurrentProgress:j.nullish(),MaxProgress:j.nullish()}).passthrough(),UP=zod.z.object({UserID:zod.z.string().nullish(),PublicData:Ae.nullish(),IsBot:zod.z.boolean().nullish(),ContributionPoints:j.nullish(),MilestoneClaims:zod.z.record(zod.z.string(),nl).nullish(),GrandPrizeClaimed:zod.z.boolean().nullish(),MemberStatus:MP.nullish(),JoinedAtUtc:u.nullish(),LeftAtUtc:u.nullish()}).passthrough(),Lh=zod.z.object({GroupID:zod.z.string().nullish(),TitleID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),Members:zod.z.array(UP).nullish(),SharedProgress:OP.nullish(),Status:qh.nullish(),CreatedAtUtc:u.nullish(),ExpiresAtUtc:u.nullish(),Version:zod.z.number().nullish()}).passthrough(),EP=zod.z.object({GroupID:zod.z.string().nullish(),RoundIndex:zod.z.number().nullish(),FinalStatus:qh.nullish(),GrandPrizeReceived:zod.z.boolean().nullish(),FinishedAtUtc:u.nullish()}).passthrough(),BP=zod.z.object({ActiveGroupID:zod.z.string().nullish(),ActiveRoundIndex:zod.z.number().nullish(),History:zod.z.array(EP).nullish()}).passthrough(),Gh=zod.z.object({ServerTimeUtc:u.nullish(),UserState:BP.nullish(),ActiveGroup:Lh.nullish(),SecondsRemaining:j.nullish()}),Nh=zod.z.object({ServerTimeUtc:u.nullish(),Group:Lh.nullish(),SecondsRemaining:j.nullish()}),Aa=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),RewardType:zod.z.string().nullish(),MilestoneID:zod.z.string().nullish(),Resources:w.nullish(),Inventory:K.nullish()}),Vh=zod.z.object({ServerTimeUtc:u.nullish(),GroupID:zod.z.string().nullish(),Success:zod.z.boolean().nullish()}),Ue={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 qP={Mesh:"Mesh",Host:"Host"},wa=zod.z.enum(["Mesh","Host"]).catch("Mesh"),LP={ServerRelay:"ServerRelay",P2P:"P2P"},Ma=zod.z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),GP={Public:"Public",Private:"Private"},NP=zod.z.enum(["Public","Private"]).catch("Public"),VP={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},FP=zod.z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Fh=zod.z.object({Urls:zod.z.string().nullish(),Username:zod.z.string().nullish(),Credential:zod.z.string().nullish()}).passthrough(),jP=zod.z.object({Enabled:zod.z.boolean().nullish()}).passthrough(),jh=zod.z.object({SystemState:jP.nullish(),DefaultTopology:wa.nullish(),AllowCreatorTopologyOverride:zod.z.boolean().nullish(),DefaultChatMode:Ma.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(),IceServers:zod.z.array(Fh).nullish()}).passthrough(),WP=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(),_P=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),Topology:wa.nullish(),ChatMode:Ma.nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),MemberCount:zod.z.number().nullish(),CreatedAt:zod.z.number().nullish()}).passthrough(),KP=zod.z.object({Seq:zod.z.number().nullish(),Type:FP.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(),Bi=zod.z.object({RoomID:zod.z.string().nullish(),Name:zod.z.string().nullish(),HostUserID:zod.z.string().nullish(),OwnerUserID:zod.z.string().nullish(),Topology:wa.nullish(),ChatMode:Ma.nullish(),Visibility:NP.nullish(),Status:zod.z.string().nullish(),MaxPlayers:zod.z.number().nullish(),Mode:zod.z.string().nullish(),Members:zod.z.array(WP).nullish(),IceServers:zod.z.array(Fh).nullish(),Seq:zod.z.number().nullish(),BannedUserIDs:zod.z.array(zod.z.string()).nullish()}).passthrough(),Wh=zod.z.object({Removed:zod.z.boolean().nullish(),Banned:zod.z.boolean().nullish()}).passthrough(),_h=zod.z.object({WasBanned:zod.z.boolean().nullish()}).passthrough(),Oa=zod.z.object({Closed:zod.z.boolean().nullish(),NewHostUserID:zod.z.string().nullish()}).passthrough(),Kh=zod.z.object({Rooms:zod.z.array(_P).nullish(),Page:zod.z.number().nullish(),PageSize:zod.z.number().nullish(),HasMore:zod.z.boolean().nullish()}).passthrough(),Qh=zod.z.object({Envelopes:zod.z.array(KP).nullish(),MaxSeq:zod.z.number().nullish()}).passthrough(),Mr=zod.z.object({Seq:zod.z.number().nullish()}).passthrough(),Ke={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 Ua=zod.z.object({TitleCustomData:Tr.nullish(),Character:Qn.nullish(),Item:_s.nullish(),Currency:bs.nullish(),Store:fn.nullish(),Lootbox:Ra.nullish(),Quest:Wi.nullish(),TimedEvent:Mn.nullish(),Leaderboard:Nn.nullish(),Season:jn.nullish(),Reward:Sa.nullish(),Collection:yr.nullish(),Craft:ba.nullish(),DealOffer:Ao.nullish(),Premium:fa.nullish(),TimedBoost:vr.nullish(),CoopEvent:ts.nullish(),GameLoop:wr.nullish(),Match:$o.nullish(),Experiment:ld.nullish(),Blockchain:Fo.nullish(),Marketplace:ea.nullish(),Multiplayer:jh.nullish(),UserCustomData:fs.nullish(),Referral:va.nullish(),Localization:Rd.nullish(),Analytics:Zp.nullish(),Social:Lc.nullish(),PlatformBridge:Gc.nullish()}).passthrough();var Jt={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Or=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Title",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getTitlePublicConfiguration(e){return this.send(Jt.GetTitlePublicConfiguration,e,Ua)}getTitlePublicConfigurationExcept(e){return this.send(Jt.GetTitlePublicConfigurationExcept,e,Ua)}getCurrencyDefinitions(e){return this.send(Jt.GetCurrencyDefinitions,e,bs)}getItemDefinitions(e){return this.send(Jt.GetItemDefinitions,e,_s)}getServerTime(e){return this.send(Jt.GetServerTime,e,Me)}};var Ur=class{constructor(e){this.ctx=e;}ctx;send(e,t,i,n=false){let s=E(this.ctx.settings.titleID,"GameLoop",e,t.UserID??"");return this.ctx.transport.post(s,t,i,{ticket:t.ClientSessionTicket,silent:n})}getGameLoops(e){return this.send(Ue.GetGameLoops,e,wr)}getBoardDefinition(e,t=false){return this.send(Ue.GetBoardDefinition,e,Ar,t)}getBoardDefinitionForLevel(e,t=false){return this.send(Ue.GetBoardDefinitionForLevel,e,Ar,t)}getUserBoardState(e){return this.send(Ue.GetUserBoardState,e,Ph)}boardLoopRoll(e){return this.send(Ue.BoardLoopRoll,e,wh)}boardLoopAttack(e){return this.send(Ue.BoardLoopAttack,e,Mh)}boardLoopRaid(e){return this.send(Ue.BoardLoopRaid,e,ka)}boardLoopRaidFast(e){return this.send(Ue.BoardLoopRaidFast,e,ka)}boardLoopBuild(e){return this.send(Ue.BoardLoopBuild,e,Oh)}boardSpecialChoose(e){return this.send(Ue.BoardSpecialChoose,e,Uh)}boardSpecialApplyMultiplier(e){return this.send(Ue.BoardSpecialApplyMultiplier,e,Eh)}boardSpecialClaim(e){return this.send(Ue.BoardSpecialClaim,e,Bh)}getCommunityChestState(e){return this.send(Ue.GetCommunityChestState,e,Gh)}joinOrCreateCommunityChest(e){return this.send(Ue.JoinOrCreateCommunityChest,e,Nh)}claimCommunityChestMilestone(e){return this.send(Ue.ClaimCommunityChestMilestone,e,Aa)}claimCommunityChestGrandPrize(e){return this.send(Ue.ClaimCommunityChestGrandPrize,e,Aa)}leaveCommunityChest(e){return this.send(Ue.LeaveCommunityChest,e,Vh)}};var HP={Live:"Live",Latest:"Latest",Specific:"Specific"},$P={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},JP=zod.z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),ZP={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"},YP=zod.z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),XP=zod.z.object({Level:JP,Message:zod.z.string().nullish(),Data:Mt.nullish()}),ev=zod.z.object({Error:YP,Message:zod.z.string().nullish(),StackTrace:zod.z.string().nullish()}),Hh=zod.z.object({FunctionName:zod.z.string().nullish(),Revision:zod.z.number().nullish(),FunctionResult:Mt.nullish(),FunctionResultTooLarge:zod.z.boolean().nullish(),Logs:zod.z.array(XP).nullish(),LogsTooLarge:zod.z.boolean().nullish(),ExecutionTimeSeconds:zod.z.number().nullish(),APIRequestsIssued:zod.z.number().nullish(),Error:ev.nullish()}),Ea={Execute:"Execute"};var Er=class{constructor(e){this.ctx=e;}ctx;execute(e){let t=E(this.ctx.settings.titleID,"CloudCode",Ea.Execute,e.UserID??"");return this.ctx.transport.post(t,e,Hh,{ticket:e.ClientSessionTicket})}};var Br=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Blockchain",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(_e.GetDefinitions,e,op)}getUserState(e){return this.send(_e.GetUserState,e,ap)}depositToken(e){return this.send(_e.DepositToken,e,lp)}depositNFT(e){return this.send(_e.DepositNFT,e,up)}requestTokenWithdrawal(e){return this.send(_e.RequestTokenWithdrawal,e,cp)}requestNFTWithdrawal(e){return this.send(_e.RequestNFTWithdrawal,e,pp)}getTransactionHistory(e){return this.send(_e.GetTransactionHistory,e,dp)}retryWithdrawal(e){return this.send(_e.RetryWithdrawal,e,hp)}confirmWithdrawal(e){return this.send(_e.ConfirmWithdrawal,e,mp)}donateToDeveloper(e){return this.send(_e.DonateToDeveloper,e,Ko)}donateToUsersPool(e){return this.send(_e.DonateToUsersPool,e,Ko)}getPlayAccess(e){return this.send(_e.GetPlayAccess,e,sp)}confirmPlayAccess(e){return this.send(_e.ConfirmPlayAccess,e,Et)}};var qr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Marketplace",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(ve.GetDefinitions,e,zp)}getGroupedOffers(e){return this.send(ve.GetGroupedOffers,e,Tp)}getOffersByItem(e){return this.send(ve.GetOffersByItem,e,ta)}getOffer(e){return this.send(ve.GetOffer,e,kp)}getBuyOrders(e){return this.send(ve.GetBuyOrders,e,ta)}getMyState(e){return this.send(ve.GetMyState,e,ks)}getHistory(e){return this.send(ve.GetHistory,e,wp)}createListing(e){return this.send(ve.CreateListing,e,Mi)}cancelListing(e){return this.send(ve.CancelListing,e,ot)}buy(e){return this.send(ve.Buy,e,ot)}marketBuy(e){return this.send(ve.MarketBuy,e,ot)}marketSell(e){return this.send(ve.MarketSell,e,ot)}createAuction(e){return this.send(ve.CreateAuction,e,Mi)}placeBid(e){return this.send(ve.PlaceBid,e,Ap)}claimAuction(e){return this.send(ve.ClaimAuction,e,ot)}createBuyOrder(e){return this.send(ve.CreateBuyOrder,e,Mi)}cancelBuyOrder(e){return this.send(ve.CancelBuyOrder,e,ot)}fillBuyOrder(e){return this.send(ve.FillBuyOrder,e,ot)}createDirectTrade(e){return this.send(ve.CreateDirectTrade,e,Mi)}respondDirectTrade(e){return this.send(ve.RespondDirectTrade,e,ot)}cancelDirectTrade(e){return this.send(ve.CancelDirectTrade,e,ot)}claimBack(e){return this.send(ve.ClaimBack,e,ot)}};var Lr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i,n={}){let s=E(this.ctx.settings.titleID,"Multiplayer",e,t.UserID??"");return this.ctx.transport.post(s,t,i,{ticket:t.ClientSessionTicket,...n})}createRoom(e){return this.send(Ke.CreateRoom,e,Bi)}joinRoom(e){return this.send(Ke.JoinRoom,e,Bi)}leaveRoom(e,t=false){return this.send(Ke.LeaveRoom,e,Oa,{keepalive:t})}listRooms(e){return this.send(Ke.ListRooms,e,Kh)}getRoom(e){return this.send(Ke.GetRoom,e,Bi)}closeRoom(e){return this.send(Ke.CloseRoom,e,Oa)}poll(e){return this.send(Ke.Poll,e,Qh)}sendSignal(e){return this.send(Ke.SendSignal,e,Mr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(Ke.ClaimHost,e,Bi)}kickMember(e){return this.send(Ke.KickMember,e,Wh)}unbanMember(e){return this.send(Ke.UnbanMember,e,_h)}sendChat(e){return this.send(Ke.SendChat,e,Mr)}setMemberState(e){return this.send(Ke.SetMemberState,e,Mr)}};var tv={Free:"Free",Price:"Price",Holding:"Holding"},Ba=zod.z.enum(["Free","Price","Holding"]).catch("Free"),iv={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},nv=zod.z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),sv={All:"All",Any:"Any"},rv=zod.z.enum(["All","Any"]).catch("All"),ov={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},av=zod.z.enum(["Public","Unlisted","Friends"]).catch("Public"),lv={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},uv=zod.z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),cv={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Jh=zod.z.enum(["Purchase","Free","Holding"]).catch("Free"),pv={New:"New",Popular:"Popular",MostLiked:"MostLiked"},dv={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},hv=zod.z.enum(["Creator","License","Free","Holding"]).catch("License"),mv=zod.z.object({Type:ri.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(),fv=zod.z.object({Requirements:zod.z.array(mv).nullish(),Match:rv.nullish(),Mode:nv.nullish()}).passthrough(),gv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Ba.nullish(),Price:ae.nullish(),Holding:fv.nullish()}).passthrough(),yv=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(),Rv=zod.z.object({DisplayName:zod.z.string().nullish(),Enabled:zod.z.boolean().nullish(),Files:zod.z.record(zod.z.string(),yv).nullish(),ThumbnailRequired:zod.z.boolean().nullish(),AllowedAccessModes:zod.z.array(Ba).nullish(),PricePolicy:Ts.nullish(),PublishGate:$.nullish(),PublishFeeOptions:oe.nullish(),TagVocabulary:zod.z.array(zod.z.string()).nullish(),MaxPublishedPerPlayer:zod.z.number().nullish(),DailyPublishCap:zod.z.number().nullish()}).passthrough(),Cv=zod.z.object({Allowed:zod.z.array(wi).nullish(),MaxRequirements:zod.z.number().nullish()}).passthrough(),Sv=zod.z.object({AutoHideReportThreshold:zod.z.number().nullish(),RequireApproval:zod.z.boolean().nullish(),BlockedTerms:zod.z.array(zod.z.string()).nullish()}).passthrough(),xv=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(),bv=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:de.nullish(),Gate:$.nullish(),Order:zod.z.number().nullish()}).passthrough(),Dv=zod.z.object({Enabled:zod.z.boolean().nullish(),Gate:$.nullish(),Schedule:de.nullish(),ContentTypes:zod.z.record(zod.z.string(),Rv).nullish(),PricePolicy:Ts.nullish(),Commission:Xo.nullish(),HoldingPolicy:Cv.nullish(),Moderation:Sv.nullish(),Limits:xv.nullish(),Featured:zod.z.array(bv).nullish()}).passthrough(),Pv=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()}).passthrough(),Zt=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),CreatorUserID:zod.z.string().nullish(),IsOfficial:zod.z.boolean().nullish(),CreatorPublicData:Ae.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:av.nullish(),Access:zod.z.array(gv).nullish(),Status:uv.nullish(),ModerationNote:zod.z.string().nullish(),Stats:Pv.nullish(),Revision:zod.z.number().nullish(),FileCount:zod.z.number().nullish(),TotalBytes:zod.z.number().nullish(),CreatedAt:u.nullish(),UpdatedAt:u.nullish(),PublishedAt:u.nullish(),IsMine:zod.z.boolean().nullish(),Owned:zod.z.boolean().nullish(),Liked:zod.z.boolean().nullish(),Favorited:zod.z.boolean().nullish()}).passthrough(),vv=zod.z.object({OptionID:zod.z.string().nullish(),Mode:Ba.nullish(),Available:zod.z.boolean().nullish()}).passthrough(),Zh=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(),Yh=zod.z.object({Definitions:Dv.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(Zh).nullish()}).passthrough(),Gr=zod.z.object({Items:zod.z.array(Zt).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),Xh=zod.z.object({Content:Zt.nullish(),AccessState:zod.z.array(vv).nullish(),CanDownload:zod.z.boolean().nullish()}).passthrough(),em=zod.z.object({Collection:Zh.nullish(),Items:zod.z.array(Zt).nullish()}).passthrough(),tm=zod.z.object({CreatorUserID:zod.z.string().nullish(),PublicData:Ae.nullish(),PublishedCount:zod.z.number().nullish(),FollowerCount:zod.z.number().nullish(),IsFollowing:zod.z.boolean().nullish(),Items:zod.z.array(Zt).nullish()}).passthrough(),$h=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(),im=zod.z.object({ContentID:zod.z.string().nullish(),Revision:zod.z.number().nullish(),Uploads:zod.z.array($h).nullish(),ThumbnailUpload:$h.nullish(),ExpiresAt:u.nullish()}).passthrough(),nm=zod.z.object({Content:Zt.nullish(),Resources:w.nullish()}).passthrough(),qa=zod.z.object({Content:Zt.nullish()}).passthrough(),sm=zod.z.object({ContentID:zod.z.string().nullish(),OptionID:zod.z.string().nullish(),Source:Jh.nullish(),AlreadyOwned:zod.z.boolean().nullish(),AccessActive:zod.z.boolean().nullish(),Settlement:St.nullish(),Resources:w.nullish(),CommissionTaken:ae.nullish()}).passthrough(),Iv=zod.z.object({Role:zod.z.string().nullish(),Url:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Size:zod.z.number().nullish()}).passthrough(),rm=zod.z.object({ContentID:zod.z.string().nullish(),ContentType:zod.z.string().nullish(),Revision:zod.z.number().nullish(),AccessVia:hv.nullish(),Files:zod.z.array(Iv).nullish(),ThumbnailUrl:zod.z.string().nullish(),ExpiresAt:u.nullish()}).passthrough(),zv=zod.z.object({ContentID:zod.z.string().nullish(),Source:Jh.nullish(),OptionID:zod.z.string().nullish(),PricePaid:ae.nullish(),AcquiredAt:u.nullish(),Content:Zt.nullish()}).passthrough(),om=zod.z.object({Licenses:zod.z.array(zv).nullish(),ContinuationToken:zod.z.string().nullish()}).passthrough(),je={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 Nr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i){let n=E(this.ctx.settings.titleID,"Workshop",e,t.UserID??"");return this.ctx.transport.post(n,t,i,{ticket:t.ClientSessionTicket})}getDefinitions(e){return this.send(je.GetDefinitions,e,Yh)}browse(e){return this.send(je.Browse,e,Gr)}getContent(e){return this.send(je.GetContent,e,Xh)}getCollection(e){return this.send(je.GetCollection,e,em)}getCreatorProfile(e){return this.send(je.GetCreatorProfile,e,tm)}beginUpload(e){return this.send(je.BeginUpload,e,im)}publish(e){return this.send(je.Publish,e,nm)}updateContent(e){return this.send(je.UpdateContent,e,qa)}unpublish(e){return this.send(je.Unpublish,e,qa)}getMyContent(e){return this.send(je.GetMyContent,e,Gr)}acquire(e){return this.send(je.Acquire,e,sm)}getDownload(e){return this.send(je.GetDownload,e,rm)}getMyLicenses(e){return this.send(je.GetMyLicenses,e,om)}getMyFavorites(e){return this.send(je.GetMyFavorites,e,Gr)}};var Vr=class{constructor(e){this.ctx=e;}ctx;send(e,t,i,n){let s=E(this.ctx.settings.titleID,"DataCollections",e,t.UserID??"");return this.ctx.transport.post(s,t,i,{ticket:t.ClientSessionTicket,throttleKey:`${s}|${n}`})}sendPublic(e,t,i,n){let o=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(o,t,i,{throttleKey:`${o}|${n}`})}getDefinitions(e){return this.send("GetDefinitions",e,qp,"defs")}get(e){return this.send("Get",e,na,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.send("GetMany",e,Gp,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.send("Query",e,sa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.send("Count",e,Np,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.send("Create",e,ra,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.send("Update",e,ra,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.send("Delete",e,Vp,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.send("Batch",e,jp,e.RelatedEntityID??"batch")}getCounter(e){return this.send("GetCounter",e,Fp,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.send("GetMyRoles",e,Wp,"roles")}beginFileUpload(e){return this.send("BeginFileUpload",e,Lp,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,_p,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,na,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,sa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Fr=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e){this.settings=Fa(e),this.emitter=new Si,this.platform=e.platform??new ii,this.clientPlatform=e.clientPlatform??tl(),this.acquisition=new Lt(this.platform),this.acquisition.capture(),this.playtime=new xi(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear();}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.transport=new Zi({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 tn(this.emitter),this.cache=new sn(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new rn(this.platform.storage,this.settings.titleID),this.api={authentication:new Ns(this),user:new Fs(this),currency:new js(this),item:new Ks(this),store:new Qs(this),purchase:new Zs(this),lootbox:new er(this),reward:new tr(this),quest:new ar(this),tutorial:new ir(this),communityMarketing:new nr(this),chat:new sr(this),push:new rr(this),localization:new or(this),timedEvent:new lr(this),leaderboard:new ur(this),season:new cr(this),premium:new pr(this),character:new dr(this),match:new hr(this),craft:new fr(this),ai:new gr(this),collection:new Rr(this),coopEvent:new Cr(this),dealOffer:new Sr(this),referral:new xr(this),mailbox:new br(this),social:new Dr(this),timedBoost:new Ir(this),userCustomData:new zr(this),titleCustomData:new kr(this),title:new Or(this),gameLoop:new Ur(this),cloudCode:new Er(this),blockchain:new Br(this),marketplace:new qr(this),multiplayer:new Lr(this),workshop:new Nr(this),dataCollections:new Vr(this),analytics:new Ls(this),experiment:new Gs(this)},this.userService=new cn(this),this.cache.attachState(this.userService),this.auth=new on(this),this.currency=new dn(this),this.item=new hn(this),this.store=new yn(this),this.purchase=new Rn(this),this.checkout=new Cn(this),this.lootbox=new Sn(this),this.reward=new xn(this),this.quest=new wn(this),this.tutorial=new Dn(this),this.communityMarketing=new Pn(this),this.chat=new zn(this),this.push=new Tn(this),this.localization=new An(this),this.timedEvent=new Un(this),this.leaderboard=new Vn(this),this.season=new Wn(this),this.premium=new _n(this),this.character=new Hn(this),this.match=new $n(this),this.craft=new Jn(this),this.ai=new Yn(this),this.collection=new Xn(this),this.coopEvent=new is(this),this.dealOffer=new rs(this),this.referral=new os(this),this.mailbox=new us(this),this.social=new ds(this),this.timedBoost=new hs(this),this.userCustomData=new gs(this),this.titleCustomData=new ys(this),this.title=new Rs(this),this.gameLoop=new Cs(this),this.cloudCode=new Ss(this),this.blockchain=new Ps(this),this.marketplace=new As(this),this.multiplayer=new ws(this),this.workshop=new Ms(this),this.dataCollections=new Us(this),this.analytics=new Bs(this),this.experiments=new qs(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:q()}}};var jr=class{ctx;constructor(e){this.ctx=new Fr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let n=this.ctx.buildAuthedBaseRequest(),s=E(this.ctx.settings.titleID,e,t,n.UserID??"");return this.ctx.transport.post(s,{...n,...i},zod.z.unknown(),{ticket:n.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get platform(){return this.ctx.platform}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function kv(a){return new jr(a)}var am="idos_sso",lm="state",La="idos:sso:state",Av="https://idosgames.com/sso/";function wv(){if(typeof window>"u")return null;let a=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!a)return null;let e=new URLSearchParams(a),t=e.get(am);if(!t)return null;let i=e.get(lm)??"",n=Bv();return Lv(e),qv(),n&&i!==n?null:{code:t,state:i}}function Mv(a){if(typeof window>"u")return;let e=a.returnTo??Ov(),t=Uv();Ev(t);let i=new URL(a.ssoUrl??Av);i.searchParams.set("title",a.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function Ov(){let{origin:a,pathname:e,search:t}=window.location;return `${a}${e}${t}`}function Uv(){let a=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(a);else for(let e=0;e<a.length;e++)a[e]=Math.floor(Math.random()*256);return Array.from(a,e=>e.toString(16).padStart(2,"0")).join("")}function Ev(a){try{window.sessionStorage.setItem(La,a);}catch{}}function Bv(){try{return window.sessionStorage.getItem(La)}catch{return null}}function qv(){try{window.sessionStorage.removeItem(La);}catch{}}function Lv(a){a.delete(am),a.delete(lm);let e=a.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}function Gv(a,e){return !!a?.Claims?.[e]?.ClaimedAt}function Nv(a){let e=a?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function Vv(a,e){return a?.Claims?.[e]?.PremiumTiers??[]}function cm(a,e,t,i=1){if(!a)return e;let n=a.Base??e,s=Math.max(0,t-i),o;switch(a.Shape??"Flat"){case "PerStep":o=n+(a.PerStep??0)*s;break;case "PerStepRate":o=n*(1+(a.PerStepRate??0)*s);break;case "Geometric":o=n*Math.pow(1+(a.GrowthRate??0),s);break;case "Table":o=n*um(a,t,1);break;case "TableAbsolute":o=um(a,t,n);break;default:o=n;break}return Number.isNaN(o)?n:(a.MinResult!=null&&o<a.MinResult&&(o=a.MinResult),a.MaxResult!=null&&o>a.MaxResult&&(o=a.MaxResult),o)}function Fv(a,e,t=1){return cm(a,1,e,t)}function jv(a){if(!a)return false;switch(a.Shape??"Flat"){case "PerStep":return (a.PerStep??0)!==0;case "PerStepRate":return (a.PerStepRate??0)!==0;case "Geometric":return (a.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return pm(a.Points).length>0;default:return a.MinResult!=null||a.MaxResult!=null}}function Wv(a){if(Number.isNaN(a)||a<=0)return 0;if(!Number.isFinite(a))return Number.MAX_SAFE_INTEGER;let e=Math.round(a);return Math.abs(a-e)<=1e-9*Math.max(1,Math.abs(a))?e:Math.ceil(a)}function pm(a){if(!a)return [];let e=[];for(let t of a)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function um(a,e,t){let i=pm(a.Points);if(i.length===0)return t;let n=null,s=null,o=null;for(let c of i)(o===null||c.AtStep>o.AtStep)&&(o=c),c.AtStep<=e&&(n===null||c.AtStep>=n.AtStep)&&(n=c),c.AtStep>e&&(s===null||c.AtStep<s.AtStep)&&(s=c);if(n===null)return t;if(s===null){let c=a.TailGrowthRate??0;return c===0?o.Value:o.Value*Math.pow(1+c,e-o.AtStep)}switch(a.Interpolation??"Step"){case "Linear":{let c=(e-n.AtStep)/(s.AtStep-n.AtStep);return n.Value+c*(s.Value-n.Value)}case "Geometric":{if(n.Value<=0||s.Value<=0){let d=(e-n.AtStep)/(s.AtStep-n.AtStep);return n.Value+d*(s.Value-n.Value)}let c=(e-n.AtStep)/(s.AtStep-n.AtStep);return n.Value*Math.pow(s.Value/n.Value,c)}default:return n.Value}}var _v={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Ga=zod.z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),Kv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},Qv=zod.z.enum(["Top","Bottom","Left","Right"]).catch("Top"),Hv=zod.z.object({PlacementID:zod.z.string().nullish(),Type:Ga.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(),$v=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(),Jv=zod.z.object({CooldownSeconds:zod.z.number().nullish(),MinSessionTimeBeforeFirstSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),Zv=zod.z.object({Enabled:zod.z.boolean().nullish(),Position:Qv.nullish(),RefreshIntervalSeconds:zod.z.number().nullish()}).passthrough(),Yv=zod.z.object({Enabled:zod.z.boolean().nullish(),CooldownSeconds:zod.z.number().nullish(),DailyImpressionCap:zod.z.number().nullish()}).passthrough(),Xv=zod.z.object({MaxImpressionsPerHour:zod.z.number().nullish(),MaxImpressionsPerDay:zod.z.number().nullish(),MaxImpressionsPerSession:zod.z.number().nullish()}).passthrough(),eI=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(),tI=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(),iI=zod.z.object({RequireServerSideVerification:zod.z.boolean().nullish(),PendingRequestTtlSeconds:zod.z.number().nullish(),MaxPendingRequestsPerUser:zod.z.number().nullish()}).passthrough(),nI=zod.z.object({AndroidUnitID:zod.z.string().nullish(),IosUnitID:zod.z.string().nullish(),WebUnitID:zod.z.string().nullish(),Type:Ga.nullish()}).passthrough(),sI={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},rI=zod.z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),oI=zod.z.object({ProviderID:zod.z.string().nullish(),Kind:rI.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(),nI).nullish()}).passthrough();zod.z.object({Enabled:zod.z.boolean().nullish(),Placements:zod.z.record(zod.z.string(),Hv).nullish(),Providers:zod.z.record(zod.z.string(),oI).nullish(),RewardedVideo:$v.nullish(),Interstitial:Jv.nullish(),Banner:Zv.nullish(),AppOpen:Yv.nullish(),FrequencyCapping:Xv.nullish(),PremiumAdReductions:zod.z.array(eI).nullish(),Consent:tI.nullish(),Verification:iI.nullish()}).passthrough();var aI=zod.z.object({RewardedVideoCredit:zod.z.number().nullish(),TotalEarned:zod.z.number().nullish(),TotalSpent:zod.z.number().nullish()}).passthrough(),lI=zod.z.object({PlacementID:zod.z.string().nullish(),LastShownAt:u.nullish(),LastCompletedAt:u.nullish(),TotalImpressions:zod.z.number().nullish(),TotalCompletions:zod.z.number().nullish(),ConsecutiveFailures:zod.z.number().nullish()}).passthrough(),uI=zod.z.object({Date:u.nullish(),ImpressionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),CompletionsByPlacement:zod.z.record(zod.z.string(),zod.z.number()).nullish(),TotalImpressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish(),AppOpenImpressions:zod.z.number().nullish(),CreditsEarnedToday:zod.z.number().nullish()}).passthrough(),cI=zod.z.object({SessionID:zod.z.string().nullish(),SessionStartAt:u.nullish(),Impressions:zod.z.number().nullish(),InterstitialImpressions:zod.z.number().nullish(),RewardedCompletions:zod.z.number().nullish()}).passthrough(),pI=zod.z.object({PersonalizedAdsConsent:zod.z.boolean().nullish(),TrackingConsent:zod.z.boolean().nullish(),PolicyVersion:zod.z.string().nullish(),Region:zod.z.string().nullish(),ConsentGivenAt:u.nullish(),ConsentRevokedAt:u.nullish()}).passthrough(),dI=zod.z.object({RequestID:zod.z.string().nullish(),PlacementID:zod.z.string().nullish(),ProviderID:zod.z.string().nullish(),Type:Ga.nullish(),IssuedAt:u.nullish(),ExpiresAt:u.nullish(),CreditsToAward:zod.z.number().nullish()}).passthrough(),hI=zod.z.object({InvalidSsvCount:zod.z.number().nullish(),OrphanCompletions:zod.z.number().nullish(),FastCompletions:zod.z.number().nullish(),LastFlaggedAt:u.nullish()}).passthrough();zod.z.object({Credits:aI.nullish(),Placements:zod.z.record(zod.z.string(),lI).nullish(),Daily:uI.nullish(),Session:cI.nullish(),LastImpressionAt:u.nullish(),LastInterstitialAt:u.nullish(),LastRewardedAt:u.nullish(),LastAppOpenAt:u.nullish(),TotalImpressions:zod.z.number().nullish(),TotalRewardedCompletions:zod.z.number().nullish(),AdsDisabledUntil:u.nullish(),Consent:pI.nullish(),PendingRequests:zod.z.record(zod.z.string(),dI).nullish(),FraudFlags:hI.nullish(),UpdatedAt:u.nullish()}).passthrough();var dm="idos_device_id",Wr=class{storage;constructor(e=new ei){this.storage=e;}getPlatform(){return "Web"}getFullURL(){return ""}getStartParameter(){return null}getTelegramInitDataRaw(){return null}getDeviceID(){let e=this.storage.getString(dm);return e||(e="noop-device",this.storage.setString(dm,e)),e}getDeviceModel(){return "Noop"}shareLink(){}openInvoice(){}async showAd(){}async copyToClipboard(){}};
2
2
  exports.AIAction=qe;exports.AIErrorCode=Oy;exports.AIGenerationStatus=Ft;exports.AIModality=Ot;exports.AcquisitionCapture=Lt;exports.AdProviderKind=sI;exports.AdType=_v;exports.AnalyticsAction=ua;exports.AnalyticsDropReason=bx;exports.AnalyticsEventNaming=la;exports.AnalyticsLimits=Rt;exports.AttackOutcome=JD;exports.AuthType=Te;exports.AuthenticationAction=Oe;exports.AutomaticEvent=Bt;exports.BannerPosition=Kv;exports.BlockchainAction=_e;exports.BlockchainNetworkType=wC;exports.BlockchainOperationCategory=Xc;exports.BlockchainTransactionStatus=NC;exports.BlockchainTransactionType=EC;exports.BodyPart=mS;exports.BoostWindowKind=ND;exports.BrowserPlatformAdapter=ii;exports.BrowserStorage=Xt;exports.CharacterAction=Ne;exports.ChatAction=We;exports.ChatAuthorType=Dg;exports.ChatBlockedTermAction=xg;exports.ChatChannelType=gg;exports.ChatDirectAudience=Cg;exports.ChatPartitioning=yg;exports.ChatReportReason=vg;exports.ClientPlatform=ht;exports.CloudCodeAction=Ea;exports.CloudCodeErrorCode=ZP;exports.CloudCodeLogLevel=$P;exports.CloudCodeRevisionSelection=HP;exports.CollectionAction=Ve;exports.CommissionSink=US;exports.CommunityChestMemberStatus=wP;exports.CommunityChestStatus=AP;exports.CommunityCreatorStatus=Hb;exports.CommunityMarketingAction=Kt;exports.CommunityMetricKind=Jb;exports.CommunityParticipationMode=Kb;exports.CommunityPayoutCurrencyKind=$b;exports.ConversionRateMode=SC;exports.CoopEventAction=pt;exports.CoopGroupStatus=_y;exports.CoopMemberStatus=Ky;exports.CraftAction=mr;exports.CraftInputSelectionMode=uD;exports.CraftOutputLevelMode=aD;exports.CraftOutputLevelOverflow=pD;exports.CraftType=oD;exports.CurrencyAction=xs;exports.CurrencyStatus=CC;exports.CurrencyType=lt;exports.CurveInterpolation=Lm;exports.CurveShape=Bm;exports.CustomDataBucket=Pt;exports.CustomDataValueType=uC;exports.CustomDataWriter=rC;exports.DEFAULT_BASE_URL=Va;exports.DataAccessMode=ex;exports.DataCollectionKind=JS;exports.DataCollectionSchemaMode=lx;exports.DataCollectionsAction=yx;exports.DataCounterKind=sx;exports.DataFieldType=YS;exports.DataFieldVisibility=XS;exports.DataOwnerDeletedPolicy=ox;exports.DataRefKind=ix;exports.DealComparisonOperator=cR;exports.DealNodeRuntimeStatus=iR;exports.DealNodeType=uR;exports.DealOfferAction=gt;exports.DealOfferActivationStatus=tR;exports.EVENT_NAME_PATTERN=Es;exports.EnvelopeType=VP;exports.EventTokenType=Dm;exports.ExperimentAction=da;exports.ExperimentGoalKind=Ox;exports.FRIENDS_FROM_PLATFORM=tC;exports.FodderSelectionMode=Kx;exports.FodderValuationMode=Wx;exports.FriendActionStatus=FR;exports.FriendSource=jR;exports.GameLoopAction=Ue;exports.IDosGamesClient=jr;exports.IapProductType=rb;exports.IapPurchaseStatus=Cb;exports.IapStoreValues=bm;exports.ItemAction=Ws;exports.KycStatus=BC;exports.KycTier=LC;exports.LeaderboardAction=Ge;exports.LocalizationAction=Vs;exports.LocalizationMissingKeyMode=Gx;exports.LootboxAction=Xs;exports.MAILBOX_COUNTER_CAP=OR;exports.MailboxAction=Ye;exports.MailboxCategory=zR;exports.MailboxErrors=MR;exports.MailboxLetterSource=TR;exports.MailboxRewardModule=AR;exports.MarketGoodsType=zs;exports.MarketOfferStatus=OS;exports.MarketOfferType=MS;exports.MarketplaceAction=ve;exports.MatchAction=yt;exports.MatchStatus=fS;exports.MemoryStorage=ei;exports.MultiplayerAction=Ke;exports.MultiplayerChatMode=LP;exports.MultiplayerTopology=qP;exports.NoopPlatformAdapter=Wr;exports.OFFER_NOT_IN_ROTATION=fg;exports.PLATFORM_ORIGINS=Pi;exports.PlatformFriendsMode=nC;exports.PlatformProfileMode=iC;exports.PlayAccessMode=$C;exports.PlayerExperimentStatus=Bx;exports.PlaytimeTracker=xi;exports.PremiumAction=Wt;exports.PurchaseAction=_t;exports.PushAction=hi;exports.PushPermissionState=bt;exports.PushTopic=Gg;exports.PushTransport=qg;exports.QuestAction=ct;exports.QuestObjectiveSource=$m;exports.QuestPrerequisiteMode=Zm;exports.QuestStatus=Km;exports.RaidMode=HD;exports.ReferralAction=Qt;exports.ResourceEntryType=Li;exports.RewardAction=It;exports.RoomVisibility=GP;exports.SKIN_ALREADY_OWNED=My;exports.SKIN_SLOT=Po;exports.ScheduleMode=Pm;exports.SeasonAction=wt;exports.SocialAction=ge;exports.SocialContentStatus=HR;exports.SocialEntityType=_R;exports.SocialInboxVerb=$R;exports.SocialReactionKind=KR;exports.SocialReportReason=QR;exports.SpecialChoiceMode=$D;exports.StoreAction=Vt;exports.StoreRotationMode=Yf;exports.StoreType=nb;exports.TimedBoostAction=$t;exports.TimedBoostStackingPolicy=AD;exports.TimedEventAction=rt;exports.TitleAction=Jt;exports.TitleCustomDataAction=Ei;exports.TitleDataBucket=jD;exports.TitleDataScope=FD;exports.TradeOfferStatus=yD;exports.TransactionDirection=VC;exports.TutorialAction=nt;exports.TutorialBoardAction=hf;exports.TutorialFlowStatus=cf;exports.TutorialGateMode=Am;exports.TutorialRestartPolicy=lf;exports.TutorialScriptModule=df;exports.TutorialStepCompletionMode=of;exports.TypedEmitter=Si;exports.UserAction=at;exports.UserCustomDataAction=dt;exports.WalletGateBalanceSource=KC;exports.WalletLinkType=OC;exports.WorkshopAccessMode=tv;exports.WorkshopAccessVia=dv;exports.WorkshopAction=je;exports.WorkshopContentStatus=lv;exports.WorkshopHoldingMatch=sv;exports.WorkshopHoldingMode=iv;exports.WorkshopLicenseSource=cv;exports.WorkshopSort=pv;exports.WorkshopVisibility=ov;exports.beginSsoRedirect=Mv;exports.claimedMilestoneIDs=Nv;exports.createIDosGamesClient=kv;exports.curveMultiplier=Fv;exports.defineView=Ef;exports.describeUserAgent=Xp;exports.evaluateCurve=cm;exports.grantedPremiumTiers=Vv;exports.isAIGenerationTerminal=Ii;exports.isCurveConfigured=jv;exports.isFail=Im;exports.isMilestoneClaimed=Gv;exports.isOk=vm;exports.isPlatformParentOrigin=Vg;exports.isReservedSlot=xy;exports.normalizeBlockchainCategory=Ds;exports.parseAIErrorCode=Uy;exports.readSsoCodeFromUrl=wv;exports.roundAmount=Wv;exports.where=Cx;exports.zPaymentProof=$f;exports.zPriceOption=Ul;exports.zPriceOptions=oe;