@idosgames/core 0.21.3 → 0.21.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/dist/{RealtimeSession-wV_8qMas.d.cts → RealtimeSession-BBJ3gAb8.d.cts} +1 -1
- package/dist/{RealtimeSession-C5VICo95.d.ts → RealtimeSession-D7evucmN.d.ts} +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/realtime/index.d.cts +2 -2
- package/dist/realtime/index.d.ts +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {e,d,l,m,f}from'./chunk-YEBYHDZG.js';export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,n as NoopPlatformAdapter,h as PLATFORM_BRIDGE_ACK,f as PLATFORM_ORIGINS,i as PLATFORM_PAGE_UNAVAILABLE,k as PLATFORM_TOPUP_MESSAGES,j as askPlatformPage,l as canUsePlatformTopUp,g as isPlatformParentOrigin,m as requestPlatformTopUp}from'./chunk-YEBYHDZG.js';import {b,a,c as c$1}from'./chunk-CS7ACWDY.js';export{e as isFail,d as isOk}from'./chunk-CS7ACWDY.js';import {z}from'zod';import Nt from'decimal.js';var Ci=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,s=>{i(),t(s);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let s of [...i])s(t);}removeAllListeners(){this.listeners.clear();}};function Im(){let o=new Map;return {get:e=>o.get(e)??null,set:(e,t)=>{o.set(e,t);},remove:e=>{o.delete(e);}}}function ja(){return vm()??Im()}function vm(){try{let o=globalThis.localStorage;if(!o)return null;let e="__idos_probe__";return o.setItem(e,"1"),o.removeItem(e),{get:t=>{try{return o.getItem(t)}catch{return null}},set:(t,i)=>{try{o.setItem(t,i);}catch{try{o.removeItem(t);}catch{}}},remove:t=>{try{o.removeItem(t);}catch{}}}}catch{return null}}var Na="https://api.idosgames.com";function _a(o){return {titleID:o.titleID,titleTemplateID:o.titleTemplateID??"default",buildKey:o.buildKey??"",baseUrl:(o.baseUrl??Na).replace(/\/+$/,""),devBuild:o.devBuild??false,debugLogging:o.debugLogging??false,configStorage:o.configStorage??ja(),locale:o.locale??Tm(),appVersion:o.appVersion??""}}function Tm(){try{return globalThis.navigator?.language??""}catch{return ""}}var Kr="idos_acq",Wa=["gclid","fbclid","ttclid","msclkid","yclid"],km=["ref","r"],zm=["ref_","ref-","ref=","r_","r-"];var Vt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();Am(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=Om(this.platform.getDeviceModel());return s&&(i.OsVersion=s),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(Kr);}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=Ha(Qa(t));if(i)return i}return qi(t)}readFromEnvironment(){let e={},t=Qa(this.platform.getFullURL());Ft(e,"UtmSource",t.get("utm_source")),Ft(e,"UtmMedium",t.get("utm_medium")),Ft(e,"UtmCampaign",t.get("utm_campaign")),Ft(e,"UtmTerm",t.get("utm_term")),Ft(e,"UtmContent",t.get("utm_content")),Ft(e,"ClaimToken",t.get("idos_click"));for(let C of Wa){let j=t.get(C);if(j){e.ClickID=j;break}}let i=this.platform.getStartParameter()??"",s=Mm(i);if(s){for(let C of wm)Ft(e,C,s.get($a[C])??null);for(let C of Wa){let j=s.get(C);if(j){e.ClickID=j;break}}}let n=qi(s?s.get("ref")??s.get("r")??"":i),r=Ha(t),p=n||r;p&&(e.ReferralCode=p,e.ChannelHint=n?"telegram":"query");let d=this.platform.getReferrer?.();return d&&(e.Referrer=d),e}read(){try{let e=this.platform.storage.getString(Kr);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(Kr,JSON.stringify(e));}catch{}}};function Am(o){return !!(o.UtmSource||o.UtmMedium||o.UtmCampaign||o.ClickID||o.Referrer||o.ReferralCode||o.ClaimToken)}function Ft(o,e,t){t&&(o[e]=t);}var Ka="a1_",$a={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},wm=Object.keys($a);function Mm(o){let e=(o||"").trim();if(!e.startsWith(Ka))return null;let t=e.slice(Ka.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),n=Uint8Array.from(s,d=>d.charCodeAt(0)),r=new TextDecoder().decode(n),p=new URLSearchParams(r);return [...p.keys()].length>0?p:null}catch{return null}}function Qa(o){try{let e=o.indexOf("?");return new URLSearchParams(e>=0?o.slice(e):"")}catch{return new URLSearchParams}}function Ha(o){for(let e of km){let t=o.get(e);if(t)return qi(t)}return null}function qi(o){let e=(o||"").trim();if(!e)return null;for(let t of zm)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function Om(o){let e=o||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var Ja="idos_usage_pending",Za="idos_usage_session",Ya="idos_usage_closed_session",Xa="idos_usage_new_session",el="idos_usage_last_activity",Si=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=typeof document<"u"&&document.visibilityState==="hidden",this.timer=setInterval(()=>this.tick(),200*1e3),window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide)),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();}};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,i=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,i,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(Ja),this.currentSessionSeconds=this.readNumber(Za),this.pendingClosedSessionSeconds=this.readNumber(Ya),this.isNewSessionPending=this.readNumber(Xa)!==0;let e=this.readNumber(el);this.currentSessionSeconds>0&&e>0&&(Date.now()-e)/1e3>=1800&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,Math.floor(this.currentSessionSeconds)),this.currentSessionSeconds=0);}persist(){this.writeNumber(Ja,this.pendingSeconds),this.writeNumber(Za,this.currentSessionSeconds),this.writeNumber(Ya,this.pendingClosedSessionSeconds),this.writeNumber(Xa,this.isNewSessionPending?1:0),this.writeNumber(el,Date.now());}readNumber(e){let t=this.ctx.platform.storage.getString(e),i=t?Number(t):0;return Number.isFinite(i)&&i>0?i:0}writeNumber(e,t){try{this.ctx.platform.storage.setString(e,String(Math.floor(t)));}catch{}}};var ut={Virtual:"Virtual",Crypto:"Crypto"},ii=z.enum(["Virtual","Crypto"]).catch("Virtual"),Bi={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase"},si=z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase"]).catch("Item"),mt={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Li=z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),Um={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Gi=z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),Em={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Fi=z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),qm={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},xi=z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),Ae={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function il(){let o=globalThis,e=o.Capacitor?.getPlatform?.();if(e)return tl(e);let t=o.cordova?.platformId;return t?tl(t):o.navigator?.userAgent??""?mt.Web:mt.Unknown}function tl(o){let e=o.toLowerCase();return e==="android"?mt.Android:e==="ios"?mt.Ios:e==="web"?mt.Web:mt.Unknown}var _=z.union([z.number(),z.string()]).transform((o,e)=>{let t=typeof o=="string"?Number(o):o;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(o)}`}),z.NEVER)}),Y=z.union([z.number(),z.string()]).transform((o,e)=>{let t=typeof o=="number"?String(o):o.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid decimal: ${String(o)}`}),z.NEVER):t}),c=z.string();var Qr=z.object({Type:si.nullish(),CurrencyID:z.string().nullish(),Amount:_.nullish(),AmountUsd:z.number().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ProductID:z.string().nullish()}),Bm=z.object({Type:Fi.nullish(),EntityID:z.string()}),Lm=z.object({Address:Bm.nullish(),Amount:_.nullish(),Source:z.string().nullish()}),ae=z.object({Entries:z.array(Qr).nullish(),EventTokens:z.array(Lm).nullish()}),sl=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Resources:ae.nullish()}),H=z.object({Standard:ae.nullish(),PremiumBonuses:z.array(z.unknown()).nullish(),PremiumTiers:z.array(sl).nullish()}),St=z.object({Standard:ae.nullish(),PremiumDiscounts:z.array(z.unknown()).nullish(),PremiumTiers:z.array(sl).nullish()}),M=z.object({Grant:H.nullish(),Consume:St.nullish()}),xt=z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Transferred:ae.nullish()});var Gm=z.object({ExperimentID:z.string().nullish(),Variants:z.array(z.string()).nullish()}).passthrough(),Fm={Completed:"Completed",Started:"Started",StepReached:"StepReached"},Vm=z.object({FlowIDs:z.array(z.string()).nullish(),Mode:z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:z.string().nullish(),Negate:z.boolean().nullish(),SkippedCountsAsCompleted:z.boolean().nullish()}).passthrough(),J=z.object({Segments:z.array(z.string()).nullish(),MinPremiumTier:z.number().nullish(),RequiredPremiumIDs:z.array(z.string()).nullish(),MinLevel:z.number().nullish(),MaxLevel:z.number().nullish(),Countries:z.array(z.string()).nullish(),RegisteredWithinDays:z.number().nullish(),ActiveWithinDays:z.number().nullish(),Experiment:Gm.nullish(),Tutorial:Vm.nullish(),Platforms:z.array(Li).nullish()}).passthrough();var ye=z.object({TotalCap:z.number().nullish(),DailyCap:z.number().nullish(),DailyWeightCap:z.number().nullish(),PerActivationCap:z.number().nullish(),CooldownSeconds:z.number().nullish(),MaxPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish()}).passthrough();var jm=z.object({OffsetSecondsFromParentStart:z.number().nullish(),DurationSeconds:z.number().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Nm=z.object({StartUtc:z.string().nullish(),EndUtc:z.string().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),_m=z.object({AnchorUtc:z.string().nullish(),MaxCycles:z.number().nullish(),PauseBetweenPhasesSec:z.number().nullish(),PauseBetweenCyclesSec:z.number().nullish()}).passthrough();z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();var Wm=z.object({Reset:z.string().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:z.string().nullish(),PauseBetweenCyclesSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();z.object({SourceType:z.string().nullish(),TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),Outcome:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough();var st=z.object({SourceType:z.string().nullish(),BaseWeight:z.number().nullish(),ScaleWithRollMultiplier:z.boolean().nullish(),TileTypeFilter:z.array(z.string()).nullish(),TileIndexFilter:z.array(z.number()).nullish(),ChanceOutcomeFilter:z.array(z.string()).nullish(),OutcomeFilter:z.array(z.string()).nullish(),Params:z.record(z.string(),z.string()).nullish(),Limits:ye.nullish()}).passthrough(),me=z.object({Mode:z.string().nullish(),IsActive:z.boolean().nullish(),Scheduled:Nm.nullish(),Chain:_m.nullish(),Cyclic:Wm.nullish(),ActivationTriggers:z.array(st).nullish(),Relative:jm.nullish()}).passthrough();var Km={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},Qm=z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Hm={Step:"Step",Linear:"Linear",Geometric:"Geometric"},$m=z.enum(["Step","Linear","Geometric"]).catch("Step"),Jm=z.object({AtStep:z.number().nullish(),Value:z.number().nullish()}).passthrough(),Fe=z.object({Base:z.number().nullish(),Shape:Qm.nullish(),PerStep:z.number().nullish(),PerStepRate:z.number().nullish(),GrowthRate:z.number().nullish(),Points:z.array(Jm).nullish(),Interpolation:$m.nullish(),TailGrowthRate:z.number().nullish(),MinResult:z.number().nullish(),MaxResult:z.number().nullish()}).passthrough();var Zm=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Rewards:H.nullish()}).passthrough(),Ym=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Multiplier:z.number().nullish()}).passthrough(),Hr=z.object({Bundles:z.array(Zm).nullish(),Multipliers:z.array(Ym).nullish()}).passthrough();var Xm=z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Vi=z.object({Source:Xm.nullish(),SourceKey:z.string().nullish(),Curve:Fe.nullish(),Anchor:z.number().nullish(),IncludeRewards:ae.nullish(),ExcludeRewards:ae.nullish()}).passthrough(),nl=z.object({ClaimedAt:z.string().nullish(),PremiumTiers:z.array(z.string()).nullish(),Unlocked:z.boolean().nullish()}).passthrough(),Be=z.object({MilestoneID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredProgress:z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:Hr.nullish(),SortOrder:z.number().nullish(),IsFeatured:z.boolean().nullish()}).passthrough(),ni=z.object({Milestones:z.record(z.string(),Be).nullish()}).passthrough();var K=z.object({PresetID:z.string().nullish(),Remove:z.array(z.string()).nullish()}).passthrough();var ef=z.object({TargetCurrencyID:z.string().nullish(),Rate:z.number().nullish(),MaxConvertAmount:z.number().nullish()}).passthrough(),jt=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxBalance:z.number().nullish(),MaxPerGrant:z.number().nullish(),DailyEarnCap:z.number().nullish(),BurnOnEventEnd:z.boolean().nullish(),BurnConversion:ef.nullish()}).passthrough();var tf=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),rl=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:tf.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Q=z.object({ChangedInstances:z.record(z.string(),rl).nullish(),RemovedInstanceIDs:z.array(z.string()).nullish()});var Pe=o=>z.object({Id:z.string(),Success:z.boolean(),Error:z.string().nullish(),Data:o.nullish()}),ft=o=>z.object({ServerTimeUtc:c,Items:z.array(Pe(o)),Resources:M.nullish(),Inventory:Q.nullish()});var sf={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},ol=z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),nf=z.object({}).passthrough().transform(o=>o),rf=z.object({CycleID:z.string(),InstanceKey:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),CycleStartUtc:c.nullish(),CycleEndUtc:c.nullish(),PointsTotalEarned:_.nullish(),PointsCurrent:_.nullish(),ClaimedPointMilestoneIDs:z.array(z.string()).nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),$r=z.object({QuestID:z.string(),CycleID:z.string().nullish(),ObjectiveID:z.string().nullish(),NewValue:_.nullish(),ObjectiveCompleted:z.boolean().nullish(),Status:ol}),al=z.object({State:nf.nullish(),PointsTracks:z.record(z.string(),rf).nullish()}),Jr=z.object({ServerTimeUtc:c,QuestID:z.string(),CycleID:z.string().nullish(),NewStatus:ol.nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Zr=z.object({ServerTimeUtc:c,CycleID:z.string(),MilestoneID:z.string(),PointsTotalEarned:_.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),ll=z.object({ServerTimeUtc:c,CycleID:z.string(),GroupCompletionID:z.string(),GroupID:z.string().nullish(),CompletedGroupQuests:z.number().nullish(),RequiredGroupQuests:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),ul=z.object({MetricID:z.string(),Updates:z.array($r).nullish()}),cl=z.array(Pe(Jr)),pl=z.array(Pe(Zr)),of={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},af=z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),lf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},uf=z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),hl=z.object({ObjectiveID:z.string().nullish(),Source:af.nullish(),MaxProgressPerCall:z.number().nullish(),MetricID:z.string().nullish(),Triggers:z.array(st).nullish(),TargetValue:z.number().nullish(),AggregationMethod:z.string().nullish()}).passthrough(),Yr=z.object({Milestones:K.nullish(),Linking:K.nullish(),Availability:K.nullish(),Reward:K.nullish(),Objectives:K.nullish()}).passthrough(),cf=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),dl=z.object({CycleIDs:z.array(z.string()).nullish(),GroupID:z.string().nullish(),PhaseIDs:z.array(z.string()).nullish(),RequiredQuestIDs:z.array(z.string()).nullish(),PrerequisiteMode:uf.nullish()}).passthrough(),ml=z.object({Schedule:me.nullish(),AccrueProgressWhenLocked:z.boolean().nullish(),Gate:J.nullish(),Limits:ye.nullish()}).passthrough(),fl=z.object({Grant:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),pf=z.object({QuestID:z.string().nullish(),Identity:cf.nullish(),Linking:dl.nullish(),Availability:ml.nullish(),Objectives:z.record(z.string(),hl).nullish(),Reward:fl.nullish(),Presets:Yr.nullish()}).passthrough(),hf=z.object({CompletionID:z.string().nullish(),GroupID:z.string().nullish(),RequiredCompletedQuests:z.number().nullish(),Gate:J.nullish(),Reward:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),df=z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Gate:J.nullish(),Milestones:z.record(z.string(),Be).nullish(),Presets:Yr.nullish(),PointsToken:jt.nullish()}).passthrough(),mf=z.object({Milestones:z.record(z.string(),ni).nullish(),Linking:z.record(z.string(),dl).nullish(),Availability:z.record(z.string(),ml).nullish(),Reward:z.record(z.string(),fl).nullish(),Objectives:z.record(z.string(),z.record(z.string(),hl)).nullish()}).passthrough(),ff=z.object({CycleID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:me.nullish(),Milestones:z.record(z.string(),Be).nullish(),Gate:J.nullish(),PointsToken:jt.nullish(),GroupCompletions:z.record(z.string(),hf).nullish(),Phases:z.record(z.string(),df).nullish(),Presets:Yr.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Ni=z.object({Cycles:z.record(z.string(),ff).nullish(),Quests:z.record(z.string(),pf).nullish(),Presets:mf.nullish()}).passthrough(),pt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var gf={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},yf=z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),Rf={Never:"Never",OnRequest:"OnRequest",Always:"Always"},Cf=z.enum(["Never","OnRequest","Always"]).catch("Never"),Sf={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},xf=z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),bf={GameLoop:"GameLoop"},Df={Raid:"Raid",Attack:"Attack"},Pf=z.object({Title:z.string().nullish(),TitleKey:z.string().nullish(),Body:z.string().nullish(),BodyKey:z.string().nullish(),AnchorID:z.string().nullish(),HighlightTarget:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),UiHint:z.record(z.string(),z.string()).nullish()}).passthrough(),If=z.object({Mode:yf.nullish(),Triggers:z.array(st).nullish(),TargetValue:z.number().nullish(),RequireAllTriggers:z.boolean().nullish()}).passthrough(),vf=z.object({Grant:H.nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),Tf=z.object({TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),RandomActionType:z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),kf=z.object({Module:z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:Tf.nullish(),MaxUses:z.number().nullish()}).passthrough(),zf=z.object({Skippable:z.boolean().nullish(),TimeoutSeconds:z.number().nullish()}).passthrough(),Xr=z.object({StepID:z.string().nullish(),Order:z.number().nullish(),Identity:Pf.nullish(),Completion:If.nullish(),Effects:vf.nullish(),Script:kf.nullish(),Policy:zf.nullish()}).passthrough(),Af=z.object({DisplayName:z.string().nullish(),DisplayNameKey:z.string().nullish(),Description:z.string().nullish(),DescriptionKey:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),gl=z.object({Schedule:me.nullish(),Gate:J.nullish(),RequiredFlowIDs:z.array(z.string()).nullish(),AutoStart:z.boolean().nullish(),StartTrigger:st.nullish()}).passthrough(),yl=z.object({Skippable:z.boolean().nullish(),SkippableFromOrder:z.number().nullish(),RestartPolicy:Cf.nullish(),ExpireAfterSeconds:z.number().nullish(),IsBlocking:z.boolean().nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),Rl=z.object({Grant:H.nullish(),AutoClaim:z.boolean().nullish()}).passthrough(),wf=z.object({Availability:K.nullish(),Policy:K.nullish(),Reward:K.nullish(),Steps:K.nullish()}).passthrough(),Mf=z.object({FlowID:z.string().nullish(),Identity:Af.nullish(),Availability:gl.nullish(),Policy:yl.nullish(),Steps:z.record(z.string(),Xr).nullish(),Reward:Rl.nullish(),Presets:wf.nullish()}).passthrough(),Of=z.object({BlockingFlowIDs:z.array(z.string()).nullish(),BlockedModules:z.array(z.string()).nullish(),BlockedActions:z.record(z.string(),z.array(z.string())).nullish(),BlockBeforeStart:z.boolean().nullish(),SkipLiftsBlock:z.boolean().nullish()}).passthrough(),Uf=z.object({IsEnabled:z.boolean().nullish(),MaxActiveFlows:z.number().nullish(),Blocking:Of.nullish()}).passthrough(),Ef=z.object({Availability:z.record(z.string(),gl).nullish(),Policy:z.record(z.string(),yl).nullish(),Reward:z.record(z.string(),Rl).nullish(),Steps:z.record(z.string(),z.record(z.string(),Xr)).nullish()}).passthrough(),Cl=z.object({Flows:z.record(z.string(),Mf).nullish(),Settings:Uf.nullish(),Presets:Ef.nullish()}).passthrough(),qf=z.object({}).passthrough().transform(o=>o),Sl=z.object({FlowID:z.string(),Status:xf,CurrentStepID:z.string().nullish(),CurrentStep:Xr.nullish(),TotalSteps:z.number(),CompletedSteps:z.number(),CanSkip:z.boolean(),RewardClaimed:z.boolean(),RewardPending:z.boolean(),VariantID:z.string().nullish()}).passthrough(),_i=z.object({State:qf.nullish(),Flows:z.array(Sl).nullish(),UnlockedFeatures:z.array(z.string()).nullish()}).passthrough(),At=z.object({Flow:Sl.nullish()}).passthrough(),xl=z.object({FlowID:z.string().nullish(),Granted:M.nullish()}).passthrough(),bl=z.array(Pe(At)),Dl=z.object({FlowID:z.string(),StepID:z.string(),Progress:z.number(),Target:z.number(),Completed:z.boolean()}).passthrough(),nt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Wi(o){return Array.isArray(o)?o.filter(e=>e!==null).map(Wi):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).filter(([,e])=>e!==null).map(([e,t])=>[e,Wi(t)])):o}var Ki=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var Qi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Pl(o){return o===429||o>=500&&o<=599}function Hi(o,e=Math.random){let t=Math.min(500*Math.pow(2,o-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function wt(o){return new Promise(e=>setTimeout(e,o))}function Il(o,e=Math.random){let t=o<=1?1500:o===2?4e3:6e3;return t+t*.1*e()}var eo=15,vl=1e3,$i=class{constructor(e=eo,t=()=>Date.now(),i=wt){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 Bf=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function oi(o){if(!o)return null;let e=Bf.exec(o);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new Nt(i),r=new Nt(s),p=r.minus(Nt.max(n,0));return p.lte(0)?null:{currencyID:t,required:r.toNumber(),available:n.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var Lf=12e3,Gf=new Set(["RelatedEntityID"]);function Ff(o,e){if(e===null||typeof e!="object"||Array.isArray(e))return o;let t={};for(let[i,s]of Object.entries(e))Gf.has(i)||(t[i]=s);try{return `${o}|${JSON.stringify(t)}`}catch{return o}}var Vf=z.object({Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().optional(),QuestProgress:z.array($r).nullish(),TutorialProgress:z.array(Dl).nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish()}).passthrough(),Ji=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Qi;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new Ki(e.throttleMs),this.pacer=new $i(e.maxRequestsPerSecond??eo),this.clientPlatform=e.clientPlatform??mt.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,s={}){let n=s.throttleKey??Ff(e,t);if(!this.throttler.tryAcquire(n))return b("throttled","Throttled");if(!this.inflight.add(n))return b("throttled","Duplicate request skipped");this.raiseBusy();try{let r=`${this.baseUrl}/${e}`,p=JSON.stringify(t),d=s.ticket??null,C=s.silent??!1,j=s.timeoutMs??Lf,le=s.autoRetry??!0,Ie=!1,ge=!1,Me=0;for(;;){let kt;s.keepalive||await this.pacer.take();try{kt=await this.doFetch(r,p,d,j,s.keepalive??!1);}catch{if(le&&Me<3){Me++,await wt(Hi(Me));continue}return this.connectionFailure("Internet Connection Error",C)}let Ye=kt.status;if(Ye>=200&&Ye<300){let ce=!ge&&this.cryptoTopUpHandler!==null,De=await this.parseSuccess(kt,i,C,e,ce);if(!De.ok&&ce){let ue=oi(De.error);if(ue){if(ge=!0,await this.runTopUp(ue))continue;C||this.emitter.emit("error:global",De.error);}}return De}if(Ye===401){if(!Ie&&this.sessionRefreshHandler){Ie=!0;let ce=null;try{ce=await this.sessionRefreshHandler();}catch{ce=null;}if(ce){d=ce;continue}}return this.emitter.emit("auth:unauthorized",void 0),b("unauthorized","Unauthorized")}if(Pl(Ye)){if(le&&Me<3){Me++,await wt(Ye===429?Il(Me):Hi(Me));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Ye})`,C)}let yi="";try{yi=await kt.text();}catch{}if(Ye===409&&/operation in progress/i.test(yi)&&le&&Me<3){Me++,await wt(Hi(Me));continue}return this.handleWebError(yi,Ye,C)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let r=new AbortController,p=setTimeout(()=>{r.abort();},s);try{let d={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(d.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:d,signal:r.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,i,s,n=false){let r;try{r=await e.text();}catch{return this.globalError("Failed to read response body",i)}let p;try{p=JSON.parse(r);}catch{return this.globalError("JSON Parse Error",i)}let d=Vf.safeParse(p);if(!d.success)return this.globalError("Malformed response envelope",i);if(!d.data.Success){let ge=d.data.Error??"Server returned Success=false",Me=n&&oi(ge);return !i&&!Me&&this.emitter.emit("error:global",ge),b("server",ge)}let C=d.data.StateVersions;C&&Object.keys(C).length>0&&this.emitter.emit("user:stateVersions",{epoch:d.data.StateEpoch??null,versions:C});let j=d.data.QuestProgress;j&&j.length>0&&this.emitter.emit("quest:systemProgress",j);let le=d.data.TutorialProgress;le&&le.length>0&&this.emitter.emit("tutorial:systemProgress",le);let Ie=t.safeParse(d.data.Data);if(!Ie.success){let ge=t.safeParse(Wi(d.data.Data));ge.success&&(Ie=ge);}if(!Ie.success){let ge=`Validation error (${s}): ${Ie.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",ge),i||this.emitter.emit("error:global",ge),b("validation",ge)}return a(Ie.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let r=JSON.parse(e)?.Error;if(t===403&&r==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),b("server","PLAY_ACCESS_REQUIRED");s=typeof r=="string"&&r.length>0?`HTTP ${t}: ${r}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),b("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),b("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),b("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function ai(o){return (typeof o=="string"?o:o.toISOString()).slice(0,10)}function bi(o){return `${ai(o)}T00:00:00.000Z`}function Tl(o){let e=new Date(o);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function kl(o,e){return new Date(o.getTime()+e*6e4).toISOString()}function so(o,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;o.InventoryV2??={};let n=o.InventoryV2,r=i.toISOString(),p=new Map,d$1=new Map,C=new Map,j=new Map,le=new Map,Ie=new Map,ge=new Map,Me=new Map,kt=e.Grant?.PremiumTiers??[],Ye=kt.length;for(let ce=0;;ce++){let De,ue;if(ce===0)De=e.Grant?.Standard?.Entries,ue=false;else if(ce-1<Ye)De=kt[ce-1]?.Resources?.Entries,ue=false;else if(ce===1+Ye)De=e.Consume?.Standard?.Entries,ue=true;else break;if(De)for(let re of De){if(re.Type==null)continue;let pe=Math.max(0,re.Amount??0);if(!(pe<=0))switch(re.Type){case "VirtualCurrency":{if(!re.CurrencyID)continue;let he=ue?d$1:p;he.set(re.CurrencyID,(he.get(re.CurrencyID)??0)+pe);break}case "CryptoCurrency":{if(!re.CurrencyID)continue;let he=ue?j:C;he.set(re.CurrencyID,(he.get(re.CurrencyID)??new Nt(0)).plus(pe));break}case "Item":{if(!re.ItemID)continue;let he=Nf(t,re.CatalogID,re.ItemID),Se=(he?he.IsStackable??true:true)?ue?Ie:le:ue?Me:ge;Se.set(re.ItemID,(Se.get(re.ItemID)??0)+pe);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||d$1.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let ce of new Set([...p.keys(),...d$1.keys()])){let De=p.get(ce)??0,ue=d$1.get(ce)??0,re=De-ue,pe=n.VirtualCurrencies[ce];pe?(pe.Amount+=re,pe.UpdatedAt=r,pe.Daily&&ai(pe.Daily.PeriodStartUtc)===ai(i)?(pe.Daily.Earned+=De,pe.Daily.Spent+=ue):pe.Daily={PeriodStartUtc:bi(i),Earned:De,Spent:ue}):n.VirtualCurrencies[ce]={Amount:re,CreatedAt:r,UpdatedAt:r,Daily:{PeriodStartUtc:bi(i),Earned:De,Spent:ue}};}}if(s.ccChanged=C.size>0||j.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let ce of new Set([...C.keys(),...j.keys()])){let De=C.get(ce)??new Nt(0),ue=j.get(ce)??new Nt(0),re=De.minus(ue),pe=n.CryptoCurrencies[ce];pe?(pe.Amount=new Nt(pe.Amount).plus(re).toString(),pe.UpdatedAt=r):n.CryptoCurrencies[ce]={Amount:re.toString(),Frozen:"0",CreatedAt:r,UpdatedAt:r};}}if(s.itemsChanged=le.size>0||Ie.size>0||ge.size>0||Me.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let ce=n.UnstackableItems,De=new Set([...le.keys(),...Ie.keys(),...ge.keys(),...Me.keys()]);for(let ue of De){let re=(le.get(ue)??0)-(Ie.get(ue)??0),pe=(ge.get(ue)??0)-(Me.get(ue)??0),he=re+pe,it=n.Items[ue];it?(re!==0&&(it.StackableAmount+=re),pe!==0&&(it.UnstackableAmount+=pe),he!==0&&(it.TotalAmount+=he)):n.Items[ue]={StackableAmount:Math.max(0,re),UnstackableAmount:Math.max(0,pe),TotalAmount:Math.max(0,he)};}for(let[ue,re]of Me){if(re<=0)continue;let pe=Object.values(ce).filter(he=>he.ItemID===ue&&he.EquippedSlot==null&&(he.ExpiresAt==null||new Date(he.ExpiresAt)>i)).sort(jf).slice(0,re).map(he=>he.ItemInstanceID);for(let he of pe)delete ce[he];}for(let[ue,re]of ge){let pe=_f(t,ue);for(let he=0;he<re;he++){let it=d();ce[it]={ItemInstanceID:it,ItemID:ue,CatalogID:pe,RemainingUses:1,AcquiredAt:r};}}}o.EventToken??={};let yi=o.EventToken;for(let ce=0;;ce++){let De,ue;if(ce===0)De=e.Grant?.Standard?.EventTokens,ue=false;else if(ce-1<Ye)De=kt[ce-1]?.Resources?.EventTokens,ue=false;else if(ce===1+Ye)De=e.Consume?.Standard?.EventTokens,ue=true;else break;if(!(!De||De.length===0))for(let re of De){let pe=re.Address;if(!pe||pe.Type==null)continue;let he=re.Amount??0;if(he<=0)continue;let it=Wf(yi,pe.Type);if(!it)continue;let Se=it[pe.EntityID];Se||(Se={},it[pe.EntityID]=Se),Se.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Se.Daily??={Date:bi(i),TotalEarned:0},Se.Meta??={};let Ri=re.Source&&re.Source.length>0?re.Source:"CustomAction";ue?(Se.Balance.Current-=he,Se.Balance.TotalSpent+=he):(Se.Balance.Current+=he,Se.Balance.TotalEarned+=he,ai(Se.Daily.Date)!==ai(i)&&(Se.Daily={Date:bi(i),TotalEarned:0}),Se.Daily.TotalEarned+=he,Se.Daily.EarnedBySource??={},Se.Daily.EarnedBySource[Ri]=(Se.Daily.EarnedBySource[Ri]??0)+he,Se.Daily.TriggersBySource??={},Se.Daily.TriggersBySource[Ri]=(Se.Daily.TriggersBySource[Ri]??0)+1,Se.Daily.LastTriggerBySource??={},Se.Daily.LastTriggerBySource[Ri]=r,Se.Meta.JoinedAtUtc||(Se.Meta.JoinedAtUtc=r),Se.Meta.LastEarnedAtUtc=r),s.tokensChanged=true;}}return s}function jf(o,e){return o.AcquiredAt!==e.AcquiredAt?o.AcquiredAt<e.AcquiredAt?-1:1:o.ItemInstanceID===e.ItemInstanceID?0:o.ItemInstanceID<e.ItemInstanceID?-1:1}function Nf(o,e,t){let i=o?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let n=s.Items?.[t];if(n)return n}}}function _f(o,e){let t=o?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function Wf(o,e){switch(e){case "TimedEvent":return o.TimedEvent??={};case "Quest":return o.Quest??={};case "Leaderboard":return o.Leaderboard??={};case "CoopEvent":return o.CoopEvent??={};case "Season":return o.Season??={};default:return null}}function zl(o,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},n=new Set(t.RemovedInstanceIDs??[]),r=new Set;for(let d of Object.values(s))d?.ItemID&&r.add(d.ItemID);for(let d of n){let C=o[d]?.ItemID;C&&r.add(C);}if(r.size===0)return i;let p=d=>n.has(d)||d in s;if(e){for(let[d,C]of Object.entries(e))d in o||p(d)||C&&r.has(C.ItemID)&&i.drop.push(d);for(let[d,C]of Object.entries(o))d in e||p(d)||C&&r.has(C.ItemID)&&(i.restore[d]=C);}return i}function no(o,e){return o===e||o.startsWith(`${e}:`)}var Yi=class o{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){o.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];o.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){o.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let s=so(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let n=this.currentState,r={...n.InventoryV2?.UnstackableItems??{}},p=so(n,e,i,s),d=zl(r,n.InventoryV2?.UnstackableItems,t),C=Object.entries(t?.ChangedInstances??{}),j=t?.RemovedInstanceIDs??[],le=d.drop.length>0||Object.keys(d.restore).length>0||C.length>0||j.length>0;if(le){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let Ie=n.InventoryV2.UnstackableItems;for(let ge of d.drop)delete Ie[ge];for(let[ge,Me]of Object.entries(d.restore))Ie[ge]=Me;for(let[ge,Me]of C)Ie[ge]=Me;for(let ge of j)delete Ie[ge];}this.emitResourceChanges(p,le);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,r=t instanceof Nt?t:new Nt(t),p=s===void 0?new Nt(0):s instanceof Nt?s:new Nt(s),d=i??new Date().toISOString(),C=n[e];C?(C.Amount=new Nt(C.Amount).plus(r).toString(),p.isZero()||(C.Frozen=new Nt(C.Frozen??0).plus(p).toString()),C.UpdatedAt=d):n[e]={Amount:r.toString(),Frozen:p.toString(),CreatedAt:d,UpdatedAt:d},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,n=s[e];n||(n={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=n),n.TotalPurchases+=t,n.LastPurchasedAt=i,i>=n.DailyResetUtc?(n.DailyPurchases=t,n.DailyResetUtc=Tl(i)):n.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let n=new Date().toISOString();for(let r of t)r.RuleID&&(s.Pity[`${e}:${r.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:n});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let n=s.Cycles[t];if(!n)return;n.Quests??={};let r=n.Quests[e]??={QuestID:e,Status:i};r.Status=i,i==="Claimed"&&(r.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let n=s.PermanentQuests[e]??={QuestID:e,Status:i};n.Status=i,i==="Claimed"&&(n.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,n=t[s]??={};n.Balance??={Current:0,TotalEarned:0,TotalSpent:0},n.Balance.Current=i.PointsCurrent??0,n.Balance.TotalEarned=i.PointsTotalEarned??0,n.Milestone??={};for(let r of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(n.Milestone,r);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let n=s.Steps[i.StepID]??={StepID:i.StepID};n.Progress=i.Progress,i.Completed&&(n.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let n=t.Cycles[i.CycleID];if(!n)continue;n.Quests??={},s=n.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let n=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};n.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(n.Completed=true,n.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(no(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[n,r]of Object.entries(this.currentState.EventToken.TimedEvent))r&&((s?n!==s:!no(n,t))||this.markMilestoneClaimed(r.Milestone??(r.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let n=this.activeEventsCache?.ActiveEvents;if(n)for(let r of n)r.Type!==e||r.TimedEventID!==t||s&&r.TokenEntityID&&r.TokenEntityID!==s||(r.Progress??={},this.markMilestoneClaimed(r.Progress.Milestone??(r.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,s){if(!e)return;let n=this.ensureLeaderboardProgress(e);(n.ScoreCycleVersion??0)<s&&(n.ScoreEarnedThisCycle=0,n.ClaimedMilestoneIDs=[],n.BracketID=null),n.CurrentScore=t,n.ScoreEarnedThisCycle=(n.ScoreEarnedThisCycle??0)+i,n.ScoreCycleVersion=s,n.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let s=false;for(let n of Object.values(i))for(let r of Object.values(n.Equipment??{}))r?.ItemInstanceID===e&&(r.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[s,n]of Object.entries(e.ChangedInstances??{}))t[s]=n,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(i)){let n=i[s];n&&n.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,s,n){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let r=this.currentState.CustomData,p={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")r.Private??={},r.Private[t]=p;else if(e==="Public")r.Public??={},r.Public[t]=p;else return;r.Version=(r.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let s=i.BuildingStates.find(n=>n.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},n=s.PendingWithdrawals??[];t.size>0&&(n=n.filter(r=>!r.TitleTransactionID||!t.has(r.TitleTransactionID))),i&&!n.some(r=>r.TitleTransactionID===i.TitleTransactionID)&&(n=[...n,i]),s.PendingWithdrawals=n;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var Xi=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,i]of Object.entries(e))this.sections.has(t)||this.sections.set(t,i);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let i=this.config?.[e];return i??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var es=class{user;config;constructor(e){this.user=new Yi(e),this.config=new Xi;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function Kf(o){return o}var Qf=0,Hf=1500,$f=3,is=class{constructor(e,t,i=null,s="",n="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=s;this.loginMode=n;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return a(void 0);let i=Date.now(),s=[],n=[];for(let d of new Set(e)){let C=this.rules.get(d);if(C&&(t?.force||C.needsServer(i))){s.push(this.runRule(d,C));continue}(t?.force||!this.state.isStateFresh(d,t?.maxAgeMs))&&n.push(d);}let p=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(a(void 0))])).find(d=>!d.ok);return p&&!p.ok?p:a(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},Qf),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(s=>i=s);try{let s=this.state?await this.state.readStateSlice(e):a(void 0),n=s.ok?a(void 0):s;for(let r of t)r(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=ts(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let C=this.fresh(s,i?.maxAgeMs);if(C)return a(C.data);let j=this.loginFailures.get(s);if(j)return this.loginFailures.delete(s),j;let le=this.inflight.get(s);if(le)return le}let n=this.generation.get(s)??0,r=Date.now(),d=t().then(C=>{if(!C.ok)return C;let j=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:C.data,storedAt:j,expiresAt:ro(e,C.data,j)}),C;let le=this.entries.get(s);if(le&&le.storedAt>=r)return C;let Ie=ro(e,C.data,j);return this.entries.set(s,{data:C.data,storedAt:j,expiresAt:Math.min(Ie??1/0,j+Hf)}),C}).finally(()=>{this.inflight.get(s)===d&&this.inflight.delete(s);});return this.inflight.set(s,d),d}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let s=t.Key?t.Key:void 0,n=ts(i.view,s);if(!t.Success){this.loginFailures.set(n,b("server",t.Error??"View failed."));continue}let r=i.schema.safeParse(t.Data);r.success&&(this.loginFailures.delete(n),i.apply(r.data,s),this.put(i.view,r.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let n=Al({Name:s,Key:t});this.used.get(n)?.n!==this.session&&(this.used.set(n,{Name:s,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>$f||this.used.set(Al(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(ts(e,t))?.data}put(e,t,i){this.register(e);let s=ts(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:ro(e,t,n)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===i||s.startsWith(`${i}|`))&&this.drop(s);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let s=Date.now();if(!(i.expiresAt!==null&&s>=i.expiresAt)&&!(t!==void 0&&s-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(s=>t.has(s))&&this.invalidate(i);}};function ts(o,e){return e===void 0?o.key:`${o.key}|${e}`}function Al(o){return o.Key?`${o.Name}|${o.Key}`:o.Name}function ro(o,e,t){let i=o.expiresAt?.(e)??null,s=o.ttlMs!==void 0?t+o.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var ss=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 Jf(e)?e:Ae.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 Jf(o){return o!==null&&Object.values(Ae).includes(o)}var Zf=8,Yf=100,Xf=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,wl=["GameLoop"];function eg(o){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(o)}var ns=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=Ae.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let s=this.authContext;if(!s)return c$1;let n=this.baseRequest();n.UserID=s.userID,n.ClientSessionTicket=s.clientSessionTicket,n.WalletAddress=e,n.NetworkID=t,i&&(n.WalletSignature=i);let r=await this.ctx.api.authentication.linkWallet(n);return r.ok&&r.data.PlayAccess&&this.setPlayAccess(r.data.PlayAccess),r}async unlinkWallet(e){let t=this.authContext;if(!t)return c$1;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(i);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.platform.getDeviceID(),e.Device=this.ctx.platform.getDeviceModel(),e.Platform=this.ctx.platform.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(Ae.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return b("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(Ae.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let s=await this.ctx.api.authentication.loginWithEmail(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(Ae.Email);return n.ok&&this.keepEmailCredentials(e,t),n}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.platform.getDeviceID(),i.Device=this.ctx.platform.getDeviceModel(),i.Platform=this.ctx.platform.getPlatform();let s=await this.ctx.api.authentication.registerWithEmail(i);return s.ok?(this.pendingRegistration={email:e,password:t},a({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(Ae.Email);return n.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,n}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?a(void 0):i}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let i=await this.ctx.api.authentication.loginWithGoogle(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(Ae.Google)):i}async loginWithApple(e,t){if(!e?.trim())return b("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(Ae.Apple)):s}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=i,s.Platform=this.ctx.platform.getPlatform(),s.Device=this.ctx.platform.getDeviceModel(),s.DeviceID=this.ctx.platform.getDeviceID();let n=await this.ctx.api.authentication.loginWithWallet(s);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Ae.Wallet)):n}async loginWithSsoCode(e){if(!e)return b("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.platform.getDeviceID(),t.Device=this.ctx.platform.getDeviceModel(),t.Platform=this.ctx.platform.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(Ae.iDosGames)):i}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=i,this.ctx.api.authentication.resetPassword(s)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==Ae.None?e:Ae.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let s=await this.ctx.api.authentication.refreshSession(i);return s.ok?(this.applyRefresh(s.data),"ok"):(eg(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case Ae.Email:return this.loginWithEmail(t,i);case Ae.Device:case Ae.None:return this.loginWithDeviceID();case Ae.Telegram:return this.loginWithTelegram();default:return Promise.resolve(b("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==Ae.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===Ae.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&&Xf.test(e)}static isValidPasswordLength(e){return e.length>=Zf&&e.length<=Yf}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.sessionAuthType=Ae.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(wl,wl);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 tg="idos:cfg",li=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${Ml(t)}`:e&&e.length>0?`f:${Ml(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${tg}:${this.titleId}:${e}`}};function Ml(o){return [...o].map(e=>e.toLowerCase()).sort().join(",")}var Ol="idos:loc",ui=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[s,n]of Object.entries(t))typeof n=="number"&&n>0&&(i[s]=n);return i}catch{return {}}}async noteVersion(e,t){let i=await this.readVersions();i[e]!==t&&(i[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(i)));}keyOf(e){return `${Ol}:${this.titleId}:${e}`}versionsKey(){return `${Ol}:${this.titleId}:versions`}};var ig="idos:sec",rs=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 `${ig}:${this.titleId}`}};var sg="idos:state",os=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,s){if(!(!e||!t))try{let n={e:t,v:i,s};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}keyOf(e){return `${sg}:${this.titleId}:${e}`}};function ng(o,e){if(!o)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return o;let i={};for(let[s,n]of Object.entries(o))t.has(s.toLowerCase())||(i[s]=n);return i}function oo(o,e,t,i){let s={...o??{}};if(!e||!t||!i)return s;for(let[n,r]of Object.entries(t))i[n]===r&&n in e&&(s[n]=e[n]);return s}function rg(o){return {...o??{}}}function ao(o){return typeof o.StateEpoch=="string"&&o.StateEpoch.length>0?o.StateEpoch:null}var as=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let s=this.confirmedAt[e];return s===void 0?false:t===void 0||i-s<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=ng(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let n=Object.keys(this.versions);this.reset(e),this.notify(n);}return}let i=Date.now(),s=[];for(let[n,r]of Object.entries(t)){let p=this.versions[n];p!==r&&(p!==void 0&&r===p+1?(this.versions[n]=r,this.confirmedAt[n]=i):(delete this.versions[n],delete this.confirmedAt[n]),s.push(n),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=rg(t);let s=Date.now();this.confirmedAt={};for(let r of Object.keys(this.versions))this.confirmedAt[r]=s;this.dirty=true;let n=new Set;for(let r of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[r]!==this.versions[r]&&n.add(r);this.notify([...n]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[n,r]of Object.entries(t??{}))this.versions[n]!==r&&s.push(n),this.versions[n]=r,this.confirmedAt[n]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Ul=b("server","Title configuration is unavailable (CDN and API both failed)."),ls=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),RelatedEntityID:d()}:null}get configCache(){return this.cache??=new li(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new ui(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new rs(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new as(new os(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return c$1;let t=li.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let n=await this.ctx.api.user.getClientState(e);if(!n.ok)return n;let r=await this.resolveTitleConfig(n.data,t,i,{Fields:e.TitleFields});return r==null?Ul:(this.finishStateHandshake(n.data,s),await this.restoreSections(n.data.TitleConfigVersion,r),await this.applyClientState(n.data,r,void 0,void 0),this.ctx.cache.acceptLoginViews(n.data.Views),await this.applyLocalization(n.data.Localization),await this.flushState(s),n)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let n=this.stateStore.currentEpoch;n&&(e.KnownStateEpoch=n);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=oo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=ao(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,i,s){let n=e.TitleConfigVersion;if(i&&n&&i.v===n)return i.c;if(e.TitleConfigUrl){let p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return n&&await this.configCache.write(t,n,p),p}let r=await this.fetchConfigFromApi(s);return r!=null?(n&&await this.configCache.write(t,n,r),r):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return c$1;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=li.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let r=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let p=await this.ctx.api.user.getClientStateExcept(i);if(!p.ok)return p;let d=await this.resolveTitleConfig(p.data,s,n,{ExcludeFields:t??[]});return d==null?Ul:(this.finishStateHandshake(p.data,r),await this.restoreSections(p.data.TitleConfigVersion,d),await this.applyClientState(p.data,d,e,t),this.ctx.cache.acceptLoginViews(p.data.Views),await this.applyLocalization(p.data.Localization),await this.flushState(r),p)}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let i=t,s={};for(let[n,r]of Object.entries(await this.sectionCache.read(e)))i[n]==null&&(s[n]=r);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((n,r)=>{i[n]!=null||r==null||(s[n]=r,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let r=await this.fetchLocalizationFromCdn(e.Url);if(r!=null)return await this.localizationCache.write(t,i,r),r}let n=await this.fetchLocalizationFromApi(t,s?.v??0);return n??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let n=s.data;if(n.NotModified)return null;let r=n.Entries??{},p=n.Version??0,d=n.Locale??e;return p>0&&await this.localizationCache.write(d,p,r),r}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):c$1}async getUserState(e){let t=this.baseRequest();if(!t)return c$1;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let n=oo(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let r=i.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([C,j])=>r[C]!==j||this.ctx.data.user.state?.[C]===void 0).map(([C])=>C);this.ctx.data.user.applyUserStateContainers(n,p);let d=ao(s.data);return d&&(this.stateStore.afterSliceRead(d,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return c$1;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return c$1;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return c$1;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let s=this.baseRequest();if(!s)return c$1;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=i;let n=await this.ctx.api.user.addUsageTime(s);return n.ok&&this.ctx.emitter.emit("user:usageTimeAdded",n.data),n}async deleteUserAccount(){let e=this.baseRequest();if(!e)return c$1;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return c$1;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,s){let n=i?.includes("GameLoop")===true,r=s?.includes("GameLoop")===true,p=n?this.ctx.data.user.state?.GameLoop:void 0,d=r?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let C=this.ctx.data.user.state;n&&C&&C.GameLoop==null&&(C.GameLoop=p);let j=this.ctx.data.config.titlePublicConfiguration;r&&j&&j.GameLoop==null&&(j.GameLoop=d),this.ctx.emitter.emit("user:clientStateReceived",e);}};var cs=class{constructor(e){this.ctx=e;}ctx;async convert(e,t,i,s,n,r){if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(n<=0)return b("client","Amount must be positive.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===ut.Crypto||i===ut.Crypto)return b("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(n)),TransactionID:r&&r.length>0?r:`convert_${e}_${t}_to_${i}_${s}_${d()}`},d$1=await this.ctx.api.currency.convert(p);if(d$1.ok){let C=d$1.data,j={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:C.SourceID,Amount:C.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:C.TargetID,Amount:C.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(j,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",C);}return d$1}async cryptoConvert(e,t,i,s,n,r){let p=n instanceof Nt?n:new Nt(n);if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(p.lte(0))return b("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===ut.Virtual&&i===ut.Virtual)return b("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ut.Virtual&&!p.isInteger())return b("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:p.toString(),TransactionID:r&&r.length>0?r:`crypto_convert_${e}_${t}_to_${i}_${s}_${d()}`},C=await this.ctx.api.currency.cryptoConvert(d$1);if(C.ok){let j=C.data,le=[],Ie=[];if(j.SourceType===ut.Virtual&&le.push({Type:"VirtualCurrency",CurrencyID:j.SourceID,Amount:Math.trunc(Number(j.SourceSpent))}),j.TargetType===ut.Virtual&&Ie.push({Type:"VirtualCurrency",CurrencyID:j.TargetID,Amount:Math.trunc(Number(j.TargetCredited))}),le.length>0||Ie.length>0){let ge={Consume:le.length>0?{Standard:{Entries:le}}:null,Grant:Ie.length>0?{Standard:{Entries:Ie}}:null};this.ctx.data.user.applyResourceOperation(ge,this.ctx.data.config.itemDefinitions);}j.SourceType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.SourceID,new Nt(j.SourceSpent).negated(),j.ServerTimeUtc),j.TargetType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.TargetID,new Nt(j.TargetCredited),j.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",j);}return C}};var ps=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let s=e.trim();if(!s)return b("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${s}_${d()}`};t&&t.length>0&&(n.FodderInstanceIDs=[...t]);let r=await this.ctx.api.item.upgradeLevel(n);return r.ok&&(this.ctx.data.user.patchEquippedItemLevel(r.data.ItemInstanceID??s,r.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",r.data)),r}async upgradeLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let s of i.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var El=z.object({OptionID:z.string().nullish(),Name:z.string().nullish(),Cost:St.nullish(),AllowedPlatforms:z.array(Li).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),oe=z.record(z.string(),El),og=z.object({Store:Gi,Receipt:z.string(),Signature:z.string().nullish()}).passthrough();var lo=z.object({ServerTimeUtc:c,OfferID:z.string(),Count:z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),ql=z.array(Pe(lo)),ag=z.object({OfferID:z.string(),TotalPurchases:z.number(),DailyPurchases:z.number(),DailyResetUtc:c,LastPurchasedAt:c}),lg=z.object({SlotKey:z.string(),InstanceKey:z.string(),OfferID:z.string().nullish(),Purchases:z.number(),LastPurchasedAt:c}),Bl=z.object({Purchases:z.record(z.string(),ag).nullish(),Rotations:z.record(z.string(),lg).nullish()}).passthrough().transform(o=>o),bt=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),hs=z.object({Schedule:me.nullish(),Gate:J.nullish()}).passthrough(),ug={Fixed:"Fixed",Title:"Title",Player:"Player"},cg=z.object({OfferID:z.string().nullish(),Weight:z.number().nullish(),Gate:J.nullish()}).passthrough(),Ll=z.object({Mode:z.string().nullish(),OfferID:z.string().nullish(),Pool:z.array(cg).nullish(),Salt:z.string().nullish(),PerInstanceCap:z.number().nullish()}).passthrough(),pg=z.object({Identity:K.nullish(),Availability:K.nullish(),Rotation:K.nullish()}).passthrough(),hg=z.object({SlotID:z.string().nullish(),Identity:bt.nullish(),Availability:hs.nullish(),Rotation:Ll.nullish(),Presets:pg.nullish()}).passthrough(),dg=z.object({Identity:K.nullish(),Availability:K.nullish()}).passthrough(),mg=z.object({SectionID:z.string().nullish(),Identity:bt.nullish(),Availability:hs.nullish(),Slots:z.record(z.string(),hg).nullish(),UniqueOffersInSection:z.boolean().nullish(),Presets:dg.nullish()}).passthrough(),Gl=z.object({Sections:z.record(z.string(),mg).nullish()}).passthrough(),fg=z.object({Identity:K.nullish(),Availability:K.nullish(),Layout:K.nullish()}).passthrough(),gg=z.object({StoreID:z.string().nullish(),Identity:bt.nullish(),Availability:hs.nullish(),Layout:Gl.nullish(),Presets:fg.nullish()}).passthrough(),Fl=z.object({Options:oe.nullish(),CompareAt:z.record(z.string(),St).nullish()}).passthrough(),Vl=z.object({Grant:H.nullish()}).passthrough(),jl=z.object({Schedule:me.nullish(),Gate:J.nullish(),Limits:ye.nullish()}).passthrough(),yg=z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish(),Availability:K.nullish()}).passthrough(),Rg=z.object({OfferID:z.string().nullish(),Identity:bt.nullish(),Pricing:Fl.nullish(),Reward:Vl.nullish(),Availability:jl.nullish(),Presets:yg.nullish()}).passthrough(),Cg=z.object({Identity:z.record(z.string(),bt).nullish(),Availability:z.record(z.string(),hs).nullish(),Layout:z.record(z.string(),Gl).nullish(),Rotation:z.record(z.string(),Ll).nullish(),Pricing:z.record(z.string(),Fl).nullish(),Reward:z.record(z.string(),Vl).nullish(),OfferAvailability:z.record(z.string(),jl).nullish()}).passthrough(),ds=z.object({Stores:z.record(z.string(),gg).nullish(),StoreOffers:z.record(z.string(),Rg).nullish(),Presets:Cg.nullish()}).passthrough(),Sg=z.object({PurchasedTotal:z.number(),PurchasedToday:z.number(),PurchasedThisRotation:z.number(),RemainingTotal:z.number().nullish(),RemainingToday:z.number().nullish(),IsFirstPurchaseAvailable:z.boolean(),SoldOut:z.boolean(),AvailableAtUtc:c.nullish()}).passthrough(),xg=z.object({OptionID:z.string(),Name:z.string().nullish(),Cost:St.nullish(),CompareAtCost:St.nullish(),DiscountPercent:z.number().nullish(),IsFree:z.boolean(),IsAdPaid:z.boolean(),IsStorePaid:z.boolean(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),bg=z.object({OfferID:z.string(),Identity:bt.nullish(),PriceOptions:z.array(xg).nullish(),Rewards:H.nullish(),State:Sg.nullish()}).passthrough(),Dg=z.object({SlotID:z.string(),Identity:bt.nullish(),SortOrder:z.number(),RotationMode:z.string().nullish(),RotationInstanceKey:z.string().nullish(),RefreshesAtUtc:c.nullish(),RemainingThisRotation:z.number().nullish(),Offer:bg.nullish()}).passthrough(),Pg=z.object({SectionID:z.string(),Identity:bt.nullish(),SortOrder:z.number(),Slots:z.array(Dg).nullish()}).passthrough(),Ig=z.object({StoreID:z.string(),Identity:bt.nullish(),SortOrder:z.number(),ScheduleInstanceKey:z.string().nullish(),ExpiresAtUtc:c.nullish(),Sections:z.array(Pg).nullish()}).passthrough(),ms=z.object({ServerTimeUtc:c,Stores:z.array(Ig).nullish(),AdCreditBalance:z.number()}).passthrough(),_t={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront"},vg="OFFER_NOT_IN_ROTATION";var Nl="Store",_l={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:o=>{let e=null;for(let t of o.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},fs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(_l,{schema:ms,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return b("client","OfferID is required.");if(t<1)return b("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,RelatedEntityID:`store_buy_${e}_${s.userID}_${d()}`},r=await this.ctx.api.store.purchase(n);if(r.ok){let p=r.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return r}async purchaseBatch(e){if(!e||e.length===0)return b("client","purchases is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||!n.Data.OfferID||(this.ctx.data.user.patchStorePurchase(n.Data.OfferID,n.Data.Count,n.Data.ServerTimeUtc),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(Nl,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Nl,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(_l,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=s.RefreshesAtUtc;n&&(e===null||Date.parse(n)<Date.parse(e))&&(e=n);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var gs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return c$1;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return c$1;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?a(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return b("client","Receipt is required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},n=await this.ctx.api.purchase.validatePurchase(s);return n.ok&&this.applyValidation(n.data),n}async buyWithTelegramStars(e,t){if(!e)return b("client","productID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(i);return s.ok&&t?.open!==false&&this.ctx.platform.openInvoice(s.data.InvoiceLink),s}async validatePurchasesBatch(e){if(!e||e.length===0)return b("client","receipts is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let s of i.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Wl=3,Tg=700,ys=class{constructor(e){this.ctx=e;l()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return oi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await m({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return i.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:i.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=Wl;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===Wl)break;await wt(Tg);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t)if(i?.Type===Bi.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!==Bi.CryptoCurrency||!i.CurrencyID)continue;let s=Number(i.Amount??0);if(!(s>0))continue;let n=this.cryptoBalance(i.CurrencyID);return n>=s?null:{currencyID:i.CurrencyID,required:s,available:n,missing:s-n}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var Kl="Lootbox",Rs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Kl,e);if(t){let n={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection(Kl,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s){if(!e)return b("client","LootboxID is required.");if(t<1)return b("client","Count must be at least 1.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,RelatedEntityID:`lootbox_${e}_${i??"default"}_${d()}`},r=await this.ctx.api.lootbox.open(n);if(r.ok){let p=r.data;p.TriggeredPity&&p.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,p.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",p);}return r}};var uo="Reward";function co(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Cs=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(uo)?.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(uo,e);if(t){let n={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(uo,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${d()}`},s=await this.ctx.api.reward.claimDailyReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchDailyCalendarState(n.CalendarID,n.DailyState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",n);}return s}async collectIdleAccrual(e){if(!co(e))return b("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${d()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let s=i.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return i}async claimComebackReward(e){if(!co(e))return b("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${d()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return i}async claimReward(e){if(!co(e))return b("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${d()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return i}};var Ss="Tutorial",Ql={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"]},xs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ql,{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(Ss)?.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(Ss,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ss,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(Ql,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${d()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return b("client","FlowID is required.");if(!t||t.length===0)return b("client","stepIDs is required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${d()}`},n=await this.ctx.api.tutorial.completeStepsBatch(s);return n.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",n.data)),n}async skipStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.skipStep(i))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${d()}`},s=await this.ctx.api.tutorial.claimFlowReward(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let s=e?.trim();if(!s)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:s},r=await t(n);return r.ok&&(this.applyFlowView(r.data),this.ctx.emitter.emit(i.event,r.data)),r}async stepCall(e,t,i,s){let n=e?.trim(),r=t?.trim();if(!n)return b("client","FlowID is required.");if(!r)return b("client","StepID is required.");if(!this.ctx.auth.context)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:r};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let d=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,C=await i(p);return C.ok&&(this.applyFlowView(C.data),this.mayHavePaid(n,r,d,C.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",C.data)),C}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Ss)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}};var bs=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return c$1;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return b("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return b("client","campaignID is required.");if(!t)return b("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.CampaignID=e,s.WalletAddress=t,i&&(s.Amount=i);let n=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return n.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",n.data),n}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Oe=z.object({Username:z.string().nullish(),Country:z.string().nullish(),AvatarUrl:z.string().nullish(),Premium:z.boolean().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),BoardRank:z.number().nullish()}).passthrough();var kg={Global:"Global",Announcement:"Announcement",Group:"Group"},$l=z.enum(["Global","Announcement","Group"]).catch("Global"),zg={None:"None",Language:"Language",Region:"Region"},Ag=z.enum(["None","Language","Region"]).catch("None"),wg={Anyone:"Anyone",Friends:"Friends"},Mg=z.enum(["Anyone","Friends"]).catch("Anyone"),Og={Reject:"Reject",Mask:"Mask"},Ug=z.enum(["Reject","Mask"]).catch("Reject"),Eg={Player:"Player",Publisher:"Publisher",System:"System"},qg=z.enum(["Player","Publisher","System"]).catch("Player"),Bg={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Lg=z.object({DisplayNameKey:z.string().nullish(),SortOrder:z.number().nullish(),IconPath:z.string().nullish(),JoinedByDefault:z.boolean().nullish()}).passthrough(),Jl=z.object({Gate:J.nullish(),Schedule:me.nullish()}).passthrough(),Zl=z.object({Gate:J.nullish(),Limits:ye.nullish(),MaxLength:z.number().nullish()}).passthrough(),Yl=z.object({HotTailSize:z.number().nullish(),HistoryHours:z.number().nullish()}).passthrough(),Gg=z.object({Availability:K.nullish(),Write:K.nullish(),Retention:K.nullish()}).passthrough(),Fg=z.object({ChannelID:z.string().nullish(),Identity:Lg.nullish(),Type:$l.nullish(),GroupSource:z.string().nullish(),Partitioning:Ag.nullish(),Capacity:z.number().nullish(),Availability:Jl.nullish(),Write:Zl.nullish(),Retention:Yl.nullish(),Presets:Gg.nullish()}).passthrough(),Vg=z.object({IsEnabled:z.boolean().nullish(),Gate:J.nullish(),WhoCanMessage:Mg.nullish(),Limits:ye.nullish(),MaxLength:z.number().nullish(),HistoryHours:z.number().nullish(),MaxConversations:z.number().nullish()}).passthrough(),jg=z.object({BlockedTerms:z.array(z.string()).nullish(),BlockedTermAction:Ug.nullish(),MaxIgnoreListSize:z.number().nullish(),ReportsEnabled:z.boolean().nullish(),ReportLimits:ye.nullish()}).passthrough(),Ng=z.object({MinIntervalSeconds:z.number().nullish(),MaxMessagesPerPoll:z.number().nullish(),MaxHistoryPageSize:z.number().nullish()}).passthrough(),_g=z.object({Availability:z.record(z.string(),Jl).nullish(),Write:z.record(z.string(),Zl).nullish(),Retention:z.record(z.string(),Yl).nullish()}).passthrough(),Xl=z.object({IsEnabled:z.boolean().nullish(),Channels:z.record(z.string(),Fg).nullish(),Direct:Vg.nullish(),Moderation:jg.nullish(),Polling:Ng.nullish(),Presets:_g.nullish()}).passthrough(),Wg=z.object({LastReadAt:z.string().nullish(),LastReadMessageID:z.string().nullish(),Left:z.boolean().nullish()}).passthrough(),Hl=z.object({LastAt:z.string().nullish(),DailyCount:z.number().nullish(),DailyResetUtc:z.string().nullish(),TotalCount:z.number().nullish(),LastTextHash:z.string().nullish()}).passthrough();z.object({MutedUntil:z.string().nullish(),MuteReason:z.string().nullish(),Ignored:z.array(z.string()).nullish(),Channels:z.record(z.string(),Wg).nullish(),Limits:z.record(z.string(),Hl).nullish(),ReportLimits:Hl.nullish()}).passthrough();var po=z.object({RoomID:z.string().nullish(),SentAt:z.string().nullish(),MessageID:z.string().nullish()}).passthrough(),Ds=z.object({RoomID:z.string().nullish(),ChannelID:z.string().nullish(),MessageID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderProfile:Oe.nullish(),AuthorType:qg.nullish(),Text:z.string().nullish(),SentAt:z.string().nullish()}).passthrough(),Kg=z.object({ChannelID:z.string().nullish(),RoomID:z.string().nullish(),DisplayNameKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),Type:$l.nullish(),CanWrite:z.boolean().nullish(),WriteBlockedReason:z.string().nullish(),SlowModeSeconds:z.number().nullish(),MaxLength:z.number().nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),Ps=z.object({Channels:z.array(Kg).nullish(),PollIntervalSeconds:z.number().nullish(),MutedUntil:z.string().nullish(),MuteReason:z.string().nullish()}).passthrough(),Qg=z.object({RoomID:z.string().nullish(),Messages:z.array(Ds).nullish(),NextCursor:po.nullish(),UnreadCount:z.number().nullish(),ServedFromDatabase:z.boolean().nullish()}).passthrough(),eu=z.object({Rooms:z.array(Qg).nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),tu=z.object({RoomID:z.string().nullish(),Messages:z.array(Ds).nullish(),NextBefore:po.nullish()}).passthrough(),iu=z.object({Message:Ds.nullish(),Moderated:z.boolean().nullish()}).passthrough(),su=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Oe.nullish(),MaxLength:z.number().nullish()}).passthrough(),Hg=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Oe.nullish(),LastMessage:Ds.nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),nu=z.object({Conversations:z.array(Hg).nullish()}).passthrough(),ci=z.object({Ignored:z.array(z.string()).nullish(),Cursor:po.nullish(),Joined:z.boolean().nullish()}).passthrough(),ru=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish()}).passthrough(),Ke={GetChatDefinitions:"GetChatDefinitions",GetChannels:"GetChannels",Poll:"Poll",GetHistory:"GetHistory",GetConversations:"GetConversations",SendMessage:"SendMessage",OpenDirectChannel:"OpenDirectChannel",MarkRead:"MarkRead",JoinChannel:"JoinChannel",LeaveChannel:"LeaveChannel",ReportMessage:"ReportMessage",IgnoreUser:"IgnoreUser",UnignoreUser:"UnignoreUser"};var ou="Chat",au={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Is=class{constructor(e){this.ctx=e;e.cache.bindLoginView(au,{schema:Ps,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(ou,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ou,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(au,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let s of i.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return i}async getHistory(e,t,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),i&&(s.Limit=i),this.ctx.api.chat.getHistory(s)):c$1}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return c$1;s.ChannelID=e,s.Text=t,i&&(s.Locale=i);let n=await this.ctx.api.chat.sendMessage(s);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.Text=t;let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):c$1}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):c$1}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(i);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):c$1}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):c$1}async reportMessage(e,t,i,s){let n=this.ctx.authedRequest();return n?(n.RoomID=e,n.MessageID=t,n.Reason=i,s&&(n.Comment=s),this.ctx.api.chat.reportMessage(n)):c$1}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):c$1}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):c$1}resetCursors(){this.cursors.clear();}};var $g={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},Jg=z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),Zg={Player:"player",Title:"title",Creator:"creator"},pi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},lu=z.object({Configured:z.boolean().nullish(),PublicKey:z.string().nullish()}).passthrough(),Yg=z.object({TitleID:z.string().nullish(),Topic:z.string().nullish()}).passthrough(),ho=z.object({EndpointHash:z.string().nullish(),Transport:Jg.nullish(),Locale:z.string().nullish(),Topics:z.array(Yg).nullish()}).passthrough(),uu=z.object({Configured:z.boolean().nullish(),Subscriptions:z.array(ho).nullish()}).passthrough(),Dt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var Xg="IDOS_PLATFORM_PUSH_REQUEST",ey="IDOS_PLATFORM_PUSH_RESPONSE",ty=12e4;function cu(o){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let s=false,n=d=>{s||(s=true,window.removeEventListener("message",r),clearTimeout(p),i(d));},r=d=>{let C=d?.data;!C||C.type!==ey||C.requestId!==t||f.includes(d.origin)&&n(C.ok===true);},p=setTimeout(()=>n(false),ty);window.addEventListener("message",r);for(let d of f)try{e.postMessage({type:Xg,requestId:t,titleID:o},d);}catch{}})}var vs=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),s=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,i.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return Dt.Unsupported;if(this.isEmbedded())return Dt.Embedded;if(!this.isSupported())return Dt.Unsupported;let t=Notification.permission;return t==="denied"?Dt.Blocked:t!=="granted"?Dt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?Dt.Subscribed:Dt.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return b("client","Push notifications are not available for this title.");if(this.isEmbedded())return await cu(this.ctx.settings.titleID)?a({Where:"portal",Subscription:null}):b("client","The portal did not complete the subscription.");if(!this.isSupported())return b("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return b("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let r=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:iy(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return c$1;let d=r.toJSON();p.PushEndpoint=d.endpoint,p.PushP256dh=d.keys?.p256dh,p.PushAuth=d.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let C=await this.ctx.api.push.subscribePush(p);return C.ok?(this.ctx.emitter.emit("push:subscribed",C.data),a({Where:"game",Subscription:C.data})):C}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return c$1;if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return b("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):c$1}async unsubscribeByHash(e){if(!e)return b("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function iy(o){let e=o.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(o.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return i}var Ts=Object.freeze({}),ks=class{constructor(e){this.ctx=e;}ctx;table={...Ts};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new ui(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),s=this.lookup(i)??this.lookup(e);return s===void 0?this.onMissing(e):t?sy(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Ts},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return c$1;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:r}=i.data,p=null;if(r){let d=await this.loadTableFromApi(r);d.ok&&(p=d.data.table);}return this.table=n,this.fallbackTable=p,this.currentFallbackLocale=r,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:r,entryCount:Object.keys(n).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):c$1}reset(){this.table={...Ts},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:d()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return c$1;t.Locale=e;let i=await this.cache.read(pu(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let n=s.data,r=n.Locale??pu(e),p=n.Version??0;if(n.NotModified){let C=i??await this.cache.read(r);return {ok:true,data:{locale:r,table:C?.t??{...Ts},fallbackLocale:n.FallbackLocale??null}}}let d=n.Entries??{};return p>0&&await this.cache.write(r,p,d),{ok:true,data:{locale:r,table:d,fallbackLocale:n.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let s=this.pluralCategory(i),n=`${e}.${s}`;if(this.lookup(n)!==void 0)return n;let r=`${e}.other`;return this.lookup(r)!==void 0?r:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function sy(o,e){return o.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function pu(o){return o.trim().replace(/_/g,"-").toLowerCase()}var mo="Quest",ny={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:o=>{let e=Date.now(),t=null,i=[...Object.values(o.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(o.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let n=Date.parse(s??"");!Number.isNaN(n)&&n>e&&(t===null||n<t)&&(t=n);}return t}},zs=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let s=e.cache.configSection(mo)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let r of Object.keys(s)){let p=Date.parse(n[r]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=i&&t<p)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true,{forceRefresh:true});return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(mo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(mo,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(ny,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let s=i.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let i=e.trim();if(!i)return b("client","QuestID is required.");if(!this.ctx.auth.context)return c$1;let s=t&&t.trim().length>0?t.trim():void 0,n={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${d()}`},r=await this.ctx.api.quest.claimQuestReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return r}async claimQuestRewardsBatch(e){if(!e||e.length===0)return b("client","quests is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchQuestStatus(n.Data.QuestID,n.Data.CycleID,"Claimed"),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${d()}`},r=await this.ctx.api.quest.claimMilestoneReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return r}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchMilestoneClaimed(n.Data.CycleID,n.Data.MilestoneID),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${d()}`},r=await this.ctx.api.quest.claimGroupCompletionReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return r}async addQuestProgress(e,t){let i=e.trim();if(!i)return b("client","MetricID is required.");if(t<0)return b("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},n=await this.ctx.api.quest.addQuestProgress(s);return n.ok&&(this.ctx.data.user.patchQuestProgressUpdates(n.data.Updates),this.ctx.emitter.emit("quest:progressAdded",n.data)),n}};var hu=z.object({}).passthrough().transform(o=>o);var ry=z.object({Order:z.number().nullish(),Type:z.string().nullish(),DurationSec:z.number().nullish(),BonusMultiplier:z.number().nullish()}).passthrough(),oy=z.object({Schedule:z.array(ry).nullish(),RepeatCycle:z.boolean().nullish(),MaxCycles:z.number().nullish()}).passthrough(),ay=z.object({IsActive:z.boolean().nullish(),CurrentPhaseEndUtc:c.nullish(),NextBonusStartUtc:c.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentPhaseIndex:z.number().nullish(),ActiveBonusMultiplier:z.number().nullish()}).passthrough(),ly=z.object({Milestones:K.nullish()}).passthrough(),fo=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Category:z.string().nullish(),Token:jt.nullish(),TokenSources:z.array(st).nullish(),ClaimMode:z.string().nullish(),Milestones:z.record(z.string(),Be).nullish(),Presets:ly.nullish(),BonusWindow:oy.nullish()}).passthrough(),uy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Content:fo.nullish(),ClaimGraceHours:z.number().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),cy=z.object({TimedEventID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:me.nullish(),Content:fo.nullish(),Events:z.array(uy).nullish(),Gate:J.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),py=z.object({MaxConcurrentEvents:z.number().nullish()}).passthrough(),hy=z.object({Milestones:z.record(z.string(),ni).nullish()}).passthrough(),As=z.object({Definitions:z.record(z.string(),cy).nullish(),Settings:py.nullish(),Presets:hy.nullish()}).passthrough(),dy=z.object({Type:xi,TimedEventID:z.string(),CurrentChainedEventID:z.string().nullish(),Content:fo.nullish(),Progress:hu.nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),NextMilestone:Be.nullish(),BonusWindow:ay.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentEventOrder:z.number().nullish(),TotalEventsInChain:z.number().nullish(),TokenEntityID:z.string().nullish()}).passthrough(),ws=z.object({ActiveEvents:z.array(dy).nullish()}).passthrough(),du=z.object({Tokens:z.record(z.string(),hu).nullish()}),go=z.object({Type:xi.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),yo=z.object({Type:xi.nullish(),LteID:z.string().nullish(),MilestoneID:z.string().nullish(),TokenEntityID:z.string().nullish(),Rewards:M.nullish(),Inventory:Q.nullish()}),my=z.object({Type:xi.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),Ro=z.array(Pe(yo)),mu=z.array(Pe(go)),fu=z.array(Pe(my)),ot={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var gu="TimedEvent",yu={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:o=>{let e=null;for(let t of o.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Ms=class{constructor(e){this.ctx=e;e.cache.bindLoginView(yu,{schema:ws,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(yu,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(gu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(gu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,s,n,r,p=1){if(!t)return b("client","LteID is required.");if(!i)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c$1;let d={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:r,RollMultiplier:p},C=await this.ctx.api.timedEvent.grantTokens(d);return C.ok&&(this.ctx.data.user.applyResourceOperation(C.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",C.data)),C}async spendTokens(e,t,i){if(!t)return b("client","LteID is required.");if(i<=0)return b("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},n=await this.ctx.api.timedEvent.spendTokens(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",n.data)),n}async claimMilestone(e,t,i){if(!t||!i)return b("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},n=await this.ctx.api.timedEvent.claimMilestone(s);if(n.ok){let r=n.data;this.ctx.data.user.applyResourcesWithDelta(r.Rewards,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,r.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",r);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return b("client","spends is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return b("client","grants is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let s=i.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var fy=z.object({UserID:z.string(),Score:_.nullish(),Rank:z.number().nullish(),LastScoreUpdateUtc:c.nullish(),IpHash:z.string().nullish(),PublicProfile:Oe.nullish(),SeasonTierAtCycleEnd:z.number().nullish()}).passthrough(),Di=z.object({LeaderboardID:z.string(),CycleVersion:z.number().nullish(),TotalParticipants:_.nullish(),CycleEndUtc:c.nullish(),TopUsers:z.array(fy).nullish(),BracketID:z.string().nullish()}),gy=z.object({CycleKey:z.string().nullish(),CycleEndUtc:c.nullish(),ClaimDeadlineUtc:c.nullish(),MilestoneTokensEarned:_.nullish(),ClaimableMilestoneIDs:z.array(z.string()).nullish(),CycleIndex:z.number().nullish(),ChainedEventID:z.string().nullish()}).passthrough(),Os=z.object({LeaderboardID:z.string(),CurrentScore:_.nullish(),LastKnownRank:z.number().nullish(),HasUnclaimedReward:z.boolean().nullish(),UnclaimedRewardRank:z.number().nullish(),ScoreEarnedThisCycle:_.nullish(),MilestoneTokensEarned:_.nullish(),TokenEntityID:z.string().nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish(),GrantedPremiumTiers:z.record(z.string(),z.array(z.string())).nullish(),ClaimableGraceCycles:z.array(gy).nullish()}),Us=z.object({LeaderboardID:z.string(),NewScore:_,CycleVersion:z.number()}),Es=z.object({ServerTimeUtc:c,LeaderboardID:z.string(),Rank:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),qs=z.object({ServerTimeUtc:c,LeaderboardID:z.string(),MilestoneID:z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),Ru=z.array(Pe(Di)),Bs=z.array(Pe(Os)),Cu=z.array(Pe(Es)),Su=z.array(Pe(qs)),xu=z.array(Pe(Us)),yy=z.object({LeaderboardID:z.string(),CycleReward:Pe(Es).nullish(),Milestones:z.array(Pe(qs)).nullish()}),bu=z.array(yy),Ry=z.object({LeaderboardID:z.string(),Leaderboard:Pe(Di).nullish(),Progress:Pe(Os).nullish()}),Du=z.array(Ry),Cy=z.string(),Pu=z.object({Rank:z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:Hr.nullish()}).passthrough(),Sy=z.object({RankRewards:z.array(Pu).nullish()}).passthrough(),xy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),by=z.object({Milestones:K.nullish(),RankRewards:K.nullish()}).passthrough(),Dy=z.object({LeaderboardID:z.string(),DisplayName:z.string().nullish(),ScoreDisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),IsEnabled:z.boolean().nullish(),ScoreAggregation:Cy.nullish(),Schedule:me.nullish(),ChainEvents:z.array(xy).nullish(),Gate:J.nullish(),TopUsersLimit:z.number().nullish(),MinScoreToEnterTop:z.number().nullish(),BracketSize:z.number().nullish(),LinkedSeasonChainID:z.string().nullish(),RankRewards:z.array(Pu).nullish(),Milestones:z.record(z.string(),Be).nullish(),Presets:by.nullish(),MilestoneClaimMode:z.string().nullish(),MilestoneClaimGraceHours:z.number().nullish(),ScoreSources:z.array(st).nullish()}).passthrough(),Py=z.object({Milestones:z.record(z.string(),ni).nullish(),RankRewards:z.record(z.string(),Sy).nullish()}).passthrough(),Ls=z.object({Definitions:z.record(z.string(),Dy).nullish(),Presets:Py.nullish()}).passthrough(),Ve={GetDefinitions:"GetDefinitions",GetLeaderboard:"GetLeaderboard",GetMyProgress:"GetMyProgress",SubmitScore:"SubmitScore",SubmitScoreFromSource:"SubmitScoreFromSource",ClaimCycleReward:"ClaimCycleReward",ClaimMilestone:"ClaimMilestone",GetFriendsLeaderboard:"GetFriendsLeaderboard",GetLeaderboardsBatch:"GetLeaderboardsBatch",GetProgressBatch:"GetProgressBatch",ClaimCycleRewardsBatch:"ClaimCycleRewardsBatch",ClaimMilestonesBatch:"ClaimMilestonesBatch",SubmitScoresBatch:"SubmitScoresBatch",ClaimAllRewardsBatch:"ClaimAllRewardsBatch",GetOverviewBatch:"GetOverviewBatch"};var Iu="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"]},Gs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(vu,{schema:Bs,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(Iu,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Iu,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return b("client","LeaderboardID is required.");if(t<=0)return b("client","Score must be positive.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(i);if(s.ok){let n=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),n.NewScore,t,n.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",n);}return s}async submitScoreFromSource(e,t,i,s,n=1){if(!e)return b("client","LeaderboardID is required.");if(!t)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},p=await this.ctx.api.leaderboard.submitScoreFromSource(r);if(p.ok){let d=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),d.NewScore,d.NewScore,d.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",d);}return p}async claimCycleReward(e){if(!e)return b("client","LeaderboardID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return i}async claimMilestone(e,t,i){if(!e||!t)return b("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},n=await this.ctx.api.leaderboard.claimMilestone(s);if(n.ok){let r=n.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",r);}return n}async getFriendsLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(b("client","leaderboardIDs is required.")):this.ctx.cache.read(vu,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return b("client","scores is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let n=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(n),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let r of s.Milestones??[])!r.Success||!r.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(n,r.Data.MilestoneID),r.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let s of i.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var Co=z.object({}).passthrough().transform(o=>o),Fs=z.object({SeasonChainID:z.string(),CycleIndex:z.number().nullish(),Season:z.lazy(()=>Au).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:_.nullish(),UserState:Co.nullish(),NextTier:z.lazy(()=>zu).nullish()}).passthrough(),Tu=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),AmountGranted:_.nullish(),NewStatusTokens:_.nullish(),OldTier:z.number().nullish(),NewTier:z.number(),TierUp:z.boolean().nullish()}),So=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),TierNumber:z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),ku=ft(So);var zu=z.object({Tier:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredTokens:_.nullish(),TierReachedReward:H.nullish()}).passthrough(),Au=z.object({SeasonID:z.string().nullish(),Order:z.number().nullish(),DurationSec:_.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(zu).nullish(),LinkedCollectionID:z.string().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough();var Iy=z.object({SeasonChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:me.nullish(),Seasons:z.array(Au).nullish(),GrantTokensAccessMode:z.string().nullish(),Gate:J.nullish()}).passthrough(),Vs=z.object({Chains:z.record(z.string(),Iy).nullish()}).passthrough(),Ot={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var wu="Season",Mu={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:o=>{let e=Date.parse(o.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},js=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Mu,{schema:Fs,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(wu,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(wu,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(Mu,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(b("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return b("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","Amount must be positive.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${d()}`},s=await this.ctx.api.season.grantStatusTokens(i);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","TierNumber must be positive.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${d()}`},s=await this.ctx.api.season.claimTierReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",n);}return s}async claimTierRewardsBatch(e,t){if(!e)return b("client","SeasonChainID is required.");let i=(t??[]).filter(r=>r>0);if(i.length===0)return b("client","TierNumbers is required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${d()}`},n=await this.ctx.api.season.claimTierRewardsBatch(s);if(n.ok){let r=n.data;for(let p of r.Items??[]){let d=p.Data?.TierNumber;p.Success&&typeof d=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,d);}this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",r);}return n}};var Ou="Premium",Ns=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ou,e);if(t){let n={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",n),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(Ou,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(i);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,i="Default",s=1){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,RelatedEntityID:`premium_purchase_${e}_${t}`},r=await this.ctx.api.premium.purchaseItemOrCurrency(n);if(r.ok){let p=r.data;p.Premium&&this.ctx.data.user.applyPremium(p.Premium),this.ctx.data.user.applyResourceOperation(p.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",p);}return r}async purchaseRealMoney(e,t,i,s,n,r,p,d){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!s||!n)return b("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return c$1;let C={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:r,PackageName:p,AppStoreEnvironment:d,RelatedEntityID:`premium_iap_${e}_${t}`},j=await this.ctx.api.premium.purchaseRealMoney(C);if(j.ok){let le=j.data;le.Premium&&this.ctx.data.user.applyPremium(le.Premium),this.ctx.data.user.applyResourceOperation(le.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",le);}return j}};var _s=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ItemInstanceID:z.string().nullish(),Level:z.number().nullish(),EquippedAt:c.nullish()}),xo=z.object({CharacterID:z.string(),Level:z.number().nullish(),Experience:_.nullish(),Power:z.number().nullish(),StatLevels:z.record(z.string(),z.number()).nullish(),Equipment:z.record(z.string(),_s).nullish(),UpdatedAt:c.nullish()}).passthrough(),Uu=z.object({Characters:z.record(z.string(),xo).nullish()}),bo=z.object({ServerTimeUtc:c,CharacterID:z.string(),StatID:z.string(),StatLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),Do=z.object({ServerTimeUtc:c,CharacterID:z.string(),NewLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),Eu=z.object({ServerTimeUtc:c,CharacterID:z.string(),Equipment:z.record(z.string(),_s).nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),qu=z.object({ServerTimeUtc:c,CharacterID:z.string(),ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),vy=z.object({ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish()}),Bu=z.object({ServerTimeUtc:c,Characters:z.record(z.string(),vy).nullish(),Inventory:Q.nullish()}),Po=z.object({ServerTimeUtc:c,CharacterID:z.string(),Power:z.number().nullish(),Resources:M.nullish()}),Lu=z.object({ServerTimeUtc:c,CharacterID:z.string(),SkinID:z.string(),Resources:M.nullish(),Inventory:Q.nullish(),Equipped:z.boolean().nullish(),EquipError:z.string().nullish(),Equipment:_s.nullish(),Power:z.number().nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish()}),Gu=z.object({ServerTimeUtc:c,CharacterID:z.string(),SkinID:z.string(),Equipped:_s.nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),Fu=z.object({ServerTimeUtc:c,CharacterID:z.string(),Cleared:z.boolean().nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),Ty=z.object({SkinID:z.string(),IsDefault:z.boolean().nullish(),Misconfigured:z.string().nullish(),Owned:z.boolean().nullish(),OwnedCopies:z.number().nullish(),IsWorn:z.boolean().nullish(),MeetsRequirements:z.boolean().nullish(),SoldDirectly:z.boolean().nullish(),OnSale:z.boolean().nullish(),SaleEndsAtUtc:c.nullish(),GateOpen:z.boolean().nullish(),Purchasable:z.boolean().nullish(),PriceOptions:oe.nullish()}),ky=z.object({CharacterID:z.string(),CharacterOpen:z.boolean().nullish(),DefaultSkinID:z.string().nullish(),WornSkinID:z.string().nullish(),Skins:z.array(Ty).nullish()}),Vu=z.object({ServerTimeUtc:c,Characters:z.record(z.string(),ky).nullish()}),ju=ft(Po),Nu=ft(Do),_u=ft(bo),Io=z.object({RequiredStatID:z.string(),RequiredLevel:z.number()}).passthrough(),Wu=z.object({StatID:z.string(),TypeID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),MaxLevel:z.number().nullish(),Weight:z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:Fe.nullish(),BaseStatValue:z.number().nullish(),ValueCurve:Fe.nullish(),RankCurve:Fe.nullish(),Requirements:z.array(Io).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),zy=z.object({SlotID:z.string(),MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Io).nullish(),AllowedRarityIDs:z.array(z.string()).nullish(),AllowedItemTags:z.array(z.string()).nullish(),MinItemLevel:z.number().nullish(),MaxItemLevel:z.number().nullish()}).passthrough(),Ku=z.object({Slots:z.record(z.string(),zy).nullish()}).passthrough(),Qu=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Lore:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Ay=z.object({ClassID:z.string().nullish(),RarityID:z.string().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),wy=z.object({UnlockedByDefault:z.boolean().nullish(),PriceOptions:oe.nullish()}).passthrough(),My=z.object({Stats:K.nullish(),Levels:K.nullish(),Equipment:K.nullish()}).passthrough(),Hu=z.object({MaxRank:z.number().nullish(),FirstPaidRank:z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:Fe.nullish()}).passthrough(),vo="@skin";function Oy(o){return !!o&&o.startsWith("@")}var Uy=z.object({CatalogID:z.string().nullish(),ItemID:z.string()}).passthrough(),Ey=z.object({PriceOptions:oe.nullish(),Schedule:me.nullish(),Gate:J.nullish()}).passthrough(),qy=z.object({MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Io).nullish()}).passthrough(),By=z.object({SkinID:z.string().nullish(),Identity:Qu.nullish(),Item:Uy.nullish(),Sale:Ey.nullish(),Requirements:qy.nullish()}).passthrough(),Ly=z.object({DefaultSkinID:z.string().nullish(),Definitions:z.record(z.string(),By).nullish()}).passthrough(),Gy=z.object({CharacterID:z.string(),Identity:Qu.nullish(),Classification:Ay.nullish(),Unlock:wy.nullish(),Presets:My.nullish(),Equipment:Ku.nullish(),Stats:z.record(z.string(),Wu).nullish(),RankLadder:Hu.nullish(),RankStatCurve:Fe.nullish(),StatMaxLevelCurve:Fe.nullish(),Skins:Ly.nullish()}).passthrough(),Fy=z.object({Stats:z.record(z.string(),Wu).nullish()}).passthrough(),Vy=z.object({RankLadder:Hu.nullish()}).passthrough(),jy=z.object({Equipment:Ku.nullish()}).passthrough(),Ny=z.object({Stats:z.record(z.string(),Fy).nullish(),Levels:z.record(z.string(),Vy).nullish(),Equipment:z.record(z.string(),jy).nullish()}).passthrough(),Ws=z.object({Definitions:z.record(z.string(),Gy).nullish(),Presets:Ny.nullish()}).passthrough(),je={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"},_y="SKIN_ALREADY_OWNED";var To="Character",Ks=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(To)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,n])=>n?.Unlock?.UnlockedByDefault===true&&!i[n.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(To,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(To,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${d()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level??=1,r.StatLevels??={},r.Equipment??={},n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",n);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return b("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${d()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,p=>{p.StatLevels??={},p.StatLevels[r.StatID]=r.StatLevel,r.Power!=null&&(p.Power=r.Power),p.UpdatedAt=r.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",r);}return n}async upgradeCharacterLevel(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${d()}`,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level=n.NewLevel,n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(r.StatLevels??={},r.Equipment??={});}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",n);}return s}async equipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(i);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(i);if(s.ok){let n=s.data;this.applyUnequipChangesLocally(e,n),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:n.ClearedSlotIDs??[],power:n.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,i){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${d()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok){let r=n.data;this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),r.Equipped&&r.Equipment&&this.applySkinLocally(r.CharacterID,r.Equipment,r.Power,r.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",r);}return n}async equipSkin(e,t,i){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},n=await this.ctx.api.character.equipSkin(s);if(n.ok){let r=n.data;this.applyInventoryDelta(r.Inventory),this.applySkinLocally(r.CharacterID,r.Equipped??null,r.Power,r.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",r);}return n}async unequipSkin(e){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let s=i.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):c$1}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,vo,t??null),n.patchCharacter(e,r=>{i!=null&&(r.Power=i),r.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return b("client","characterIDs is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level??=1,n.StatLevels??={},n.Equipment??={},s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level=s.NewLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(n.StatLevels??={},n.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.StatLevels??={},n.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[s,n]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,s,n);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let n of i)s.patchCharacterEquipment(e,n,null);s.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,s]of Object.entries(e.Characters??{})){for(let n of s.ClearedSlotIDs??[])t.patchCharacterEquipment(i,n,null);t.patchCharacter(i,n=>{s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=e.ServerTimeUtc;});}}};var $u="Match",Qs=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,r){let p=this.ctx.auth.context;if(!p)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:r,RelatedEntityID:`pvp_create_${p.userID}_${d()}`},C=await this.ctx.api.match.createMatch(d$1);return C.ok&&(this.ctx.data.user.applyResourceOperation(C.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",C.data)),C}async updateMatch(e,t={}){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(i);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,s){let n=this.ctx.auth.context;if(!n)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${d()}`},p=await this.ctx.api.match.instantBattle(r);if(p.ok){let d=p.data,C=this.ctx.data.config.itemDefinitions;if(d.Resources)this.ctx.data.user.applyResourceOperation(d.Resources,C);else if(d.ResourcesDual){let j=d.ResourcesDual;j.FromUserID===n.userID&&j.FromResult?this.ctx.data.user.applyResourceOperation(j.FromResult,C):j.ToUserID===n.userID&&j.ToResult&&this.ctx.data.user.applyResourceOperation(j.ToResult,C);}this.ctx.emitter.emit("match:instantBattleCompleted",d);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let s=this.ctx.authedRequest();if(!s)return c$1;s.Page=e,s.PageSize=t,s.Statuses=i;let n=await this.ctx.api.match.getMyMatches(s);return n.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",n.data),n}async getAvailableMatches(e=0,t=20,i=false){let s=this.ctx.authedRequest();if(!s)return c$1;s.Page=e,s.PageSize=t,s.OnlyPublic=i;let n=await this.ctx.api.match.getAvailableMatches(s);return n.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",n.data),n}async getDefinitions(e){let t=this.ctx.cache.configSection($u,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection($u,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var Ju="Craft",Hs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Ju,e);if(t){let n={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(Ju,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n){if(!e)return b("client","CraftID is required.");let r=this.ctx.auth.context;if(!r)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,RelatedEntityID:`craft_${e}_${r.userID}_${d()}`},d$1=await this.ctx.api.craft.craft(p);return d$1.ok&&(this.ctx.data.user.applyResourcesWithDelta(d$1.data.Resources,d$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",d$1.data)),d$1}};var Ut=z.lazy(()=>z.union([z.string(),z.number(),z.boolean(),z.null(),z.array(Ut),z.record(z.string(),Ut)]));var Et={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},Zu=z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Wt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Pi(o){return o!==Wt.Pending&&o!==Wt.Running}var Wy={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 Ky(o){return o?/\b(AI_[A-Z_]+)\s*:/.exec(o)?.[1]??null:null}var Qy=z.object({Url:z.string().nullish(),ContentType:z.string().nullish(),Variant:z.string().nullish()}),Hy=z.object({Code:z.string().nullish(),Message:z.string().nullish()}),$s=z.object({GenerationID:z.string(),FeatureKey:z.string().nullish(),Modality:Zu.nullish(),Status:z.string(),Progress:z.number().nullish(),OutputText:z.string().nullish(),OutputJson:z.record(z.string(),Ut).nullish(),Assets:z.array(Qy).nullish(),Error:Hy.nullish(),Charge:M.nullish(),PlayerRefunded:z.boolean().nullish(),Reward:M.nullish(),Context:z.record(z.string(),Ut).nullish(),PaymentSettled:z.boolean().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish()}),Yu=z.object({Data:z.array($s).nullish(),Skip:z.number().nullish(),Limit:z.number().nullish()}),$y=z.object({Name:z.string().nullish(),Type:z.string().nullish(),Required:z.boolean().nullish(),MaxLength:z.number().nullish(),Enum:z.array(z.string()).nullish()}).passthrough(),Jy=z.object({Modality:Zu.nullish(),Async:z.boolean().nullish(),Limits:ye.nullish(),PriceOptions:oe.nullish(),Tags:z.array(z.string()).nullish(),HistoryMessages:z.number().nullish(),MaxTokens:z.number().nullish(),AllowImages:z.boolean().nullish(),MaxInputImages:z.number().nullish(),MaxInputImageBytes:z.number().nullish(),AllowedImageTypes:z.array(z.string()).nullish(),MaxImages:z.number().nullish(),AllowEdit:z.boolean().nullish(),AllowReferenceImage:z.boolean().nullish(),MaxPromptChars:z.number().nullish(),LockBehavior:z.boolean().nullish(),ImageSize:z.string().nullish(),VideoSize:z.string().nullish(),VideoSeconds:z.number().nullish(),Voice:z.string().nullish(),AudioFormat:z.string().nullish(),MusicFormat:z.string().nullish(),ThreeDOperation:z.string().nullish(),ArtStyle:z.string().nullish(),ThreeDFormat:z.string().nullish(),Reward:H.nullish(),PromptVariables:z.array($y).nullish(),AllowFreePrompt:z.boolean().nullish()}).passthrough(),Xu=z.object({Enabled:z.boolean().nullish(),Features:z.record(z.string(),Jy).nullish()}).passthrough(),Ge={GetDefinitions:"GetDefinitions",GenerateText:"GenerateText",GetText:"GetText",GenerateImage:"GenerateImage",EditImage:"EditImage",GenerateVideo:"GenerateVideo",GetVideo:"GetVideo",GenerateAudio:"GenerateAudio",GenerateMusic:"GenerateMusic",GenerateThreeD:"GenerateThreeD",GetThreeD:"GetThreeD",ListGenerations:"ListGenerations",GetGeneration:"GetGeneration",GetImage:"GetImage",GetAudio:"GetAudio",GetMusic:"GetMusic"};var ec="AI",Zy=/^[A-Za-z0-9_-]{1,128}$/,Yy=2e3,Xy=5e3,eR=30*6e4;function tR(o,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,o);e?.addEventListener("abort",i,{once:true});})}var Js=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(ec,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ec,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,i){return this.generate(e,{Text:t},i,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):c$1}async getGeneration(e){if(!e)return b("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):c$1}isTerminal(e){return Pi(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;i=p.data;}else {if(!e?.GenerationID)return b("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??eR),n=Math.max(1,t.intervalMs??Yy),r=Math.max(n,t.maxIntervalMs??Xy);for(;!Pi(i.Status);){if(t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");if(Date.now()+n>s)return b("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await tR(n,t.signal),t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(i);if(n=Math.min(r,Math.round(n*1.5)),!p.ok){if(p.reason==="connection")continue;return p}i=p.data,Pi(i.Status)||t.onUpdate?.(i);}return a(i)}pollFor(e){switch(e.Modality){case Et.Text:return this.getText(e.GenerationID);case Et.Image:return this.getImage(e.GenerationID);case Et.Audio:return this.getAudio(e.GenerationID);case Et.Music:return this.getMusic(e.GenerationID);case Et.Video:return this.getVideo(e.GenerationID);case Et.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,s){if(!e)return b("client","FeatureKey is required.");let n=i?.relatedEntityID;if(n!==void 0&&!Zy.test(n))return b("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:n??d()},p=await s(r);return p.ok&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return b("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.GenerationID=e;let s=await t(i);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Wt.Completed&&!this.rewarded.has(e.GenerationID)&&(this.rewarded.add(e.GenerationID),await this.ctx.userService.getUserInventory()),!(!t||!e.Charge||this.charged.has(e.GenerationID))&&(this.charged.add(e.GenerationID),this.ctx.data.user.applyResourceOperation(e.Charge,this.ctx.data.config.itemDefinitions));}emitView(e){this.ctx.emitter.emit("ai:generationUpdated",e),e.Status===Wt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Wt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var ko="Collection",Zs=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(ko),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let n=e.cache.configSection("Season");return Object.values(n?.Chains??{}).some(p=>(p?.Seasons??[]).some(d=>!!d?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ko,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ko,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,s){let n=this.ctx.auth.context;if(!n)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${d()}`},p=await this.ctx.api.collection.openPack(r);return p.ok&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${d()}`},r=await this.ctx.api.collection.openCollectionChest(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",r.data)),r}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${d()}`},n=await this.ctx.api.collection.useCollectibleJoker(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",n.data)),n}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${d()}`},n=await this.ctx.api.collection.claimSetReward(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",n.data)),n}async claimSetRewardsBatch(e){if(!e||e.length===0)return b("client","sets is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${d()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,n,r=false){let p=this.ctx.auth.context;if(!p)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:r,RelatedEntityID:`trade_send_${p.userID}_${s}_${d()}`},C=await this.ctx.api.collection.sendTradeOffer(d$1);return C.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",C.data)),C}async cancelTradeOffer(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${d()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${d()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${d()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var iR=z.object({}).passthrough().transform(o=>o),sR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},nR={Active:"Active",Left:"Left",Replaced:"Replaced"},rR=z.object({ObjectIndex:z.number().nullish(),ObjectCompletionRewardClaimed:z.boolean().nullish()}).passthrough(),oR=z.object({UserID:z.string().nullish(),PublicData:Oe.nullish(),BuildObjectsProgress:rR.nullish(),IsBot:z.boolean().nullish(),SpinsCount:z.number().nullish(),TokensSpent:z.number().nullish(),MemberStatus:z.string().nullish(),GrandPrizeClaimed:z.boolean().nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),aR=z.object({Index:z.number().nullish(),OwnerUserID:z.string().nullish(),CurrentProgress:z.number().nullish(),MaxProgress:z.number().nullish(),IsCompleted:z.boolean().nullish()}).passthrough(),lR=z.object({Objects:z.array(aR).nullish()}).passthrough(),tc=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),CoopChainID:z.string().nullish(),CoopEventID:z.string().nullish(),CycleIndex:z.number().nullish(),Members:z.array(oR).nullish(),BuildObjectsState:lR.nullish(),Status:z.string().nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:z.number().nullish()}).passthrough(),ic=z.object({CoopChainID:z.string(),CycleIndex:z.number().nullish(),EventOrder:z.number().nullish(),EventDef:z.lazy(()=>sc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:z.number().nullish()}).passthrough(),uR=z.string(),zo=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Weight:z.number().nullish(),MinProgress:z.number().nullish(),MaxProgress:z.number().nullish()}).passthrough(),cR=z.object({Index:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxProgress:z.number().nullish(),CompletionReward:H.nullish()}).passthrough(),pR=z.object({Objects:z.array(cR).nullish(),PriceOptions:oe.nullish(),SpinnerTable:z.array(zo).nullish(),MaxSpinsPerCall:z.number().nullish()}).passthrough(),sc=z.object({CoopEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),EventType:uR.nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),BuildObjects:pR.nullish(),GrandPrize:H.nullish()}).passthrough(),hR=z.object({CoopChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:me.nullish(),Events:z.array(sc).nullish(),Gate:J.nullish()}).passthrough(),Ys=z.object({ServerTimeUtc:c.nullish(),UserState:iR.nullish(),ActiveGroup:tc.nullish()}),Ao=z.object({ServerTimeUtc:c.nullish(),Group:tc.nullish(),SecondsRemaining:_.nullish()}),nc=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Resources:M.nullish(),ObjectIndex:z.number().nullish(),Sector:zo.nullish(),RequestedSpins:z.number().nullish(),SpinsUsed:z.number().nullish(),Sectors:z.array(zo).nullish(),ProgressDelta:z.number().nullish(),NewProgress:_.nullish(),MaxProgress:_.nullish(),ObjectCompleted:z.boolean().nullish(),AllObjectsCompleted:z.boolean().nullish()}),wo=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),rc=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),Xs=z.object({Chains:z.record(z.string(),hR).nullish()}).passthrough(),ht={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var oc="CoopEvent",ac={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},en=class{constructor(e){this.ctx=e;e.cache.bindLoginView(ac,{schema:Ys,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(oc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(oc,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return b("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(ac,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return b("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return b("client","CoopChainID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let s=i.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,s){if(!e||!t)return b("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,RelatedEntityID:d()},r=await this.ctx.api.coopEvent.spin(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",r.data)),r}async claimObjectReward(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var dR={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},mR={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},fR=z.object({NodeID:z.string().nullish(),Status:z.string().nullish(),ExecutionCount:z.number().nullish(),UnlockedAtUtc:c.nullish(),CompletedAtUtc:c.nullish(),LastExecutedAtUtc:c.nullish(),NextAvailableAtUtc:c.nullish(),LastExecutionRefID:z.string().nullish()}).passthrough(),gR=z.object({TrackID:z.string().nullish(),CurrentValue:z.number().nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),lc=z.object({OfferID:z.string().nullish(),InstanceKey:z.string().nullish(),SourceOfferVersion:z.number().nullish(),Status:z.string().nullish(),ActivatedAtUtc:c.nullish(),ExhaustedAtUtc:c.nullish(),ExpiredAtUtc:c.nullish(),DismissedAtUtc:c.nullish(),ShowCount:z.number().nullish(),LastShownAtUtc:c.nullish(),Nodes:z.record(z.string(),fR).nullish(),Tracks:z.record(z.string(),gR).nullish(),SelectedChoiceNodeID:z.string().nullish()}).passthrough(),yR=z.object({SlotID:z.string().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),ActiveOfferID:z.string().nullish(),ActiveOfferStartedAtUtc:c.nullish(),ActiveOfferExpiresAtUtc:c.nullish(),ActiveOffer:lc.nullish(),NextCycleStartsAtUtc:c.nullish(),LastUpdatedUtc:c.nullish(),DismissSkipAvailableAtUtc:c.nullish(),LastDismissedAtUtc:c.nullish(),ActiveScheduleInstanceKey:z.string().nullish()}).passthrough(),RR=z.object({TotalExecutions:z.number().nullish(),DailyExecutions:z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),CR=z.object({TotalActivations:z.number().nullish(),TotalExhausted:z.number().nullish(),TotalExpired:z.number().nullish(),TotalDismissed:z.number().nullish(),TotalShows:z.number().nullish(),LastShownAtUtc:c.nullish(),LastActivatedAtUtc:c.nullish(),LastExhaustedAtUtc:c.nullish(),NodeCounts:z.record(z.string(),RR).nullish()}).passthrough(),SR=z.object({Slots:z.record(z.string(),yR).nullish(),OfferHistory:z.record(z.string(),CR).nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),xR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},bR={Eq:"Eq",Gte:"Gte",Lte:"Lte"},DR=z.object({Order:z.number().nullish(),OfferID:z.string().nullish(),DurationSec:z.number().nullish(),DelayBeforeActivationSec:z.number().nullish()}).passthrough(),tn=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),uc=z.object({Schedule:me.nullish(),Gate:J.nullish()}).passthrough(),cc=z.object({AllowDismissSkip:z.boolean().nullish(),DismissSkipDelaySec:z.number().nullish()}).passthrough(),PR=z.object({Identity:K.nullish(),Availability:K.nullish(),Behaviour:K.nullish()}).passthrough(),IR=z.object({SlotID:z.string().nullish(),Enabled:z.boolean().nullish(),Identity:tn.nullish(),Availability:uc.nullish(),Behaviour:cc.nullish(),Queue:z.array(DR).nullish(),Presets:PR.nullish()}).passthrough(),vR=z.object({ViewsRequiredToComplete:z.number().nullish(),MaxViewsPerActivation:z.number().nullish(),GrantRewardsPerView:z.boolean().nullish()}).passthrough(),TR=z.object({RewardedVideo:vR.nullish()}).passthrough(),kR=z.object({TrackID:z.string().nullish(),Operator:z.string().nullish(),Value:z.number().nullish()}).passthrough(),zR=z.object({Identity:K.nullish(),Graph:K.nullish(),Milestones:K.nullish()}).passthrough(),AR=z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish()}).passthrough(),wR=z.object({TrackID:z.string().nullish(),Amount:z.number().nullish(),RespectBounds:z.boolean().nullish()}).passthrough(),MR=z.object({TrackID:z.string().nullish(),DisplayName:z.string().nullish(),StartValue:z.number().nullish(),MinValue:z.number().nullish(),MaxValue:z.number().nullish(),ClampToMin:z.boolean().nullish(),ClampToMax:z.boolean().nullish(),HiddenFromUI:z.boolean().nullish()}).passthrough(),OR=z.object({RequiredCompletedNodeIDs:z.array(z.string()).nullish(),RequiredAnyCompletedNodeIDs:z.array(z.string()).nullish(),RequiredTracks:z.array(kR).nullish(),VisibleWhileLocked:z.boolean().nullish()}).passthrough(),pc=z.object({Options:oe.nullish()}).passthrough(),hc=z.object({Grants:H.nullish(),TrackChanges:z.array(wR).nullish(),MilestonePoints:z.number().nullish()}).passthrough(),UR=z.object({NodeID:z.string().nullish(),Type:z.string().nullish(),Identity:tn.nullish(),Pricing:pc.nullish(),Reward:hc.nullish(),Action:TR.nullish(),UnlockRules:OR.nullish(),NextNodeIDs:z.array(z.string()).nullish(),ChoiceGroupID:z.string().nullish(),Limits:ye.nullish(),HideWhenCompleted:z.boolean().nullish(),ExhaustOfferOnComplete:z.boolean().nullish(),Presets:AR.nullish()}).passthrough(),dc=z.object({RootNodeIDs:z.array(z.string()).nullish(),Nodes:z.array(UR).nullish(),Tracks:z.array(MR).nullish(),ExhaustedWhenAllTerminalNodesCompleted:z.boolean().nullish()}).passthrough(),mc=z.object({Milestones:z.record(z.string(),Be).nullish(),ClaimMode:z.string().nullish(),Token:jt.nullish()}).passthrough(),fc=z.object({OfferID:z.string().nullish(),Version:z.number().nullish(),Enabled:z.boolean().nullish(),Identity:tn.nullish(),Graph:dc.nullish(),Milestones:mc.nullish(),Presets:zR.nullish()}).passthrough(),ER=z.object({Identity:z.record(z.string(),tn).nullish(),Availability:z.record(z.string(),uc).nullish(),Behaviour:z.record(z.string(),cc).nullish(),Graph:z.record(z.string(),dc).nullish(),Milestones:z.record(z.string(),mc).nullish(),Pricing:z.record(z.string(),pc).nullish(),Reward:z.record(z.string(),hc).nullish()}).passthrough(),Mo=z.object({Slots:z.record(z.string(),IR).nullish(),Offers:z.record(z.string(),fc).nullish(),Presets:ER.nullish()}).passthrough(),gc=z.object({DealOfferDefinitions:Mo.nullish()}),yc=z.object({DealOffers:SR.nullish()}),qR=z.object({EntityID:z.string().nullish(),TotalEarned:z.number().nullish(),ClaimedIDs:z.array(z.string()).nullish(),ReachedUnclaimedIDs:z.array(z.string()).nullish()}).passthrough(),BR=z.object({SlotID:z.string().nullish(),SortOrder:z.number().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),OfferDef:fc.nullish(),ActivationState:lc.nullish(),IsNewActivation:z.boolean().nullish(),ComputedExpiresAtUtc:c.nullish(),Cost:St.nullish(),Milestone:qR.nullish(),ScheduleInstanceKey:z.string().nullish()}).passthrough(),sn=z.object({Slots:z.array(BR).nullish()}),Rc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),NodeID:z.string().nullish(),NodeCompleted:z.boolean().nullish(),OfferExhausted:z.boolean().nullish(),Idempotent:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Cc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),Sc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),xc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),bc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),ClaimedIDs:z.array(z.string()).nullish(),Rejected:z.record(z.string(),z.string()).nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),yt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var LR="DealOffer",Dc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},nn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Dc,{schema:sn,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(LR,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(Dc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${d()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,s){if(!e||!t)return b("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return c$1;let n=i&&i.trim().length>0?i.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:n??`deal_exec_${e}_${t}_${d()}`},p=await this.ctx.api.dealOffer.executeNode(r);return p.ok&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${d()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return b("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${d()}`},s=await this.ctx.api.dealOffer.claimMilestone(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;let i=[...new Set(t.map(r=>r.trim()).filter(r=>r.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${d()}`},n=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",n.data)),n}};var Pc="Referral",rn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Pc,e);if(t){let n={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",n),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Pc,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=Vt.parseReferralCode(e)?.toUpperCase();if(!t)return b("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},n=await this.ctx.api.referral.activateReferralCode(s);if(n.ok){let r=n.data;r.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(r.ReferrerUserID),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",r);}return n}async claimInviteReward(e){let t=e.trim();if(!t)return b("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},n=await this.ctx.api.referral.claimInviteReward(s);if(n.ok){let r=n.data;r.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(r.RewardID),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",r);}return n}async claimInviteRewardsBatch(e){let t=(e??[]).map(r=>r?.trim()).filter(Boolean);if(t.length===0)return b("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},n=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(n.ok){let r=n.data;for(let p of r.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",r);}return n}};var GR={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},Ic=z.enum(["System","Reward","Gift","Social"]).catch("System"),FR={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},VR=z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),jR={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},NR=z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),et={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},_R={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"},WR=100,KR=z.object({Subject:z.string().nullish(),Body:z.string().nullish()}).passthrough(),vc=z.object({FeatureID:z.string().nullish(),Args:z.record(z.string(),z.string()).nullish(),Url:z.string().nullish(),Label:z.string().nullish()}).passthrough(),QR=z.object({Texts:z.record(z.string(),KR).nullish(),Category:Ic.nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:vc.nullish(),SenderName:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),HR=z.object({Enabled:z.boolean().nullish(),Grant:ae.nullish(),Cost:ae.nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:c.nullish(),SenderGate:J.nullish(),TemplateID:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),$R=z.object({Type:z.string().nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxAmountPerGift:z.number().nullish()}).passthrough(),JR=z.object({Enabled:z.boolean().nullish(),AllowedResources:z.array($R).nullish(),MaxEntriesPerGift:z.number().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:c.nullish(),FeePercent:z.number().nullish(),FeeCost:ae.nullish(),SenderGate:J.nullish(),ExpirationDays:z.number().nullish(),TemplateID:z.string().nullish()}).passthrough(),Tc=z.object({Enabled:z.boolean().nullish(),Capacity:z.number().nullish(),RewardLetterDays:z.number().nullish(),PlainLetterDays:z.number().nullish(),ClaimedRetentionDays:z.number().nullish(),DefaultLanguage:z.string().nullish(),Templates:z.record(z.string(),QR).nullish(),Gifts:z.object({Social:z.record(z.string(),HR).nullish(),Transfer:JR.nullish()}).passthrough().nullish(),Integrations:z.object({Leaderboard:z.boolean().nullish(),CoopEvent:z.boolean().nullish(),Season:z.boolean().nullish(),Referral:z.boolean().nullish()}).passthrough().nullish()}).passthrough(),ZR=z.object({MessageID:z.string(),Source:VR,Category:Ic,TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:vc.nullish(),SenderName:z.string().nullish(),SenderUserID:z.string().nullish(),SenderAvatarUrl:z.string().nullish(),SenderNote:z.string().nullish(),Rewards:H.nullish(),HasRewards:z.boolean().nullish(),IsTransfer:z.boolean().nullish(),SentAt:c,ExpiresAt:c.nullish(),ReadAt:c.nullish(),ClaimedAt:c.nullish()}).passthrough(),YR=z.object({MessageID:z.string(),Module:NR,Key:z.string(),TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish()}).passthrough(),Oo=z.object({ID:z.string(),Error:z.string().nullish()}).passthrough(),kc=z.object({ServerTimeUtc:c.nullish(),Messages:z.array(ZR).default([]),NextCursor:z.string().nullish(),PendingRewards:z.array(YR).nullish(),UnreadCount:z.number().nullish(),UnclaimedCount:z.number().nullish(),DeliveredNow:z.number().nullish()}).passthrough(),on=z.object({ServerTimeUtc:c.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Uo=z.object({ServerTimeUtc:c.nullish(),AffectedCount:z.number().default(0),Failed:z.array(Oo).default([]),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),XR=z.object({MessageID:z.string(),Rewards:ae.nullish()}).passthrough(),an=z.object({ServerTimeUtc:c.nullish(),Claimed:z.array(XR).default([]),Failed:z.array(Oo).default([]),Resources:M.nullish(),Inventory:Q.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),zc=z.object({ServerTimeUtc:c.nullish(),GiftID:z.string().nullish(),Sent:z.array(z.string()).default([]),Failed:z.array(Oo).default([]),Resources:M.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish()}).passthrough(),Ac=z.object({ServerTimeUtc:c.nullish(),MessageID:z.string().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),RecipientReceives:ae.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish(),IdempotentReplay:z.boolean().nullish()}).passthrough(),wc=z.object({ServerTimeUtc:c.nullish(),ResetsAt:c.nullish(),Social:z.record(z.string(),z.object({IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ReceivedInPeriod:z.number().default(0),SentTo:z.array(z.string()).default([]),ResetsAt:c.nullish()}).passthrough()).default({}),Transfer:z.object({Enabled:z.boolean().default(false),IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish()}).passthrough().nullish()}).passthrough();var Eo="Mailbox",qo={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},ln=class{constructor(e){this.ctx=e;e.cache.bindLoginView(qo,{schema:on,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(qo,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Eo)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Eo,e);if(t)return a(t);let i=this.request();if(!i)return c$1;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(Eo,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return c$1;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(qo,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return c$1;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return c$1;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return b("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):c$1}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return b("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):c$1}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):c$1}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return c$1;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return b("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return b("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return c$1;let n=await this.ctx.api.mailbox.sendGift(s);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",n.data)),n}async sendTransfer(e,t,i){if(!e?.trim())return b("client","RecipientUserID is required.");if(!i?.requestID?.trim())return b("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return c$1;let n=await this.ctx.api.mailbox.sendTransfer(s);return n.ok&&(n.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(n.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",n.data)),n}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):c$1}};var eC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},tC={Title:"Title",Platform:"Platform"},Mc=z.object({UserID:z.string(),PublicData:Oe.nullish(),Source:z.enum(["Title","Platform"]).nullish()}),Ii=z.object({Friends:z.array(Mc).nullish()}),iC=z.object({FriendsCount:z.number().nullish(),IncomingRequestsCount:z.number().nullish(),OutgoingRequestsCount:z.number().nullish()}),vi=z.object({TargetUserID:z.string().nullish(),Status:z.string().nullish(),Target:Mc.nullish(),Counters:iC.nullish()}),sC={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},nC={Like:"Like",Favorite:"Favorite"},rC={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},oC={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},aC={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},lC=z.object({Key:z.string().nullish(),DisplayName:z.string().nullish(),AvatarUrl:z.string().nullish()}).passthrough(),uC=z.object({Id:z.string(),Verb:z.string().nullish(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),Count:z.number().nullish(),LastActors:z.array(lC).nullish(),Payload:z.object({Title:z.string().nullish(),Excerpt:z.string().nullish(),ImageUrl:z.string().nullish()}).passthrough().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),OccurredAt:c.nullish(),OwnerImpact:M.nullish(),IsBlocked:z.boolean().nullish(),TargetObjectName:z.string().nullish()}).passthrough(),Oc=z.object({Items:z.array(uC).nullish(),HasMore:z.boolean().nullish(),NextBeforeUpdatedAt:z.string().nullish(),NextBeforeID:z.string().nullish(),UnreadCount:z.number().nullish(),SeenAt:c.nullish()}).passthrough(),Ti=z.object({UnreadCount:z.number().nullish(),SeenAt:c.nullish()}).passthrough(),cC=z.object({Likes:z.number().nullish(),Favorites:z.number().nullish(),Followers:z.number().nullish(),Following:z.number().nullish(),Comments:z.number().nullish(),Replies:z.number().nullish(),Posts:z.number().nullish(),Dislikes:z.number().nullish()}).passthrough(),qt=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Counts:cC.nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish(),Following:z.boolean().nullish(),Blocked:z.boolean().nullish()}).passthrough(),Uc=z.object({Items:z.array(qt).nullish()}).passthrough(),Bo={HasMore:z.boolean().nullish(),NextCursorAt:z.string().nullish(),NextCursorID:z.string().nullish()},pC=z.object({UserID:z.string(),PublicData:Oe.nullish(),Mutual:z.boolean().nullish(),Since:c.nullish()}).passthrough(),un=z.object({Items:z.array(pC).nullish(),...Bo}).passthrough(),hC=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Kind:z.string().nullish(),At:c.nullish()}).passthrough(),Ec=z.object({Items:z.array(hC).nullish(),...Bo}).passthrough(),cn=z.object({CommentID:z.string(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),ParentCommentID:z.string().nullish(),AuthorUserID:z.string().nullish(),AuthorPublicData:Oe.nullish(),Text:z.string().nullish(),Status:z.string().nullish(),Pinned:z.boolean().nullish(),CreatedAt:c.nullish(),EditedAt:c.nullish(),Likes:z.number().nullish(),Replies:z.number().nullish(),Liked:z.boolean().nullish(),IsMine:z.boolean().nullish()}).passthrough(),qc=z.object({Items:z.array(cn).nullish(),...Bo,TotalCount:z.number().nullish()}).passthrough(),Bc=z.object({CommentID:z.string().nullish(),Deleted:z.boolean().nullish()}).passthrough(),Lc=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish(),AutoHidden:z.boolean().nullish()}).passthrough(),Gc=z.object({CommentsEnabled:z.boolean().nullish(),CommentableTypes:z.array(z.string()).nullish(),CommentMaxLength:z.number().nullish(),CommentMaxLinks:z.number().nullish()}).passthrough(),dC="FRIENDS_FROM_PLATFORM",mC={Off:"Off",Default:"Default",Always:"Always"},fC={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Fc=z.object({Profile:z.enum(["Off","Default","Always"]).nullish(),Friends:z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish()}).passthrough(),Re={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report"};var Lo={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},pn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Lo,{schema:Ti,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return c$1;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return b("client","TargetUserID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return b("client","FriendUserID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return c$1;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(Lo,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(Lo,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):c$1}async getEntityStates(e,t){if(!t?.length)return b("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):c$1}async addComment(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i?.trim())return b("client","Text is required.");n.Text=i,n.ParentCommentID=s;let r=await this.ctx.api.social.addComment(n);return r.ok&&this.ctx.emitter.emit("social:commentAdded",r.data),r}async editComment(e,t){if(!e)return b("client","CommentID is required.");if(!t?.trim())return b("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.CommentID=e,i.Text=t;let s=await this.ctx.api.social.editComment(i);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return b("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=i.parentCommentID,this.applyPage(s,i.cursor,i.limit),this.ctx.api.social.getComments(s))}async report(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i)return b("client","ReportReason is required.");n.ReportReason=i,n.ReportComment=s;let r=await this.ctx.api.social.report(n);return r.ok&&this.ctx.emitter.emit("social:reported",r.data),r}async mutate(e,t,i,s){let n=this.targetRequest(t,i);if("ok"in n)return n;n.ReactionKind=s;let r=await this.ctx.api.social[e](n);return r.ok&&this.ctx.emitter.emit("social:entityStateChanged",r.data),r}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):c$1}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return b("client","EntityType is required.");if(!t)return b("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):c$1}};var Vc="TimedBoost";function gC(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var hn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Vc,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Vc,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let i=e.trim();if(!gC(i))return b("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${d()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok){let r=n.data;if(r.ActivatedBoost){let p=r.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(r.ActivatedBoost,p);}this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",r);}return n}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var It={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},yC={Client:"Client",Server:"Server",System:"System"},RC=z.enum(["Client","Server","System"]).catch("Client"),CC=z.object({Value:z.string().nullish(),UpdatedAt:c.nullish(),Version:z.number().nullish(),LastWriter:RC.nullish(),ExpiresAt:c.nullish()}).passthrough(),dn=z.record(z.string(),CC),jc=z.object({Version:z.number().nullish(),Private:dn.nullish(),Public:dn.nullish(),ReadOnly:dn.nullish()}),Go=z.object({UserID:z.string().nullish(),Version:z.number().nullish(),Public:dn.nullish()}),Fo=z.object({ServerTimeUtc:c.nullish(),Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:c.nullish()}),SC=z.object({Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:c.nullish()}),Nc=z.object({ServerTimeUtc:c.nullish(),Results:z.array(SC).nullish()}),_c=z.object({ServerTimeUtc:c.nullish(),DeletedCount:z.number().nullish()}),Wc=z.object({Results:z.array(Go).nullish(),NotFoundUserIDs:z.array(z.string()).nullish()}),xC={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},bC=z.enum(["String","Int","Bool","Json"]).catch("String"),DC=z.object({KeyID:z.string(),Bucket:z.string().nullish(),ValueType:bC.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),mn=z.object({Keys:z.record(z.string(),DC).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),dt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var PC="UserCustomData";function Kc(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var fn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(PC,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,It.Private)}async setPublicData(e,t){return this.setData(e,t,It.Public)}async setData(e,t,i){let s=e.trim();if(!Kc(s))return b("client",'KeyID is required and must not contain "." or "$".');if(t==null)return b("client","Value is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(i===It.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(p.ok){let d=p.data;this.ctx.data.user.patchUserCustomDataKey(i,d.KeyID,t,d.Version??0,d.ExpiresAt),this.ctx.emitter.emit(i===It.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",d);}return p}async deleteKey(e,t){let i=e.trim();if(!Kc(i))return b("client",'KeyID is required and must not contain "." or "$".');if(t!==It.Private&&t!==It.Public)return b("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},n=await this.ctx.api.userCustomData.deleteKey(s);return n.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),n}async batchSet(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let n=s.Bucket??It.Private,r=e.find(p=>p.Bucket===n&&p.KeyID===s.KeyID);r&&this.ctx.data.user.patchUserCustomDataKey(n,s.KeyID,r.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return b("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var IC="TitleCustomDataDefinitions",Qc=50;function vC(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}function Vo(o){if(o.ExpiresAt==null)return false;let e=Date.parse(o.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function TC(o){let e={};for(let[t,i]of Object.entries(o))Vo(i)||(e[t]=i);return e}var gn=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(IC,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return c$1;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(n=>n.trim()).filter(n=>n.length>0);if(!t.length)return b("client","At least one KeyID is required.");if(t.some(n=>!vC(n)))return b("client",'KeyID must not contain "." or "$".');if(t.length>Qc)return b("client",`At most ${Qc} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return c$1;i.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Vo(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Vo(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=TC(this.runtimeCache),e.Runtime=this.runtimeCache):e.Runtime&&(this.runtimeCache=e.Runtime),e.RuntimeVersion!=null&&(this.lastRuntimeVersion=e.RuntimeVersion),this.ctx.emitter.emit("titleCustomData:publicDataLoaded",e);}};var yn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var kC=15,zC="GameLoop",Hc="BoardDefinition",Rn=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(zC,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(Hc,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),a(i);let s=this.ctx.authedRequest();if(!s)return c$1;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(Hc,n.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n.data)),n}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return b("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return c$1;i.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return b("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let n=s.data,r=kl(new Date,kC);this.ctx.data.user.patchBoardState(p=>{p.Position=n.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(n.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),n.ActionRequired&&n.ActionData?p.Pending={Type:n.ActionRequired,TargetUserID:n.ActionData.TargetUserID,TargetPublicData:n.ActionData.PublicData,TargetBuildingStates:n.ActionData.TargetBuildingStates??void 0,TargetHasShield:n.ActionData.TargetHasShield??void 0,RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:r}:n.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:r,Special:{ModeID:n.SpecialModeOffer.ModeID??void 0,Choices:n.SpecialModeOffer.Choices??void 0}});}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),n.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",n);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.IsBotTarget&&n.Operation?this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs):!n.IsBotTarget&&n.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(n.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",n);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return b("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${d()}`},n=await this.ctx.api.gameLoop.boardLoopRaid(s);if(n.ok){let r=n.data;r.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(r.RaidLayout,r.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(r)),this.ctx.emitter.emit("gameLoop:boardRaided",r);}else await this.getUserBoardState();return n}async boardLoopRaidFast(e){if(!e.length)return b("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(s.ok){let n=s.data;n.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(n)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",n);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return b("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let n=s.data;n.StageComplete?this.ctx.data.user.patchBoardState(r=>{r.StageLevel=(r.StageLevel??1)+1,r.Position=0,r.Pending=null,r.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(n.BuiltIndex,r=>{n.NewLevel!=null&&(r.Level=n.NewLevel),r.IsDamaged=false,n.MaxLevelRewardClaimed&&(r.MaxLevelRewardClaimed=true);}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",n);}return s}async boardSpecialChoose(e,t){if(!e)return b("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${d()}`},n=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(n.ok){let r=n.data;r.Mode==="Instant"||r.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(d=>{d.ChoiceID=e,d.ChosenMode=r.Mode??"Timed",d.StartedAtUtc=r.StartedAtUtc??null,d.DurationSeconds=r.DurationSeconds??null,d.AdViewsUsed=0;}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",r);}return n}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let n=s.data;this.ctx.data.user.patchBoardSpecialPending(r=>{r.AdViewsUsed=n.AdViewsUsed??0,r.AccumulatedMultiplier=n.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",n);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${d()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",n);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return c$1;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return b("client","milestoneID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var Cn=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let n=e.trim();if(!n)return b("client","FunctionName is required.");if(!this.ctx.auth.context)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(r);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var $c=z.object({ServerTimeUtc:c,SourceType:ii,SourceID:z.string(),TargetType:ii,TargetID:z.string(),SourceSpent:_,FeeAmount:_,RateApplied:Y,TargetCredited:_}),Jc=z.object({ServerTimeUtc:c,SourceType:ii,SourceID:z.string(),TargetType:ii,TargetID:z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),Sn={Convert:"Convert",CryptoConvert:"CryptoConvert"},AC={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},Zc=z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),wC={Automatic:"Automatic",Manual:"Manual"},MC=z.enum(["Automatic","Manual"]).catch("Automatic"),OC=z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),InitialDeposit:z.number().nullish(),MinBalance:z.number().nullish(),MaxBalance:z.number().nullish(),DailyEarnLimit:z.number().nullish(),DailySpendLimit:z.number().nullish()}).passthrough(),UC=z.object({Rate:z.number().nullish(),Max:z.number().nullish(),Period:z.number().nullish()}).passthrough(),EC=z.object({IsTradable:z.boolean().nullish(),IsPurchasable:z.boolean().nullish(),IsRefundable:z.boolean().nullish()}).passthrough(),qC=z.object({TargetCurrencyType:ii.nullish(),TargetCurrencyID:z.string(),Rate:Y.nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish(),DailyLimit:z.number().nullish()}).passthrough(),Yc=z.object({Enabled:z.boolean().nullish(),RateMode:MC.nullish(),Fee:z.number().nullish(),Targets:z.array(qC).nullish()}).passthrough(),Xc=z.object({CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough(),BC=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Economy:OC.nullish(),Recharge:UC.nullish(),Conversion:Yc.nullish(),Permissions:EC.nullish(),Audit:Xc.nullish(),Status:Zc.nullish()}).passthrough(),LC=z.object({NetworkID:z.string(),ContractAddress:z.string().nullish(),Decimals:z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),GC=z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),FC=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),SpendableInGame:z.boolean().nullish(),ConvertibleToVirtual:z.boolean().nullish()}).passthrough(),VC=z.object({Mode:z.string().nullish(),FundingNetworkID:z.string().nullish(),PerPlayerDailyTokens:z.number().nullish(),TitleDailyTokens:z.number().nullish()}).passthrough(),jo=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),DisplayDecimals:z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),UsdPriceRefreshMinutes:z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:z.array(LC).nullish(),Limits:GC.nullish(),Permissions:FC.nullish(),Conversion:Yc.nullish(),Audit:Xc.nullish(),Status:Zc.nullish(),ServerGrantPolicy:VC.nullish(),UnbackedRewardCurrencyID:z.string().nullish()}).passthrough(),xn=z.object({VirtualCurrencies:z.record(z.string(),BC).nullish(),CryptoCurrencies:z.record(z.string(),jo).nullish()}).passthrough();var jC={EVM:"EVM",Solana:"Solana"},NC=z.enum(["EVM","Solana"]).catch("EVM"),_C={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},WC=z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),KC={Token:"Token",Nft:"Nft"},ep=z.enum(["Token","Nft"]).catch("Token"),QC={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},HC=z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),$C={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},JC=z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),ZC={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},No=z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),tp={GameTopUp:"game_topup",CommunityReward:"community_reward"};function bn(o){let e=o?.trim();return e||tp.GameTopUp}var YC={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},ip=z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),XC=z.object({ContractAddress:z.string().nullish(),ItemCatalogID:z.string().nullish(),DisplayName:z.string().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),sp=z.object({Ios:z.boolean().nullish(),Android:z.boolean().nullish(),Web:z.boolean().nullish()}).passthrough(),eS=z.object({NetworkID:z.string().nullish(),DisplayName:z.string().nullish(),Type:NC.nullish(),ChainID:z.number().nullish(),ChainTicker:z.string().nullish(),RewardPoolAddress:z.string().nullish(),VaultDepositAddress:z.string().nullish(),ChainConfigVersion:z.number().nullish(),RequiredConfirmations:z.number().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:sp.nullish(),NftCollections:z.array(XC).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RpcUrl:z.string().nullish(),GasPrice:z.number().nullish(),NftBridgeAddress:z.string().nullish(),SignatureEpoch:z.number().nullish()}).passthrough(),tS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:sp.nullish()}).passthrough(),iS=z.object({MinAccountAgeDays:z.number().nullish(),MultiAccountCheckEnabled:z.boolean().nullish(),BanOnSharedWithdrawalAddress:z.boolean().nullish(),PendingWithdrawalTtlHours:z.number().nullish()}).passthrough(),sS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},nS=z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),np=z.object({Enabled:z.boolean().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:nS.nullish(),DenyMessage:z.string().nullish()}).passthrough(),rS=z.object({Enabled:z.boolean().nullish(),WalletConnectProjectId:z.string().nullish()}).passthrough(),oS={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},ki=z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),aS=z.object({Mode:ki.nullish(),TokenGates:z.array(np).nullish()}).passthrough(),_o=z.object({SystemState:tS.nullish(),Networks:z.record(z.string(),eS).nullish(),AccountSafety:iS.nullish(),WalletLogin:rS.nullish(),PlayAccess:aS.nullish(),IframeConnectHosts:z.array(z.string()).nullish()}).passthrough(),lS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),LinkedAt:c.nullish(),LastUsedAt:c.nullish(),LinkType:WC.nullish(),IsSignatureVerified:z.boolean().nullish()}).passthrough(),rp=z.object({TitleTransactionID:z.string().nullish(),Type:ep.nullish(),NetworkID:z.string().nullish(),AssetID:z.string().nullish(),Amount:Y.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),uS=z.object({Status:HC.nullish(),Tier:JC.nullish(),VerifiedAt:c.nullish(),ExpiresAt:c.nullish(),RejectedAt:c.nullish(),ProviderReference:z.string().nullish(),RejectionReason:z.string().nullish()}).passthrough(),cS=z.object({CurrencyID:z.string().nullish(),Deposits:z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),pS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:z.record(z.string(),cS).nullish()}).passthrough(),hS=z.object({NetworkID:z.string().nullish(),ItemCatalogID:z.string().nullish(),Deposits:z.number().nullish(),Withdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),dS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),PerCollection:z.record(z.string(),hS).nullish()}).passthrough(),mS=z.object({Tokens:pS.nullish(),Nfts:dS.nullish()}).passthrough(),Wo=z.object({CurrencyID:z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Bt=z.object({Granted:z.boolean(),Mode:ki.nullish(),Error:z.string().nullish(),WalletRequired:z.boolean().nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),GrantedUntil:c.nullish(),Balances:z.array(Wo).nullish()}).passthrough(),fS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:c.nullish(),Passed:z.boolean().nullish(),GrantedUntil:c.nullish(),Error:z.string().nullish(),Balances:z.array(Wo).nullish()}).passthrough(),gS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CanUnlink:z.boolean().nullish()}).passthrough(),op=z.object({Mode:ki.nullish(),TokenGates:z.array(np).nullish(),WalletLoginEnabled:z.boolean().nullish(),CanLinkWallet:z.boolean().nullish(),WalletsFromPlatformProfile:z.boolean().nullish(),LinkedWallets:z.array(gS).nullish(),Status:Bt.nullish()}).passthrough(),yS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:c.nullish(),LoggedInAt:c.nullish(),GatePassed:z.boolean().nullish(),GatedBalances:z.array(Wo).nullish()}).passthrough(),RS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),UnlinkedAt:c.nullish()}).passthrough(),CS=z.object({Version:z.number().nullish(),Stats:mS.nullish(),LinkedWallets:z.record(z.string(),lS).nullish(),LastWalletLogin:yS.nullish(),PlayAccess:fS.nullish(),PendingWithdrawals:z.array(rp).nullish(),Kyc:uS.nullish(),FirstActivityAt:c.nullish(),LastActivityAt:c.nullish(),IsFlagged:z.boolean().nullish(),FlagReason:z.string().nullish(),UnlinkedWallets:z.array(RS).nullish()}).passthrough(),SS=z.object({CurrencyID:z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:c}).passthrough(),hi=z.object({CryptoBalances:z.record(z.string(),SS).nullish(),PendingAdded:rp.nullish(),PendingRemovedIDs:z.array(z.string()).nullish()}).passthrough(),xS=z.object({Amount:Y,Frozen:Y,CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough().transform(o=>o),bS=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:ip.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:No.nullish(),SignatureData:z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),TokenID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:c.nullish(),BurnAmount:z.number().nullish(),RefundedAt:c.nullish(),RefundCheckedAt:c.nullish()}).passthrough(),DS=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:ip.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:No.nullish(),SignatureData:z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),NFTID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),SkinID:z.string().nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:c.nullish()}).passthrough(),ap=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),Ko=z.object({TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),ContractAddress:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(ap).nullish(),Signature:z.string().nullish()}).passthrough(),Qo=z.object({Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),ProgramID:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(ap).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),lp=z.object({Blockchain:_o.nullish(),CryptoCurrencies:z.record(z.string(),jo).nullish()}).passthrough(),up=z.object({State:CS.nullish(),CryptoBalances:z.record(z.string(),xS).nullish()}).passthrough(),cp=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:hi.nullish()}).passthrough(),pp=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),hp=z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:c.nullish(),EvmSignature:Ko.nullish(),SolanaSignature:Qo.nullish(),StateDelta:hi.nullish(),ChainID:z.number().nullish()}).passthrough(),dp=z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),EvmSignature:Ko.nullish(),SolanaSignature:Qo.nullish(),StateDelta:hi.nullish(),Inventory:Q.nullish()}).passthrough(),mp=z.object({TokenTransactions:z.array(bS).nullish(),NFTTransactions:z.array(DS).nullish(),RefundedIDs:z.array(z.string()).nullish()}).passthrough(),Ho=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:z.string().nullish()}).passthrough(),fp=z.object({TitleTransactionID:z.string().nullish(),Kind:ep.nullish(),EvmSignature:Ko.nullish(),SolanaSignature:Qo.nullish()}).passthrough(),gp=z.object({TitleTransactionID:z.string().nullish(),OnChainTxHash:z.string().nullish(),Status:No.nullish(),StateDelta:hi.nullish()}).passthrough(),Qe={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",DepositToken:"DepositToken",DepositNFT:"DepositNFT",RequestTokenWithdrawal:"RequestTokenWithdrawal",RequestNFTWithdrawal:"RequestNFTWithdrawal",GetTransactionHistory:"GetTransactionHistory",RetryWithdrawal:"RetryWithdrawal",ConfirmWithdrawal:"ConfirmWithdrawal",DonateToDeveloper:"DonateToDeveloper",DonateToUsersPool:"DonateToUsersPool",GetPlayAccess:"GetPlayAccess",ConfirmPlayAccess:"ConfirmPlayAccess"};var PS="Blockchain",yp="Blockchain:Definitions",Dn=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(yp,e);if(t)return a(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return c$1;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(PS,n.data.Blockchain),this.ctx.data.config.patchSection(yp,n.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",n.data)),n)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,i,s,n){if(!e)return b("client","CurrencyID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let r=this.ctx.authedRequest();if(!r)return c$1;r.CurrencyID=e,r.NetworkID=t,r.WalletAddress=i,r.Amount=s,r.Category=bn(n);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(r);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,i,s,n,r,p){if(!e)return b("client","ItemID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.NetworkID=t,d.WalletAddress=i,d.Amount=s,d.Category=bn(n),r!==void 0&&(d.Level=r),p&&(d.ItemInstanceID=p);let C=await this.ctx.api.blockchain.requestNFTWithdrawal(d);return C.ok&&(this.ctx.data.user.applyBlockchainStateDelta(C.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(C.data.Resources,C.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",C.data)),C}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return c$1;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return b("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return b("client","TitleTransactionID is required.");if(!t)return b("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.TitleTransactionID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var IS={Head:"Head",Torso:"Torso",Legs:"Legs"},Pn=z.enum(["Head","Torso","Legs"]).catch("Head"),vS={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},$o=z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),Cp=z.object({AttackTarget:Pn,DefenseTarget:Pn});var TS=z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),kS=z.object({RoundIndex:z.number().nullish(),AttackerID:z.string().nullish(),DefenderID:z.string().nullish(),AttackZone:Pn.nullish(),DefenseZone:Pn.nullish(),HitType:TS.nullish(),DamageDealt:z.number().nullish(),DefenderHpRemaining:z.number().nullish()}).passthrough(),zS=z.object({MaxHp:z.number().nullish(),CurrentHp:z.number().nullish(),Damage:z.number().nullish(),AttackSpeed:z.number().nullish(),CritChance:z.number().nullish(),CritMultiplier:z.number().nullish(),Armor:z.number().nullish(),DodgeChance:z.number().nullish()}).passthrough(),AS=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Rp=z.object({UserID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),SelectedCharacter:xo.nullish(),BattleStrategy:z.array(Cp).nullish(),UnstackableItems:z.record(z.string(),AS).nullish(),Stats:zS.nullish()}).passthrough(),wS=z.object({WinnerUserID:z.string().nullish(),LoserUserID:z.string().nullish(),Entry:ae.nullish(),NetReward:ae.nullish(),BattleLog:z.array(kS).nullish(),IsDraw:z.boolean().nullish(),P1BattleProfile:Rp.nullish(),P2BattleProfile:Rp.nullish()}).passthrough(),Sp=z.object({MatchID:z.string(),TitleID:z.string().nullish(),RuleID:z.string().nullish(),CreatedAt:c.nullish(),CreatorID:z.string().nullish(),CreatorCharacterID:z.string().nullish(),CreatorStrategy:z.array(Cp).nullish(),TargetUserID:z.string().nullish(),Entry:ae.nullish(),CreationCostPaid:ae.nullish(),RefundCreationCostOnCancel:z.boolean().nullish(),ExpiresAt:c.nullish(),JoinedByUserID:z.string().nullish(),JoinedByCharacterID:z.string().nullish(),JoinedAt:c.nullish(),Status:$o.nullish(),WinnerUserID:z.string().nullish(),CompletedAt:c.nullish(),IsRewardDistributed:z.boolean().nullish(),RewardDistributedAt:c.nullish()}).passthrough(),xp=z.object({Status:$o,MatchID:z.string(),Entry:ae.nullish(),Resources:M.nullish()}),bp=z.object({Match:Sp.nullish()}),Dp=z.object({MatchID:z.string(),Status:$o,Resources:M.nullish()}),Pp=z.object({Battle:wS.nullish(),Resources:M.nullish(),ResourcesDual:xt.nullish()}),Jo=z.object({Matches:z.array(Sp).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}),Rt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var MS=z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var OS=z.enum(["Constant","Variable","Curve"]).catch("Constant"),US=z.object({HealthStatID:z.string().nullish(),DamageStatID:z.string().nullish(),ArmorStatID:z.string().nullish(),AttackSpeedStatID:z.string().nullish(),CritChanceStatID:z.string().nullish(),CritDamageStatID:z.string().nullish(),DodgeStatID:z.string().nullish(),AllMightStatID:z.string().nullish()}).passthrough(),ES=z.enum(["Flat","PercentReduction"]).catch("Flat"),qS=z.object({MaxRounds:z.number().nullish(),BlockDamageMultiplier:z.number().nullish(),MinHitDamage:z.number().nullish(),DefaultCritMultiplier:z.number().nullish(),MaxCritChance:z.number().nullish(),MaxDodgeChance:z.number().nullish(),ArmorMode:ES.nullish(),MaxArmorReduction:z.number().nullish()}).passthrough(),BS=z.object({Kind:OS.nullish(),Constant:z.number().nullish(),VariableID:z.string().nullish(),Argument:z.string().nullish(),Curve:Fe.nullish(),OnePlus:z.boolean().nullish()}).passthrough(),LS=z.object({Coefficient:z.number().nullish(),Factors:z.array(BS).nullish()}).passthrough(),Kt=z.object({Terms:z.array(LS).nullish()}).passthrough(),GS=z.object({Health:Kt.nullish(),Damage:Kt.nullish(),Armor:Kt.nullish(),AttackSpeed:Kt.nullish(),CritChance:Kt.nullish(),CritDamage:Kt.nullish(),Dodge:Kt.nullish()}).passthrough(),Ip=z.object({StatMapping:US.nullish(),Combat:qS.nullish(),Formula:GS.nullish()}).passthrough(),FS=z.object({BurnRate:z.number().nullish()}).passthrough(),zi=z.object({Kind:MS.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),TokenType:Fi.nullish(),EntityID:z.string().nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish()}).passthrough(),vp=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(zi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),Tp=z.object({PriceOptions:oe.nullish(),RefundCostOnCancel:z.boolean().nullish(),MaxOpenMatches:z.number().nullish(),OfferLifetimeSeconds:z.number().nullish(),Limits:ye.nullish(),AllowPrivateMatches:z.boolean().nullish(),MaxMatchesPerOpponentPerDay:z.number().nullish()}).passthrough(),VS=z.object({RuleID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Economy:FS.nullish(),Entry:vp.nullish(),Creation:Tp.nullish(),Settings:Ip.nullish()}).passthrough(),jS=z.object({Rules:z.record(z.string(),VS).nullish(),Defaults:Ip.nullish(),EntryDefaults:vp.nullish(),CreationDefaults:Tp.nullish()}).passthrough(),Zo=z.object({InstantBattle:jS.nullish()}).passthrough(),kp=Zo;var NS={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Yo=z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),_S={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Xo=z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),WS={Burn:"Burn",Ledger:"Ledger"},KS=z.enum(["Burn","Ledger"]).catch("Burn"),vn={Item:"Item",VirtualCurrency:"VirtualCurrency"},ea=z.enum(["Item","VirtualCurrency"]).catch("Item"),QS=z.object({Percent:z.number().nullish(),MinPerPosition:_.nullish()}).passthrough(),Tn=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(zi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),ta=z.object({Percent:z.number().nullish(),MinPerPosition:_.nullish(),Sink:KS.nullish(),LedgerAccountID:z.string().nullish(),PerCatalogOverrides:z.record(z.string(),QS).nullish(),ApplyToDirectTrades:z.boolean().nullish()}).passthrough(),HS=z.object({AllowedCatalogIDs:z.array(z.string()).nullish(),DeniedCatalogIDs:z.array(z.string()).nullish(),DeniedItemIDs:z.array(z.string()).nullish(),AllowUnstackableWithState:z.boolean().nullish(),AllowedCurrencyIDs:z.array(z.string()).nullish(),DeniedCurrencyIDs:z.array(z.string()).nullish()}).passthrough(),$S=z.object({Enabled:z.boolean().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),MaxActiveListings:z.number().nullish(),CreateLimits:ye.nullish(),BuyLimits:ye.nullish(),ListingFeeOptions:oe.nullish(),RefundListingFeeOnCancel:z.boolean().nullish()}).passthrough(),JS=z.object({Enabled:z.boolean().nullish(),MinDurationHours:z.number().nullish(),MaxDurationHours:z.number().nullish(),AntiSnipeWindowSeconds:z.number().nullish(),AntiSnipeExtensionSeconds:z.number().nullish(),MaxAntiSnipeExtensions:z.number().nullish(),MinBidStepPercent:z.number().nullish(),MinBidStepAbsolute:_.nullish(),BidLimits:ye.nullish()}).passthrough(),ZS=z.object({Enabled:z.boolean().nullish(),MaxActiveOrders:z.number().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),CreateLimits:ye.nullish(),FillLimits:ye.nullish()}).passthrough(),YS=z.object({Enabled:z.boolean().nullish(),OfferExpirationHours:z.number().nullish(),MaxPendingOutgoing:z.number().nullish(),AllowGifts:z.boolean().nullish(),CreateLimits:ye.nullish()}).passthrough(),XS=z.object({Enabled:z.boolean().nullish()}).passthrough(),ia=z.object({Enabled:z.boolean().nullish(),Gate:J.nullish(),Schedule:me.nullish(),PricePolicy:Tn.nullish(),Commission:ta.nullish(),Tradability:HS.nullish(),Listings:$S.nullish(),Auctions:JS.nullish(),BuyOrders:ZS.nullish(),DirectTrades:YS.nullish(),Matching:XS.nullish()}).passthrough(),zp=z.object({BidIndex:z.number().nullish(),UserID:z.string().nullish(),Amount:_.nullish(),Settled:z.boolean().nullish(),SettledAt:c.nullish()}).passthrough(),ex=z.object({BidAxisType:si.nullish(),BidCurrencyID:z.string().nullish(),BidCatalogID:z.string().nullish(),BidItemID:z.string().nullish(),StartingBid:_.nullish(),CurrentBid:_.nullish(),CurrentBidderID:z.string().nullish(),BidCount:z.number().nullish(),ExtensionCount:z.number().nullish(),PendingRefunds:z.array(zp).nullish()}).passthrough(),In=z.object({LastAt:c.nullish(),DailyCount:z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),tx=z.object({Create:In.nullish(),Buy:In.nullish(),Sell:In.nullish(),Bid:In.nullish()}).passthrough(),ix=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),sx=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:ix.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),vt=z.object({OfferID:z.string().nullish(),OfferType:Yo.nullish(),Status:Xo.nullish(),CreatorUserID:z.string().nullish(),CreatorPublicData:Oe.nullish(),TargetUserID:z.string().nullish(),GoodsType:ea.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:_.nullish(),GoodsInstances:z.array(sx).nullish(),Price:ae.nullish(),Auction:ex.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),nx=z.object({GoodsType:ea.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),CountsByType:z.partialRecord(Yo,_).nullish()}).passthrough(),Ap=z.object({Definitions:ia.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish()}).passthrough(),sa=z.object({Offers:z.array(vt).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),wp=z.object({Groups:z.array(nx).nullish()}).passthrough(),Mp=z.object({Offer:vt.nullish()}).passthrough(),at=z.object({OfferID:z.string().nullish(),Status:Xo.nullish(),Settlement:xt.nullish(),Resources:M.nullish(),CommissionTaken:ae.nullish()}).passthrough(),Ai=z.object({OfferID:z.string().nullish(),Offer:vt.nullish(),Resources:M.nullish(),Matched:z.boolean().nullish(),Settlement:at.nullish()}).passthrough(),Op=z.object({OfferID:z.string().nullish(),CurrentBid:_.nullish(),BidCount:z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish()}).passthrough(),kn=z.object({MyOffers:z.array(vt).nullish(),MyBids:z.array(vt).nullish(),MyBuyOrders:z.array(vt).nullish(),IncomingTrades:z.array(vt).nullish(),OutgoingTrades:z.array(vt).nullish(),Claimables:z.array(vt).nullish(),DrainedRefunds:z.array(zp).nullish(),Limits:tx.nullish()}).passthrough(),rx=z.object({OfferID:z.string().nullish(),OfferType:Yo.nullish(),FinalStatus:Xo.nullish(),SellerUserID:z.string().nullish(),BuyerUserID:z.string().nullish(),GoodsType:ea.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:_.nullish(),PricePaid:ae.nullish(),CommissionTaken:ae.nullish(),CompletedAt:c.nullish(),MyRole:z.string().nullish()}).passthrough(),Up=z.object({Entries:z.array(rx).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Te={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 ox="Marketplace",Ep={key:"marketplace.myState",login:"MarketplaceMyState",ttlMs:6e4,dependsOn:["Marketplace"],invalidateOn:["marketplace:listingCreated","marketplace:listingCancelled","marketplace:bought","marketplace:marketBought","marketplace:marketSold","marketplace:auctionCreated","marketplace:bidPlaced","marketplace:auctionClaimed","marketplace:buyOrderCreated","marketplace:buyOrderCancelled","marketplace:buyOrderFilled","marketplace:directTradeCreated","marketplace:directTradeResponded","marketplace:directTradeCancelled","marketplace:claimedBack"]},zn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ep,{schema:kn,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(ox,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,s=20){if(!e)return b("client","ItemID is required.");let n=this.ctx.authedRequest();if(!n)return c$1;n.ItemID=e,n.OfferTypeFilter=t,n.ContinuationToken=i,n.PageSize=s;let r=await this.ctx.api.marketplace.getOffersByItem(n);return r.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",r.data),r}async getOffer(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let s=this.ctx.authedRequest();if(!s)return c$1;s.ItemID=e,s.ContinuationToken=t,s.PageSize=i;let n=await this.ctx.api.marketplace.getBuyOrders(s);return n.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",n.data),n}getMyState(e,t){return this.ctx.cache.read(Ep,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let s=this.ctx.authedRequest();if(!s)return c$1;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let n=await this.ctx.api.marketplace.getHistory(s);return n.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",n.data),n}async createListing(e,t,i,s,n,r,p){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.PriceBundle=s,d.DurationHours=n,d.ItemInstanceIDs=r,d.SelectedOptionID=p;let C=await this.ctx.api.marketplace.createListing(d);return this.applyCreateOfferResult(C,"marketplace:listingCreated"),C}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c$1;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let r=await this.ctx.api.marketplace.marketBuy(s);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",r.data)),r}async marketSell(e,t,i){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c$1;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let r=await this.ctx.api.marketplace.marketSell(s);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",r.data)),r}async createAuction(e,t,i,s,n,r,p={}){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.BidAxisType=s,d.BidCurrencyID=p.bidCurrencyID,d.BidCatalogID=p.bidCatalogID,d.BidItemID=p.bidItemID,d.StartingBid=n,d.DurationHours=r,d.ItemInstanceIDs=p.itemInstanceIDs,d.SelectedOptionID=p.selectedOptionID;let C=await this.ctx.api.marketplace.createAuction(d);return this.applyCreateOfferResult(C,"marketplace:auctionCreated"),C}async placeBid(e,t){if(!e)return b("client","OfferID is required.");if(!t||t<=0)return b("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return c$1;i.OfferID=e,i.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,s,n){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let r=this.ctx.authedRequest();if(!r)return c$1;r.ItemID=e,r.CatalogID=t,r.GoodsAmount=i,r.PriceBundle=s,r.DurationHours=n;let p=await this.ctx.api.marketplace.createBuyOrder(r);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,s,n){if(!e)return b("client","TargetUserID is required.");if(!t)return b("client","CatalogID is required.");if(!i)return b("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return c$1;r.TargetUserID=e,r.CatalogID=t,r.ItemID=i,r.ItemInstanceIDs=s,r.RequestedBundle=n;let p=await this.ctx.api.marketplace.createDirectTrade(r);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return b("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.OfferID=e,i.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(i);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return b("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.OfferID=e;let n=await t(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,n.data)),n}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=vn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=vn.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):b("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var An=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return b("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode;let s=await this.ctx.api.multiplayer.createRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.RoomID=e,s.TargetUserID=t,s.Ban=i;let n=await this.ctx.api.multiplayer.kickMember(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",n.data),n}async unbanMember(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return c$1;i.Page=e,i.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(i);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,i,s){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");if(!i)return b("client","SignalKind is required.");let n=this.ctx.authedRequest();if(!n)return c$1;n.RoomID=e,n.TargetUserID=t,n.SignalKind=i,n.Payload=s;let r=await this.ctx.api.multiplayer.sendSignal(n);return r.ok&&this.ctx.emitter.emit("multiplayer:signalSent",r.data),r}async sendChat(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(i);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,i){if(!e)return b("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.RoomID=e,s.Ready=t,s.MemberState=i;let n=await this.ctx.api.multiplayer.setMemberState(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",n.data),n}};var qp=" (if the network is fine, the storage bucket has no CORS rule for this origin)",wn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):c$1}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return b("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):c$1}async getCreatorProfile(e,t,i){if(!e)return b("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):c$1}async publish(e){if(!e.files||e.files.length===0)return b("client","At least one file is required.");let t=new Map,i=e.files.map((d,C)=>{if("sourceAssetUrl"in d)return {Role:d.role,ContentType:d.contentType,SourceAssetUrl:d.sourceAssetUrl};let j=Bp(d.data,d.contentType);return t.set(C,j),{Role:d.role,ContentType:d.contentType,Size:j.size}}),s=e.thumbnail?Bp(e.thumbnail.data,e.thumbnail.contentType):null,n=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!n.ok)return n;let r=n.data.Uploads??[];for(let d=0;d<r.length;d++){let C=r[d];if(!C||C.ServerCopy||!C.Url)continue;let j=t.get(d);if(!j)return b("client",`No bytes for file #${d+1}.`);let le=await this.putBytes(C.Url,j,C.ContentType??j.type);if(!le.ok)return le}let p=n.data.ThumbnailUpload;if(p?.Url&&s){let d=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!d.ok)return d}return this.publishUploaded({ContentID:n.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID})}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):c$1}async publishUploaded(e){if(!e.ContentID)return b("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let s=await this.ctx.api.workshop.updateContent(i);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getMyContent(s)):c$1}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let s=await this.ctx.api.workshop.acquire(i);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let s of t.data.Files??[])if(s.Url)try{let n=await this.ctx.fetchImpl(s.Url);if(!n.ok)return b("connection",`Download failed (HTTP ${n.status}).`);i.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await n.arrayBuffer()});}catch(n){return b("connection",`Download failed: ${n instanceof Error?n.message:String(n)}${qp}`)}return a({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):c$1}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):c$1}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${qp}`)}}contentRequest(e){if(!e)return b("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):c$1}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function Bp(o,e){return o instanceof Blob?o:typeof o=="string"?new Blob([new TextEncoder().encode(o)],{type:e}):o instanceof Uint8Array?new Blob([o.slice().buffer],{type:e}):new Blob([o],{type:e})}var ax={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},lx=z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),ux={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Lp=z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),cx={Everyone:"Everyone",Owner:"Owner",Server:"Server"},Gp=z.enum(["Everyone","Owner","Server"]).catch("Everyone"),px={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},hx=z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),dx={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},mx=z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),fx={Count:"Count",Sum:"Sum"},gx=z.enum(["Count","Sum"]).catch("Count"),yx={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},Rx=z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),Cx={Strict:"Strict",Loose:"Loose"},Sx=z.enum(["Strict","Loose"]).catch("Strict"),xx=z.object({Kind:mx,Collection:z.string().nullish(),Validate:z.boolean().nullish()}),bx=z.object({Type:Lp,ItemType:Lp.nullish(),Ref:xx.nullish(),Required:z.boolean().optional(),Default:z.string().nullish(),Min:z.number().nullish(),Max:z.number().nullish(),MaxLength:z.number().nullish(),MaxItems:z.number().nullish(),Enum:z.array(z.string()).nullish(),Unique:z.boolean().optional(),UniqueIgnoreCase:z.boolean().optional(),Indexed:z.boolean().optional(),Visibility:Gp.optional(),ClientWritable:z.boolean().nullish(),Immutable:z.boolean().optional(),Description:z.string().nullish(),AllowedMimeTypes:z.array(z.string()).nullish(),MaxFileBytes:z.number().nullish()}),Dx=z.object({ID:z.string(),Components:z.array(z.object({Field:z.string(),Descending:z.boolean().optional()})).default([])}),Mn=z.object({Mode:hx,Role:z.string().nullish(),MembersField:z.string().nullish()}),Px=z.object({Read:z.array(Mn).nullish(),Create:z.array(Mn).nullish(),Update:z.array(Mn).nullish(),Delete:z.array(Mn).nullish()}),na=z.object({Cost:ae.nullish(),Grant:ae.nullish()}),Ix=z.object({ID:z.string(),SortKey:z.string(),PartitionField:z.string().nullish(),PageSize:z.number().optional(),MaxItems:z.number().optional(),PublishItems:z.boolean().optional()}),vx=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Namespace:z.string().nullish(),Tags:z.array(z.string()).nullish(),Enabled:z.boolean().nullish(),Kind:lx,Mode:Sx.optional(),SchemaVersion:z.number().optional(),Fields:z.record(z.string(),bx).nullish(),SortKeys:z.array(Dx).nullish(),Access:Px.nullish(),Limits:z.object({MaxItemBytes:z.number().nullish(),MaxItemsPerOwner:z.number().nullish(),TtlSeconds:z.number().nullish()}).nullish(),OnOwnerDeleted:Rx.optional(),Counters:z.array(z.object({ID:z.string(),Kind:gx,SumField:z.string().nullish(),GroupBy:z.string().nullish(),Visibility:Gp.optional()})).nullish(),Economy:z.object({OnCreate:na.nullish(),OnUpdate:na.nullish(),OnDelete:na.nullish()}).nullish(),WriteGate:J.nullish(),PublicViews:z.array(Ix).nullish(),AnonymousSearch:z.boolean().nullish(),Integrations:z.object({QuestMetricOnCreate:z.string().nullish(),QuestMetricOnUpdate:z.string().nullish(),QuestMetricOnDelete:z.string().nullish(),AnalyticsEventOnCreate:z.string().nullish(),AnalyticsEventOnUpdate:z.string().nullish(),AnalyticsEventOnDelete:z.string().nullish(),TriggerOnCreate:z.string().nullish(),TriggerOnUpdate:z.string().nullish(),TriggerOnDelete:z.string().nullish()}).nullish(),Moderation:z.object({BlockedTerms:z.array(z.string()).nullish()}).nullish()}),Fp=z.object({Enabled:z.boolean().optional(),Collections:z.record(z.string(),vx).default({})}),Tx=z.object({FileID:z.string(),Url:z.string(),ContentType:z.string().nullish(),Size:z.number()}),Vp=z.object({FileID:z.string(),UploadUrl:z.string(),ContentType:z.string(),MaxBytes:z.number(),ExpiresAt:z.string()}),di=z.object({Collection:z.string(),ItemID:z.string(),OwnerUserID:z.string().nullish(),Data:z.record(z.string(),z.unknown()).default({}),Version:z.number(),CreatedAt:z.string(),UpdatedAt:z.string(),ExpireAt:z.string().nullish(),Expanded:z.record(z.string(),z.unknown()).nullish(),Files:z.record(z.string(),Tx).nullish()}),ra=z.object({Item:di}),jp=z.object({Items:z.array(di).default([]),Missing:z.array(z.string()).default([])}),oa=z.object({Items:z.array(di).default([]),NextCursor:z.string().nullish()}),Np=z.object({Count:z.number(),Capped:z.boolean().optional()}),aa=z.object({Item:di,AlreadyExists:z.boolean().optional(),Economy:M.nullish()}),_p=z.object({ItemID:z.string(),Deleted:z.boolean(),Economy:M.nullish()}),Wp=z.object({CounterID:z.string(),Group:z.unknown().optional(),Value:z.number()}),Kp=z.object({Results:z.array(z.object({Op:z.string(),Collection:z.string(),ItemID:z.string(),Item:di.nullish(),Deleted:z.boolean().optional()})).default([])}),Qp=z.object({Roles:z.array(z.string()).default([])}),Hp=z.object({Views:z.record(z.string(),z.string()).default({}),ItemUrlTemplate:z.string().nullish()}),$p=z.object({Version:z.string(),Collection:z.string(),View:z.string(),SortKey:z.string().nullish(),PageSize:z.number(),UpdatedAt:z.string(),BaseUrl:z.string(),Partitions:z.record(z.string(),z.object({Segment:z.string(),Pages:z.number(),Total:z.number()})).default({})}),Jp=z.object({Page:z.number(),HasMore:z.boolean(),Items:z.array(di).default([])}),kx={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 zx=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,Xp=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,ua=100,Zp=25,Yp=100;function Ax(o,e,t){return {Field:o,Op:e,Value:t}}var On=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(c$1)}get(e,t,i={}){let s=tt(e)??wi(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.get({...n,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let s=tt(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(r=>Xp.test(r)))];return n.length?n.length>Yp?Promise.resolve(b("client",`At most ${Yp} ids per call.`)):this.call(r=>this.ctx.api.dataCollections.getMany({...r,Collection:e,ItemIDs:n,Expand:i.expand})):Promise.resolve(b("client","At least one valid item id is required."))}query(e,t={},i={}){let s=tt(e)??la(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.query({...n,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),n=[],r=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:r,Limit:t.Limit??ua},i);if(!p.ok)return p;if(n.push(...p.data.Items),r=p.data.NextCursor??void 0,!r||n.length>=s)return a(n.slice(0,s))}}count(e,t={}){let i=tt(e)??la(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,i={}){let s=tt(e)??(i.itemID?wi(i.itemID):null);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.create({...n,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,s={}){let n=tt(e)??wi(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.update({...r,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=tt(e)??wi(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.delete({...n,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(b("client","Operations are empty."));if(e.length>Zp)return Promise.resolve(b("client",`At most ${Zp} operations per batch.`));let t=e.map(i=>tt(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let s=tt(e);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.getCounter({...n,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,s){let n=tt(e);return n?Promise.resolve(n):t?s>0?this.call(r=>this.ctx.api.dataCollections.beginFileUpload({...r,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(b("client","File size must be positive.")):Promise.resolve(b("client","Field is required."))}async uploadFile(e,t,i,s={}){let n=s.contentType||i.type||"application/octet-stream",r=await this.beginFileUpload(e,t,n,i.size);if(!r.ok)return r;let p=await this.putBytes(r.data.UploadUrl,i,r.data.ContentType||n);return p.ok?r:p}async getPublicViews(e){let t=tt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return a(i);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,i={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let n=s.data.Views[t];if(!n)return b("client",`Collection '${e}' has no public view '${t}'.`);let r=await this.fetchJson(n,$p);if(!r.ok)return r;let p=r.data.Partitions[i.partition??""],d=Math.max(1,i.page??1);if(!p||d>p.Pages)return a({pointer:r.data,page:{Page:d,HasMore:false,Items:[]}});let C=await this.fetchJson(`${r.data.BaseUrl}${p.Segment}/page-${d}.json`,Jp);return C.ok?a({pointer:r.data,page:C.data}):C}getPublic(e,t){let i=tt(e)??wi(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=tt(e)??la(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(c$1)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return b("connection","Internet Connection Error")}if(!i.ok)return b("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return b("server","CDN answer is not JSON.")}let n=t.safeParse(s);return n.success?a(n.data):b("server","CDN answer has an unexpected shape.")}};function tt(o){return zx.test(o??"")?null:b("client",`Collection id '${o}' is invalid (letters, digits, '_', '-', ':').`)}function wi(o){return Xp.test(o??"")?null:b("client",`Item id '${o}' is invalid.`)}function la(o){return o.Limit!=null&&(o.Limit<1||o.Limit>ua)?b("client",`Limit must be 1..${ua}.`):(o.Where?.length??0)>8?b("client","At most 8 filters per query."):null}var ca={Open:"Open",Declared:"Declared"},wx=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Blocked:z.boolean().nullish()}).passthrough(),Mx=z.object({ParamName:z.string().nullish(),DisplayName:z.string().nullish()}).passthrough(),eh=z.object({Enabled:z.boolean().nullish(),EventNaming:z.string().nullish(),Events:z.record(z.string(),wx).nullish(),Dimensions:z.array(Mx).nullish(),RetentionDays:z.number().nullish(),AutomaticEvents:z.boolean().nullish()}).passthrough(),Lt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Ct={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Un=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,Ox={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},Ux=z.object({Index:z.number().nullish(),Name:z.string().nullish(),Reason:z.string().nullish()}).passthrough(),th=z.object({Accepted:z.number().nullish(),Dropped:z.array(Ux).nullish(),Duplicate:z.boolean().nullish(),Disabled:z.boolean().nullish()}).passthrough(),pa={LogEvents:"LogEvents"};function ih(o,e=0){let t=o??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let p=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let p=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let n=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(n)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(n[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let r=/\bWindows NT (\d+\.\d+)/.exec(t);return r?{osName:"Windows",osVersion:r[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function sh(o){let e=typeof navigator>"u"?void 0:navigator,t=ih(e?.userAgent??"",e?.maxTouchPoints??0),i={};o.appVersion&&(i.AppVersion=o.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let s=o.locale||e?.language;return s&&(i.Language=s),i}var Ex=25,qx=3e4,nh=1800*1e3,rh=500,Bx=5,Lx=1e3,Gx=3600*1e3,oh="idos_analytics_queue",ha="idos_analytics_pending",da="idos_analytics_opt_out",ah="idos_analytics_first_open",lh="idos_analytics_last_activity",uh="idos_analytics_last_context",ch="idos_analytics_owner",En=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!Un.test(e)?b("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Fx(e)?b("client",`Event name "${e}" uses a reserved prefix (${Ct.reservedPrefixes.join(", ")}).`):this.enqueue(e,t,i,false)}logScreenView(e,t){if(!e)return b("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Lt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return a(null);if(this.config()?.Enabled===false)return this.clear(),a(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return a(null);this.pending={BatchID:d(),Events:this.queue.splice(0,Ct.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return c$1;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=Bx)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(da);return}this.write(da,"1"),this.clear();}get isEnabled(){return this.read(da)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(ch);e&&t&&t!==e&&this.clear(),e&&this.write(ch,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},qx),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(lh)??"0");this.read(ah)||(this.write(ah,new Date().toISOString()),this.enqueue(Lt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(uh);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Lt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Lt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(uh,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=nh)&&this.enqueue(Lt.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>=nh&&this.enqueue(Lt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,s){if(!this.isEnabled||this.disabledByServer)return a(null);let n=this.config();if(n?.Enabled===false)return a(null);if(s&&n?.AutomaticEvents===false)return a(null);if(n?.Events?.[e]?.Blocked)return b("client",`Event "${e}" is blocked by the title.`);if(!s&&n?.EventNaming?.toLowerCase()===ca.Declared.toLowerCase()&&!n.Events?.[e])return b("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return b("client","value must be a finite number.");let r=Vx(t);if(r.error)return b("client",r.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return r.params&&(p.Params=r.params),i!==void 0&&(p.Value=i),this.queue.push(p),this.queue.length>rh&&this.queue.splice(0,this.queue.length-rh),this.touch(),this.persist(),this.started&&this.queue.length>=Ex&&this.flush(),a(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},Lx));}dropStale(){let e=Date.now()-(Ct.maxEventAgeMs-Gx);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??=sh({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(oh);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(ha);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(oh,this.queue),this.pending?this.writeJson(ha,this.pending):this.remove(ha);}touch(){this.write(lh,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 Fx(o){let e=o.toLowerCase();return Ct.reservedPrefixes.some(t=>e.startsWith(t))}function Vx(o){if(!o)return {};let e=Object.keys(o);if(e.length===0)return {};if(e.length>Ct.maxParams)return {error:`Too many parameters: ${e.length}, max ${Ct.maxParams}.`};let t={};for(let i of e){if(!Un.test(i))return {error:`Invalid parameter name "${i}".`};let s=o[i];typeof s=="string"?t[i]=s.length>Ct.maxStringValueLength?s.slice(0,Ct.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var jx="idos_experiments",qn=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return c$1;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let n=Number(s);return s.trim()!==""&&Number.isFinite(n)?n:i}if(typeof i=="boolean"){let n=s.trim().toLowerCase();return n==="true"||n==="1"?true:n==="false"||n==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,n]of t){let r=this.views.get(s);(!r||r.VariantID!==n.VariantID||r.Status!==n.Status)&&i.push(n);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.platform.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.platform.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${jx}:${this.ctx.settings.titleID}`}};function Gt(o,e,t,i){let n=`api/v2/${o&&o.length>0?o:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var q=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Gt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,s){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...s,ticket:t.ClientSessionTicket})}};var Bn=class extends q{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(pa.LogEvents,e,th,{silent:true})}};var Nx=z.object({VariantID:z.string().nullish(),DisplayName:z.string().nullish(),Weight:z.number().nullish(),IsControl:z.boolean().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),_x={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Wx=z.object({MetricID:z.string().nullish(),Kind:z.string().nullish(),EventName:z.string().nullish(),IsPrimary:z.boolean().nullish()}).passthrough(),Kx=z.object({ExperimentID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),IsEnabled:z.boolean().nullish(),Schedule:me.nullish(),Gate:J.nullish(),Variants:z.array(Nx).nullish(),Salt:z.string().nullish(),LayerID:z.string().nullish(),StickyAssignment:z.boolean().nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Goals:z.array(Wx).nullish(),ActivationEvent:z.string().nullish(),RolloutVariantID:z.string().nullish()}).passthrough(),ph=z.object({Experiments:z.record(z.string(),Kx).nullish()}).passthrough(),Qx={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Hx=z.object({ExperimentID:z.string().nullish(),VariantID:z.string().nullish(),Status:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),hh=z.object({Experiments:z.array(Hx).nullish(),IsAbTestingAvailable:z.boolean().nullish()}).passthrough(),ma={GetExperiments:"GetExperiments"};var Ln=class extends q{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(ma.GetExperiments,e,hh)}};var dh=z.object({PlatformUserID:z.string().nullish(),PlatformAuthToken:z.string().nullish(),PlatformAuthTokenExpiration:c.nullish(),TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:c,PlayAccess:Bt.nullish(),RefreshToken:z.string().nullish(),RefreshTokenExpiration:c.nullish()}),mh=z.object({TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:c,RefreshToken:z.string(),RefreshTokenExpiration:c.nullish(),PlayAccess:Bt.nullish()}),$x=z.object({ReturnMode:z.string().nullish(),UrlScheme:z.string().nullish(),UserCodeSupported:z.boolean().nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),fh=z.object({Google:z.object({Enabled:z.boolean().nullish(),WebClientID:z.string().nullish(),PlatformFallback:z.boolean().nullish(),AndroidClientID:z.string().nullish(),IosClientID:z.string().nullish(),DesktopClientID:z.string().nullish()}).passthrough().nullish(),Apple:z.object({Enabled:z.boolean().nullish(),BundleID:z.string().nullish(),ServiceID:z.string().nullish()}).passthrough().nullish(),PlayAccessMode:ki.nullish(),WalletLoginNetworks:z.array(z.object({NetworkID:z.string().nullish(),Type:z.string().nullish()}).passthrough()).nullish(),NativeSso:$x.nullish()}).passthrough(),gh=z.object({Linked:z.boolean().nullish(),Challenge:z.string().nullish(),ExpiresAt:c.nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),PlayAccess:Bt.nullish()}).passthrough(),yh=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CooldownUntil:c.nullish(),PlayAccess:Bt.nullish()}).passthrough(),Rh=z.object({CodeTtlMinutes:z.number().nullish(),ResendCooldownSeconds:z.number().nullish()}),Ue=z.object({IsCompleted:z.boolean().nullish(),ServerTime:c.nullish()}),Ch=z.object({Message:z.string(),ExpiresAt:c}),Ee={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 Gn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Gt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,dh,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ee.RefreshSession),e,mh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ee.GetAuthOptions),e,fh,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Gt(this.ctx.settings.titleID,"Authentication",Ee.LinkWallet,e.UserID??""),e,gh,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Gt(this.ctx.settings.titleID,"Authentication",Ee.UnlinkWallet,e.UserID??""),e,yh,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ee.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ee.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ee.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ee.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ee.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ee.LoginWithSsoCode,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ee.RegisterWithEmail),e,Rh,{ticket:null})}confirmEmailRegistration(e){return this.login(Ee.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ee.ResendVerificationCode),e,Ue,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ee.RequestWalletChallenge),e,Ch,{ticket:null})}loginWithWallet(e){return this.login(Ee.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ee.ForgotPassword),e,Ue,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ee.ResetPassword),e,Ue,{ticket:null})}};var Jx={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},Sh=z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),Zx=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),IsEnabled:z.boolean().nullish(),Order:z.number().nullish()}).passthrough(),xh=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),Locales:z.record(z.string(),Zx).nullish(),MissingKeyMode:Sh.nullish(),MaxEntriesPerLocale:z.number().nullish(),MaxValueLengthBytes:z.number().nullish()}).passthrough(),Yx=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish()}).passthrough(),bh=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish(),Fallback:Yx.nullish()}).passthrough(),Fn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},Xx=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),Order:z.number().nullish(),Version:z.number().nullish()}).passthrough(),Dh=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),MissingKeyMode:Sh.nullish(),ResolvedLocale:z.string().nullish(),Locales:z.array(Xx).nullish()}).passthrough(),Ph=z.object({RequestedLocale:z.string().nullish(),Locale:z.string().nullish(),Version:z.number().nullish(),NotModified:z.boolean().nullish(),Entries:z.record(z.string(),z.string()).nullish(),FallbackLocale:z.string().nullish(),FallbackVersion:z.number().nullish()}).passthrough();var fa=z.object({TitleConfigVersion:z.string().nullish(),TitleConfigUrl:z.string().nullish(),User:z.unknown().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish(),Localization:bh.nullish(),Views:z.array(z.object({Name:z.string(),Key:z.string().nullish(),Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(o=>o),Ih=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish()}).passthrough().transform(o=>o),vh=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),User:z.unknown().nullish()}).passthrough().transform(o=>o),Th=z.object({}).passthrough().transform(o=>o),kh=z.object({}).passthrough().transform(o=>o),zh=z.object({Today:z.number(),Yesterday:z.number(),CurrentWeek:z.number(),CurrentMonth:z.number(),Total:z.number(),TotalSessions:z.number(),FirstActiveAt:c.nullish(),LastActiveAt:c.nullish(),LongestSessionEverSeconds:z.number().nullish(),CurrentWeekActiveHoursMask:z.number().nullish(),CurrentMonthActiveHoursMask:z.number().nullish(),ReactivationCount:z.number().nullish(),History:z.record(z.string(),z.unknown()).nullish()}).passthrough(),Ah=z.object({Username:z.string()}),lt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Vn=class extends q{constructor(e){super(e,"User");}getClientState(e){return this.send(lt.GetClientState,e,fa)}getClientStateExcept(e){return this.send(lt.GetClientStateExcept,e,fa)}getStateVersions(e){return this.send(lt.GetStateVersions,e,Ih)}getUserState(e){return this.send(lt.GetUserState,e,vh)}getInventory(e){return this.send(lt.GetInventory,e,Th)}getEventTokens(e){return this.send(lt.GetEventTokens,e,kh)}getUsageTime(e){return this.send(lt.GetUsageTime,e,zh)}addUsageTime(e){return this.send(lt.AddUsageTime,e,Ue,{silent:true})}deleteUserAccount(e){return this.send(lt.DeleteUserAccount,e,Ue)}changeUsername(e){return this.send(lt.ChangeUsername,e,Ah)}};var jn=class extends q{constructor(e){super(e,"Currency");}convert(e){return this.send(Sn.Convert,e,$c)}cryptoConvert(e){return this.send(Sn.CryptoConvert,e,Jc)}};var eb=z.object({ItemInstanceID:z.string(),Units:z.number(),Level:z.number()}),ga=z.object({ServerTimeUtc:c,ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Level:z.number(),Resources:M.nullish(),FodderConsumed:z.array(eb).nullish()}),wh=z.array(Pe(ga)),Nn={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},tb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},ib=z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),sb={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},nb=z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),rb=z.object({ContractAddress:z.string().nullish(),TokenID:z.string().nullish(),TokenStandard:z.string().nullish(),MaxLevel:z.number().nullish()}).passthrough(),ob=z.object({Networks:z.record(z.string(),rb).nullish(),MetadataUrl:z.string().nullish()}).passthrough(),ab=z.object({FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),lb=z.object({MinCharacterLevel:z.number().nullish(),UseRequirements:z.record(z.string(),z.number()).nullish(),AllowedCharacterIDs:z.array(z.string()).nullish(),AllowedSlotIDs:z.array(z.string()).nullish(),IdleRateBonus:z.number().nullish()}).passthrough(),ub=z.object({ValuationMode:ib.nullish(),WeightCurve:Fe.nullish(),Selection:nb.nullish()}).passthrough(),cb=z.object({MaxLevel:z.number().nullish(),PriceOptions:oe.nullish(),CostCurve:Fe.nullish(),FlatBonusCurve:Fe.nullish(),PercentBonusCurve:Fe.nullish(),PowerCurve:Fe.nullish(),Fodder:ub.nullish()}).passthrough(),pb=z.object({RarityID:z.string().nullish(),CollectionID:z.string().nullish(),AuthorID:z.string().nullish()}).passthrough(),hb=z.object({ItemID:z.string(),CatalogID:z.string(),ItemClass:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),CustomData:z.record(z.string(),z.string()).nullish(),IsStackable:z.boolean().nullish(),IsTradable:z.boolean().nullish(),Weight:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),NFT:ob.nullish(),Stats:ab.nullish(),Equipment:lb.nullish(),Upgrade:cb.nullish(),Metadata:pb.nullish(),ExpirationDurationSeconds:z.number().nullish(),MaxSupply:z.number().nullish()}).passthrough(),db=z.object({Items:z.record(z.string(),hb).nullish()}).passthrough(),_n=z.object({Catalogs:z.record(z.string(),db).nullish()}).passthrough();var Wn=class extends q{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(Nn.UpgradeLevel,e,ga)}upgradeLevelsBatch(e){return this.send(Nn.UpgradeLevelsBatch,e,wh)}};var Kn=class extends q{constructor(e){super(e,"Store");}purchase(e){return this.send(_t.Purchase,e,lo)}purchaseBatch(e){return this.send(_t.PurchaseBatch,e,ql)}getDefinitions(e){return this.send(_t.GetDefinitions,e,ds)}getUserState(e){return this.send(_t.GetUserState,e,Bl)}getStorefront(e){return this.send(_t.GetStorefront,e,ms)}};var mb={Apple:"Apple",Google:"Google"},Qn=z.object({PremiumID:z.string().nullish(),PurchaseDate:z.string().nullish(),ExpirationDate:z.string().nullish(),TransactionID:z.string().nullish(),IsAutoRenewEnabled:z.boolean().nullish()}).passthrough(),Hn=z.object({Subscriptions:z.record(z.string(),Qn).nullish(),ActivatedTrialIDs:z.array(z.string()).nullish(),MaxActiveTier:z.number().nullish()}).passthrough().transform(o=>o),fb=z.object({PremiumID:z.string().nullish(),DisplayName:z.string().nullish(),Tier:z.number().nullish(),DurationDays:z.number().nullish(),TrialDurationDays:z.number().nullish(),PriceOptions:oe.nullish(),Benefits:z.record(z.string(),z.string()).nullish()}).passthrough(),ya=z.object({Definitions:z.record(z.string(),fb).nullish()}).passthrough(),Mh=z.object({Premium:ya.nullish()}),Oh=z.object({ServerTimeUtc:c.nullish(),Premium:Hn.nullish()}),$n=z.object({ServerTimeUtc:c.nullish(),Premium:Hn.nullish(),Subscription:Qn.nullish(),Resources:M.nullish()}),Qt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var gb={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},yb=z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Uh=z.object({StartUtc:c.nullish(),EndUtc:c.nullish(),Gate:J.nullish(),Limits:ye.nullish()}).passthrough(),Ra=z.object({ResourceAction:z.string().nullish(),RevokeEntitlement:z.boolean().nullish(),BlockFuturePurchases:z.boolean().nullish()}).passthrough(),Rb=z.object({PremiumID:z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:z.number().nullish(),RevokeOnRefund:z.boolean().nullish()}).passthrough(),Cb=z.object({Rewards:K.nullish(),Rules:K.nullish(),Refund:K.nullish()}).passthrough(),Sb=z.object({ProductID:z.string().nullish(),Name:z.string().nullish(),Type:yb.nullish(),Enabled:z.boolean().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:z.number().nullish(),TelegramStarsPrice:z.number().nullish(),Rules:Uh.nullish(),Refund:Ra.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Subscription:Rb.nullish(),Presets:Cb.nullish()}).passthrough(),xb=z.object({StoreID:z.string().nullish(),Enabled:z.boolean().nullish(),PackageName:z.string().nullish(),VerificationMode:z.string().nullish(),PlayPublicKey:z.string().nullish(),RequireCertificateChain:z.boolean().nullish(),SecretName:z.string().nullish(),IssuerID:z.string().nullish(),KeyID:z.string().nullish(),AcknowledgePurchases:z.boolean().nullish(),NotificationPackageName:z.string().nullish()}).passthrough(),bb=z.object({Rewards:H.nullish()}).passthrough(),Db=z.object({Rules:Uh.nullish()}).passthrough(),Pb=z.object({Refund:Ra.nullish()}).passthrough(),Ib=z.object({Rewards:z.record(z.string(),bb).nullish(),Rules:z.record(z.string(),Db).nullish(),Refund:z.record(z.string(),Pb).nullish()}).passthrough(),vb=z.object({MaxPurchaseAgeDays:z.number().nullish(),AllowSandbox:z.boolean().nullish(),RequirePackageMatch:z.boolean().nullish(),MaxReceiptsPerBatch:z.number().nullish(),RefundCheckHorizonDays:z.number().nullish(),RejectCrossUserReceipts:z.boolean().nullish()}).passthrough(),Tb=z.object({Enabled:z.boolean().nullish(),Products:z.record(z.string(),Sb).nullish(),Stores:z.record(z.string(),xb).nullish(),Presets:Ib.nullish(),Validation:vb.nullish(),Refund:Ra.nullish()}).passthrough(),Eh=z.object({ProductID:z.string().nullish(),TotalPurchases:z.number().nullish(),DailyPurchases:z.number().nullish(),DailyResetUtc:c.nullish(),LastPurchasedAt:c.nullish(),Owned:z.boolean().nullish(),Refunded:z.boolean().nullish(),PurchaseBlocked:z.boolean().nullish(),Store:z.string().nullish(),LastTransactionID:z.string().nullish()}).passthrough(),qh=z.object({ProductID:z.string().nullish(),PremiumID:z.string().nullish(),Store:z.string().nullish(),OriginalTransactionID:z.string().nullish(),LastTransactionID:z.string().nullish(),ExpiresAt:c.nullish(),AutoRenew:z.boolean().nullish(),Status:z.string().nullish(),RenewalCount:z.number().nullish(),LastStoreCheckAt:c.nullish(),LastStoreCheckError:z.string().nullish(),UpdatedAt:c.nullish()}).passthrough(),kb=z.object({Products:z.record(z.string(),Eh).nullish(),LifetimeSpendUsdCents:z.number().nullish(),Subscriptions:z.record(z.string(),qh).nullish(),LastRefundCheckAt:c.nullish(),TotalPurchases:z.number().nullish(),FirstPurchaseAt:c.nullish(),LastPurchaseAt:c.nullish()}).passthrough(),zb=z.object({ProductID:z.string(),Available:z.boolean(),Owned:z.boolean(),Blocked:z.boolean(),Reason:z.string().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish()}).passthrough(),Bh=z.object({ServerTimeUtc:c,Purchase:Tb.nullish(),Availability:z.array(zb).nullish()}),Lh=z.object({ServerTimeUtc:c,Purchase:kb.nullish()}),Ab={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},wb=z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Ca=z.object({ServerTimeUtc:c,Store:Gi.nullish(),ProductID:z.string().nullish(),TransactionID:z.string().nullish(),Status:wb.nullish(),Granted:z.boolean().nullish(),Quantity:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),ProductState:Eh.nullish(),Premium:Hn.nullish(),Subscription:Qn.nullish(),SubscriptionMirror:qh.nullish()}).passthrough(),Gh=z.object({ServerTimeUtc:c,ProductID:z.string().nullish(),Stars:z.number().nullish(),InvoiceLink:z.string(),ExpiresAt:c.nullish()}).passthrough(),Fh=ft(Ca),Ht={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var Jn=class extends q{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(Ht.GetDefinitions,e,Bh)}getUserState(e){return this.send(Ht.GetUserState,e,Lh)}validatePurchase(e){return this.send(Ht.ValidatePurchase,e,Ca)}validatePurchasesBatch(e){return this.send(Ht.ValidatePurchasesBatch,e,Fh)}createTelegramInvoice(e){return this.send(Ht.CreateTelegramInvoice,e,Gh)}};var Mb=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),Vh=z.object({Reward:H.nullish(),Weight:z.number().nullish(),AmountRange:Mb.nullish()}).passthrough(),mi=z.object({SlotID:z.string().nullish(),MinRolls:z.number().nullish(),MaxRolls:z.number().nullish(),Pool:z.array(Vh).nullish()}).passthrough(),fi=z.object({RuleID:z.string().nullish(),Threshold:z.number().nullish(),Pool:z.array(Vh).nullish()}).passthrough(),Ob=z.object({RewardSlots:z.array(mi).nullish()}).passthrough(),Ub=z.object({PityRules:z.array(fi).nullish()}).passthrough(),Zn=z.object({SlotPresets:z.record(z.string(),Ob).nullish(),PityPresets:z.record(z.string(),Ub).nullish()}).passthrough();var Eb=z.object({RuleID:z.string(),BoxIndex:z.number().nullish()}),jh=z.object({ServerTimeUtc:c,LootboxID:z.string(),OpenedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:z.array(M).nullish(),TriggeredPity:z.array(Eb).nullish()}),qb=z.object({RewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),Bb=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxDrops:_.nullish()}).passthrough(),Lb=z.object({LootboxID:z.string(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:oe.nullish(),RewardSlots:z.array(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:qb.nullish(),RewardMultiplier:Vi.nullish(),SupplyLimits:z.array(Bb).nullish(),MaxOpenCount:z.number().nullish()}).passthrough(),Gb=z.object({MaxOpenCount:z.number().nullish()}).passthrough(),Sa=z.object({Definitions:z.record(z.string(),Lb).nullish(),RewardPools:Zn.nullish(),Settings:Gb.nullish()}).passthrough(),Nh=z.object({LootboxDefinitions:Sa.nullish()}),Yn={GetDefinitions:"GetDefinitions",Open:"Open"};var Xn=class extends q{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(Yn.GetDefinitions,e,Nh)}open(e){return this.send(Yn.Open,e,jh)}};var Fb=z.object({}).passthrough().transform(o=>o),Vb=z.object({}).passthrough().transform(o=>o),jb=z.object({}).passthrough().transform(o=>o),Nb=z.object({}).passthrough().transform(o=>o),_b=z.object({}).passthrough().transform(o=>o),_h=z.object({ServerTimeUtc:c,CalendarID:z.string(),DayNumber:z.number().nullish(),DailyState:Fb,Resources:M.nullish(),Inventory:Q.nullish()}),Wh=z.object({ServerTimeUtc:c,AccrualID:z.string(),AccruedSeconds:_.nullish(),AppliedRatePerSecond:z.number().nullish(),IdleState:Vb,Resources:M.nullish(),Inventory:Q.nullish()}),Kh=z.object({ServerTimeUtc:c,ComebackID:z.string(),ClaimedTierIndex:z.number().nullish(),ComebackState:jb,Resources:M.nullish(),Inventory:Q.nullish()}),Qh=z.object({ServerTimeUtc:c,ClaimID:z.string(),ClaimState:Nb,Resources:M.nullish(),Inventory:Q.nullish()}),Hh=z.object({Enabled:z.boolean(),Multiplier:z.number().nullish(),Progress:_.nullish(),Source:z.string().nullish(),SourceKey:z.string().nullish()}),Wb=z.object({RewardMode:z.string().nullish(),RewardStackLowerTiers:z.boolean().nullish()}).passthrough(),Kb=z.object({DayNumber:z.number().nullish(),Rewards:H.nullish(),IsMilestone:z.boolean().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Mi=z.object({Gate:J.nullish(),Limits:ye.nullish()}).passthrough(),xa=z.object({Availability:K.nullish()}).passthrough(),Qb=z.object({Availability:z.record(z.string(),Mi).nullish()}).passthrough(),Hb=z.object({CalendarID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Days:z.array(Kb).nullish(),IsLooping:z.boolean().nullish(),MissBehavior:z.string().nullish(),ResetByDays:z.number().nullish(),MissThresholdMultiplier:z.number().nullish(),ClaimMode:z.string().nullish(),ClaimCooldownSeconds:z.number().nullish(),Availability:Mi.nullish(),Presets:xa.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),$b=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Multiplier:z.number().nullish()}).passthrough(),Jb=z.object({BaseRatePerSecond:z.number().nullish(),PowerCoefficient:z.number().nullish(),BoardRankCoefficient:z.number().nullish(),EquipmentBonusEnabled:z.boolean().nullish(),EquipmentCharacterID:z.string().nullish(),PremiumMultipliers:z.array($b).nullish()}).passthrough(),Zb=z.object({MinCharacterLevel:z.number().nullish(),RequirementsCharacterID:z.string().nullish(),Availability:Mi.nullish(),RequiredItemIDs:z.array(z.string()).nullish(),RequiredEquippedItemIDs:z.array(z.string()).nullish()}).passthrough(),Yb=z.object({AccrualID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rate:Jb.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:z.number().nullish(),MinClaimSeconds:z.number().nullish(),Requirements:Zb.nullish(),FirstClaimMode:z.string().nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),Xb=z.object({MinAbsenceSeconds:z.number().nullish(),Rewards:H.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),eD=z.object({ComebackID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(Xb).nullish(),ClaimCooldownSeconds:z.number().nullish(),ClaimWindowSeconds:z.number().nullish(),TrackPresenceOnRead:z.boolean().nullish(),Availability:Mi.nullish(),Presets:xa.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),tD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),CooldownSeconds:z.number().nullish(),MaxClaimsPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish(),TotalClaimLimit:z.number().nullish()}).passthrough(),iD=z.object({ClaimID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Mode:z.string().nullish(),Rewards:H.nullish(),PremiumLimitOverrides:z.array(tD).nullish(),Availability:Mi.nullish(),Presets:xa.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),ba=z.object({TierRewards:Wb.nullish(),MilestoneRewardMultiplier:Vi.nullish(),DailyCalendars:z.record(z.string(),Hb).nullish(),IdleAccruals:z.record(z.string(),Yb).nullish(),Comebacks:z.record(z.string(),eD).nullish(),Claims:z.record(z.string(),iD).nullish(),Presets:Qb.nullish()}).passthrough(),$h=z.object({RewardDefinitions:ba.nullish()}),Jh=z.object({Rewards:_b.nullish()}),Tt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var er=class extends q{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(Tt.GetRewardDefinitions,e,$h)}getUserRewardsState(e){return this.send(Tt.GetUserRewardsState,e,Jh)}getMilestoneRewardMultiplier(e){return this.send(Tt.GetMilestoneRewardMultiplier,e,Hh)}claimDailyReward(e){return this.send(Tt.ClaimDailyReward,e,_h)}collectIdleAccrual(e){return this.send(Tt.CollectIdleAccrual,e,Wh)}claimComebackReward(e){return this.send(Tt.ClaimComebackReward,e,Kh)}claimReward(e){return this.send(Tt.ClaimReward,e,Qh)}};var tr=class extends q{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(nt.GetTutorialDefinitions,e,Cl)}getUserTutorialState(e){return this.send(nt.GetUserTutorialState,e,_i)}startFlow(e){return this.send(nt.StartFlow,e,At)}reportStepShown(e){return this.send(nt.ReportStepShown,e,At)}completeStep(e){return this.send(nt.CompleteStep,e,At)}completeStepsBatch(e){return this.send(nt.CompleteStepsBatch,e,bl)}skipStep(e){return this.send(nt.SkipStep,e,At)}skipFlow(e){return this.send(nt.SkipFlow,e,At)}claimFlowReward(e){return this.send(nt.ClaimFlowReward,e,xl)}resetFlow(e){return this.send(nt.ResetFlow,e,At)}};var sD={Open:"Open",Application:"Application"},nD=z.enum(["Open","Application"]).catch("Open"),rD={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},Zh=z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),oD={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Da=z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),aD={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var $t={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},lD=z.object({CampaignID:z.string().nullish(),DisplayNameKey:z.string().nullish(),DescriptionKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),IsRunning:z.boolean().nullish()}).passthrough(),Yh=z.object({IsEnabled:z.boolean().nullish(),CreatorPortalUrl:z.string().nullish(),ParticipationMode:nD.nullish(),IsCreator:z.boolean().nullish(),CreatorStatus:Zh.nullish(),VerificationCode:z.string().nullish(),TeamID:z.string().nullish(),Campaigns:z.array(lD).nullish()}).passthrough(),uD=z.object({Earned:z.number().nullish(),Mature:z.number().nullish(),CountedMetrics:z.record(z.string(),z.number()).nullish(),ReachedMilestones:z.array(z.string()).nullish(),CappedBySubmissionLimit:z.boolean().nullish(),CappedByCreatorLimit:z.boolean().nullish(),NotPaidAsCopy:z.boolean().nullish()}).passthrough(),cD=z.object({CampaignID:z.string().nullish(),CurrencyKind:Da.nullish(),CurrencyID:z.string().nullish(),NetworkID:z.string().nullish(),Earned:z.number().nullish(),Mature:z.number().nullish(),Granted:z.number().nullish(),Paid:z.number().nullish(),Overpaid:z.number().nullish(),Claimable:z.number().nullish(),BySubmission:z.record(z.string(),uD).nullish(),ComputedAt:z.string().nullish()}).passthrough(),pD=z.object({PayoutID:z.string().nullish(),CampaignID:z.string().nullish(),Amount:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Da.nullish(),NetworkID:z.string().nullish(),PaidAt:z.string().nullish()}).passthrough(),Xh=z.object({ServerTimeUtc:z.string().nullish(),HoldDays:z.number().nullish(),Campaigns:z.array(cD).nullish(),Payouts:z.array(pD).nullish()}).passthrough(),ed=z.object({CampaignID:z.string().nullish(),PayoutID:z.string().nullish(),Claimed:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Da.nullish(),NetworkID:z.string().nullish(),RemainingFraction:z.number().nullish(),IdempotentReplay:z.boolean().nullish(),Message:z.string().nullish()}).passthrough(),hD=z.object({To:z.string().nullish(),Amount:z.string().nullish()}).passthrough(),dD=z.object({ContractAddress:z.string().nullish(),TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),Signature:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(hD).nullish()}).passthrough(),mD=z.object({Kind:z.string().nullish(),Target:z.string().nullish(),Required:z.number().nullish(),Actual:z.number().nullish(),Passed:z.boolean().nullish()}).passthrough(),td=z.object({Passed:z.boolean().nullish(),Approved:z.boolean().nullish(),Status:Zh.nullish(),WalletMissing:z.boolean().nullish(),WalletConnectAllowed:z.boolean().nullish(),Conditions:z.array(mD).nullish()}).passthrough(),fD=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),gD=z.object({ProgramID:z.string().nullish(),Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(fD).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),id=z.object({ServerTimeUtc:z.string().nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ChainID:z.number().nullish(),CurrencyID:z.string().nullish(),AmountNative:z.number().nullish(),NetAmountNative:z.number().nullish(),BurnAmountNative:z.number().nullish(),AmountUsd:z.number().nullish(),ExpiresAt:z.string().nullish(),EvmSignature:dD.nullish(),SolanaSignature:gD.nullish(),StateDelta:hi.nullish()}).passthrough();var ir=class extends q{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send($t.GetCommunityMarketingState,e,Yh)}getEarnings(e){return this.send($t.GetEarnings,e,Xh)}claim(e){return this.send($t.Claim,e,ed)}checkJoinEligibility(e){return this.send($t.CheckJoinEligibility,e,td)}withdrawCryptoReward(e){return this.send($t.WithdrawCryptoReward,e,id)}};var sr=class extends q{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(Ke.GetChatDefinitions,e,Xl)}getChannels(e){return this.send(Ke.GetChannels,e,Ps)}poll(e){return this.send(Ke.Poll,e,eu)}getHistory(e){return this.send(Ke.GetHistory,e,tu)}getConversations(e){return this.send(Ke.GetConversations,e,nu)}sendMessage(e){return this.send(Ke.SendMessage,e,iu)}openDirectChannel(e){return this.send(Ke.OpenDirectChannel,e,su)}markRead(e){return this.send(Ke.MarkRead,e,ci)}joinChannel(e){return this.send(Ke.JoinChannel,e,ci)}leaveChannel(e){return this.send(Ke.LeaveChannel,e,ci)}reportMessage(e){return this.send(Ke.ReportMessage,e,ru)}ignoreUser(e){return this.send(Ke.IgnoreUser,e,ci)}unignoreUser(e){return this.send(Ke.UnignoreUser,e,ci)}};var nr=class extends q{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(pi.GetPushConfig,e,lu)}subscribePush(e){return this.send(pi.SubscribePush,e,ho)}unsubscribePush(e){return this.send(pi.UnsubscribePush,e,Ue)}getPushSubscriptions(e){return this.send(pi.GetPushSubscriptions,e,uu)}};var rr=class extends q{constructor(e){super(e,"Localization");}send(e,t,i,s){let n=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${n}:${t.Locale}`:n,...s})}getLocalizationManifest(e){return this.send(Fn.GetLocalizationManifest,e,Dh)}getLocalizationTable(e){return this.send(Fn.GetLocalizationTable,e,Ph)}};var or=class extends q{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(pt.GetQuestDefinitions,e,Ni)}getUserQuestState(e){return this.send(pt.GetUserQuestState,e,al)}refreshQuestCycles(e){return this.send(pt.RefreshQuestCycles,e,Ue)}claimQuestReward(e){return this.send(pt.ClaimQuestReward,e,Jr)}claimQuestRewardsBatch(e){return this.send(pt.ClaimQuestRewardsBatch,e,cl)}claimMilestoneReward(e){return this.send(pt.ClaimMilestoneReward,e,Zr)}claimMilestoneRewardsBatch(e){return this.send(pt.ClaimMilestoneRewardsBatch,e,pl)}claimGroupCompletionReward(e){return this.send(pt.ClaimGroupCompletionReward,e,ll)}addQuestProgress(e){return this.send(pt.AddQuestProgress,e,ul)}};var ar=class extends q{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ot.GetActiveEvents,e,ws)}getDefinitions(e){return this.send(ot.GetDefinitions,e,As)}getUserLteState(e){return this.send(ot.GetUserLteState,e,du)}grantTokens(e){return this.send(ot.GrantTokens,e,M)}spendTokens(e){return this.send(ot.SpendTokens,e,go)}claimMilestone(e){return this.send(ot.ClaimMilestone,e,yo)}claimMilestonesBatch(e){return this.send(ot.ClaimMilestonesBatch,e,Ro)}claimAllMilestones(e){return this.send(ot.ClaimAllMilestones,e,Ro)}spendTokensBatch(e){return this.send(ot.SpendTokensBatch,e,mu)}grantTokensBatch(e){return this.send(ot.GrantTokensBatch,e,fu)}};var lr=class extends q{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ve.GetDefinitions,e,Ls)}getLeaderboard(e){return this.send(Ve.GetLeaderboard,e,Di)}getMyProgress(e){return this.send(Ve.GetMyProgress,e,Os)}submitScore(e){return this.send(Ve.SubmitScore,e,Us)}submitScoreFromSource(e){return this.send(Ve.SubmitScoreFromSource,e,Us)}claimCycleReward(e){return this.send(Ve.ClaimCycleReward,e,Es)}claimMilestone(e){return this.send(Ve.ClaimMilestone,e,qs)}getFriendsLeaderboard(e){return this.send(Ve.GetFriendsLeaderboard,e,Di)}getLeaderboardsBatch(e){return this.send(Ve.GetLeaderboardsBatch,e,Ru)}getProgressBatch(e){return this.send(Ve.GetProgressBatch,e,Bs)}claimCycleRewardsBatch(e){return this.send(Ve.ClaimCycleRewardsBatch,e,Cu)}claimMilestonesBatch(e){return this.send(Ve.ClaimMilestonesBatch,e,Su)}submitScoresBatch(e){return this.send(Ve.SubmitScoresBatch,e,xu)}claimAllRewardsBatch(e){return this.send(Ve.ClaimAllRewardsBatch,e,bu)}getOverviewBatch(e){return this.send(Ve.GetOverviewBatch,e,Du)}};var ur=class extends q{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Ot.GetDefinitions,e,Vs)}getActiveSeason(e){return this.send(Ot.GetActiveSeason,e,Fs)}getUserState(e){return this.send(Ot.GetUserState,e,Co)}grantStatusTokens(e){return this.send(Ot.GrantStatusTokens,e,Tu)}claimTierReward(e){return this.send(Ot.ClaimTierReward,e,So)}claimTierRewardsBatch(e){return this.send(Ot.ClaimTierRewardsBatch,e,ku)}};var cr=class extends q{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Qt.GetDefinitions,e,Mh)}getUserState(e){return this.send(Qt.GetUserState,e,Oh)}activateTrial(e){return this.send(Qt.ActivateTrial,e,$n)}purchaseItemOrCurrency(e){return this.send(Qt.PurchaseWithResources,e,$n)}purchaseRealMoney(e){return this.send(Qt.PurchaseRealMoney,e,$n)}};var pr=class extends q{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(je.GetCharacterDefinitions,e,Ws)}getUserCharacters(e){return this.send(je.GetUserCharacters,e,Uu)}unlockCharacter(e){return this.send(je.UnlockCharacter,e,Po)}upgradeStatLevel(e){return this.send(je.UpgradeStatLevel,e,bo)}upgradeCharacterLevel(e){return this.send(je.UpgradeCharacterLevel,e,Do)}equipItems(e){return this.send(je.EquipItems,e,Eu)}unequipItems(e){return this.send(je.UnequipItems,e,qu)}unequipAllCharacters(e){return this.send(je.UnequipAllCharacters,e,Bu)}unlockCharactersBatch(e){return this.send(je.UnlockCharactersBatch,e,ju)}upgradeCharacterLevelsBatch(e){return this.send(je.UpgradeCharacterLevelsBatch,e,Nu)}upgradeStatLevelsBatch(e){return this.send(je.UpgradeStatLevelsBatch,e,_u)}unlockSkin(e){return this.send(je.UnlockSkin,e,Lu)}equipSkin(e){return this.send(je.EquipSkin,e,Gu)}unequipSkin(e){return this.send(je.UnequipSkin,e,Fu)}getCharacterSkins(e){return this.send(je.GetCharacterSkins,e,Vu)}};var hr=class extends q{constructor(e){super(e,"Match");}createMatch(e){return this.send(Rt.CreateMatch,e,xp)}updateMatch(e){return this.send(Rt.UpdateMatch,e,bp)}cancelMatch(e){return this.send(Rt.CancelMatch,e,Dp)}instantBattle(e){return this.send(Rt.InstantBattle,e,Pp)}saveStrategy(e){return this.send(Rt.SaveStrategy,e,Ue)}getMyMatches(e){return this.send(Rt.GetMyMatches,e,Jo)}getAvailableMatches(e){return this.send(Rt.GetAvailableMatches,e,Jo)}getDefinitions(e){return this.send(Rt.GetDefinitions,e,kp)}};var yD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},sd=z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),RD={None:"None",Min:"Min",Average:"Average",Max:"Max"},CD=z.enum(["None","Min","Average","Max"]).catch("None"),SD={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},xD=z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),bD={Clamp:"Clamp",Reject:"Reject"},DD=z.enum(["Clamp","Reject"]).catch("Clamp"),PD=z.object({ItemInstanceID:z.string().nullish(),ItemID:z.string().nullish(),Level:z.number().nullish(),Units:z.number().nullish()}),ID=z.object({Index:z.number().nullish(),BurnedItemIDs:z.array(z.string()).nullish(),RolledCollectionID:z.string().nullish(),UsedCollections:z.record(z.string(),z.number()).nullish(),Output:Qr.nullish(),OutputLevel:z.number().nullish(),BurnedInstances:z.array(PD).nullish()}),nd=z.object({ServerTimeUtc:c,Type:sd.nullish(),CraftID:z.string(),CraftedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),InputRarity:z.string().nullish(),OutputRarity:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:z.array(ID).nullish()}),vD=z.object({CraftID:z.string().nullish(),Type:sd.nullish(),CatalogID:z.string().nullish(),CollectionID:z.string().nullish(),InputRarityID:z.string().nullish(),OutputRarityID:z.string().nullish(),RequiredItemCount:z.number().nullish(),PriceOptions:oe.nullish(),OutputLevelMode:CD.nullish(),InputSelection:xD.nullish(),OutputLevelOverflow:DD.nullish()}).passthrough(),Pa=z.object({Definitions:z.record(z.string(),vD).nullish()}).passthrough(),rd=z.object({ServerTimeUtc:c.nullish(),CraftDefinitions:Pa.nullish()}),dr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var mr=class extends q{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(dr.GetDefinitions,e,rd)}craft(e){return this.send(dr.Craft,e,nd)}};var TD=2e5,fr=class extends q{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,$s,{timeoutMs:TD,autoRetry:false})}readGeneration(e,t){return this.send(e,t,$s,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Ge.GetDefinitions,e,Xu)}generateText(e){return this.generate(Ge.GenerateText,e)}getText(e){return this.readGeneration(Ge.GetText,e)}generateImage(e){return this.generate(Ge.GenerateImage,e)}editImage(e){return this.generate(Ge.EditImage,e)}getImage(e){return this.readGeneration(Ge.GetImage,e)}generateVideo(e){return this.generate(Ge.GenerateVideo,e)}getVideo(e){return this.readGeneration(Ge.GetVideo,e)}generateAudio(e){return this.generate(Ge.GenerateAudio,e)}getAudio(e){return this.readGeneration(Ge.GetAudio,e)}generateMusic(e){return this.generate(Ge.GenerateMusic,e)}getMusic(e){return this.readGeneration(Ge.GetMusic,e)}generateThreeD(e){return this.generate(Ge.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Ge.GetThreeD,e)}listGenerations(e){return this.send(Ge.ListGenerations,e,Yu)}getGeneration(e){return this.readGeneration(Ge.GetGeneration,e)}};var kD={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},zD=z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),od=z.object({}).passthrough().transform(o=>o),gi=z.object({CollectibleID:z.string(),Rarity:z.number().nullish(),IsSpecial:z.boolean().nullish(),IsDuplicate:z.boolean().nullish(),CollectionCurrencyConverted:z.number().nullish()}),ad=z.object({GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish()}),ld=z.object({OpenedCount:z.number().nullish(),Packs:z.array(ad).nullish(),GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish(),NewCollectionCurrencyBalance:_.nullish(),NewlyCompletedSetIDs:z.array(z.string()).nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),ud=z.object({OpenedCount:z.number().nullish(),Chests:z.array(ad).nullish(),GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish(),NewCollectionCurrencyBalance:_.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),cd=z.object({GrantedCollectibleID:z.string().nullish(),NewlyCompletedSetID:z.string().nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ia=z.object({SetID:z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),pd=z.array(Pe(Ia)),hd=z.object({Resources:M.nullish(),Inventory:Q.nullish()}),AD=z.object({OfferID:z.string(),TitleID:z.string().nullish(),CollectionID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderPublicData:Oe.nullish(),OfferedCollectibleID:z.string().nullish(),OfferedCollectibleIsSpecial:z.boolean().nullish(),ReceiverUserID:z.string().nullish(),RequestedCollectibleID:z.string().nullish(),RequestedCollectibleIsSpecial:z.boolean().nullish(),Status:zD.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RespondedAtUtc:c.nullish(),DeclineReason:z.string().nullish(),IsSpecialTradeEvent:z.boolean().nullish(),SpecialTradeEventID:z.string().nullish()}).passthrough(),dd=z.object({OfferID:z.string(),ExpiresAtUtc:c.nullish(),Resources:M.nullish()}),md=z.object({OfferID:z.string(),Resources:M.nullish()}),fd=z.object({OfferID:z.string(),ReceivedCollectibleID:z.string().nullish(),ReceivedIsSpecial:z.boolean().nullish(),SentCollectibleID:z.string().nullish(),SentCollectibleIsSpecial:z.boolean().nullish(),Transfer:z.unknown().nullish()}),gd=z.object({OfferID:z.string(),Resources:M.nullish()}),va=z.object({Offers:z.array(AD).nullish()}),wD=z.object({CollectibleID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rarity:z.number().nullish(),HasSpecialVersion:z.boolean().nullish(),SortOrder:z.number().nullish()}).passthrough(),MD=z.object({SetID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SortOrder:z.number().nullish(),Collectibles:z.array(wD).nullish(),SetCompletionReward:H.nullish()}).passthrough(),OD=z.object({CollectionID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SeasonChainID:z.string().nullish(),Sets:z.array(MD).nullish(),GrandPrize:H.nullish()}).passthrough(),yd=z.object({BonusRewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),UD=z.object({PackTypeID:z.string().nullish(),PriceOptions:oe.nullish(),BonusRewardSlots:z.array(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:yd.nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectibleCount:z.number().nullish(),MaxOpenCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),GuaranteeMaxRarity:z.boolean().nullish(),RarityWeights:z.record(z.string(),z.number()).nullish(),ColorTier:z.number().nullish()}).passthrough(),ED=z.object({Rarity:z.number().nullish(),CollectionCurrencyGranted:z.number().nullish()}).passthrough(),qD=z.object({CollectionChestID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectionCurrencyCost:z.number().nullish(),MaxOpenCount:z.number().nullish(),MinCollectibleCount:z.number().nullish(),MaxCollectibleCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),BonusRewardSlots:z.array(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:yd.nullish(),Tier:z.number().nullish()}).passthrough(),BD=z.object({SpecialTradeEventID:z.string().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),AllowedSpecialCollectibleIDs:z.array(z.string()).nullish(),SpecialTradeEventDailyTradeLimit:z.number().nullish()}).passthrough(),LD=z.object({MaxPackOpenCount:z.number().nullish(),MaxChestOpenCount:z.number().nullish()}).passthrough(),gr=z.object({Collections:z.record(z.string(),OD).nullish(),PackTypes:z.record(z.string(),UD).nullish(),CollectionChests:z.array(qD).nullish(),DuplicateConversions:z.array(ED).nullish(),DailyTradeLimit:z.number().nullish(),CollectibleJokerCatalogID:z.string().nullish(),CollectibleJokerItemID:z.string().nullish(),SpecialTradeEvents:z.array(BD).nullish(),RewardPools:Zn.nullish(),Settings:LD.nullish()}).passthrough(),Ne={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 yr=class extends q{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ne.GetDefinitions,e,gr)}getUserState(e){return this.send(Ne.GetUserState,e,od)}openPack(e){return this.send(Ne.OpenPack,e,ld)}openCollectionChest(e){return this.send(Ne.OpenCollectionChest,e,ud)}useCollectibleJoker(e){return this.send(Ne.UseCollectibleJoker,e,cd)}claimSetReward(e){return this.send(Ne.ClaimSetReward,e,Ia)}claimSetRewardsBatch(e){return this.send(Ne.ClaimSetRewardsBatch,e,pd)}claimGrandPrize(e){return this.send(Ne.ClaimGrandPrize,e,hd)}sendTradeOffer(e){return this.send(Ne.SendTradeOffer,e,dd)}cancelTradeOffer(e){return this.send(Ne.CancelTradeOffer,e,md)}acceptTradeOffer(e){return this.send(Ne.AcceptTradeOffer,e,fd)}declineTradeOffer(e){return this.send(Ne.DeclineTradeOffer,e,gd)}getMyTradeOffers(e){return this.send(Ne.GetMyTradeOffers,e,va)}getIncomingTradeOffers(e){return this.send(Ne.GetIncomingTradeOffers,e,va)}};var Rr=class extends q{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(ht.GetDefinitions,e,Xs)}getActiveEvent(e){return this.send(ht.GetActiveEvent,e,ic)}getUserState(e){return this.send(ht.GetUserState,e,Ys)}getGroupState(e){return this.send(ht.GetGroupState,e,Ao)}joinOrCreateGroup(e){return this.send(ht.JoinOrCreateGroup,e,Ao)}spin(e){return this.send(ht.Spin,e,nc)}claimObjectReward(e){return this.send(ht.ClaimObjectReward,e,wo)}claimGrandPrize(e){return this.send(ht.ClaimGrandPrize,e,wo)}leaveGroup(e){return this.send(ht.LeaveGroup,e,rc)}};var Cr=class extends q{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(yt.GetDefinition,e,gc)}getUserState(e){return this.send(yt.GetUserState,e,yc)}getActiveDeals(e){return this.send(yt.GetActiveDeals,e,sn)}dismissDeal(e){return this.send(yt.DismissDeal,e,Cc)}executeNode(e){return this.send(yt.ExecuteNode,e,Rc)}recordShow(e){return this.send(yt.RecordShow,e,Sc)}claimMilestone(e){return this.send(yt.ClaimMilestone,e,xc)}claimMilestonesBatch(e){return this.send(yt.ClaimMilestonesBatch,e,bc)}};var GD=z.object({}).passthrough().transform(o=>o),FD=z.object({FeatureKey:z.string().nullish(),IsEnabled:z.boolean().nullish(),Rate:z.number().nullish(),Basis:z.string().nullish(),SourceCurrencyID:z.string().nullish(),TargetCurrencyID:z.string().nullish(),MinSourceAmount:z.number().nullish(),MaxRewardPerOperation:z.number().nullish(),Limits:ye.nullish()}).passthrough(),Ta=z.object({IsEnabled:z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:z.record(z.string(),Be).nullish(),SpendRewards:z.array(FD).nullish()}).passthrough(),Rd=z.object({ReferralDefinitions:Ta.nullish()}).passthrough(),Cd=z.object({Referral:GD.nullish(),InviteUrl:z.string().nullish()}).passthrough(),Sd=z.object({ReferralCode:z.string().nullish(),ReferrerUserID:z.string().nullish(),IsFirstActivation:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),ka=z.object({RewardID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),xd=ft(ka),Jt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch"};var Sr=class extends q{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Jt.GetDefinitions,e,Rd)}getUserState(e){return this.send(Jt.GetUserState,e,Cd)}activateReferralCode(e){return this.send(Jt.ActivateReferralCode,e,Sd)}claimInviteReward(e){return this.send(Jt.ClaimInviteReward,e,ka)}claimInviteRewardsBatch(e){return this.send(Jt.ClaimInviteRewardsBatch,e,xd)}};var xr=class extends q{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(et.GetDefinitions,e,Tc)}getMessages(e){return this.send(et.GetMessages,e,kc)}getUnreadCount(e){return this.send(et.GetUnreadCount,e,on)}readMessages(e){return this.send(et.ReadMessages,e,Uo)}claimReward(e){return this.send(et.ClaimReward,e,an)}claimRewardsBatch(e){return this.send(et.ClaimRewardsBatch,e,an)}claimAll(e){return this.send(et.ClaimAll,e,an)}deleteMessages(e){return this.send(et.DeleteMessages,e,Uo)}sendGift(e){return this.send(et.SendGift,e,zc)}sendTransfer(e){return this.send(et.SendTransfer,e,Ac)}getGiftStatus(e){return this.send(et.GetGiftStatus,e,wc)}};var br=class extends q{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Re.GetFriendsList,e,Ii)}getIncomingRequests(e){return this.send(Re.GetIncomingRequests,e,Ii)}getOutgoingRequests(e){return this.send(Re.GetOutgoingRequests,e,Ii)}getRecommendedFriends(e){return this.send(Re.GetRecommendedFriends,e,Ii)}sendFriendRequest(e){return this.send(Re.SendFriendRequest,e,vi)}acceptFriendRequest(e){return this.send(Re.AcceptFriendRequest,e,vi)}declineFriendRequest(e){return this.send(Re.DeclineFriendRequest,e,vi)}removeFriend(e){return this.send(Re.RemoveFriend,e,vi)}getInbox(e){return this.send(Re.GetInbox,e,Oc)}markInboxSeen(e){return this.send(Re.MarkInboxSeen,e,Ti)}getInboxUnread(e){return this.send(Re.GetInboxUnread,e,Ti)}follow(e){return this.send(Re.Follow,e,qt)}unfollow(e){return this.send(Re.Unfollow,e,qt)}getFollowers(e){return this.send(Re.GetFollowers,e,un)}getFollowing(e){return this.send(Re.GetFollowing,e,un)}block(e){return this.send(Re.Block,e,qt)}unblock(e){return this.send(Re.Unblock,e,qt)}getBlocked(e){return this.send(Re.GetBlocked,e,un)}react(e){return this.send(Re.React,e,qt)}unreact(e){return this.send(Re.Unreact,e,qt)}getMyReactions(e){return this.send(Re.GetMyReactions,e,Ec)}getEntityStates(e){return this.send(Re.GetEntityStates,e,Uc)}addComment(e){return this.send(Re.AddComment,e,cn)}editComment(e){return this.send(Re.EditComment,e,cn)}deleteComment(e){return this.send(Re.DeleteComment,e,Bc)}getComments(e){return this.send(Re.GetComments,e,qc)}report(e){return this.send(Re.Report,e,Lc)}};var VD={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Zt=z.object({Target:z.string().nullish(),Operation:z.string().nullish(),Value:z.number().nullish()}).passthrough(),jD=z.object({BoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:oe.nullish(),Effect:Zt.nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),Dr=z.object({Schedule:me.nullish(),Gate:J.nullish()}).passthrough(),za=z.object({Availability:K.nullish(),Effects:K.nullish()}).passthrough(),ND=z.object({ScheduledBoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Effects:z.array(Zt).nullish(),Availability:Dr.nullish(),Presets:za.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),_D=z.object({ChainedBoostID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Effects:z.array(Zt).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),WD=z.object({ChainID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Phases:z.array(_D).nullish(),Availability:Dr.nullish(),Presets:za.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),KD=z.object({TriggeredBoostID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Sources:z.array(st).nullish(),Effects:z.array(Zt).nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Availability:Dr.nullish(),Presets:za.nullish()}).passthrough(),QD=z.object({MaxAddPercent:z.number().nullish(),MaxMultiply:z.number().nullish(),MaxAddFlat:z.number().nullish()}).passthrough(),HD=z.object({Effects:z.array(Zt).nullish()}).passthrough(),$D=z.object({Availability:z.record(z.string(),Dr).nullish(),Effects:z.record(z.string(),HD).nullish()}).passthrough(),JD=z.object({StackingCaps:z.record(z.string(),QD).nullish()}).passthrough(),Pr=z.object({Definitions:z.record(z.string(),jD).nullish(),ScheduledBoosts:z.record(z.string(),ND).nullish(),BoostChains:z.record(z.string(),WD).nullish(),TriggeredBoosts:z.record(z.string(),KD).nullish(),Settings:JD.nullish(),Presets:$D.nullish()}).passthrough(),bd=z.object({InstanceID:z.string(),BoostID:z.string(),ActivatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RemainingCharges:z.number().nullish(),EffectSnapshot:Zt.nullish(),SourceType:z.string().nullish(),SourceRef:z.string().nullish()}).passthrough();z.object({Date:c.nullish(),DailyCount:z.number().nullish(),LastFiredUtc:c.nullish()}).passthrough();var Dd=z.object({ServerTimeUtc:c.nullish(),Active:z.record(z.string(),bd).nullish()}),Pd=z.object({ServerTimeUtc:c.nullish(),BoostID:z.string().nullish(),StackingPolicy:z.string().nullish(),ActivatedBoost:bd.nullish(),Resources:M.nullish()}),ZD={Scheduled:"Scheduled",Chain:"Chain"},YD=z.object({Kind:z.string().nullish(),SourceID:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),PhaseOrder:z.number().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),Effects:z.array(Zt).nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Id=z.object({ServerTimeUtc:c.nullish(),Windows:z.array(YD).nullish()}),Yt={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Ir=class extends q{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(Yt.GetDefinitions,e,Pr)}getActive(e){return this.send(Yt.GetActive,e,Dd)}getActiveWindows(e){return this.send(Yt.GetActiveWindows,e,Id)}activate(e){return this.send(Yt.Activate,e,Pd)}cleanupExpired(e){return this.send(Yt.CleanupExpired,e,Ue)}};var vr=class extends q{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(dt.GetUserCustomDataDefinitions,e,mn)}getMyUserCustomData(e){return this.send(dt.GetMyUserCustomData,e,jc)}getPublicUserCustomDataOf(e){return this.send(dt.GetPublicUserCustomDataOf,e,Go)}setPrivateData(e){return this.send(dt.SetPrivateData,e,Fo)}setPublicData(e){return this.send(dt.SetPublicData,e,Fo)}deleteKey(e){return this.send(dt.DeleteKey,e,Ue)}batchSet(e){return this.send(dt.BatchSet,e,Nc)}batchDelete(e){return this.send(dt.BatchDelete,e,_c)}batchGetPublicUserCustomDataOf(e){return this.send(dt.BatchGetPublicUserCustomDataOf,e,Wc)}};var XD={Static:"Static",Runtime:"Runtime"},eP={Public:"Public",Private:"Private"},tP=z.enum(["Client","Server","System"]).catch("Client"),iP=z.enum(["String","Int","Bool","Json"]).catch("String"),sP=z.object({Value:z.string().nullish(),UpdatedAt:c.nullish(),Version:z.number().nullish(),LastWriter:tP.nullish(),ExpiresAt:c.nullish()}).passthrough(),vd=z.record(z.string(),sP),Aa=z.object({StaticVersion:z.number().nullish(),RuntimeVersion:z.number().nullish(),Static:vd.nullish(),Runtime:vd.nullish(),NotModified:z.boolean().nullish()}),nP=z.object({KeyID:z.string(),Scope:z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:iP.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),Tr=z.object({Keys:z.record(z.string(),nP).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),Oi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var kr=class extends q{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Oi.GetTitleCustomDataDefinitions,e,Tr)}getPublicTitleData(e){return this.send(Oi.GetPublicTitleData,e,Aa)}getPublicTitleDataKeys(e){return this.send(Oi.GetPublicTitleDataKeys,e,Aa)}};var rP={Fast:"Fast",Sequential:"Sequential"},oP={Instant:"Instant",Timed:"Timed"};var aP={Hit:"Hit",Blocked:"Blocked"},lP=z.object({SlotIndex:z.number(),Level:z.number().nullish(),IsDamaged:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish()}).passthrough(),uP=z.object({Symbol:z.union([z.string(),z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:z.string().nullish()}).passthrough();z.object({ElapsedSeconds:z.number().nullish(),Reward:H.nullish()}).passthrough();var cP=z.object({RequiredValue:z.number().nullish(),Reward:H.nullish()}).passthrough(),pP=z.object({Reward:H.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough();z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(cP).nullish(),Rate:pP.nullish()}).passthrough();z.object({PlayedCount:z.number().nullish(),RewardsClaimedCount:z.number().nullish(),InstantClaimsCount:z.number().nullish(),EarlyClaimsCount:z.number().nullish(),LateClaimsCount:z.number().nullish(),AdViewsTotal:z.number().nullish(),StatRewardClaimsCount:z.number().nullish(),StatReportsClampedCount:z.number().nullish(),StatReportsUnknownMetricCount:z.number().nullish()}).passthrough();var Td=z.object({}).passthrough().transform(o=>o),kd=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),_e=z.object({Operation:M.nullish(),ScaleWithRollMultiplier:z.boolean().nullish()}).passthrough(),hP=z.object({Count:z.number().nullish(),Sides:z.number().nullish()}).passthrough(),dP=z.object({ShieldChance:z.number().nullish(),DamagedBuildingChance:z.number().nullish(),RankMultiplierMin:z.number().nullish(),RankMultiplierMax:z.number().nullish(),RankOffsetMin:z.number().nullish(),RankOffsetMax:z.number().nullish(),StageLevelSpread:z.number().nullish()}).passthrough(),mP=z.object({CostMatrixTemplatesByID:z.record(z.string(),z.array(z.array(z.number()))).nullish(),PerBoardGrowth:z.number().nullish(),VisualTemplateCycle:z.array(z.string()).nullish(),EconomyScaledResources:ae.nullish(),ScaleRaidStealWithEconomy:z.boolean().nullish(),ScaleAttackRewardWithEconomy:z.boolean().nullish(),AttackValueFromCostMatrix:z.boolean().nullish(),AttackBlockedRewardFactor:z.number().nullish(),ScaleVictimLossWithEconomy:z.boolean().nullish(),ScaleVictimLossWithTier:z.boolean().nullish(),SynthesizedBuildingSlots:z.number().nullish(),SynthesizedBuildingMaxLevel:z.number().nullish(),DifficultyGrowthPerBoard:z.number().nullish()}).passthrough(),fP=z.object({CostMatrix:z.array(z.array(z.number())).nullish(),PerBoardGrowth:z.number().nullish(),EconomyScale:z.number().nullish(),ScaledResources:ae.nullish()}).passthrough(),zd=z.object({SlotIndex:z.number().nullish(),Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxLevel:z.number().nullish(),MaxLevelReward:H.nullish()}).passthrough(),gP=z.object({Index:z.number().nullish(),Type:z.string().nullish(),CustomTypeID:z.string().nullish(),RandomActionAttackWeight:z.number().nullish(),RandomActionRaidWeight:z.number().nullish(),ChanceTableID:z.string().nullish(),SpecialModeID:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),yP=z.object({Tiles:z.record(z.string(),gP).nullish()}).passthrough(),RP=z.object({Weight:z.number().nullish(),Bonus:_e.nullish(),Tag:z.string().nullish()}).passthrough(),CP=z.object({Weight:z.number().nullish(),Tag:z.string().nullish(),MinBonusCells:z.number().nullish(),MaxBonusCells:z.number().nullish(),BonusPool:z.array(RP).nullish(),GuaranteedBonus:_e.nullish(),IsJackpot:z.boolean().nullish(),JackpotFinalMultiplier:z.number().nullish(),JackpotSymbolDistribution:z.record(z.string(),z.number()).nullish()}).passthrough(),SP=z.object({Variants:z.array(CP).nullish()}).passthrough(),xP=z.object({Weight:z.number().nullish(),OutcomeID:z.string().nullish(),Reward:_e.nullish(),ForceAction:z.string().nullish(),SpecialModeID:z.string().nullish()}).passthrough(),bP=z.object({Outcomes:z.array(xP).nullish()}).passthrough(),Ad=z.object({PerAdMultiplierRange:kd.nullish(),MaxAdViews:z.number().nullish(),AdCreditCost:z.number().nullish(),FormulaKind:z.string().nullish(),ApplyMultiplierOnEarlyClaim:z.boolean().nullish()}).passthrough(),DP=z.object({ElapsedSeconds:z.number().nullish(),Reward:_e.nullish()}).passthrough(),PP=z.object({Tiers:z.array(DP).nullish(),TierMode:z.string().nullish(),BelowFirstTierReward:_e.nullish()}).passthrough(),IP=z.object({RequiredValue:z.number().nullish(),Reward:_e.nullish()}).passthrough(),vP=z.object({Reward:_e.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough(),TP=z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(IP).nullish(),Rate:vP.nullish()}).passthrough(),wd=z.object({MetricsByID:z.record(z.string(),TP).nullish()}).passthrough(),kP=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:_e.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:oe.nullish(),Multipliers:Ad.nullish(),Gradation:PP.nullish(),RunStats:wd.nullish()}).passthrough(),zP=z.object({Choices:z.array(kP).nullish(),OfferExpireSeconds:z.number().nullish(),ClaimExpireSeconds:z.number().nullish()}).passthrough(),AP=z.object({Chance:z.number().nullish(),RequiredOutcome:z.string().nullish(),Reward:_e.nullish(),Tag:z.string().nullish()}).passthrough(),wP=z.object({OnPassStart:_e.nullish(),OnTileLanding:z.record(z.string(),_e).nullish(),OnAttack:z.record(z.string(),_e).nullish(),OnRaid:z.record(z.string(),_e).nullish(),OnBuild:_e.nullish(),OnStageComplete:_e.nullish(),OnAttackBonusDrops:z.array(AP).nullish(),ChanceTablesByID:z.record(z.string(),bP).nullish(),SpecialModesByID:z.record(z.string(),zP).nullish()}).passthrough(),Md=z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:z.number().nullish(),MaxShields:z.number().nullish(),Buildings:z.array(zd).nullish(),HeistGridBonusConfig:SP.nullish(),StageOperations:wP.nullish(),TileLandingMultiplier:kd.nullish(),EconomyOverride:fP.nullish()}).passthrough(),MP=z.object({Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BoardTemplateID:z.string().nullish(),Buildings:z.array(zd).nullish(),StageTemplateID:z.string().nullish(),CostMatrixTemplateID:z.string().nullish(),UnitValue:z.number().nullish(),Override:Md.nullish()}).passthrough(),OP=z.object({AttackCooldownSeconds:z.number().nullish(),RaidCooldownSeconds:z.number().nullish(),MaxRecentTargets:z.number().nullish(),LiveOpponentActiveDays:z.number().nullish(),LiveOpponentPoolSize:z.number().nullish(),LiveOpponentPoolCacheSeconds:z.number().nullish(),MaxLiveCandidateReads:z.number().nullish(),VictimImmunitySeconds:z.number().nullish()}).passthrough(),UP=z.object({Enabled:z.boolean().nullish(),IntervalSeconds:z.number().nullish(),MaxPerCatchUp:z.number().nullish(),Chance:z.number().nullish(),AttackWeight:z.number().nullish(),RaidWeight:z.number().nullish(),MinBoardStageLevel:z.number().nullish(),RaidLossMultiplier:z.number().nullish()}).passthrough(),zr=z.object({RollCurrencyID:z.string().nullish(),ShieldCurrencyID:z.string().nullish(),RaidMode:z.string().nullish(),AllowedRollMultipliers:z.array(z.number()).nullish(),BoardTemplatesByID:z.record(z.string(),yP).nullish(),StageTemplatesByID:z.record(z.string(),Md).nullish(),StagesByLevel:z.record(z.string(),MP).nullish(),SoftCurrencyID:z.string().nullish(),ProceduralEconomy:mP.nullish(),Dice:hP.nullish(),Bots:dP.nullish(),Targeting:OP.nullish(),BotRaids:UP.nullish()}).passthrough(),EP=z.object({IsActive:z.boolean().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AnchorUtc:c.nullish(),RoundDurationSec:z.number().nullish(),PauseBetweenRoundsSec:z.number().nullish(),MaxRounds:z.number().nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),ContributionMin:z.number().nullish(),ContributionMax:z.number().nullish(),ScaleContributionWithRollMultiplier:z.boolean().nullish(),MaxProgress:z.number().nullish(),Milestones:z.record(z.string(),Be).nullish(),GrandPrize:H.nullish()}).passthrough(),Ar=z.object({Board:zr.nullish(),CommunityChest:EP.nullish()}).passthrough(),Od=z.object({AttackerGainByOutcome:z.record(z.string(),ae).nullish()}).passthrough(),qP=z.object({TargetUserID:z.string().nullish(),IsBot:z.boolean().nullish(),PublicData:Oe.nullish(),TargetBuildingStates:z.array(lP).nullish(),TargetHasShield:z.boolean().nullish(),TargetStageLevel:z.number().nullish(),RaidRewardPreview:Od.nullish()}).passthrough(),BP=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:_e.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:oe.nullish(),Multipliers:Ad.nullish(),RunStats:wd.nullish()}).passthrough(),LP=z.object({ModeID:z.string().nullish(),Choices:z.array(BP).nullish()}).passthrough(),GP=z.object({GroupID:z.string().nullish(),Delta:_.nullish(),NewProgress:_.nullish(),MaxProgress:_.nullish(),UnlockedMilestoneIDs:z.array(z.string()).nullish(),Completed:z.boolean().nullish()}).passthrough(),Ud=z.object({UsedMultiplier:z.number().nullish(),Steps:z.number().nullish(),DiceValues:z.array(z.number()).nullish(),OldPosition:z.number().nullish(),NewPosition:z.number(),CyclesCompletedDelta:_.nullish(),LandedTileType:z.string().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),ActionRequired:z.string().nullish(),ActionData:qP.nullish(),SpecialModeOffer:LP.nullish(),CommunityChestContribution:GP.nullish()}).passthrough(),Ed=z.object({Outcome:z.string().nullish(),IsBotTarget:z.boolean().nullish(),BuildingIndexHit:z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:xt.nullish()}).passthrough(),wa=z.object({Status:z.string().nullish(),Outcome:z.string().nullish(),FoundSymbol:z.union([z.string(),z.number()]).nullish(),FoundBonus:H.nullish(),OpenedIndex:z.number().nullish(),AttemptsLeft:z.number().nullish(),RaidLayout:z.array(uP).nullish(),HeistVariantTag:z.string().nullish(),IsJackpot:z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:xt.nullish(),RaidRewardPreview:Od.nullish()}).passthrough(),qd=z.object({BuiltIndex:z.number(),NewLevel:z.number().nullish(),StageComplete:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish()}).passthrough(),Bd=z.object({Mode:z.union([z.string(),z.number()]).nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DurationSeconds:z.number().nullish(),StartedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish()}).passthrough(),Ld=z.object({AdViewsUsed:z.number().nullish(),RolledMultiplier:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),RemainingAdViews:z.number().nullish()}).passthrough(),FP=z.object({MetricID:z.string().nullish(),ReachedTierIndex:z.number().nullish(),RequiredValue:z.number().nullish(),RewardUnits:z.number().nullish()}).passthrough(),Gd=z.object({FinalMultiplier:z.number().nullish(),AdViewsUsed:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),IsEarlyClaim:z.boolean().nullish(),ReachedTierIndex:z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),AcceptedRunStats:z.record(z.string(),z.number()).nullish(),RunStatAwards:z.array(FP).nullish(),RunStatsClamped:z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),VP={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Fd=z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),jP={Active:"Active",Left:"Left",Replaced:"Replaced"},NP=z.enum(["Active","Left","Replaced"]).catch("Active"),_P=z.object({CurrentProgress:_.nullish(),MaxProgress:_.nullish()}).passthrough(),WP=z.object({UserID:z.string().nullish(),PublicData:Oe.nullish(),IsBot:z.boolean().nullish(),ContributionPoints:_.nullish(),MilestoneClaims:z.record(z.string(),nl).nullish(),GrandPrizeClaimed:z.boolean().nullish(),MemberStatus:NP.nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),Vd=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),RoundIndex:z.number().nullish(),Members:z.array(WP).nullish(),SharedProgress:_P.nullish(),Status:Fd.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:z.number().nullish()}).passthrough(),KP=z.object({GroupID:z.string().nullish(),RoundIndex:z.number().nullish(),FinalStatus:Fd.nullish(),GrandPrizeReceived:z.boolean().nullish(),FinishedAtUtc:c.nullish()}).passthrough(),QP=z.object({ActiveGroupID:z.string().nullish(),ActiveRoundIndex:z.number().nullish(),History:z.array(KP).nullish()}).passthrough(),jd=z.object({ServerTimeUtc:c.nullish(),UserState:QP.nullish(),ActiveGroup:Vd.nullish(),SecondsRemaining:_.nullish()}),Nd=z.object({ServerTimeUtc:c.nullish(),Group:Vd.nullish(),SecondsRemaining:_.nullish()}),Ma=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),_d=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),qe={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var HP={Mesh:"Mesh",Host:"Host"},Oa=z.enum(["Mesh","Host"]).catch("Mesh"),$P={ServerRelay:"ServerRelay",P2P:"P2P"},Ua=z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),JP={Public:"Public",Private:"Private"},ZP=z.enum(["Public","Private"]).catch("Public"),YP={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},XP=z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Wd=z.object({Urls:z.string().nullish(),Username:z.string().nullish(),Credential:z.string().nullish()}).passthrough(),eI=z.object({Enabled:z.boolean().nullish()}).passthrough(),Kd=z.object({SystemState:eI.nullish(),DefaultTopology:Oa.nullish(),AllowCreatorTopologyOverride:z.boolean().nullish(),DefaultChatMode:Ua.nullish(),AllowCreatorChatOverride:z.boolean().nullish(),MaxPlayersPerRoom:z.number().nullish(),RoomTtlSeconds:z.number().nullish(),MaxRoomLifetimeSeconds:z.number().nullish(),HeartbeatIntervalMs:z.number().nullish(),MemberTimeoutMs:z.number().nullish(),MaxSignalPayloadBytes:z.number().nullish(),MaxChatTextLength:z.number().nullish(),RoomLogCap:z.number().nullish(),IceServers:z.array(Wd).nullish()}).passthrough(),tI=z.object({UserID:z.string().nullish(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),Ready:z.boolean().nullish(),State:z.record(z.string(),z.string()).nullish(),JoinedAt:z.number().nullish(),IsHost:z.boolean().nullish(),LastSeenMs:z.number().nullish()}).passthrough(),iI=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),Topology:Oa.nullish(),ChatMode:Ua.nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),MemberCount:z.number().nullish(),CreatedAt:z.number().nullish()}).passthrough(),sI=z.object({Seq:z.number().nullish(),Type:XP.nullish(),FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Kind:z.string().nullish(),Payload:z.string().nullish(),Ts:z.number().nullish()}).passthrough(),Ui=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),OwnerUserID:z.string().nullish(),Topology:Oa.nullish(),ChatMode:Ua.nullish(),Visibility:ZP.nullish(),Status:z.string().nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Members:z.array(tI).nullish(),IceServers:z.array(Wd).nullish(),Seq:z.number().nullish(),BannedUserIDs:z.array(z.string()).nullish()}).passthrough(),Qd=z.object({Removed:z.boolean().nullish(),Banned:z.boolean().nullish()}).passthrough(),Hd=z.object({WasBanned:z.boolean().nullish()}).passthrough(),Ea=z.object({Closed:z.boolean().nullish(),NewHostUserID:z.string().nullish()}).passthrough(),$d=z.object({Rooms:z.array(iI).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}).passthrough(),Jd=z.object({Envelopes:z.array(sI).nullish(),MaxSeq:z.number().nullish()}).passthrough(),wr=z.object({Seq:z.number().nullish()}).passthrough(),He={CreateRoom:"CreateRoom",JoinRoom:"JoinRoom",LeaveRoom:"LeaveRoom",ListRooms:"ListRooms",GetRoom:"GetRoom",CloseRoom:"CloseRoom",Poll:"Poll",SendSignal:"SendSignal",SendChat:"SendChat",SetMemberState:"SetMemberState",ClaimHost:"ClaimHost",KickMember:"KickMember",UnbanMember:"UnbanMember"};var qa=z.object({TitleCustomData:Tr.nullish(),Character:Ws.nullish(),Item:_n.nullish(),Currency:xn.nullish(),Store:ds.nullish(),Lootbox:Sa.nullish(),Quest:Ni.nullish(),TimedEvent:As.nullish(),Leaderboard:Ls.nullish(),Season:Vs.nullish(),Reward:ba.nullish(),Collection:gr.nullish(),Craft:Pa.nullish(),DealOffer:Mo.nullish(),Premium:ya.nullish(),TimedBoost:Pr.nullish(),CoopEvent:Xs.nullish(),GameLoop:Ar.nullish(),Match:Zo.nullish(),Experiment:ph.nullish(),Blockchain:_o.nullish(),Marketplace:ia.nullish(),Multiplayer:Kd.nullish(),UserCustomData:mn.nullish(),Referral:Ta.nullish(),Localization:xh.nullish(),Analytics:eh.nullish(),Social:Gc.nullish(),PlatformBridge:Fc.nullish()}).passthrough();var Xt={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Mr=class extends q{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(Xt.GetTitlePublicConfiguration,e,qa)}getTitlePublicConfigurationExcept(e){return this.send(Xt.GetTitlePublicConfigurationExcept,e,qa)}getCurrencyDefinitions(e){return this.send(Xt.GetCurrencyDefinitions,e,xn)}getItemDefinitions(e){return this.send(Xt.GetItemDefinitions,e,_n)}getServerTime(e){return this.send(Xt.GetServerTime,e,Ue)}};var Or=class extends q{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(qe.GetGameLoops,e,Ar)}getBoardDefinition(e,t=false){return this.send(qe.GetBoardDefinition,e,zr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(qe.GetBoardDefinitionForLevel,e,zr,{silent:t})}getUserBoardState(e){return this.send(qe.GetUserBoardState,e,Td)}boardLoopRoll(e){return this.send(qe.BoardLoopRoll,e,Ud)}boardLoopAttack(e){return this.send(qe.BoardLoopAttack,e,Ed)}boardLoopRaid(e){return this.send(qe.BoardLoopRaid,e,wa)}boardLoopRaidFast(e){return this.send(qe.BoardLoopRaidFast,e,wa)}boardLoopBuild(e){return this.send(qe.BoardLoopBuild,e,qd)}boardSpecialChoose(e){return this.send(qe.BoardSpecialChoose,e,Bd)}boardSpecialApplyMultiplier(e){return this.send(qe.BoardSpecialApplyMultiplier,e,Ld)}boardSpecialClaim(e){return this.send(qe.BoardSpecialClaim,e,Gd)}getCommunityChestState(e){return this.send(qe.GetCommunityChestState,e,jd)}joinOrCreateCommunityChest(e){return this.send(qe.JoinOrCreateCommunityChest,e,Nd)}claimCommunityChestMilestone(e){return this.send(qe.ClaimCommunityChestMilestone,e,Ma)}claimCommunityChestGrandPrize(e){return this.send(qe.ClaimCommunityChestGrandPrize,e,Ma)}leaveCommunityChest(e){return this.send(qe.LeaveCommunityChest,e,_d)}};var rI={Live:"Live",Latest:"Latest",Specific:"Specific"},oI={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},aI=z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),lI={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"},uI=z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),cI=z.object({Level:aI,Message:z.string().nullish(),Data:Ut.nullish()}),pI=z.object({Error:uI,Message:z.string().nullish(),StackTrace:z.string().nullish()}),Zd=z.object({FunctionName:z.string().nullish(),Revision:z.number().nullish(),FunctionResult:Ut.nullish(),FunctionResultTooLarge:z.boolean().nullish(),Logs:z.array(cI).nullish(),LogsTooLarge:z.boolean().nullish(),ExecutionTimeSeconds:z.number().nullish(),APIRequestsIssued:z.number().nullish(),Error:pI.nullish()}),Ba={Execute:"Execute"};var Ur=class extends q{constructor(e){super(e,"CloudCode");}execute(e){return this.send(Ba.Execute,e,Zd)}};var Er=class extends q{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Qe.GetDefinitions,e,lp)}getUserState(e){return this.send(Qe.GetUserState,e,up)}depositToken(e){return this.send(Qe.DepositToken,e,cp)}depositNFT(e){return this.send(Qe.DepositNFT,e,pp)}requestTokenWithdrawal(e){return this.send(Qe.RequestTokenWithdrawal,e,hp)}requestNFTWithdrawal(e){return this.send(Qe.RequestNFTWithdrawal,e,dp)}getTransactionHistory(e){return this.send(Qe.GetTransactionHistory,e,mp)}retryWithdrawal(e){return this.send(Qe.RetryWithdrawal,e,fp)}confirmWithdrawal(e){return this.send(Qe.ConfirmWithdrawal,e,gp)}donateToDeveloper(e){return this.send(Qe.DonateToDeveloper,e,Ho)}donateToUsersPool(e){return this.send(Qe.DonateToUsersPool,e,Ho)}getPlayAccess(e){return this.send(Qe.GetPlayAccess,e,op)}confirmPlayAccess(e){return this.send(Qe.ConfirmPlayAccess,e,Bt)}};var qr=class extends q{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Te.GetDefinitions,e,Ap)}getGroupedOffers(e){return this.send(Te.GetGroupedOffers,e,wp)}getOffersByItem(e){return this.send(Te.GetOffersByItem,e,sa)}getOffer(e){return this.send(Te.GetOffer,e,Mp)}getBuyOrders(e){return this.send(Te.GetBuyOrders,e,sa)}getMyState(e){return this.send(Te.GetMyState,e,kn)}getHistory(e){return this.send(Te.GetHistory,e,Up)}createListing(e){return this.send(Te.CreateListing,e,Ai)}cancelListing(e){return this.send(Te.CancelListing,e,at)}buy(e){return this.send(Te.Buy,e,at)}marketBuy(e){return this.send(Te.MarketBuy,e,at)}marketSell(e){return this.send(Te.MarketSell,e,at)}createAuction(e){return this.send(Te.CreateAuction,e,Ai)}placeBid(e){return this.send(Te.PlaceBid,e,Op)}claimAuction(e){return this.send(Te.ClaimAuction,e,at)}createBuyOrder(e){return this.send(Te.CreateBuyOrder,e,Ai)}cancelBuyOrder(e){return this.send(Te.CancelBuyOrder,e,at)}fillBuyOrder(e){return this.send(Te.FillBuyOrder,e,at)}createDirectTrade(e){return this.send(Te.CreateDirectTrade,e,Ai)}respondDirectTrade(e){return this.send(Te.RespondDirectTrade,e,at)}cancelDirectTrade(e){return this.send(Te.CancelDirectTrade,e,at)}claimBack(e){return this.send(Te.ClaimBack,e,at)}};var Br=class extends q{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(He.CreateRoom,e,Ui)}joinRoom(e){return this.send(He.JoinRoom,e,Ui)}leaveRoom(e,t=false){return this.send(He.LeaveRoom,e,Ea,{keepalive:t})}listRooms(e){return this.send(He.ListRooms,e,$d)}getRoom(e){return this.send(He.GetRoom,e,Ui)}closeRoom(e){return this.send(He.CloseRoom,e,Ea)}poll(e){return this.send(He.Poll,e,Jd)}sendSignal(e){return this.send(He.SendSignal,e,wr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(He.ClaimHost,e,Ui)}kickMember(e){return this.send(He.KickMember,e,Qd)}unbanMember(e){return this.send(He.UnbanMember,e,Hd)}sendChat(e){return this.send(He.SendChat,e,wr)}setMemberState(e){return this.send(He.SetMemberState,e,wr)}};var hI={Free:"Free",Price:"Price",Holding:"Holding"},La=z.enum(["Free","Price","Holding"]).catch("Free"),dI={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},mI=z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),fI={All:"All",Any:"Any"},gI=z.enum(["All","Any"]).catch("All"),yI={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},RI=z.enum(["Public","Unlisted","Friends"]).catch("Public"),CI={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},SI=z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),xI={Purchase:"Purchase",Free:"Free",Holding:"Holding"},Xd=z.enum(["Purchase","Free","Holding"]).catch("Free"),bI={New:"New",Popular:"Popular",MostLiked:"MostLiked"},DI={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},PI=z.enum(["Creator","License","Free","Holding"]).catch("License"),II=z.object({Type:si.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),Amount:z.number().nullish(),MinLevel:z.number().nullish()}).passthrough(),vI=z.object({Requirements:z.array(II).nullish(),Match:gI.nullish(),Mode:mI.nullish()}).passthrough(),TI=z.object({OptionID:z.string().nullish(),Mode:La.nullish(),Price:ae.nullish(),Holding:vI.nullish()}).passthrough(),kI=z.object({AllowedMimeTypes:z.array(z.string()).nullish(),MaxBytes:z.number().nullish(),MaxCount:z.number().nullish(),Required:z.boolean().nullish()}).passthrough(),zI=z.object({DisplayName:z.string().nullish(),Enabled:z.boolean().nullish(),Files:z.record(z.string(),kI).nullish(),ThumbnailRequired:z.boolean().nullish(),AllowedAccessModes:z.array(La).nullish(),PricePolicy:Tn.nullish(),PublishGate:J.nullish(),PublishFeeOptions:oe.nullish(),TagVocabulary:z.array(z.string()).nullish(),MaxPublishedPerPlayer:z.number().nullish(),DailyPublishCap:z.number().nullish()}).passthrough(),AI=z.object({Allowed:z.array(zi).nullish(),MaxRequirements:z.number().nullish()}).passthrough(),wI=z.object({AutoHideReportThreshold:z.number().nullish(),RequireApproval:z.boolean().nullish(),BlockedTerms:z.array(z.string()).nullish()}).passthrough(),MI=z.object({MaxTitleLength:z.number().nullish(),MaxDescriptionLength:z.number().nullish(),MaxTags:z.number().nullish(),MaxTagLength:z.number().nullish(),MaxMetadataKeys:z.number().nullish(),MaxMetadataValueLength:z.number().nullish(),MaxAccessOptions:z.number().nullish(),ThumbnailMaxBytes:z.number().nullish()}).passthrough(),OI=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Schedule:me.nullish(),Gate:J.nullish(),Order:z.number().nullish()}).passthrough(),UI=z.object({Enabled:z.boolean().nullish(),Gate:J.nullish(),Schedule:me.nullish(),ContentTypes:z.record(z.string(),zI).nullish(),PricePolicy:Tn.nullish(),Commission:ta.nullish(),HoldingPolicy:AI.nullish(),Moderation:wI.nullish(),Limits:MI.nullish(),Featured:z.array(OI).nullish()}).passthrough(),EI=z.object({Acquisitions:z.number().nullish(),Downloads:z.number().nullish(),Likes:z.number().nullish(),Favorites:z.number().nullish(),ReportCount:z.number().nullish()}).passthrough(),ei=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),CreatorUserID:z.string().nullish(),IsOfficial:z.boolean().nullish(),CreatorPublicData:Oe.nullish(),Title:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),Metadata:z.record(z.string(),z.string()).nullish(),ThumbnailUrl:z.string().nullish(),Visibility:RI.nullish(),Access:z.array(TI).nullish(),Status:SI.nullish(),ModerationNote:z.string().nullish(),Stats:EI.nullish(),Revision:z.number().nullish(),FileCount:z.number().nullish(),TotalBytes:z.number().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),PublishedAt:c.nullish(),IsMine:z.boolean().nullish(),Owned:z.boolean().nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish()}).passthrough(),qI=z.object({OptionID:z.string().nullish(),Mode:La.nullish(),Available:z.boolean().nullish()}).passthrough(),em=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Order:z.number().nullish()}).passthrough(),tm=z.object({Definitions:UI.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish(),CanPublish:z.record(z.string(),z.boolean()).nullish(),Collections:z.array(em).nullish()}).passthrough(),Lr=z.object({Items:z.array(ei).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),im=z.object({Content:ei.nullish(),AccessState:z.array(qI).nullish(),CanDownload:z.boolean().nullish()}).passthrough(),sm=z.object({Collection:em.nullish(),Items:z.array(ei).nullish()}).passthrough(),nm=z.object({CreatorUserID:z.string().nullish(),PublicData:Oe.nullish(),PublishedCount:z.number().nullish(),FollowerCount:z.number().nullish(),IsFollowing:z.boolean().nullish(),Items:z.array(ei).nullish()}).passthrough(),Yd=z.object({Role:z.string().nullish(),Index:z.number().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish(),ServerCopy:z.boolean().nullish()}).passthrough(),rm=z.object({ContentID:z.string().nullish(),Revision:z.number().nullish(),Uploads:z.array(Yd).nullish(),ThumbnailUpload:Yd.nullish(),ExpiresAt:c.nullish()}).passthrough(),om=z.object({Content:ei.nullish(),Resources:M.nullish()}).passthrough(),Ga=z.object({Content:ei.nullish()}).passthrough(),am=z.object({ContentID:z.string().nullish(),OptionID:z.string().nullish(),Source:Xd.nullish(),AlreadyOwned:z.boolean().nullish(),AccessActive:z.boolean().nullish(),Settlement:xt.nullish(),Resources:M.nullish(),CommissionTaken:ae.nullish()}).passthrough(),BI=z.object({Role:z.string().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish()}).passthrough(),lm=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),Revision:z.number().nullish(),AccessVia:PI.nullish(),Files:z.array(BI).nullish(),ThumbnailUrl:z.string().nullish(),ExpiresAt:c.nullish()}).passthrough(),LI=z.object({ContentID:z.string().nullish(),Source:Xd.nullish(),OptionID:z.string().nullish(),PricePaid:ae.nullish(),AcquiredAt:c.nullish(),Content:ei.nullish()}).passthrough(),um=z.object({Licenses:z.array(LI).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),We={GetDefinitions:"GetDefinitions",Browse:"Browse",GetContent:"GetContent",GetCollection:"GetCollection",GetCreatorProfile:"GetCreatorProfile",BeginUpload:"BeginUpload",Publish:"Publish",UpdateContent:"UpdateContent",Unpublish:"Unpublish",GetMyContent:"GetMyContent",Acquire:"Acquire",GetDownload:"GetDownload",GetMyLicenses:"GetMyLicenses",GetMyFavorites:"GetMyFavorites"};var Gr=class extends q{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(We.GetDefinitions,e,tm)}browse(e){return this.send(We.Browse,e,Lr)}getContent(e){return this.send(We.GetContent,e,im)}getCollection(e){return this.send(We.GetCollection,e,sm)}getCreatorProfile(e){return this.send(We.GetCreatorProfile,e,nm)}beginUpload(e){return this.send(We.BeginUpload,e,rm)}publish(e){return this.send(We.Publish,e,om)}updateContent(e){return this.send(We.UpdateContent,e,Ga)}unpublish(e){return this.send(We.Unpublish,e,Ga)}getMyContent(e){return this.send(We.GetMyContent,e,Lr)}acquire(e){return this.send(We.Acquire,e,am)}getDownload(e){return this.send(We.GetDownload,e,lm)}getMyLicenses(e){return this.send(We.GetMyLicenses,e,um)}getMyFavorites(e){return this.send(We.GetMyFavorites,e,Lr)}};var Fr=class extends q{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let r=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(r,t,i,{throttleKey:`${r}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,Fp,"defs")}get(e){return this.sendKeyed("Get",e,ra,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,jp,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,oa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Np,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,aa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,aa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,_p,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,Kp,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Wp,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,Qp,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,Vp,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Hp,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,ra,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,oa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Vr=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e$1){this.settings=_a(e$1),this.emitter=new Ci,this.platform=e$1.platform??new e,this.clientPlatform=e$1.clientPlatform??il(),this.acquisition=new Vt(this.platform),this.acquisition.capture(),this.playtime=new Si(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear();}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e$1.fetch??globalThis.fetch.bind(globalThis),this.transport=new Ji({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e$1.fetch,debugLogging:this.settings.debugLogging,throttleMs:e$1.throttleMs,maxRequestsPerSecond:e$1.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new es(this.emitter),this.cache=new is(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e$1.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new ss(this.platform.storage,this.settings.titleID),this.api={authentication:new Gn(this),user:new Vn(this),currency:new jn(this),item:new Wn(this),store:new Kn(this),purchase:new Jn(this),lootbox:new Xn(this),reward:new er(this),quest:new or(this),tutorial:new tr(this),communityMarketing:new ir(this),chat:new sr(this),push:new nr(this),localization:new rr(this),timedEvent:new ar(this),leaderboard:new lr(this),season:new ur(this),premium:new cr(this),character:new pr(this),match:new hr(this),craft:new mr(this),ai:new fr(this),collection:new yr(this),coopEvent:new Rr(this),dealOffer:new Cr(this),referral:new Sr(this),mailbox:new xr(this),social:new br(this),timedBoost:new Ir(this),userCustomData:new vr(this),titleCustomData:new kr(this),title:new Mr(this),gameLoop:new Or(this),cloudCode:new Ur(this),blockchain:new Er(this),marketplace:new qr(this),multiplayer:new Br(this),workshop:new Gr(this),dataCollections:new Fr(this),analytics:new Bn(this),experiment:new Ln(this)},this.userService=new ls(this),this.cache.attachState(this.userService),this.auth=new ns(this),this.currency=new cs(this),this.item=new ps(this),this.store=new fs(this),this.purchase=new gs(this),this.checkout=new ys(this),this.lootbox=new Rs(this),this.reward=new Cs(this),this.quest=new zs(this),this.tutorial=new xs(this),this.communityMarketing=new bs(this),this.chat=new Is(this),this.push=new vs(this),this.localization=new ks(this),this.timedEvent=new Ms(this),this.leaderboard=new Gs(this),this.season=new js(this),this.premium=new Ns(this),this.character=new Ks(this),this.match=new Qs(this),this.craft=new Hs(this),this.ai=new Js(this),this.collection=new Zs(this),this.coopEvent=new en(this),this.dealOffer=new nn(this),this.referral=new rn(this),this.mailbox=new ln(this),this.social=new pn(this),this.timedBoost=new hn(this),this.userCustomData=new fn(this),this.titleCustomData=new gn(this),this.title=new yn(this),this.gameLoop=new Rn(this),this.cloudCode=new Cn(this),this.blockchain=new Dn(this),this.marketplace=new zn(this),this.multiplayer=new An(this),this.workshop=new wn(this),this.dataCollections=new On(this),this.analytics=new En(this),this.experiments=new qn(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.platform.getFullURL(),RelatedEntityID:d()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var jr=class{ctx;constructor(e){this.ctx=new Vr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Gt(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(n,{...s,...i},z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get platform(){return this.ctx.platform}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function FI(o){return new jr(o)}var cm="idos_sso",pm="state",Fa="idos:sso:state",VI="https://idosgames.com/sso/",jI=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],NI=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function _I(){if(typeof window>"u")return false;let{origin:o}=window.location;return jI.includes(o)||NI.test(o)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function WI(){if(typeof window>"u")return null;let o=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!o)return null;let e=new URLSearchParams(o),t=e.get(cm);if(!t)return null;let i=e.get(pm)??"",s=JI();return YI(e),ZI(),s&&i!==s?null:{code:t,state:i}}function KI(o){if(typeof window>"u")return;let e=o.returnTo??QI(),t=HI();$I(t);let i=new URL(o.ssoUrl??VI);i.searchParams.set("title",o.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function QI(){let{origin:o,pathname:e,search:t}=window.location;return `${o}${e}${t}`}function HI(){let o=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(o);else for(let e=0;e<o.length;e++)o[e]=Math.floor(Math.random()*256);return Array.from(o,e=>e.toString(16).padStart(2,"0")).join("")}function $I(o){try{window.sessionStorage.setItem(Fa,o);}catch{}}function JI(){try{return window.sessionStorage.getItem(Fa)}catch{return null}}function ZI(){try{window.sessionStorage.removeItem(Fa);}catch{}}function YI(o){o.delete(cm),o.delete(pm);let e=o.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var XI={EMAIL_SENDER_NOT_CONFIGURED:"Sign-in by e-mail is unavailable in this game right now. Try another way to sign in.",INVALID_VERIFICATION_CODE:"That code is not right. Check the e-mail and try again.",VERIFICATION_CODE_ATTEMPTS_EXCEEDED:"Too many wrong attempts. Ask for a new code.",INCORRECT_EMAIL_OR_PASSWORD:"Wrong e-mail or password.",INCORRECT_EMAIL:"That does not look like an e-mail address.",PASSWORD_LENGTH_INVALID:"The password must be 8 to 100 characters long.",TOO_MANY_FAILED_ATTEMPTS:"Too many attempts. Please try again a little later.",RATE_LIMIT_EXCEEDED:"Too many requests. Please try again in a moment.",APPLE_EMAIL_MISSING:"Apple did not share an e-mail address. Try again and allow it, or use another way to sign in.",INVALID_WALLET_SIGNATURE:"The signature does not match the wallet. Please try again.",WALLET_CHALLENGE_EXPIRED:"The request expired. Please try again.",WALLET_CHANGES_TOO_FREQUENT:"Too many wallets were changed this week. Try again in a few days.",WALLET_UNLINK_COOLDOWN:"This wallet was unlinked from another account less than 7 days ago. Try again after the 7 days.",PLAY_ACCESS_GUEST_DISABLED:"Guest play is off in this game. Sign in to link a crypto wallet.",PLAY_ACCESS_WALLET_LOGIN_ONLY:"This game can only be entered with a crypto wallet or your iDos Games account.",PLAY_ACCESS_WALLET_USED_BY_ANOTHER_ACCOUNT:"This wallet already plays with another account.",PLAY_ACCESS_WALLET_REQUIRED:"Link a crypto wallet to play.",PLAY_ACCESS_WALLET_NETWORK_NOT_GATED:"This wallet's network is not accepted here. Link a wallet of the required network.",PLAY_ACCESS_REQUIRED:"Check your balance to continue.",PLAY_ACCESS_CHECK_FAILED:"Could not check your balance right now. Please try again in a moment."};function ev(o,e="Something went wrong. Please try again."){return o?XI[o]??o:e}function tv(o,e){return !!o?.Claims?.[e]?.ClaimedAt}function iv(o){let e=o?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function sv(o,e){return o?.Claims?.[e]?.PremiumTiers??[]}function dm(o,e,t,i=1){if(!o)return e;let s=o.Base??e,n=Math.max(0,t-i),r;switch(o.Shape??"Flat"){case "PerStep":r=s+(o.PerStep??0)*n;break;case "PerStepRate":r=s*(1+(o.PerStepRate??0)*n);break;case "Geometric":r=s*Math.pow(1+(o.GrowthRate??0),n);break;case "Table":r=s*hm(o,t,1);break;case "TableAbsolute":r=hm(o,t,s);break;default:r=s;break}return Number.isNaN(r)?s:(o.MinResult!=null&&r<o.MinResult&&(r=o.MinResult),o.MaxResult!=null&&r>o.MaxResult&&(r=o.MaxResult),r)}function nv(o,e,t=1){return dm(o,1,e,t)}function rv(o){if(!o)return false;switch(o.Shape??"Flat"){case "PerStep":return (o.PerStep??0)!==0;case "PerStepRate":return (o.PerStepRate??0)!==0;case "Geometric":return (o.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return mm(o.Points).length>0;default:return o.MinResult!=null||o.MaxResult!=null}}function ov(o){if(Number.isNaN(o)||o<=0)return 0;if(!Number.isFinite(o))return Number.MAX_SAFE_INTEGER;let e=Math.round(o);return Math.abs(o-e)<=1e-9*Math.max(1,Math.abs(o))?e:Math.ceil(o)}function mm(o){if(!o)return [];let e=[];for(let t of o)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function hm(o,e,t){let i=mm(o.Points);if(i.length===0)return t;let s=null,n=null,r=null;for(let p of i)(r===null||p.AtStep>r.AtStep)&&(r=p),p.AtStep<=e&&(s===null||p.AtStep>=s.AtStep)&&(s=p),p.AtStep>e&&(n===null||p.AtStep<n.AtStep)&&(n=p);if(s===null)return t;if(n===null){let p=o.TailGrowthRate??0;return p===0?r.Value:r.Value*Math.pow(1+p,e-r.AtStep)}switch(o.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+p*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let d=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+d*(n.Value-s.Value)}let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,p)}default:return s.Value}}var av={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Va=z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),lv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},uv=z.enum(["Top","Bottom","Left","Right"]).catch("Top"),cv=z.object({PlacementID:z.string().nullish(),Type:Va.nullish(),Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),CreditsRewarded:z.number().nullish(),AllowedProviderIDs:z.array(z.string()).nullish()}).passthrough(),pv=z.object({DefaultCreditsPerView:z.number().nullish(),MaxCreditsBalance:z.number().nullish(),DailyCreditEarnCap:z.number().nullish(),DailyViewCap:z.number().nullish(),MinSecondsBetweenViews:z.number().nullish()}).passthrough(),hv=z.object({CooldownSeconds:z.number().nullish(),MinSessionTimeBeforeFirstSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),dv=z.object({Enabled:z.boolean().nullish(),Position:uv.nullish(),RefreshIntervalSeconds:z.number().nullish()}).passthrough(),mv=z.object({Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish()}).passthrough(),fv=z.object({MaxImpressionsPerHour:z.number().nullish(),MaxImpressionsPerDay:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),gv=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),DisableInterstitials:z.boolean().nullish(),DisableBanners:z.boolean().nullish(),DisableAppOpen:z.boolean().nullish()}).passthrough(),yv=z.object({RequirePersonalizedAdsConsent:z.boolean().nullish(),RequireTrackingConsent:z.boolean().nullish(),CurrentPolicyVersion:z.string().nullish(),RegulatedRegions:z.array(z.string()).nullish()}).passthrough(),Rv=z.object({RequireServerSideVerification:z.boolean().nullish(),PendingRequestTtlSeconds:z.number().nullish(),MaxPendingRequestsPerUser:z.number().nullish()}).passthrough(),Cv=z.object({AndroidUnitID:z.string().nullish(),IosUnitID:z.string().nullish(),WebUnitID:z.string().nullish(),Type:Va.nullish()}).passthrough(),Sv={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},xv=z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),bv=z.object({ProviderID:z.string().nullish(),Kind:xv.nullish(),Enabled:z.boolean().nullish(),Priority:z.number().nullish(),AndroidAppID:z.string().nullish(),IosAppID:z.string().nullish(),WebAppID:z.string().nullish(),Units:z.record(z.string(),Cv).nullish()}).passthrough();z.object({Enabled:z.boolean().nullish(),Placements:z.record(z.string(),cv).nullish(),Providers:z.record(z.string(),bv).nullish(),RewardedVideo:pv.nullish(),Interstitial:hv.nullish(),Banner:dv.nullish(),AppOpen:mv.nullish(),FrequencyCapping:fv.nullish(),PremiumAdReductions:z.array(gv).nullish(),Consent:yv.nullish(),Verification:Rv.nullish()}).passthrough();var Dv=z.object({RewardedVideoCredit:z.number().nullish(),TotalEarned:z.number().nullish(),TotalSpent:z.number().nullish()}).passthrough(),Pv=z.object({PlacementID:z.string().nullish(),LastShownAt:c.nullish(),LastCompletedAt:c.nullish(),TotalImpressions:z.number().nullish(),TotalCompletions:z.number().nullish(),ConsecutiveFailures:z.number().nullish()}).passthrough(),Iv=z.object({Date:c.nullish(),ImpressionsByPlacement:z.record(z.string(),z.number()).nullish(),CompletionsByPlacement:z.record(z.string(),z.number()).nullish(),TotalImpressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish(),AppOpenImpressions:z.number().nullish(),CreditsEarnedToday:z.number().nullish()}).passthrough(),vv=z.object({SessionID:z.string().nullish(),SessionStartAt:c.nullish(),Impressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish()}).passthrough(),Tv=z.object({PersonalizedAdsConsent:z.boolean().nullish(),TrackingConsent:z.boolean().nullish(),PolicyVersion:z.string().nullish(),Region:z.string().nullish(),ConsentGivenAt:c.nullish(),ConsentRevokedAt:c.nullish()}).passthrough(),kv=z.object({RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),Type:Va.nullish(),IssuedAt:c.nullish(),ExpiresAt:c.nullish(),CreditsToAward:z.number().nullish()}).passthrough(),zv=z.object({InvalidSsvCount:z.number().nullish(),OrphanCompletions:z.number().nullish(),FastCompletions:z.number().nullish(),LastFlaggedAt:c.nullish()}).passthrough();z.object({Credits:Dv.nullish(),Placements:z.record(z.string(),Pv).nullish(),Daily:Iv.nullish(),Session:vv.nullish(),LastImpressionAt:c.nullish(),LastInterstitialAt:c.nullish(),LastRewardedAt:c.nullish(),LastAppOpenAt:c.nullish(),TotalImpressions:z.number().nullish(),TotalRewardedCompletions:z.number().nullish(),AdsDisabledUntil:c.nullish(),Consent:Tv.nullish(),PendingRequests:z.record(z.string(),kv).nullish(),FraudFlags:zv.nullish(),UpdatedAt:c.nullish()}).passthrough();
|
|
2
|
-
export{Ge as AIAction,
|
|
1
|
+
import {e,d,l,m,f}from'./chunk-YEBYHDZG.js';export{e as BrowserPlatformAdapter,a as BrowserStorage,b as MemoryStorage,n as NoopPlatformAdapter,h as PLATFORM_BRIDGE_ACK,f as PLATFORM_ORIGINS,i as PLATFORM_PAGE_UNAVAILABLE,k as PLATFORM_TOPUP_MESSAGES,j as askPlatformPage,l as canUsePlatformTopUp,g as isPlatformParentOrigin,m as requestPlatformTopUp}from'./chunk-YEBYHDZG.js';import {b,a,c as c$1}from'./chunk-CS7ACWDY.js';export{e as isFail,d as isOk}from'./chunk-CS7ACWDY.js';import {z}from'zod';import Nt from'decimal.js';var Ci=class{listeners=new Map;on(e,t){let i=this.listeners.get(e);return i||(i=new Set,this.listeners.set(e,i)),i.add(t),()=>{this.off(e,t);}}once(e,t){let i=this.on(e,s=>{i(),t(s);});return i}off(e,t){let i=this.listeners.get(e);i&&(i.delete(t),i.size===0&&this.listeners.delete(e));}emit(e,t){let i=this.listeners.get(e);if(i)for(let s of [...i])s(t);}removeAllListeners(){this.listeners.clear();}};function km(){let o=new Map;return {get:e=>o.get(e)??null,set:(e,t)=>{o.set(e,t);},remove:e=>{o.delete(e);}}}function ja(){return zm()??km()}function zm(){try{let o=globalThis.localStorage;if(!o)return null;let e="__idos_probe__";return o.setItem(e,"1"),o.removeItem(e),{get:t=>{try{return o.getItem(t)}catch{return null}},set:(t,i)=>{try{o.setItem(t,i);}catch{try{o.removeItem(t);}catch{}}},remove:t=>{try{o.removeItem(t);}catch{}}}}catch{return null}}var Na="https://api.idosgames.com";function _a(o){return {titleID:o.titleID,titleTemplateID:o.titleTemplateID??"default",buildKey:o.buildKey??"",baseUrl:(o.baseUrl??Na).replace(/\/+$/,""),devBuild:o.devBuild??false,debugLogging:o.debugLogging??false,configStorage:o.configStorage??ja(),locale:o.locale??Am(),appVersion:o.appVersion??""}}function Am(){try{return globalThis.navigator?.language??""}catch{return ""}}var Kr="idos_acq",Wa=["gclid","fbclid","ttclid","msclkid","yclid"],wm=["ref","r"],Mm=["ref_","ref-","ref=","r_","r-"];var Vt=class{constructor(e){this.platform=e;}platform;capture(){let e=this.readFromEnvironment();Om(e)&&this.store({signal:e,capturedAt:Date.now()});}buildForLogin(e){let t=this.read(),i=t?{...t.signal}:{},s=qm(this.platform.getDeviceModel());return s&&(i.OsVersion=s),e&&(i.AppVersion=e),Object.keys(i).length>0?i:void 0}clear(){this.platform.storage.remove(Kr);}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=Ha(Qa(t));if(i)return i}return qi(t)}readFromEnvironment(){let e={},t=Qa(this.platform.getFullURL());Ft(e,"UtmSource",t.get("utm_source")),Ft(e,"UtmMedium",t.get("utm_medium")),Ft(e,"UtmCampaign",t.get("utm_campaign")),Ft(e,"UtmTerm",t.get("utm_term")),Ft(e,"UtmContent",t.get("utm_content")),Ft(e,"ClaimToken",t.get("idos_click"));for(let C of Wa){let j=t.get(C);if(j){e.ClickID=j;break}}let i=this.platform.getStartParameter()??"",s=Em(i);if(s){for(let C of Um)Ft(e,C,s.get($a[C])??null);for(let C of Wa){let j=s.get(C);if(j){e.ClickID=j;break}}}let n=qi(s?s.get("ref")??s.get("r")??"":i),r=Ha(t),p=n||r;p&&(e.ReferralCode=p,e.ChannelHint=n?"telegram":"query");let d=this.platform.getReferrer?.();return d&&(e.Referrer=d),e}read(){try{let e=this.platform.storage.getString(Kr);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(Kr,JSON.stringify(e));}catch{}}};function Om(o){return !!(o.UtmSource||o.UtmMedium||o.UtmCampaign||o.ClickID||o.Referrer||o.ReferralCode||o.ClaimToken)}function Ft(o,e,t){t&&(o[e]=t);}var Ka="a1_",$a={UtmSource:"utm_source",UtmMedium:"utm_medium",UtmCampaign:"utm_campaign",UtmTerm:"utm_term",UtmContent:"utm_content"},Um=Object.keys($a);function Em(o){let e=(o||"").trim();if(!e.startsWith(Ka))return null;let t=e.slice(Ka.length);if(!t)return null;try{let i=t.replace(/-/g,"+").replace(/_/g,"/"),s=atob(i+"=".repeat((4-i.length%4)%4)),n=Uint8Array.from(s,d=>d.charCodeAt(0)),r=new TextDecoder().decode(n),p=new URLSearchParams(r);return [...p.keys()].length>0?p:null}catch{return null}}function Qa(o){try{let e=o.indexOf("?");return new URLSearchParams(e>=0?o.slice(e):"")}catch{return new URLSearchParams}}function Ha(o){for(let e of wm){let t=o.get(e);if(t)return qi(t)}return null}function qi(o){let e=(o||"").trim();if(!e)return null;for(let t of Mm)if(e.toLowerCase().startsWith(t)){e=e.slice(t.length).trim();break}return e||null}function qm(o){let e=o||"",t=/android\s+(\d+)/i.exec(e);if(t)return t[1];let i=/(?:iphone )?os\s+(\d+)[._]/i.exec(e);if(i)return i[1]}var Ja="idos_usage_pending",Za="idos_usage_session",Ya="idos_usage_closed_session",Xa="idos_usage_new_session",el="idos_usage_last_activity",Si=class{constructor(e){this.ctx=e;}ctx;pendingSeconds=0;currentSessionSeconds=0;pendingClosedSessionSeconds=0;isNewSessionPending=false;lastTickAt=0;suspendedAt=null;countingPaused=false;timer=null;started=false;flushing=false;start(){this.started||typeof window>"u"||(this.started=true,this.restore(),this.lastTickAt=Date.now(),this.countingPaused=typeof document<"u"&&document.visibilityState==="hidden",this.timer=setInterval(()=>this.tick(),200*1e3),window.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("pagehide",this.onPageHide));}async stop(){this.started&&(this.started=false,this.timer&&(clearInterval(this.timer),this.timer=null),typeof window<"u"&&(window.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("pagehide",this.onPageHide)),this.accumulate(),this.closeCurrentSession(false),await this.flush());}onVisibilityChange=()=>{if(!(typeof document>"u")){if(document.visibilityState==="hidden"){this.accumulate(),this.countingPaused=true,this.suspendedAt=Date.now(),this.flush();return}this.countingPaused=false,this.suspendedAt!==null&&((Date.now()-this.suspendedAt)/1e3>=1800&&this.closeCurrentSession(true),this.suspendedAt=null),this.lastTickAt=Date.now();}};onPageHide=()=>{this.accumulate(),this.persist(),this.flush();};tick(){this.accumulate(),this.flush();}accumulate(){let e=Date.now(),t=Math.floor((e-this.lastTickAt)/1e3);this.lastTickAt=e,!(t<=0)&&(this.countingPaused||(this.pendingSeconds+=t,this.currentSessionSeconds+=t,this.persist()));}closeCurrentSession(e){let t=Math.floor(this.currentSessionSeconds);t>0&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t)),this.currentSessionSeconds=0,e&&(this.isNewSessionPending=true),this.persist();}async flush(){if(this.flushing||this.pendingSeconds<=0&&this.pendingClosedSessionSeconds<=0&&!this.isNewSessionPending)return;let e=this.pendingSeconds,t=this.pendingClosedSessionSeconds,i=this.isNewSessionPending;this.flushing=true,this.pendingSeconds=0,this.pendingClosedSessionSeconds=0,this.isNewSessionPending=false,this.persist();try{(await this.ctx.userService.addUsageTime(e,i,t)).ok||(this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist());}catch{this.pendingSeconds+=e,this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,t),this.isNewSessionPending||=i,this.persist();}finally{this.flushing=false;}}restore(){this.pendingSeconds=this.readNumber(Ja),this.currentSessionSeconds=this.readNumber(Za),this.pendingClosedSessionSeconds=this.readNumber(Ya),this.isNewSessionPending=this.readNumber(Xa)!==0;let e=this.readNumber(el);this.currentSessionSeconds>0&&e>0&&(Date.now()-e)/1e3>=1800&&(this.pendingClosedSessionSeconds=Math.max(this.pendingClosedSessionSeconds,Math.floor(this.currentSessionSeconds)),this.currentSessionSeconds=0);}persist(){this.writeNumber(Ja,this.pendingSeconds),this.writeNumber(Za,this.currentSessionSeconds),this.writeNumber(Ya,this.pendingClosedSessionSeconds),this.writeNumber(Xa,this.isNewSessionPending?1:0),this.writeNumber(el,Date.now());}readNumber(e){let t=this.ctx.platform.storage.getString(e),i=t?Number(t):0;return Number.isFinite(i)&&i>0?i:0}writeNumber(e,t){try{this.ctx.platform.storage.setString(e,String(Math.floor(t)));}catch{}}};var ut={Virtual:"Virtual",Crypto:"Crypto"},ii=z.enum(["Virtual","Crypto"]).catch("Virtual"),Bi={Item:"Item",VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency",RewardedVideoCredit:"RewardedVideoCredit",Purchase:"Purchase"},si=z.enum(["Item","VirtualCurrency","CryptoCurrency","RewardedVideoCredit","Purchase"]).catch("Item"),mt={Unknown:"Unknown",Web:"Web",Android:"Android",Ios:"Ios"},Li=z.enum(["Unknown","Web","Android","Ios"]).catch("Unknown"),Bm={GooglePlay:"GooglePlay",AppleAppStore:"AppleAppStore"},Gi=z.enum(["GooglePlay","AppleAppStore","TelegramStars"]).catch("GooglePlay"),Lm={TimedEvent:"TimedEvent",Quest:"Quest",Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season"},Fi=z.enum(["TimedEvent","Quest","Leaderboard","CoopEvent","Season"]).catch("TimedEvent"),Gm={AlwaysOn:"AlwaysOn",Scheduled:"Scheduled",Chained:"Chained",Triggered:"Triggered",Cyclic:"Cyclic",Relative:"Relative"},xi=z.enum(["AlwaysOn","Scheduled","Chained","Triggered","Cyclic","Relative"]).catch("Cyclic"),Ae={None:"None",Device:"Device",Email:"Email",iDosGames:"iDosGames",Facebook:"Facebook",Google:"Google",Apple:"Apple",GooglePlay:"GooglePlay",Telegram:"Telegram",Wallet:"Wallet"};function il(){let o=globalThis,e=o.Capacitor?.getPlatform?.();if(e)return tl(e);let t=o.cordova?.platformId;return t?tl(t):o.navigator?.userAgent??""?mt.Web:mt.Unknown}function tl(o){let e=o.toLowerCase();return e==="android"?mt.Android:e==="ios"?mt.Ios:e==="web"?mt.Web:mt.Unknown}var _=z.union([z.number(),z.string()]).transform((o,e)=>{let t=typeof o=="string"?Number(o):o;return Number.isFinite(t)?Math.trunc(t):(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid integer amount: ${String(o)}`}),z.NEVER)}),Y=z.union([z.number(),z.string()]).transform((o,e)=>{let t=typeof o=="number"?String(o):o.trim();return t===""||Number.isNaN(Number(t))?(e.addIssue({code:z.ZodIssueCode.custom,message:`Invalid decimal: ${String(o)}`}),z.NEVER):t}),c=z.string();var Qr=z.object({Type:si.nullish(),CurrencyID:z.string().nullish(),Amount:_.nullish(),AmountUsd:z.number().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ProductID:z.string().nullish()}),Fm=z.object({Type:Fi.nullish(),EntityID:z.string()}),Vm=z.object({Address:Fm.nullish(),Amount:_.nullish(),Source:z.string().nullish()}),le=z.object({Entries:z.array(Qr).nullish(),EventTokens:z.array(Vm).nullish()}),sl=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Resources:le.nullish()}),H=z.object({Standard:le.nullish(),PremiumBonuses:z.array(z.unknown()).nullish(),PremiumTiers:z.array(sl).nullish()}),xt=z.object({Standard:le.nullish(),PremiumDiscounts:z.array(z.unknown()).nullish(),PremiumTiers:z.array(sl).nullish()}),M=z.object({Grant:H.nullish(),Consume:xt.nullish()}),bt=z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),FromResult:M.nullish(),ToResult:M.nullish()});z.object({FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Transferred:le.nullish()});var jm=z.object({ExperimentID:z.string().nullish(),Variants:z.array(z.string()).nullish()}).passthrough(),Nm={Completed:"Completed",Started:"Started",StepReached:"StepReached"},_m=z.object({FlowIDs:z.array(z.string()).nullish(),Mode:z.enum(["Completed","Started","StepReached"]).catch("Completed").nullish(),StepID:z.string().nullish(),Negate:z.boolean().nullish(),SkippedCountsAsCompleted:z.boolean().nullish()}).passthrough(),J=z.object({Segments:z.array(z.string()).nullish(),MinPremiumTier:z.number().nullish(),RequiredPremiumIDs:z.array(z.string()).nullish(),MinLevel:z.number().nullish(),MaxLevel:z.number().nullish(),Countries:z.array(z.string()).nullish(),RegisteredWithinDays:z.number().nullish(),ActiveWithinDays:z.number().nullish(),Experiment:jm.nullish(),Tutorial:_m.nullish(),Platforms:z.array(Li).nullish()}).passthrough();var ye=z.object({TotalCap:z.number().nullish(),DailyCap:z.number().nullish(),DailyWeightCap:z.number().nullish(),PerActivationCap:z.number().nullish(),CooldownSeconds:z.number().nullish(),MaxPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish()}).passthrough();var Wm=z.object({OffsetSecondsFromParentStart:z.number().nullish(),DurationSeconds:z.number().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Km=z.object({StartUtc:z.string().nullish(),EndUtc:z.string().nullish(),AllowEarningAfterEnd:z.boolean().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Qm=z.object({AnchorUtc:z.string().nullish(),MaxCycles:z.number().nullish(),PauseBetweenPhasesSec:z.number().nullish(),PauseBetweenCyclesSec:z.number().nullish()}).passthrough();z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();var Hm=z.object({Reset:z.string().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:z.string().nullish(),PauseBetweenCyclesSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough();z.object({SourceType:z.string().nullish(),TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),Outcome:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough();var st=z.object({SourceType:z.string().nullish(),BaseWeight:z.number().nullish(),ScaleWithRollMultiplier:z.boolean().nullish(),TileTypeFilter:z.array(z.string()).nullish(),TileIndexFilter:z.array(z.number()).nullish(),ChanceOutcomeFilter:z.array(z.string()).nullish(),OutcomeFilter:z.array(z.string()).nullish(),Params:z.record(z.string(),z.string()).nullish(),Limits:ye.nullish()}).passthrough(),me=z.object({Mode:z.string().nullish(),IsActive:z.boolean().nullish(),Scheduled:Km.nullish(),Chain:Qm.nullish(),Cyclic:Hm.nullish(),ActivationTriggers:z.array(st).nullish(),Relative:Wm.nullish()}).passthrough();var $m={Flat:"Flat",PerStep:"PerStep",PerStepRate:"PerStepRate",Geometric:"Geometric",Table:"Table",TableAbsolute:"TableAbsolute"},Jm=z.enum(["Flat","PerStep","PerStepRate","Geometric","Table","TableAbsolute"]).catch("Flat"),Zm={Step:"Step",Linear:"Linear",Geometric:"Geometric"},Ym=z.enum(["Step","Linear","Geometric"]).catch("Step"),Xm=z.object({AtStep:z.number().nullish(),Value:z.number().nullish()}).passthrough(),Fe=z.object({Base:z.number().nullish(),Shape:Jm.nullish(),PerStep:z.number().nullish(),PerStepRate:z.number().nullish(),GrowthRate:z.number().nullish(),Points:z.array(Xm).nullish(),Interpolation:Ym.nullish(),TailGrowthRate:z.number().nullish(),MinResult:z.number().nullish(),MaxResult:z.number().nullish()}).passthrough();var ef=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Rewards:H.nullish()}).passthrough(),tf=z.object({SeasonChainID:z.string().nullish(),MinSeasonTier:z.number().nullish(),Multiplier:z.number().nullish()}).passthrough(),Hr=z.object({Bundles:z.array(ef).nullish(),Multipliers:z.array(tf).nullish()}).passthrough();var sf=z.enum(["BoardStageLevel","BoardRank","BoardCyclesCompleted","CharacterLevel","SeasonTier","EventTokenTotalEarned","VirtualCurrencyBalance","PlayerLevel"]).catch("BoardStageLevel"),Vi=z.object({Source:sf.nullish(),SourceKey:z.string().nullish(),Curve:Fe.nullish(),Anchor:z.number().nullish(),IncludeRewards:le.nullish(),ExcludeRewards:le.nullish()}).passthrough(),nl=z.object({ClaimedAt:z.string().nullish(),PremiumTiers:z.array(z.string()).nullish(),Unlocked:z.boolean().nullish()}).passthrough(),Be=z.object({MilestoneID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredProgress:z.number().nullish(),Rewards:H.nullish(),BonusRewards:H.nullish(),SeasonTierRewards:Hr.nullish(),SortOrder:z.number().nullish(),IsFeatured:z.boolean().nullish()}).passthrough(),ni=z.object({Milestones:z.record(z.string(),Be).nullish()}).passthrough();var K=z.object({PresetID:z.string().nullish(),Remove:z.array(z.string()).nullish()}).passthrough();var nf=z.object({TargetCurrencyID:z.string().nullish(),Rate:z.number().nullish(),MaxConvertAmount:z.number().nullish()}).passthrough(),jt=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxBalance:z.number().nullish(),MaxPerGrant:z.number().nullish(),DailyEarnCap:z.number().nullish(),BurnOnEventEnd:z.boolean().nullish(),BurnConversion:nf.nullish()}).passthrough();var rf=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),rl=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:rf.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Q=z.object({ChangedInstances:z.record(z.string(),rl).nullish(),RemovedInstanceIDs:z.array(z.string()).nullish()});var Pe=o=>z.object({Id:z.string(),Success:z.boolean(),Error:z.string().nullish(),Data:o.nullish()}),ft=o=>z.object({ServerTimeUtc:c,Items:z.array(Pe(o)),Resources:M.nullish(),Inventory:Q.nullish()});var of={Active:"Active",Completed:"Completed",Claimed:"Claimed",Expired:"Expired"},ol=z.enum(["Active","Completed","Claimed","Expired"]).catch("Active"),af=z.object({}).passthrough().transform(o=>o),lf=z.object({CycleID:z.string(),InstanceKey:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),CycleStartUtc:c.nullish(),CycleEndUtc:c.nullish(),PointsTotalEarned:_.nullish(),PointsCurrent:_.nullish(),ClaimedPointMilestoneIDs:z.array(z.string()).nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),$r=z.object({QuestID:z.string(),CycleID:z.string().nullish(),ObjectiveID:z.string().nullish(),NewValue:_.nullish(),ObjectiveCompleted:z.boolean().nullish(),Status:ol}),al=z.object({State:af.nullish(),PointsTracks:z.record(z.string(),lf).nullish()}),Jr=z.object({ServerTimeUtc:c,QuestID:z.string(),CycleID:z.string().nullish(),NewStatus:ol.nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Zr=z.object({ServerTimeUtc:c,CycleID:z.string(),MilestoneID:z.string(),PointsTotalEarned:_.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish()}),ll=z.object({ServerTimeUtc:c,CycleID:z.string(),GroupCompletionID:z.string(),GroupID:z.string().nullish(),CompletedGroupQuests:z.number().nullish(),RequiredGroupQuests:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),ul=z.object({MetricID:z.string(),Updates:z.array($r).nullish()}),cl=z.array(Pe(Jr)),pl=z.array(Pe(Zr)),uf={ClientApi:"ClientApi",ServerApi:"ServerApi",SystemEvent:"SystemEvent"},cf=z.enum(["ClientApi","ServerApi","SystemEvent"]).catch("ClientApi"),pf={BlockProgressAndClaim:"BlockProgressAndClaim",BlockClaimOnly:"BlockClaimOnly"},hf=z.enum(["BlockProgressAndClaim","BlockClaimOnly"]).catch("BlockProgressAndClaim"),hl=z.object({ObjectiveID:z.string().nullish(),Source:cf.nullish(),MaxProgressPerCall:z.number().nullish(),MetricID:z.string().nullish(),Triggers:z.array(st).nullish(),TargetValue:z.number().nullish(),AggregationMethod:z.string().nullish()}).passthrough(),Yr=z.object({Milestones:K.nullish(),Linking:K.nullish(),Availability:K.nullish(),Reward:K.nullish(),Objectives:K.nullish()}).passthrough(),df=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),dl=z.object({CycleIDs:z.array(z.string()).nullish(),GroupID:z.string().nullish(),PhaseIDs:z.array(z.string()).nullish(),RequiredQuestIDs:z.array(z.string()).nullish(),PrerequisiteMode:hf.nullish()}).passthrough(),ml=z.object({Schedule:me.nullish(),AccrueProgressWhenLocked:z.boolean().nullish(),Gate:J.nullish(),Limits:ye.nullish()}).passthrough(),fl=z.object({Grant:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),mf=z.object({QuestID:z.string().nullish(),Identity:df.nullish(),Linking:dl.nullish(),Availability:ml.nullish(),Objectives:z.record(z.string(),hl).nullish(),Reward:fl.nullish(),Presets:Yr.nullish()}).passthrough(),ff=z.object({CompletionID:z.string().nullish(),GroupID:z.string().nullish(),RequiredCompletedQuests:z.number().nullish(),Gate:J.nullish(),Reward:H.nullish(),PointsReward:z.number().nullish()}).passthrough(),gf=z.object({PhaseID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Gate:J.nullish(),Milestones:z.record(z.string(),Be).nullish(),Presets:Yr.nullish(),PointsToken:jt.nullish()}).passthrough(),yf=z.object({Milestones:z.record(z.string(),ni).nullish(),Linking:z.record(z.string(),dl).nullish(),Availability:z.record(z.string(),ml).nullish(),Reward:z.record(z.string(),fl).nullish(),Objectives:z.record(z.string(),z.record(z.string(),hl)).nullish()}).passthrough(),Rf=z.object({CycleID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:me.nullish(),Milestones:z.record(z.string(),Be).nullish(),Gate:J.nullish(),PointsToken:jt.nullish(),GroupCompletions:z.record(z.string(),ff).nullish(),Phases:z.record(z.string(),gf).nullish(),Presets:Yr.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),Ni=z.object({Cycles:z.record(z.string(),Rf).nullish(),Quests:z.record(z.string(),mf).nullish(),Presets:yf.nullish()}).passthrough(),pt={GetQuestDefinitions:"GetQuestDefinitions",GetUserQuestState:"GetUserQuestState",RefreshQuestCycles:"RefreshQuestCycles",ClaimQuestReward:"ClaimQuestReward",ClaimMilestoneReward:"ClaimMilestoneReward",AddQuestProgress:"AddQuestProgress",ClaimQuestRewardsBatch:"ClaimQuestRewardsBatch",ClaimMilestoneRewardsBatch:"ClaimMilestoneRewardsBatch",ClaimGroupCompletionReward:"ClaimGroupCompletionReward"};var Cf={ClientAck:"ClientAck",SystemEvent:"SystemEvent",Auto:"Auto",Composite:"Composite"},Sf=z.enum(["ClientAck","SystemEvent","Auto","Composite"]).catch("ClientAck"),xf={Never:"Never",OnRequest:"OnRequest",Always:"Always"},bf=z.enum(["Never","OnRequest","Always"]).catch("Never"),Df={NotStarted:"NotStarted",InProgress:"InProgress",Completed:"Completed",Skipped:"Skipped",Expired:"Expired"},Pf=z.enum(["NotStarted","InProgress","Completed","Skipped","Expired"]).catch("NotStarted"),If={GameLoop:"GameLoop"},vf={Raid:"Raid",Attack:"Attack"},Tf=z.object({Title:z.string().nullish(),TitleKey:z.string().nullish(),Body:z.string().nullish(),BodyKey:z.string().nullish(),AnchorID:z.string().nullish(),HighlightTarget:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),UiHint:z.record(z.string(),z.string()).nullish()}).passthrough(),kf=z.object({Mode:Sf.nullish(),Triggers:z.array(st).nullish(),TargetValue:z.number().nullish(),RequireAllTriggers:z.boolean().nullish()}).passthrough(),zf=z.object({Grant:H.nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),Af=z.object({TileType:z.string().nullish(),TileIndex:z.number().nullish(),ChanceOutcomeID:z.string().nullish(),RandomActionType:z.enum(["Raid","Attack"]).catch("Raid").nullish()}).passthrough(),wf=z.object({Module:z.enum(["GameLoop"]).catch("GameLoop").nullish(),Board:Af.nullish(),MaxUses:z.number().nullish()}).passthrough(),Mf=z.object({Skippable:z.boolean().nullish(),TimeoutSeconds:z.number().nullish()}).passthrough(),Xr=z.object({StepID:z.string().nullish(),Order:z.number().nullish(),Identity:Tf.nullish(),Completion:kf.nullish(),Effects:zf.nullish(),Script:wf.nullish(),Policy:Mf.nullish()}).passthrough(),Of=z.object({DisplayName:z.string().nullish(),DisplayNameKey:z.string().nullish(),Description:z.string().nullish(),DescriptionKey:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),gl=z.object({Schedule:me.nullish(),Gate:J.nullish(),RequiredFlowIDs:z.array(z.string()).nullish(),AutoStart:z.boolean().nullish(),StartTrigger:st.nullish()}).passthrough(),yl=z.object({Skippable:z.boolean().nullish(),SkippableFromOrder:z.number().nullish(),RestartPolicy:bf.nullish(),ExpireAfterSeconds:z.number().nullish(),IsBlocking:z.boolean().nullish(),UnlockFeatures:z.array(z.string()).nullish()}).passthrough(),Rl=z.object({Grant:H.nullish(),AutoClaim:z.boolean().nullish()}).passthrough(),Uf=z.object({Availability:K.nullish(),Policy:K.nullish(),Reward:K.nullish(),Steps:K.nullish()}).passthrough(),Ef=z.object({FlowID:z.string().nullish(),Identity:Of.nullish(),Availability:gl.nullish(),Policy:yl.nullish(),Steps:z.record(z.string(),Xr).nullish(),Reward:Rl.nullish(),Presets:Uf.nullish()}).passthrough(),qf=z.object({BlockingFlowIDs:z.array(z.string()).nullish(),BlockedModules:z.array(z.string()).nullish(),BlockedActions:z.record(z.string(),z.array(z.string())).nullish(),BlockBeforeStart:z.boolean().nullish(),SkipLiftsBlock:z.boolean().nullish()}).passthrough(),Bf=z.object({IsEnabled:z.boolean().nullish(),MaxActiveFlows:z.number().nullish(),Blocking:qf.nullish()}).passthrough(),Lf=z.object({Availability:z.record(z.string(),gl).nullish(),Policy:z.record(z.string(),yl).nullish(),Reward:z.record(z.string(),Rl).nullish(),Steps:z.record(z.string(),z.record(z.string(),Xr)).nullish()}).passthrough(),Cl=z.object({Flows:z.record(z.string(),Ef).nullish(),Settings:Bf.nullish(),Presets:Lf.nullish()}).passthrough(),Gf=z.object({}).passthrough().transform(o=>o),Sl=z.object({FlowID:z.string(),Status:Pf,CurrentStepID:z.string().nullish(),CurrentStep:Xr.nullish(),TotalSteps:z.number(),CompletedSteps:z.number(),CanSkip:z.boolean(),RewardClaimed:z.boolean(),RewardPending:z.boolean(),VariantID:z.string().nullish()}).passthrough(),_i=z.object({State:Gf.nullish(),Flows:z.array(Sl).nullish(),UnlockedFeatures:z.array(z.string()).nullish()}).passthrough(),At=z.object({Flow:Sl.nullish()}).passthrough(),xl=z.object({FlowID:z.string().nullish(),Granted:M.nullish()}).passthrough(),bl=z.array(Pe(At)),Dl=z.object({FlowID:z.string(),StepID:z.string(),Progress:z.number(),Target:z.number(),Completed:z.boolean()}).passthrough(),nt={GetTutorialDefinitions:"GetTutorialDefinitions",GetUserTutorialState:"GetUserTutorialState",StartFlow:"StartFlow",ReportStepShown:"ReportStepShown",CompleteStep:"CompleteStep",CompleteStepsBatch:"CompleteStepsBatch",SkipStep:"SkipStep",SkipFlow:"SkipFlow",ClaimFlowReward:"ClaimFlowReward",ResetFlow:"ResetFlow"};function Wi(o){return Array.isArray(o)?o.filter(e=>e!==null).map(Wi):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).filter(([,e])=>e!==null).map(([e,t])=>[e,Wi(t)])):o}var Ki=class{constructor(e=600,t=()=>Date.now()){this.windowMs=e;this.now=t;}windowMs;now;last=new Map;tryAcquire(e){if(this.windowMs<=0)return true;let t=this.now(),i=this.last.get(e);return i!==void 0&&t-i<this.windowMs?false:(this.last.set(e,t),true)}reset(){this.last.clear();}};var Qi=class{set=new Set;add(e){return this.set.has(e)?false:(this.set.add(e),true)}remove(e){this.set.delete(e);}};function Pl(o){return o===429||o>=500&&o<=599}function Hi(o,e=Math.random){let t=Math.min(500*Math.pow(2,o-1),4e3),i=t*.2*(e()*2-1);return Math.max(50,t+i)}function wt(o){return new Promise(e=>setTimeout(e,o))}var Il=15e3;async function vl(o){try{let t=JSON.parse(await o.text()),i=Number(t?.RetryAfterMs);if(Number.isFinite(i)&&i>0)return i}catch{}let e=Number(o.headers.get("Retry-After"));return Number.isFinite(e)&&e>0?e*1e3:null}function Tl(o,e=Math.random){return o+10+Math.min(250,o*.2)*e()}function kl(o,e=Math.random){let t=o<=1?1500:o===2?4e3:6e3;return t+t*.1*e()}var eo=15,zl=1e3,$i=class{constructor(e=eo,t=()=>Date.now(),i=wt){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]>=zl;)this.starts.shift();if(this.starts.length<this.perSecond){this.starts.push(e);return}await this.wait(zl-(e-this.starts[0])+5);}}};var Ff=/\bCC ([A-Za-z0-9_.:-]+): insufficient balance \(have (-?\d+(?:\.\d+)?), need (\d+(?:\.\d+)?)\)/;function oi(o){if(!o)return null;let e=Ff.exec(o);if(!e)return null;let[,t,i,s]=e;if(!t||i===void 0||s===void 0)return null;let n=new Nt(i),r=new Nt(s),p=r.minus(Nt.max(n,0));return p.lte(0)?null:{currencyID:t,required:r.toNumber(),available:n.toNumber(),missing:p.toNumber(),missingAmount:p.toFixed()}}var Vf=12e3,jf=new Set(["RelatedEntityID"]);function Nf(o,e){if(e===null||typeof e!="object"||Array.isArray(e))return o;let t={};for(let[i,s]of Object.entries(e))jf.has(i)||(t[i]=s);try{return `${o}|${JSON.stringify(t)}`}catch{return o}}var _f=z.object({Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().optional(),QuestProgress:z.array($r).nullish(),TutorialProgress:z.array(Dl).nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish()}).passthrough(),Ji=class{baseUrl;emitter;fetchImpl;debugLogging;throttler;clientPlatform;inflight=new Qi;pacer;inFlightRequests=0;sessionRefreshHandler=null;cryptoTopUpHandler=null;constructor(e){this.baseUrl=e.baseUrl,this.emitter=e.emitter,this.fetchImpl=e.fetchImpl??globalThis.fetch.bind(globalThis),this.debugLogging=e.debugLogging??false,this.throttler=new Ki(e.throttleMs),this.pacer=new $i(e.maxRequestsPerSecond??eo),this.clientPlatform=e.clientPlatform??mt.Unknown;}setSessionRefreshHandler(e){this.sessionRefreshHandler=e;}setCryptoTopUpHandler(e){this.cryptoTopUpHandler=e;}get hasCryptoTopUpHandler(){return this.cryptoTopUpHandler!==null}async post(e,t,i,s={}){let n=s.throttleKey??Nf(e,t);if(!this.throttler.tryAcquire(n))return b("throttled","Throttled");if(!this.inflight.add(n))return b("throttled","Duplicate request skipped");this.raiseBusy();try{let r=`${this.baseUrl}/${e}`,p=JSON.stringify(t),d=s.ticket??null,C=s.silent??!1,j=s.timeoutMs??Vf,ue=s.autoRetry??!0,Ie=!1,ge=!1,Me=0;for(;;){let St;s.keepalive||await this.pacer.take();try{St=await this.doFetch(r,p,d,j,s.keepalive??!1);}catch{if(ue&&Me<3){Me++,await wt(Hi(Me));continue}return this.connectionFailure("Internet Connection Error",C)}let Je=St.status;if(Je>=200&&Je<300){let ne=!ge&&this.cryptoTopUpHandler!==null,De=await this.parseSuccess(St,i,C,e,ne);if(!De.ok&&ne){let ce=oi(De.error);if(ce){if(ge=!0,await this.runTopUp(ce))continue;C||this.emitter.emit("error:global",De.error);}}return De}if(Je===401){if(!Ie&&this.sessionRefreshHandler){Ie=!0;let ne=null;try{ne=await this.sessionRefreshHandler();}catch{ne=null;}if(ne){d=ne;continue}}return this.emitter.emit("auth:unauthorized",void 0),b("unauthorized","Unauthorized")}if(Pl(Je)){let ne=Je===429?await vl(St):null;if(ne!==null&&ne>Il)return this.connectionFailure(`Too many requests \u2014 try again in ${Math.ceil(ne/1e3)} s`,C);if(ue&&Me<3){Me++,await wt(ne!==null?Tl(ne):Je===429?kl(Me):Hi(Me));continue}return this.connectionFailure(`Server temporarily unavailable (HTTP ${Je})`,C)}let yi="";try{yi=await St.text();}catch{}if(Je===409&&/operation in progress/i.test(yi)&&ue&&Me<3){Me++,await wt(Hi(Me));continue}return this.handleWebError(yi,Je,C)}}finally{this.inflight.remove(n),this.lowerBusy();}}async doFetch(e,t,i,s,n=false){let r=new AbortController,p=setTimeout(()=>{r.abort();},s);try{let d={"Content-Type":"application/json","X-IG-Platform":this.clientPlatform};return i&&(d.Authorization=`Bearer ${i}`),await this.fetchImpl(e,{method:"POST",body:t,headers:d,signal:r.signal,...n?{keepalive:!0}:{}})}finally{clearTimeout(p);}}async parseSuccess(e,t,i,s,n=false){let r;try{r=await e.text();}catch{return this.globalError("Failed to read response body",i)}let p;try{p=JSON.parse(r);}catch{return this.globalError("JSON Parse Error",i)}let d=_f.safeParse(p);if(!d.success)return this.globalError("Malformed response envelope",i);if(!d.data.Success){let ge=d.data.Error??"Server returned Success=false",Me=n&&oi(ge);return !i&&!Me&&this.emitter.emit("error:global",ge),b("server",ge)}let C=d.data.StateVersions;C&&Object.keys(C).length>0&&this.emitter.emit("user:stateVersions",{epoch:d.data.StateEpoch??null,versions:C});let j=d.data.QuestProgress;j&&j.length>0&&this.emitter.emit("quest:systemProgress",j);let ue=d.data.TutorialProgress;ue&&ue.length>0&&this.emitter.emit("tutorial:systemProgress",ue);let Ie=t.safeParse(d.data.Data);if(!Ie.success){let ge=t.safeParse(Wi(d.data.Data));ge.success&&(Ie=ge);}if(!Ie.success){let ge=`Validation error (${s}): ${Ie.error.message}`;return this.debugLogging&&console.warn("[HttpTransport]",ge),i||this.emitter.emit("error:global",ge),b("validation",ge)}return a(Ie.data)}handleWebError(e,t,i){let s=`HTTP ${t}`;if(e)try{let r=JSON.parse(e)?.Error;if(t===403&&r==="PLAY_ACCESS_REQUIRED")return this.emitter.emit("playAccess:required",void 0),b("server","PLAY_ACCESS_REQUIRED");s=typeof r=="string"&&r.length>0?`HTTP ${t}: ${r}`:`HTTP ${t}: ${e}`;}catch{s=`HTTP ${t}: ${e}`;}return i||this.emitter.emit("error:global",s),b("server",s)}connectionFailure(e,t){return t||this.emitter.emit("error:connection",e),b("connection",e)}globalError(e,t){return t||this.emitter.emit("error:global",e),b("server",e)}async runTopUp(e){let t=this.cryptoTopUpHandler;if(!t)return false;this.lowerBusy();try{return await t(e)===!0}catch{return false}finally{this.raiseBusy();}}raiseBusy(){this.inFlightRequests++,this.inFlightRequests===1&&this.emitter.emit("transport:busy",true);}lowerBusy(){this.inFlightRequests>0&&(this.inFlightRequests--,this.inFlightRequests===0&&this.emitter.emit("transport:busy",false));}};function ai(o){return (typeof o=="string"?o:o.toISOString()).slice(0,10)}function bi(o){return `${ai(o)}T00:00:00.000Z`}function Al(o){let e=new Date(o);return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()+1)).toISOString()}function wl(o,e){return new Date(o.getTime()+e*6e4).toISOString()}function so(o,e,t,i){let s={vcChanged:false,ccChanged:false,itemsChanged:false,tokensChanged:false};if(!e)return s;o.InventoryV2??={};let n=o.InventoryV2,r=i.toISOString(),p=new Map,d$1=new Map,C=new Map,j=new Map,ue=new Map,Ie=new Map,ge=new Map,Me=new Map,St=e.Grant?.PremiumTiers??[],Je=St.length;for(let ne=0;;ne++){let De,ce;if(ne===0)De=e.Grant?.Standard?.Entries,ce=false;else if(ne-1<Je)De=St[ne-1]?.Resources?.Entries,ce=false;else if(ne===1+Je)De=e.Consume?.Standard?.Entries,ce=true;else break;if(De)for(let oe of De){if(oe.Type==null)continue;let pe=Math.max(0,oe.Amount??0);if(!(pe<=0))switch(oe.Type){case "VirtualCurrency":{if(!oe.CurrencyID)continue;let he=ce?d$1:p;he.set(oe.CurrencyID,(he.get(oe.CurrencyID)??0)+pe);break}case "CryptoCurrency":{if(!oe.CurrencyID)continue;let he=ce?j:C;he.set(oe.CurrencyID,(he.get(oe.CurrencyID)??new Nt(0)).plus(pe));break}case "Item":{if(!oe.ItemID)continue;let he=Kf(t,oe.CatalogID,oe.ItemID),Se=(he?he.IsStackable??true:true)?ce?Ie:ue:ce?Me:ge;Se.set(oe.ItemID,(Se.get(oe.ItemID)??0)+pe);break}case "Purchase":case "RewardedVideoCredit":continue}}}if(s.vcChanged=p.size>0||d$1.size>0,s.vcChanged){n.VirtualCurrencies??={};for(let ne of new Set([...p.keys(),...d$1.keys()])){let De=p.get(ne)??0,ce=d$1.get(ne)??0,oe=De-ce,pe=n.VirtualCurrencies[ne];pe?(pe.Amount+=oe,pe.UpdatedAt=r,pe.Daily&&ai(pe.Daily.PeriodStartUtc)===ai(i)?(pe.Daily.Earned+=De,pe.Daily.Spent+=ce):pe.Daily={PeriodStartUtc:bi(i),Earned:De,Spent:ce}):n.VirtualCurrencies[ne]={Amount:oe,CreatedAt:r,UpdatedAt:r,Daily:{PeriodStartUtc:bi(i),Earned:De,Spent:ce}};}}if(s.ccChanged=C.size>0||j.size>0,s.ccChanged){n.CryptoCurrencies??={};for(let ne of new Set([...C.keys(),...j.keys()])){let De=C.get(ne)??new Nt(0),ce=j.get(ne)??new Nt(0),oe=De.minus(ce),pe=n.CryptoCurrencies[ne];pe?(pe.Amount=new Nt(pe.Amount).plus(oe).toString(),pe.UpdatedAt=r):n.CryptoCurrencies[ne]={Amount:oe.toString(),Frozen:"0",CreatedAt:r,UpdatedAt:r};}}if(s.itemsChanged=ue.size>0||Ie.size>0||ge.size>0||Me.size>0,s.itemsChanged){n.Items??={},n.UnstackableItems??={};let ne=n.UnstackableItems,De=new Set([...ue.keys(),...Ie.keys(),...ge.keys(),...Me.keys()]);for(let ce of De){let oe=(ue.get(ce)??0)-(Ie.get(ce)??0),pe=(ge.get(ce)??0)-(Me.get(ce)??0),he=oe+pe,it=n.Items[ce];it?(oe!==0&&(it.StackableAmount+=oe),pe!==0&&(it.UnstackableAmount+=pe),he!==0&&(it.TotalAmount+=he)):n.Items[ce]={StackableAmount:Math.max(0,oe),UnstackableAmount:Math.max(0,pe),TotalAmount:Math.max(0,he)};}for(let[ce,oe]of Me){if(oe<=0)continue;let pe=Object.values(ne).filter(he=>he.ItemID===ce&&he.EquippedSlot==null&&(he.ExpiresAt==null||new Date(he.ExpiresAt)>i)).sort(Wf).slice(0,oe).map(he=>he.ItemInstanceID);for(let he of pe)delete ne[he];}for(let[ce,oe]of ge){let pe=Qf(t,ce);for(let he=0;he<oe;he++){let it=d();ne[it]={ItemInstanceID:it,ItemID:ce,CatalogID:pe,RemainingUses:1,AcquiredAt:r};}}}o.EventToken??={};let yi=o.EventToken;for(let ne=0;;ne++){let De,ce;if(ne===0)De=e.Grant?.Standard?.EventTokens,ce=false;else if(ne-1<Je)De=St[ne-1]?.Resources?.EventTokens,ce=false;else if(ne===1+Je)De=e.Consume?.Standard?.EventTokens,ce=true;else break;if(!(!De||De.length===0))for(let oe of De){let pe=oe.Address;if(!pe||pe.Type==null)continue;let he=oe.Amount??0;if(he<=0)continue;let it=Hf(yi,pe.Type);if(!it)continue;let Se=it[pe.EntityID];Se||(Se={},it[pe.EntityID]=Se),Se.Balance??={Current:0,TotalEarned:0,TotalSpent:0},Se.Daily??={Date:bi(i),TotalEarned:0},Se.Meta??={};let Ri=oe.Source&&oe.Source.length>0?oe.Source:"CustomAction";ce?(Se.Balance.Current-=he,Se.Balance.TotalSpent+=he):(Se.Balance.Current+=he,Se.Balance.TotalEarned+=he,ai(Se.Daily.Date)!==ai(i)&&(Se.Daily={Date:bi(i),TotalEarned:0}),Se.Daily.TotalEarned+=he,Se.Daily.EarnedBySource??={},Se.Daily.EarnedBySource[Ri]=(Se.Daily.EarnedBySource[Ri]??0)+he,Se.Daily.TriggersBySource??={},Se.Daily.TriggersBySource[Ri]=(Se.Daily.TriggersBySource[Ri]??0)+1,Se.Daily.LastTriggerBySource??={},Se.Daily.LastTriggerBySource[Ri]=r,Se.Meta.JoinedAtUtc||(Se.Meta.JoinedAtUtc=r),Se.Meta.LastEarnedAtUtc=r),s.tokensChanged=true;}}return s}function Wf(o,e){return o.AcquiredAt!==e.AcquiredAt?o.AcquiredAt<e.AcquiredAt?-1:1:o.ItemInstanceID===e.ItemInstanceID?0:o.ItemInstanceID<e.ItemInstanceID?-1:1}function Kf(o,e,t){let i=o?.Catalogs;if(i){if(e){let s=i[e]?.Items?.[t];if(s)return s}for(let s of Object.values(i)){let n=s.Items?.[t];if(n)return n}}}function Qf(o,e){let t=o?.Catalogs;if(t){for(let[i,s]of Object.entries(t))if(s.Items&&e in s.Items)return i}}function Hf(o,e){switch(e){case "TimedEvent":return o.TimedEvent??={};case "Quest":return o.Quest??={};case "Leaderboard":return o.Leaderboard??={};case "CoopEvent":return o.CoopEvent??={};case "Season":return o.Season??={};default:return null}}function Ml(o,e,t){let i={drop:[],restore:{}};if(!t)return i;let s=t.ChangedInstances??{},n=new Set(t.RemovedInstanceIDs??[]),r=new Set;for(let d of Object.values(s))d?.ItemID&&r.add(d.ItemID);for(let d of n){let C=o[d]?.ItemID;C&&r.add(C);}if(r.size===0)return i;let p=d=>n.has(d)||d in s;if(e){for(let[d,C]of Object.entries(e))d in o||p(d)||C&&r.has(C.ItemID)&&i.drop.push(d);for(let[d,C]of Object.entries(o))d in e||p(d)||C&&r.has(C.ItemID)&&(i.restore[d]=C);}return i}function no(o,e){return o===e||o.startsWith(`${e}:`)}var Yi=class o{constructor(e){this.emitter=e;}emitter;currentState={};activeEventsCache=null;get state(){return this.currentState}getCachedActiveEvents(){return this.activeEventsCache}clear(){this.currentState=null,this.emitter.emit("user:anyUpdated",void 0);}static stringifyCryptoBalances(e){let t=e?.CryptoCurrencies;if(t)for(let i of Object.values(t))i&&(typeof i.Amount=="number"&&(i.Amount=String(i.Amount)),typeof i.Frozen=="number"&&(i.Frozen=String(i.Frozen)));}applyUserState(e){o.stringifyCryptoBalances(e.InventoryV2),this.currentState=e,this.emitter.emit("user:stateUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserStateContainers(e,t){if(t.length!==0){this.currentState??={};for(let i of t)this.currentState[i]=e[i];o.stringifyCryptoBalances(this.currentState.InventoryV2),this.emitter.emit("user:stateUpdated",void 0),t.includes("InventoryV2")&&this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}applyInventory(e){o.stringifyCryptoBalances(e),this.currentState??={},this.currentState.InventoryV2=e,this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyVirtualCurrency(e){this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.VirtualCurrencies=e,this.emitter.emit("user:virtualCurrencyUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyResourceOperation(e,t,i=new Date){if(!this.currentState)return;let s=so(this.currentState,e,t,i);this.emitResourceChanges(s,false);}applyResourcesWithDelta(e,t,i,s=new Date){if(!this.currentState)return;let n=this.currentState,r={...n.InventoryV2?.UnstackableItems??{}},p=so(n,e,i,s),d=Ml(r,n.InventoryV2?.UnstackableItems,t),C=Object.entries(t?.ChangedInstances??{}),j=t?.RemovedInstanceIDs??[],ue=d.drop.length>0||Object.keys(d.restore).length>0||C.length>0||j.length>0;if(ue){n.InventoryV2??={},n.InventoryV2.UnstackableItems??={};let Ie=n.InventoryV2.UnstackableItems;for(let ge of d.drop)delete Ie[ge];for(let[ge,Me]of Object.entries(d.restore))Ie[ge]=Me;for(let[ge,Me]of C)Ie[ge]=Me;for(let ge of j)delete Ie[ge];}this.emitResourceChanges(p,ue);}emitResourceChanges(e,t){let i=e.vcChanged||e.ccChanged||e.itemsChanged||t;e.vcChanged&&this.emitter.emit("user:virtualCurrencyUpdated",void 0),i&&this.emitter.emit("user:inventoryUpdated",void 0),e.tokensChanged&&this.emitter.emit("user:eventTokenUpdated",void 0),(i||e.tokensChanged)&&this.emitter.emit("user:anyUpdated",void 0);}patchCryptoCurrencyDelta(e,t,i,s){if(!e||!this.currentState)return;this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies??={};let n=this.currentState.InventoryV2.CryptoCurrencies,r=t instanceof Nt?t:new Nt(t),p=s===void 0?new Nt(0):s instanceof Nt?s:new Nt(s),d=i??new Date().toISOString(),C=n[e];C?(C.Amount=new Nt(C.Amount).plus(r).toString(),p.isZero()||(C.Frozen=new Nt(C.Frozen??0).plus(p).toString()),C.UpdatedAt=d):n[e]={Amount:r.toString(),Frozen:p.toString(),CreatedAt:d,UpdatedAt:d},this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyStore(e){this.currentState??={},this.currentState.Store=e??{},this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchStorePurchase(e,t,i){if(!e||t<1||!this.currentState)return;this.currentState.Store??={},this.currentState.Store.Purchases??={};let s=this.currentState.Store.Purchases,n=s[e];n||(n={OfferID:e,TotalPurchases:0,DailyPurchases:0,DailyResetUtc:"",LastPurchasedAt:""},s[e]=n),n.TotalPurchases+=t,n.LastPurchasedAt=i,i>=n.DailyResetUtc?(n.DailyPurchases=t,n.DailyResetUtc=Al(i)):n.DailyPurchases+=t,this.emitter.emit("user:storeUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyLootboxPityTriggers(e,t,i){if(!e||i<=0)return;this.currentState??={};let s=this.currentState.Lootbox??={};if(s.Pity??={},t){let n=new Date().toISOString();for(let r of t)r.RuleID&&(s.Pity[`${e}:${r.RuleID}`]={OpensSinceLastTrigger:0,LastTriggeredAtUtc:n});}this.emitter.emit("user:lootboxUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReward(e){this.currentState??={},this.currentState.Reward=e??{},this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchDailyCalendarState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.DailyCalendars??={},this.currentState.Reward.DailyCalendars[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchIdleAccrualState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.IdleAccruals??={},this.currentState.Reward.IdleAccruals[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchComebackState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Comebacks??={},this.currentState.Reward.Comebacks[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchClaimRewardState(e,t){!e||!t||(this.currentState??={},this.currentState.Reward??={},this.currentState.Reward.Claims??={},this.currentState.Reward.Claims[e]=t,this.emitter.emit("user:rewardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyQuest(e){this.currentState??={},this.currentState.Quest=e??{},this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestStatus(e,t,i){if(!e)return;this.currentState??={},this.currentState.Quest??={};let s=this.currentState.Quest;if(t){s.Cycles??={};let n=s.Cycles[t];if(!n)return;n.Quests??={};let r=n.Quests[e]??={QuestID:e,Status:i};r.Status=i,i==="Claimed"&&(r.ClaimedAtUtc??=new Date().toISOString());}else {s.PermanentQuests??={};let n=s.PermanentQuests[e]??={QuestID:e,Status:i};n.Status=i,i==="Claimed"&&(n.ClaimedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMilestoneClaimed(e,t){if(!e||!t)return;let i=this.getQuestPointsProgress(e);i&&(i.Milestone??={},this.markMilestoneClaimed(i.Milestone,t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchQuestPointsTracks(e){if(!e)return;this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.Quest??={};let t=this.currentState.EventToken.Quest;for(let i of Object.values(e)){if(!i.CycleID)continue;let s=i.InstanceKey?`${i.CycleID}:${i.InstanceKey}`:i.CycleID,n=t[s]??={};n.Balance??={Current:0,TotalEarned:0,TotalSpent:0},n.Balance.Current=i.PointsCurrent??0,n.Balance.TotalEarned=i.PointsTotalEarned??0,n.Milestone??={};for(let r of i.ClaimedPointMilestoneIDs??[])this.markMilestoneClaimed(n.Milestone,r);}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchGroupCompletionClaimed(e,t){if(!e||!t)return;this.currentState??={},this.currentState.Quest??={},this.currentState.Quest.Cycles??={};let i=this.currentState.Quest.Cycles[e];i&&(i.ClaimedGroupCompletionIDs??=[],i.ClaimedGroupCompletionIDs.includes(t)||i.ClaimedGroupCompletionIDs.push(t),this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyTutorial(e){this.currentState??={},this.currentState.Tutorial=e??{},this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialFlow(e){if(!e?.FlowID)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};let i=t.Flows[e.FlowID]??={FlowID:e.FlowID};i.Status=e.Status,i.CurrentStepID=e.CurrentStepID??null,i.RewardClaimed=e.RewardClaimed,e.VariantID!==void 0&&(i.VariantID=e.VariantID),this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchTutorialProgress(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Tutorial??={};let t=this.currentState.Tutorial;t.Flows??={};for(let i of e){if(!i.FlowID||!i.StepID)continue;let s=t.Flows[i.FlowID]??={FlowID:i.FlowID,Status:"InProgress"};s.Steps??={};let n=s.Steps[i.StepID]??={StepID:i.StepID};n.Progress=i.Progress,i.Completed&&(n.CompletedAtUtc??=new Date().toISOString(),s.CurrentStepID===i.StepID&&(s.CurrentStepID=null));}this.emitter.emit("user:tutorialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchQuestProgressUpdates(e){if(!e||e.length===0)return;this.currentState??={},this.currentState.Quest??={};let t=this.currentState.Quest;for(let i of e){if(!i.QuestID)continue;let s;if(!i.CycleID)t.PermanentQuests??={},s=t.PermanentQuests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};else {t.Cycles??={};let n=t.Cycles[i.CycleID];if(!n)continue;n.Quests??={},s=n.Quests[i.QuestID]??={QuestID:i.QuestID,Status:i.Status};}if(s.Status=i.Status,i.ObjectiveID){s.Objectives??={};let n=s.Objectives[i.ObjectiveID]??={ObjectiveID:i.ObjectiveID,CurrentValue:0,Completed:false};n.CurrentValue=i.NewValue??0,i.ObjectiveCompleted&&(n.Completed=true,n.CompletedAtUtc??=new Date().toISOString());}i.Status==="Completed"&&(s.CompletedAtUtc??=new Date().toISOString());}this.emitter.emit("user:questUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getQuestPointsProgress(e){if(!e)return null;let t=this.currentState?.EventToken?.Quest;if(!t)return null;for(let[i,s]of Object.entries(t))if(no(i,e)&&s)return s;return null}applyActiveEvents(e){this.activeEventsCache=e??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserLteState(e){e&&(this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent=e.Tokens??{},this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchTimedEventMilestoneClaimed(e,t,i,s){if(!(!t||!i)){this.currentState??={},this.currentState.EventToken??={},this.currentState.EventToken.TimedEvent??={};for(let[n,r]of Object.entries(this.currentState.EventToken.TimedEvent))r&&((s?n!==s:!no(n,t))||this.markMilestoneClaimed(r.Milestone??(r.Milestone={}),i));this.patchActiveEventMilestoneClaimed(e,t,i,s),this.emitter.emit("user:timedEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}}patchActiveEventMilestoneClaimed(e,t,i,s){let n=this.activeEventsCache?.ActiveEvents;if(n)for(let r of n)r.Type!==e||r.TimedEventID!==t||s&&r.TokenEntityID&&r.TokenEntityID!==s||(r.Progress??={},this.markMilestoneClaimed(r.Progress.Milestone??(r.Progress.Milestone={}),i));}markMilestoneClaimed(e,t){e.Claims??={};let i=e.Claims[t]??={};i.ClaimedAt??=new Date().toISOString(),i.Unlocked=false;}patchLeaderboardMyProgress(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.CurrentScore=t.CurrentScore??0,i.LastKnownRank=t.LastKnownRank??0,i.ScoreEarnedThisCycle=t.ScoreEarnedThisCycle??0,i.UnclaimedRewardCycleVersion=t.HasUnclaimedReward?Math.max(1,i.UnclaimedRewardCycleVersion??0):0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardScoreSubmitted(e,t,i,s){if(!e)return;let n=this.ensureLeaderboardProgress(e);(n.ScoreCycleVersion??0)<s&&(n.ScoreEarnedThisCycle=0,n.ClaimedMilestoneIDs=[],n.BracketID=null),n.CurrentScore=t,n.ScoreEarnedThisCycle=(n.ScoreEarnedThisCycle??0)+i,n.ScoreCycleVersion=s,n.LastScoreSubmitUtc=new Date().toISOString(),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchLeaderboardCycleRewardClaimed(e){if(!e)return;let t=this.currentState?.Leaderboard?.ProgressByCycle?.[e];t&&(t.UnclaimedRewardCycleVersion=0,this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchLeaderboardMilestoneClaimed(e,t){if(!e||!t)return;let i=this.ensureLeaderboardProgress(e);i.ClaimedMilestoneIDs??=[],i.ClaimedMilestoneIDs.includes(t)||i.ClaimedMilestoneIDs.push(t),this.emitter.emit("user:leaderboardUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureLeaderboardProgress(e){this.currentState??={},this.currentState.Leaderboard??={},this.currentState.Leaderboard.ProgressByCycle??={};let t=this.currentState.Leaderboard.ProgressByCycle,i=t[e];return i||(i={CurrentScore:0,ScoreEarnedThisCycle:0,ScoreCycleVersion:0,UnclaimedRewardCycleVersion:0,LastKnownRank:0},t[e]=i),i}applySeasonsState(e){this.currentState??={},this.currentState.Season=e??{},this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonState(e,t){!e||!t||(this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={},this.currentState.Season.States[e]=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSeasonCurrentTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.CurrentTier=t,this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSeasonClaimedTier(e,t){if(!e)return;let i=this.ensureSeasonState(e);i.ClaimedTierRewards??=[],i.ClaimedTierRewards.includes(t)||i.ClaimedTierRewards.push(t),this.emitter.emit("user:seasonUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}ensureSeasonState(e){this.currentState??={},this.currentState.Season??={},this.currentState.Season.States??={};let t=this.currentState.Season.States,i=t[e];return i||(i={SeasonChainID:e},t[e]=i),i}applyPremium(e){this.currentState??={},this.currentState.Premium=e??{},this.emitter.emit("user:premiumUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchEquippedItemLevel(e,t){if(!e)return;let i=this.currentState?.Character?.Characters;if(!i)return;let s=false;for(let n of Object.values(i))for(let r of Object.values(n.Equipment??{}))r?.ItemInstanceID===e&&(r.Level=t,s=true);s&&(this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCharacter(e){this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters=e??{},this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacter(e,t){if(!e)return;this.currentState??={},this.currentState.Character??={},this.currentState.Character.Characters??={};let i=this.currentState.Character.Characters,s=i[e];s||(s={CharacterID:e},i[e]=s),t(s),this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCharacterEquipment(e,t,i){if(!e||!t)return;let s=this.currentState?.Character?.Characters?.[e];s&&(s.Equipment??={},i===null?delete s.Equipment[t]:s.Equipment[t]=i,this.emitter.emit("user:characterUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyInventoryDelta(e){if(!e)return;this.currentState??={},this.currentState.InventoryV2??={},this.currentState.InventoryV2.UnstackableItems??={};let t=this.currentState.InventoryV2.UnstackableItems,i=false;for(let[s,n]of Object.entries(e.ChangedInstances??{}))t[s]=n,i=true;for(let s of e.RemovedInstanceIDs??[])s in t&&(delete t[s],i=true);i&&(this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyMatch(e){this.currentState??={},this.currentState.Match=e??{},this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchMatchStrategy(e){e&&(this.currentState??={},this.currentState.Match??={},this.currentState.Match.PvPBattleStrategy=e,this.emitter.emit("user:matchUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applyCollection(e){this.currentState??={},this.currentState.Collection=e??{},this.emitter.emit("user:collectionUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCoopEvent(e){this.currentState??={},this.currentState.CoopEvent=e??{MyObjectIndex:-1},this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchCoopEventActiveGroup(e,t,i){this.currentState??={};let s=this.currentState.CoopEvent??={MyObjectIndex:-1};s.ActiveGroupID=e,s.ActiveCoopEventID=t,s.MyObjectIndex=i,this.emitter.emit("user:coopEventUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyDealOffer(e){this.currentState??={},this.currentState.DealOffer=e??{},this.emitter.emit("user:dealOfferUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyReferral(e){this.currentState??={},this.currentState.Referral=e??{},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchReferralSubscription(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.SubscribedToUserID=e,this.currentState.Referral.PendingActivationReward=false,this.currentState.Referral.UpdatedAt=new Date().toISOString(),this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchReferralInviteRewardClaimed(e){e&&(this.currentState??={},this.currentState.Referral??={},this.currentState.Referral.InviteRewardStates??={},this.currentState.Referral.InviteRewardStates[e]={RewardID:e,IsClaimed:true,ClaimedAt:new Date().toISOString()},this.emitter.emit("user:referralUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}applySocialFriendsList(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.Accepted=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialIncomingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.IncomingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialOutgoingRequests(e){this.currentState??={},this.currentState.Social??={},this.currentState.Social.OutgoingRequests=(e??[]).map(t=>t.UserID),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialInboxSeenAt(e){e&&(this.currentState??={},this.currentState.Social??={},this.currentState.Social.InboxSeenAt=e,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchSocialAddOutgoingRequest(e){if(!e)return;let t=this.ensureSocial();t.OutgoingRequests??=[],t.OutgoingRequests.includes(e)||(t.OutgoingRequests.push(e),t.OutgoingCount=(t.OutgoingCount??0)+1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialAcceptFriend(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.Accepted??=[],t.Accepted.includes(e)||t.Accepted.push(e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),t.FriendsCount=(t.FriendsCount??0)+1,this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveIncomingRequest(e){if(!e)return;let t=this.ensureSocial();t.IncomingRequests=(t.IncomingRequests??[]).filter(i=>i!==e),t.IncomingCount=Math.max(0,(t.IncomingCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchSocialRemoveFriend(e){if(!e)return;let t=this.ensureSocial();t.Accepted=(t.Accepted??[]).filter(i=>i!==e),t.FriendsCount=Math.max(0,(t.FriendsCount??0)-1),this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applySocialCounters(e){if(!e)return;let t=this.ensureSocial(),i=false;typeof e.FriendsCount=="number"&&(i||=t.FriendsCount!==e.FriendsCount,t.FriendsCount=e.FriendsCount),typeof e.IncomingRequestsCount=="number"&&(i||=t.IncomingCount!==e.IncomingRequestsCount,t.IncomingCount=e.IncomingRequestsCount),typeof e.OutgoingRequestsCount=="number"&&(i||=t.OutgoingCount!==e.OutgoingRequestsCount,t.OutgoingCount=e.OutgoingRequestsCount),i&&(this.emitter.emit("user:socialUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureSocial(){return this.currentState??={},this.currentState.Social??={},this.currentState.Social}applyTimedBoost(e){this.currentState??={},this.currentState.TimedBoost=e??{},this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchActiveTimedBoost(e,t){this.currentState??={},this.currentState.TimedBoost??={},this.currentState.TimedBoost.Active??={};let i=this.currentState.TimedBoost.Active;if(t==="Replace"||t==="KeepBest")for(let s of Object.keys(i)){let n=i[s];n&&n.BoostID===e.BoostID&&s!==e.InstanceID&&delete i[s];}i[e.InstanceID]=e,this.emitter.emit("user:timedBoostUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyUserCustomData(e){this.currentState??={},this.currentState.CustomData??={};let t=this.currentState.CustomData;t.Version=e.Version??0,t.Private=e.Private??{},t.Public=e.Public??{},t.ReadOnly=e.ReadOnly??{},this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchUserCustomDataKey(e,t,i,s,n){if(!t)return;this.currentState??={},this.currentState.CustomData??={};let r=this.currentState.CustomData,p={Value:i,UpdatedAt:new Date().toISOString(),Version:s,LastWriter:"Client",ExpiresAt:n??null};if(e==="Private")r.Private??={},r.Private[t]=p;else if(e==="Public")r.Public??={},r.Public[t]=p;else return;r.Version=(r.Version??0)+1,this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}removeUserCustomDataKey(e,t){if(!t||!this.currentState?.CustomData)return;let i=this.currentState.CustomData;if(e==="Private")i.Private&&delete i.Private[t];else if(e==="Public")i.Public&&delete i.Public[t];else return;this.emitter.emit("user:customDataUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBoardState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyCommunityChestUserState(e){this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.CommunityChest=e??{},this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardState(e){let t=this.ensureBoard();e(t),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardBuilding(e,t){if(e<0)return;let i=this.ensureBoard();i.BuildingStates??=[];let s=i.BuildingStates.find(n=>n.SlotIndex===e);s||(s={SlotIndex:e},i.BuildingStates.push(s)),t(s),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}patchBoardPendingRaidLayout(e,t){let s=this.ensureBoard().Pending;s&&(e&&(s.RaidLayout=e),t>=0&&(s.OpenedIndices??=[],s.OpenedIndices.includes(t)||s.OpenedIndices.push(t)),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}patchBoardSpecialPending(e){let i=this.ensureBoard().Pending;!i||i.Type.toUpperCase()!=="SPECIAL"||(i.Special??={},e(i.Special),this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}clearBoardPending(){let e=this.currentState?.GameLoop?.Board;!e||!e.Pending||(e.Pending=null,this.emitter.emit("user:gameLoopUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0));}ensureBoard(){return this.currentState??={},this.currentState.GameLoop??={},this.currentState.GameLoop.Board??={},this.currentState.GameLoop.Board}applyBlockchainState(e,t){this.currentState??={},this.currentState.Blockchain=e??{},t&&(this.currentState.InventoryV2??={},this.currentState.InventoryV2.CryptoCurrencies=t),this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyBlockchainStateDelta(e){if(!e)return;this.currentState??={};for(let s of Object.values(e.CryptoBalances??{}))s?.CurrencyID&&this.patchCryptoCurrencyDelta(s.CurrencyID,s.AmountDelta,s.UpdatedAt,s.FrozenDelta);let t=new Set(e.PendingRemovedIDs??[]),i=e.PendingAdded;if(t.size>0||i){let s=this.currentState.Blockchain??={},n=s.PendingWithdrawals??[];t.size>0&&(n=n.filter(r=>!r.TitleTransactionID||!t.has(r.TitleTransactionID))),i&&!n.some(r=>r.TitleTransactionID===i.TitleTransactionID)&&(n=[...n,i]),s.PendingWithdrawals=n;}this.emitter.emit("user:blockchainUpdated",void 0),this.emitter.emit("user:inventoryUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}applyMarketplaceState(e){this.currentState??={},this.currentState.Marketplace=e??{},this.emitter.emit("user:marketplaceUpdated",void 0),this.emitter.emit("user:anyUpdated",void 0);}getVirtualCurrencyAmount(e){return this.currentState?.InventoryV2?.VirtualCurrencies?.[e]?.Amount??0}getCryptoCurrencyAmount(e){return this.currentState?.InventoryV2?.CryptoCurrencies?.[e]?.Amount??"0"}};var Xi=class{config=null;sections=new Map;itemDefs;currencyDefs;get titlePublicConfiguration(){return this.config}sectionSink=null;patchSection(e,t){this.sections.set(e,t),this.sectionSink?.(e,t);}restoreSections(e){for(let[t,i]of Object.entries(e))this.sections.has(t)||this.sections.set(t,i);}clearSections(){this.sections.clear();}setSectionSink(e){this.sectionSink=e;}getSection(e){let t=this.sections.get(e);if(t!==void 0)return t;let i=this.config?.[e];return i??void 0}applyTitlePublicConfiguration(e){this.config=e&&typeof e=="object"?e:null;}get itemDefinitions(){return this.itemDefs??this.config?.Item??void 0}applyItemDefinitions(e){this.itemDefs=e;}get currencyDefinitions(){return this.currencyDefs??this.config?.Currency??void 0}applyCurrencyDefinitions(e){this.currencyDefs=e;}};var es=class{user;config;constructor(e){this.user=new Yi(e),this.config=new Xi;}reset(){this.user.clear(),this.config.applyTitlePublicConfiguration(null);}};function $f(o){return o}var Jf=0,Zf=1500,Yf=3,is=class{constructor(e,t,i=null,s="",n="auto"){this.emitter=e;this.config=t;this.storage=i;this.titleId=s;this.loginMode=n;e.on("auth:loggedOut",()=>{this.clear(),this.loginFailures.clear();});}emitter;config;storage;titleId;loginMode;entries=new Map;inflight=new Map;generation=new Map;views=new Map;rules=new Map;ruleInflight=new Map;state=null;loginBindings=new Map;used=new Map;usedLoaded=null;session=0;loginFailures=new Map;pending=new Set;waiters=[];batchTimer=null;batchRunning=null;attachState(e){this.state=e,e.onStateChanged(t=>this.onStateChanged(t));}configSection(e,t){if(!t?.forceRefresh)return this.config.getSection(e)??void 0}defineStateRule(e,t){this.rules.set(e,t);}isStateFresh(e,t){return this.state?.isStateFresh(e,t)??false}invalidateState(e){this.state?.forgetState(e);}async ensureState(e,t){if(!this.state)return a(void 0);let i=Date.now(),s=[],n=[];for(let d of new Set(e)){let C=this.rules.get(d);if(C&&(t?.force||C.needsServer(i))){s.push(this.runRule(d,C));continue}(t?.force||!this.state.isStateFresh(d,t?.maxAgeMs))&&n.push(d);}let p=(await Promise.all([...s,n.length>0?this.queueSlice(n):Promise.resolve(a(void 0))])).find(d=>!d.ok);return p&&!p.ok?p:a(void 0)}runRule(e,t){let i=this.ruleInflight.get(e);if(i)return i;let s=t.refresh().finally(()=>this.ruleInflight.delete(e));return this.ruleInflight.set(e,s),s}queueSlice(e){for(let i of e)this.pending.add(i);let t=new Promise(i=>this.waiters.push(i));return this.batchTimer??=setTimeout(()=>{this.flushSlices();},Jf),t}async flushSlices(){for(this.batchTimer=null;this.batchRunning;)await this.batchRunning;if(this.pending.size===0)return;let e=[...this.pending],t=this.waiters;this.pending=new Set,this.waiters=[];let i;this.batchRunning=new Promise(s=>i=s);try{let s=this.state?await this.state.readStateSlice(e):a(void 0),n=s.ok?a(void 0):s;for(let r of t)r(n);}finally{this.batchRunning=null,i();}}async read(e,t,i){this.register(e);let s=ts(e,i?.args);if(this.noteUsed(e,i?.args,i?.loginParams),!i?.forceRefresh){let C=this.fresh(s,i?.maxAgeMs);if(C)return a(C.data);let j=this.loginFailures.get(s);if(j)return this.loginFailures.delete(s),j;let ue=this.inflight.get(s);if(ue)return ue}let n=this.generation.get(s)??0,r=Date.now(),d=t().then(C=>{if(!C.ok)return C;let j=Date.now();if((this.generation.get(s)??0)===n)return this.entries.set(s,{data:C.data,storedAt:j,expiresAt:ro(e,C.data,j)}),C;let ue=this.entries.get(s);if(ue&&ue.storedAt>=r)return C;let Ie=ro(e,C.data,j);return this.entries.set(s,{data:C.data,storedAt:j,expiresAt:Math.min(Ie??1/0,j+Zf)}),C}).finally(()=>{this.inflight.get(s)===d&&this.inflight.delete(s);});return this.inflight.set(s,d),d}bindLoginView(e,t){e.login&&(this.register(e),this.loginBindings.set(e.login,{view:e,schema:t.schema,apply:t.apply}));}async loginViews(){let e=this.loginMode;return e==="none"?[]:e==="all"?[{Name:"*"}]:e!=="auto"?e.map(t=>typeof t=="string"?{Name:t}:t):(await this.loadUsed(),[...this.used.values()].filter(t=>this.loginBindings.has(t.Name)).map(({n:t,...i})=>i))}acceptLoginViews(e){for(let t of e??[]){let i=this.loginBindings.get(t.Name);if(!i)continue;let s=t.Key?t.Key:void 0,n=ts(i.view,s);if(!t.Success){this.loginFailures.set(n,b("server",t.Error??"View failed."));continue}let r=i.schema.safeParse(t.Data);r.success&&(this.loginFailures.delete(n),i.apply(r.data,s),this.put(i.view,r.data,s));}}noteUsed(e,t,i){if(!e.login||this.loginMode!=="auto")return;let s=e.login;this.loadUsed().then(()=>{let n=Ol({Name:s,Key:t});this.used.get(n)?.n!==this.session&&(this.used.set(n,{Name:s,Key:t??"",...i,n:this.session}),this.writeUsed());});}loadUsed(){return this.usedLoaded??=(async()=>{let e=await this.readUsed();this.session=e.session+1;for(let t of e.views)this.session-t.n>Yf||this.used.set(Ol(t),t);})()}usedKey(){return `idos:views:${this.titleId}`}async readUsed(){let e={session:0,views:[]};if(!this.storage)return e;try{let t=await this.storage.get(this.usedKey()),i=t?JSON.parse(t):null;return !i||typeof i.s!="number"||!Array.isArray(i.v)?e:{session:i.s,views:i.v.filter(s=>s&&typeof s.Name=="string"&&typeof s.n=="number")}}catch{return e}}async writeUsed(){if(this.storage)try{await this.storage.set(this.usedKey(),JSON.stringify({s:this.session,v:[...this.used.values()]}));}catch{}}peek(e,t){return this.fresh(ts(e,t))?.data}put(e,t,i){this.register(e);let s=ts(e,i);this.bump(s);let n=Date.now();this.entries.set(s,{data:t,storedAt:n,expiresAt:ro(e,t,n)});}invalidate(e,t){let i=typeof e=="string"?e:e.key;if(t!==void 0){this.drop(`${i}|${t}`);return}for(let s of [...this.entries.keys(),...this.inflight.keys()])(s===i||s.startsWith(`${i}|`))&&this.drop(s);this.drop(i);}clear(){for(let e of [...this.entries.keys(),...this.inflight.keys()])this.drop(e);}describe(){let e=Date.now();return [...this.entries.entries()].map(([t,i])=>({key:t,ageMs:e-i.storedAt,expiresInMs:i.expiresAt===null?null:i.expiresAt-e}))}fresh(e,t){let i=this.entries.get(e);if(!i)return;let s=Date.now();if(!(i.expiresAt!==null&&s>=i.expiresAt)&&!(t!==void 0&&s-i.storedAt>t))return i}drop(e){this.entries.delete(e),this.inflight.delete(e),this.bump(e);}bump(e){this.generation.set(e,(this.generation.get(e)??0)+1);}register(e){if(!this.views.has(e.key)){this.views.set(e.key,e);for(let t of e.invalidateOn??[])this.emitter.on(t,()=>this.invalidate(e));}}onStateChanged(e){let t=new Set(e);for(let i of this.views.values())i.dependsOn?.some(s=>t.has(s))&&this.invalidate(i);}};function ts(o,e){return e===void 0?o.key:`${o.key}|${e}`}function Ol(o){return o.Key?`${o.Name}|${o.Key}`:o.Name}function ro(o,e,t){let i=o.expiresAt?.(e)??null,s=o.ttlMs!==void 0?t+o.ttlMs:null;return i!==null&&s!==null?Math.min(i,s):i??s}var ss=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 Xf(e)?e:Ae.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 Xf(o){return o!==null&&Object.values(Ae).includes(o)}var eg=8,tg=100,ig=/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i,Ul=["GameLoop"];function sg(o){return ["REFRESH_TOKEN_INVALID","REFRESH_TOKEN_EXPIRED","REFRESH_TOKEN_REVOKED","REFRESH_TOKEN_REUSED","REFRESH_TOKEN_MISSING","BANNED"].includes(o)}var ns=class{constructor(e){this.ctx=e;}ctx;authContext=null;refreshing=false;rememberSession=true;sessionAuthType=Ae.None;sessionEmail="";sessionPassword="";sessionRefreshToken="";pendingRegistration=null;playAccessStatus=null;get playAccess(){return this.playAccessStatus}setPlayAccess(e){this.playAccessStatus=e,this.ctx.emitter.emit("playAccess:changed",e);}async getAuthOptions(){return this.ctx.api.authentication.getAuthOptions(this.baseRequest())}async linkWallet(e,t,i){let s=this.authContext;if(!s)return c$1;let n=this.baseRequest();n.UserID=s.userID,n.ClientSessionTicket=s.clientSessionTicket,n.WalletAddress=e,n.NetworkID=t,i&&(n.WalletSignature=i);let r=await this.ctx.api.authentication.linkWallet(n);return r.ok&&r.data.PlayAccess&&this.setPlayAccess(r.data.PlayAccess),r}async unlinkWallet(e){let t=this.authContext;if(!t)return c$1;let i=this.baseRequest();i.UserID=t.userID,i.ClientSessionTicket=t.clientSessionTicket,i.NetworkID=e;let s=await this.ctx.api.authentication.unlinkWallet(i);return s.ok&&s.data.PlayAccess&&this.setPlayAccess(s.data.PlayAccess),s}get context(){return this.authContext}get isLoggedIn(){return this.authContext!==null&&this.authContext.userID.length>0&&this.authContext.clientSessionTicket.length>0}get lastAuthType(){return this.ctx.authStore.lastAuthType}setRememberSession(e){this.rememberSession=e;}get remembersSession(){return this.rememberSession}baseRequest(){return {BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),Attribution:this.ctx.acquisition.buildForLogin(this.ctx.settings.appVersion)}}async loginWithDeviceID(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.baseRequest();e.DeviceID=this.ctx.platform.getDeviceID(),e.Device=this.ctx.platform.getDeviceModel(),e.Platform=this.ctx.platform.getPlatform();let t=await this.ctx.api.authentication.loginWithDeviceID(e);return t.ok?(this.applyAuthContext(t.data),this.fetchAndApplyClientState(Ae.Device)):t}async loginWithTelegram(){this.ctx.emitter.emit("auth:requestSent",void 0);let e=this.ctx.platform.getTelegramInitDataRaw();if(!e)return b("client","Telegram initData is not available.");let t=this.baseRequest();t.TelegramInitData=e;let i=await this.ctx.api.authentication.loginWithTelegram(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(Ae.Telegram)):i}async loginWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t;let s=await this.ctx.api.authentication.loginWithEmail(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(Ae.Email);return n.ok&&this.keepEmailCredentials(e,t),n}async registerWithEmail(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.Password=t,i.DeviceID=this.ctx.platform.getDeviceID(),i.Device=this.ctx.platform.getDeviceModel(),i.Platform=this.ctx.platform.getPlatform();let s=await this.ctx.api.authentication.registerWithEmail(i);return s.ok?(this.pendingRegistration={email:e,password:t},a({codeTtlMinutes:s.data.CodeTtlMinutes??0,resendCooldownSeconds:s.data.ResendCooldownSeconds??0})):s}async confirmEmailRegistration(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.Email=e,i.VerificationCode=t;let s=await this.ctx.api.authentication.confirmEmailRegistration(i);if(!s.ok)return s;this.applyAuthContext(s.data);let n=await this.fetchAndApplyClientState(Ae.Email);return n.ok&&this.pendingRegistration?.email===e&&this.keepEmailCredentials(e,this.pendingRegistration.password),this.pendingRegistration=null,n}async resendVerificationCode(e){let t=this.baseRequest();t.Email=e;let i=await this.ctx.api.authentication.resendVerificationCode(t);return i.ok?a(void 0):i}async loginWithGoogle(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.GoogleIDToken=e;let i=await this.ctx.api.authentication.loginWithGoogle(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(Ae.Google)):i}async loginWithApple(e,t){if(!e?.trim())return b("client","Apple identity token is required.");this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();i.AppleIDToken=e,t?.nonce&&(i.AuthNonce=t.nonce),t?.name?.trim()&&(i.Username=t.name.trim());let s=await this.ctx.api.authentication.loginWithApple(i);return s.ok?(this.applyAuthContext(s.data),this.fetchAndApplyClientState(Ae.Apple)):s}async requestWalletChallenge(e,t){this.ctx.emitter.emit("auth:requestSent",void 0);let i=this.baseRequest();return i.WalletAddress=e,i.NetworkID=t,this.ctx.api.authentication.requestWalletChallenge(i)}async loginWithWallet(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();s.WalletAddress=e,s.NetworkID=t,s.WalletSignature=i,s.Platform=this.ctx.platform.getPlatform(),s.Device=this.ctx.platform.getDeviceModel(),s.DeviceID=this.ctx.platform.getDeviceID();let n=await this.ctx.api.authentication.loginWithWallet(s);return n.ok?(this.applyAuthContext(n.data),this.fetchAndApplyClientState(Ae.Wallet)):n}async loginWithSsoCode(e){if(!e)return b("client","SSO code is null or empty.");this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();t.SsoCode=e,t.DeviceID=this.ctx.platform.getDeviceID(),t.Device=this.ctx.platform.getDeviceModel(),t.Platform=this.ctx.platform.getPlatform();let i=await this.ctx.api.authentication.loginWithSsoCode(t);return i.ok?(this.applyAuthContext(i.data),this.fetchAndApplyClientState(Ae.iDosGames)):i}async forgotPassword(e){this.ctx.emitter.emit("auth:requestSent",void 0);let t=this.baseRequest();return t.Email=e,this.ctx.api.authentication.forgotPassword(t)}async resetPassword(e,t,i){this.ctx.emitter.emit("auth:requestSent",void 0);let s=this.baseRequest();return s.Email=e,s.ResetToken=t,s.Password=i,this.ctx.api.authentication.resetPassword(s)}async autoLogin(){let e=this.ctx.authStore.lastAuthType;return await this.rotateSession({appOpened:true})==="ok"?this.fetchAndApplyClientState(e!==Ae.None?e:Ae.Device):this.replay(e,this.ctx.authStore.savedEmail,this.ctx.authStore.savedPassword)}async rotateSession(e){let t=this.sessionRefreshToken||this.ctx.authStore.savedRefreshToken;if(!t)return "failed";let i=this.baseRequest();i.RefreshToken=t,e?.appOpened&&(i.AppOpened=true);let s=await this.ctx.api.authentication.refreshSession(i);return s.ok?(this.applyRefresh(s.data),"ok"):(sg(s.error)&&(this.sessionRefreshToken="",this.ctx.authStore.saveRefreshToken("")),"failed")}applyRefresh(e){this.authContext={...this.authContext??{},userID:e.TitleUserID,clientSessionTicket:e.TitleClientSessionTicket,clientSessionTicketExpiration:e.TitleClientSessionTicketExpiration},this.keepRefreshToken(e.RefreshToken),this.setPlayAccess(e.PlayAccess??null);}keepRefreshToken(e){this.sessionRefreshToken=e??"",this.rememberSession&&this.ctx.authStore.saveRefreshToken(e??"");}replay(e,t,i){switch(e){case Ae.Email:return this.loginWithEmail(t,i);case Ae.Device:case Ae.None:return this.loginWithDeviceID();case Ae.Telegram:return this.loginWithTelegram();default:return Promise.resolve(b("client",`Cannot auto-login: last session used "${e}", which requires a fresh token from the platform SDK. Obtain a new token and call the matching login method (e.g. loginWithGoogle) instead of autoLogin().`))}}async refreshSession(){if(this.refreshing)return null;this.refreshing=true;try{if(await this.rotateSession()==="ok")return this.authContext?this.authContext.clientSessionTicket:null}catch{}finally{this.refreshing=false;}let e=this.sessionAuthType!==Ae.None?this.sessionAuthType:this.ctx.authStore.lastAuthType;if(e===Ae.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&&ig.test(e)}static isValidPasswordLength(e){return e.length>=eg&&e.length<=tg}keepEmailCredentials(e,t){this.sessionEmail=e,this.sessionPassword=t,this.rememberSession&&this.ctx.authStore.saveEmailAndPassword(e,t);}forgetSession(){this.sessionAuthType=Ae.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(Ul,Ul);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 ng="idos:cfg",li=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;static scopeOf(e,t){return t&&t.length>0?`x:${El(t)}`:e&&e.length>0?`f:${El(e)}`:t?"x:":"f:"}async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="string"||!i.c?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,c:i};await this.storage.set(this.keyOf(e),JSON.stringify(s));}catch{}}async clear(e){try{await this.storage.remove(this.keyOf(e));}catch{}}keyOf(e){return `${ng}:${this.titleId}:${e}`}};function El(o){return [...o].map(e=>e.toLowerCase()).sort().join(",")}var ql="idos:loc",ui=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.v!="number"||!i.t||typeof i.t!="object"?null:i}catch{return null}}async write(e,t,i){try{let s={v:t,t:i};await this.storage.set(this.keyOf(e),JSON.stringify(s)),await this.noteVersion(e,t);}catch{}}async readVersions(){try{let e=await this.storage.get(this.versionsKey());if(!e)return {};let t=JSON.parse(e);if(!t||typeof t!="object")return {};let i={};for(let[s,n]of Object.entries(t))typeof n=="number"&&n>0&&(i[s]=n);return i}catch{return {}}}async noteVersion(e,t){let i=await this.readVersions();i[e]!==t&&(i[e]=t,await this.storage.set(this.versionsKey(),JSON.stringify(i)));}keyOf(e){return `${ql}:${this.titleId}:${e}`}versionsKey(){return `${ql}:${this.titleId}:versions`}};var rg="idos:sec",rs=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 `${rg}:${this.titleId}`}};var og="idos:state",os=class{constructor(e,t){this.storage=e;this.titleId=t;}storage;titleId;async read(e){if(!e)return null;try{let t=await this.storage.get(this.keyOf(e));if(!t)return null;let i=JSON.parse(t);return !i||typeof i!="object"||typeof i.e!="string"||!i.v||!i.s?null:i}catch{return null}}async write(e,t,i,s){if(!(!e||!t))try{let n={e:t,v:i,s};await this.storage.set(this.keyOf(e),JSON.stringify(n));}catch{}}keyOf(e){return `${og}:${this.titleId}:${e}`}};function ag(o,e){if(!o)return;let t=new Set((e??[]).map(s=>s.trim().toLowerCase()));if(t.size===0)return o;let i={};for(let[s,n]of Object.entries(o))t.has(s.toLowerCase())||(i[s]=n);return i}function oo(o,e,t,i){let s={...o??{}};if(!e||!t||!i)return s;for(let[n,r]of Object.entries(t))i[n]===r&&n in e&&(s[n]=e[n]);return s}function lg(o){return {...o??{}}}function ao(o){return typeof o.StateEpoch=="string"&&o.StateEpoch.length>0?o.StateEpoch:null}var as=class{constructor(e){this.cache=e;}cache;loadedFor=null;epoch=null;versions={};confirmedAt={};state=null;dirty=false;listener=null;onChanged(e){this.listener=e;}async load(e){if(this.loadedFor===e)return;let t=await this.cache.read(e);this.loadedFor=e,this.epoch=t?.e??null,this.versions=t?{...t.v}:{},this.confirmedAt={},this.state=t?.s??null,this.dirty=false;}get cachedState(){return this.state}get currentEpoch(){return this.epoch}isFresh(e,t,i=Date.now()){if(this.versions[e]===void 0)return false;let s=this.confirmedAt[e];return s===void 0?false:t===void 0||i-s<=t}forget(e){let t=[];for(let i of e)this.versions[i]!==void 0&&(delete this.versions[i],delete this.confirmedAt[i],t.push(i));t.length!==0&&(this.dirty=true,this.notify(t));}versionsFor(e){if(!this.epoch)return;let t=ag(this.versions,e);return t&&Object.keys(t).length>0?t:void 0}noteMutation(e,t){if(!e||e!==this.epoch){if(e&&e!==this.epoch){let n=Object.keys(this.versions);this.reset(e),this.notify(n);}return}let i=Date.now(),s=[];for(let[n,r]of Object.entries(t)){let p=this.versions[n];p!==r&&(p!==void 0&&r===p+1?(this.versions[n]=r,this.confirmedAt[n]=i):(delete this.versions[n],delete this.confirmedAt[n]),s.push(n),this.dirty=true);}this.notify(s);}afterFullRead(e,t){let i=e===this.epoch?this.versions:{};e!==this.epoch&&this.reset(e),this.versions=lg(t);let s=Date.now();this.confirmedAt={};for(let r of Object.keys(this.versions))this.confirmedAt[r]=s;this.dirty=true;let n=new Set;for(let r of new Set([...Object.keys(i),...Object.keys(this.versions)]))i[r]!==this.versions[r]&&n.add(r);this.notify([...n]);}afterSliceRead(e,t){e!==this.epoch&&this.reset(e);let i=Date.now(),s=[];for(let[n,r]of Object.entries(t??{}))this.versions[n]!==r&&s.push(n),this.versions[n]=r,this.confirmedAt[n]=i;this.dirty=true,this.notify(s);}async flush(e,t){!this.dirty||!this.epoch||!e||(this.state=t??{},this.dirty=false,await this.cache.write(e,this.epoch,this.versions,this.state));}notify(e){e.length>0&&this.listener?.(e);}reset(e){this.epoch=e,this.versions={},this.confirmedAt={},this.state=null,this.dirty=true;}};var Bl=b("server","Title configuration is unavailable (CDN and API both failed)."),ls=class{constructor(e){this.ctx=e;}ctx;baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,WebAppLink:this.ctx.platform.getFullURL(),RelatedEntityID:d()}:null}get configCache(){return this.cache??=new li(this.ctx.settings.configStorage,this.ctx.settings.titleID)}cache;get localizationCache(){return this.locCache??=new ui(this.ctx.settings.configStorage,this.ctx.settings.titleID)}locCache;get sectionCache(){return this.secCache??=new rs(this.ctx.settings.configStorage,this.ctx.settings.titleID)}secCache;sectionsVersion=null;get stateStore(){return this.versionStore??=new as(new os(this.ctx.settings.configStorage,this.ctx.settings.titleID))}versionStore;noteStateVersions(e,t){this.ctx.auth.context?.userID&&this.stateStore.currentEpoch&&this.stateStore.noteMutation(e,t);}isStateFresh(e,t){return this.stateStore.isFresh(e,t)}readStateSlice(e){return this.getUserState(e)}forgetState(e){this.stateStore.forget(e);}onStateChanged(e){this.stateStore.onChanged(e);}async getClientState(){let e=this.baseRequest();if(!e)return c$1;let t=li.scopeOf(e.TitleFields,null),i=await this.configCache.read(t);i&&(e.KnownTitleConfigVersion=i.v),await this.prepareLocalization(e);let s=await this.prepareStateHandshake(e,null);await this.prepareLoginViews(e);let n=await this.ctx.api.user.getClientState(e);if(!n.ok)return n;let r=await this.resolveTitleConfig(n.data,t,i,{Fields:e.TitleFields});return r==null?Bl:(this.finishStateHandshake(n.data,s),await this.restoreSections(n.data.TitleConfigVersion,r),await this.applyClientState(n.data,r,void 0,void 0),this.ctx.cache.acceptLoginViews(n.data.Views),await this.applyLocalization(n.data.Localization),await this.flushState(s),n)}async prepareStateHandshake(e,t){let i=this.ctx.auth.context?.userID;if(!i)return {userId:null,cached:null,sent:void 0};await this.stateStore.load(i),await this.stateStore.flush(i,this.ctx.data.user.state);let s=this.stateStore.versionsFor(t);if(s){e.KnownStateVersions=s;let n=this.stateStore.currentEpoch;n&&(e.KnownStateEpoch=n);}return {userId:i,cached:this.stateStore.cachedState,sent:s}}finishStateHandshake(e,t){let i=oo(e.User,t.cached,t.sent,e.StateVersions);e.User=i;let s=ao(e);!s||!t.userId||this.stateStore.afterFullRead(s,e.StateVersions);}async resolveTitleConfig(e,t,i,s){let n=e.TitleConfigVersion;if(i&&n&&i.v===n)return i.c;if(e.TitleConfigUrl){let p=await this.fetchConfigFromCdn(e.TitleConfigUrl);if(p!=null)return n&&await this.configCache.write(t,n,p),p}let r=await this.fetchConfigFromApi(s);return r!=null?(n&&await this.configCache.write(t,n,r),r):i?.c??null}async fetchConfigFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchConfigFromApi(e){let t=this.baseRequest();if(!t)return null;let i={...t,...e},s=e.ExcludeFields?await this.ctx.api.title.getTitlePublicConfigurationExcept(i):await this.ctx.api.title.getTitlePublicConfiguration(i);return s.ok?s.data:null}async getClientStateExcept(e,t){let i=this.baseRequest();if(!i)return c$1;i.ExcludeFields=e,i.ExcludeTitleFields=t;let s=li.scopeOf(null,t??[]),n=await this.configCache.read(s);n&&(i.KnownTitleConfigVersion=n.v),await this.prepareLocalization(i);let r=await this.prepareStateHandshake(i,e??null);await this.prepareLoginViews(i);let p=await this.ctx.api.user.getClientStateExcept(i);if(!p.ok)return p;let d=await this.resolveTitleConfig(p.data,s,n,{ExcludeFields:t??[]});return d==null?Bl:(this.finishStateHandshake(p.data,r),await this.restoreSections(p.data.TitleConfigVersion,d),await this.applyClientState(p.data,d,e,t),this.ctx.cache.acceptLoginViews(p.data.Views),await this.applyLocalization(p.data.Localization),await this.flushState(r),p)}async restoreSections(e,t){if(e!==this.sectionsVersion&&this.ctx.data.config.clearSections(),this.sectionsVersion=e??null,!e){this.ctx.data.config.setSectionSink(null);return}let i=t,s={};for(let[n,r]of Object.entries(await this.sectionCache.read(e)))i[n]==null&&(s[n]=r);this.ctx.data.config.restoreSections(s),this.ctx.data.config.setSectionSink((n,r)=>{i[n]!=null||r==null||(s[n]=r,this.sectionCache.write(e,s));});}async prepareLoginViews(e){let t=await this.ctx.cache.loginViews();t.length>0&&(e.Views=t);}async prepareLocalization(e){let t=this.ctx.localization.locale??this.ctx.settings.locale;t&&(e.Locale=t);let i=await this.localizationCache.readVersions();Object.keys(i).length>0&&(e.KnownLocalizationVersions=i);}async applyLocalization(e){if(!e){this.ctx.localization.applyState(null,{table:null,fallbackTable:null});return}let t=await this.resolveLocalizationTable({Locale:e.Locale,Version:e.Version,Url:e.Url}),i=e.Fallback?await this.resolveLocalizationTable(e.Fallback):null;this.ctx.localization.applyState(e,{table:t,fallbackTable:i});}async resolveLocalizationTable(e){let t=e.Locale??null,i=e.Version??0;if(!t)return null;let s=await this.localizationCache.read(t);if(i<=0)return s?.t??null;if(s&&s.v===i)return s.t;if(e.Url){let r=await this.fetchLocalizationFromCdn(e.Url);if(r!=null)return await this.localizationCache.write(t,i,r),r}let n=await this.fetchLocalizationFromApi(t,s?.v??0);return n??s?.t??null}async fetchLocalizationFromCdn(e){try{let t=await this.ctx.fetchImpl(e);if(!t.ok)return null;let i=await t.json();return i&&typeof i=="object"?i:null}catch{return null}}async fetchLocalizationFromApi(e,t){let i=this.baseRequest();if(!i)return null;let s=await this.ctx.api.localization.getLocalizationTable({...i,Locale:e,KnownVersion:t});if(!s.ok)return null;let n=s.data;if(n.NotModified)return null;let r=n.Entries??{},p=n.Version??0,d=n.Locale??e;return p>0&&await this.localizationCache.write(d,p,r),r}async getStateVersions(e){let t=this.baseRequest();return t?(e&&e.length>0&&(t.Fields=e),this.ctx.api.user.getStateVersions(t)):c$1}async getUserState(e){let t=this.baseRequest();if(!t)return c$1;e&&e.length>0&&(t.Fields=e);let i=await this.prepareStateHandshake(t,null),s=await this.ctx.api.user.getUserState(t);if(!s.ok)return s;let n=oo(s.data.User,i.cached,i.sent,s.data.StateVersions);s.data.User=n;let r=i.sent??{},p=Object.entries(s.data.StateVersions??{}).filter(([C,j])=>r[C]!==j||this.ctx.data.user.state?.[C]===void 0).map(([C])=>C);this.ctx.data.user.applyUserStateContainers(n,p);let d=ao(s.data);return d&&(this.stateStore.afterSliceRead(d,s.data.StateVersions),await this.flushState(i)),s}async flushState(e){e.userId&&await this.stateStore.flush(e.userId,this.ctx.data.user.state);}async getUserInventory(){let e=this.baseRequest();if(!e)return c$1;let t=await this.ctx.api.user.getInventory(e);return t.ok&&(this.ctx.data.user.applyInventory(t.data),this.ctx.emitter.emit("user:inventoryReceived",t.data)),t}async getEventTokens(){let e=this.baseRequest();if(!e)return c$1;let t=await this.ctx.api.user.getEventTokens(e);return t.ok&&this.ctx.emitter.emit("user:eventTokensReceived",t.data),t}async getUsageTime(){let e=this.baseRequest();if(!e)return c$1;let t=await this.ctx.api.user.getUsageTime(e);return t.ok&&this.ctx.emitter.emit("user:usageTimeReceived",t.data),t}async addUsageTime(e,t,i){let s=this.baseRequest();if(!s)return c$1;s.UsageTime=e,s.IsNewSession=t,s.SessionDurationSeconds=i;let n=await this.ctx.api.user.addUsageTime(s);return n.ok&&this.ctx.emitter.emit("user:usageTimeAdded",n.data),n}async deleteUserAccount(){let e=this.baseRequest();if(!e)return c$1;let t=await this.ctx.api.user.deleteUserAccount(e);return t.ok&&this.ctx.emitter.emit("user:accountDeleted",t.data),t}async changeUsername(e){let t=this.baseRequest();if(!t)return c$1;t.Username=e;let i=await this.ctx.api.user.changeUsername(t);return i.ok&&this.ctx.emitter.emit("user:usernameChanged",i.data),i}async applyClientState(e,t,i,s){let n=i?.includes("GameLoop")===true,r=s?.includes("GameLoop")===true,p=n?this.ctx.data.user.state?.GameLoop:void 0,d=r?this.ctx.data.config.titlePublicConfiguration?.GameLoop:void 0;this.ctx.data.config.applyTitlePublicConfiguration(t),this.ctx.data.user.applyUserState(e.User??{});let C=this.ctx.data.user.state;n&&C&&C.GameLoop==null&&(C.GameLoop=p);let j=this.ctx.data.config.titlePublicConfiguration;r&&j&&j.GameLoop==null&&(j.GameLoop=d),this.ctx.emitter.emit("user:clientStateReceived",e);}};var cs=class{constructor(e){this.ctx=e;}ctx;async convert(e,t,i,s,n,r){if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(n<=0)return b("client","Amount must be positive.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===ut.Crypto||i===ut.Crypto)return b("client","Convert supports VC\u2194VC only. Use cryptoConvert for crypto.");if(!this.ctx.auth.context)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:String(Math.trunc(n)),TransactionID:r&&r.length>0?r:`convert_${e}_${t}_to_${i}_${s}_${d()}`},d$1=await this.ctx.api.currency.convert(p);if(d$1.ok){let C=d$1.data,j={Consume:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:C.SourceID,Amount:C.SourceSpent}]}},Grant:{Standard:{Entries:[{Type:"VirtualCurrency",CurrencyID:C.TargetID,Amount:C.TargetCredited}]}}};this.ctx.data.user.applyResourceOperation(j,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("currency:converted",C);}return d$1}async cryptoConvert(e,t,i,s,n,r){let p=n instanceof Nt?n:new Nt(n);if(!t)return b("client","SourceID is required.");if(!s)return b("client","TargetID is required.");if(p.lte(0))return b("client","SourceAmount must be a positive decimal.");if(e===i&&t===s)return b("client","Source and target must differ.");if(e===ut.Virtual&&i===ut.Virtual)return b("client","cryptoConvert requires at least one crypto side. Use convert for VC\u2194VC.");if(e===ut.Virtual&&!p.isInteger())return b("client","Virtual currency source amount must be integer.");if(!this.ctx.auth.context)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),SourceType:e,SourceID:t,TargetType:i,TargetID:s,SourceAmount:p.toString(),TransactionID:r&&r.length>0?r:`crypto_convert_${e}_${t}_to_${i}_${s}_${d()}`},C=await this.ctx.api.currency.cryptoConvert(d$1);if(C.ok){let j=C.data,ue=[],Ie=[];if(j.SourceType===ut.Virtual&&ue.push({Type:"VirtualCurrency",CurrencyID:j.SourceID,Amount:Math.trunc(Number(j.SourceSpent))}),j.TargetType===ut.Virtual&&Ie.push({Type:"VirtualCurrency",CurrencyID:j.TargetID,Amount:Math.trunc(Number(j.TargetCredited))}),ue.length>0||Ie.length>0){let ge={Consume:ue.length>0?{Standard:{Entries:ue}}:null,Grant:Ie.length>0?{Standard:{Entries:Ie}}:null};this.ctx.data.user.applyResourceOperation(ge,this.ctx.data.config.itemDefinitions);}j.SourceType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.SourceID,new Nt(j.SourceSpent).negated(),j.ServerTimeUtc),j.TargetType===ut.Crypto&&this.ctx.data.user.patchCryptoCurrencyDelta(j.TargetID,new Nt(j.TargetCredited),j.ServerTimeUtc),this.ctx.emitter.emit("currency:cryptoConverted",j);}return C}};var ps=class{constructor(e){this.ctx=e;}ctx;async upgradeLevel(e,t,i){let s=e.trim();if(!s)return b("client","ItemInstanceID is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),ItemInstanceID:s,SelectedOptionID:i,RelatedEntityID:`upgrade_item_${s}_${d()}`};t&&t.length>0&&(n.FodderInstanceIDs=[...t]);let r=await this.ctx.api.item.upgradeLevel(n);return r.ok&&(this.ctx.data.user.patchEquippedItemLevel(r.data.ItemInstanceID??s,r.data.Level),await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelUpgraded",r.data)),r}async upgradeLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Upgrades:e},i=await this.ctx.api.item.upgradeLevelsBatch(t);if(i.ok){for(let s of i.data)s.Success&&s.Data?.ItemInstanceID&&this.ctx.data.user.patchEquippedItemLevel(s.Data.ItemInstanceID,s.Data.Level);await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("item:levelsUpgradedBatch",i.data);}return i}};var Ll=z.object({OptionID:z.string().nullish(),Name:z.string().nullish(),Cost:xt.nullish(),AllowedPlatforms:z.array(Li).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),ae=z.record(z.string(),Ll),ug=z.object({Store:Gi,Receipt:z.string(),Signature:z.string().nullish()}).passthrough();var lo=z.object({ServerTimeUtc:c,OfferID:z.string(),Count:z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),Gl=z.array(Pe(lo)),cg=z.object({OfferID:z.string(),TotalPurchases:z.number(),DailyPurchases:z.number(),DailyResetUtc:c,LastPurchasedAt:c}),pg=z.object({SlotKey:z.string(),InstanceKey:z.string(),OfferID:z.string().nullish(),Purchases:z.number(),LastPurchasedAt:c}),Fl=z.object({Purchases:z.record(z.string(),cg).nullish(),Rotations:z.record(z.string(),pg).nullish()}).passthrough().transform(o=>o),Dt=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),hs=z.object({Schedule:me.nullish(),Gate:J.nullish()}).passthrough(),hg={Fixed:"Fixed",Title:"Title",Player:"Player"},dg=z.object({OfferID:z.string().nullish(),Weight:z.number().nullish(),Gate:J.nullish()}).passthrough(),Vl=z.object({Mode:z.string().nullish(),OfferID:z.string().nullish(),Pool:z.array(dg).nullish(),Salt:z.string().nullish(),PerInstanceCap:z.number().nullish()}).passthrough(),mg=z.object({Identity:K.nullish(),Availability:K.nullish(),Rotation:K.nullish()}).passthrough(),fg=z.object({SlotID:z.string().nullish(),Identity:Dt.nullish(),Availability:hs.nullish(),Rotation:Vl.nullish(),Presets:mg.nullish()}).passthrough(),gg=z.object({Identity:K.nullish(),Availability:K.nullish()}).passthrough(),yg=z.object({SectionID:z.string().nullish(),Identity:Dt.nullish(),Availability:hs.nullish(),Slots:z.record(z.string(),fg).nullish(),UniqueOffersInSection:z.boolean().nullish(),Presets:gg.nullish()}).passthrough(),jl=z.object({Sections:z.record(z.string(),yg).nullish()}).passthrough(),Rg=z.object({Identity:K.nullish(),Availability:K.nullish(),Layout:K.nullish()}).passthrough(),Cg=z.object({StoreID:z.string().nullish(),Identity:Dt.nullish(),Availability:hs.nullish(),Layout:jl.nullish(),Presets:Rg.nullish()}).passthrough(),Nl=z.object({Options:ae.nullish(),CompareAt:z.record(z.string(),xt).nullish()}).passthrough(),_l=z.object({Grant:H.nullish()}).passthrough(),Wl=z.object({Schedule:me.nullish(),Gate:J.nullish(),Limits:ye.nullish()}).passthrough(),Sg=z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish(),Availability:K.nullish()}).passthrough(),xg=z.object({OfferID:z.string().nullish(),Identity:Dt.nullish(),Pricing:Nl.nullish(),Reward:_l.nullish(),Availability:Wl.nullish(),Presets:Sg.nullish()}).passthrough(),bg=z.object({Identity:z.record(z.string(),Dt).nullish(),Availability:z.record(z.string(),hs).nullish(),Layout:z.record(z.string(),jl).nullish(),Rotation:z.record(z.string(),Vl).nullish(),Pricing:z.record(z.string(),Nl).nullish(),Reward:z.record(z.string(),_l).nullish(),OfferAvailability:z.record(z.string(),Wl).nullish()}).passthrough(),ds=z.object({Stores:z.record(z.string(),Cg).nullish(),StoreOffers:z.record(z.string(),xg).nullish(),Presets:bg.nullish()}).passthrough(),Dg=z.object({PurchasedTotal:z.number(),PurchasedToday:z.number(),PurchasedThisRotation:z.number(),RemainingTotal:z.number().nullish(),RemainingToday:z.number().nullish(),IsFirstPurchaseAvailable:z.boolean(),SoldOut:z.boolean(),AvailableAtUtc:c.nullish()}).passthrough(),Pg=z.object({OptionID:z.string(),Name:z.string().nullish(),Cost:xt.nullish(),CompareAtCost:xt.nullish(),DiscountPercent:z.number().nullish(),IsFree:z.boolean(),IsAdPaid:z.boolean(),IsStorePaid:z.boolean(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Ig=z.object({OfferID:z.string(),Identity:Dt.nullish(),PriceOptions:z.array(Pg).nullish(),Rewards:H.nullish(),State:Dg.nullish()}).passthrough(),vg=z.object({SlotID:z.string(),Identity:Dt.nullish(),SortOrder:z.number(),RotationMode:z.string().nullish(),RotationInstanceKey:z.string().nullish(),RefreshesAtUtc:c.nullish(),RemainingThisRotation:z.number().nullish(),Offer:Ig.nullish()}).passthrough(),Tg=z.object({SectionID:z.string(),Identity:Dt.nullish(),SortOrder:z.number(),Slots:z.array(vg).nullish()}).passthrough(),kg=z.object({StoreID:z.string(),Identity:Dt.nullish(),SortOrder:z.number(),ScheduleInstanceKey:z.string().nullish(),ExpiresAtUtc:c.nullish(),Sections:z.array(Tg).nullish()}).passthrough(),ms=z.object({ServerTimeUtc:c,Stores:z.array(kg).nullish(),AdCreditBalance:z.number()}).passthrough(),_t={Purchase:"Purchase",GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",PurchaseBatch:"PurchaseBatch",GetStorefront:"GetStorefront"},zg="OFFER_NOT_IN_ROTATION";var Kl="Store",Ql={key:"store.storefront",login:"Storefront",ttlMs:10*6e4,dependsOn:["Store","Premium"],invalidateOn:["store:offerPurchased","store:offersPurchasedBatch","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:o=>{let e=null;for(let t of o.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=Date.parse(s.RefreshesAtUtc??"");!Number.isNaN(n)&&(e===null||n<e)&&(e=n);}return e}},fs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Ql,{schema:ms,apply:t=>this.applyStorefront(t)});}ctx;storefront=null;storefrontLoadedAt=0;async purchase(e,t=1,i){if(!e)return b("client","OfferID is required.");if(t<1)return b("client","Count must be at least 1.");let s=this.ctx.auth.context;if(!s)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),OfferID:e,Count:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,StoreID:i?.slot?.storeID,SectionID:i?.slot?.sectionID,SlotID:i?.slot?.slotID,RelatedEntityID:`store_buy_${e}_${s.userID}_${d()}`},r=await this.ctx.api.store.purchase(n);if(r.ok){let p=r.data;this.ctx.data.user.patchStorePurchase(e,t,p.ServerTimeUtc),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("store:offerPurchased",p);}return r}async purchaseBatch(e){if(!e||e.length===0)return b("client","purchases is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Purchases:e},i=await this.ctx.api.store.purchaseBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||!n.Data.OfferID||(this.ctx.data.user.patchStorePurchase(n.Data.OfferID,n.Data.Count,n.Data.ServerTimeUtc),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("store:offersPurchasedBatch",i.data);}return i}async getDefinitions(e){let t=this.ctx.cache.configSection(Kl,e);if(t)return this.ctx.emitter.emit("store:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.store.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Kl,s.data),this.ctx.emitter.emit("store:definitionsLoaded",s.data)),s}getStorefront(e){return this.ctx.cache.read(Ql,()=>this.fetchStorefront(),e)}async fetchStorefront(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.store.getStorefront(e);return t.ok&&this.applyStorefront(t.data),t}applyStorefront(e){this.storefront=e,this.storefrontLoadedAt=Date.now(),this.ctx.emitter.emit("store:storefrontLoaded",e);}get cachedStorefront(){return this.storefront}nextRefreshAtUtc(){let e=null;for(let t of this.storefront?.Stores??[])for(let i of t.Sections??[])for(let s of i.Slots??[]){let n=s.RefreshesAtUtc;n&&(e===null||Date.parse(n)<Date.parse(e))&&(e=n);}return e}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.store.getUserState(e);return t.ok&&(this.ctx.data.user.applyStore(t.data),this.ctx.emitter.emit("store:userStateLoaded",t.data)),t}};var gs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){if(!this.ctx.auth.context)return c$1;let e={...this.ctx.buildAuthedBaseRequest()};return this.ctx.api.purchase.getDefinitions(e)}async getUserState(){if(!this.ctx.auth.context)return c$1;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.purchase.getUserState(e);return t.ok?a(t.data.Purchase??{}):t}async validatePurchase(e,t,i){if(!t)return b("client","Receipt is required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),Store:e,Receipt:t,Signature:i?.signature,ProductID:i?.productID,TransactionID:i?.transactionID},n=await this.ctx.api.purchase.validatePurchase(s);return n.ok&&this.applyValidation(n.data),n}async buyWithTelegramStars(e,t){if(!e)return b("client","productID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),ProductID:e},s=await this.ctx.api.purchase.createTelegramInvoice(i);return s.ok&&t?.open!==false&&this.ctx.platform.openInvoice(s.data.InvoiceLink),s}async validatePurchasesBatch(e){if(!e||e.length===0)return b("client","receipts is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Receipts:e},i=await this.ctx.api.purchase.validatePurchasesBatch(t);if(i.ok)for(let s of i.data.Items)s.Success&&s.Data&&this.applyValidation(s.Data);return i}applyValidation(e){e.Granted&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);}};var Hl=3,Ag=700,ys=class{constructor(e){this.ctx=e;l()&&this.setTopUpHandler(this.platformTopUp);}ctx;setTopUpHandler(e){this.ctx.transport.setCryptoTopUpHandler(e);}get topUpAvailable(){return this.ctx.transport.hasCryptoTopUpHandler}shortfallFromError(e){return oi(e)}platformTopUp=async e=>{let t=this.ctx.auth.context?.userID;if(!t)return false;let i=await m({titleID:this.ctx.settings.titleID,userID:t,currencyID:e.currencyID,amount:e.missingAmount??String(e.missing)});return i.ok?(await this.refreshAfterTopUp(e),true):(this.ctx.emitter.emit("checkout:topUpFailed",{currencyID:e.currencyID,error:i.error??"FAILED"}),false)};async refreshAfterTopUp(e){for(let t=1;t<=Hl;t++){let i=await this.ctx.cache.ensureState(["InventoryV2"],{force:true});if(i.ok)return;if(i.reason!=="throttled"||t===Hl)break;await wt(Ag);}this.ctx.data.user.patchCryptoCurrencyDelta(e.currencyID,e.missingAmount??e.missing);}get platform(){return this.ctx.clientPlatform}availableOptions(e){return e?Object.entries(e).filter(([,t])=>t!=null).map(([t,i])=>({...i,OptionID:i.OptionID||t})).filter(t=>this.isAvailable(t)).sort((t,i)=>(t.OptionID??"").localeCompare(i.OptionID??"")):[]}isAvailable(e){if(!e)return false;let t=e.AllowedPlatforms;return !t||t.length===0?true:t.includes(this.platform)}requirementOf(e){let t=this.storeProductOf(e.Cost);return t?{option:e,kind:"store",productID:t}:{option:e,kind:"resources",shortfall:this.cryptoShortfallOf(e.Cost)??void 0}}storeProductOf(e){let t=e?.Standard?.Entries;if(!t)return null;for(let i of t)if(i?.Type===Bi.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!==Bi.CryptoCurrency||!i.CurrencyID)continue;let s=Number(i.Amount??0);if(!(s>0))continue;let n=this.cryptoBalance(i.CurrencyID);return n>=s?null:{currencyID:i.CurrencyID,required:s,available:n,missing:s-n}}return null}cryptoBalance(e){let i=this.ctx.data.user.state?.InventoryV2?.CryptoCurrencies?.[e];return Number(i?.Amount??0)}};var $l="Lootbox",Rs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection($l,e);if(t){let n={LootboxDefinitions:t};return this.ctx.emitter.emit("lootbox:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.lootbox.getDefinitions(i);if(s.ok){let n=s.data.LootboxDefinitions;n&&(this.ctx.data.config.patchSection($l,n),this.ctx.emitter.emit("lootbox:definitionsLoaded",n));}return s}async open(e,t,i,s){if(!e)return b("client","LootboxID is required.");if(t<1)return b("client","Count must be at least 1.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),LootboxID:e,Count:t,SelectedOptionID:i,Payment:s,RelatedEntityID:`lootbox_${e}_${i??"default"}_${d()}`},r=await this.ctx.api.lootbox.open(n);if(r.ok){let p=r.data;p.TriggeredPity&&p.TriggeredPity.length>0&&this.ctx.data.user.applyLootboxPityTriggers(e,p.TriggeredPity,t),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("lootbox:opened",p);}return r}};var uo="Reward";function co(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var Cs=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(uo)?.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(uo,e);if(t){let n={RewardDefinitions:t};return this.ctx.emitter.emit("reward:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.reward.getRewardDefinitions(i);if(s.ok){let n=s.data.RewardDefinitions;n&&(this.ctx.data.config.patchSection(uo,n),this.ctx.emitter.emit("reward:definitionsLoaded",n));}return s}async getUserRewardsState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.reward.getUserRewardsState(e);return t.ok&&t.data.Rewards&&(this.ctx.data.user.applyReward(t.data.Rewards),this.ctx.emitter.emit("reward:userStateLoaded",t.data.Rewards)),t}async getMilestoneRewardMultiplier(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.reward.getMilestoneRewardMultiplier(e);if(t.ok){let i=t.data;this.multiplierEnabled=i.Enabled,this.multiplier=i.Enabled?i.Multiplier??1:1,this.ctx.emitter.emit("reward:milestoneMultiplierLoaded",i);}return t}async claimDailyReward(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CalendarID:e,RelatedEntityID:`dailyreward_${t.userID}_${e??"default"}_${d()}`},s=await this.ctx.api.reward.claimDailyReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchDailyCalendarState(n.CalendarID,n.DailyState),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:dailyClaimed",n);}return s}async collectIdleAccrual(e){if(!co(e))return b("client",'AccrualID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),AccrualID:e,RelatedEntityID:`idle_collect_${e}_${d()}`},i=await this.ctx.api.reward.collectIdleAccrual(t);if(i.ok){let s=i.data;this.ctx.data.user.patchIdleAccrualState(s.AccrualID,s.IdleState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:idleCollected",s);}return i}async claimComebackReward(e){if(!co(e))return b("client",'ComebackID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),ComebackID:e,RelatedEntityID:`comeback_claim_${e}_${d()}`},i=await this.ctx.api.reward.claimComebackReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchComebackState(s.ComebackID,s.ComebackState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:comebackClaimed",s);}return i}async claimReward(e){if(!co(e))return b("client",'ClaimID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),ClaimID:e,RelatedEntityID:`reward_claim_${e}_${d()}`},i=await this.ctx.api.reward.claimReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchClaimRewardState(s.ClaimID,s.ClaimState),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("reward:claimed",s);}return i}};var Ss="Tutorial",Jl={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"]},xs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Jl,{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(Ss)?.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(Ss,e);if(t)return this.ctx.emitter.emit("tutorial:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.tutorial.getTutorialDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Ss,s.data),this.ctx.emitter.emit("tutorial:definitionsLoaded",s.data)),s}getUserTutorialState(e=true,t){return this.ctx.cache.read(Jl,()=>this.fetchUserTutorialState(e),{...t,args:e?void 0:"manual",loginParams:e?{}:{AutoStart:false}})}async fetchUserTutorialState(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.AutoStart=e;let i=await this.ctx.api.tutorial.getUserTutorialState(t);return i.ok&&this.applyUserTutorialState(i.data),i}applyUserTutorialState(e){let t=e.State??{};this.ctx.data.user.applyTutorial(t),this.ctx.emitter.emit("tutorial:userStateLoaded",e);}async startFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.startFlow(t),{event:"tutorial:flowStarted"})}async reportStepShown(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.reportStepShown(i))}async completeStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.completeStep(i),{relatedEntityID:`tutorial_step_${e}_${t}_${d()}`})}async completeStepsBatch(e,t){let i=e?.trim();if(!i)return b("client","FlowID is required.");if(!t||t.length===0)return b("client","stepIDs is required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),FlowID:i,StepIDs:t,RelatedEntityID:`tutorial_batch_${i}_${d()}`},n=await this.ctx.api.tutorial.completeStepsBatch(s);return n.ok&&(await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:stepsCompletedBatch",n.data)),n}async skipStep(e,t){return this.stepCall(e,t,i=>this.ctx.api.tutorial.skipStep(i))}async skipFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.skipFlow(t),{event:"tutorial:flowSkipped"})}async claimFlowReward(e){let t=e?.trim();if(!t)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),FlowID:t,RelatedEntityID:`tutorial_claim_${t}_${d()}`},s=await this.ctx.api.tutorial.claimFlowReward(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Granted,this.ctx.data.config.itemDefinitions),await this.refreshAfterMutation(),this.ctx.emitter.emit("tutorial:rewardClaimed",s.data)),s}async resetFlow(e){return this.flowCall(e,t=>this.ctx.api.tutorial.resetFlow(t),{event:"tutorial:flowReset"})}async flowCall(e,t,i){let s=e?.trim();if(!s)return b("client","FlowID is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),FlowID:s},r=await t(n);return r.ok&&(this.applyFlowView(r.data),this.ctx.emitter.emit(i.event,r.data)),r}async stepCall(e,t,i,s){let n=e?.trim(),r=t?.trim();if(!n)return b("client","FlowID is required.");if(!r)return b("client","StepID is required.");if(!this.ctx.auth.context)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),FlowID:n,StepID:r};s?.relatedEntityID&&(p.RelatedEntityID=s.relatedEntityID);let d=this.ctx.data.user.state?.Tutorial?.Flows?.[n]?.RewardClaimed===true,C=await i(p);return C.ok&&(this.applyFlowView(C.data),this.mayHavePaid(n,r,d,C.data)&&await this.ctx.userService.getUserInventory(),this.ctx.emitter.emit("tutorial:stepChanged",C.data)),C}mayHavePaid(e,t,i,s){return !i&&s.Flow?.RewardClaimed===true?true:s.Flow?.Status==="Skipped"?false:!!this.ctx.data.config.getSection(Ss)?.Flows?.[e]?.Steps?.[t]?.Effects?.Grant}applyFlowView(e){e?.Flow&&this.ctx.data.user.patchTutorialFlow(e.Flow);}async refreshAfterMutation(){await this.getUserTutorialState(false).catch(()=>{});}};var bs=class{constructor(e){this.ctx=e;}ctx;async getState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.communityMarketing.getCommunityMarketingState(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:stateLoaded",t.data),t}async getEarnings(e=0){let t=this.ctx.authedRequest();if(!t)return c$1;e>0&&(t.Limit=e);let i=await this.ctx.api.communityMarketing.getEarnings(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:earningsLoaded",i.data),i}async claim(e){if(!e)return b("client","campaignID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.CampaignID=e;let i=await this.ctx.api.communityMarketing.claim(t);return i.ok&&this.ctx.emitter.emit("communityMarketing:claimed",i.data),i}async withdrawCryptoReward(e,t,i){if(!e)return b("client","campaignID is required.");if(!t)return b("client","walletAddress is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.CampaignID=e,s.WalletAddress=t,i&&(s.Amount=i);let n=await this.ctx.api.communityMarketing.withdrawCryptoReward(s);return n.ok&&this.ctx.emitter.emit("communityMarketing:withdrawn",n.data),n}async checkJoinEligibility(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.communityMarketing.checkJoinEligibility(e);return t.ok&&this.ctx.emitter.emit("communityMarketing:eligibilityChecked",t.data),t}};var Oe=z.object({Username:z.string().nullish(),Country:z.string().nullish(),AvatarUrl:z.string().nullish(),Premium:z.boolean().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),BoardRank:z.number().nullish()}).passthrough();var wg={Global:"Global",Announcement:"Announcement",Group:"Group"},Yl=z.enum(["Global","Announcement","Group"]).catch("Global"),Mg={None:"None",Language:"Language",Region:"Region"},Og=z.enum(["None","Language","Region"]).catch("None"),Ug={Anyone:"Anyone",Friends:"Friends"},Eg=z.enum(["Anyone","Friends"]).catch("Anyone"),qg={Reject:"Reject",Mask:"Mask"},Bg=z.enum(["Reject","Mask"]).catch("Reject"),Lg={Player:"Player",Publisher:"Publisher",System:"System"},Gg=z.enum(["Player","Publisher","System"]).catch("Player"),Fg={Spam:"Spam",Abuse:"Abuse",Scam:"Scam",Inappropriate:"Inappropriate",Other:"Other"};z.enum(["Spam","Abuse","Scam","Inappropriate","Other"]).catch("Other");var Vg=z.object({DisplayNameKey:z.string().nullish(),SortOrder:z.number().nullish(),IconPath:z.string().nullish(),JoinedByDefault:z.boolean().nullish()}).passthrough(),Xl=z.object({Gate:J.nullish(),Schedule:me.nullish()}).passthrough(),eu=z.object({Gate:J.nullish(),Limits:ye.nullish(),MaxLength:z.number().nullish()}).passthrough(),tu=z.object({HotTailSize:z.number().nullish(),HistoryHours:z.number().nullish()}).passthrough(),jg=z.object({Availability:K.nullish(),Write:K.nullish(),Retention:K.nullish()}).passthrough(),Ng=z.object({ChannelID:z.string().nullish(),Identity:Vg.nullish(),Type:Yl.nullish(),GroupSource:z.string().nullish(),Partitioning:Og.nullish(),Capacity:z.number().nullish(),Availability:Xl.nullish(),Write:eu.nullish(),Retention:tu.nullish(),Presets:jg.nullish()}).passthrough(),_g=z.object({IsEnabled:z.boolean().nullish(),Gate:J.nullish(),WhoCanMessage:Eg.nullish(),Limits:ye.nullish(),MaxLength:z.number().nullish(),HistoryHours:z.number().nullish(),MaxConversations:z.number().nullish()}).passthrough(),Wg=z.object({BlockedTerms:z.array(z.string()).nullish(),BlockedTermAction:Bg.nullish(),MaxIgnoreListSize:z.number().nullish(),ReportsEnabled:z.boolean().nullish(),ReportLimits:ye.nullish()}).passthrough(),Kg=z.object({MinIntervalSeconds:z.number().nullish(),MaxMessagesPerPoll:z.number().nullish(),MaxHistoryPageSize:z.number().nullish()}).passthrough(),Qg=z.object({Availability:z.record(z.string(),Xl).nullish(),Write:z.record(z.string(),eu).nullish(),Retention:z.record(z.string(),tu).nullish()}).passthrough(),iu=z.object({IsEnabled:z.boolean().nullish(),Channels:z.record(z.string(),Ng).nullish(),Direct:_g.nullish(),Moderation:Wg.nullish(),Polling:Kg.nullish(),Presets:Qg.nullish()}).passthrough(),Hg=z.object({LastReadAt:z.string().nullish(),LastReadMessageID:z.string().nullish(),Left:z.boolean().nullish()}).passthrough(),Zl=z.object({LastAt:z.string().nullish(),DailyCount:z.number().nullish(),DailyResetUtc:z.string().nullish(),TotalCount:z.number().nullish(),LastTextHash:z.string().nullish()}).passthrough();z.object({MutedUntil:z.string().nullish(),MuteReason:z.string().nullish(),Ignored:z.array(z.string()).nullish(),Channels:z.record(z.string(),Hg).nullish(),Limits:z.record(z.string(),Zl).nullish(),ReportLimits:Zl.nullish()}).passthrough();var po=z.object({RoomID:z.string().nullish(),SentAt:z.string().nullish(),MessageID:z.string().nullish()}).passthrough(),Ds=z.object({RoomID:z.string().nullish(),ChannelID:z.string().nullish(),MessageID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderProfile:Oe.nullish(),AuthorType:Gg.nullish(),Text:z.string().nullish(),SentAt:z.string().nullish()}).passthrough(),$g=z.object({ChannelID:z.string().nullish(),RoomID:z.string().nullish(),DisplayNameKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),Type:Yl.nullish(),CanWrite:z.boolean().nullish(),WriteBlockedReason:z.string().nullish(),SlowModeSeconds:z.number().nullish(),MaxLength:z.number().nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),Ps=z.object({Channels:z.array($g).nullish(),PollIntervalSeconds:z.number().nullish(),MutedUntil:z.string().nullish(),MuteReason:z.string().nullish()}).passthrough(),Jg=z.object({RoomID:z.string().nullish(),Messages:z.array(Ds).nullish(),NextCursor:po.nullish(),UnreadCount:z.number().nullish(),ServedFromDatabase:z.boolean().nullish()}).passthrough(),su=z.object({Rooms:z.array(Jg).nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),nu=z.object({RoomID:z.string().nullish(),Messages:z.array(Ds).nullish(),NextBefore:po.nullish()}).passthrough(),ru=z.object({Message:Ds.nullish(),Moderated:z.boolean().nullish()}).passthrough(),ou=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Oe.nullish(),MaxLength:z.number().nullish()}).passthrough(),Zg=z.object({RoomID:z.string().nullish(),PeerUserID:z.string().nullish(),PeerProfile:Oe.nullish(),LastMessage:Ds.nullish(),UnreadCount:z.number().nullish(),LastReadAt:z.string().nullish()}).passthrough(),au=z.object({Conversations:z.array(Zg).nullish()}).passthrough(),ci=z.object({Ignored:z.array(z.string()).nullish(),Cursor:po.nullish(),Joined:z.boolean().nullish()}).passthrough(),lu=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish()}).passthrough(),Ke={GetChatDefinitions:"GetChatDefinitions",GetChannels:"GetChannels",Poll:"Poll",GetHistory:"GetHistory",GetConversations:"GetConversations",SendMessage:"SendMessage",OpenDirectChannel:"OpenDirectChannel",MarkRead:"MarkRead",JoinChannel:"JoinChannel",LeaveChannel:"LeaveChannel",ReportMessage:"ReportMessage",IgnoreUser:"IgnoreUser",UnignoreUser:"UnignoreUser"};var uu="Chat",cu={key:"chat.channels",login:"ChatChannels",ttlMs:3e4,invalidateOn:["chat:sent","chat:read"]},Is=class{constructor(e){this.ctx=e;e.cache.bindLoginView(cu,{schema:Ps,apply:t=>this.ctx.emitter.emit("chat:channelsLoaded",t)});}ctx;cursors=new Map;async getChatDefinitions(e){let t=this.ctx.cache.configSection(uu,e);if(t)return this.ctx.emitter.emit("chat:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.chat.getChatDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(uu,s.data),this.ctx.emitter.emit("chat:definitionsLoaded",s.data)),s}getChannels(e,t){return this.ctx.cache.read(cu,()=>this.fetchChannels(e),{...t,args:e||void 0,loginParams:e?{Locale:e}:{}})}async fetchChannels(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&(t.Locale=e);let i=await this.ctx.api.chat.getChannels(t);return i.ok&&this.ctx.emitter.emit("chat:channelsLoaded",i.data),i}async poll(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&(t.Locale=e),this.cursors.size>0&&(t.Cursors=[...this.cursors.values()]);let i=await this.ctx.api.chat.poll(t);if(!i.ok)return i;for(let s of i.data.Rooms??[])s.NextCursor&&s.RoomID&&this.cursors.set(s.RoomID,s.NextCursor),s.Messages&&s.Messages.length>0&&this.ctx.emitter.emit("chat:messages",s);return i}async getHistory(e,t,i){let s=this.ctx.authedRequest();return s?(s.RoomID=e,t&&(s.Before=t),i&&(s.Limit=i),this.ctx.api.chat.getHistory(s)):c$1}async sendMessage(e,t,i){let s=this.ctx.authedRequest();if(!s)return c$1;s.ChannelID=e,s.Text=t,i&&(s.Locale=i);let n=await this.ctx.api.chat.sendMessage(s);return n.ok&&this.ctx.emitter.emit("chat:sent",n.data),n}async sendDirect(e,t){let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.Text=t;let s=await this.ctx.api.chat.sendMessage(i);return s.ok&&this.ctx.emitter.emit("chat:sent",s.data),s}async openDirectChannel(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.openDirectChannel(t)):c$1}async getConversations(){let e=this.ctx.authedRequest();return e?this.ctx.api.chat.getConversations(e):c$1}async markRead(e,t){let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.Cursors=[t??this.cursors.get(e)??{RoomID:e}];let s=await this.ctx.api.chat.markRead(i);return s.ok&&this.ctx.emitter.emit("chat:read",{roomID:e}),s}async joinChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.joinChannel(t)):c$1}async leaveChannel(e){let t=this.ctx.authedRequest();return t?(t.ChannelID=e,this.ctx.api.chat.leaveChannel(t)):c$1}async reportMessage(e,t,i,s){let n=this.ctx.authedRequest();return n?(n.RoomID=e,n.MessageID=t,n.Reason=i,s&&(n.Comment=s),this.ctx.api.chat.reportMessage(n)):c$1}async ignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.ignoreUser(t)):c$1}async unignoreUser(e){let t=this.ctx.authedRequest();return t?(t.TargetUserID=e,this.ctx.api.chat.unignoreUser(t)):c$1}resetCursors(){this.cursors.clear();}};var Yg={WebPush:"WebPush",Fcm:"Fcm",Apns:"Apns"},Xg=z.enum(["WebPush","Fcm","Apns"]).catch("WebPush"),ey={Player:"player",Title:"title",Creator:"creator"},pi={GetPushConfig:"GetPushConfig",SubscribePush:"SubscribePush",UnsubscribePush:"UnsubscribePush",GetPushSubscriptions:"GetPushSubscriptions"},pu=z.object({Configured:z.boolean().nullish(),PublicKey:z.string().nullish()}).passthrough(),ty=z.object({TitleID:z.string().nullish(),Topic:z.string().nullish()}).passthrough(),ho=z.object({EndpointHash:z.string().nullish(),Transport:Xg.nullish(),Locale:z.string().nullish(),Topics:z.array(ty).nullish()}).passthrough(),hu=z.object({Configured:z.boolean().nullish(),Subscriptions:z.array(ho).nullish()}).passthrough(),Pt={Unsupported:"unsupported",Idle:"idle",Subscribed:"subscribed",Blocked:"blocked",Embedded:"embedded"};var iy="IDOS_PLATFORM_PUSH_REQUEST",sy="IDOS_PLATFORM_PUSH_RESPONSE",ny=12e4;function du(o){if(typeof window>"u"||window.self===window.top)return Promise.resolve(false);let e=window.parent;if(!e)return Promise.resolve(false);let t=`push-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return new Promise(i=>{let s=false,n=d=>{s||(s=true,window.removeEventListener("message",r),clearTimeout(p),i(d));},r=d=>{let C=d?.data;!C||C.type!==sy||C.requestId!==t||f.includes(d.origin)&&n(C.ok===true);},p=setTimeout(()=>n(false),ny);window.addEventListener("message",r);for(let d of f)try{e.postMessage({type:iy,requestId:t,titleID:o},d);}catch{}})}var vs=class{constructor(e){this.ctx=e;}ctx;cachedConfig=null;async getConfig(e=false){if(!e&&this.cachedConfig)return this.cachedConfig;let t=this.ctx.authedRequest();if(!t)return {Configured:false,PublicKey:null};let i=await this.ctx.api.push.getPushConfig(t),s=i.ok?i.data:{Configured:false,PublicKey:null};return this.cachedConfig=s,i.ok&&this.ctx.emitter.emit("push:configLoaded",s),s}async getState(){let e=await this.getConfig();if(!e.Configured||!e.PublicKey)return Pt.Unsupported;if(this.isEmbedded())return Pt.Embedded;if(!this.isSupported())return Pt.Unsupported;let t=Notification.permission;return t==="denied"?Pt.Blocked:t!=="granted"?Pt.Idle:await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription()?Pt.Subscribed:Pt.Idle}async subscribe(e={}){let t=await this.getConfig();if(!t.Configured||!t.PublicKey)return b("client","Push notifications are not available for this title.");if(this.isEmbedded())return await du(this.ctx.settings.titleID)?a({Where:"portal",Subscription:null}):b("client","The portal did not complete the subscription.");if(!this.isSupported())return b("client","This browser has no Push API.");let i=await Notification.requestPermission();if(i!=="granted")return b("client",i==="denied"?"The player blocked notifications for this site.":"The player dismissed the permission prompt.");let s=await navigator.serviceWorker.register(e.swPath??"./sw.js");await navigator.serviceWorker.ready;let r=await s.pushManager.getSubscription()??await s.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:ry(t.PublicKey)}),p=this.ctx.authedRequest();if(!p)return c$1;let d=r.toJSON();p.PushEndpoint=d.endpoint,p.PushP256dh=d.keys?.p256dh,p.PushAuth=d.keys?.auth,p.PushTransport="WebPush",p.PushLocale=e.locale??navigator.language,p.PushTimezoneOffsetMinutes=-new Date().getTimezoneOffset();let C=await this.ctx.api.push.subscribePush(p);return C.ok?(this.ctx.emitter.emit("push:subscribed",C.data),a({Where:"game",Subscription:C.data})):C}async unsubscribe(){let e=this.ctx.authedRequest();if(!e)return c$1;if(this.isSupported()){let s=await(await navigator.serviceWorker.getRegistration())?.pushManager.getSubscription();s&&(e.PushEndpoint=s.endpoint,await s.unsubscribe());}if(!e.PushEndpoint)return b("client","This browser has no push subscription to remove.");let t=await this.ctx.api.push.unsubscribePush(e);return t.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),t}async getSubscriptions(){let e=this.ctx.authedRequest();return e?await this.ctx.api.push.getPushSubscriptions(e):c$1}async unsubscribeByHash(e){if(!e)return b("client","endpointHash is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.PushEndpointHash=e;let i=await this.ctx.api.push.unsubscribePush(t);return i.ok&&this.ctx.emitter.emit("push:unsubscribed",void 0),i}isSupported(){return typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window}isEmbedded(){return typeof window<"u"&&window.self!==window.top}};function ry(o){let e=o.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(o.length/4)*4,"="),t=atob(e),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return i}var Ts=Object.freeze({}),ks=class{constructor(e){this.ctx=e;}ctx;table={...Ts};fallbackTable=null;currentLocale=null;currentFallbackLocale=null;pluralRules=null;get cache(){return this.tableCache??=new ui(this.ctx.settings.configStorage,this.ctx.settings.titleID)}tableCache;get locale(){return this.currentLocale}get fallbackLocale(){return this.currentFallbackLocale}get locales(){let e=this.ctx.data.config.titlePublicConfiguration?.Localization??null;return e?.Locales?Object.entries(e.Locales).filter(([,t])=>t?.IsEnabled!==false).map(([t,i])=>({Locale:i?.Locale??t,DisplayName:i?.DisplayName??null,Order:i?.Order??0})).sort((t,i)=>(t.Order??0)-(i.Order??0)):[]}has(e){return this.lookup(e)!==void 0}t(e,t){if(!e)return "";let i=this.resolveKey(e,t),s=this.lookup(i)??this.lookup(e);return s===void 0?this.onMissing(e):t?oy(s,t):s}applyState(e,t){if(!e){this.reset();return}let i=e.Locale??null;this.table=t.table??{...Ts},this.fallbackTable=t.fallbackTable,this.currentFallbackLocale=e.Fallback?.Locale??null,this.setLocaleInternal(i),this.ctx.emitter.emit("localization:changed",{locale:i,fallbackLocale:this.currentFallbackLocale,entryCount:Object.keys(this.table).length});}async setLocale(e){if(!this.baseRequest())return c$1;let i=await this.loadTableFromApi(e);if(!i.ok)return i;let{locale:s,table:n,fallbackLocale:r}=i.data,p=null;if(r){let d=await this.loadTableFromApi(r);d.ok&&(p=d.data.table);}return this.table=n,this.fallbackTable=p,this.currentFallbackLocale=r,this.setLocaleInternal(s),this.ctx.emitter.emit("localization:changed",{locale:s,fallbackLocale:r,entryCount:Object.keys(n).length}),{ok:true,data:s}}async getManifest(){let e=this.baseRequest();return e?(e.Locale=this.currentLocale??this.ctx.settings.locale,this.ctx.api.localization.getLocalizationManifest(e)):c$1}reset(){this.table={...Ts},this.fallbackTable=null,this.currentFallbackLocale=null,this.setLocaleInternal(null);}setLocaleInternal(e){this.currentLocale=e,this.pluralRules=null;}baseRequest(){let e=this.ctx.auth.context;return e?{UserID:e.userID,ClientSessionTicket:e.clientSessionTicket,BuildKey:this.ctx.settings.buildKey,RelatedEntityID:d()}:null}async loadTableFromApi(e){let t=this.baseRequest();if(!t)return c$1;t.Locale=e;let i=await this.cache.read(mu(e));i&&(t.KnownVersion=i.v);let s=await this.ctx.api.localization.getLocalizationTable(t);if(!s.ok)return s;let n=s.data,r=n.Locale??mu(e),p=n.Version??0;if(n.NotModified){let C=i??await this.cache.read(r);return {ok:true,data:{locale:r,table:C?.t??{...Ts},fallbackLocale:n.FallbackLocale??null}}}let d=n.Entries??{};return p>0&&await this.cache.write(r,p,d),{ok:true,data:{locale:r,table:d,fallbackLocale:n.FallbackLocale??null}}}lookup(e){let t=this.table[e];return t!==void 0?t:this.fallbackTable?.[e]}resolveKey(e,t){let i=t?.count;if(typeof i!="number")return e;let s=this.pluralCategory(i),n=`${e}.${s}`;if(this.lookup(n)!==void 0)return n;let r=`${e}.other`;return this.lookup(r)!==void 0?r:e}pluralCategory(e){try{return this.pluralRules??=new Intl.PluralRules(this.currentLocale??void 0),this.pluralRules.select(e)}catch{return "other"}}onMissing(e){let t=this.ctx.data.config.titlePublicConfiguration?.Localization?.MissingKeyMode??"ReturnKey";return t==="ReturnEmpty"?"":t==="ReturnMarkedKey"?`\u27E6${e}\u27E7`:e}};function oy(o,e){return o.replace(/\{(\w+)\}/g,(t,i)=>{let s=e[i];return s===void 0?t:String(s)})}function mu(o){return o.trim().replace(/_/g,"-").toLowerCase()}var mo="Quest",ay={key:"quest.state",dependsOn:["Quest","EventToken"],expiresAt:o=>{let e=Date.now(),t=null,i=[...Object.values(o.PointsTracks??{}).map(s=>s?.CycleEndUtc),...Object.values(o.State?.Cycles??{}).map(s=>s?.CycleEndUtc)];for(let s of i){let n=Date.parse(s??"");!Number.isNaN(n)&&n>e&&(t===null||n<t)&&(t=n);}return t}},zs=class{constructor(e){this.ctx=e;let t=0;e.emitter.on("auth:loggedOut",()=>t=0),e.cache.defineStateRule("Quest",{needsServer:i=>{let s=e.cache.configSection(mo)?.Cycles;if(!s)return false;let n=e.data.user.state?.Quest?.Cycles??{};for(let r of Object.keys(s)){let p=Date.parse(n[r]?.CycleEndUtc??"");if(Number.isNaN(p)){if(t===0)return true}else if(p<=i&&t<p)return true}return false},refresh:async()=>{let i=await this.getUserQuestState(true,{forceRefresh:true});return i.ok&&(t=Date.now()),i}});}ctx;async getQuestDefinitions(e){let t=this.ctx.cache.configSection(mo,e);if(t)return this.ctx.emitter.emit("quest:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.quest.getQuestDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(mo,s.data),this.ctx.emitter.emit("quest:definitionsLoaded",s.data)),s}getUserQuestState(e=true,t){return this.ctx.cache.read(ay,()=>this.fetchUserQuestState(e),{...t,args:e?void 0:"manual"})}async fetchUserQuestState(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.AutoRefreshCycles=e;let i=await this.ctx.api.quest.getUserQuestState(t);if(i.ok){let s=i.data.State??{};this.ctx.data.user.applyQuest(s),this.ctx.data.user.patchQuestPointsTracks(i.data.PointsTracks),this.ctx.emitter.emit("quest:userStateLoaded",s);}return i}async refreshQuestCycles(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.quest.refreshQuestCycles(e);return t.ok&&this.ctx.emitter.emit("quest:cyclesRefreshed",void 0),t}async claimQuestReward(e,t){let i=e.trim();if(!i)return b("client","QuestID is required.");if(!this.ctx.auth.context)return c$1;let s=t&&t.trim().length>0?t.trim():void 0,n={...this.ctx.buildAuthedBaseRequest(),QuestID:i,CycleID:s,RelatedEntityID:`quest_claim_${s??""}_${i}_${d()}`},r=await this.ctx.api.quest.claimQuestReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchQuestStatus(p.QuestID,p.CycleID,"Claimed"),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:rewardClaimed",p);}return r}async claimQuestRewardsBatch(e){if(!e||e.length===0)return b("client","quests is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Quests:e},i=await this.ctx.api.quest.claimQuestRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchQuestStatus(n.Data.QuestID,n.Data.CycleID,"Claimed"),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:rewardsClaimedBatch",i.data);}return i}async claimMilestoneReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,MilestoneID:s,RelatedEntityID:`milestone_claim_${i}_${s}_${d()}`},r=await this.ctx.api.quest.claimMilestoneReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchMilestoneClaimed(p.CycleID,p.MilestoneID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:milestoneClaimed",p);}return r}async claimMilestoneRewardsBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.quest.claimMilestoneRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!n.Success||!n.Data||(this.ctx.data.user.patchMilestoneClaimed(n.Data.CycleID,n.Data.MilestoneID),!s&&n.Data.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true));this.ctx.emitter.emit("quest:milestonesClaimedBatch",i.data);}return i}async claimGroupCompletionReward(e,t){let i=e.trim(),s=t.trim();if(!i||!s)return b("client","CycleID and GroupCompletionID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CycleID:i,GroupCompletionID:s,RelatedEntityID:`group_completion_${i}_${s}_${d()}`},r=await this.ctx.api.quest.claimGroupCompletionReward(n);if(r.ok){let p=r.data;this.ctx.data.user.patchGroupCompletionClaimed(p.CycleID,p.GroupCompletionID),this.ctx.data.user.applyResourcesWithDelta(p.Resources,p.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("quest:groupCompletionClaimed",p);}return r}async addQuestProgress(e,t){let i=e.trim();if(!i)return b("client","MetricID is required.");if(t<0)return b("client","ProgressValue must be >= 0.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),MetricID:i,ProgressValue:t},n=await this.ctx.api.quest.addQuestProgress(s);return n.ok&&(this.ctx.data.user.patchQuestProgressUpdates(n.data.Updates),this.ctx.emitter.emit("quest:progressAdded",n.data)),n}};var fu=z.object({}).passthrough().transform(o=>o);var ly=z.object({Order:z.number().nullish(),Type:z.string().nullish(),DurationSec:z.number().nullish(),BonusMultiplier:z.number().nullish()}).passthrough(),uy=z.object({Schedule:z.array(ly).nullish(),RepeatCycle:z.boolean().nullish(),MaxCycles:z.number().nullish()}).passthrough(),cy=z.object({IsActive:z.boolean().nullish(),CurrentPhaseEndUtc:c.nullish(),NextBonusStartUtc:c.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentPhaseIndex:z.number().nullish(),ActiveBonusMultiplier:z.number().nullish()}).passthrough(),py=z.object({Milestones:K.nullish()}).passthrough(),fo=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Category:z.string().nullish(),Token:jt.nullish(),TokenSources:z.array(st).nullish(),ClaimMode:z.string().nullish(),Milestones:z.record(z.string(),Be).nullish(),Presets:py.nullish(),BonusWindow:uy.nullish()}).passthrough(),hy=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Content:fo.nullish(),ClaimGraceHours:z.number().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),dy=z.object({TimedEventID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Schedule:me.nullish(),Content:fo.nullish(),Events:z.array(hy).nullish(),Gate:J.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),my=z.object({MaxConcurrentEvents:z.number().nullish()}).passthrough(),fy=z.object({Milestones:z.record(z.string(),ni).nullish()}).passthrough(),As=z.object({Definitions:z.record(z.string(),dy).nullish(),Settings:my.nullish(),Presets:fy.nullish()}).passthrough(),gy=z.object({Type:xi,TimedEventID:z.string(),CurrentChainedEventID:z.string().nullish(),Content:fo.nullish(),Progress:fu.nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),CanEarn:z.boolean().nullish(),CanClaim:z.boolean().nullish(),NextMilestone:Be.nullish(),BonusWindow:cy.nullish(),CurrentCycleIndex:z.number().nullish(),CurrentEventOrder:z.number().nullish(),TotalEventsInChain:z.number().nullish(),TokenEntityID:z.string().nullish()}).passthrough(),ws=z.object({ActiveEvents:z.array(gy).nullish()}).passthrough(),gu=z.object({Tokens:z.record(z.string(),fu).nullish()}),go=z.object({Type:xi.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),yo=z.object({Type:xi.nullish(),LteID:z.string().nullish(),MilestoneID:z.string().nullish(),TokenEntityID:z.string().nullish(),Rewards:M.nullish(),Inventory:Q.nullish()}),yy=z.object({Type:xi.nullish(),LteID:z.string().nullish(),Resources:M.nullish()}),Ro=z.array(Pe(yo)),yu=z.array(Pe(go)),Ru=z.array(Pe(yy)),ot={GetActiveEvents:"GetActiveEvents",GrantTokens:"GrantTokens",SpendTokens:"SpendTokens",ClaimMilestone:"ClaimMilestone",GetDefinitions:"GetDefinitions",GetUserLteState:"GetUserLteState",ClaimMilestonesBatch:"ClaimMilestonesBatch",ClaimAllMilestones:"ClaimAllMilestones",SpendTokensBatch:"SpendTokensBatch",GrantTokensBatch:"GrantTokensBatch"};var Cu="TimedEvent",Su={key:"timedEvent.active",login:"ActiveEvents",ttlMs:5*6e4,dependsOn:["EventToken"],invalidateOn:["timedEvent:tokensGranted","timedEvent:tokensGrantedBatch","timedEvent:tokensSpent","timedEvent:tokensSpentBatch","timedEvent:milestoneClaimed","timedEvent:milestonesClaimedBatch","timedEvent:allMilestonesClaimed"],expiresAt:o=>{let e=null;for(let t of o.ActiveEvents??[]){let i=Date.parse(t.ComputedEndUtc??"");!Number.isNaN(i)&&(e===null||i<e)&&(e=i);}return e}},Ms=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Su,{schema:ws,apply:t=>this.applyActiveEvents(t)});}ctx;getActiveEvents(e){return this.ctx.cache.read(Su,()=>this.fetchActiveEvents(),e)}async fetchActiveEvents(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedEvent.getActiveEvents(e);return t.ok&&this.applyActiveEvents(t.data),t}applyActiveEvents(e){this.ctx.data.user.applyActiveEvents(e),this.ctx.emitter.emit("timedEvent:activeEventsLoaded",e);}async getDefinitions(e){let t=this.ctx.cache.configSection(Cu,e);if(t)return this.ctx.emitter.emit("timedEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.timedEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Cu,s.data),this.ctx.emitter.emit("timedEvent:definitionsLoaded",s.data)),s}async getUserLteState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedEvent.getUserLteState(e);return t.ok&&(this.ctx.data.user.applyUserLteState(t.data),this.ctx.emitter.emit("timedEvent:userStateLoaded",t.data)),t}async grantTokens(e,t,i,s,n,r,p=1){if(!t)return b("client","LteID is required.");if(!i)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c$1;let d={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SourceType:i,Outcome:s,AmountOverride:n,SourceParams:r,RollMultiplier:p},C=await this.ctx.api.timedEvent.grantTokens(d);return C.ok&&(this.ctx.data.user.applyResourceOperation(C.data,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensGranted",C.data)),C}async spendTokens(e,t,i){if(!t)return b("client","LteID is required.");if(i<=0)return b("client","SpendAmount must be positive.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,SpendAmount:i},n=await this.ctx.api.timedEvent.spendTokens(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedEvent:tokensSpent",n.data)),n}async claimMilestone(e,t,i){if(!t||!i)return b("client","LteID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),Type:e,LteID:t,MilestoneID:i},n=await this.ctx.api.timedEvent.claimMilestone(s);if(n.ok){let r=n.data;this.ctx.data.user.applyResourcesWithDelta(r.Rewards,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchTimedEventMilestoneClaimed(e,t,i,r.TokenEntityID),this.ctx.emitter.emit("timedEvent:milestoneClaimed",r);}return n}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.timedEvent.claimMilestonesBatch(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:milestonesClaimedBatch",i.data)),i}async claimAllMilestones(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&e.length>0&&(t.Events=e);let i=await this.ctx.api.timedEvent.claimAllMilestones(t);return i.ok&&(this.applyMilestoneClaimBatch(i.data),this.ctx.emitter.emit("timedEvent:allMilestonesClaimed",i.data)),i}async spendTokensBatch(e){if(!e||e.length===0)return b("client","spends is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Spends:e},i=await this.ctx.api.timedEvent.spendTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensSpentBatch",i.data);}return i}async grantTokensBatch(e){if(!e||e.length===0)return b("client","grants is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Grants:e},i=await this.ctx.api.timedEvent.grantTokensBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourceOperation(n.Data.Resources,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("timedEvent:tokensGrantedBatch",i.data);}return i}applyMilestoneClaimBatch(e){let t=false;for(let i of e){if(!i.Success||!i.Data)continue;let s=i.Data;s.Type&&s.LteID&&s.MilestoneID&&this.ctx.data.user.patchTimedEventMilestoneClaimed(s.Type,s.LteID,s.MilestoneID,s.TokenEntityID),!t&&s.Rewards&&(this.ctx.data.user.applyResourcesWithDelta(s.Rewards,s.Inventory,this.ctx.data.config.itemDefinitions),t=true);}}};var Ry=z.object({UserID:z.string(),Score:_.nullish(),Rank:z.number().nullish(),LastScoreUpdateUtc:c.nullish(),IpHash:z.string().nullish(),PublicProfile:Oe.nullish(),SeasonTierAtCycleEnd:z.number().nullish()}).passthrough(),Di=z.object({LeaderboardID:z.string(),CycleVersion:z.number().nullish(),TotalParticipants:_.nullish(),CycleEndUtc:c.nullish(),TopUsers:z.array(Ry).nullish(),BracketID:z.string().nullish()}),Cy=z.object({CycleKey:z.string().nullish(),CycleEndUtc:c.nullish(),ClaimDeadlineUtc:c.nullish(),MilestoneTokensEarned:_.nullish(),ClaimableMilestoneIDs:z.array(z.string()).nullish(),CycleIndex:z.number().nullish(),ChainedEventID:z.string().nullish()}).passthrough(),Os=z.object({LeaderboardID:z.string(),CurrentScore:_.nullish(),LastKnownRank:z.number().nullish(),HasUnclaimedReward:z.boolean().nullish(),UnclaimedRewardRank:z.number().nullish(),ScoreEarnedThisCycle:_.nullish(),MilestoneTokensEarned:_.nullish(),TokenEntityID:z.string().nullish(),NextMilestone:Be.nullish(),HasUnclaimedMilestone:z.boolean().nullish(),GrantedPremiumTiers:z.record(z.string(),z.array(z.string())).nullish(),ClaimableGraceCycles:z.array(Cy).nullish()}),Us=z.object({LeaderboardID:z.string(),NewScore:_,CycleVersion:z.number()}),Es=z.object({ServerTimeUtc:c,LeaderboardID:z.string(),Rank:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),qs=z.object({ServerTimeUtc:c,LeaderboardID:z.string(),MilestoneID:z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),xu=z.array(Pe(Di)),Bs=z.array(Pe(Os)),bu=z.array(Pe(Es)),Du=z.array(Pe(qs)),Pu=z.array(Pe(Us)),Sy=z.object({LeaderboardID:z.string(),CycleReward:Pe(Es).nullish(),Milestones:z.array(Pe(qs)).nullish()}),Iu=z.array(Sy),xy=z.object({LeaderboardID:z.string(),Leaderboard:Pe(Di).nullish(),Progress:Pe(Os).nullish()}),vu=z.array(xy),by=z.string(),Tu=z.object({Rank:z.string().nullish(),Rewards:H.nullish(),SeasonTierRewards:Hr.nullish()}).passthrough(),Dy=z.object({RankRewards:z.array(Tu).nullish()}).passthrough(),Py=z.object({ChainedEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),ClaimGraceHours:z.number().nullish()}).passthrough(),Iy=z.object({Milestones:K.nullish(),RankRewards:K.nullish()}).passthrough(),vy=z.object({LeaderboardID:z.string(),DisplayName:z.string().nullish(),ScoreDisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),IsEnabled:z.boolean().nullish(),ScoreAggregation:by.nullish(),Schedule:me.nullish(),ChainEvents:z.array(Py).nullish(),Gate:J.nullish(),TopUsersLimit:z.number().nullish(),MinScoreToEnterTop:z.number().nullish(),BracketSize:z.number().nullish(),LinkedSeasonChainID:z.string().nullish(),RankRewards:z.array(Tu).nullish(),Milestones:z.record(z.string(),Be).nullish(),Presets:Iy.nullish(),MilestoneClaimMode:z.string().nullish(),MilestoneClaimGraceHours:z.number().nullish(),ScoreSources:z.array(st).nullish()}).passthrough(),Ty=z.object({Milestones:z.record(z.string(),ni).nullish(),RankRewards:z.record(z.string(),Dy).nullish()}).passthrough(),Ls=z.object({Definitions:z.record(z.string(),vy).nullish(),Presets:Ty.nullish()}).passthrough(),Ve={GetDefinitions:"GetDefinitions",GetLeaderboard:"GetLeaderboard",GetMyProgress:"GetMyProgress",SubmitScore:"SubmitScore",SubmitScoreFromSource:"SubmitScoreFromSource",ClaimCycleReward:"ClaimCycleReward",ClaimMilestone:"ClaimMilestone",GetFriendsLeaderboard:"GetFriendsLeaderboard",GetLeaderboardsBatch:"GetLeaderboardsBatch",GetProgressBatch:"GetProgressBatch",ClaimCycleRewardsBatch:"ClaimCycleRewardsBatch",ClaimMilestonesBatch:"ClaimMilestonesBatch",SubmitScoresBatch:"SubmitScoresBatch",ClaimAllRewardsBatch:"ClaimAllRewardsBatch",GetOverviewBatch:"GetOverviewBatch"};var ku="Leaderboard",zu={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"]},Gs=class{constructor(e){this.ctx=e;e.cache.bindLoginView(zu,{schema:Bs,apply:t=>this.applyProgressBatch(t)});}ctx;cycleDocID(e){return `${this.ctx.settings.titleID}_${e}`}async getDefinitions(e){let t=this.ctx.cache.configSection(ku,e);if(t)return this.ctx.emitter.emit("leaderboard:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.leaderboard.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ku,s.data),this.ctx.emitter.emit("leaderboard:definitionsLoaded",s.data)),s}async getLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loaded",i.data),i}async getMyProgress(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getMyProgress(t);return i.ok&&(this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(e),i.data),this.ctx.emitter.emit("leaderboard:myProgressLoaded",i.data)),i}async submitScore(e,t){if(!e)return b("client","LeaderboardID is required.");if(t<=0)return b("client","Score must be positive.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,Score:t},s=await this.ctx.api.leaderboard.submitScore(i);if(s.ok){let n=s.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),n.NewScore,t,n.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",n);}return s}async submitScoreFromSource(e,t,i,s,n=1){if(!e)return b("client","LeaderboardID is required.");if(!t)return b("client","SourceType is required.");if(!this.ctx.auth.context)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,SourceType:t,Outcome:i,Params:s,RollMultiplier:n},p=await this.ctx.api.leaderboard.submitScoreFromSource(r);if(p.ok){let d=p.data;this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(e),d.NewScore,d.NewScore,d.CycleVersion),this.ctx.emitter.emit("leaderboard:scoreSubmitted",d);}return p}async claimCycleReward(e){if(!e)return b("client","LeaderboardID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e},i=await this.ctx.api.leaderboard.claimCycleReward(t);if(i.ok){let s=i.data;this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(e)),this.ctx.data.user.applyResourcesWithDelta(s.Resources,s.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:cycleRewardClaimed",s);}return i}async claimMilestone(e,t,i){if(!e||!t)return b("client","LeaderboardID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),LeaderboardID:e,MilestoneID:t,...i?{CycleKey:i}:{}},n=await this.ctx.api.leaderboard.claimMilestone(s);if(n.ok){let r=n.data;i||this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(e),t),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("leaderboard:milestoneClaimed",r);}return n}async getFriendsLeaderboard(e){if(!e)return b("client","LeaderboardID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardID=e;let i=await this.ctx.api.leaderboard.getFriendsLeaderboard(t);return i.ok&&this.ctx.emitter.emit("leaderboard:friendsLoaded",i.data),i}async getLeaderboardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getLeaderboardsBatch(t);return i.ok&&this.ctx.emitter.emit("leaderboard:loadedBatch",i.data),i}getProgressBatch(e,t){return !e||e.length===0?Promise.resolve(b("client","leaderboardIDs is required.")):this.ctx.cache.read(zu,()=>this.fetchProgressBatch(e),{...t,args:[...e].sort().join(","),loginParams:{LeaderboardIDs:[...e].sort()}})}async fetchProgressBatch(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getProgressBatch(t);return i.ok&&this.applyProgressBatch(i.data),i}applyProgressBatch(e){for(let t of e)!t.Success||!t.Data||this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(t.Data.LeaderboardID),t.Data);this.ctx.emitter.emit("leaderboard:myProgressLoadedBatch",e);}async claimCycleRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimCycleRewardsBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(this.cycleDocID(s.Data.LeaderboardID)),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:cycleRewardsClaimedBatch",i.data);}return i}async claimMilestonesBatch(e){if(!e||e.length===0)return b("client","milestones is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Milestones:e},i=await this.ctx.api.leaderboard.claimMilestonesBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(this.cycleDocID(s.Data.LeaderboardID),s.Data.MilestoneID),s.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.Data.Resources,s.Data.Inventory,this.ctx.data.config.itemDefinitions));this.ctx.emitter.emit("leaderboard:milestonesClaimedBatch",i.data);}return i}async submitScoresBatch(e){if(!e||e.length===0)return b("client","scores is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Scores:e},i=await this.ctx.api.leaderboard.submitScoresBatch(t);if(i.ok){for(let s of i.data)!s.Success||!s.Data||this.ctx.data.user.patchLeaderboardScoreSubmitted(this.cycleDocID(s.Data.LeaderboardID),s.Data.NewScore,s.Data.NewScore,s.Data.CycleVersion);this.ctx.emitter.emit("leaderboard:scoresSubmittedBatch",i.data);}return i}async claimAllRewardsBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LeaderboardIDs:e},i=await this.ctx.api.leaderboard.claimAllRewardsBatch(t);if(i.ok){for(let s of i.data){let n=this.cycleDocID(s.LeaderboardID);s.CycleReward?.Success&&s.CycleReward.Data&&(this.ctx.data.user.patchLeaderboardCycleRewardClaimed(n),s.CycleReward.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.CycleReward.Data.Resources,s.CycleReward.Data.Inventory,this.ctx.data.config.itemDefinitions));for(let r of s.Milestones??[])!r.Success||!r.Data||(this.ctx.data.user.patchLeaderboardMilestoneClaimed(n,r.Data.MilestoneID),r.Data.Resources&&this.ctx.data.user.applyResourcesWithDelta(r.Data.Resources,r.Data.Inventory,this.ctx.data.config.itemDefinitions));}this.ctx.emitter.emit("leaderboard:allRewardsClaimedBatch",i.data);}return i}async getOverviewBatch(e){if(!e||e.length===0)return b("client","leaderboardIDs is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.LeaderboardIDs=e;let i=await this.ctx.api.leaderboard.getOverviewBatch(t);if(i.ok){for(let s of i.data)s.Progress?.Success&&s.Progress.Data&&this.ctx.data.user.patchLeaderboardMyProgress(this.cycleDocID(s.LeaderboardID),s.Progress.Data);this.ctx.emitter.emit("leaderboard:overviewLoadedBatch",i.data);}return i}};var Co=z.object({}).passthrough().transform(o=>o),Fs=z.object({SeasonChainID:z.string(),CycleIndex:z.number().nullish(),Season:z.lazy(()=>Ou).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:_.nullish(),UserState:Co.nullish(),NextTier:z.lazy(()=>Mu).nullish()}).passthrough(),Au=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),AmountGranted:_.nullish(),NewStatusTokens:_.nullish(),OldTier:z.number().nullish(),NewTier:z.number(),TierUp:z.boolean().nullish()}),So=z.object({SeasonChainID:z.string(),CurrentSeasonID:z.string().nullish(),TierNumber:z.number(),Resources:M.nullish(),Inventory:Q.nullish()}),wu=ft(So);var Mu=z.object({Tier:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RequiredTokens:_.nullish(),TierReachedReward:H.nullish()}).passthrough(),Ou=z.object({SeasonID:z.string().nullish(),Order:z.number().nullish(),DurationSec:_.nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(Mu).nullish(),LinkedCollectionID:z.string().nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough();var ky=z.object({SeasonChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:me.nullish(),Seasons:z.array(Ou).nullish(),GrantTokensAccessMode:z.string().nullish(),Gate:J.nullish()}).passthrough(),Vs=z.object({Chains:z.record(z.string(),ky).nullish()}).passthrough(),Ot={GetDefinitions:"GetDefinitions",GetActiveSeason:"GetActiveSeason",GetUserState:"GetUserState",GrantStatusTokens:"GrantStatusTokens",ClaimTierReward:"ClaimTierReward",ClaimTierRewardsBatch:"ClaimTierRewardsBatch"};var Uu="Season",Eu={key:"season.active",login:"ActiveSeason",ttlMs:5*6e4,dependsOn:["Season","EventToken","Premium"],invalidateOn:["season:statusTokensGranted","season:tierRewardClaimed","season:tierRewardsBatchClaimed","premium:purchaseCompleted","premium:realMoneyPurchaseCompleted","premium:trialActivated"],expiresAt:o=>{let e=Date.parse(o.ComputedEndUtc??"");return Number.isNaN(e)?null:e}},js=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Eu,{schema:Fs,apply:(t,i)=>this.applyActiveSeason(i??t.SeasonChainID,t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Uu,e);if(t)return this.ctx.emitter.emit("season:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.season.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Uu,s.data),this.ctx.emitter.emit("season:definitionsLoaded",s.data)),s}getActiveSeason(e,t){return e?this.ctx.cache.read(Eu,()=>this.fetchActiveSeason(e),{...t,args:e,loginParams:{SeasonChainID:e}}):Promise.resolve(b("client","SeasonChainID is required."))}async fetchActiveSeason(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.SeasonChainID=e;let i=await this.ctx.api.season.getActiveSeason(t);return i.ok&&this.applyActiveSeason(e,i.data),i}applyActiveSeason(e,t){t.UserState&&this.ctx.data.user.patchSeasonState(e,t.UserState),this.ctx.emitter.emit("season:activeLoaded",t);}async getUserState(e){if(!e)return b("client","SeasonChainID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.SeasonChainID=e;let i=await this.ctx.api.season.getUserState(t);return i.ok&&(this.ctx.data.user.patchSeasonState(e,i.data),this.ctx.emitter.emit("season:userStateLoaded",i.data)),i}async grantStatusTokens(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","Amount must be positive.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,Amount:t,RelatedEntityID:`season_grant_${e}_${d()}`},s=await this.ctx.api.season.grantStatusTokens(i);return s.ok&&(this.ctx.data.user.patchSeasonCurrentTier(e,s.data.NewTier),this.ctx.emitter.emit("season:statusTokensGranted",s.data)),s}async claimTierReward(e,t){if(!e)return b("client","SeasonChainID is required.");if(t<=0)return b("client","TierNumber must be positive.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumber:t,RelatedEntityID:`season_tier_${e}_t${t}_${d()}`},s=await this.ctx.api.season.claimTierReward(i);if(s.ok){let n=s.data;this.ctx.data.user.patchSeasonClaimedTier(e,t),this.ctx.data.user.applyResourcesWithDelta(n.Resources,n.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardClaimed",n);}return s}async claimTierRewardsBatch(e,t){if(!e)return b("client","SeasonChainID is required.");let i=(t??[]).filter(r=>r>0);if(i.length===0)return b("client","TierNumbers is required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),SeasonChainID:e,TierNumbers:i,RelatedEntityID:`season_tier_batch_${e}_${d()}`},n=await this.ctx.api.season.claimTierRewardsBatch(s);if(n.ok){let r=n.data;for(let p of r.Items??[]){let d=p.Data?.TierNumber;p.Success&&typeof d=="number"&&this.ctx.data.user.patchSeasonClaimedTier(e,d);}this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("season:tierRewardsBatchClaimed",r);}return n}};var qu="Premium",Ns=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(qu,e);if(t){let n={Premium:t};return this.ctx.emitter.emit("premium:definitionsLoaded",n),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.premium.getDefinitions(i);return s.ok&&s.data.Premium&&(this.ctx.data.config.patchSection(qu,s.data.Premium),this.ctx.emitter.emit("premium:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.premium.getUserState(e);return t.ok&&t.data.Premium&&(this.ctx.data.user.applyPremium(t.data.Premium),this.ctx.emitter.emit("premium:stateLoaded",t.data)),t}async activateTrial(e,t){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,RelatedEntityID:`premium_trial_${e}_${t}`},s=await this.ctx.api.premium.activateTrial(i);return s.ok&&(s.data.Premium&&this.ctx.data.user.applyPremium(s.data.Premium),this.ctx.emitter.emit("premium:trialActivated",s.data)),s}async purchaseItemOrCurrency(e,t,i="Default",s=1){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,SelectedOptionID:i,Count:s,RelatedEntityID:`premium_purchase_${e}_${t}`},r=await this.ctx.api.premium.purchaseItemOrCurrency(n);if(r.ok){let p=r.data;p.Premium&&this.ctx.data.user.applyPremium(p.Premium),this.ctx.data.user.applyResourceOperation(p.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:purchaseCompleted",p);}return r}async purchaseRealMoney(e,t,i,s,n,r,p,d){if(!e||!t)return b("client","PremiumID and TransactionID are required.");if(!s||!n)return b("client","ProductID and ReceiptData are required.");if(!this.ctx.auth.context)return c$1;let C={...this.ctx.buildAuthedBaseRequest(),PremiumID:e,TransactionID:t,Store:i,ProductID:s,ReceiptData:n,PurchaseToken:r,PackageName:p,AppStoreEnvironment:d,RelatedEntityID:`premium_iap_${e}_${t}`},j=await this.ctx.api.premium.purchaseRealMoney(C);if(j.ok){let ue=j.data;ue.Premium&&this.ctx.data.user.applyPremium(ue.Premium),this.ctx.data.user.applyResourceOperation(ue.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("premium:realMoneyPurchaseCompleted",ue);}return j}};var _s=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),ItemInstanceID:z.string().nullish(),Level:z.number().nullish(),EquippedAt:c.nullish()}),xo=z.object({CharacterID:z.string(),Level:z.number().nullish(),Experience:_.nullish(),Power:z.number().nullish(),StatLevels:z.record(z.string(),z.number()).nullish(),Equipment:z.record(z.string(),_s).nullish(),UpdatedAt:c.nullish()}).passthrough(),Bu=z.object({Characters:z.record(z.string(),xo).nullish()}),bo=z.object({ServerTimeUtc:c,CharacterID:z.string(),StatID:z.string(),StatLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),Do=z.object({ServerTimeUtc:c,CharacterID:z.string(),NewLevel:z.number(),Power:z.number().nullish(),Resources:M.nullish()}),Lu=z.object({ServerTimeUtc:c,CharacterID:z.string(),Equipment:z.record(z.string(),_s).nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),Gu=z.object({ServerTimeUtc:c,CharacterID:z.string(),ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),zy=z.object({ClearedSlotIDs:z.array(z.string()).nullish(),Power:z.number().nullish()}),Fu=z.object({ServerTimeUtc:c,Characters:z.record(z.string(),zy).nullish(),Inventory:Q.nullish()}),Po=z.object({ServerTimeUtc:c,CharacterID:z.string(),Power:z.number().nullish(),Resources:M.nullish()}),Vu=z.object({ServerTimeUtc:c,CharacterID:z.string(),SkinID:z.string(),Resources:M.nullish(),Inventory:Q.nullish(),Equipped:z.boolean().nullish(),EquipError:z.string().nullish(),Equipment:_s.nullish(),Power:z.number().nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish()}),ju=z.object({ServerTimeUtc:c,CharacterID:z.string(),SkinID:z.string(),Equipped:_s.nullish(),ReplacedInstanceIDs:z.array(z.string()).nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),Nu=z.object({ServerTimeUtc:c,CharacterID:z.string(),Cleared:z.boolean().nullish(),Power:z.number().nullish(),Inventory:Q.nullish()}),Ay=z.object({SkinID:z.string(),IsDefault:z.boolean().nullish(),Misconfigured:z.string().nullish(),Owned:z.boolean().nullish(),OwnedCopies:z.number().nullish(),IsWorn:z.boolean().nullish(),MeetsRequirements:z.boolean().nullish(),SoldDirectly:z.boolean().nullish(),OnSale:z.boolean().nullish(),SaleEndsAtUtc:c.nullish(),GateOpen:z.boolean().nullish(),Purchasable:z.boolean().nullish(),PriceOptions:ae.nullish()}),wy=z.object({CharacterID:z.string(),CharacterOpen:z.boolean().nullish(),DefaultSkinID:z.string().nullish(),WornSkinID:z.string().nullish(),Skins:z.array(Ay).nullish()}),_u=z.object({ServerTimeUtc:c,Characters:z.record(z.string(),wy).nullish()}),Wu=ft(Po),Ku=ft(Do),Qu=ft(bo),Io=z.object({RequiredStatID:z.string(),RequiredLevel:z.number()}).passthrough(),Hu=z.object({StatID:z.string(),TypeID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),MaxLevel:z.number().nullish(),Weight:z.number().nullish(),PriceOptions:ae.nullish(),CostCurve:Fe.nullish(),BaseStatValue:z.number().nullish(),ValueCurve:Fe.nullish(),RankCurve:Fe.nullish(),Requirements:z.array(Io).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),My=z.object({SlotID:z.string(),MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Io).nullish(),AllowedRarityIDs:z.array(z.string()).nullish(),AllowedItemTags:z.array(z.string()).nullish(),MinItemLevel:z.number().nullish(),MaxItemLevel:z.number().nullish()}).passthrough(),$u=z.object({Slots:z.record(z.string(),My).nullish()}).passthrough(),Ju=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Lore:z.string().nullish(),SortOrder:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Oy=z.object({ClassID:z.string().nullish(),RarityID:z.string().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),Uy=z.object({UnlockedByDefault:z.boolean().nullish(),PriceOptions:ae.nullish()}).passthrough(),Ey=z.object({Stats:K.nullish(),Levels:K.nullish(),Equipment:K.nullish()}).passthrough(),Zu=z.object({MaxRank:z.number().nullish(),FirstPaidRank:z.number().nullish(),PriceOptions:ae.nullish(),CostCurve:Fe.nullish()}).passthrough(),vo="@skin";function qy(o){return !!o&&o.startsWith("@")}var By=z.object({CatalogID:z.string().nullish(),ItemID:z.string()}).passthrough(),Ly=z.object({PriceOptions:ae.nullish(),Schedule:me.nullish(),Gate:J.nullish()}).passthrough(),Gy=z.object({MinCharacterLevel:z.number().nullish(),StatRequirements:z.array(Io).nullish()}).passthrough(),Fy=z.object({SkinID:z.string().nullish(),Identity:Ju.nullish(),Item:By.nullish(),Sale:Ly.nullish(),Requirements:Gy.nullish()}).passthrough(),Vy=z.object({DefaultSkinID:z.string().nullish(),Definitions:z.record(z.string(),Fy).nullish()}).passthrough(),jy=z.object({CharacterID:z.string(),Identity:Ju.nullish(),Classification:Oy.nullish(),Unlock:Uy.nullish(),Presets:Ey.nullish(),Equipment:$u.nullish(),Stats:z.record(z.string(),Hu).nullish(),RankLadder:Zu.nullish(),RankStatCurve:Fe.nullish(),StatMaxLevelCurve:Fe.nullish(),Skins:Vy.nullish()}).passthrough(),Ny=z.object({Stats:z.record(z.string(),Hu).nullish()}).passthrough(),_y=z.object({RankLadder:Zu.nullish()}).passthrough(),Wy=z.object({Equipment:$u.nullish()}).passthrough(),Ky=z.object({Stats:z.record(z.string(),Ny).nullish(),Levels:z.record(z.string(),_y).nullish(),Equipment:z.record(z.string(),Wy).nullish()}).passthrough(),Ws=z.object({Definitions:z.record(z.string(),jy).nullish(),Presets:Ky.nullish()}).passthrough(),je={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"},Qy="SKIN_ALREADY_OWNED";var To="Character",Ks=class{constructor(e){this.ctx=e;e.cache.defineStateRule("Character",{needsServer:()=>{let t=e.cache.configSection(To)?.Definitions,i=e.data.user.state?.Character?.Characters??{};return Object.entries(t??{}).some(([s,n])=>n?.Unlock?.UnlockedByDefault===true&&!i[n.CharacterID??s])},refresh:()=>this.getUserCharacters()});}ctx;async getCharacterDefinitions(e){let t=this.ctx.cache.configSection(To,e);if(t)return this.ctx.emitter.emit("character:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.character.getCharacterDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(To,s.data),this.ctx.emitter.emit("character:definitionsLoaded",s.data)),s}async getUserCharacters(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.character.getUserCharacters(e);if(t.ok){let i=t.data.Characters??{};this.ctx.data.user.applyCharacter(i),this.ctx.emitter.emit("character:userCharactersLoaded",i);}return t}async unlockCharacter(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`unlock_char_${e}_${d()}`},s=await this.ctx.api.character.unlockCharacter(i);if(s.ok){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level??=1,r.StatLevels??={},r.Equipment??={},n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:unlocked",n);}return s}async upgradeStatLevel(e,t,i){if(!e||!t)return b("client","CharacterID and StatID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,StatID:t,RelatedEntityID:`upgrade_stat_${e}_${t}_${d()}`,...i?.levels!=null?{Levels:i.levels}:{},...i?.targetLevel!=null?{TargetLevel:i.targetLevel}:{}},n=await this.ctx.api.character.upgradeStatLevel(s);if(n.ok){let r=n.data;this.ctx.data.user.patchCharacter(r.CharacterID,p=>{p.StatLevels??={},p.StatLevels[r.StatID]=r.StatLevel,r.Power!=null&&(p.Power=r.Power),p.UpdatedAt=r.ServerTimeUtc;}),this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:statLevelUpgraded",r);}return n}async upgradeCharacterLevel(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,RelatedEntityID:`upgrade_char_${e}_${d()}`,...t?.levels!=null?{Levels:t.levels}:{},...t?.targetLevel!=null?{TargetLevel:t.targetLevel}:{}},s=await this.ctx.api.character.upgradeCharacterLevel(i);if(s.ok){let n=s.data;this.ctx.data.user.patchCharacter(n.CharacterID,r=>{r.Level=n.NewLevel,n.Power!=null&&(r.Power=n.Power),r.UpdatedAt=n.ServerTimeUtc,n.NewLevel===1&&(r.StatLevels??={},r.Equipment??={});}),this.ctx.data.user.applyResourceOperation(n.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("character:levelUpgraded",n);}return s}async equipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,ItemsToEquip:t},s=await this.ctx.api.character.equipItems(i);return s.ok&&(this.applyEquipChangesLocally(e,s.data),this.ctx.emitter.emit("character:itemsEquipped",s.data)),s}async unequipItems(e,t){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,UnequipSlotIDs:t},s=await this.ctx.api.character.unequipItems(i);if(s.ok){let n=s.data;this.applyUnequipChangesLocally(e,n),this.ctx.emitter.emit("character:itemsUnequipped",{characterID:e,slotIDs:n.ClearedSlotIDs??[],power:n.Power??null});}return s}async unequipAllCharacters(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.character.unequipAllCharacters(e);return t.ok&&(this.applyUnequipAllLocally(t.data),this.ctx.emitter.emit("character:allUnequipped",t.data)),t}async unlockSkin(e,t,i){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,AutoEquip:i?.autoEquip??false,RelatedEntityID:`unlock_skin_${e}_${t}_${d()}`},n=await this.ctx.api.character.unlockSkin(s);if(n.ok){let r=n.data;this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),r.Equipped&&r.Equipment&&this.applySkinLocally(r.CharacterID,r.Equipment,r.Power,r.ServerTimeUtc),this.ctx.emitter.emit("character:skinUnlocked",r);}return n}async equipSkin(e,t,i){if(!e||!t)return b("client","CharacterID and SkinID are required.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CharacterID:e,SkinID:t,ItemInstanceID:i},n=await this.ctx.api.character.equipSkin(s);if(n.ok){let r=n.data;this.applyInventoryDelta(r.Inventory),this.applySkinLocally(r.CharacterID,r.Equipped??null,r.Power,r.ServerTimeUtc),this.ctx.emitter.emit("character:skinEquipped",r);}return n}async unequipSkin(e){if(!e)return b("client","CharacterID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),CharacterID:e},i=await this.ctx.api.character.unequipSkin(t);if(i.ok){let s=i.data;s.Cleared&&(this.applyInventoryDelta(s.Inventory),this.applySkinLocally(s.CharacterID,null,s.Power,s.ServerTimeUtc)),this.ctx.emitter.emit("character:skinUnequipped",s);}return i}async getCharacterSkins(e){let t=this.ctx.authedRequest();return t?(e&&(t.CharacterID=e),this.ctx.api.character.getCharacterSkins(t)):c$1}applySkinLocally(e,t,i,s){let n=this.ctx.data.user;n.patchCharacterEquipment(e,vo,t??null),n.patchCharacter(e,r=>{i!=null&&(r.Power=i),r.UpdatedAt=s;});}async unlockCharactersBatch(e){if(!e||e.length===0)return b("client","characterIDs is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),UnlockCharacterIDs:e},i=await this.ctx.api.character.unlockCharactersBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level??=1,n.StatLevels??={},n.Equipment??={},s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:charactersUnlocked",i.data)),i}async upgradeCharacterLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),LevelUpgrades:e},i=await this.ctx.api.character.upgradeCharacterLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.Level=s.NewLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc,s.NewLevel===1&&(n.StatLevels??={},n.Equipment??={});});}),this.ctx.emitter.emit("character:levelsUpgraded",i.data)),i}async upgradeStatLevelsBatch(e){if(!e||e.length===0)return b("client","upgrades is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),StatUpgrades:e},i=await this.ctx.api.character.upgradeStatLevelsBatch(t);return i.ok&&(this.applyBatchResults(i.data,s=>{this.ctx.data.user.patchCharacter(s.CharacterID,n=>{n.StatLevels??={},n.StatLevels[s.StatID]=s.StatLevel,s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=s.ServerTimeUtc;});}),this.ctx.emitter.emit("character:statLevelsUpgraded",i.data)),i}applyBatchResults(e,t){e.Resources&&this.ctx.data.user.applyResourcesWithDelta(e.Resources,e.Inventory,this.ctx.data.config.itemDefinitions);for(let i of e.Items??[])!i.Success||!i.Data||t(i.Data);}applyInventoryDelta(e){this.ctx.data.user.applyInventoryDelta(e);}applyEquipChangesLocally(e,t){let i=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let[s,n]of Object.entries(t.Equipment??{}))i.patchCharacterEquipment(e,s,n);i.patchCharacter(e,s=>{t.Power!=null&&(s.Power=t.Power),s.UpdatedAt=t.ServerTimeUtc;});}applyUnequipChangesLocally(e,t){let i=t.ClearedSlotIDs??[];if(i.length===0&&t.Power==null)return;let s=this.ctx.data.user;this.applyInventoryDelta(t.Inventory);for(let n of i)s.patchCharacterEquipment(e,n,null);s.patchCharacter(e,n=>{t.Power!=null&&(n.Power=t.Power),n.UpdatedAt=t.ServerTimeUtc;});}applyUnequipAllLocally(e){let t=this.ctx.data.user;this.applyInventoryDelta(e.Inventory);for(let[i,s]of Object.entries(e.Characters??{})){for(let n of s.ClearedSlotIDs??[])t.patchCharacterEquipment(i,n,null);t.patchCharacter(i,n=>{s.Power!=null&&(n.Power=s.Power),n.UpdatedAt=e.ServerTimeUtc;});}}};var Yu="Match",Qs=class{constructor(e){this.ctx=e;}ctx;async createMatch(e,t,i,s,n,r){let p=this.ctx.auth.context;if(!p)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),Entry:e,RuleID:t,CharacterID:i,BattleStrategy:s,TargetUserID:n,SelectedOptionID:r,RelatedEntityID:`pvp_create_${p.userID}_${d()}`},C=await this.ctx.api.match.createMatch(d$1);return C.ok&&(this.ctx.data.user.applyResourceOperation(C.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:created",C.data)),C}async updateMatch(e,t={}){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),MatchID:e,TargetUserID:t.targetUserID,ClearTargetUser:t.clearTargetUser,RuleID:t.ruleID,CharacterID:t.characterID,BattleStrategy:t.battleStrategy},s=await this.ctx.api.match.updateMatch(i);return s.ok&&this.ctx.emitter.emit("match:updated",s.data),s}async cancelMatch(e){if(!e)return b("client","MatchID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),MatchID:e},i=await this.ctx.api.match.cancelMatch(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("match:cancelled",i.data)),i}async instantBattle(e,t,i,s){let n=this.ctx.auth.context;if(!n)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),MatchID:e,RuleID:t,CharacterID:i,BattleStrategy:s,RelatedEntityID:`pvp_battle_${e}_${d()}`},p=await this.ctx.api.match.instantBattle(r);if(p.ok){let d=p.data,C=this.ctx.data.config.itemDefinitions;if(d.Resources)this.ctx.data.user.applyResourceOperation(d.Resources,C);else if(d.ResourcesDual){let j=d.ResourcesDual;j.FromUserID===n.userID&&j.FromResult?this.ctx.data.user.applyResourceOperation(j.FromResult,C):j.ToUserID===n.userID&&j.ToResult&&this.ctx.data.user.applyResourceOperation(j.ToResult,C);}this.ctx.emitter.emit("match:instantBattleCompleted",d);}return p}async saveStrategy(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),BattleStrategy:e},i=await this.ctx.api.match.saveStrategy(t);return i.ok&&(this.ctx.data.user.patchMatchStrategy(e),this.ctx.emitter.emit("match:strategySaved",e)),i}async getMyMatches(e=0,t=20,i){let s=this.ctx.authedRequest();if(!s)return c$1;s.Page=e,s.PageSize=t,s.Statuses=i;let n=await this.ctx.api.match.getMyMatches(s);return n.ok&&this.ctx.emitter.emit("match:myMatchesLoaded",n.data),n}async getAvailableMatches(e=0,t=20,i=false){let s=this.ctx.authedRequest();if(!s)return c$1;s.Page=e,s.PageSize=t,s.OnlyPublic=i;let n=await this.ctx.api.match.getAvailableMatches(s);return n.ok&&this.ctx.emitter.emit("match:availableMatchesLoaded",n.data),n}async getDefinitions(e){let t=this.ctx.cache.configSection(Yu,e);if(t)return this.ctx.emitter.emit("match:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.match.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(Yu,s.data),this.ctx.emitter.emit("match:definitionsLoaded",s.data)),s}};var Xu="Craft",Hs=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Xu,e);if(t){let n={CraftDefinitions:t};return this.ctx.emitter.emit("craft:definitionsLoaded",t),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.craft.getDefinitions(i);return s.ok&&s.data.CraftDefinitions&&(this.ctx.data.config.patchSection(Xu,s.data.CraftDefinitions),this.ctx.emitter.emit("craft:definitionsLoaded",s.data.CraftDefinitions)),s}async craft(e,t,i=1,s,n){if(!e)return b("client","CraftID is required.");let r=this.ctx.auth.context;if(!r)return c$1;let p={...this.ctx.buildAuthedBaseRequest(),CraftID:e,InputItemIDs:t,Count:i,SelectedOptionID:s,InputInstanceIDs:n,RelatedEntityID:`craft_${e}_${r.userID}_${d()}`},d$1=await this.ctx.api.craft.craft(p);return d$1.ok&&(this.ctx.data.user.applyResourcesWithDelta(d$1.data.Resources,d$1.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("craft:completed",d$1.data)),d$1}};var Ut=z.lazy(()=>z.union([z.string(),z.number(),z.boolean(),z.null(),z.array(Ut),z.record(z.string(),Ut)]));var Et={Text:"Text",Image:"Image",Video:"Video",Audio:"Audio",Music:"Music",ThreeD:"ThreeD"},ec=z.enum(["Text","Image","Video","Audio","Music","ThreeD"]).catch("Text"),Wt={Pending:"pending",Running:"running",Completed:"completed",Failed:"failed"};function Pi(o){return o!==Wt.Pending&&o!==Wt.Running}var Hy={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 $y(o){return o?/\b(AI_[A-Z_]+)\s*:/.exec(o)?.[1]??null:null}var Jy=z.object({Url:z.string().nullish(),ContentType:z.string().nullish(),Variant:z.string().nullish()}),Zy=z.object({Code:z.string().nullish(),Message:z.string().nullish()}),$s=z.object({GenerationID:z.string(),FeatureKey:z.string().nullish(),Modality:ec.nullish(),Status:z.string(),Progress:z.number().nullish(),OutputText:z.string().nullish(),OutputJson:z.record(z.string(),Ut).nullish(),Assets:z.array(Jy).nullish(),Error:Zy.nullish(),Charge:M.nullish(),PlayerRefunded:z.boolean().nullish(),Reward:M.nullish(),Context:z.record(z.string(),Ut).nullish(),PaymentSettled:z.boolean().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish()}),tc=z.object({Data:z.array($s).nullish(),Skip:z.number().nullish(),Limit:z.number().nullish()}),Yy=z.object({Name:z.string().nullish(),Type:z.string().nullish(),Required:z.boolean().nullish(),MaxLength:z.number().nullish(),Enum:z.array(z.string()).nullish()}).passthrough(),Xy=z.object({Modality:ec.nullish(),Async:z.boolean().nullish(),Limits:ye.nullish(),PriceOptions:ae.nullish(),Tags:z.array(z.string()).nullish(),HistoryMessages:z.number().nullish(),MaxTokens:z.number().nullish(),AllowImages:z.boolean().nullish(),MaxInputImages:z.number().nullish(),MaxInputImageBytes:z.number().nullish(),AllowedImageTypes:z.array(z.string()).nullish(),MaxImages:z.number().nullish(),AllowEdit:z.boolean().nullish(),AllowReferenceImage:z.boolean().nullish(),MaxPromptChars:z.number().nullish(),LockBehavior:z.boolean().nullish(),ImageSize:z.string().nullish(),VideoSize:z.string().nullish(),VideoSeconds:z.number().nullish(),Voice:z.string().nullish(),AudioFormat:z.string().nullish(),MusicFormat:z.string().nullish(),ThreeDOperation:z.string().nullish(),ArtStyle:z.string().nullish(),ThreeDFormat:z.string().nullish(),Reward:H.nullish(),PromptVariables:z.array(Yy).nullish(),AllowFreePrompt:z.boolean().nullish()}).passthrough(),ic=z.object({Enabled:z.boolean().nullish(),Features:z.record(z.string(),Xy).nullish()}).passthrough(),Ge={GetDefinitions:"GetDefinitions",GenerateText:"GenerateText",GetText:"GetText",GenerateImage:"GenerateImage",EditImage:"EditImage",GenerateVideo:"GenerateVideo",GetVideo:"GetVideo",GenerateAudio:"GenerateAudio",GenerateMusic:"GenerateMusic",GenerateThreeD:"GenerateThreeD",GetThreeD:"GetThreeD",ListGenerations:"ListGenerations",GetGeneration:"GetGeneration",GetImage:"GetImage",GetAudio:"GetAudio",GetMusic:"GetMusic"};var sc="AI",eR=/^[A-Za-z0-9_-]{1,128}$/,tR=2e3,iR=5e3,sR=30*6e4;function nR(o,e){return new Promise(t=>{if(e?.aborted){t();return}let i=()=>{clearTimeout(s),e?.removeEventListener("abort",i),t();},s=setTimeout(i,o);e?.addEventListener("abort",i,{once:true});})}var Js=class{constructor(e){this.ctx=e;}ctx;charged=new Set;rewarded=new Set;async getDefinitions(e){let t=this.ctx.cache.configSection(sc,e);if(t)return this.ctx.emitter.emit("ai:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.ai.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(sc,s.data),this.ctx.emitter.emit("ai:definitionsLoaded",s.data)),s}generateText(e,t,i){return this.generate(e,{Text:t},i,s=>this.ctx.api.ai.generateText(s))}getText(e){return this.poll(e,t=>this.ctx.api.ai.getText(t))}generateImage(e,t,i){return this.generate(e,{Image:t},i,s=>this.ctx.api.ai.generateImage(s))}editImage(e,t,i){return this.generate(e,{ImageEdit:t},i,s=>this.ctx.api.ai.editImage(s))}getImage(e){return this.poll(e,t=>this.ctx.api.ai.getImage(t))}generateVideo(e,t,i){return this.generate(e,{Video:t},i,s=>this.ctx.api.ai.generateVideo(s))}getVideo(e){return this.poll(e,t=>this.ctx.api.ai.getVideo(t))}generateAudio(e,t,i){return this.generate(e,{Audio:t},i,s=>this.ctx.api.ai.generateAudio(s))}getAudio(e){return this.poll(e,t=>this.ctx.api.ai.getAudio(t))}generateMusic(e,t,i){return this.generate(e,{Music:t},i,s=>this.ctx.api.ai.generateMusic(s))}getMusic(e){return this.poll(e,t=>this.ctx.api.ai.getMusic(t))}generateThreeD(e,t,i){return this.generate(e,{ThreeD:t},i,s=>this.ctx.api.ai.generateThreeD(s))}getThreeD(e){return this.poll(e,t=>this.ctx.api.ai.getThreeD(t))}async listGenerations(e){let t=this.ctx.authedRequest();return t?(e&&(t.Query=e),this.ctx.api.ai.listGenerations(t)):c$1}async getGeneration(e){if(!e)return b("client","GenerationID is required.");let t=this.ctx.authedRequest();return t?(t.GenerationID=e,this.ctx.api.ai.getGeneration(t)):c$1}isTerminal(e){return Pi(e)}async waitForGeneration(e,t={}){let i;if(typeof e=="string"){let p=await this.getGeneration(e);if(!p.ok)return p;i=p.data;}else {if(!e?.GenerationID)return b("client","GenerationID is required.");i=e;}let s=Date.now()+(t.timeoutMs??sR),n=Math.max(1,t.intervalMs??tR),r=Math.max(n,t.maxIntervalMs??iR);for(;!Pi(i.Status);){if(t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");if(Date.now()+n>s)return b("client","Stopped waiting: timed out. The generation keeps running \u2014 read it later with getGeneration.");if(await nR(n,t.signal),t.signal?.aborted)return b("client","Stopped waiting: the wait was aborted.");let p=await this.pollFor(i);if(n=Math.min(r,Math.round(n*1.5)),!p.ok){if(p.reason==="connection")continue;return p}i=p.data,Pi(i.Status)||t.onUpdate?.(i);}return a(i)}pollFor(e){switch(e.Modality){case Et.Text:return this.getText(e.GenerationID);case Et.Image:return this.getImage(e.GenerationID);case Et.Audio:return this.getAudio(e.GenerationID);case Et.Music:return this.getMusic(e.GenerationID);case Et.Video:return this.getVideo(e.GenerationID);case Et.ThreeD:return this.getThreeD(e.GenerationID);default:return this.getGeneration(e.GenerationID)}}async generate(e,t,i,s){if(!e)return b("client","FeatureKey is required.");let n=i?.relatedEntityID;if(n!==void 0&&!eR.test(n))return b("client","relatedEntityID must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'.");if(!this.ctx.auth.context)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),...t,FeatureKey:e,SelectedOptionID:i?.selectedOptionID,Payment:i?.payment,Variables:i?.variables,Context:i?.context,RelatedEntityID:n??d()},p=await s(r);return p.ok&&(await this.reconcileCharge(p.data,true),this.emitView(p.data)),p}async poll(e,t){if(!e)return b("client","GenerationID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.GenerationID=e;let s=await t(i);return s.ok&&(await this.reconcileCharge(s.data,false),this.emitView(s.data)),s}async reconcileCharge(e,t){if(e.PlayerRefunded){this.charged.delete(e.GenerationID)&&await this.ctx.userService.getUserInventory();return}e.Reward&&e.Status===Wt.Completed&&!this.rewarded.has(e.GenerationID)&&(this.rewarded.add(e.GenerationID),await this.ctx.userService.getUserInventory()),!(!t||!e.Charge||this.charged.has(e.GenerationID))&&(this.charged.add(e.GenerationID),this.ctx.data.user.applyResourceOperation(e.Charge,this.ctx.data.config.itemDefinitions));}emitView(e){this.ctx.emitter.emit("ai:generationUpdated",e),e.Status===Wt.Completed?this.ctx.emitter.emit("ai:generationCompleted",e):e.Status===Wt.Failed&&this.ctx.emitter.emit("ai:generationFailed",e);}};var ko="Collection",Zs=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(ko),s=Object.keys(i?.Collections??{});if(s.length===0||t)return false;let n=e.cache.configSection("Season");return Object.values(n?.Chains??{}).some(p=>(p?.Seasons??[]).some(d=>!!d?.LinkedCollectionID))?true:e.data.user.state?.Collection?.CollectionID!==s[0]},refresh:async()=>{let i=await this.getUserState();return i.ok&&(t=true),i}});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(ko,e);if(t)return this.ctx.emitter.emit("collection:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.collection.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(ko,s.data),this.ctx.emitter.emit("collection:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.collection.getUserState(e);return t.ok&&(this.ctx.data.user.applyCollection(t.data),this.ctx.emitter.emit("collection:userStateLoaded",t.data)),t}async openPack(e,t,i=1,s){let n=this.ctx.auth.context;if(!n)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,PackTypeID:t,Count:i,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:`open_pack_${e}_${t}_${n.userID}_${d()}`},p=await this.ctx.api.collection.openPack(r);return p.ok&&(this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:packOpened",p.data)),p}async openCollectionChest(e,t,i=1){let s=this.ctx.auth.context;if(!s)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectionChestID:t,Count:i,RelatedEntityID:`open_chest_${e}_${t}_${s.userID}_${d()}`},r=await this.ctx.api.collection.openCollectionChest(n);return r.ok&&(this.ctx.data.user.applyResourcesWithDelta(r.data.Resources,r.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:chestOpened",r.data)),r}async useCollectibleJoker(e,t){let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:false,RelatedEntityID:`use_joker_${e}_${t}_${i.userID}_${d()}`},n=await this.ctx.api.collection.useCollectibleJoker(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:jokerUsed",n.data)),n}async claimSetReward(e,t){let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,SetID:t,RelatedEntityID:`claim_set_${e}_${t}_${i.userID}_${d()}`},n=await this.ctx.api.collection.claimSetReward(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:setRewardClaimed",n.data)),n}async claimSetRewardsBatch(e){if(!e||e.length===0)return b("client","sets is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),Sets:e},i=await this.ctx.api.collection.claimSetRewardsBatch(t);if(i.ok){let s=false;for(let n of i.data)!s&&n.Success&&n.Data?.Resources&&(this.ctx.data.user.applyResourcesWithDelta(n.Data.Resources,n.Data.Inventory,this.ctx.data.config.itemDefinitions),s=true);this.ctx.emitter.emit("collection:setRewardsClaimedBatch",i.data);}return i}async claimGrandPrize(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,RelatedEntityID:`grand_prize_${e}_${t.userID}_${d()}`},s=await this.ctx.api.collection.claimGrandPrize(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("collection:grandPrizeClaimed",s.data)),s}async sendTradeOffer(e,t,i,s,n,r=false){let p=this.ctx.auth.context;if(!p)return c$1;let d$1={...this.ctx.buildAuthedBaseRequest(),CollectionID:e,CollectibleID:t,CollectibleIsSpecial:i,ReceiverUserID:s,RequestedCollectibleID:n,RequestedCollectibleIsSpecial:r,RelatedEntityID:`trade_send_${p.userID}_${s}_${d()}`},C=await this.ctx.api.collection.sendTradeOffer(d$1);return C.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferSent",C.data)),C}async cancelTradeOffer(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_cancel_${e}_${d()}`},i=await this.ctx.api.collection.cancelTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferCancelled",i.data)),i}async acceptTradeOffer(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_accept_${e}_${d()}`},i=await this.ctx.api.collection.acceptTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferAccepted",i.data)),i}async declineTradeOffer(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),OfferID:e,RelatedEntityID:`trade_decline_${e}_${d()}`},i=await this.ctx.api.collection.declineTradeOffer(t);return i.ok&&(this.tradeChangedCollection(),this.ctx.emitter.emit("collection:tradeOfferDeclined",i.data)),i}tradeChangedCollection(){this.ctx.cache.invalidateState(["Collection"]);}async getMyTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.CollectionID=e;let i=await this.ctx.api.collection.getMyTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:myTradeOffersLoaded",i.data),i}async getIncomingTradeOffers(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.CollectionID=e;let i=await this.ctx.api.collection.getIncomingTradeOffers(t);return i.ok&&this.ctx.emitter.emit("collection:incomingTradeOffersLoaded",i.data),i}};var rR=z.object({}).passthrough().transform(o=>o),oR={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},aR={Active:"Active",Left:"Left",Replaced:"Replaced"},lR=z.object({ObjectIndex:z.number().nullish(),ObjectCompletionRewardClaimed:z.boolean().nullish()}).passthrough(),uR=z.object({UserID:z.string().nullish(),PublicData:Oe.nullish(),BuildObjectsProgress:lR.nullish(),IsBot:z.boolean().nullish(),SpinsCount:z.number().nullish(),TokensSpent:z.number().nullish(),MemberStatus:z.string().nullish(),GrandPrizeClaimed:z.boolean().nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),cR=z.object({Index:z.number().nullish(),OwnerUserID:z.string().nullish(),CurrentProgress:z.number().nullish(),MaxProgress:z.number().nullish(),IsCompleted:z.boolean().nullish()}).passthrough(),pR=z.object({Objects:z.array(cR).nullish()}).passthrough(),nc=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),CoopChainID:z.string().nullish(),CoopEventID:z.string().nullish(),CycleIndex:z.number().nullish(),Members:z.array(uR).nullish(),BuildObjectsState:pR.nullish(),Status:z.string().nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:z.number().nullish()}).passthrough(),rc=z.object({CoopChainID:z.string(),CycleIndex:z.number().nullish(),EventOrder:z.number().nullish(),EventDef:z.lazy(()=>oc).nullish(),ComputedStartUtc:c.nullish(),ComputedEndUtc:c.nullish(),SecondsRemaining:z.number().nullish()}).passthrough(),hR=z.string(),zo=z.object({DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Weight:z.number().nullish(),MinProgress:z.number().nullish(),MaxProgress:z.number().nullish()}).passthrough(),dR=z.object({Index:z.number().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxProgress:z.number().nullish(),CompletionReward:H.nullish()}).passthrough(),mR=z.object({Objects:z.array(dR).nullish(),PriceOptions:ae.nullish(),SpinnerTable:z.array(zo).nullish(),MaxSpinsPerCall:z.number().nullish()}).passthrough(),oc=z.object({CoopEventID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),EventType:hR.nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),BuildObjects:mR.nullish(),GrandPrize:H.nullish()}).passthrough(),fR=z.object({CoopChainID:z.string().nullish(),DisplayName:z.string().nullish(),Schedule:me.nullish(),Events:z.array(oc).nullish(),Gate:J.nullish()}).passthrough(),Ys=z.object({ServerTimeUtc:c.nullish(),UserState:rR.nullish(),ActiveGroup:nc.nullish()}),Ao=z.object({ServerTimeUtc:c.nullish(),Group:nc.nullish(),SecondsRemaining:_.nullish()}),ac=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Resources:M.nullish(),ObjectIndex:z.number().nullish(),Sector:zo.nullish(),RequestedSpins:z.number().nullish(),SpinsUsed:z.number().nullish(),Sectors:z.array(zo).nullish(),ProgressDelta:z.number().nullish(),NewProgress:_.nullish(),MaxProgress:_.nullish(),ObjectCompleted:z.boolean().nullish(),AllObjectsCompleted:z.boolean().nullish()}),wo=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),lc=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),Xs=z.object({Chains:z.record(z.string(),fR).nullish()}).passthrough(),ht={GetDefinitions:"GetDefinitions",GetActiveEvent:"GetActiveEvent",GetUserState:"GetUserState",GetGroupState:"GetGroupState",JoinOrCreateGroup:"JoinOrCreateGroup",Spin:"Spin",ClaimObjectReward:"ClaimObjectReward",ClaimGrandPrize:"ClaimGrandPrize",LeaveGroup:"LeaveGroup"};var uc="CoopEvent",cc={key:"coopEvent.userState",login:"CoopUserState",ttlMs:3e4,dependsOn:["CoopEvent"],invalidateOn:["coopEvent:groupJoined","coopEvent:groupLeft","coopEvent:spinCompleted","coopEvent:objectRewardClaimed","coopEvent:grandPrizeClaimed"]},en=class{constructor(e){this.ctx=e;e.cache.bindLoginView(cc,{schema:Ys,apply:t=>this.applyUserState(t)});}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(uc,e);if(t)return this.ctx.emitter.emit("coopEvent:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.coopEvent.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(uc,s.data),this.ctx.emitter.emit("coopEvent:definitionsLoaded",s.data)),s}async getActiveEvent(e){if(!e)return b("client","CoopChainID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.CoopChainID=e;let i=await this.ctx.api.coopEvent.getActiveEvent(t);return i.ok&&this.ctx.emitter.emit("coopEvent:activeEventLoaded",i.data),i}getUserState(e){return this.ctx.cache.read(cc,()=>this.fetchUserState(),e)}async fetchUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.coopEvent.getUserState(e);return t.ok&&this.applyUserState(t.data),t}applyUserState(e){this.ctx.data.user.applyCoopEvent(e.UserState??null),this.ctx.emitter.emit("coopEvent:userStateLoaded",e);}async getGroupState(e){if(!e)return b("client","GroupID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.GroupID=e;let i=await this.ctx.api.coopEvent.getGroupState(t);return i.ok&&this.ctx.emitter.emit("coopEvent:groupStateLoaded",i.data),i}async joinOrCreateGroup(e){if(!e)return b("client","CoopChainID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e},i=await this.ctx.api.coopEvent.joinOrCreateGroup(t);if(i.ok){let s=i.data.Group;s&&this.ctx.data.user.patchCoopEventActiveGroup(s.GroupID??null,s.CoopEventID??null,-1),this.ctx.emitter.emit("coopEvent:groupJoined",i.data);}return i}async spin(e,t,i=1,s){if(!e||!t)return b("client","CoopChainID and GroupID are required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),CoopChainID:e,GroupID:t,Count:i,SelectedOptionID:s,RelatedEntityID:d()},r=await this.ctx.api.coopEvent.spin(n);return r.ok&&(this.ctx.data.user.applyResourceOperation(r.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:spinCompleted",r.data)),r}async claimObjectReward(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimObjectReward(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("coopEvent:objectRewardClaimed",i.data)),i}async claimGrandPrize(e){if(!e)return b("client","GroupID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.claimGrandPrize(t);return i.ok&&(this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:grandPrizeClaimed",i.data)),i}async leaveGroup(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.coopEvent.leaveGroup(t);return i.ok&&(this.ctx.data.user.patchCoopEventActiveGroup(null,null,-1),this.ctx.emitter.emit("coopEvent:groupLeft",i.data)),i}};var gR={Active:"Active",Exhausted:"Exhausted",Expired:"Expired",Dismissed:"Dismissed"},yR={Locked:"Locked",Available:"Available",InProgress:"InProgress",Completed:"Completed",Hidden:"Hidden"},RR=z.object({NodeID:z.string().nullish(),Status:z.string().nullish(),ExecutionCount:z.number().nullish(),UnlockedAtUtc:c.nullish(),CompletedAtUtc:c.nullish(),LastExecutedAtUtc:c.nullish(),NextAvailableAtUtc:c.nullish(),LastExecutionRefID:z.string().nullish()}).passthrough(),CR=z.object({TrackID:z.string().nullish(),CurrentValue:z.number().nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),pc=z.object({OfferID:z.string().nullish(),InstanceKey:z.string().nullish(),SourceOfferVersion:z.number().nullish(),Status:z.string().nullish(),ActivatedAtUtc:c.nullish(),ExhaustedAtUtc:c.nullish(),ExpiredAtUtc:c.nullish(),DismissedAtUtc:c.nullish(),ShowCount:z.number().nullish(),LastShownAtUtc:c.nullish(),Nodes:z.record(z.string(),RR).nullish(),Tracks:z.record(z.string(),CR).nullish(),SelectedChoiceNodeID:z.string().nullish()}).passthrough(),SR=z.object({SlotID:z.string().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),ActiveOfferID:z.string().nullish(),ActiveOfferStartedAtUtc:c.nullish(),ActiveOfferExpiresAtUtc:c.nullish(),ActiveOffer:pc.nullish(),NextCycleStartsAtUtc:c.nullish(),LastUpdatedUtc:c.nullish(),DismissSkipAvailableAtUtc:c.nullish(),LastDismissedAtUtc:c.nullish(),ActiveScheduleInstanceKey:z.string().nullish()}).passthrough(),xR=z.object({TotalExecutions:z.number().nullish(),DailyExecutions:z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),bR=z.object({TotalActivations:z.number().nullish(),TotalExhausted:z.number().nullish(),TotalExpired:z.number().nullish(),TotalDismissed:z.number().nullish(),TotalShows:z.number().nullish(),LastShownAtUtc:c.nullish(),LastActivatedAtUtc:c.nullish(),LastExhaustedAtUtc:c.nullish(),NodeCounts:z.record(z.string(),xR).nullish()}).passthrough(),DR=z.object({Slots:z.record(z.string(),SR).nullish(),OfferHistory:z.record(z.string(),bR).nullish(),LastUpdatedUtc:c.nullish()}).passthrough(),PR={Purchase:"Purchase",FreeClaim:"FreeClaim",RewardedVideo:"RewardedVideo",Info:"Info"},IR={Eq:"Eq",Gte:"Gte",Lte:"Lte"},vR=z.object({Order:z.number().nullish(),OfferID:z.string().nullish(),DurationSec:z.number().nullish(),DelayBeforeActivationSec:z.number().nullish()}).passthrough(),tn=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),SortOrder:z.number().nullish(),Tags:z.array(z.string()).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),hc=z.object({Schedule:me.nullish(),Gate:J.nullish()}).passthrough(),dc=z.object({AllowDismissSkip:z.boolean().nullish(),DismissSkipDelaySec:z.number().nullish()}).passthrough(),TR=z.object({Identity:K.nullish(),Availability:K.nullish(),Behaviour:K.nullish()}).passthrough(),kR=z.object({SlotID:z.string().nullish(),Enabled:z.boolean().nullish(),Identity:tn.nullish(),Availability:hc.nullish(),Behaviour:dc.nullish(),Queue:z.array(vR).nullish(),Presets:TR.nullish()}).passthrough(),zR=z.object({ViewsRequiredToComplete:z.number().nullish(),MaxViewsPerActivation:z.number().nullish(),GrantRewardsPerView:z.boolean().nullish()}).passthrough(),AR=z.object({RewardedVideo:zR.nullish()}).passthrough(),wR=z.object({TrackID:z.string().nullish(),Operator:z.string().nullish(),Value:z.number().nullish()}).passthrough(),MR=z.object({Identity:K.nullish(),Graph:K.nullish(),Milestones:K.nullish()}).passthrough(),OR=z.object({Identity:K.nullish(),Pricing:K.nullish(),Reward:K.nullish()}).passthrough(),UR=z.object({TrackID:z.string().nullish(),Amount:z.number().nullish(),RespectBounds:z.boolean().nullish()}).passthrough(),ER=z.object({TrackID:z.string().nullish(),DisplayName:z.string().nullish(),StartValue:z.number().nullish(),MinValue:z.number().nullish(),MaxValue:z.number().nullish(),ClampToMin:z.boolean().nullish(),ClampToMax:z.boolean().nullish(),HiddenFromUI:z.boolean().nullish()}).passthrough(),qR=z.object({RequiredCompletedNodeIDs:z.array(z.string()).nullish(),RequiredAnyCompletedNodeIDs:z.array(z.string()).nullish(),RequiredTracks:z.array(wR).nullish(),VisibleWhileLocked:z.boolean().nullish()}).passthrough(),mc=z.object({Options:ae.nullish()}).passthrough(),fc=z.object({Grants:H.nullish(),TrackChanges:z.array(UR).nullish(),MilestonePoints:z.number().nullish()}).passthrough(),BR=z.object({NodeID:z.string().nullish(),Type:z.string().nullish(),Identity:tn.nullish(),Pricing:mc.nullish(),Reward:fc.nullish(),Action:AR.nullish(),UnlockRules:qR.nullish(),NextNodeIDs:z.array(z.string()).nullish(),ChoiceGroupID:z.string().nullish(),Limits:ye.nullish(),HideWhenCompleted:z.boolean().nullish(),ExhaustOfferOnComplete:z.boolean().nullish(),Presets:OR.nullish()}).passthrough(),gc=z.object({RootNodeIDs:z.array(z.string()).nullish(),Nodes:z.array(BR).nullish(),Tracks:z.array(ER).nullish(),ExhaustedWhenAllTerminalNodesCompleted:z.boolean().nullish()}).passthrough(),yc=z.object({Milestones:z.record(z.string(),Be).nullish(),ClaimMode:z.string().nullish(),Token:jt.nullish()}).passthrough(),Rc=z.object({OfferID:z.string().nullish(),Version:z.number().nullish(),Enabled:z.boolean().nullish(),Identity:tn.nullish(),Graph:gc.nullish(),Milestones:yc.nullish(),Presets:MR.nullish()}).passthrough(),LR=z.object({Identity:z.record(z.string(),tn).nullish(),Availability:z.record(z.string(),hc).nullish(),Behaviour:z.record(z.string(),dc).nullish(),Graph:z.record(z.string(),gc).nullish(),Milestones:z.record(z.string(),yc).nullish(),Pricing:z.record(z.string(),mc).nullish(),Reward:z.record(z.string(),fc).nullish()}).passthrough(),Mo=z.object({Slots:z.record(z.string(),kR).nullish(),Offers:z.record(z.string(),Rc).nullish(),Presets:LR.nullish()}).passthrough(),Cc=z.object({DealOfferDefinitions:Mo.nullish()}),Sc=z.object({DealOffers:DR.nullish()}),GR=z.object({EntityID:z.string().nullish(),TotalEarned:z.number().nullish(),ClaimedIDs:z.array(z.string()).nullish(),ReachedUnclaimedIDs:z.array(z.string()).nullish()}).passthrough(),FR=z.object({SlotID:z.string().nullish(),SortOrder:z.number().nullish(),QueueIndex:z.number().nullish(),CycleIndex:z.number().nullish(),OfferDef:Rc.nullish(),ActivationState:pc.nullish(),IsNewActivation:z.boolean().nullish(),ComputedExpiresAtUtc:c.nullish(),Cost:xt.nullish(),Milestone:GR.nullish(),ScheduleInstanceKey:z.string().nullish()}).passthrough(),sn=z.object({Slots:z.array(FR).nullish()}),xc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),NodeID:z.string().nullish(),NodeCompleted:z.boolean().nullish(),OfferExhausted:z.boolean().nullish(),Idempotent:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),bc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),Dc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),Resources:M.nullish()}),Pc=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ic=z.object({ServerTimeUtc:c.nullish(),SlotID:z.string().nullish(),ClaimedIDs:z.array(z.string()).nullish(),Rejected:z.record(z.string(),z.string()).nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),yt={GetDefinition:"GetDefinition",GetUserState:"GetUserState",GetActiveDeals:"GetActiveDeals",DismissDeal:"DismissDeal",ExecuteNode:"ExecuteNode",RecordShow:"RecordShow",ClaimMilestone:"ClaimMilestone",ClaimMilestonesBatch:"ClaimMilestonesBatch"};var VR="DealOffer",vc={key:"dealOffer.active",login:"ActiveDeals",ttlMs:5*6e4,dependsOn:["DealOffer"],invalidateOn:["dealOffer:nodeExecuted","dealOffer:showRecorded","dealOffer:dealDismissed","dealOffer:milestoneClaimed","dealOffer:milestonesBatchClaimed"]},nn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(vc,{schema:sn,apply:t=>this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t)});}ctx;async getDefinition(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.dealOffer.getDefinition(e);return t.ok&&t.data.DealOfferDefinitions&&(this.ctx.data.config.patchSection(VR,t.data.DealOfferDefinitions),this.ctx.emitter.emit("dealOffer:definitionLoaded",t.data.DealOfferDefinitions)),t}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.dealOffer.getUserState(e);return t.ok&&t.data.DealOffers&&(this.ctx.data.user.applyDealOffer(t.data.DealOffers),this.ctx.emitter.emit("dealOffer:userStateLoaded",t.data.DealOffers)),t}getActiveDeals(e){return this.ctx.cache.read(vc,()=>this.fetchActiveDeals(),e)}async fetchActiveDeals(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.dealOffer.getActiveDeals(e);return t.ok&&this.ctx.emitter.emit("dealOffer:activeDealsLoaded",t.data),t}async dismissDeal(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_dismiss_${e}_${d()}`},i=await this.ctx.api.dealOffer.dismissDeal(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:dealDismissed",i.data)),i}async executeNode(e,t,i,s){if(!e||!t)return b("client","SlotID and NodeID are required.");if(!this.ctx.auth.context)return c$1;let n=i&&i.trim().length>0?i.trim():void 0,r={...this.ctx.buildAuthedBaseRequest(),SlotID:e,NodeID:t,SelectedOptionID:s?.selectedOptionID,Payment:s?.payment,RelatedEntityID:n??`deal_exec_${e}_${t}_${d()}`},p=await this.ctx.api.dealOffer.executeNode(r);return p.ok&&(p.data.Idempotent||this.ctx.data.user.applyResourcesWithDelta(p.data.Resources,p.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:nodeExecuted",p.data)),p}async recordShow(e){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),SlotID:e,RelatedEntityID:`deal_show_${e}_${d()}`},i=await this.ctx.api.dealOffer.recordShow(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:showRecorded",i.data)),i}async claimMilestone(e,t){if(!e||!t)return b("client","SlotID and MilestoneID are required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneID:t,RelatedEntityID:`deal_milestone_${e}_${t}_${d()}`},s=await this.ctx.api.dealOffer.claimMilestone(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestoneClaimed",s.data)),s}async claimMilestonesBatch(e,t){if(!e)return b("client","SlotID is required.");if(!this.ctx.auth.context)return c$1;let i=[...new Set(t.map(r=>r.trim()).filter(r=>r.length>0))],s={...this.ctx.buildAuthedBaseRequest(),SlotID:e,MilestoneIDs:i,RelatedEntityID:`deal_milestone_batch_${e}_${d()}`},n=await this.ctx.api.dealOffer.claimMilestonesBatch(s);return n.ok&&(this.ctx.data.user.applyResourcesWithDelta(n.data.Resources,n.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("dealOffer:milestonesBatchClaimed",n.data)),n}};var Tc="Referral",rn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(Tc,e);if(t){let n={ReferralDefinitions:t};return this.ctx.emitter.emit("referral:definitionsLoaded",n),a(n)}let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.referral.getDefinitions(i);return s.ok&&s.data.ReferralDefinitions&&(this.ctx.data.config.patchSection(Tc,s.data.ReferralDefinitions),this.ctx.emitter.emit("referral:definitionsLoaded",s.data)),s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.referral.getUserState(e);return t.ok&&t.data.Referral&&(this.ctx.data.user.applyReferral(t.data.Referral),this.ctx.emitter.emit("referral:userStateLoaded",t.data)),t}async activateReferralCode(e){let t=Vt.parseReferralCode(e)?.toUpperCase();if(!t)return b("client","ReferralCode is required.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),ReferralCode:t,RelatedEntityID:`referral_activation_${i.userID}`},n=await this.ctx.api.referral.activateReferralCode(s);if(n.ok){let r=n.data;r.ReferrerUserID&&this.ctx.data.user.patchReferralSubscription(r.ReferrerUserID),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:codeActivated",r);}return n}async claimInviteReward(e){let t=e.trim();if(!t)return b("client","InviteRewardID is required.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardID:t,RelatedEntityID:`referral_invite_${t}_${i.userID}`},n=await this.ctx.api.referral.claimInviteReward(s);if(n.ok){let r=n.data;r.RewardID&&this.ctx.data.user.patchReferralInviteRewardClaimed(r.RewardID),this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardClaimed",r);}return n}async claimInviteRewardsBatch(e){let t=(e??[]).map(r=>r?.trim()).filter(Boolean);if(t.length===0)return b("client","InviteRewardIDs is required.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),InviteRewardIDs:t,RelatedEntityID:`referral_invite_batch_${t.join("_")}_${i.userID}`},n=await this.ctx.api.referral.claimInviteRewardsBatch(s);if(n.ok){let r=n.data;for(let p of r.Items??[])p.Success&&p.Id&&this.ctx.data.user.patchReferralInviteRewardClaimed(p.Id);this.ctx.data.user.applyResourcesWithDelta(r.Resources,r.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("referral:inviteRewardsBatchClaimed",r);}return n}};var jR={System:"System",Reward:"Reward",Gift:"Gift",Social:"Social"},kc=z.enum(["System","Reward","Gift","Social"]).catch("System"),NR={Admin:"Admin",Broadcast:"Broadcast",SocialGift:"SocialGift",Transfer:"Transfer",TransferReturn:"TransferReturn",Module:"Module",CloudCode:"CloudCode"},_R=z.enum(["Admin","Broadcast","SocialGift","Transfer","TransferReturn","Module","CloudCode"]).catch("Admin"),WR={Leaderboard:"Leaderboard",CoopEvent:"CoopEvent",Season:"Season",Referral:"Referral"},KR=z.enum(["Leaderboard","CoopEvent","Season","Referral"]).catch("Leaderboard"),et={GetDefinitions:"GetDefinitions",GetMessages:"GetMessages",GetUnreadCount:"GetUnreadCount",ReadMessages:"ReadMessages",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",ClaimAll:"ClaimAll",DeleteMessages:"DeleteMessages",SendGift:"SendGift",SendTransfer:"SendTransfer",GetGiftStatus:"GetGiftStatus"},QR={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"},HR=100,$R=z.object({Subject:z.string().nullish(),Body:z.string().nullish()}).passthrough(),zc=z.object({FeatureID:z.string().nullish(),Args:z.record(z.string(),z.string()).nullish(),Url:z.string().nullish(),Label:z.string().nullish()}).passthrough(),JR=z.object({Texts:z.record(z.string(),$R).nullish(),Category:kc.nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:zc.nullish(),SenderName:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),ZR=z.object({Enabled:z.boolean().nullish(),Grant:le.nullish(),Cost:le.nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:c.nullish(),SenderGate:J.nullish(),TemplateID:z.string().nullish(),ExpirationDays:z.number().nullish()}).passthrough(),YR=z.object({Type:z.string().nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxAmountPerGift:z.number().nullish()}).passthrough(),XR=z.object({Enabled:z.boolean().nullish(),AllowedResources:z.array(YR).nullish(),MaxEntriesPerGift:z.number().nullish(),IntervalSeconds:z.number().nullish(),AnchorUtc:c.nullish(),FeePercent:z.number().nullish(),FeeCost:le.nullish(),SenderGate:J.nullish(),ExpirationDays:z.number().nullish(),TemplateID:z.string().nullish()}).passthrough(),Ac=z.object({Enabled:z.boolean().nullish(),Capacity:z.number().nullish(),RewardLetterDays:z.number().nullish(),PlainLetterDays:z.number().nullish(),ClaimedRetentionDays:z.number().nullish(),DefaultLanguage:z.string().nullish(),Templates:z.record(z.string(),JR).nullish(),Gifts:z.object({Social:z.record(z.string(),ZR).nullish(),Transfer:XR.nullish()}).passthrough().nullish(),Integrations:z.object({Leaderboard:z.boolean().nullish(),CoopEvent:z.boolean().nullish(),Season:z.boolean().nullish(),Referral:z.boolean().nullish()}).passthrough().nullish()}).passthrough(),eC=z.object({MessageID:z.string(),Source:_R,Category:kc,TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Icon:z.string().nullish(),Banner:z.string().nullish(),Link:zc.nullish(),SenderName:z.string().nullish(),SenderUserID:z.string().nullish(),SenderAvatarUrl:z.string().nullish(),SenderNote:z.string().nullish(),Rewards:H.nullish(),HasRewards:z.boolean().nullish(),IsTransfer:z.boolean().nullish(),SentAt:c,ExpiresAt:c.nullish(),ReadAt:c.nullish(),ClaimedAt:c.nullish()}).passthrough(),tC=z.object({MessageID:z.string(),Module:KR,Key:z.string(),TemplateID:z.string().nullish(),Subject:z.string().nullish(),Body:z.string().nullish(),Language:z.string().nullish(),TemplateParams:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish()}).passthrough(),Oo=z.object({ID:z.string(),Error:z.string().nullish()}).passthrough(),wc=z.object({ServerTimeUtc:c.nullish(),Messages:z.array(eC).default([]),NextCursor:z.string().nullish(),PendingRewards:z.array(tC).nullish(),UnreadCount:z.number().nullish(),UnclaimedCount:z.number().nullish(),DeliveredNow:z.number().nullish()}).passthrough(),on=z.object({ServerTimeUtc:c.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Uo=z.object({ServerTimeUtc:c.nullish(),AffectedCount:z.number().default(0),Failed:z.array(Oo).default([]),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),iC=z.object({MessageID:z.string(),Rewards:le.nullish()}).passthrough(),an=z.object({ServerTimeUtc:c.nullish(),Claimed:z.array(iC).default([]),Failed:z.array(Oo).default([]),Resources:M.nullish(),Inventory:Q.nullish(),UnreadCount:z.number().default(0),UnclaimedCount:z.number().default(0)}).passthrough(),Mc=z.object({ServerTimeUtc:c.nullish(),GiftID:z.string().nullish(),Sent:z.array(z.string()).default([]),Failed:z.array(Oo).default([]),Resources:M.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish()}).passthrough(),Oc=z.object({ServerTimeUtc:c.nullish(),MessageID:z.string().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),RecipientReceives:le.nullish(),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish(),IdempotentReplay:z.boolean().nullish()}).passthrough(),Uc=z.object({ServerTimeUtc:c.nullish(),ResetsAt:c.nullish(),Social:z.record(z.string(),z.object({IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ReceivedInPeriod:z.number().default(0),SentTo:z.array(z.string()).default([]),ResetsAt:c.nullish()}).passthrough()).default({}),Transfer:z.object({Enabled:z.boolean().default(false),IntervalSeconds:z.number().default(86400),SentInPeriod:z.number().default(0),RemainingInPeriod:z.number().default(0),ResetsAt:c.nullish()}).passthrough().nullish()}).passthrough();var Eo="Mailbox",qo={key:"mailbox.unread",login:"MailUnread",ttlMs:6e4},ln=class{constructor(e){this.ctx=e;e.cache.bindLoginView(qo,{schema:on,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(qo,{...t}),this.ctx.emitter.emit("mailbox:countersChanged",t);}get definitions(){return this.ctx.data.config.getSection(Eo)}get enabled(){return this.definitions?.Enabled===true}async getDefinitions(e){let t=this.ctx.cache.configSection(Eo,e);if(t)return a(t);let i=this.request();if(!i)return c$1;let s=await this.ctx.api.mailbox.getDefinitions(i);return s.ok&&this.ctx.data.config.patchSection(Eo,s.data),s}async getMessages(e){let t=this.request({Cursor:e?.cursor??void 0,PageSize:e?.pageSize,Category:e?.category,Language:e?.language??this.ctx.localization.locale??void 0});if(!t)return c$1;let i=await this.ctx.api.mailbox.getMessages(t);return i.ok&&(this.emitCounters(i.data),this.ctx.emitter.emit("mailbox:messagesLoaded",i.data)),i}getUnreadCount(e){return this.ctx.cache.read(qo,()=>this.fetchUnreadCount(),e)}async fetchUnreadCount(){let e=this.request();if(!e)return c$1;let t=await this.ctx.api.mailbox.getUnreadCount(e);return t.ok&&this.emitCounters(t.data),t}async readMessages(e){let t=this.request(e==="all"?{All:true}:{MessageIDs:e});if(!t)return c$1;let i=await this.ctx.api.mailbox.readMessages(t);return i.ok&&this.emitCounters(i.data),i}async claimReward(e){let t=e?.trim();if(!t)return b("client","MessageID is required.");let i=this.request({MessageID:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimReward(i)):c$1}async claimRewards(e){let t=(e??[]).map(s=>s?.trim()).filter(Boolean);if(t.length===0)return b("client","MessageIDs are required.");let i=this.request({MessageIDs:t});return i?this.afterClaim(await this.ctx.api.mailbox.claimRewardsBatch(i)):c$1}async claimAll(){let e=this.request();return e?this.afterClaim(await this.ctx.api.mailbox.claimAll(e)):c$1}afterClaim(e){return e.ok&&(this.ctx.data.user.applyResourcesWithDelta(e.data.Resources??null,e.data.Inventory??null,this.ctx.data.config.itemDefinitions),this.emitCounters(e.data),this.ctx.emitter.emit("mailbox:rewardsClaimed",e.data)),e}async deleteMessages(e,t){let i=this.request(e==="allRead"?{All:true}:{MessageIDs:e,Force:t?.force===true});if(!i)return c$1;let s=await this.ctx.api.mailbox.deleteMessages(i);return s.ok&&this.emitCounters(s.data),s}async sendGift(e,t){if(!e?.trim())return b("client","GiftID is required.");let i=(t??[]).filter(Boolean);if(i.length===0)return b("client","Recipients are required.");let s=this.request({GiftID:e.trim(),RecipientUserIDs:i});if(!s)return c$1;let n=await this.ctx.api.mailbox.sendGift(s);return n.ok&&(n.data.Resources&&this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:giftSent",n.data)),n}async sendTransfer(e,t,i){if(!e?.trim())return b("client","RecipientUserID is required.");if(!i?.requestID?.trim())return b("client","requestID is required.");let s=this.request({RecipientUserID:e.trim(),TransferEntries:t,Note:i.note,RelatedEntityID:i.requestID.trim()});if(!s)return c$1;let n=await this.ctx.api.mailbox.sendTransfer(s);return n.ok&&(n.data.IdempotentReplay||this.ctx.data.user.applyResourceOperation(n.data.Resources??null,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("mailbox:transferSent",n.data)),n}async getGiftStatus(){let e=this.request();return e?this.ctx.api.mailbox.getGiftStatus(e):c$1}};var sC={RequestSent:"RequestSent",Accepted:"Accepted",Declined:"Declined",Removed:"Removed"},nC={Title:"Title",Platform:"Platform"},Ec=z.object({UserID:z.string(),PublicData:Oe.nullish(),Source:z.enum(["Title","Platform"]).nullish()}),Ii=z.object({Friends:z.array(Ec).nullish()}),rC=z.object({FriendsCount:z.number().nullish(),IncomingRequestsCount:z.number().nullish(),OutgoingRequestsCount:z.number().nullish()}),vi=z.object({TargetUserID:z.string().nullish(),Status:z.string().nullish(),Target:Ec.nullish(),Counters:rC.nullish()}),oC={User:"User",Channel:"Channel",Title:"Title",WorkshopItem:"WorkshopItem",Post:"Post",Comment:"Comment"},aC={Like:"Like",Favorite:"Favorite"},lC={Inappropriate:"Inappropriate",Spam:"Spam",Stolen:"Stolen",Broken:"Broken",Other:"Other",Harassment:"Harassment"},uC={Visible:"Visible",HiddenByOwner:"HiddenByOwner",HiddenByModeration:"HiddenByModeration",Deleted:"Deleted"},cC={Attack:"Attack",Raid:"Raid",FriendAdded:"FriendAdded",WorkshopSale:"WorkshopSale",Followed:"Followed",Liked:"Liked",Commented:"Commented",Replied:"Replied",Mentioned:"Mentioned",ChannelCreated:"ChannelCreated",TipReceived:"TipReceived"},pC=z.object({Key:z.string().nullish(),DisplayName:z.string().nullish(),AvatarUrl:z.string().nullish()}).passthrough(),hC=z.object({Id:z.string(),Verb:z.string().nullish(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),Count:z.number().nullish(),LastActors:z.array(pC).nullish(),Payload:z.object({Title:z.string().nullish(),Excerpt:z.string().nullish(),ImageUrl:z.string().nullish()}).passthrough().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),OccurredAt:c.nullish(),OwnerImpact:M.nullish(),IsBlocked:z.boolean().nullish(),TargetObjectName:z.string().nullish()}).passthrough(),qc=z.object({Items:z.array(hC).nullish(),HasMore:z.boolean().nullish(),NextBeforeUpdatedAt:z.string().nullish(),NextBeforeID:z.string().nullish(),UnreadCount:z.number().nullish(),SeenAt:c.nullish()}).passthrough(),Ti=z.object({UnreadCount:z.number().nullish(),SeenAt:c.nullish()}).passthrough(),dC=z.object({Likes:z.number().nullish(),Favorites:z.number().nullish(),Followers:z.number().nullish(),Following:z.number().nullish(),Comments:z.number().nullish(),Replies:z.number().nullish(),Posts:z.number().nullish(),Dislikes:z.number().nullish()}).passthrough(),qt=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Counts:dC.nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish(),Following:z.boolean().nullish(),Blocked:z.boolean().nullish()}).passthrough(),Bc=z.object({Items:z.array(qt).nullish()}).passthrough(),Bo={HasMore:z.boolean().nullish(),NextCursorAt:z.string().nullish(),NextCursorID:z.string().nullish()},mC=z.object({UserID:z.string(),PublicData:Oe.nullish(),Mutual:z.boolean().nullish(),Since:c.nullish()}).passthrough(),un=z.object({Items:z.array(mC).nullish(),...Bo}).passthrough(),fC=z.object({EntityType:z.string().nullish(),EntityID:z.string().nullish(),Kind:z.string().nullish(),At:c.nullish()}).passthrough(),Lc=z.object({Items:z.array(fC).nullish(),...Bo}).passthrough(),cn=z.object({CommentID:z.string(),EntityType:z.string().nullish(),EntityID:z.string().nullish(),ParentCommentID:z.string().nullish(),AuthorUserID:z.string().nullish(),AuthorPublicData:Oe.nullish(),Text:z.string().nullish(),Status:z.string().nullish(),Pinned:z.boolean().nullish(),CreatedAt:c.nullish(),EditedAt:c.nullish(),Likes:z.number().nullish(),Replies:z.number().nullish(),Liked:z.boolean().nullish(),IsMine:z.boolean().nullish()}).passthrough(),Gc=z.object({Items:z.array(cn).nullish(),...Bo,TotalCount:z.number().nullish()}).passthrough(),Fc=z.object({CommentID:z.string().nullish(),Deleted:z.boolean().nullish()}).passthrough(),Vc=z.object({ReportID:z.string().nullish(),AlreadyReported:z.boolean().nullish(),AutoHidden:z.boolean().nullish()}).passthrough(),jc=z.object({CommentsEnabled:z.boolean().nullish(),CommentableTypes:z.array(z.string()).nullish(),CommentMaxLength:z.number().nullish(),CommentMaxLinks:z.number().nullish()}).passthrough(),gC="FRIENDS_FROM_PLATFORM",yC={Off:"Off",Default:"Default",Always:"Always"},RC={TitleOnly:"TitleOnly",TitleAndPlatform:"TitleAndPlatform",PlatformOnly:"PlatformOnly"},Nc=z.object({Profile:z.enum(["Off","Default","Always"]).nullish(),Friends:z.enum(["TitleOnly","TitleAndPlatform","PlatformOnly"]).nullish()}).passthrough(),Re={GetFriendsList:"GetFriendsList",GetIncomingRequests:"GetIncomingRequests",GetOutgoingRequests:"GetOutgoingRequests",GetRecommendedFriends:"GetRecommendedFriends",SendFriendRequest:"SendFriendRequest",AcceptFriendRequest:"AcceptFriendRequest",DeclineFriendRequest:"DeclineFriendRequest",RemoveFriend:"RemoveFriend",GetInbox:"GetInbox",MarkInboxSeen:"MarkInboxSeen",GetInboxUnread:"GetInboxUnread",Follow:"Follow",Unfollow:"Unfollow",GetFollowers:"GetFollowers",GetFollowing:"GetFollowing",Block:"Block",Unblock:"Unblock",GetBlocked:"GetBlocked",React:"React",Unreact:"Unreact",GetMyReactions:"GetMyReactions",GetEntityStates:"GetEntityStates",AddComment:"AddComment",EditComment:"EditComment",DeleteComment:"DeleteComment",GetComments:"GetComments",Report:"Report"};var Lo={key:"social.inboxUnread",login:"InboxUnread",ttlMs:6e4,dependsOn:["Social"],invalidateOn:["social:inboxLoaded"]},pn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Lo,{schema:Ti,apply:t=>this.ctx.emitter.emit("social:inboxBadge",t)});}ctx;async getFriendsList(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.social.getFriendsList(e);return t.ok&&(this.ctx.data.user.applySocialFriendsList(t.data.Friends),this.ctx.emitter.emit("social:friendsListLoaded",t.data)),t}async getIncomingRequests(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.social.getIncomingRequests(e);return t.ok&&(this.ctx.data.user.applySocialIncomingRequests(t.data.Friends),this.ctx.emitter.emit("social:incomingRequestsLoaded",t.data)),t}async getOutgoingRequests(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.social.getOutgoingRequests(e);return t.ok&&(this.ctx.data.user.applySocialOutgoingRequests(t.data.Friends),this.ctx.emitter.emit("social:outgoingRequestsLoaded",t.data)),t}friendRequestsAllowed(){return this.ctx.data.config.titlePublicConfiguration?.PlatformBridge?.Friends!=="PlatformOnly"}async getRecommendedFriends(e=5){let t=this.ctx.authedRequest();if(!t)return c$1;t.Limit=e;let i=await this.ctx.api.social.getRecommendedFriends(t);return i.ok&&this.ctx.emitter.emit("social:recommendedFriendsLoaded",i.data),i}async sendFriendRequest(e){if(!e)return b("client","TargetUserID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.sendFriendRequest(t);return i.ok&&(i.data.Status==="Accepted"?this.ctx.data.user.patchSocialAcceptFriend(e):this.ctx.data.user.patchSocialAddOutgoingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestSent",i.data)),i}async acceptFriendRequest(e){if(!e)return b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.acceptFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialAcceptFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestAccepted",i.data)),i}async declineFriendRequest(e){if(!e)return b("client","RequesterUserID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.declineFriendRequest(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveIncomingRequest(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRequestDeclined",i.data)),i}async removeFriend(e){if(!e)return b("client","FriendUserID is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),TargetUserID:e},i=await this.ctx.api.social.removeFriend(t);return i.ok&&(this.ctx.data.user.patchSocialRemoveFriend(e),this.ctx.data.user.applySocialCounters(i.data.Counters),this.ctx.emitter.emit("social:friendRemoved",i.data)),i}async getInbox(e={}){let t=this.ctx.authedRequest();if(!t)return c$1;t.InboxLimit=e.limit,t.InboxBeforeUpdatedAt=e.cursor?.beforeUpdatedAt??void 0,t.InboxBeforeID=e.cursor?.beforeID??void 0,t.InboxVerbs=e.verbs;let i=await this.ctx.api.social.getInbox(t);return i.ok&&this.ctx.emitter.emit("social:inboxLoaded",i.data),i}getInboxUnread(e){return this.ctx.cache.read(Lo,()=>this.fetchInboxUnread(),e)}async fetchInboxUnread(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.social.getInboxUnread(e);return t.ok&&this.ctx.emitter.emit("social:inboxBadge",t.data),t}async markInboxSeen(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.social.markInboxSeen(e);return t.ok&&(this.ctx.data.user.applySocialInboxSeenAt(t.data.SeenAt),this.ctx.cache.put(Lo,t.data),this.ctx.emitter.emit("social:inboxBadge",t.data)),t}follow(e,t){return this.mutate("follow",e,t)}unfollow(e,t){return this.mutate("unfollow",e,t)}block(e,t){return this.mutate("block",e,t)}unblock(e,t){return this.mutate("unblock",e,t)}getFollowers(e,t){return this.page("getFollowers",e,t)}getFollowing(e,t){return this.page("getFollowing",e,t)}getBlocked(e,t){return this.page("getBlocked",e,t)}like(e,t){return this.mutate("react",e,t,"Like")}unlike(e,t){return this.mutate("unreact",e,t,"Like")}favorite(e,t){return this.mutate("react",e,t,"Favorite")}unfavorite(e,t){return this.mutate("unreact",e,t,"Favorite")}async getMyReactions(e="Like",t={}){let i=this.ctx.authedRequest();return i?(i.ReactionKind=e,i.EntityType=t.entityType,this.applyPage(i,t.cursor,t.limit),this.ctx.api.social.getMyReactions(i)):c$1}async getEntityStates(e,t){if(!t?.length)return b("client","EntityIDs are required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityIDs=t,this.ctx.api.social.getEntityStates(i)):c$1}async addComment(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i?.trim())return b("client","Text is required.");n.Text=i,n.ParentCommentID=s;let r=await this.ctx.api.social.addComment(n);return r.ok&&this.ctx.emitter.emit("social:commentAdded",r.data),r}async editComment(e,t){if(!e)return b("client","CommentID is required.");if(!t?.trim())return b("client","Text is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.CommentID=e,i.Text=t;let s=await this.ctx.api.social.editComment(i);return s.ok&&this.ctx.emitter.emit("social:commentEdited",s.data),s}async deleteComment(e){if(!e)return b("client","CommentID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.CommentID=e;let i=await this.ctx.api.social.deleteComment(t);return i.ok&&this.ctx.emitter.emit("social:commentDeleted",i.data),i}async getComments(e,t,i={}){let s=this.targetRequest(e,t);return "ok"in s?s:(s.ParentCommentID=i.parentCommentID,this.applyPage(s,i.cursor,i.limit),this.ctx.api.social.getComments(s))}async report(e,t,i,s){let n=this.targetRequest(e,t);if("ok"in n)return n;if(!i)return b("client","ReportReason is required.");n.ReportReason=i,n.ReportComment=s;let r=await this.ctx.api.social.report(n);return r.ok&&this.ctx.emitter.emit("social:reported",r.data),r}async mutate(e,t,i,s){let n=this.targetRequest(t,i);if("ok"in n)return n;n.ReactionKind=s;let r=await this.ctx.api.social[e](n);return r.ok&&this.ctx.emitter.emit("social:entityStateChanged",r.data),r}async page(e,t,i){let s=this.ctx.authedRequest();return s?(this.applyPage(s,t,i),this.ctx.api.social[e](s)):c$1}applyPage(e,t,i){e.CursorAt=t?.at??void 0,e.CursorID=t?.id??void 0,e.PageLimit=i;}targetRequest(e,t){if(!e)return b("client","EntityType is required.");if(!t)return b("client","EntityID is required.");let i=this.ctx.authedRequest();return i?(i.EntityType=e,i.EntityID=t,i):c$1}};var _c="TimedBoost";function CC(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var hn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(e){let t=this.ctx.cache.configSection(_c,e);if(t)return this.ctx.emitter.emit("timedBoost:definitionsLoaded",t),a(t);let i=this.ctx.authedRequest();if(!i)return c$1;let s=await this.ctx.api.timedBoost.getDefinitions(i);return s.ok&&(this.ctx.data.config.patchSection(_c,s.data),this.ctx.emitter.emit("timedBoost:definitionsLoaded",s.data)),s}async getActive(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedBoost.getActive(e);return t.ok&&(this.ctx.data.user.applyTimedBoost({Active:t.data.Active??{}}),this.ctx.emitter.emit("timedBoost:activeLoaded",t.data)),t}async getActiveWindows(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedBoost.getActiveWindows(e);return t.ok&&this.ctx.emitter.emit("timedBoost:activeWindowsLoaded",t.data),t}async activate(e,t){let i=e.trim();if(!CC(i))return b("client",'BoostID is required and must not contain "." or "$".');if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),BoostID:i,SelectedOptionID:t?.selectedOptionID,Payment:t?.payment,RelatedEntityID:`timed_boost_activate_${i}_${d()}`},n=await this.ctx.api.timedBoost.activate(s);if(n.ok){let r=n.data;if(r.ActivatedBoost){let p=r.StackingPolicy??"Replace";this.ctx.data.user.patchActiveTimedBoost(r.ActivatedBoost,p);}this.ctx.data.user.applyResourceOperation(r.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("timedBoost:activated",r);}return n}async cleanupExpired(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.timedBoost.cleanupExpired(e);return t.ok&&(await this.getActive(),this.ctx.emitter.emit("timedBoost:expiredCleaned",void 0)),t}};var vt={Private:"Private",Public:"Public",ReadOnly:"ReadOnly",Internal:"Internal"},SC={Client:"Client",Server:"Server",System:"System"},xC=z.enum(["Client","Server","System"]).catch("Client"),bC=z.object({Value:z.string().nullish(),UpdatedAt:c.nullish(),Version:z.number().nullish(),LastWriter:xC.nullish(),ExpiresAt:c.nullish()}).passthrough(),dn=z.record(z.string(),bC),Wc=z.object({Version:z.number().nullish(),Private:dn.nullish(),Public:dn.nullish(),ReadOnly:dn.nullish()}),Go=z.object({UserID:z.string().nullish(),Version:z.number().nullish(),Public:dn.nullish()}),Fo=z.object({ServerTimeUtc:c.nullish(),Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:c.nullish()}),DC=z.object({Bucket:z.string().nullish(),KeyID:z.string(),Version:z.number().nullish(),ExpiresAt:c.nullish()}),Kc=z.object({ServerTimeUtc:c.nullish(),Results:z.array(DC).nullish()}),Qc=z.object({ServerTimeUtc:c.nullish(),DeletedCount:z.number().nullish()}),Hc=z.object({Results:z.array(Go).nullish(),NotFoundUserIDs:z.array(z.string()).nullish()}),PC={String:"String",Int:"Int",Bool:"Bool",Json:"Json"},IC=z.enum(["String","Int","Bool","Json"]).catch("String"),vC=z.object({KeyID:z.string(),Bucket:z.string().nullish(),ValueType:IC.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),mn=z.object({Keys:z.record(z.string(),vC).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),dt={GetUserCustomDataDefinitions:"GetUserCustomDataDefinitions",GetMyUserCustomData:"GetMyUserCustomData",GetPublicUserCustomDataOf:"GetPublicUserCustomDataOf",SetPrivateData:"SetPrivateData",SetPublicData:"SetPublicData",DeleteKey:"DeleteKey",BatchSet:"BatchSet",BatchDelete:"BatchDelete",BatchGetPublicUserCustomDataOf:"BatchGetPublicUserCustomDataOf"};var TC="UserCustomData";function $c(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}var fn=class{constructor(e){this.ctx=e;}ctx;async getUserCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.userCustomData.getUserCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(TC,t.data),this.ctx.emitter.emit("userCustomData:definitionsLoaded",t.data)),t}async getMyUserCustomData(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.userCustomData.getMyUserCustomData(e);return t.ok&&(this.ctx.data.user.applyUserCustomData(t.data),this.ctx.emitter.emit("userCustomData:myDataLoaded",t.data)),t}async getPublicUserCustomDataOf(e){let t=e.trim();if(!t)return b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.TargetUserID=t;let s=await this.ctx.api.userCustomData.getPublicUserCustomDataOf(i);return s.ok&&this.ctx.emitter.emit("userCustomData:publicDataLoaded",s.data),s}async setPrivateData(e,t){return this.setData(e,t,vt.Private)}async setPublicData(e,t){return this.setData(e,t,vt.Public)}async setData(e,t,i){let s=e.trim();if(!$c(s))return b("client",'KeyID is required and must not contain "." or "$".');if(t==null)return b("client","Value is required.");if(!this.ctx.auth.context)return c$1;let n={...this.ctx.buildAuthedBaseRequest(),KeyID:s,Value:t},p=await(i===vt.Private?this.ctx.api.userCustomData.setPrivateData(n):this.ctx.api.userCustomData.setPublicData(n));if(p.ok){let d=p.data;this.ctx.data.user.patchUserCustomDataKey(i,d.KeyID,t,d.Version??0,d.ExpiresAt),this.ctx.emitter.emit(i===vt.Private?"userCustomData:privateDataSet":"userCustomData:publicDataSet",d);}return p}async deleteKey(e,t){let i=e.trim();if(!$c(i))return b("client",'KeyID is required and must not contain "." or "$".');if(t!==vt.Private&&t!==vt.Public)return b("client","Only Private or Public keys can be deleted.");if(!this.ctx.auth.context)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),KeyID:i,Bucket:t},n=await this.ctx.api.userCustomData.deleteKey(s);return n.ok&&(this.ctx.data.user.removeUserCustomDataKey(t,i),this.ctx.emitter.emit("userCustomData:keyDeleted",void 0)),n}async batchSet(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),BatchSetItems:e},i=await this.ctx.api.userCustomData.batchSet(t);if(i.ok){for(let s of i.data.Results??[]){let n=s.Bucket??vt.Private,r=e.find(p=>p.Bucket===n&&p.KeyID===s.KeyID);r&&this.ctx.data.user.patchUserCustomDataKey(n,s.KeyID,r.Value,s.Version??0,s.ExpiresAt);}this.ctx.emitter.emit("userCustomData:batchSet",i.data);}return i}async batchDelete(e){if(!e.length)return b("client","At least one item is required.");if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),BatchDeleteItems:e},i=await this.ctx.api.userCustomData.batchDelete(t);if(i.ok){for(let s of e)this.ctx.data.user.removeUserCustomDataKey(s.Bucket,s.KeyID.trim());this.ctx.emitter.emit("userCustomData:batchDeleted",i.data);}return i}async batchGetPublicUserCustomDataOf(e){if(!e.length)return b("client","At least one target user id is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.TargetUserIDs=e;let i=await this.ctx.api.userCustomData.batchGetPublicUserCustomDataOf(t);return i.ok&&this.ctx.emitter.emit("userCustomData:batchPublicDataLoaded",i.data),i}};var kC="TitleCustomDataDefinitions",Jc=50;function zC(o){return o.length>0&&!o.includes(".")&&!o.includes("$")}function Vo(o){if(o.ExpiresAt==null)return false;let e=Date.parse(o.ExpiresAt);return !Number.isNaN(e)&&e<=Date.now()}function AC(o){let e={};for(let[t,i]of Object.entries(o))Vo(i)||(e[t]=i);return e}var gn=class{constructor(e){this.ctx=e;}ctx;lastRuntimeVersion=null;runtimeCache={};async getTitleCustomDataDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.titleCustomData.getTitleCustomDataDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(kC,t.data),this.ctx.emitter.emit("titleCustomData:definitionsLoaded",t.data)),t}async getPublicTitleData(e=true){let t=this.ctx.authedRequest();if(!t)return c$1;e&&this.lastRuntimeVersion!=null&&(t.KnownRuntimeVersion=this.lastRuntimeVersion);let i=await this.ctx.api.titleCustomData.getPublicTitleData(t);return i.ok&&this.absorb(i.data),i}async getPublicTitleDataKeys(e){let t=e.map(n=>n.trim()).filter(n=>n.length>0);if(!t.length)return b("client","At least one KeyID is required.");if(t.some(n=>!zC(n)))return b("client",'KeyID must not contain "." or "$".');if(t.length>Jc)return b("client",`At most ${Jc} keys per call \u2014 request them in chunks.`);let i=this.ctx.authedRequest();if(!i)return c$1;i.KeyIDs=t;let s=await this.ctx.api.titleCustomData.getPublicTitleDataKeys(i);return s.ok&&this.ctx.emitter.emit("titleCustomData:publicDataLoaded",s.data),s}getValue(e){let t=this.runtimeCache[e];if(t?.Value!=null&&!Vo(t))return t.Value;let i=this.staticCache[e];if(i?.Value!=null&&!Vo(i))return i.Value}get runtimeVersion(){return this.lastRuntimeVersion}staticCache={};absorb(e){e.Static&&(this.staticCache=e.Static),e.NotModified?(this.runtimeCache=AC(this.runtimeCache),e.Runtime=this.runtimeCache):e.Runtime&&(this.runtimeCache=e.Runtime),e.RuntimeVersion!=null&&(this.lastRuntimeVersion=e.RuntimeVersion),this.ctx.emitter.emit("titleCustomData:publicDataLoaded",e);}};var yn=class{constructor(e){this.ctx=e;}ctx;async getTitlePublicConfiguration(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.title.getTitlePublicConfiguration(e);return t.ok&&(this.ctx.data.config.applyTitlePublicConfiguration(t.data),this.ctx.emitter.emit("title:publicConfigurationReceived",t.data)),t}async getCurrencyDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.title.getCurrencyDefinitions(e);return t.ok&&(this.ctx.data.config.applyCurrencyDefinitions(t.data),this.ctx.emitter.emit("title:currencyDefinitionsReceived",t.data)),t}async getItemDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.title.getItemDefinitions(e);return t.ok&&(this.ctx.data.config.applyItemDefinitions(t.data),this.ctx.emitter.emit("title:itemDefinitionsReceived",t.data)),t}async getServerTime(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.title.getServerTime(e);return t.ok&&this.ctx.emitter.emit("title:serverTimeReceived",t.data),t}};var wC=15,MC="GameLoop",Zc="BoardDefinition",Rn=class{constructor(e){this.ctx=e;}ctx;get itemDefs(){return this.ctx.data.config.itemDefinitions}async getGameLoops(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.gameLoop.getGameLoops(e);return t.ok&&(this.ctx.data.config.patchSection(MC,t.data),this.ctx.emitter.emit("gameLoop:gameLoopsLoaded",t.data)),t}async getBoardDefinition(e=false,t){let i=this.ctx.cache.configSection(Zc,t);if(i)return this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",i),a(i);let s=this.ctx.authedRequest();if(!s)return c$1;let n=await this.ctx.api.gameLoop.getBoardDefinition(s,e);return n.ok&&(this.ctx.data.config.patchSection(Zc,n.data),this.ctx.emitter.emit("gameLoop:boardDefinitionLoaded",n.data)),n}async getBoardDefinitionForLevel(e,t=false){if(e<=0)return b("client","stageLevel must be > 0.");let i=this.ctx.authedRequest();if(!i)return c$1;i.StageLevel=e;let s=await this.ctx.api.gameLoop.getBoardDefinitionForLevel(i,t);return s.ok&&this.ctx.emitter.emit("gameLoop:boardDefinitionForLevelLoaded",s.data),s}async getUserBoardState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.gameLoop.getUserBoardState(e);return t.ok&&(this.ctx.data.user.applyBoardState(t.data),this.ctx.emitter.emit("gameLoop:boardStateLoaded",t.data)),t}async boardLoopRoll(e=1){if(e<1)return b("client","rollMultiplier must be >= 1.");let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),RollMultiplier:e,RelatedEntityID:`roll_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopRoll(i);if(s.ok){let n=s.data,r=wl(new Date,wC);this.ctx.data.user.patchBoardState(p=>{p.Position=n.NewPosition,p.CyclesCompleted=(p.CyclesCompleted??0)+(n.CyclesCompletedDelta??0),p.LastRollAtUtc=new Date().toISOString(),n.ActionRequired&&n.ActionData?p.Pending={Type:n.ActionRequired,TargetUserID:n.ActionData.TargetUserID,TargetPublicData:n.ActionData.PublicData,TargetBuildingStates:n.ActionData.TargetBuildingStates??void 0,TargetHasShield:n.ActionData.TargetHasShield??void 0,RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:r}:n.SpecialModeOffer&&(p.Pending={Type:"SPECIAL",RollMultiplier:n.UsedMultiplier??1,ExpiresAtUtc:r,Special:{ModeID:n.SpecialModeOffer.ModeID??void 0,Choices:n.SpecialModeOffer.Choices??void 0}});}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),n.ActionRequired==="RAID"&&await this.getUserBoardState(),this.ctx.emitter.emit("gameLoop:boardRolled",n);}return s}async boardLoopAttack(e=-1){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`attack_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopAttack(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.IsBotTarget&&n.Operation?this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs):!n.IsBotTarget&&n.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(n.DualResult.FromResult,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardAttacked",n);}else await this.getUserBoardState();return s}async boardLoopRaid(e,t){if(e<0||e>11)return b("client","digIndex must be between 0 and 11.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),DigIndex:e,RelatedEntityID:t??`raid_${i.userID}_${d()}`},n=await this.ctx.api.gameLoop.boardLoopRaid(s);if(n.ok){let r=n.data;r.Status==="CONTINUE"?this.ctx.data.user.patchBoardPendingRaidLayout(r.RaidLayout,r.OpenedIndex??-1):(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(r)),this.ctx.emitter.emit("gameLoop:boardRaided",r);}else await this.getUserBoardState();return n}async boardLoopRaidFast(e){if(!e.length)return b("client","digIndices must not be empty.");let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),DigIndices:e,RelatedEntityID:`raidfast_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopRaidFast(i);if(s.ok){let n=s.data;n.Status!=="CONTINUE"&&(this.ctx.data.user.clearBoardPending(),this.applyRaidResources(n)),this.ctx.emitter.emit("gameLoop:boardRaidedFast",n);}else await this.getUserBoardState();return s}async boardLoopBuild(e){if(e<0)return b("client","buildingIndex must be >= 0.");let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),BuildingIndex:e,RelatedEntityID:`build_${t.userID}_${e}_${d()}`},s=await this.ctx.api.gameLoop.boardLoopBuild(i);if(s.ok){let n=s.data;n.StageComplete?this.ctx.data.user.patchBoardState(r=>{r.StageLevel=(r.StageLevel??1)+1,r.Position=0,r.Pending=null,r.BuildingStates=null;}):this.ctx.data.user.patchBoardBuilding(n.BuiltIndex,r=>{n.NewLevel!=null&&(r.Level=n.NewLevel),r.IsDamaged=false,n.MaxLevelRewardClaimed&&(r.MaxLevelRewardClaimed=true);}),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardBuilt",n);}return s}async boardSpecialChoose(e,t){if(!e)return b("client","choiceID must not be empty.");let i=this.ctx.auth.context;if(!i)return c$1;let s={...this.ctx.buildAuthedBaseRequest(),ChoiceID:e,SelectedOptionID:t,RelatedEntityID:`special_choose_${i.userID}_${d()}`},n=await this.ctx.api.gameLoop.boardSpecialChoose(s);if(n.ok){let r=n.data;r.Mode==="Instant"||r.Mode===0?this.ctx.data.user.clearBoardPending():this.ctx.data.user.patchBoardSpecialPending(d=>{d.ChoiceID=e,d.ChosenMode=r.Mode??"Timed",d.StartedAtUtc=r.StartedAtUtc??null,d.DurationSeconds=r.DurationSeconds??null,d.AdViewsUsed=0;}),r.Operation&&this.ctx.data.user.applyResourcesWithDelta(r.Operation,r.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialChose",r);}return n}async boardSpecialApplyMultiplier(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:e??`special_ad_${t.userID}_${d()}`},s=await this.ctx.api.gameLoop.boardSpecialApplyMultiplier(i);if(s.ok){let n=s.data;this.ctx.data.user.patchBoardSpecialPending(r=>{r.AdViewsUsed=n.AdViewsUsed??0,r.AccumulatedMultiplier=n.AccumulatedMultiplier??0;}),this.ctx.emitter.emit("gameLoop:boardSpecialApplyMultiplier",n);}return s}async boardSpecialClaim(e){let t=this.ctx.auth.context;if(!t)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),RelatedEntityID:`special_claim_${t.userID}_${d()}`,...e&&Object.keys(e).length>0?{RunStats:e}:{}},s=await this.ctx.api.gameLoop.boardSpecialClaim(i);if(s.ok){let n=s.data;this.ctx.data.user.clearBoardPending(),n.Operation&&this.ctx.data.user.applyResourcesWithDelta(n.Operation,n.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:boardSpecialClaimed",n);}return s}async getCommunityChestState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.gameLoop.getCommunityChestState(e);return t.ok&&(this.ctx.data.user.applyCommunityChestUserState(t.data.UserState??null),this.ctx.emitter.emit("gameLoop:communityChestStateLoaded",t.data)),t}async joinOrCreateCommunityChest(){if(!this.ctx.auth.context)return c$1;let e={...this.ctx.buildAuthedBaseRequest()},t=await this.ctx.api.gameLoop.joinOrCreateCommunityChest(e);if(t.ok){let i=t.data.Group;i?.GroupID&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:i.GroupID,ActiveRoundIndex:i.RoundIndex??void 0}),this.ctx.emitter.emit("gameLoop:communityChestJoined",t.data);}return t}async claimCommunityChestMilestone(e,t){if(!e)return b("client","milestoneID is required.");if(!this.ctx.auth.context)return c$1;let i={...this.ctx.buildAuthedBaseRequest(),MilestoneID:e,GroupID:t},s=await this.ctx.api.gameLoop.claimCommunityChestMilestone(i);return s.ok&&(s.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestMilestoneClaimed",s.data)),s}async claimCommunityChestGrandPrize(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.claimCommunityChestGrandPrize(t);return i.ok&&(i.data.Resources&&this.ctx.data.user.applyResourcesWithDelta(i.data.Resources,i.data.Inventory,this.itemDefs),this.ctx.emitter.emit("gameLoop:communityChestGrandPrizeClaimed",i.data)),i}async leaveCommunityChest(e){if(!this.ctx.auth.context)return c$1;let t={...this.ctx.buildAuthedBaseRequest(),GroupID:e},i=await this.ctx.api.gameLoop.leaveCommunityChest(t);return i.ok&&(i.data.Success&&this.ctx.data.user.applyCommunityChestUserState({ActiveGroupID:void 0,ActiveRoundIndex:-1}),this.ctx.emitter.emit("gameLoop:communityChestLeft",i.data)),i}applyRaidResources(e){e.Operation?this.ctx.data.user.applyResourcesWithDelta(e.Operation,e.Inventory,this.itemDefs):e.DualResult?.FromResult&&this.ctx.data.user.applyResourceOperation(e.DualResult.FromResult,this.itemDefs);}};var Cn=class{constructor(e){this.ctx=e;}ctx;async execute(e,t,i,s){let n=e.trim();if(!n)return b("client","FunctionName is required.");if(!this.ctx.auth.context)return c$1;let r={...this.ctx.buildAuthedBaseRequest(),FunctionName:n,FunctionParameter:t,RevisionSelection:i,SpecificRevision:s},p=await this.ctx.api.cloudCode.execute(r);return p.ok&&this.ctx.emitter.emit("cloudCode:executed",p.data),p}};var Yc=z.object({ServerTimeUtc:c,SourceType:ii,SourceID:z.string(),TargetType:ii,TargetID:z.string(),SourceSpent:_,FeeAmount:_,RateApplied:Y,TargetCredited:_}),Xc=z.object({ServerTimeUtc:c,SourceType:ii,SourceID:z.string(),TargetType:ii,TargetID:z.string(),SourceSpent:Y,FeeAmount:Y,RateApplied:Y,TargetCredited:Y}),Sn={Convert:"Convert",CryptoConvert:"CryptoConvert"},OC={Active:"Active",Hidden:"Hidden",Deprecated:"Deprecated",Maintenance:"Maintenance"},ep=z.enum(["Active","Hidden","Deprecated","Maintenance"]).catch("Active"),UC={Automatic:"Automatic",Manual:"Manual"},EC=z.enum(["Automatic","Manual"]).catch("Automatic"),qC=z.object({ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),InitialDeposit:z.number().nullish(),MinBalance:z.number().nullish(),MaxBalance:z.number().nullish(),DailyEarnLimit:z.number().nullish(),DailySpendLimit:z.number().nullish()}).passthrough(),BC=z.object({Rate:z.number().nullish(),Max:z.number().nullish(),Period:z.number().nullish()}).passthrough(),LC=z.object({IsTradable:z.boolean().nullish(),IsPurchasable:z.boolean().nullish(),IsRefundable:z.boolean().nullish()}).passthrough(),GC=z.object({TargetCurrencyType:ii.nullish(),TargetCurrencyID:z.string(),Rate:Y.nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish(),DailyLimit:z.number().nullish()}).passthrough(),tp=z.object({Enabled:z.boolean().nullish(),RateMode:EC.nullish(),Fee:z.number().nullish(),Targets:z.array(GC).nullish()}).passthrough(),ip=z.object({CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough(),FC=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Economy:qC.nullish(),Recharge:BC.nullish(),Conversion:tp.nullish(),Permissions:LC.nullish(),Audit:ip.nullish(),Status:ep.nullish()}).passthrough(),VC=z.object({NetworkID:z.string(),ContractAddress:z.string().nullish(),Decimals:z.number().nullish(),MinWithdraw:Y.nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),jC=z.object({DailyWithdrawUsd:Y.nullish(),MonthlyWithdrawUsd:Y.nullish(),KycRequiredAboveUsd:Y.nullish()}).passthrough(),NC=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),SpendableInGame:z.boolean().nullish(),ConvertibleToVirtual:z.boolean().nullish()}).passthrough(),_C=z.object({Mode:z.string().nullish(),FundingNetworkID:z.string().nullish(),PerPlayerDailyTokens:z.number().nullish(),TitleDailyTokens:z.number().nullish(),RefuseOverCap:z.boolean().nullish()}).passthrough(),jo=z.object({CurrencyID:z.string(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),DisplayDecimals:z.number().nullish(),ValueInUSD:Y.nullish(),ValueInUSDUpdatedAt:c.nullish(),UsdPriceRefreshMinutes:z.number().nullish(),DeveloperWithdrawalFeePercent:Y.nullish(),CommunityMarketingWithdrawalFeePercent:Y.nullish(),WithdrawalBurnPercent:Y.nullish(),PlayerTradeFeePercent:Y.nullish(),Networks:z.array(VC).nullish(),Limits:jC.nullish(),Permissions:NC.nullish(),Conversion:tp.nullish(),Audit:ip.nullish(),Status:ep.nullish(),ServerGrantPolicy:_C.nullish(),UnbackedRewardCurrencyID:z.string().nullish()}).passthrough(),xn=z.object({VirtualCurrencies:z.record(z.string(),FC).nullish(),CryptoCurrencies:z.record(z.string(),jo).nullish()}).passthrough();var WC={EVM:"EVM",Solana:"Solana"},KC=z.enum(["EVM","Solana"]).catch("EVM"),QC={AutoLinkedFromTransaction:"AutoLinkedFromTransaction",SignatureVerified:"SignatureVerified",ManuallyLinked:"ManuallyLinked"},HC=z.enum(["AutoLinkedFromTransaction","SignatureVerified","ManuallyLinked"]).catch("AutoLinkedFromTransaction"),$C={Token:"Token",Nft:"Nft"},sp=z.enum(["Token","Nft"]).catch("Token"),JC={NotRequested:"NotRequested",Pending:"Pending",Verified:"Verified",Rejected:"Rejected",Expired:"Expired"},ZC=z.enum(["NotRequested","Pending","Verified","Rejected","Expired"]).catch("NotRequested"),YC={None:"None",Tier1:"Tier1",Tier2:"Tier2",Tier3:"Tier3"},XC=z.enum(["None","Tier1","Tier2","Tier3"]).catch("None"),eS={Pending:"Pending",Completed:"Completed",Failed:"Failed",Expired:"Expired",Abandoned:"Abandoned"},No=z.enum(["Pending","Completed","Failed","Expired","Abandoned"]).catch("Pending"),np={GameTopUp:"game_topup",CommunityReward:"community_reward"};function bn(o){let e=o?.trim();return e||np.GameTopUp}var tS={UsersCryptoWallet:"UsersCryptoWallet",Game:"Game"},rp=z.enum(["UsersCryptoWallet","Game"]).catch("UsersCryptoWallet"),iS=z.object({ContractAddress:z.string().nullish(),ItemCatalogID:z.string().nullish(),DisplayName:z.string().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish()}).passthrough(),op=z.object({Ios:z.boolean().nullish(),Android:z.boolean().nullish(),Web:z.boolean().nullish()}).passthrough(),sS=z.object({NetworkID:z.string().nullish(),DisplayName:z.string().nullish(),Type:KC.nullish(),ChainID:z.number().nullish(),ChainTicker:z.string().nullish(),RewardPoolAddress:z.string().nullish(),VaultDepositAddress:z.string().nullish(),ChainConfigVersion:z.number().nullish(),RequiredConfirmations:z.number().nullish(),DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:op.nullish(),NftCollections:z.array(iS).nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),RpcUrl:z.string().nullish(),GasPrice:z.number().nullish(),NftBridgeAddress:z.string().nullish(),SignatureEpoch:z.number().nullish()}).passthrough(),nS=z.object({DepositsEnabled:z.boolean().nullish(),WithdrawalsEnabled:z.boolean().nullish(),NftDepositsEnabled:z.boolean().nullish(),NftWithdrawalsEnabled:z.boolean().nullish(),PlatformOverrides:op.nullish()}).passthrough(),rS=z.object({MinAccountAgeDays:z.number().nullish(),MultiAccountCheckEnabled:z.boolean().nullish(),BanOnSharedWithdrawalAddress:z.boolean().nullish(),PendingWithdrawalTtlHours:z.number().nullish()}).passthrough(),oS={OnChain:"OnChain",Combined:"Combined",InGame:"InGame"},aS=z.enum(["OnChain","Combined","InGame"]).catch("OnChain"),ap=z.object({Enabled:z.boolean().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),MinBalance:Y.nullish(),BalanceSource:aS.nullish(),DenyMessage:z.string().nullish()}).passthrough(),lS=z.object({Enabled:z.boolean().nullish(),WalletConnectProjectId:z.string().nullish()}).passthrough(),uS={Open:"Open",AnyWithLinkedWallet:"AnyWithLinkedWallet",WalletOnly:"WalletOnly"},ki=z.enum(["Open","AnyWithLinkedWallet","WalletOnly"]).catch("Open"),cS=z.object({Mode:ki.nullish(),TokenGates:z.array(ap).nullish()}).passthrough(),_o=z.object({SystemState:nS.nullish(),Networks:z.record(z.string(),sS).nullish(),AccountSafety:rS.nullish(),WalletLogin:lS.nullish(),PlayAccess:cS.nullish(),IframeConnectHosts:z.array(z.string()).nullish()}).passthrough(),pS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),LinkedAt:c.nullish(),LastUsedAt:c.nullish(),LinkType:HC.nullish(),IsSignatureVerified:z.boolean().nullish()}).passthrough(),lp=z.object({TitleTransactionID:z.string().nullish(),Type:sp.nullish(),NetworkID:z.string().nullish(),AssetID:z.string().nullish(),Amount:Y.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),hS=z.object({Status:ZC.nullish(),Tier:XC.nullish(),VerifiedAt:c.nullish(),ExpiresAt:c.nullish(),RejectedAt:c.nullish(),ProviderReference:z.string().nullish(),RejectionReason:z.string().nullish()}).passthrough(),dS=z.object({CurrencyID:z.string().nullish(),Deposits:z.number().nullish(),DepositsVolumeNative:Y.nullish(),DepositsVolumeUsd:Y.nullish(),Withdrawals:z.number().nullish(),WithdrawalsVolumeNative:Y.nullish(),WithdrawalsVolumeUsd:Y.nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),mS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),TotalDepositsVolumeUsd:Y.nullish(),TotalWithdrawalsVolumeUsd:Y.nullish(),PerCurrency:z.record(z.string(),dS).nullish()}).passthrough(),fS=z.object({NetworkID:z.string().nullish(),ItemCatalogID:z.string().nullish(),Deposits:z.number().nullish(),Withdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),FirstDepositAt:c.nullish(),LastDepositAt:c.nullish(),FirstWithdrawalAt:c.nullish(),LastWithdrawalAt:c.nullish()}).passthrough(),gS=z.object({TotalDeposits:z.number().nullish(),TotalWithdrawals:z.number().nullish(),FailedWithdrawals:z.number().nullish(),RejectedDeposits:z.number().nullish(),PerCollection:z.record(z.string(),fS).nullish()}).passthrough(),yS=z.object({Tokens:mS.nullish(),Nfts:gS.nullish()}).passthrough(),Wo=z.object({CurrencyID:z.string().nullish(),Balance:Y.nullish(),MinBalance:Y.nullish()}).passthrough(),Bt=z.object({Granted:z.boolean(),Mode:ki.nullish(),Error:z.string().nullish(),WalletRequired:z.boolean().nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),GrantedUntil:c.nullish(),Balances:z.array(Wo).nullish()}).passthrough(),RS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:c.nullish(),Passed:z.boolean().nullish(),GrantedUntil:c.nullish(),Error:z.string().nullish(),Balances:z.array(Wo).nullish()}).passthrough(),CS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CanUnlink:z.boolean().nullish()}).passthrough(),up=z.object({Mode:ki.nullish(),TokenGates:z.array(ap).nullish(),WalletLoginEnabled:z.boolean().nullish(),CanLinkWallet:z.boolean().nullish(),WalletsFromPlatformProfile:z.boolean().nullish(),LinkedWallets:z.array(CS).nullish(),Status:Bt.nullish()}).passthrough(),SS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CheckedAt:c.nullish(),LoggedInAt:c.nullish(),GatePassed:z.boolean().nullish(),GatedBalances:z.array(Wo).nullish()}).passthrough(),xS=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),UnlinkedAt:c.nullish()}).passthrough(),bS=z.object({Version:z.number().nullish(),Stats:yS.nullish(),LinkedWallets:z.record(z.string(),pS).nullish(),LastWalletLogin:SS.nullish(),PlayAccess:RS.nullish(),PendingWithdrawals:z.array(lp).nullish(),Kyc:hS.nullish(),FirstActivityAt:c.nullish(),LastActivityAt:c.nullish(),IsFlagged:z.boolean().nullish(),FlagReason:z.string().nullish(),UnlinkedWallets:z.array(xS).nullish()}).passthrough(),DS=z.object({CurrencyID:z.string(),AmountDelta:Y,FrozenDelta:Y,UpdatedAt:c}).passthrough(),hi=z.object({CryptoBalances:z.record(z.string(),DS).nullish(),PendingAdded:lp.nullish(),PendingRemovedIDs:z.array(z.string()).nullish()}).passthrough(),PS=z.object({Amount:Y,Frozen:Y,CreatedAt:c.nullish(),UpdatedAt:c.nullish()}).passthrough().transform(o=>o),IS=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:rp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:No.nullish(),SignatureData:z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),TokenID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountUsd:Y.nullish(),NetPayoutAmount:Y.nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:c.nullish(),BurnAmount:z.number().nullish(),RefundedAt:c.nullish(),RefundCheckedAt:c.nullish()}).passthrough(),vS=z.object({ID:z.string().nullish(),TitleID:z.string().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),UserID:z.string().nullish(),TransactionHash:z.string().nullish(),Nonce:z.string().nullish(),NetworkID:z.string().nullish(),ChainType:z.string().nullish(),ChainID:z.number().nullish(),Direction:rp.nullish(),From:z.string().nullish(),To:z.string().nullish(),Amount:Y.nullish(),Status:No.nullish(),SignatureData:z.string().nullish(),CompletedAt:c.nullish(),ExpiresAt:c.nullish(),FailReason:z.string().nullish(),Reason:z.string().nullish(),Category:z.string().nullish(),NFTID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),SkinID:z.string().nullish(),TemplateID:z.string().nullish(),DataType:z.string().nullish(),TitleDeletedAt:c.nullish()}).passthrough(),cp=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),Ko=z.object({TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),ContractAddress:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(cp).nullish(),Signature:z.string().nullish()}).passthrough(),Qo=z.object({Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),ProgramID:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(cp).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),pp=z.object({Blockchain:_o.nullish(),CryptoCurrencies:z.record(z.string(),jo).nullish()}).passthrough(),hp=z.object({State:bS.nullish(),CryptoBalances:z.record(z.string(),PS).nullish()}).passthrough(),dp=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),StateDelta:hi.nullish()}).passthrough(),mp=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),fp=z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),NetAmountNative:Y.nullish(),BurnAmountNative:Y.nullish(),AmountUsd:Y.nullish(),ExpiresAt:c.nullish(),EvmSignature:Ko.nullish(),SolanaSignature:Qo.nullish(),StateDelta:hi.nullish(),ChainID:z.number().nullish()}).passthrough(),gp=z.object({ServerTimeUtc:c.nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ItemID:z.string().nullish(),CatalogID:z.string().nullish(),NftTokenID:z.string().nullish(),Amount:z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish(),EvmSignature:Ko.nullish(),SolanaSignature:Qo.nullish(),StateDelta:hi.nullish(),Inventory:Q.nullish()}).passthrough(),yp=z.object({TokenTransactions:z.array(IS).nullish(),NFTTransactions:z.array(vS).nullish(),RefundedIDs:z.array(z.string()).nullish()}).passthrough(),Ho=z.object({ServerTimeUtc:c.nullish(),TransactionHash:z.string().nullish(),NetworkID:z.string().nullish(),CurrencyID:z.string().nullish(),AmountNative:Y.nullish(),AmountUsd:Y.nullish(),Target:z.string().nullish()}).passthrough(),Rp=z.object({TitleTransactionID:z.string().nullish(),Kind:sp.nullish(),EvmSignature:Ko.nullish(),SolanaSignature:Qo.nullish()}).passthrough(),Cp=z.object({TitleTransactionID:z.string().nullish(),OnChainTxHash:z.string().nullish(),Status:No.nullish(),StateDelta:hi.nullish()}).passthrough(),Qe={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",DepositToken:"DepositToken",DepositNFT:"DepositNFT",RequestTokenWithdrawal:"RequestTokenWithdrawal",RequestNFTWithdrawal:"RequestNFTWithdrawal",GetTransactionHistory:"GetTransactionHistory",RetryWithdrawal:"RetryWithdrawal",ConfirmWithdrawal:"ConfirmWithdrawal",DonateToDeveloper:"DonateToDeveloper",DonateToUsersPool:"DonateToUsersPool",GetPlayAccess:"GetPlayAccess",ConfirmPlayAccess:"ConfirmPlayAccess"};var TS="Blockchain",Sp="Blockchain:Definitions",Dn=class{constructor(e){this.ctx=e;}ctx;definitionsInflight=null;async getDefinitions(e){let t=this.ctx.cache.configSection(Sp,e);if(t)return a(t);if(this.definitionsInflight&&!e?.forceRefresh)return this.definitionsInflight;let i=this.ctx.authedRequest();if(!i)return c$1;let s=this.ctx.api.blockchain.getDefinitions(i).then(n=>(n.ok&&(this.ctx.data.config.patchSection(TS,n.data.Blockchain),this.ctx.data.config.patchSection(Sp,n.data),this.ctx.emitter.emit("blockchain:definitionsLoaded",n.data)),n)).finally(()=>{this.definitionsInflight===s&&(this.definitionsInflight=null);});return this.definitionsInflight=s,s}async getUserState(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.blockchain.getUserState(e);return t.ok&&(this.ctx.data.user.applyBlockchainState(t.data.State??null,t.data.CryptoBalances),this.ctx.emitter.emit("blockchain:userStateLoaded",t.data)),t}async depositToken(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositToken(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenDeposited",s.data)),s}async depositNFT(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.depositNFT(i);return s.ok&&(this.ctx.data.user.applyResourcesWithDelta(s.data.Resources,s.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftDeposited",s.data)),s}async requestTokenWithdrawal(e,t,i,s,n){if(!e)return b("client","CurrencyID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let r=this.ctx.authedRequest();if(!r)return c$1;r.CurrencyID=e,r.NetworkID=t,r.WalletAddress=i,r.Amount=s,r.Category=bn(n);let p=await this.ctx.api.blockchain.requestTokenWithdrawal(r);return p.ok&&(this.ctx.data.user.applyBlockchainStateDelta(p.data.StateDelta),this.ctx.emitter.emit("blockchain:tokenWithdrawalRequested",p.data)),p}async requestNFTWithdrawal(e,t,i,s,n,r,p){if(!e)return b("client","ItemID is required.");if(!t)return b("client","NetworkID is required.");if(!i)return b("client","WalletAddress is required.");if(!s)return b("client","Amount is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.NetworkID=t,d.WalletAddress=i,d.Amount=s,d.Category=bn(n),r!==void 0&&(d.Level=r),p&&(d.ItemInstanceID=p);let C=await this.ctx.api.blockchain.requestNFTWithdrawal(d);return C.ok&&(this.ctx.data.user.applyBlockchainStateDelta(C.data.StateDelta),this.ctx.data.user.applyResourcesWithDelta(C.data.Resources,C.data.Inventory,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("blockchain:nftWithdrawalRequested",C.data)),C}async getTransactionHistory(e=50){let t=this.ctx.authedRequest();if(!t)return c$1;t.Amount=String(e);let i=await this.ctx.api.blockchain.getTransactionHistory(t);return i.ok&&this.ctx.emitter.emit("blockchain:transactionHistoryLoaded",i.data),i}async retryWithdrawal(e){if(!e)return b("client","TitleTransactionID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.TitleTransactionID=e;let i=await this.ctx.api.blockchain.retryWithdrawal(t);return i.ok&&this.ctx.emitter.emit("blockchain:withdrawalRetried",i.data),i}async confirmWithdrawal(e,t){if(!e)return b("client","TitleTransactionID is required.");if(!t)return b("client","On-chain TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.TitleTransactionID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.confirmWithdrawal(i);return s.ok&&(this.ctx.data.user.applyBlockchainStateDelta(s.data.StateDelta),this.ctx.emitter.emit("blockchain:withdrawalConfirmed",s.data)),s}async donateToDeveloper(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToDeveloper(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToDeveloper",s.data),s}async donateToUsersPool(e,t){if(!e)return b("client","NetworkID is required.");if(!t)return b("client","TransactionHash is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.NetworkID=e,i.TransactionHash=t;let s=await this.ctx.api.blockchain.donateToUsersPool(i);return s.ok&&this.ctx.emitter.emit("blockchain:donatedToUsersPool",s.data),s}async getPlayAccess(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.blockchain.getPlayAccess(e);return t.ok&&t.data.Status!==void 0&&this.ctx.auth.setPlayAccess(t.data.Status??null),t}async confirmPlayAccess(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&(t.NetworkID=e);let i=await this.ctx.api.blockchain.confirmPlayAccess(t);return i.ok&&this.ctx.auth.setPlayAccess(i.data),i}};var kS={Head:"Head",Torso:"Torso",Legs:"Legs"},Pn=z.enum(["Head","Torso","Legs"]).catch("Head"),zS={Open:"Open",InProgress:"InProgress",Cancelled:"Cancelled",Completed:"Completed",Expired:"Expired"},$o=z.enum(["Open","InProgress","Cancelled","Completed","Expired"]).catch("Open"),bp=z.object({AttackTarget:Pn,DefenseTarget:Pn});var AS=z.enum(["Hit","Critical","Block","Dodge"]).catch("Hit"),wS=z.object({RoundIndex:z.number().nullish(),AttackerID:z.string().nullish(),DefenderID:z.string().nullish(),AttackZone:Pn.nullish(),DefenseZone:Pn.nullish(),HitType:AS.nullish(),DamageDealt:z.number().nullish(),DefenderHpRemaining:z.number().nullish()}).passthrough(),MS=z.object({MaxHp:z.number().nullish(),CurrentHp:z.number().nullish(),Damage:z.number().nullish(),AttackSpeed:z.number().nullish(),CritChance:z.number().nullish(),CritMultiplier:z.number().nullish(),Armor:z.number().nullish(),DodgeChance:z.number().nullish()}).passthrough(),OS=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),xp=z.object({UserID:z.string().nullish(),SelectedCharacterID:z.string().nullish(),SelectedCharacter:xo.nullish(),BattleStrategy:z.array(bp).nullish(),UnstackableItems:z.record(z.string(),OS).nullish(),Stats:MS.nullish()}).passthrough(),US=z.object({WinnerUserID:z.string().nullish(),LoserUserID:z.string().nullish(),Entry:le.nullish(),NetReward:le.nullish(),BattleLog:z.array(wS).nullish(),IsDraw:z.boolean().nullish(),P1BattleProfile:xp.nullish(),P2BattleProfile:xp.nullish()}).passthrough(),Dp=z.object({MatchID:z.string(),TitleID:z.string().nullish(),RuleID:z.string().nullish(),CreatedAt:c.nullish(),CreatorID:z.string().nullish(),CreatorCharacterID:z.string().nullish(),CreatorStrategy:z.array(bp).nullish(),TargetUserID:z.string().nullish(),Entry:le.nullish(),CreationCostPaid:le.nullish(),RefundCreationCostOnCancel:z.boolean().nullish(),ExpiresAt:c.nullish(),JoinedByUserID:z.string().nullish(),JoinedByCharacterID:z.string().nullish(),JoinedAt:c.nullish(),Status:$o.nullish(),WinnerUserID:z.string().nullish(),CompletedAt:c.nullish(),IsRewardDistributed:z.boolean().nullish(),RewardDistributedAt:c.nullish()}).passthrough(),Pp=z.object({Status:$o,MatchID:z.string(),Entry:le.nullish(),Resources:M.nullish()}),Ip=z.object({Match:Dp.nullish()}),vp=z.object({MatchID:z.string(),Status:$o,Resources:M.nullish()}),Tp=z.object({Battle:US.nullish(),Resources:M.nullish(),ResourcesDual:bt.nullish()}),Jo=z.object({Matches:z.array(Dp).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}),Rt={CreateMatch:"CreateMatch",UpdateMatch:"UpdateMatch",CancelMatch:"CancelMatch",InstantBattle:"InstantBattle",SaveStrategy:"SaveStrategy",GetMyMatches:"GetMyMatches",GetAvailableMatches:"GetAvailableMatches",GetDefinitions:"GetDefinitions"};var ES=z.enum(["VirtualCurrency","Item","EventToken","CryptoCurrency"]).catch("VirtualCurrency");var qS=z.enum(["Constant","Variable","Curve"]).catch("Constant"),BS=z.object({HealthStatID:z.string().nullish(),DamageStatID:z.string().nullish(),ArmorStatID:z.string().nullish(),AttackSpeedStatID:z.string().nullish(),CritChanceStatID:z.string().nullish(),CritDamageStatID:z.string().nullish(),DodgeStatID:z.string().nullish(),AllMightStatID:z.string().nullish()}).passthrough(),LS=z.enum(["Flat","PercentReduction"]).catch("Flat"),GS=z.object({MaxRounds:z.number().nullish(),BlockDamageMultiplier:z.number().nullish(),MinHitDamage:z.number().nullish(),DefaultCritMultiplier:z.number().nullish(),MaxCritChance:z.number().nullish(),MaxDodgeChance:z.number().nullish(),ArmorMode:LS.nullish(),MaxArmorReduction:z.number().nullish()}).passthrough(),FS=z.object({Kind:qS.nullish(),Constant:z.number().nullish(),VariableID:z.string().nullish(),Argument:z.string().nullish(),Curve:Fe.nullish(),OnePlus:z.boolean().nullish()}).passthrough(),VS=z.object({Coefficient:z.number().nullish(),Factors:z.array(FS).nullish()}).passthrough(),Kt=z.object({Terms:z.array(VS).nullish()}).passthrough(),jS=z.object({Health:Kt.nullish(),Damage:Kt.nullish(),Armor:Kt.nullish(),AttackSpeed:Kt.nullish(),CritChance:Kt.nullish(),CritDamage:Kt.nullish(),Dodge:Kt.nullish()}).passthrough(),kp=z.object({StatMapping:BS.nullish(),Combat:GS.nullish(),Formula:jS.nullish()}).passthrough(),NS=z.object({BurnRate:z.number().nullish()}).passthrough(),zi=z.object({Kind:ES.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),TokenType:Fi.nullish(),EntityID:z.string().nullish(),MinAmount:z.number().nullish(),MaxAmount:z.number().nullish()}).passthrough(),zp=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(zi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),Ap=z.object({PriceOptions:ae.nullish(),RefundCostOnCancel:z.boolean().nullish(),MaxOpenMatches:z.number().nullish(),OfferLifetimeSeconds:z.number().nullish(),Limits:ye.nullish(),AllowPrivateMatches:z.boolean().nullish(),MaxMatchesPerOpponentPerDay:z.number().nullish()}).passthrough(),_S=z.object({RuleID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Economy:NS.nullish(),Entry:zp.nullish(),Creation:Ap.nullish(),Settings:kp.nullish()}).passthrough(),WS=z.object({Rules:z.record(z.string(),_S).nullish(),Defaults:kp.nullish(),EntryDefaults:zp.nullish(),CreationDefaults:Ap.nullish()}).passthrough(),Zo=z.object({InstantBattle:WS.nullish()}).passthrough(),wp=Zo;var KS={Listing:"Listing",Auction:"Auction",BuyOrder:"BuyOrder",DirectTrade:"DirectTrade"},Yo=z.enum(["Listing","Auction","BuyOrder","DirectTrade"]).catch("Listing"),QS={Active:"Active",Completed:"Completed",Cancelled:"Cancelled",Declined:"Declined",Expired:"Expired"},Xo=z.enum(["Active","Completed","Cancelled","Declined","Expired"]).catch("Active"),HS={Burn:"Burn",Ledger:"Ledger"},$S=z.enum(["Burn","Ledger"]).catch("Burn"),vn={Item:"Item",VirtualCurrency:"VirtualCurrency"},ea=z.enum(["Item","VirtualCurrency"]).catch("Item"),JS=z.object({Percent:z.number().nullish(),MinPerPosition:_.nullish()}).passthrough(),Tn=z.object({AllowVirtualCurrency:z.boolean().nullish(),AllowItems:z.boolean().nullish(),AllowEventTokens:z.boolean().nullish(),AllowCryptoCurrency:z.boolean().nullish(),Allowed:z.array(zi).nullish(),MaxPositions:z.number().nullish()}).passthrough(),ta=z.object({Percent:z.number().nullish(),MinPerPosition:_.nullish(),Sink:$S.nullish(),LedgerAccountID:z.string().nullish(),PerCatalogOverrides:z.record(z.string(),JS).nullish(),ApplyToDirectTrades:z.boolean().nullish()}).passthrough(),ZS=z.object({AllowedCatalogIDs:z.array(z.string()).nullish(),DeniedCatalogIDs:z.array(z.string()).nullish(),DeniedItemIDs:z.array(z.string()).nullish(),AllowUnstackableWithState:z.boolean().nullish(),AllowedCurrencyIDs:z.array(z.string()).nullish(),DeniedCurrencyIDs:z.array(z.string()).nullish()}).passthrough(),YS=z.object({Enabled:z.boolean().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),MaxActiveListings:z.number().nullish(),CreateLimits:ye.nullish(),BuyLimits:ye.nullish(),ListingFeeOptions:ae.nullish(),RefundListingFeeOnCancel:z.boolean().nullish()}).passthrough(),XS=z.object({Enabled:z.boolean().nullish(),MinDurationHours:z.number().nullish(),MaxDurationHours:z.number().nullish(),AntiSnipeWindowSeconds:z.number().nullish(),AntiSnipeExtensionSeconds:z.number().nullish(),MaxAntiSnipeExtensions:z.number().nullish(),MinBidStepPercent:z.number().nullish(),MinBidStepAbsolute:_.nullish(),BidLimits:ye.nullish()}).passthrough(),ex=z.object({Enabled:z.boolean().nullish(),MaxActiveOrders:z.number().nullish(),AllowedDurationsHours:z.array(z.number()).nullish(),CreateLimits:ye.nullish(),FillLimits:ye.nullish()}).passthrough(),tx=z.object({Enabled:z.boolean().nullish(),OfferExpirationHours:z.number().nullish(),MaxPendingOutgoing:z.number().nullish(),AllowGifts:z.boolean().nullish(),CreateLimits:ye.nullish()}).passthrough(),ix=z.object({Enabled:z.boolean().nullish()}).passthrough(),ia=z.object({Enabled:z.boolean().nullish(),Gate:J.nullish(),Schedule:me.nullish(),PricePolicy:Tn.nullish(),Commission:ta.nullish(),Tradability:ZS.nullish(),Listings:YS.nullish(),Auctions:XS.nullish(),BuyOrders:ex.nullish(),DirectTrades:tx.nullish(),Matching:ix.nullish()}).passthrough(),Mp=z.object({BidIndex:z.number().nullish(),UserID:z.string().nullish(),Amount:_.nullish(),Settled:z.boolean().nullish(),SettledAt:c.nullish()}).passthrough(),sx=z.object({BidAxisType:si.nullish(),BidCurrencyID:z.string().nullish(),BidCatalogID:z.string().nullish(),BidItemID:z.string().nullish(),StartingBid:_.nullish(),CurrentBid:_.nullish(),CurrentBidderID:z.string().nullish(),BidCount:z.number().nullish(),ExtensionCount:z.number().nullish(),PendingRefunds:z.array(Mp).nullish()}).passthrough(),In=z.object({LastAt:c.nullish(),DailyCount:z.number().nullish(),DailyResetUtc:c.nullish()}).passthrough(),nx=z.object({Create:In.nullish(),Buy:In.nullish(),Sell:In.nullish(),Bid:In.nullish()}).passthrough(),rx=z.object({CharacterID:z.string().nullish(),SlotID:z.string().nullish()}).passthrough(),ox=z.object({ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Quantity:z.number().nullish(),RemainingUses:z.number().nullish(),Level:z.number().nullish(),AcquiredAt:c,ExpiresAt:c.nullish(),EquippedSlot:rx.nullish(),CustomData:z.record(z.string(),z.string()).nullish()}).passthrough().transform(o=>o),Tt=z.object({OfferID:z.string().nullish(),OfferType:Yo.nullish(),Status:Xo.nullish(),CreatorUserID:z.string().nullish(),CreatorPublicData:Oe.nullish(),TargetUserID:z.string().nullish(),GoodsType:ea.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:_.nullish(),GoodsInstances:z.array(ox).nullish(),Price:le.nullish(),Auction:sx.nullish(),CreatedAt:c.nullish(),ExpiresAt:c.nullish()}).passthrough(),ax=z.object({GoodsType:ea.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),CountsByType:z.partialRecord(Yo,_).nullish()}).passthrough(),Op=z.object({Definitions:ia.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish()}).passthrough(),sa=z.object({Offers:z.array(Tt).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Up=z.object({Groups:z.array(ax).nullish()}).passthrough(),Ep=z.object({Offer:Tt.nullish()}).passthrough(),at=z.object({OfferID:z.string().nullish(),Status:Xo.nullish(),Settlement:bt.nullish(),Resources:M.nullish(),CommissionTaken:le.nullish()}).passthrough(),Ai=z.object({OfferID:z.string().nullish(),Offer:Tt.nullish(),Resources:M.nullish(),Matched:z.boolean().nullish(),Settlement:at.nullish()}).passthrough(),qp=z.object({OfferID:z.string().nullish(),CurrentBid:_.nullish(),BidCount:z.number().nullish(),ExpiresAt:c.nullish(),Resources:M.nullish()}).passthrough(),kn=z.object({MyOffers:z.array(Tt).nullish(),MyBids:z.array(Tt).nullish(),MyBuyOrders:z.array(Tt).nullish(),IncomingTrades:z.array(Tt).nullish(),OutgoingTrades:z.array(Tt).nullish(),Claimables:z.array(Tt).nullish(),DrainedRefunds:z.array(Mp).nullish(),Limits:nx.nullish()}).passthrough(),lx=z.object({OfferID:z.string().nullish(),OfferType:Yo.nullish(),FinalStatus:Xo.nullish(),SellerUserID:z.string().nullish(),BuyerUserID:z.string().nullish(),GoodsType:ea.nullish(),GoodsCatalogID:z.string().nullish(),GoodsItemID:z.string().nullish(),GoodsCurrencyID:z.string().nullish(),GoodsAmount:_.nullish(),PricePaid:le.nullish(),CommissionTaken:le.nullish(),CompletedAt:c.nullish(),MyRole:z.string().nullish()}).passthrough(),Bp=z.object({Entries:z.array(lx).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),Te={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 ux="Marketplace",Lp={key:"marketplace.myState",login:"MarketplaceMyState",ttlMs:6e4,dependsOn:["Marketplace"],invalidateOn:["marketplace:listingCreated","marketplace:listingCancelled","marketplace:bought","marketplace:marketBought","marketplace:marketSold","marketplace:auctionCreated","marketplace:bidPlaced","marketplace:auctionClaimed","marketplace:buyOrderCreated","marketplace:buyOrderCancelled","marketplace:buyOrderFilled","marketplace:directTradeCreated","marketplace:directTradeResponded","marketplace:directTradeCancelled","marketplace:claimedBack"]},zn=class{constructor(e){this.ctx=e;e.cache.bindLoginView(Lp,{schema:kn,apply:t=>this.applyMyState(t)});}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.marketplace.getDefinitions(e);return t.ok&&(this.ctx.data.config.patchSection(ux,t.data.Definitions),this.ctx.emitter.emit("marketplace:definitionsLoaded",t.data)),t}async getGroupedOffers(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.marketplace.getGroupedOffers(e);return t.ok&&this.ctx.emitter.emit("marketplace:groupedOffersLoaded",t.data),t}async getOffersByItem(e,t,i,s=20){if(!e)return b("client","ItemID is required.");let n=this.ctx.authedRequest();if(!n)return c$1;n.ItemID=e,n.OfferTypeFilter=t,n.ContinuationToken=i,n.PageSize=s;let r=await this.ctx.api.marketplace.getOffersByItem(n);return r.ok&&this.ctx.emitter.emit("marketplace:offersByItemLoaded",r.data),r}async getOffer(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.getOffer(t);return i.ok&&this.ctx.emitter.emit("marketplace:offerLoaded",i.data),i}async getBuyOrders(e,t,i=20){let s=this.ctx.authedRequest();if(!s)return c$1;s.ItemID=e,s.ContinuationToken=t,s.PageSize=i;let n=await this.ctx.api.marketplace.getBuyOrders(s);return n.ok&&this.ctx.emitter.emit("marketplace:buyOrdersLoaded",n.data),n}getMyState(e,t){return this.ctx.cache.read(Lp,()=>this.fetchMyState(e),{...t,args:e||void 0,loginParams:e?{MyBidsFilter:e}:{}})}async fetchMyState(e){let t=this.ctx.authedRequest();if(!t)return c$1;e&&(t.MyBidsFilter=e);let i=await this.ctx.api.marketplace.getMyState(t);return i.ok&&this.applyMyState(i.data),i}applyMyState(e){this.ctx.data.user.applyMarketplaceState(e.Limits??null),this.ctx.emitter.emit("marketplace:myStateLoaded",e);}async getHistory(e,t=20,i){let s=this.ctx.authedRequest();if(!s)return c$1;i&&(s.HistoryFilter=i),s.ContinuationToken=e,s.PageSize=t;let n=await this.ctx.api.marketplace.getHistory(s);return n.ok&&this.ctx.emitter.emit("marketplace:historyLoaded",n.data),n}async createListing(e,t,i,s,n,r,p){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.PriceBundle=s,d.DurationHours=n,d.ItemInstanceIDs=r,d.SelectedOptionID=p;let C=await this.ctx.api.marketplace.createListing(d);return this.applyCreateOfferResult(C,"marketplace:listingCreated"),C}async cancelListing(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelListing(t),"marketplace:listingCancelled")}async buy(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.buy(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:bought",i.data)),i}async marketBuy(e,t,i){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c$1;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let r=await this.ctx.api.marketplace.marketBuy(s);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketBought",r.data)),r}async marketSell(e,t,i){if(!e||e<=0)return b("client","GoodsAmount must be positive.");if(!t)return b("client","PriceBundle is required.");let s=this.ctx.authedRequest();if(!s)return c$1;let n=this.applyGoodsSelector(s,i);if(n)return n;s.GoodsAmount=e,s.PriceBundle=t;let r=await this.ctx.api.marketplace.marketSell(s);return r.ok&&(this.applyDualPartySettlement(r.data.Settlement),this.ctx.emitter.emit("marketplace:marketSold",r.data)),r}async createAuction(e,t,i,s,n,r,p={}){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");let d=this.ctx.authedRequest();if(!d)return c$1;d.ItemID=e,d.CatalogID=t,d.GoodsAmount=i,d.BidAxisType=s,d.BidCurrencyID=p.bidCurrencyID,d.BidCatalogID=p.bidCatalogID,d.BidItemID=p.bidItemID,d.StartingBid=n,d.DurationHours=r,d.ItemInstanceIDs=p.itemInstanceIDs,d.SelectedOptionID=p.selectedOptionID;let C=await this.ctx.api.marketplace.createAuction(d);return this.applyCreateOfferResult(C,"marketplace:auctionCreated"),C}async placeBid(e,t){if(!e)return b("client","OfferID is required.");if(!t||t<=0)return b("client","BidAmount must be positive.");let i=this.ctx.authedRequest();if(!i)return c$1;i.OfferID=e,i.BidAmount=t;let s=await this.ctx.api.marketplace.placeBid(i);return s.ok&&(this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:bidPlaced",s.data)),s}async claimAuction(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.claimAuction(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:auctionClaimed",i.data)),i}async createBuyOrder(e,t,i,s,n){if(!e)return b("client","ItemID is required.");if(!t)return b("client","CatalogID is required.");if(!s)return b("client","PriceBundle is required.");let r=this.ctx.authedRequest();if(!r)return c$1;r.ItemID=e,r.CatalogID=t,r.GoodsAmount=i,r.PriceBundle=s,r.DurationHours=n;let p=await this.ctx.api.marketplace.createBuyOrder(r);return this.applyCreateOfferResult(p,"marketplace:buyOrderCreated"),p}async cancelBuyOrder(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelBuyOrder(t),"marketplace:buyOrderCancelled")}async fillBuyOrder(e){if(!e)return b("client","OfferID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.fillBuyOrder(t);return i.ok&&(this.applyDualPartySettlement(i.data.Settlement),this.ctx.emitter.emit("marketplace:buyOrderFilled",i.data)),i}async createDirectTrade(e,t,i,s,n){if(!e)return b("client","TargetUserID is required.");if(!t)return b("client","CatalogID is required.");if(!i)return b("client","ItemID is required.");let r=this.ctx.authedRequest();if(!r)return c$1;r.TargetUserID=e,r.CatalogID=t,r.ItemID=i,r.ItemInstanceIDs=s,r.RequestedBundle=n;let p=await this.ctx.api.marketplace.createDirectTrade(r);return this.applyCreateOfferResult(p,"marketplace:directTradeCreated"),p}async respondDirectTrade(e,t){if(!e)return b("client","OfferID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.OfferID=e,i.Accept=t;let s=await this.ctx.api.marketplace.respondDirectTrade(i);return s.ok&&(t&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):s.data.Resources&&this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions)),this.ctx.emitter.emit("marketplace:directTradeResponded",s.data)),s}async cancelDirectTrade(e){return this.cancelOffer(e,t=>this.ctx.api.marketplace.cancelDirectTrade(t),"marketplace:directTradeCancelled")}async claimBack(e){let t=this.ctx.authedRequest();if(!t)return c$1;t.OfferID=e;let i=await this.ctx.api.marketplace.claimBack(t);return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("marketplace:claimedBack",i.data)),i}async cancelOffer(e,t,i){if(!e)return b("client","OfferID is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.OfferID=e;let n=await t(s);return n.ok&&(this.ctx.data.user.applyResourceOperation(n.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(i,n.data)),n}applyCreateOfferResult(e,t){e.ok&&(e.data.Matched&&e.data.Settlement?this.applyDualPartySettlement(e.data.Settlement.Settlement):this.ctx.data.user.applyResourceOperation(e.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit(t,e.data));}applyGoodsSelector(e,t){return "goodsCurrencyID"in t&&t.goodsCurrencyID?(e.GoodsType=vn.VirtualCurrency,e.GoodsCurrencyID=t.goodsCurrencyID,null):"itemID"in t&&t.itemID&&t.catalogID?(e.GoodsType=vn.Item,e.ItemID=t.itemID,e.CatalogID=t.catalogID,null):b("client","Either itemID+catalogID or goodsCurrencyID is required.")}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};var An=class{constructor(e){this.ctx=e;}ctx;async createRoom(e,t={}){if(!e)return b("client","RoomName is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomName=e,i.Topology=t.topology,i.ChatMode=t.chatMode,i.MaxPlayers=t.maxPlayers,i.Visibility=t.visibility,i.JoinCode=t.joinCode,i.Mode=t.mode;let s=await this.ctx.api.multiplayer.createRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomCreated",s.data),s}async joinRoom(e,t){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.JoinCode=t;let s=await this.ctx.api.multiplayer.joinRoom(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomJoined",s.data),s}async leaveRoom(e,t={}){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.SuccessorUserID=t.successorUserID;let s=await this.ctx.api.multiplayer.leaveRoom(i,t.keepalive??false);return s.ok&&this.ctx.emitter.emit("multiplayer:roomLeft",s.data),s}async claimHost(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.RoomID=e;let i=await this.ctx.api.multiplayer.claimHost(t);return i.ok&&this.ctx.emitter.emit("multiplayer:hostClaimed",i.data),i}async kickMember(e,t,i=false){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.RoomID=e,s.TargetUserID=t,s.Ban=i;let n=await this.ctx.api.multiplayer.kickMember(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberKicked",n.data),n}async unbanMember(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.TargetUserID=t;let s=await this.ctx.api.multiplayer.unbanMember(i);return s.ok&&this.ctx.emitter.emit("multiplayer:memberUnbanned",s.data),s}async listRooms(e=0,t=20){let i=this.ctx.authedRequest();if(!i)return c$1;i.Page=e,i.PageSize=t;let s=await this.ctx.api.multiplayer.listRooms(i);return s.ok&&this.ctx.emitter.emit("multiplayer:roomsListed",s.data),s}async getRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.RoomID=e;let i=await this.ctx.api.multiplayer.getRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomLoaded",i.data),i}async closeRoom(e){if(!e)return b("client","RoomID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;t.RoomID=e;let i=await this.ctx.api.multiplayer.closeRoom(t);return i.ok&&this.ctx.emitter.emit("multiplayer:roomClosed",i.data),i}async poll(e,t){if(!e)return b("client","RoomID is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.LastSeq=t;let s=await this.ctx.api.multiplayer.poll(i);return s.ok&&this.ctx.emitter.emit("multiplayer:polled",s.data),s}async sendSignal(e,t,i,s){if(!e)return b("client","RoomID is required.");if(!t)return b("client","TargetUserID is required.");if(!i)return b("client","SignalKind is required.");let n=this.ctx.authedRequest();if(!n)return c$1;n.RoomID=e,n.TargetUserID=t,n.SignalKind=i,n.Payload=s;let r=await this.ctx.api.multiplayer.sendSignal(n);return r.ok&&this.ctx.emitter.emit("multiplayer:signalSent",r.data),r}async sendChat(e,t){if(!e)return b("client","RoomID is required.");if(!t)return b("client","ChatText is required.");let i=this.ctx.authedRequest();if(!i)return c$1;i.RoomID=e,i.ChatText=t;let s=await this.ctx.api.multiplayer.sendChat(i);return s.ok&&this.ctx.emitter.emit("multiplayer:chatSent",s.data),s}async setMemberState(e,t,i){if(!e)return b("client","RoomID is required.");let s=this.ctx.authedRequest();if(!s)return c$1;s.RoomID=e,s.Ready=t,s.MemberState=i;let n=await this.ctx.api.multiplayer.setMemberState(s);return n.ok&&this.ctx.emitter.emit("multiplayer:memberStateSet",n.data),n}};var Gp=" (if the network is fine, the storage bucket has no CORS rule for this origin)",wn=class{constructor(e){this.ctx=e;}ctx;async getDefinitions(){let e=this.ctx.authedRequest();if(!e)return c$1;let t=await this.ctx.api.workshop.getDefinitions(e);return t.ok&&this.ctx.emitter.emit("workshop:definitionsLoaded",t.data),t}async browse(e={}){let t=this.ctx.authedRequest();return t?(t.ContentType=e.contentType,t.Tag=e.tag,t.MetadataKey=e.metadataKey,t.MetadataValue=e.metadataValue,t.CreatorUserID=e.creatorUserID,t.FromFollowing=e.fromFollowing,t.Sort=e.sort,t.PageSize=e.pageSize,t.ContinuationToken=e.continuationToken,this.ctx.api.workshop.browse(t)):c$1}async getContent(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getContent(t)}async getCollection(e){if(!e)return b("client","CollectionID is required.");let t=this.ctx.authedRequest();return t?(t.CollectionID=e,this.ctx.api.workshop.getCollection(t)):c$1}async getCreatorProfile(e,t,i){if(!e)return b("client","CreatorUserID is required.");let s=this.ctx.authedRequest();return s?(s.CreatorUserID=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getCreatorProfile(s)):c$1}async publish(e){if(!e.files||e.files.length===0)return b("client","At least one file is required.");let t=new Map,i=e.files.map((d,C)=>{if("sourceAssetUrl"in d)return {Role:d.role,ContentType:d.contentType,SourceAssetUrl:d.sourceAssetUrl};let j=Fp(d.data,d.contentType);return t.set(C,j),{Role:d.role,ContentType:d.contentType,Size:j.size}}),s=e.thumbnail?Fp(e.thumbnail.data,e.thumbnail.contentType):null,n=await this.beginUpload({ContentType:e.contentType,ContentID:e.contentID,Files:i,Thumbnail:e.thumbnail&&s?{Role:"thumbnail",ContentType:e.thumbnail.contentType,Size:s.size}:void 0});if(!n.ok)return n;let r=n.data.Uploads??[];for(let d=0;d<r.length;d++){let C=r[d];if(!C||C.ServerCopy||!C.Url)continue;let j=t.get(d);if(!j)return b("client",`No bytes for file #${d+1}.`);let ue=await this.putBytes(C.Url,j,C.ContentType??j.type);if(!ue.ok)return ue}let p=n.data.ThumbnailUpload;if(p?.Url&&s){let d=await this.putBytes(p.Url,s,p.ContentType??s.type);if(!d.ok)return d}return this.publishUploaded({ContentID:n.data.ContentID??void 0,Title:e.title,Description:e.description,Tags:e.tags,Metadata:e.metadata,Visibility:e.visibility,Access:e.access,SelectedOptionID:e.selectedFeeOptionID})}async beginUpload(e){let t=this.ctx.authedRequest();return t?this.ctx.api.workshop.beginUpload({...t,...e}):c$1}async publishUploaded(e){if(!e.ContentID)return b("client","ContentID is required.");let t=this.ctx.authedRequest();if(!t)return c$1;let i=await this.ctx.api.workshop.publish({...t,...e});return i.ok&&(this.ctx.data.user.applyResourceOperation(i.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:published",i.data)),i}async updateContent(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.Title=t.title,i.Description=t.description,i.Tags=t.tags,i.Metadata=t.metadata,i.Visibility=t.visibility,i.Access=t.access;let s=await this.ctx.api.workshop.updateContent(i);return s.ok&&this.ctx.emitter.emit("workshop:updated",s.data),s}async unpublish(e){let t=this.contentRequest(e);if("ok"in t)return t;let i=await this.ctx.api.workshop.unpublish(t);return i.ok&&this.ctx.emitter.emit("workshop:updated",i.data),i}async getMyContent(e,t,i){let s=this.ctx.authedRequest();return s?(s.ContentType=e,s.ContinuationToken=t,s.PageSize=i,this.ctx.api.workshop.getMyContent(s)):c$1}async acquire(e,t){let i=this.contentRequest(e);if("ok"in i)return i;i.OptionID=t?.OptionID??void 0,i.ExpectedPrice=t?.Price??void 0;let s=await this.ctx.api.workshop.acquire(i);return s.ok&&(s.data.Settlement?this.applyDualPartySettlement(s.data.Settlement):this.ctx.data.user.applyResourceOperation(s.data.Resources,this.ctx.data.config.itemDefinitions),this.ctx.emitter.emit("workshop:acquired",s.data)),s}async getDownload(e){let t=this.contentRequest(e);return "ok"in t?t:this.ctx.api.workshop.getDownload(t)}async downloadFiles(e){let t=await this.getDownload(e);if(!t.ok)return t;let i=[];for(let s of t.data.Files??[])if(s.Url)try{let n=await this.ctx.fetchImpl(s.Url);if(!n.ok)return b("connection",`Download failed (HTTP ${n.status}).`);i.push({role:s.Role??"main",contentType:s.ContentType??"application/octet-stream",data:await n.arrayBuffer()});}catch(n){return b("connection",`Download failed: ${n instanceof Error?n.message:String(n)}${Gp}`)}return a({download:t.data,files:i})}async getMyLicenses(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyLicenses(i)):c$1}async getMyFavorites(e,t){let i=this.ctx.authedRequest();return i?(i.ContinuationToken=e,i.PageSize=t,this.ctx.api.workshop.getMyFavorites(i)):c$1}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}${Gp}`)}}contentRequest(e){if(!e)return b("client","ContentID is required.");let t=this.ctx.authedRequest();return t?(t.ContentID=e,t):c$1}applyDualPartySettlement(e){let t=this.ctx.auth.context?.userID;if(!e||!t)return;let i=this.ctx.data.config.itemDefinitions;e.FromUserID===t&&e.FromResult?this.ctx.data.user.applyResourceOperation(e.FromResult,i):e.ToUserID===t&&e.ToResult&&this.ctx.data.user.applyResourceOperation(e.ToResult,i);}};function Fp(o,e){return o instanceof Blob?o:typeof o=="string"?new Blob([new TextEncoder().encode(o)],{type:e}):o instanceof Uint8Array?new Blob([o.slice().buffer],{type:e}):new Blob([o],{type:e})}var cx={UserOwned:"UserOwned",Shared:"Shared",Temporary:"Temporary",Log:"Log"},px=z.enum(["UserOwned","Shared","Temporary","Log"]).catch("Shared"),hx={String:"String",Text:"Text",Int:"Int",Number:"Number",Bool:"Bool",Date:"Date",Json:"Json",Array:"Array",Ref:"Ref",File:"File"},Vp=z.enum(["String","Text","Int","Number","Bool","Date","Json","Array","Ref","File"]).catch("Json"),dx={Everyone:"Everyone",Owner:"Owner",Server:"Server"},jp=z.enum(["Everyone","Owner","Server"]).catch("Everyone"),mx={Anyone:"Anyone",Authenticated:"Authenticated",Owner:"Owner",Members:"Members",Role:"Role",Server:"Server"},fx=z.enum(["Anyone","Authenticated","Owner","Members","Role","Server"]).catch("Server"),gx={DataItem:"DataItem",User:"User",Item:"Item",Currency:"Currency",ItemInstance:"ItemInstance",StoreOffer:"StoreOffer",Leaderboard:"Leaderboard",Quest:"Quest",WorkshopContent:"WorkshopContent"},yx=z.enum(["DataItem","User","Item","Currency","ItemInstance","StoreOffer","Leaderboard","Quest","WorkshopContent"]).catch("DataItem"),Rx={Count:"Count",Sum:"Sum"},Cx=z.enum(["Count","Sum"]).catch("Count"),Sx={Delete:"Delete",Anonymize:"Anonymize",Keep:"Keep"},xx=z.enum(["Delete","Anonymize","Keep"]).catch("Delete"),bx={Strict:"Strict",Loose:"Loose"},Dx=z.enum(["Strict","Loose"]).catch("Strict"),Px=z.object({Kind:yx,Collection:z.string().nullish(),Validate:z.boolean().nullish()}),Ix=z.object({Type:Vp,ItemType:Vp.nullish(),Ref:Px.nullish(),Required:z.boolean().optional(),Default:z.string().nullish(),Min:z.number().nullish(),Max:z.number().nullish(),MaxLength:z.number().nullish(),MaxItems:z.number().nullish(),Enum:z.array(z.string()).nullish(),Unique:z.boolean().optional(),UniqueIgnoreCase:z.boolean().optional(),Indexed:z.boolean().optional(),Visibility:jp.optional(),ClientWritable:z.boolean().nullish(),Immutable:z.boolean().optional(),Description:z.string().nullish(),AllowedMimeTypes:z.array(z.string()).nullish(),MaxFileBytes:z.number().nullish()}),vx=z.object({ID:z.string(),Components:z.array(z.object({Field:z.string(),Descending:z.boolean().optional()})).default([])}),Mn=z.object({Mode:fx,Role:z.string().nullish(),MembersField:z.string().nullish()}),Tx=z.object({Read:z.array(Mn).nullish(),Create:z.array(Mn).nullish(),Update:z.array(Mn).nullish(),Delete:z.array(Mn).nullish()}),na=z.object({Cost:le.nullish(),Grant:le.nullish()}),kx=z.object({ID:z.string(),SortKey:z.string(),PartitionField:z.string().nullish(),PageSize:z.number().optional(),MaxItems:z.number().optional(),PublishItems:z.boolean().optional()}),zx=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Namespace:z.string().nullish(),Tags:z.array(z.string()).nullish(),Enabled:z.boolean().nullish(),Kind:px,Mode:Dx.optional(),SchemaVersion:z.number().optional(),Fields:z.record(z.string(),Ix).nullish(),SortKeys:z.array(vx).nullish(),Access:Tx.nullish(),Limits:z.object({MaxItemBytes:z.number().nullish(),MaxItemsPerOwner:z.number().nullish(),TtlSeconds:z.number().nullish()}).nullish(),OnOwnerDeleted:xx.optional(),Counters:z.array(z.object({ID:z.string(),Kind:Cx,SumField:z.string().nullish(),GroupBy:z.string().nullish(),Visibility:jp.optional()})).nullish(),Economy:z.object({OnCreate:na.nullish(),OnUpdate:na.nullish(),OnDelete:na.nullish()}).nullish(),WriteGate:J.nullish(),PublicViews:z.array(kx).nullish(),AnonymousSearch:z.boolean().nullish(),Integrations:z.object({QuestMetricOnCreate:z.string().nullish(),QuestMetricOnUpdate:z.string().nullish(),QuestMetricOnDelete:z.string().nullish(),AnalyticsEventOnCreate:z.string().nullish(),AnalyticsEventOnUpdate:z.string().nullish(),AnalyticsEventOnDelete:z.string().nullish(),TriggerOnCreate:z.string().nullish(),TriggerOnUpdate:z.string().nullish(),TriggerOnDelete:z.string().nullish()}).nullish(),Moderation:z.object({BlockedTerms:z.array(z.string()).nullish()}).nullish()}),Np=z.object({Enabled:z.boolean().optional(),Collections:z.record(z.string(),zx).default({})}),Ax=z.object({FileID:z.string(),Url:z.string(),ContentType:z.string().nullish(),Size:z.number()}),_p=z.object({FileID:z.string(),UploadUrl:z.string(),ContentType:z.string(),MaxBytes:z.number(),ExpiresAt:z.string()}),di=z.object({Collection:z.string(),ItemID:z.string(),OwnerUserID:z.string().nullish(),Data:z.record(z.string(),z.unknown()).default({}),Version:z.number(),CreatedAt:z.string(),UpdatedAt:z.string(),ExpireAt:z.string().nullish(),Expanded:z.record(z.string(),z.unknown()).nullish(),Files:z.record(z.string(),Ax).nullish()}),ra=z.object({Item:di}),Wp=z.object({Items:z.array(di).default([]),Missing:z.array(z.string()).default([])}),oa=z.object({Items:z.array(di).default([]),NextCursor:z.string().nullish()}),Kp=z.object({Count:z.number(),Capped:z.boolean().optional()}),aa=z.object({Item:di,AlreadyExists:z.boolean().optional(),Economy:M.nullish()}),Qp=z.object({ItemID:z.string(),Deleted:z.boolean(),Economy:M.nullish()}),Hp=z.object({CounterID:z.string(),Group:z.unknown().optional(),Value:z.number()}),$p=z.object({Results:z.array(z.object({Op:z.string(),Collection:z.string(),ItemID:z.string(),Item:di.nullish(),Deleted:z.boolean().optional()})).default([])}),Jp=z.object({Roles:z.array(z.string()).default([])}),Zp=z.object({Views:z.record(z.string(),z.string()).default({}),ItemUrlTemplate:z.string().nullish()}),Yp=z.object({Version:z.string(),Collection:z.string(),View:z.string(),SortKey:z.string().nullish(),PageSize:z.number(),UpdatedAt:z.string(),BaseUrl:z.string(),Partitions:z.record(z.string(),z.object({Segment:z.string(),Pages:z.number(),Total:z.number()})).default({})}),Xp=z.object({Page:z.number(),HasMore:z.boolean(),Items:z.array(di).default([])}),wx={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 Mx=/^[A-Za-z0-9_][A-Za-z0-9_:-]{0,63}$/,ih=/^[A-Za-z0-9_-][A-Za-z0-9_:-]{0,127}$/,ua=100,eh=25,th=100;function Ox(o,e,t){return {Field:o,Op:e,Value:t}}var On=class{constructor(e){this.ctx=e;}ctx;publicViews=new Map;getDefinitions(){let e=this.base();return e?this.ctx.api.dataCollections.getDefinitions(e):Promise.resolve(c$1)}get(e,t,i={}){let s=tt(e)??wi(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.get({...n,Collection:e,ItemID:t,Expand:i.expand}))}getMany(e,t,i={}){let s=tt(e);if(s)return Promise.resolve(s);let n=[...new Set(t.filter(r=>ih.test(r)))];return n.length?n.length>th?Promise.resolve(b("client",`At most ${th} ids per call.`)):this.call(r=>this.ctx.api.dataCollections.getMany({...r,Collection:e,ItemIDs:n,Expand:i.expand})):Promise.resolve(b("client","At least one valid item id is required."))}query(e,t={},i={}){let s=tt(e)??la(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.query({...n,Collection:e,Query:t,Expand:i.expand}))}async queryAll(e,t={},i={}){let s=Math.max(1,i.maxItems??500),n=[],r=t.Cursor;for(;;){let p=await this.query(e,{...t,Cursor:r,Limit:t.Limit??ua},i);if(!p.ok)return p;if(n.push(...p.data.Items),r=p.data.NextCursor??void 0,!r||n.length>=s)return a(n.slice(0,s))}}count(e,t={}){let i=tt(e)??la(t);return i?Promise.resolve(i):this.call(s=>this.ctx.api.dataCollections.count({...s,Collection:e,Query:t}))}create(e,t,i={}){let s=tt(e)??(i.itemID?wi(i.itemID):null);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.create({...n,Collection:e,ItemID:i.itemID,Data:t}))}update(e,t,i,s={}){let n=tt(e)??wi(t);return n?Promise.resolve(n):this.call(r=>this.ctx.api.dataCollections.update({...r,Collection:e,ItemID:t,Update:i,ExpectedVersion:s.expectedVersion}))}set(e,t,i,s={}){return this.update(e,t,{Set:i},s)}increment(e,t,i,s=1){return this.update(e,t,{Inc:{[i]:s}})}delete(e,t,i={}){let s=tt(e)??wi(t);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.delete({...n,Collection:e,ItemID:t,ExpectedVersion:i.expectedVersion}))}batch(e){if(!e.length)return Promise.resolve(b("client","Operations are empty."));if(e.length>eh)return Promise.resolve(b("client",`At most ${eh} operations per batch.`));let t=e.map(i=>tt(i.Collection)).find(i=>i!=null);return t?Promise.resolve(t):this.call(i=>this.ctx.api.dataCollections.batch({...i,Operations:e}))}getCounter(e,t,i){let s=tt(e);return s?Promise.resolve(s):this.call(n=>this.ctx.api.dataCollections.getCounter({...n,Collection:e,CounterID:t,Group:i}))}getMyRoles(){return this.call(e=>this.ctx.api.dataCollections.getMyRoles(e))}beginFileUpload(e,t,i,s){let n=tt(e);return n?Promise.resolve(n):t?s>0?this.call(r=>this.ctx.api.dataCollections.beginFileUpload({...r,Collection:e,Field:t,ContentType:i,FileSize:s})):Promise.resolve(b("client","File size must be positive.")):Promise.resolve(b("client","Field is required."))}async uploadFile(e,t,i,s={}){let n=s.contentType||i.type||"application/octet-stream",r=await this.beginFileUpload(e,t,n,i.size);if(!r.ok)return r;let p=await this.putBytes(r.data.UploadUrl,i,r.data.ContentType||n);return p.ok?r:p}async getPublicViews(e){let t=tt(e);if(t)return t;let i=this.publicViews.get(e);if(i)return a(i);let s=await this.ctx.api.dataCollections.publicGetViews({Collection:e});return s.ok&&this.publicViews.set(e,s.data),s}async readPublicView(e,t,i={}){let s=await this.getPublicViews(e);if(!s.ok)return s;let n=s.data.Views[t];if(!n)return b("client",`Collection '${e}' has no public view '${t}'.`);let r=await this.fetchJson(n,Yp);if(!r.ok)return r;let p=r.data.Partitions[i.partition??""],d=Math.max(1,i.page??1);if(!p||d>p.Pages)return a({pointer:r.data,page:{Page:d,HasMore:false,Items:[]}});let C=await this.fetchJson(`${r.data.BaseUrl}${p.Segment}/page-${d}.json`,Xp);return C.ok?a({pointer:r.data,page:C.data}):C}getPublic(e,t){let i=tt(e)??wi(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicGet({Collection:e,ItemID:t})}searchPublic(e,t){let i=tt(e)??la(t);return i?Promise.resolve(i):this.ctx.api.dataCollections.publicQuery({Collection:e,Query:t})}base(){return this.ctx.auth.context?this.ctx.buildAuthedBaseRequest():null}call(e){let t=this.base();return t?e(t):Promise.resolve(c$1)}async putBytes(e,t,i){try{let s=await this.ctx.fetchImpl(e,{method:"PUT",headers:{"Content-Type":i},body:t});return s.ok?a(!0):b("connection",`Upload failed (HTTP ${s.status}).`)}catch(s){return b("connection",`Upload failed: ${s instanceof Error?s.message:String(s)}`)}}async fetchJson(e,t){let i;try{i=await this.ctx.fetchImpl(e);}catch{return b("connection","Internet Connection Error")}if(!i.ok)return b("server",`CDN answered ${i.status}.`);let s;try{s=await i.json();}catch{return b("server","CDN answer is not JSON.")}let n=t.safeParse(s);return n.success?a(n.data):b("server","CDN answer has an unexpected shape.")}};function tt(o){return Mx.test(o??"")?null:b("client",`Collection id '${o}' is invalid (letters, digits, '_', '-', ':').`)}function wi(o){return ih.test(o??"")?null:b("client",`Item id '${o}' is invalid.`)}function la(o){return o.Limit!=null&&(o.Limit<1||o.Limit>ua)?b("client",`Limit must be 1..${ua}.`):(o.Where?.length??0)>8?b("client","At most 8 filters per query."):null}var ca={Open:"Open",Declared:"Declared"},Ux=z.object({DisplayName:z.string().nullish(),Description:z.string().nullish(),Blocked:z.boolean().nullish()}).passthrough(),Ex=z.object({ParamName:z.string().nullish(),DisplayName:z.string().nullish()}).passthrough(),sh=z.object({Enabled:z.boolean().nullish(),EventNaming:z.string().nullish(),Events:z.record(z.string(),Ux).nullish(),Dimensions:z.array(Ex).nullish(),RetentionDays:z.number().nullish(),AutomaticEvents:z.boolean().nullish()}).passthrough(),Lt={FirstOpen:"idos_first_open",SessionStart:"idos_session_start",AppUpdate:"idos_app_update",OsUpdate:"idos_os_update",ScreenView:"idos_screen_view"},Ct={maxEventsPerBatch:50,maxParams:25,maxStringValueLength:100,maxEventAgeMs:4320*60*1e3,reservedPrefixes:["idos_","firebase_","google_","ga_"]},Un=/^[A-Za-z][A-Za-z0-9_]{0,39}$/,qx={InvalidName:"InvalidName",Reserved:"Reserved",NotDeclared:"NotDeclared",Blocked:"Blocked",CatalogFull:"CatalogFull",TooOld:"TooOld",AutomaticDisabled:"AutomaticDisabled",DailyLimit:"DailyLimit"},Bx=z.object({Index:z.number().nullish(),Name:z.string().nullish(),Reason:z.string().nullish()}).passthrough(),nh=z.object({Accepted:z.number().nullish(),Dropped:z.array(Bx).nullish(),Duplicate:z.boolean().nullish(),Disabled:z.boolean().nullish()}).passthrough(),pa={LogEvents:"LogEvents"};function rh(o,e=0){let t=o??"",i=/\b(iPhone|iPad|iPod)\b.*?\bOS (\d+(?:_\d+)*)/.exec(t);if(i){let p=i[1]??"iPhone";return {osName:"iOS",osVersion:(i[2]??"").replace(/_/g,"."),deviceCategory:p==="iPad"?"tablet":"phone",deviceModel:p}}let s=/\bAndroid (\d+(?:\.\d+)*)(?:;\s*([^;)]+))?/.exec(t);if(s){let p=(s[2]??"").replace(/\s+Build\/.*$/,"").trim();return {osName:"Android",osVersion:s[1],deviceCategory:/\bMobile\b/.test(t)?"phone":"tablet",deviceModel:p&&p!=="K"&&p!=="wv"?p:void 0}}let n=/\bMac OS X (\d+(?:[_.]\d+)*)/.exec(t);if(n)return e>1?{osName:"iOS",deviceCategory:"tablet",deviceModel:"iPad"}:{osName:"macOS",osVersion:(n[1]??"").replace(/_/g,"."),deviceCategory:"desktop",deviceModel:"Mac"};let r=/\bWindows NT (\d+\.\d+)/.exec(t);return r?{osName:"Windows",osVersion:r[1],deviceCategory:"desktop"}:/\bCrOS\b/.test(t)?{osName:"ChromeOS",deviceCategory:"desktop"}:/\bLinux\b/.test(t)?{osName:"Linux",deviceCategory:"desktop"}:{}}function oh(o){let e=typeof navigator>"u"?void 0:navigator,t=rh(e?.userAgent??"",e?.maxTouchPoints??0),i={};o.appVersion&&(i.AppVersion=o.appVersion),t.osName&&(i.OsName=t.osName),t.osVersion&&(i.OsVersion=t.osVersion),t.deviceCategory&&(i.DeviceCategory=t.deviceCategory),t.deviceModel&&(i.DeviceModel=t.deviceModel);let s=o.locale||e?.language;return s&&(i.Language=s),i}var Lx=25,Gx=3e4,ah=1800*1e3,lh=500,Fx=5,Vx=1e3,jx=3600*1e3,uh="idos_analytics_queue",ha="idos_analytics_pending",da="idos_analytics_opt_out",ch="idos_analytics_first_open",ph="idos_analytics_last_activity",hh="idos_analytics_last_context",dh="idos_analytics_owner",En=class{constructor(e){this.ctx=e;}ctx;queue=[];pending=null;restored=false;started=false;flushing=false;disabledByServer=false;automaticDone=false;hiddenAt=null;timer=null;drainTimer=null;stopWaitingForConfig=null;context=null;logEvent(e,t,i){return typeof e!="string"||!Un.test(e)?b("client",`Invalid event name "${String(e)}": a letter, then letters, digits or "_", up to 40 characters.`):Nx(e)?b("client",`Event name "${e}" uses a reserved prefix (${Ct.reservedPrefixes.join(", ")}).`):this.enqueue(e,t,i,false)}logScreenView(e,t){if(!e)return b("client","screenName is required.");let i={screen_name:e};return t&&(i.screen_class=t),this.enqueue(Lt.ScreenView,i,void 0,true)}async flush(){if(this.restore(),this.flushing||!this.isEnabled||this.disabledByServer)return a(null);if(this.config()?.Enabled===false)return this.clear(),a(null);if(!this.pending){if(this.dropStale(),this.queue.length===0)return a(null);this.pending={BatchID:d(),Events:this.queue.splice(0,Ct.maxEventsPerBatch),Attempts:0},this.persist();}let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return c$1;let t=this.pending;this.flushing=true;try{let i=await this.ctx.api.analytics.logEvents({...e,BatchID:t.BatchID,Events:t.Events,Context:this.clientContext()});return i.ok?(this.pending=null,i.data.Disabled&&(this.disabledByServer=!0,this.queue=[]),this.persist(),i.data.Dropped&&i.data.Dropped.length>0&&this.ctx.emitter.emit("analytics:eventsDropped",i.data.Dropped),this.ctx.emitter.emit("analytics:flushed",i.data),this.queue.length>0&&!this.disabledByServer&&this.scheduleDrain(),i):(i.reason!=="throttled"&&t.Attempts++,(i.reason==="validation"||t.Attempts>=Fx)&&(this.pending=null),this.persist(),i)}finally{this.flushing=false;}}setEnabled(e){if(e){this.remove(da);return}this.write(da,"1"),this.clear();}get isEnabled(){return this.read(da)!=="1"}start(){if(this.started)return;this.started=true,this.restore();let e=this.ctx.auth.context?.userID??null,t=this.read(dh);e&&t&&t!==e&&this.clear(),e&&this.write(dh,e),this.timer=setInterval(()=>{this.beginAutomatic(),this.flush();},Gx),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(ph)??"0");this.read(ch)||(this.write(ch,new Date().toISOString()),this.enqueue(Lt.FirstOpen,void 0,void 0,true));let t=this.clientContext(),i=this.readJson(hh);i?.AppVersion&&t.AppVersion&&i.AppVersion!==t.AppVersion&&this.enqueue(Lt.AppUpdate,{previous_app_version:i.AppVersion},void 0,true),i?.OsVersion&&t.OsVersion&&i.OsVersion!==t.OsVersion&&this.enqueue(Lt.OsUpdate,{previous_os_version:i.OsVersion},void 0,true),this.writeJson(hh,{AppVersion:t.AppVersion,OsVersion:t.OsVersion}),(!(e>0)||Date.now()-e>=ah)&&this.enqueue(Lt.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>=ah&&this.enqueue(Lt.SessionStart,void 0,void 0,true),this.hiddenAt=null;}};onPageHide=()=>{this.touch(),this.persist(),this.flush();};enqueue(e,t,i,s){if(!this.isEnabled||this.disabledByServer)return a(null);let n=this.config();if(n?.Enabled===false)return a(null);if(s&&n?.AutomaticEvents===false)return a(null);if(n?.Events?.[e]?.Blocked)return b("client",`Event "${e}" is blocked by the title.`);if(!s&&n?.EventNaming?.toLowerCase()===ca.Declared.toLowerCase()&&!n.Events?.[e])return b("client",`Event "${e}" is not declared: the title accepts declared events only.`);if(i!==void 0&&!Number.isFinite(i))return b("client","value must be a finite number.");let r=_x(t);if(r.error)return b("client",r.error);this.restore();let p={Name:e,ClientTimeUtc:new Date().toISOString()};return r.params&&(p.Params=r.params),i!==void 0&&(p.Value=i),this.queue.push(p),this.queue.length>lh&&this.queue.splice(0,this.queue.length-lh),this.touch(),this.persist(),this.started&&this.queue.length>=Lx&&this.flush(),a(null)}scheduleDrain(){this.drainTimer||!this.started||(this.drainTimer=setTimeout(()=>{this.drainTimer=null,this.flush();},Vx));}dropStale(){let e=Date.now()-(Ct.maxEventAgeMs-jx);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??=oh({appVersion:this.ctx.settings.appVersion,locale:this.ctx.settings.locale}),this.context}restore(){if(this.restored)return;this.restored=true;let e=this.readJson(uh);Array.isArray(e)&&(this.queue=e.filter(i=>typeof i?.Name=="string").concat(this.queue));let t=this.readJson(ha);t&&typeof t.BatchID=="string"&&Array.isArray(t.Events)&&(this.pending={...t,Attempts:Number(t.Attempts)||0});}persist(){this.writeJson(uh,this.queue),this.pending?this.writeJson(ha,this.pending):this.remove(ha);}touch(){this.write(ph,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 Nx(o){let e=o.toLowerCase();return Ct.reservedPrefixes.some(t=>e.startsWith(t))}function _x(o){if(!o)return {};let e=Object.keys(o);if(e.length===0)return {};if(e.length>Ct.maxParams)return {error:`Too many parameters: ${e.length}, max ${Ct.maxParams}.`};let t={};for(let i of e){if(!Un.test(i))return {error:`Invalid parameter name "${i}".`};let s=o[i];typeof s=="string"?t[i]=s.length>Ct.maxStringValueLength?s.slice(0,Ct.maxStringValueLength):s:typeof s=="number"?Number.isFinite(s)&&(t[i]=s):typeof s=="boolean"&&(t[i]=s);}return {params:t}}var Wx="idos_experiments",qn=class{constructor(e){this.ctx=e;}ctx;views=new Map;abTestingAvailable=true;restoredFor=null;async load(){let e=this.ctx.buildAuthedBaseRequest();if(!e.UserID||!e.ClientSessionTicket)return c$1;let t=await this.ctx.api.experiment.getExperiments(e);if(t.ok){this.restore();let i=this.apply(t.data);this.save(e.UserID,t.data),this.ctx.emitter.emit("experiments:loaded",t.data),i.length>0&&this.ctx.emitter.emit("experiments:changed",i);}return t}getVariant(e){return this.restore(),this.views.get(e)?.VariantID??null}getStatus(e){return this.restore(),this.views.get(e)?.Status??null}getParams(e){return this.restore(),{...this.views.get(e)?.Params??{}}}getParam(e,t,i){let s=this.getParams(e)[t];if(s===void 0)return i;if(typeof i=="number"){let n=Number(s);return s.trim()!==""&&Number.isFinite(n)?n:i}if(typeof i=="boolean"){let n=s.trim().toLowerCase();return n==="true"||n==="1"?true:n==="false"||n==="0"?false:i}return s}isInVariant(e,t){return this.getVariant(e)===t}get isAbTestingAvailable(){return this.restore(),this.abTestingAvailable}get all(){return this.restore(),[...this.views.values()]}apply(e){let t=new Map;for(let s of e.Experiments??[])s?.ExperimentID&&t.set(s.ExperimentID,s);let i=[];for(let[s,n]of t){let r=this.views.get(s);(!r||r.VariantID!==n.VariantID||r.Status!==n.Status)&&i.push(n);}return this.views=t,this.abTestingAvailable=e.IsAbTestingAvailable!==false,i}restore(){let e=this.ctx.auth.context?.userID??null;if(e!==this.restoredFor&&(this.restoredFor=e,this.views=new Map,this.abTestingAvailable=true,!!e))try{let t=this.ctx.platform.storage.getString(this.key());if(!t)return;let i=JSON.parse(t);i?.UserID===e&&i.Data&&this.apply(i.Data);}catch{}}save(e,t){try{let i={UserID:e,Data:t};this.ctx.platform.storage.setString(this.key(),JSON.stringify(i));}catch{}}key(){return `${Wx}:${this.ctx.settings.titleID}`}};function Gt(o,e,t,i){let n=`api/v2/${o&&o.length>0?o:"0"}/Client/${e}/${t}`;return i==null?n:`${n}/${i}`}var q=class{constructor(e,t){this.ctx=e;this.feature=t;}ctx;feature;endpoint(e,t){return Gt(this.ctx.settings.titleID,this.feature,e,t.UserID??"")}send(e,t,i,s){return this.ctx.transport.post(this.endpoint(e,t),t,i,{...s,ticket:t.ClientSessionTicket})}};var Bn=class extends q{constructor(e){super(e,"Analytics");}logEvents(e){return this.send(pa.LogEvents,e,nh,{silent:true})}};var Kx=z.object({VariantID:z.string().nullish(),DisplayName:z.string().nullish(),Weight:z.number().nullish(),IsControl:z.boolean().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),Qx={EventConversion:"EventConversion",EventCountPerUser:"EventCountPerUser",EventValuePerUser:"EventValuePerUser",RetentionD1:"RetentionD1",RetentionD7:"RetentionD7",PayerConversion:"PayerConversion",Arpu:"Arpu"},Hx=z.object({MetricID:z.string().nullish(),Kind:z.string().nullish(),EventName:z.string().nullish(),IsPrimary:z.boolean().nullish()}).passthrough(),$x=z.object({ExperimentID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),IsEnabled:z.boolean().nullish(),Schedule:me.nullish(),Gate:J.nullish(),Variants:z.array(Kx).nullish(),Salt:z.string().nullish(),LayerID:z.string().nullish(),StickyAssignment:z.boolean().nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Goals:z.array(Hx).nullish(),ActivationEvent:z.string().nullish(),RolloutVariantID:z.string().nullish()}).passthrough(),mh=z.object({Experiments:z.record(z.string(),$x).nullish()}).passthrough(),Jx={Running:"Running",Stopped:"Stopped",RolledOut:"RolledOut"},Zx=z.object({ExperimentID:z.string().nullish(),VariantID:z.string().nullish(),Status:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),fh=z.object({Experiments:z.array(Zx).nullish(),IsAbTestingAvailable:z.boolean().nullish()}).passthrough(),ma={GetExperiments:"GetExperiments"};var Ln=class extends q{constructor(e){super(e,"Experiment");}getExperiments(e){return this.send(ma.GetExperiments,e,fh)}};var gh=z.object({PlatformUserID:z.string().nullish(),PlatformAuthToken:z.string().nullish(),PlatformAuthTokenExpiration:c.nullish(),TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:c,PlayAccess:Bt.nullish(),RefreshToken:z.string().nullish(),RefreshTokenExpiration:c.nullish()}),yh=z.object({TitleUserID:z.string(),TitleClientSessionTicket:z.string(),TitleClientSessionTicketExpiration:c,RefreshToken:z.string(),RefreshTokenExpiration:c.nullish(),PlayAccess:Bt.nullish()}),Yx=z.object({ReturnMode:z.string().nullish(),UrlScheme:z.string().nullish(),UserCodeSupported:z.boolean().nullish(),PollIntervalSeconds:z.number().nullish()}).passthrough(),Rh=z.object({Google:z.object({Enabled:z.boolean().nullish(),WebClientID:z.string().nullish(),PlatformFallback:z.boolean().nullish(),AndroidClientID:z.string().nullish(),IosClientID:z.string().nullish(),DesktopClientID:z.string().nullish()}).passthrough().nullish(),Apple:z.object({Enabled:z.boolean().nullish(),BundleID:z.string().nullish(),ServiceID:z.string().nullish()}).passthrough().nullish(),PlayAccessMode:ki.nullish(),WalletLoginNetworks:z.array(z.object({NetworkID:z.string().nullish(),Type:z.string().nullish()}).passthrough()).nullish(),NativeSso:Yx.nullish()}).passthrough(),Ch=z.object({Linked:z.boolean().nullish(),Challenge:z.string().nullish(),ExpiresAt:c.nullish(),NetworkID:z.string().nullish(),Address:z.string().nullish(),PlayAccess:Bt.nullish()}).passthrough(),Sh=z.object({NetworkID:z.string().nullish(),Address:z.string().nullish(),CooldownUntil:c.nullish(),PlayAccess:Bt.nullish()}).passthrough(),xh=z.object({CodeTtlMinutes:z.number().nullish(),ResendCooldownSeconds:z.number().nullish()}),Ue=z.object({IsCompleted:z.boolean().nullish(),ServerTime:c.nullish()}),bh=z.object({Message:z.string(),ExpiresAt:c}),Ee={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 Gn=class{constructor(e){this.ctx=e;}ctx;endpoint(e){return Gt(this.ctx.settings.titleID,"Authentication",e)}login(e,t){return this.ctx.transport.post(this.endpoint(e),t,gh,{ticket:null})}refreshSession(e){return this.ctx.transport.post(this.endpoint(Ee.RefreshSession),e,yh,{ticket:null,silent:true})}getAuthOptions(e){return this.ctx.transport.post(this.endpoint(Ee.GetAuthOptions),e,Rh,{ticket:null})}linkWallet(e){return this.ctx.transport.post(Gt(this.ctx.settings.titleID,"Authentication",Ee.LinkWallet,e.UserID??""),e,Ch,{ticket:e.ClientSessionTicket})}unlinkWallet(e){return this.ctx.transport.post(Gt(this.ctx.settings.titleID,"Authentication",Ee.UnlinkWallet,e.UserID??""),e,Sh,{ticket:e.ClientSessionTicket})}loginWithDeviceID(e){return this.login(Ee.LoginWithDeviceID,e)}loginWithTelegram(e){return this.login(Ee.LoginWithTelegram,e)}loginWithEmail(e){return this.login(Ee.LoginWithEmail,e)}loginWithGoogle(e){return this.login(Ee.LoginWithGoogle,e)}loginWithApple(e){return this.login(Ee.LoginWithApple,e)}loginWithSsoCode(e){return this.login(Ee.LoginWithSsoCode,e)}registerWithEmail(e){return this.ctx.transport.post(this.endpoint(Ee.RegisterWithEmail),e,xh,{ticket:null})}confirmEmailRegistration(e){return this.login(Ee.ConfirmEmailRegistration,e)}resendVerificationCode(e){return this.ctx.transport.post(this.endpoint(Ee.ResendVerificationCode),e,Ue,{ticket:null})}requestWalletChallenge(e){return this.ctx.transport.post(this.endpoint(Ee.RequestWalletChallenge),e,bh,{ticket:null})}loginWithWallet(e){return this.login(Ee.LoginWithWallet,e)}forgotPassword(e){return this.ctx.transport.post(this.endpoint(Ee.ForgotPassword),e,Ue,{ticket:null})}resetPassword(e){return this.ctx.transport.post(this.endpoint(Ee.ResetPassword),e,Ue,{ticket:null})}};var Xx={ReturnKey:"ReturnKey",ReturnMarkedKey:"ReturnMarkedKey",ReturnEmpty:"ReturnEmpty"},Dh=z.enum(["ReturnKey","ReturnMarkedKey","ReturnEmpty"]).catch("ReturnKey"),eb=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),IsEnabled:z.boolean().nullish(),Order:z.number().nullish()}).passthrough(),Ph=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),Locales:z.record(z.string(),eb).nullish(),MissingKeyMode:Dh.nullish(),MaxEntriesPerLocale:z.number().nullish(),MaxValueLengthBytes:z.number().nullish()}).passthrough(),tb=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish()}).passthrough(),Ih=z.object({Locale:z.string().nullish(),Version:z.number().nullish(),Url:z.string().nullish(),Fallback:tb.nullish()}).passthrough(),Fn={GetLocalizationManifest:"GetLocalizationManifest",GetLocalizationTable:"GetLocalizationTable"},ib=z.object({Locale:z.string().nullish(),DisplayName:z.string().nullish(),Order:z.number().nullish(),Version:z.number().nullish()}).passthrough(),vh=z.object({IsEnabled:z.boolean().nullish(),DefaultLocale:z.string().nullish(),MissingKeyMode:Dh.nullish(),ResolvedLocale:z.string().nullish(),Locales:z.array(ib).nullish()}).passthrough(),Th=z.object({RequestedLocale:z.string().nullish(),Locale:z.string().nullish(),Version:z.number().nullish(),NotModified:z.boolean().nullish(),Entries:z.record(z.string(),z.string()).nullish(),FallbackLocale:z.string().nullish(),FallbackVersion:z.number().nullish()}).passthrough();var fa=z.object({TitleConfigVersion:z.string().nullish(),TitleConfigUrl:z.string().nullish(),User:z.unknown().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),StateEpoch:z.string().nullish(),Localization:Ih.nullish(),Views:z.array(z.object({Name:z.string(),Key:z.string().nullish(),Success:z.boolean(),Error:z.string().nullish(),Data:z.unknown().nullish()}).passthrough()).nullish()}).passthrough().transform(o=>o),kh=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish()}).passthrough().transform(o=>o),zh=z.object({StateEpoch:z.string().nullish(),StateVersions:z.record(z.string(),z.number()).nullish(),User:z.unknown().nullish()}).passthrough().transform(o=>o),Ah=z.object({}).passthrough().transform(o=>o),wh=z.object({}).passthrough().transform(o=>o),Mh=z.object({Today:z.number(),Yesterday:z.number(),CurrentWeek:z.number(),CurrentMonth:z.number(),Total:z.number(),TotalSessions:z.number(),FirstActiveAt:c.nullish(),LastActiveAt:c.nullish(),LongestSessionEverSeconds:z.number().nullish(),CurrentWeekActiveHoursMask:z.number().nullish(),CurrentMonthActiveHoursMask:z.number().nullish(),ReactivationCount:z.number().nullish(),History:z.record(z.string(),z.unknown()).nullish()}).passthrough(),Oh=z.object({Username:z.string()}),lt={GetClientState:"GetClientState",GetClientStateExcept:"GetClientStateExcept",GetStateVersions:"GetStateVersions",GetUserState:"GetUserState",GetInventory:"GetInventory",GetEventTokens:"GetEventTokens",GetUsageTime:"GetUsageTime",AddUsageTime:"AddUsageTime",DeleteUserAccount:"DeleteUserAccount",ChangeUsername:"ChangeUsername"};var Vn=class extends q{constructor(e){super(e,"User");}getClientState(e){return this.send(lt.GetClientState,e,fa)}getClientStateExcept(e){return this.send(lt.GetClientStateExcept,e,fa)}getStateVersions(e){return this.send(lt.GetStateVersions,e,kh)}getUserState(e){return this.send(lt.GetUserState,e,zh)}getInventory(e){return this.send(lt.GetInventory,e,Ah)}getEventTokens(e){return this.send(lt.GetEventTokens,e,wh)}getUsageTime(e){return this.send(lt.GetUsageTime,e,Mh)}addUsageTime(e){return this.send(lt.AddUsageTime,e,Ue,{silent:true})}deleteUserAccount(e){return this.send(lt.DeleteUserAccount,e,Ue)}changeUsername(e){return this.send(lt.ChangeUsername,e,Oh)}};var jn=class extends q{constructor(e){super(e,"Currency");}convert(e){return this.send(Sn.Convert,e,Yc)}cryptoConvert(e){return this.send(Sn.CryptoConvert,e,Xc)}};var sb=z.object({ItemInstanceID:z.string(),Units:z.number(),Level:z.number()}),ga=z.object({ServerTimeUtc:c,ItemInstanceID:z.string(),ItemID:z.string(),CatalogID:z.string().nullish(),Level:z.number(),Resources:M.nullish(),FodderConsumed:z.array(sb).nullish()}),Uh=z.array(Pe(ga)),Nn={UpgradeLevel:"UpgradeLevel",UpgradeLevelsBatch:"UpgradeLevelsBatch"},nb={FlatCount:"FlatCount",Merge:"Merge",InvestmentRefund:"InvestmentRefund"},rb=z.enum(["FlatCount","Merge","InvestmentRefund"]).catch("FlatCount"),ob={ProtectLeveled:"ProtectLeveled",CheapestFirst:"CheapestFirst",ClientSelected:"ClientSelected",SameLevelOnly:"SameLevelOnly"},ab=z.enum(["ProtectLeveled","CheapestFirst","ClientSelected","SameLevelOnly"]).catch("ProtectLeveled"),lb=z.object({ContractAddress:z.string().nullish(),TokenID:z.string().nullish(),TokenStandard:z.string().nullish(),MaxLevel:z.number().nullish()}).passthrough(),ub=z.object({Networks:z.record(z.string(),lb).nullish(),MetadataUrl:z.string().nullish()}).passthrough(),cb=z.object({FlatBonuses:z.record(z.string(),z.number()).nullish(),PercentBonuses:z.record(z.string(),z.number()).nullish(),Power:z.number().nullish()}).passthrough(),pb=z.object({MinCharacterLevel:z.number().nullish(),UseRequirements:z.record(z.string(),z.number()).nullish(),AllowedCharacterIDs:z.array(z.string()).nullish(),AllowedSlotIDs:z.array(z.string()).nullish(),IdleRateBonus:z.number().nullish()}).passthrough(),hb=z.object({ValuationMode:rb.nullish(),WeightCurve:Fe.nullish(),Selection:ab.nullish()}).passthrough(),db=z.object({MaxLevel:z.number().nullish(),PriceOptions:ae.nullish(),CostCurve:Fe.nullish(),FlatBonusCurve:Fe.nullish(),PercentBonusCurve:Fe.nullish(),PowerCurve:Fe.nullish(),Fodder:hb.nullish()}).passthrough(),mb=z.object({RarityID:z.string().nullish(),CollectionID:z.string().nullish(),AuthorID:z.string().nullish()}).passthrough(),fb=z.object({ItemID:z.string(),CatalogID:z.string(),ItemClass:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),CustomData:z.record(z.string(),z.string()).nullish(),IsStackable:z.boolean().nullish(),IsTradable:z.boolean().nullish(),Weight:z.number().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),NFT:ub.nullish(),Stats:cb.nullish(),Equipment:pb.nullish(),Upgrade:db.nullish(),Metadata:mb.nullish(),ExpirationDurationSeconds:z.number().nullish(),MaxSupply:z.number().nullish()}).passthrough(),gb=z.object({Items:z.record(z.string(),fb).nullish()}).passthrough(),_n=z.object({Catalogs:z.record(z.string(),gb).nullish()}).passthrough();var Wn=class extends q{constructor(e){super(e,"Item");}upgradeLevel(e){return this.send(Nn.UpgradeLevel,e,ga)}upgradeLevelsBatch(e){return this.send(Nn.UpgradeLevelsBatch,e,Uh)}};var Kn=class extends q{constructor(e){super(e,"Store");}purchase(e){return this.send(_t.Purchase,e,lo)}purchaseBatch(e){return this.send(_t.PurchaseBatch,e,Gl)}getDefinitions(e){return this.send(_t.GetDefinitions,e,ds)}getUserState(e){return this.send(_t.GetUserState,e,Fl)}getStorefront(e){return this.send(_t.GetStorefront,e,ms)}};var yb={Apple:"Apple",Google:"Google"},Qn=z.object({PremiumID:z.string().nullish(),PurchaseDate:z.string().nullish(),ExpirationDate:z.string().nullish(),TransactionID:z.string().nullish(),IsAutoRenewEnabled:z.boolean().nullish()}).passthrough(),Hn=z.object({Subscriptions:z.record(z.string(),Qn).nullish(),ActivatedTrialIDs:z.array(z.string()).nullish(),MaxActiveTier:z.number().nullish()}).passthrough().transform(o=>o),Rb=z.object({PremiumID:z.string().nullish(),DisplayName:z.string().nullish(),Tier:z.number().nullish(),DurationDays:z.number().nullish(),TrialDurationDays:z.number().nullish(),PriceOptions:ae.nullish(),Benefits:z.record(z.string(),z.string()).nullish()}).passthrough(),ya=z.object({Definitions:z.record(z.string(),Rb).nullish()}).passthrough(),Eh=z.object({Premium:ya.nullish()}),qh=z.object({ServerTimeUtc:c.nullish(),Premium:Hn.nullish()}),$n=z.object({ServerTimeUtc:c.nullish(),Premium:Hn.nullish(),Subscription:Qn.nullish(),Resources:M.nullish()}),Qt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateTrial:"ActivateTrial",PurchaseWithResources:"PurchaseWithResources",PurchaseRealMoney:"PurchaseRealMoney"};var Cb={Consumable:"Consumable",NonConsumable:"NonConsumable",Subscription:"Subscription"},Sb=z.enum(["Consumable","NonConsumable","Subscription"]).catch("Consumable"),Bh=z.object({StartUtc:c.nullish(),EndUtc:c.nullish(),Gate:J.nullish(),Limits:ye.nullish()}).passthrough(),Ra=z.object({ResourceAction:z.string().nullish(),RevokeEntitlement:z.boolean().nullish(),BlockFuturePurchases:z.boolean().nullish()}).passthrough(),xb=z.object({PremiumID:z.string().nullish(),RenewalRewards:H.nullish(),FallbackDurationDays:z.number().nullish(),RevokeOnRefund:z.boolean().nullish()}).passthrough(),bb=z.object({Rewards:K.nullish(),Rules:K.nullish(),Refund:K.nullish()}).passthrough(),Db=z.object({ProductID:z.string().nullish(),Name:z.string().nullish(),Type:Sb.nullish(),Enabled:z.boolean().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish(),Rewards:H.nullish(),PriceUsdCents:z.number().nullish(),TelegramStarsPrice:z.number().nullish(),Rules:Bh.nullish(),Refund:Ra.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CustomParams:z.record(z.string(),z.string()).nullish(),Subscription:xb.nullish(),Presets:bb.nullish()}).passthrough(),Pb=z.object({StoreID:z.string().nullish(),Enabled:z.boolean().nullish(),PackageName:z.string().nullish(),VerificationMode:z.string().nullish(),PlayPublicKey:z.string().nullish(),RequireCertificateChain:z.boolean().nullish(),SecretName:z.string().nullish(),IssuerID:z.string().nullish(),KeyID:z.string().nullish(),AcknowledgePurchases:z.boolean().nullish(),NotificationPackageName:z.string().nullish()}).passthrough(),Ib=z.object({Rewards:H.nullish()}).passthrough(),vb=z.object({Rules:Bh.nullish()}).passthrough(),Tb=z.object({Refund:Ra.nullish()}).passthrough(),kb=z.object({Rewards:z.record(z.string(),Ib).nullish(),Rules:z.record(z.string(),vb).nullish(),Refund:z.record(z.string(),Tb).nullish()}).passthrough(),zb=z.object({MaxPurchaseAgeDays:z.number().nullish(),AllowSandbox:z.boolean().nullish(),RequirePackageMatch:z.boolean().nullish(),MaxReceiptsPerBatch:z.number().nullish(),RefundCheckHorizonDays:z.number().nullish(),RejectCrossUserReceipts:z.boolean().nullish()}).passthrough(),Ab=z.object({Enabled:z.boolean().nullish(),Products:z.record(z.string(),Db).nullish(),Stores:z.record(z.string(),Pb).nullish(),Presets:kb.nullish(),Validation:zb.nullish(),Refund:Ra.nullish()}).passthrough(),Lh=z.object({ProductID:z.string().nullish(),TotalPurchases:z.number().nullish(),DailyPurchases:z.number().nullish(),DailyResetUtc:c.nullish(),LastPurchasedAt:c.nullish(),Owned:z.boolean().nullish(),Refunded:z.boolean().nullish(),PurchaseBlocked:z.boolean().nullish(),Store:z.string().nullish(),LastTransactionID:z.string().nullish()}).passthrough(),Gh=z.object({ProductID:z.string().nullish(),PremiumID:z.string().nullish(),Store:z.string().nullish(),OriginalTransactionID:z.string().nullish(),LastTransactionID:z.string().nullish(),ExpiresAt:c.nullish(),AutoRenew:z.boolean().nullish(),Status:z.string().nullish(),RenewalCount:z.number().nullish(),LastStoreCheckAt:c.nullish(),LastStoreCheckError:z.string().nullish(),UpdatedAt:c.nullish()}).passthrough(),wb=z.object({Products:z.record(z.string(),Lh).nullish(),LifetimeSpendUsdCents:z.number().nullish(),Subscriptions:z.record(z.string(),Gh).nullish(),LastRefundCheckAt:c.nullish(),TotalPurchases:z.number().nullish(),FirstPurchaseAt:c.nullish(),LastPurchaseAt:c.nullish()}).passthrough(),Mb=z.object({ProductID:z.string(),Available:z.boolean(),Owned:z.boolean(),Blocked:z.boolean(),Reason:z.string().nullish(),StoreProductIDs:z.record(z.string(),z.string()).nullish()}).passthrough(),Fh=z.object({ServerTimeUtc:c,Purchase:Ab.nullish(),Availability:z.array(Mb).nullish()}),Vh=z.object({ServerTimeUtc:c,Purchase:wb.nullish()}),Ob={Granted:"Granted",Restored:"Restored",AlreadyProcessed:"AlreadyProcessed"},Ub=z.enum(["Granted","Restored","AlreadyProcessed"]).catch("Granted"),Ca=z.object({ServerTimeUtc:c,Store:Gi.nullish(),ProductID:z.string().nullish(),TransactionID:z.string().nullish(),Status:Ub.nullish(),Granted:z.boolean().nullish(),Quantity:z.number().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),ProductState:Lh.nullish(),Premium:Hn.nullish(),Subscription:Qn.nullish(),SubscriptionMirror:Gh.nullish()}).passthrough(),jh=z.object({ServerTimeUtc:c,ProductID:z.string().nullish(),Stars:z.number().nullish(),InvoiceLink:z.string(),ExpiresAt:c.nullish()}).passthrough(),Nh=ft(Ca),Ht={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ValidatePurchase:"ValidatePurchase",ValidatePurchasesBatch:"ValidatePurchasesBatch",CreateTelegramInvoice:"CreateTelegramInvoice"};var Jn=class extends q{constructor(e){super(e,"Purchase");}getDefinitions(e){return this.send(Ht.GetDefinitions,e,Fh)}getUserState(e){return this.send(Ht.GetUserState,e,Vh)}validatePurchase(e){return this.send(Ht.ValidatePurchase,e,Ca)}validatePurchasesBatch(e){return this.send(Ht.ValidatePurchasesBatch,e,Nh)}createTelegramInvoice(e){return this.send(Ht.CreateTelegramInvoice,e,jh)}};var Eb=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),_h=z.object({Reward:H.nullish(),Weight:z.number().nullish(),AmountRange:Eb.nullish()}).passthrough(),mi=z.object({SlotID:z.string().nullish(),MinRolls:z.number().nullish(),MaxRolls:z.number().nullish(),Pool:z.array(_h).nullish()}).passthrough(),fi=z.object({RuleID:z.string().nullish(),Threshold:z.number().nullish(),Pool:z.array(_h).nullish()}).passthrough(),qb=z.object({RewardSlots:z.array(mi).nullish()}).passthrough(),Bb=z.object({PityRules:z.array(fi).nullish()}).passthrough(),Zn=z.object({SlotPresets:z.record(z.string(),qb).nullish(),PityPresets:z.record(z.string(),Bb).nullish()}).passthrough();var Lb=z.object({RuleID:z.string(),BoxIndex:z.number().nullish()}),Wh=z.object({ServerTimeUtc:c,LootboxID:z.string(),OpenedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:z.array(M).nullish(),TriggeredPity:z.array(Lb).nullish()}),Gb=z.object({RewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),Fb=z.object({CatalogID:z.string().nullish(),ItemID:z.string().nullish(),MaxDrops:_.nullish()}).passthrough(),Vb=z.object({LootboxID:z.string(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:ae.nullish(),RewardSlots:z.array(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:Gb.nullish(),RewardMultiplier:Vi.nullish(),SupplyLimits:z.array(Fb).nullish(),MaxOpenCount:z.number().nullish()}).passthrough(),jb=z.object({MaxOpenCount:z.number().nullish()}).passthrough(),Sa=z.object({Definitions:z.record(z.string(),Vb).nullish(),RewardPools:Zn.nullish(),Settings:jb.nullish()}).passthrough(),Kh=z.object({LootboxDefinitions:Sa.nullish()}),Yn={GetDefinitions:"GetDefinitions",Open:"Open"};var Xn=class extends q{constructor(e){super(e,"Lootbox");}getDefinitions(e){return this.send(Yn.GetDefinitions,e,Kh)}open(e){return this.send(Yn.Open,e,Wh)}};var Nb=z.object({}).passthrough().transform(o=>o),_b=z.object({}).passthrough().transform(o=>o),Wb=z.object({}).passthrough().transform(o=>o),Kb=z.object({}).passthrough().transform(o=>o),Qb=z.object({}).passthrough().transform(o=>o),Qh=z.object({ServerTimeUtc:c,CalendarID:z.string(),DayNumber:z.number().nullish(),DailyState:Nb,Resources:M.nullish(),Inventory:Q.nullish()}),Hh=z.object({ServerTimeUtc:c,AccrualID:z.string(),AccruedSeconds:_.nullish(),AppliedRatePerSecond:z.number().nullish(),IdleState:_b,Resources:M.nullish(),Inventory:Q.nullish()}),$h=z.object({ServerTimeUtc:c,ComebackID:z.string(),ClaimedTierIndex:z.number().nullish(),ComebackState:Wb,Resources:M.nullish(),Inventory:Q.nullish()}),Jh=z.object({ServerTimeUtc:c,ClaimID:z.string(),ClaimState:Kb,Resources:M.nullish(),Inventory:Q.nullish()}),Zh=z.object({Enabled:z.boolean(),Multiplier:z.number().nullish(),Progress:_.nullish(),Source:z.string().nullish(),SourceKey:z.string().nullish()}),Hb=z.object({RewardMode:z.string().nullish(),RewardStackLowerTiers:z.boolean().nullish()}).passthrough(),$b=z.object({DayNumber:z.number().nullish(),Rewards:H.nullish(),IsMilestone:z.boolean().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),Mi=z.object({Gate:J.nullish(),Limits:ye.nullish()}).passthrough(),xa=z.object({Availability:K.nullish()}).passthrough(),Jb=z.object({Availability:z.record(z.string(),Mi).nullish()}).passthrough(),Zb=z.object({CalendarID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Days:z.array($b).nullish(),IsLooping:z.boolean().nullish(),MissBehavior:z.string().nullish(),ResetByDays:z.number().nullish(),MissThresholdMultiplier:z.number().nullish(),ClaimMode:z.string().nullish(),ClaimCooldownSeconds:z.number().nullish(),Availability:Mi.nullish(),Presets:xa.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),Yb=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),Multiplier:z.number().nullish()}).passthrough(),Xb=z.object({BaseRatePerSecond:z.number().nullish(),PowerCoefficient:z.number().nullish(),BoardRankCoefficient:z.number().nullish(),EquipmentBonusEnabled:z.boolean().nullish(),EquipmentCharacterID:z.string().nullish(),PremiumMultipliers:z.array(Yb).nullish()}).passthrough(),eD=z.object({MinCharacterLevel:z.number().nullish(),RequirementsCharacterID:z.string().nullish(),Availability:Mi.nullish(),RequiredItemIDs:z.array(z.string()).nullish(),RequiredEquippedItemIDs:z.array(z.string()).nullish()}).passthrough(),tD=z.object({AccrualID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rate:Xb.nullish(),Rewards:H.nullish(),MaxAccumulationSeconds:z.number().nullish(),MinClaimSeconds:z.number().nullish(),Requirements:eD.nullish(),FirstClaimMode:z.string().nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),iD=z.object({MinAbsenceSeconds:z.number().nullish(),Rewards:H.nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),sD=z.object({ComebackID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tiers:z.array(iD).nullish(),ClaimCooldownSeconds:z.number().nullish(),ClaimWindowSeconds:z.number().nullish(),TrackPresenceOnRead:z.boolean().nullish(),Availability:Mi.nullish(),Presets:xa.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),nD=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),CooldownSeconds:z.number().nullish(),MaxClaimsPerWindow:z.number().nullish(),WindowSeconds:z.number().nullish(),TotalClaimLimit:z.number().nullish()}).passthrough(),rD=z.object({ClaimID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Mode:z.string().nullish(),Rewards:H.nullish(),PremiumLimitOverrides:z.array(nD).nullish(),Availability:Mi.nullish(),Presets:xa.nullish(),AvailableFromUtc:z.string().nullish(),AvailableUntilUtc:z.string().nullish()}).passthrough(),ba=z.object({TierRewards:Hb.nullish(),MilestoneRewardMultiplier:Vi.nullish(),DailyCalendars:z.record(z.string(),Zb).nullish(),IdleAccruals:z.record(z.string(),tD).nullish(),Comebacks:z.record(z.string(),sD).nullish(),Claims:z.record(z.string(),rD).nullish(),Presets:Jb.nullish()}).passthrough(),Yh=z.object({RewardDefinitions:ba.nullish()}),Xh=z.object({Rewards:Qb.nullish()}),kt={GetRewardDefinitions:"GetRewardDefinitions",GetUserRewardsState:"GetUserRewardsState",ClaimDailyReward:"ClaimDailyReward",CollectIdleAccrual:"CollectIdleAccrual",ClaimComebackReward:"ClaimComebackReward",ClaimReward:"ClaimReward",ClaimRewardsBatch:"ClaimRewardsBatch",GetMilestoneRewardMultiplier:"GetMilestoneRewardMultiplier"};var er=class extends q{constructor(e){super(e,"Reward");}getRewardDefinitions(e){return this.send(kt.GetRewardDefinitions,e,Yh)}getUserRewardsState(e){return this.send(kt.GetUserRewardsState,e,Xh)}getMilestoneRewardMultiplier(e){return this.send(kt.GetMilestoneRewardMultiplier,e,Zh)}claimDailyReward(e){return this.send(kt.ClaimDailyReward,e,Qh)}collectIdleAccrual(e){return this.send(kt.CollectIdleAccrual,e,Hh)}claimComebackReward(e){return this.send(kt.ClaimComebackReward,e,$h)}claimReward(e){return this.send(kt.ClaimReward,e,Jh)}};var tr=class extends q{constructor(e){super(e,"Tutorial");}getTutorialDefinitions(e){return this.send(nt.GetTutorialDefinitions,e,Cl)}getUserTutorialState(e){return this.send(nt.GetUserTutorialState,e,_i)}startFlow(e){return this.send(nt.StartFlow,e,At)}reportStepShown(e){return this.send(nt.ReportStepShown,e,At)}completeStep(e){return this.send(nt.CompleteStep,e,At)}completeStepsBatch(e){return this.send(nt.CompleteStepsBatch,e,bl)}skipStep(e){return this.send(nt.SkipStep,e,At)}skipFlow(e){return this.send(nt.SkipFlow,e,At)}claimFlowReward(e){return this.send(nt.ClaimFlowReward,e,xl)}resetFlow(e){return this.send(nt.ResetFlow,e,At)}};var oD={Open:"Open",Application:"Application"},aD=z.enum(["Open","Application"]).catch("Open"),lD={Pending:"Pending",Approved:"Approved",Rejected:"Rejected",Suspended:"Suspended",Left:"Left"},ed=z.enum(["Pending","Approved","Rejected","Suspended","Left"]).catch("Pending"),uD={VirtualCurrency:"VirtualCurrency",CryptoCurrency:"CryptoCurrency"},Da=z.enum(["VirtualCurrency","CryptoCurrency"]).catch("VirtualCurrency"),cD={Views:"Views",Likes:"Likes",Comments:"Comments",Shares:"Shares"};z.enum(["Views","Likes","Comments","Shares"]).catch("Views");var $t={GetCommunityMarketingState:"GetCommunityMarketingState",GetEarnings:"GetEarnings",Claim:"Claim",WithdrawCryptoReward:"WithdrawCryptoReward",CheckJoinEligibility:"CheckJoinEligibility"},pD=z.object({CampaignID:z.string().nullish(),DisplayNameKey:z.string().nullish(),DescriptionKey:z.string().nullish(),IconPath:z.string().nullish(),SortOrder:z.number().nullish(),IsRunning:z.boolean().nullish()}).passthrough(),td=z.object({IsEnabled:z.boolean().nullish(),CreatorPortalUrl:z.string().nullish(),ParticipationMode:aD.nullish(),IsCreator:z.boolean().nullish(),CreatorStatus:ed.nullish(),VerificationCode:z.string().nullish(),TeamID:z.string().nullish(),Campaigns:z.array(pD).nullish()}).passthrough(),hD=z.object({Earned:z.number().nullish(),Mature:z.number().nullish(),CountedMetrics:z.record(z.string(),z.number()).nullish(),ReachedMilestones:z.array(z.string()).nullish(),CappedBySubmissionLimit:z.boolean().nullish(),CappedByCreatorLimit:z.boolean().nullish(),NotPaidAsCopy:z.boolean().nullish()}).passthrough(),dD=z.object({CampaignID:z.string().nullish(),CurrencyKind:Da.nullish(),CurrencyID:z.string().nullish(),NetworkID:z.string().nullish(),Earned:z.number().nullish(),Mature:z.number().nullish(),Granted:z.number().nullish(),Paid:z.number().nullish(),Overpaid:z.number().nullish(),Claimable:z.number().nullish(),BySubmission:z.record(z.string(),hD).nullish(),ComputedAt:z.string().nullish()}).passthrough(),mD=z.object({PayoutID:z.string().nullish(),CampaignID:z.string().nullish(),Amount:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Da.nullish(),NetworkID:z.string().nullish(),PaidAt:z.string().nullish()}).passthrough(),id=z.object({ServerTimeUtc:z.string().nullish(),HoldDays:z.number().nullish(),Campaigns:z.array(dD).nullish(),Payouts:z.array(mD).nullish()}).passthrough(),sd=z.object({CampaignID:z.string().nullish(),PayoutID:z.string().nullish(),Claimed:z.number().nullish(),CurrencyID:z.string().nullish(),CurrencyKind:Da.nullish(),NetworkID:z.string().nullish(),RemainingFraction:z.number().nullish(),IdempotentReplay:z.boolean().nullish(),Message:z.string().nullish()}).passthrough(),fD=z.object({To:z.string().nullish(),Amount:z.string().nullish()}).passthrough(),gD=z.object({ContractAddress:z.string().nullish(),TokenAddress:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),TokenId:z.string().nullish(),Nonce:z.string().nullish(),Signature:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish(),Deadline:z.string().nullish(),SignatureEpoch:z.string().nullish(),Splits:z.array(fD).nullish()}).passthrough(),yD=z.object({Kind:z.string().nullish(),Target:z.string().nullish(),Required:z.number().nullish(),Actual:z.number().nullish(),Passed:z.boolean().nullish()}).passthrough(),nd=z.object({Passed:z.boolean().nullish(),Approved:z.boolean().nullish(),Status:ed.nullish(),WalletMissing:z.boolean().nullish(),WalletConnectAllowed:z.boolean().nullish(),Conditions:z.array(yD).nullish()}).passthrough(),RD=z.object({To:z.string().nullish(),Amount:z.union([z.string(),z.number()]).nullish()}).passthrough(),CD=z.object({ProgramID:z.string().nullish(),Mint:z.string().nullish(),WalletAddress:z.string().nullish(),Amount:z.string().nullish(),BurnAmount:z.string().nullish(),Nonce:z.string().nullish(),ExpiresAt:z.string().nullish(),SignatureEpoch:z.string().nullish(),Domain:z.string().nullish(),Splits:z.array(RD).nullish(),SignatureHex:z.string().nullish(),Ed25519PublicKey:z.string().nullish(),Ed25519Message:z.string().nullish(),UserID:z.string().nullish(),TitleID:z.string().nullish(),Category:z.string().nullish()}).passthrough(),rd=z.object({ServerTimeUtc:z.string().nullish(),TitleTransactionID:z.string().nullish(),NetworkID:z.string().nullish(),ChainID:z.number().nullish(),CurrencyID:z.string().nullish(),AmountNative:z.number().nullish(),NetAmountNative:z.number().nullish(),BurnAmountNative:z.number().nullish(),AmountUsd:z.number().nullish(),ExpiresAt:z.string().nullish(),EvmSignature:gD.nullish(),SolanaSignature:CD.nullish(),StateDelta:hi.nullish()}).passthrough();var ir=class extends q{constructor(e){super(e,"CommunityMarketing");}getCommunityMarketingState(e){return this.send($t.GetCommunityMarketingState,e,td)}getEarnings(e){return this.send($t.GetEarnings,e,id)}claim(e){return this.send($t.Claim,e,sd)}checkJoinEligibility(e){return this.send($t.CheckJoinEligibility,e,nd)}withdrawCryptoReward(e){return this.send($t.WithdrawCryptoReward,e,rd)}};var sr=class extends q{constructor(e){super(e,"Chat");}getChatDefinitions(e){return this.send(Ke.GetChatDefinitions,e,iu)}getChannels(e){return this.send(Ke.GetChannels,e,Ps)}poll(e){return this.send(Ke.Poll,e,su)}getHistory(e){return this.send(Ke.GetHistory,e,nu)}getConversations(e){return this.send(Ke.GetConversations,e,au)}sendMessage(e){return this.send(Ke.SendMessage,e,ru)}openDirectChannel(e){return this.send(Ke.OpenDirectChannel,e,ou)}markRead(e){return this.send(Ke.MarkRead,e,ci)}joinChannel(e){return this.send(Ke.JoinChannel,e,ci)}leaveChannel(e){return this.send(Ke.LeaveChannel,e,ci)}reportMessage(e){return this.send(Ke.ReportMessage,e,lu)}ignoreUser(e){return this.send(Ke.IgnoreUser,e,ci)}unignoreUser(e){return this.send(Ke.UnignoreUser,e,ci)}};var nr=class extends q{constructor(e){super(e,"Push");}getPushConfig(e){return this.send(pi.GetPushConfig,e,pu)}subscribePush(e){return this.send(pi.SubscribePush,e,ho)}unsubscribePush(e){return this.send(pi.UnsubscribePush,e,Ue)}getPushSubscriptions(e){return this.send(pi.GetPushSubscriptions,e,hu)}};var rr=class extends q{constructor(e){super(e,"Localization");}send(e,t,i,s){let n=this.endpoint(e,t);return super.send(e,t,i,{throttleKey:t.Locale?`${n}:${t.Locale}`:n,...s})}getLocalizationManifest(e){return this.send(Fn.GetLocalizationManifest,e,vh)}getLocalizationTable(e){return this.send(Fn.GetLocalizationTable,e,Th)}};var or=class extends q{constructor(e){super(e,"Quest");}getQuestDefinitions(e){return this.send(pt.GetQuestDefinitions,e,Ni)}getUserQuestState(e){return this.send(pt.GetUserQuestState,e,al)}refreshQuestCycles(e){return this.send(pt.RefreshQuestCycles,e,Ue)}claimQuestReward(e){return this.send(pt.ClaimQuestReward,e,Jr)}claimQuestRewardsBatch(e){return this.send(pt.ClaimQuestRewardsBatch,e,cl)}claimMilestoneReward(e){return this.send(pt.ClaimMilestoneReward,e,Zr)}claimMilestoneRewardsBatch(e){return this.send(pt.ClaimMilestoneRewardsBatch,e,pl)}claimGroupCompletionReward(e){return this.send(pt.ClaimGroupCompletionReward,e,ll)}addQuestProgress(e){return this.send(pt.AddQuestProgress,e,ul)}};var ar=class extends q{constructor(e){super(e,"TimedEvent");}getActiveEvents(e){return this.send(ot.GetActiveEvents,e,ws)}getDefinitions(e){return this.send(ot.GetDefinitions,e,As)}getUserLteState(e){return this.send(ot.GetUserLteState,e,gu)}grantTokens(e){return this.send(ot.GrantTokens,e,M)}spendTokens(e){return this.send(ot.SpendTokens,e,go)}claimMilestone(e){return this.send(ot.ClaimMilestone,e,yo)}claimMilestonesBatch(e){return this.send(ot.ClaimMilestonesBatch,e,Ro)}claimAllMilestones(e){return this.send(ot.ClaimAllMilestones,e,Ro)}spendTokensBatch(e){return this.send(ot.SpendTokensBatch,e,yu)}grantTokensBatch(e){return this.send(ot.GrantTokensBatch,e,Ru)}};var lr=class extends q{constructor(e){super(e,"Leaderboard");}getDefinitions(e){return this.send(Ve.GetDefinitions,e,Ls)}getLeaderboard(e){return this.send(Ve.GetLeaderboard,e,Di)}getMyProgress(e){return this.send(Ve.GetMyProgress,e,Os)}submitScore(e){return this.send(Ve.SubmitScore,e,Us)}submitScoreFromSource(e){return this.send(Ve.SubmitScoreFromSource,e,Us)}claimCycleReward(e){return this.send(Ve.ClaimCycleReward,e,Es)}claimMilestone(e){return this.send(Ve.ClaimMilestone,e,qs)}getFriendsLeaderboard(e){return this.send(Ve.GetFriendsLeaderboard,e,Di)}getLeaderboardsBatch(e){return this.send(Ve.GetLeaderboardsBatch,e,xu)}getProgressBatch(e){return this.send(Ve.GetProgressBatch,e,Bs)}claimCycleRewardsBatch(e){return this.send(Ve.ClaimCycleRewardsBatch,e,bu)}claimMilestonesBatch(e){return this.send(Ve.ClaimMilestonesBatch,e,Du)}submitScoresBatch(e){return this.send(Ve.SubmitScoresBatch,e,Pu)}claimAllRewardsBatch(e){return this.send(Ve.ClaimAllRewardsBatch,e,Iu)}getOverviewBatch(e){return this.send(Ve.GetOverviewBatch,e,vu)}};var ur=class extends q{constructor(e){super(e,"Season");}getDefinitions(e){return this.send(Ot.GetDefinitions,e,Vs)}getActiveSeason(e){return this.send(Ot.GetActiveSeason,e,Fs)}getUserState(e){return this.send(Ot.GetUserState,e,Co)}grantStatusTokens(e){return this.send(Ot.GrantStatusTokens,e,Au)}claimTierReward(e){return this.send(Ot.ClaimTierReward,e,So)}claimTierRewardsBatch(e){return this.send(Ot.ClaimTierRewardsBatch,e,wu)}};var cr=class extends q{constructor(e){super(e,"Premium");}getDefinitions(e){return this.send(Qt.GetDefinitions,e,Eh)}getUserState(e){return this.send(Qt.GetUserState,e,qh)}activateTrial(e){return this.send(Qt.ActivateTrial,e,$n)}purchaseItemOrCurrency(e){return this.send(Qt.PurchaseWithResources,e,$n)}purchaseRealMoney(e){return this.send(Qt.PurchaseRealMoney,e,$n)}};var pr=class extends q{constructor(e){super(e,"Character");}getCharacterDefinitions(e){return this.send(je.GetCharacterDefinitions,e,Ws)}getUserCharacters(e){return this.send(je.GetUserCharacters,e,Bu)}unlockCharacter(e){return this.send(je.UnlockCharacter,e,Po)}upgradeStatLevel(e){return this.send(je.UpgradeStatLevel,e,bo)}upgradeCharacterLevel(e){return this.send(je.UpgradeCharacterLevel,e,Do)}equipItems(e){return this.send(je.EquipItems,e,Lu)}unequipItems(e){return this.send(je.UnequipItems,e,Gu)}unequipAllCharacters(e){return this.send(je.UnequipAllCharacters,e,Fu)}unlockCharactersBatch(e){return this.send(je.UnlockCharactersBatch,e,Wu)}upgradeCharacterLevelsBatch(e){return this.send(je.UpgradeCharacterLevelsBatch,e,Ku)}upgradeStatLevelsBatch(e){return this.send(je.UpgradeStatLevelsBatch,e,Qu)}unlockSkin(e){return this.send(je.UnlockSkin,e,Vu)}equipSkin(e){return this.send(je.EquipSkin,e,ju)}unequipSkin(e){return this.send(je.UnequipSkin,e,Nu)}getCharacterSkins(e){return this.send(je.GetCharacterSkins,e,_u)}};var hr=class extends q{constructor(e){super(e,"Match");}createMatch(e){return this.send(Rt.CreateMatch,e,Pp)}updateMatch(e){return this.send(Rt.UpdateMatch,e,Ip)}cancelMatch(e){return this.send(Rt.CancelMatch,e,vp)}instantBattle(e){return this.send(Rt.InstantBattle,e,Tp)}saveStrategy(e){return this.send(Rt.SaveStrategy,e,Ue)}getMyMatches(e){return this.send(Rt.GetMyMatches,e,Jo)}getAvailableMatches(e){return this.send(Rt.GetAvailableMatches,e,Jo)}getDefinitions(e){return this.send(Rt.GetDefinitions,e,wp)}};var SD={TradeUpRarity:"TradeUpRarity",TradeUpCollection:"TradeUpCollection"},od=z.enum(["TradeUpRarity","TradeUpCollection"]).catch("TradeUpRarity"),xD={None:"None",Min:"Min",Average:"Average",Max:"Max"},bD=z.enum(["None","Min","Average","Max"]).catch("None"),DD={ProtectLeveled:"ProtectLeveled",ClientSelected:"ClientSelected",LowestLevelFirst:"LowestLevelFirst",HighestLevelFirst:"HighestLevelFirst"},PD=z.enum(["ProtectLeveled","ClientSelected","LowestLevelFirst","HighestLevelFirst"]).catch("ProtectLeveled"),ID={Clamp:"Clamp",Reject:"Reject"},vD=z.enum(["Clamp","Reject"]).catch("Clamp"),TD=z.object({ItemInstanceID:z.string().nullish(),ItemID:z.string().nullish(),Level:z.number().nullish(),Units:z.number().nullish()}),kD=z.object({Index:z.number().nullish(),BurnedItemIDs:z.array(z.string()).nullish(),RolledCollectionID:z.string().nullish(),UsedCollections:z.record(z.string(),z.number()).nullish(),Output:Qr.nullish(),OutputLevel:z.number().nullish(),BurnedInstances:z.array(TD).nullish()}),ad=z.object({ServerTimeUtc:c,Type:od.nullish(),CraftID:z.string(),CraftedCount:z.number().nullish(),SelectedOptionID:z.string().nullish(),InputRarity:z.string().nullish(),OutputRarity:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),Results:z.array(kD).nullish()}),zD=z.object({CraftID:z.string().nullish(),Type:od.nullish(),CatalogID:z.string().nullish(),CollectionID:z.string().nullish(),InputRarityID:z.string().nullish(),OutputRarityID:z.string().nullish(),RequiredItemCount:z.number().nullish(),PriceOptions:ae.nullish(),OutputLevelMode:bD.nullish(),InputSelection:PD.nullish(),OutputLevelOverflow:vD.nullish()}).passthrough(),Pa=z.object({Definitions:z.record(z.string(),zD).nullish()}).passthrough(),ld=z.object({ServerTimeUtc:c.nullish(),CraftDefinitions:Pa.nullish()}),dr={GetDefinitions:"GetDefinitions",Craft:"Craft"};var mr=class extends q{constructor(e){super(e,"Craft");}getDefinitions(e){return this.send(dr.GetDefinitions,e,ld)}craft(e){return this.send(dr.Craft,e,ad)}};var AD=2e5,fr=class extends q{constructor(e){super(e,"AI");}generate(e,t){return this.send(e,t,$s,{timeoutMs:AD,autoRetry:false})}readGeneration(e,t){return this.send(e,t,$s,{throttleKey:`AI:${e}:${t.GenerationID??""}`})}getDefinitions(e){return this.send(Ge.GetDefinitions,e,ic)}generateText(e){return this.generate(Ge.GenerateText,e)}getText(e){return this.readGeneration(Ge.GetText,e)}generateImage(e){return this.generate(Ge.GenerateImage,e)}editImage(e){return this.generate(Ge.EditImage,e)}getImage(e){return this.readGeneration(Ge.GetImage,e)}generateVideo(e){return this.generate(Ge.GenerateVideo,e)}getVideo(e){return this.readGeneration(Ge.GetVideo,e)}generateAudio(e){return this.generate(Ge.GenerateAudio,e)}getAudio(e){return this.readGeneration(Ge.GetAudio,e)}generateMusic(e){return this.generate(Ge.GenerateMusic,e)}getMusic(e){return this.readGeneration(Ge.GetMusic,e)}generateThreeD(e){return this.generate(Ge.GenerateThreeD,e)}getThreeD(e){return this.readGeneration(Ge.GetThreeD,e)}listGenerations(e){return this.send(Ge.ListGenerations,e,tc)}getGeneration(e){return this.readGeneration(Ge.GetGeneration,e)}};var wD={Pending:"Pending",Accepted:"Accepted",Declined:"Declined",Cancelled:"Cancelled",Expired:"Expired"},MD=z.enum(["Pending","Accepted","Declined","Cancelled","Expired"]).catch("Pending"),ud=z.object({}).passthrough().transform(o=>o),gi=z.object({CollectibleID:z.string(),Rarity:z.number().nullish(),IsSpecial:z.boolean().nullish(),IsDuplicate:z.boolean().nullish(),CollectionCurrencyConverted:z.number().nullish()}),cd=z.object({GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish()}),pd=z.object({OpenedCount:z.number().nullish(),Packs:z.array(cd).nullish(),GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish(),NewCollectionCurrencyBalance:_.nullish(),NewlyCompletedSetIDs:z.array(z.string()).nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),hd=z.object({OpenedCount:z.number().nullish(),Chests:z.array(cd).nullish(),GrantedCollectibles:z.array(gi).nullish(),DuplicateCollectibles:z.array(gi).nullish(),CollectionCurrencyEarned:_.nullish(),NewCollectionCurrencyBalance:_.nullish(),Resources:M.nullish(),Inventory:Q.nullish(),TriggeredPity:z.array(z.unknown()).nullish()}),dd=z.object({GrantedCollectibleID:z.string().nullish(),NewlyCompletedSetID:z.string().nullish(),CollectionJustCompleted:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Ia=z.object({SetID:z.string(),Resources:M.nullish(),Inventory:Q.nullish()}),md=z.array(Pe(Ia)),fd=z.object({Resources:M.nullish(),Inventory:Q.nullish()}),OD=z.object({OfferID:z.string(),TitleID:z.string().nullish(),CollectionID:z.string().nullish(),SenderUserID:z.string().nullish(),SenderPublicData:Oe.nullish(),OfferedCollectibleID:z.string().nullish(),OfferedCollectibleIsSpecial:z.boolean().nullish(),ReceiverUserID:z.string().nullish(),RequestedCollectibleID:z.string().nullish(),RequestedCollectibleIsSpecial:z.boolean().nullish(),Status:MD.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RespondedAtUtc:c.nullish(),DeclineReason:z.string().nullish(),IsSpecialTradeEvent:z.boolean().nullish(),SpecialTradeEventID:z.string().nullish()}).passthrough(),gd=z.object({OfferID:z.string(),ExpiresAtUtc:c.nullish(),Resources:M.nullish()}),yd=z.object({OfferID:z.string(),Resources:M.nullish()}),Rd=z.object({OfferID:z.string(),ReceivedCollectibleID:z.string().nullish(),ReceivedIsSpecial:z.boolean().nullish(),SentCollectibleID:z.string().nullish(),SentCollectibleIsSpecial:z.boolean().nullish(),Transfer:z.unknown().nullish()}),Cd=z.object({OfferID:z.string(),Resources:M.nullish()}),va=z.object({Offers:z.array(OD).nullish()}),UD=z.object({CollectibleID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Rarity:z.number().nullish(),HasSpecialVersion:z.boolean().nullish(),SortOrder:z.number().nullish()}).passthrough(),ED=z.object({SetID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SortOrder:z.number().nullish(),Collectibles:z.array(UD).nullish(),SetCompletionReward:H.nullish()}).passthrough(),qD=z.object({CollectionID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),SeasonChainID:z.string().nullish(),Sets:z.array(ED).nullish(),GrandPrize:H.nullish()}).passthrough(),Sd=z.object({BonusRewardSlots:K.nullish(),PityRules:K.nullish()}).passthrough(),BD=z.object({PackTypeID:z.string().nullish(),PriceOptions:ae.nullish(),BonusRewardSlots:z.array(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:Sd.nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectibleCount:z.number().nullish(),MaxOpenCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),GuaranteeMaxRarity:z.boolean().nullish(),RarityWeights:z.record(z.string(),z.number()).nullish(),ColorTier:z.number().nullish()}).passthrough(),LD=z.object({Rarity:z.number().nullish(),CollectionCurrencyGranted:z.number().nullish()}).passthrough(),GD=z.object({CollectionChestID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),CollectionCurrencyCost:z.number().nullish(),MaxOpenCount:z.number().nullish(),MinCollectibleCount:z.number().nullish(),MaxCollectibleCount:z.number().nullish(),GuaranteedMinRarity:z.number().nullish(),BonusRewardSlots:z.array(mi).nullish(),PityRules:z.array(fi).nullish(),Presets:Sd.nullish(),Tier:z.number().nullish()}).passthrough(),FD=z.object({SpecialTradeEventID:z.string().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),AllowedSpecialCollectibleIDs:z.array(z.string()).nullish(),SpecialTradeEventDailyTradeLimit:z.number().nullish()}).passthrough(),VD=z.object({MaxPackOpenCount:z.number().nullish(),MaxChestOpenCount:z.number().nullish()}).passthrough(),gr=z.object({Collections:z.record(z.string(),qD).nullish(),PackTypes:z.record(z.string(),BD).nullish(),CollectionChests:z.array(GD).nullish(),DuplicateConversions:z.array(LD).nullish(),DailyTradeLimit:z.number().nullish(),CollectibleJokerCatalogID:z.string().nullish(),CollectibleJokerItemID:z.string().nullish(),SpecialTradeEvents:z.array(FD).nullish(),RewardPools:Zn.nullish(),Settings:VD.nullish()}).passthrough(),Ne={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 yr=class extends q{constructor(e){super(e,"Collection");}getDefinitions(e){return this.send(Ne.GetDefinitions,e,gr)}getUserState(e){return this.send(Ne.GetUserState,e,ud)}openPack(e){return this.send(Ne.OpenPack,e,pd)}openCollectionChest(e){return this.send(Ne.OpenCollectionChest,e,hd)}useCollectibleJoker(e){return this.send(Ne.UseCollectibleJoker,e,dd)}claimSetReward(e){return this.send(Ne.ClaimSetReward,e,Ia)}claimSetRewardsBatch(e){return this.send(Ne.ClaimSetRewardsBatch,e,md)}claimGrandPrize(e){return this.send(Ne.ClaimGrandPrize,e,fd)}sendTradeOffer(e){return this.send(Ne.SendTradeOffer,e,gd)}cancelTradeOffer(e){return this.send(Ne.CancelTradeOffer,e,yd)}acceptTradeOffer(e){return this.send(Ne.AcceptTradeOffer,e,Rd)}declineTradeOffer(e){return this.send(Ne.DeclineTradeOffer,e,Cd)}getMyTradeOffers(e){return this.send(Ne.GetMyTradeOffers,e,va)}getIncomingTradeOffers(e){return this.send(Ne.GetIncomingTradeOffers,e,va)}};var Rr=class extends q{constructor(e){super(e,"CoopEvent");}getDefinitions(e){return this.send(ht.GetDefinitions,e,Xs)}getActiveEvent(e){return this.send(ht.GetActiveEvent,e,rc)}getUserState(e){return this.send(ht.GetUserState,e,Ys)}getGroupState(e){return this.send(ht.GetGroupState,e,Ao)}joinOrCreateGroup(e){return this.send(ht.JoinOrCreateGroup,e,Ao)}spin(e){return this.send(ht.Spin,e,ac)}claimObjectReward(e){return this.send(ht.ClaimObjectReward,e,wo)}claimGrandPrize(e){return this.send(ht.ClaimGrandPrize,e,wo)}leaveGroup(e){return this.send(ht.LeaveGroup,e,lc)}};var Cr=class extends q{constructor(e){super(e,"DealOffer");}getDefinition(e){return this.send(yt.GetDefinition,e,Cc)}getUserState(e){return this.send(yt.GetUserState,e,Sc)}getActiveDeals(e){return this.send(yt.GetActiveDeals,e,sn)}dismissDeal(e){return this.send(yt.DismissDeal,e,bc)}executeNode(e){return this.send(yt.ExecuteNode,e,xc)}recordShow(e){return this.send(yt.RecordShow,e,Dc)}claimMilestone(e){return this.send(yt.ClaimMilestone,e,Pc)}claimMilestonesBatch(e){return this.send(yt.ClaimMilestonesBatch,e,Ic)}};var jD=z.object({}).passthrough().transform(o=>o),ND=z.object({FeatureKey:z.string().nullish(),IsEnabled:z.boolean().nullish(),Rate:z.number().nullish(),Basis:z.string().nullish(),SourceCurrencyID:z.string().nullish(),TargetCurrencyID:z.string().nullish(),MinSourceAmount:z.number().nullish(),MaxRewardPerOperation:z.number().nullish(),Limits:ye.nullish()}).passthrough(),Ta=z.object({IsEnabled:z.boolean().nullish(),ActivationReward:H.nullish(),InviteRewards:z.record(z.string(),Be).nullish(),SpendRewards:z.array(ND).nullish()}).passthrough(),xd=z.object({ReferralDefinitions:Ta.nullish()}).passthrough(),bd=z.object({Referral:jD.nullish(),InviteUrl:z.string().nullish()}).passthrough(),Dd=z.object({ReferralCode:z.string().nullish(),ReferrerUserID:z.string().nullish(),IsFirstActivation:z.boolean().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),ka=z.object({RewardID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}).passthrough(),Pd=ft(ka),Jt={GetDefinitions:"GetDefinitions",GetUserState:"GetUserState",ActivateReferralCode:"ActivateReferralCode",ClaimInviteReward:"ClaimInviteReward",ClaimInviteRewardsBatch:"ClaimInviteRewardsBatch"};var Sr=class extends q{constructor(e){super(e,"Referral");}getDefinitions(e){return this.send(Jt.GetDefinitions,e,xd)}getUserState(e){return this.send(Jt.GetUserState,e,bd)}activateReferralCode(e){return this.send(Jt.ActivateReferralCode,e,Dd)}claimInviteReward(e){return this.send(Jt.ClaimInviteReward,e,ka)}claimInviteRewardsBatch(e){return this.send(Jt.ClaimInviteRewardsBatch,e,Pd)}};var xr=class extends q{constructor(e){super(e,"Mailbox");}getDefinitions(e){return this.send(et.GetDefinitions,e,Ac)}getMessages(e){return this.send(et.GetMessages,e,wc)}getUnreadCount(e){return this.send(et.GetUnreadCount,e,on)}readMessages(e){return this.send(et.ReadMessages,e,Uo)}claimReward(e){return this.send(et.ClaimReward,e,an)}claimRewardsBatch(e){return this.send(et.ClaimRewardsBatch,e,an)}claimAll(e){return this.send(et.ClaimAll,e,an)}deleteMessages(e){return this.send(et.DeleteMessages,e,Uo)}sendGift(e){return this.send(et.SendGift,e,Mc)}sendTransfer(e){return this.send(et.SendTransfer,e,Oc)}getGiftStatus(e){return this.send(et.GetGiftStatus,e,Uc)}};var br=class extends q{constructor(e){super(e,"Social");}getFriendsList(e){return this.send(Re.GetFriendsList,e,Ii)}getIncomingRequests(e){return this.send(Re.GetIncomingRequests,e,Ii)}getOutgoingRequests(e){return this.send(Re.GetOutgoingRequests,e,Ii)}getRecommendedFriends(e){return this.send(Re.GetRecommendedFriends,e,Ii)}sendFriendRequest(e){return this.send(Re.SendFriendRequest,e,vi)}acceptFriendRequest(e){return this.send(Re.AcceptFriendRequest,e,vi)}declineFriendRequest(e){return this.send(Re.DeclineFriendRequest,e,vi)}removeFriend(e){return this.send(Re.RemoveFriend,e,vi)}getInbox(e){return this.send(Re.GetInbox,e,qc)}markInboxSeen(e){return this.send(Re.MarkInboxSeen,e,Ti)}getInboxUnread(e){return this.send(Re.GetInboxUnread,e,Ti)}follow(e){return this.send(Re.Follow,e,qt)}unfollow(e){return this.send(Re.Unfollow,e,qt)}getFollowers(e){return this.send(Re.GetFollowers,e,un)}getFollowing(e){return this.send(Re.GetFollowing,e,un)}block(e){return this.send(Re.Block,e,qt)}unblock(e){return this.send(Re.Unblock,e,qt)}getBlocked(e){return this.send(Re.GetBlocked,e,un)}react(e){return this.send(Re.React,e,qt)}unreact(e){return this.send(Re.Unreact,e,qt)}getMyReactions(e){return this.send(Re.GetMyReactions,e,Lc)}getEntityStates(e){return this.send(Re.GetEntityStates,e,Bc)}addComment(e){return this.send(Re.AddComment,e,cn)}editComment(e){return this.send(Re.EditComment,e,cn)}deleteComment(e){return this.send(Re.DeleteComment,e,Fc)}getComments(e){return this.send(Re.GetComments,e,Gc)}report(e){return this.send(Re.Report,e,Vc)}};var _D={Replace:"Replace",Refresh:"Refresh",KeepBest:"KeepBest",Stack:"Stack"};var Zt=z.object({Target:z.string().nullish(),Operation:z.string().nullish(),Value:z.number().nullish()}).passthrough(),WD=z.object({BoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),PriceOptions:ae.nullish(),Effect:Zt.nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Tags:z.array(z.string()).nullish()}).passthrough(),Dr=z.object({Schedule:me.nullish(),Gate:J.nullish()}).passthrough(),za=z.object({Availability:K.nullish(),Effects:K.nullish()}).passthrough(),KD=z.object({ScheduledBoostID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Effects:z.array(Zt).nullish(),Availability:Dr.nullish(),Presets:za.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),QD=z.object({ChainedBoostID:z.string().nullish(),Order:z.number().nullish(),DurationSec:z.number().nullish(),Effects:z.array(Zt).nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),HD=z.object({ChainID:z.string().nullish(),DisplayName:z.string().nullish(),Description:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Phases:z.array(QD).nullish(),Availability:Dr.nullish(),Presets:za.nullish(),CustomParams:z.record(z.string(),z.string()).nullish()}).passthrough(),$D=z.object({TriggeredBoostID:z.string().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),Tags:z.array(z.string()).nullish(),Sources:z.array(st).nullish(),Effects:z.array(Zt).nullish(),DurationSeconds:z.number().nullish(),Charges:z.number().nullish(),StackingPolicy:z.string().nullish(),MaxActiveInstances:z.number().nullish(),Availability:Dr.nullish(),Presets:za.nullish()}).passthrough(),JD=z.object({MaxAddPercent:z.number().nullish(),MaxMultiply:z.number().nullish(),MaxAddFlat:z.number().nullish()}).passthrough(),ZD=z.object({Effects:z.array(Zt).nullish()}).passthrough(),YD=z.object({Availability:z.record(z.string(),Dr).nullish(),Effects:z.record(z.string(),ZD).nullish()}).passthrough(),XD=z.object({StackingCaps:z.record(z.string(),JD).nullish()}).passthrough(),Pr=z.object({Definitions:z.record(z.string(),WD).nullish(),ScheduledBoosts:z.record(z.string(),KD).nullish(),BoostChains:z.record(z.string(),HD).nullish(),TriggeredBoosts:z.record(z.string(),$D).nullish(),Settings:XD.nullish(),Presets:YD.nullish()}).passthrough(),Id=z.object({InstanceID:z.string(),BoostID:z.string(),ActivatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),RemainingCharges:z.number().nullish(),EffectSnapshot:Zt.nullish(),SourceType:z.string().nullish(),SourceRef:z.string().nullish()}).passthrough();z.object({Date:c.nullish(),DailyCount:z.number().nullish(),LastFiredUtc:c.nullish()}).passthrough();var vd=z.object({ServerTimeUtc:c.nullish(),Active:z.record(z.string(),Id).nullish()}),Td=z.object({ServerTimeUtc:c.nullish(),BoostID:z.string().nullish(),StackingPolicy:z.string().nullish(),ActivatedBoost:Id.nullish(),Resources:M.nullish()}),eP={Scheduled:"Scheduled",Chain:"Chain"},tP=z.object({Kind:z.string().nullish(),SourceID:z.string().nullish(),PhaseID:z.string().nullish(),CycleIndex:z.number().nullish(),PhaseOrder:z.number().nullish(),StartUtc:c.nullish(),EndUtc:c.nullish(),Effects:z.array(Zt).nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish()}).passthrough(),kd=z.object({ServerTimeUtc:c.nullish(),Windows:z.array(tP).nullish()}),Yt={GetDefinitions:"GetDefinitions",GetActive:"GetActive",GetActiveWindows:"GetActiveWindows",Activate:"Activate",CleanupExpired:"CleanupExpired"};var Ir=class extends q{constructor(e){super(e,"TimedBoost");}getDefinitions(e){return this.send(Yt.GetDefinitions,e,Pr)}getActive(e){return this.send(Yt.GetActive,e,vd)}getActiveWindows(e){return this.send(Yt.GetActiveWindows,e,kd)}activate(e){return this.send(Yt.Activate,e,Td)}cleanupExpired(e){return this.send(Yt.CleanupExpired,e,Ue)}};var vr=class extends q{constructor(e){super(e,"UserCustomData");}getUserCustomDataDefinitions(e){return this.send(dt.GetUserCustomDataDefinitions,e,mn)}getMyUserCustomData(e){return this.send(dt.GetMyUserCustomData,e,Wc)}getPublicUserCustomDataOf(e){return this.send(dt.GetPublicUserCustomDataOf,e,Go)}setPrivateData(e){return this.send(dt.SetPrivateData,e,Fo)}setPublicData(e){return this.send(dt.SetPublicData,e,Fo)}deleteKey(e){return this.send(dt.DeleteKey,e,Ue)}batchSet(e){return this.send(dt.BatchSet,e,Kc)}batchDelete(e){return this.send(dt.BatchDelete,e,Qc)}batchGetPublicUserCustomDataOf(e){return this.send(dt.BatchGetPublicUserCustomDataOf,e,Hc)}};var iP={Static:"Static",Runtime:"Runtime"},sP={Public:"Public",Private:"Private"},nP=z.enum(["Client","Server","System"]).catch("Client"),rP=z.enum(["String","Int","Bool","Json"]).catch("String"),oP=z.object({Value:z.string().nullish(),UpdatedAt:c.nullish(),Version:z.number().nullish(),LastWriter:nP.nullish(),ExpiresAt:c.nullish()}).passthrough(),zd=z.record(z.string(),oP),Aa=z.object({StaticVersion:z.number().nullish(),RuntimeVersion:z.number().nullish(),Static:zd.nullish(),Runtime:zd.nullish(),NotModified:z.boolean().nullish()}),aP=z.object({KeyID:z.string(),Scope:z.enum(["Static","Runtime"]).catch("Static").nullish(),Bucket:z.enum(["Public","Private"]).catch("Public").nullish(),ValueType:rP.nullish(),MaxValueLengthBytes:z.number().nullish(),TtlSeconds:z.number().nullish(),DefaultValue:z.string().nullish(),Description:z.string().nullish()}).passthrough(),Tr=z.object({Keys:z.record(z.string(),aP).nullish(),DefaultMaxValueLengthBytes:z.number().nullish(),DefaultTtlSeconds:z.number().nullish(),MaxKeysPerBucket:z.number().nullish(),MaxTotalSizeBytes:z.number().nullish(),RejectUnregisteredKeys:z.boolean().nullish()}).passthrough(),Oi={GetTitleCustomDataDefinitions:"GetTitleCustomDataDefinitions",GetPublicTitleData:"GetPublicTitleData",GetPublicTitleDataKeys:"GetPublicTitleDataKeys"};var kr=class extends q{constructor(e){super(e,"TitleCustomData");}getTitleCustomDataDefinitions(e){return this.send(Oi.GetTitleCustomDataDefinitions,e,Tr)}getPublicTitleData(e){return this.send(Oi.GetPublicTitleData,e,Aa)}getPublicTitleDataKeys(e){return this.send(Oi.GetPublicTitleDataKeys,e,Aa)}};var lP={Fast:"Fast",Sequential:"Sequential"},uP={Instant:"Instant",Timed:"Timed"};var cP={Hit:"Hit",Blocked:"Blocked"},pP=z.object({SlotIndex:z.number(),Level:z.number().nullish(),IsDamaged:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish()}).passthrough(),hP=z.object({Symbol:z.union([z.string(),z.number()]).nullish(),OnOpenBonus:H.nullish(),BonusTag:z.string().nullish()}).passthrough();z.object({ElapsedSeconds:z.number().nullish(),Reward:H.nullish()}).passthrough();var dP=z.object({RequiredValue:z.number().nullish(),Reward:H.nullish()}).passthrough(),mP=z.object({Reward:H.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough();z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(dP).nullish(),Rate:mP.nullish()}).passthrough();z.object({PlayedCount:z.number().nullish(),RewardsClaimedCount:z.number().nullish(),InstantClaimsCount:z.number().nullish(),EarlyClaimsCount:z.number().nullish(),LateClaimsCount:z.number().nullish(),AdViewsTotal:z.number().nullish(),StatRewardClaimsCount:z.number().nullish(),StatReportsClampedCount:z.number().nullish(),StatReportsUnknownMetricCount:z.number().nullish()}).passthrough();var Ad=z.object({}).passthrough().transform(o=>o),wd=z.object({Min:z.number().nullish(),Max:z.number().nullish()}).passthrough(),_e=z.object({Operation:M.nullish(),ScaleWithRollMultiplier:z.boolean().nullish()}).passthrough(),fP=z.object({Count:z.number().nullish(),Sides:z.number().nullish()}).passthrough(),gP=z.object({ShieldChance:z.number().nullish(),DamagedBuildingChance:z.number().nullish(),RankMultiplierMin:z.number().nullish(),RankMultiplierMax:z.number().nullish(),RankOffsetMin:z.number().nullish(),RankOffsetMax:z.number().nullish(),StageLevelSpread:z.number().nullish()}).passthrough(),yP=z.object({CostMatrixTemplatesByID:z.record(z.string(),z.array(z.array(z.number()))).nullish(),PerBoardGrowth:z.number().nullish(),VisualTemplateCycle:z.array(z.string()).nullish(),EconomyScaledResources:le.nullish(),ScaleRaidStealWithEconomy:z.boolean().nullish(),ScaleAttackRewardWithEconomy:z.boolean().nullish(),AttackValueFromCostMatrix:z.boolean().nullish(),AttackBlockedRewardFactor:z.number().nullish(),ScaleVictimLossWithEconomy:z.boolean().nullish(),ScaleVictimLossWithTier:z.boolean().nullish(),SynthesizedBuildingSlots:z.number().nullish(),SynthesizedBuildingMaxLevel:z.number().nullish(),DifficultyGrowthPerBoard:z.number().nullish()}).passthrough(),RP=z.object({CostMatrix:z.array(z.array(z.number())).nullish(),PerBoardGrowth:z.number().nullish(),EconomyScale:z.number().nullish(),ScaledResources:le.nullish()}).passthrough(),Md=z.object({SlotIndex:z.number().nullish(),Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),MaxLevel:z.number().nullish(),MaxLevelReward:H.nullish()}).passthrough(),CP=z.object({Index:z.number().nullish(),Type:z.string().nullish(),CustomTypeID:z.string().nullish(),RandomActionAttackWeight:z.number().nullish(),RandomActionRaidWeight:z.number().nullish(),ChanceTableID:z.string().nullish(),SpecialModeID:z.string().nullish(),Params:z.record(z.string(),z.string()).nullish()}).passthrough(),SP=z.object({Tiles:z.record(z.string(),CP).nullish()}).passthrough(),xP=z.object({Weight:z.number().nullish(),Bonus:_e.nullish(),Tag:z.string().nullish()}).passthrough(),bP=z.object({Weight:z.number().nullish(),Tag:z.string().nullish(),MinBonusCells:z.number().nullish(),MaxBonusCells:z.number().nullish(),BonusPool:z.array(xP).nullish(),GuaranteedBonus:_e.nullish(),IsJackpot:z.boolean().nullish(),JackpotFinalMultiplier:z.number().nullish(),JackpotSymbolDistribution:z.record(z.string(),z.number()).nullish()}).passthrough(),DP=z.object({Variants:z.array(bP).nullish()}).passthrough(),PP=z.object({Weight:z.number().nullish(),OutcomeID:z.string().nullish(),Reward:_e.nullish(),ForceAction:z.string().nullish(),SpecialModeID:z.string().nullish()}).passthrough(),IP=z.object({Outcomes:z.array(PP).nullish()}).passthrough(),Od=z.object({PerAdMultiplierRange:wd.nullish(),MaxAdViews:z.number().nullish(),AdCreditCost:z.number().nullish(),FormulaKind:z.string().nullish(),ApplyMultiplierOnEarlyClaim:z.boolean().nullish()}).passthrough(),vP=z.object({ElapsedSeconds:z.number().nullish(),Reward:_e.nullish()}).passthrough(),TP=z.object({Tiers:z.array(vP).nullish(),TierMode:z.string().nullish(),BelowFirstTierReward:_e.nullish()}).passthrough(),kP=z.object({RequiredValue:z.number().nullish(),Reward:_e.nullish()}).passthrough(),zP=z.object({Reward:_e.nullish(),MetricPerReward:z.number().nullish(),MaxRewardUnits:z.number().nullish()}).passthrough(),AP=z.object({MetricID:z.string().nullish(),MaxValuePerClaim:z.number().nullish(),TierMode:z.string().nullish(),ApplyClaimMultiplier:z.boolean().nullish(),Tiers:z.array(kP).nullish(),Rate:zP.nullish()}).passthrough(),Ud=z.object({MetricsByID:z.record(z.string(),AP).nullish()}).passthrough(),wP=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:_e.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:ae.nullish(),Multipliers:Od.nullish(),Gradation:TP.nullish(),RunStats:Ud.nullish()}).passthrough(),MP=z.object({Choices:z.array(wP).nullish(),OfferExpireSeconds:z.number().nullish(),ClaimExpireSeconds:z.number().nullish()}).passthrough(),OP=z.object({Chance:z.number().nullish(),RequiredOutcome:z.string().nullish(),Reward:_e.nullish(),Tag:z.string().nullish()}).passthrough(),UP=z.object({OnPassStart:_e.nullish(),OnTileLanding:z.record(z.string(),_e).nullish(),OnAttack:z.record(z.string(),_e).nullish(),OnRaid:z.record(z.string(),_e).nullish(),OnBuild:_e.nullish(),OnStageComplete:_e.nullish(),OnAttackBonusDrops:z.array(OP).nullish(),ChanceTablesByID:z.record(z.string(),IP).nullish(),SpecialModesByID:z.record(z.string(),MP).nullish()}).passthrough(),Ed=z.object({BaseAttackReward:H.nullish(),BaseRaidReward:H.nullish(),MaxRollMultiplier:z.number().nullish(),MaxShields:z.number().nullish(),Buildings:z.array(Md).nullish(),HeistGridBonusConfig:DP.nullish(),StageOperations:UP.nullish(),TileLandingMultiplier:wd.nullish(),EconomyOverride:RP.nullish()}).passthrough(),EP=z.object({Name:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),BoardTemplateID:z.string().nullish(),Buildings:z.array(Md).nullish(),StageTemplateID:z.string().nullish(),CostMatrixTemplateID:z.string().nullish(),UnitValue:z.number().nullish(),Override:Ed.nullish()}).passthrough(),qP=z.object({AttackCooldownSeconds:z.number().nullish(),RaidCooldownSeconds:z.number().nullish(),MaxRecentTargets:z.number().nullish(),LiveOpponentActiveDays:z.number().nullish(),LiveOpponentPoolSize:z.number().nullish(),LiveOpponentPoolCacheSeconds:z.number().nullish(),MaxLiveCandidateReads:z.number().nullish(),VictimImmunitySeconds:z.number().nullish()}).passthrough(),BP=z.object({Enabled:z.boolean().nullish(),IntervalSeconds:z.number().nullish(),MaxPerCatchUp:z.number().nullish(),Chance:z.number().nullish(),AttackWeight:z.number().nullish(),RaidWeight:z.number().nullish(),MinBoardStageLevel:z.number().nullish(),RaidLossMultiplier:z.number().nullish()}).passthrough(),zr=z.object({RollCurrencyID:z.string().nullish(),ShieldCurrencyID:z.string().nullish(),RaidMode:z.string().nullish(),AllowedRollMultipliers:z.array(z.number()).nullish(),BoardTemplatesByID:z.record(z.string(),SP).nullish(),StageTemplatesByID:z.record(z.string(),Ed).nullish(),StagesByLevel:z.record(z.string(),EP).nullish(),SoftCurrencyID:z.string().nullish(),ProceduralEconomy:yP.nullish(),Dice:fP.nullish(),Bots:gP.nullish(),Targeting:qP.nullish(),BotRaids:BP.nullish()}).passthrough(),LP=z.object({IsActive:z.boolean().nullish(),DisplayName:z.string().nullish(),AssetPaths:z.record(z.string(),z.string()).nullish(),AnchorUtc:c.nullish(),RoundDurationSec:z.number().nullish(),PauseBetweenRoundsSec:z.number().nullish(),MaxRounds:z.number().nullish(),PartnerCount:z.number().nullish(),MatchmakingTimeoutMinutes:z.number().nullish(),MemberGracePeriodMinutes:z.number().nullish(),ContributionMin:z.number().nullish(),ContributionMax:z.number().nullish(),ScaleContributionWithRollMultiplier:z.boolean().nullish(),MaxProgress:z.number().nullish(),Milestones:z.record(z.string(),Be).nullish(),GrandPrize:H.nullish()}).passthrough(),Ar=z.object({Board:zr.nullish(),CommunityChest:LP.nullish()}).passthrough(),qd=z.object({AttackerGainByOutcome:z.record(z.string(),le).nullish()}).passthrough(),GP=z.object({TargetUserID:z.string().nullish(),IsBot:z.boolean().nullish(),PublicData:Oe.nullish(),TargetBuildingStates:z.array(pP).nullish(),TargetHasShield:z.boolean().nullish(),TargetStageLevel:z.number().nullish(),RaidRewardPreview:qd.nullish()}).passthrough(),FP=z.object({ChoiceID:z.string().nullish(),Mode:z.string().nullish(),Reward:_e.nullish(),DurationSeconds:z.number().nullish(),PriceOptions:ae.nullish(),Multipliers:Od.nullish(),RunStats:Ud.nullish()}).passthrough(),VP=z.object({ModeID:z.string().nullish(),Choices:z.array(FP).nullish()}).passthrough(),jP=z.object({GroupID:z.string().nullish(),Delta:_.nullish(),NewProgress:_.nullish(),MaxProgress:_.nullish(),UnlockedMilestoneIDs:z.array(z.string()).nullish(),Completed:z.boolean().nullish()}).passthrough(),Bd=z.object({UsedMultiplier:z.number().nullish(),Steps:z.number().nullish(),DiceValues:z.array(z.number()).nullish(),OldPosition:z.number().nullish(),NewPosition:z.number(),CyclesCompletedDelta:_.nullish(),LandedTileType:z.string().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),ActionRequired:z.string().nullish(),ActionData:GP.nullish(),SpecialModeOffer:VP.nullish(),CommunityChestContribution:jP.nullish()}).passthrough(),Ld=z.object({Outcome:z.string().nullish(),IsBotTarget:z.boolean().nullish(),BuildingIndexHit:z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:bt.nullish()}).passthrough(),wa=z.object({Status:z.string().nullish(),Outcome:z.string().nullish(),FoundSymbol:z.union([z.string(),z.number()]).nullish(),FoundBonus:H.nullish(),OpenedIndex:z.number().nullish(),AttemptsLeft:z.number().nullish(),RaidLayout:z.array(hP).nullish(),HeistVariantTag:z.string().nullish(),IsJackpot:z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DualResult:bt.nullish(),RaidRewardPreview:qd.nullish()}).passthrough(),Gd=z.object({BuiltIndex:z.number(),NewLevel:z.number().nullish(),StageComplete:z.boolean().nullish(),MaxLevelRewardClaimed:z.boolean().nullish(),Operation:M.nullish(),Inventory:Q.nullish()}).passthrough(),Fd=z.object({Mode:z.union([z.string(),z.number()]).nullish(),Operation:M.nullish(),Inventory:Q.nullish(),DurationSeconds:z.number().nullish(),StartedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish()}).passthrough(),Vd=z.object({AdViewsUsed:z.number().nullish(),RolledMultiplier:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),RemainingAdViews:z.number().nullish()}).passthrough(),NP=z.object({MetricID:z.string().nullish(),ReachedTierIndex:z.number().nullish(),RequiredValue:z.number().nullish(),RewardUnits:z.number().nullish()}).passthrough(),jd=z.object({FinalMultiplier:z.number().nullish(),AdViewsUsed:z.number().nullish(),AccumulatedMultiplier:z.number().nullish(),IsEarlyClaim:z.boolean().nullish(),ReachedTierIndex:z.number().nullish(),Operation:M.nullish(),Inventory:Q.nullish(),AcceptedRunStats:z.record(z.string(),z.number()).nullish(),RunStatAwards:z.array(NP).nullish(),RunStatsClamped:z.boolean().nullish(),RunStatGrant:H.nullish()}).passthrough(),_P={Forming:"Forming",Active:"Active",Completed:"Completed",Failed:"Failed",Expired:"Expired"},Nd=z.enum(["Forming","Active","Completed","Failed","Expired"]).catch("Forming"),WP={Active:"Active",Left:"Left",Replaced:"Replaced"},KP=z.enum(["Active","Left","Replaced"]).catch("Active"),QP=z.object({CurrentProgress:_.nullish(),MaxProgress:_.nullish()}).passthrough(),HP=z.object({UserID:z.string().nullish(),PublicData:Oe.nullish(),IsBot:z.boolean().nullish(),ContributionPoints:_.nullish(),MilestoneClaims:z.record(z.string(),nl).nullish(),GrandPrizeClaimed:z.boolean().nullish(),MemberStatus:KP.nullish(),JoinedAtUtc:c.nullish(),LeftAtUtc:c.nullish()}).passthrough(),_d=z.object({GroupID:z.string().nullish(),TitleID:z.string().nullish(),RoundIndex:z.number().nullish(),Members:z.array(HP).nullish(),SharedProgress:QP.nullish(),Status:Nd.nullish(),CreatedAtUtc:c.nullish(),ExpiresAtUtc:c.nullish(),Version:z.number().nullish()}).passthrough(),$P=z.object({GroupID:z.string().nullish(),RoundIndex:z.number().nullish(),FinalStatus:Nd.nullish(),GrandPrizeReceived:z.boolean().nullish(),FinishedAtUtc:c.nullish()}).passthrough(),JP=z.object({ActiveGroupID:z.string().nullish(),ActiveRoundIndex:z.number().nullish(),History:z.array($P).nullish()}).passthrough(),Wd=z.object({ServerTimeUtc:c.nullish(),UserState:JP.nullish(),ActiveGroup:_d.nullish(),SecondsRemaining:_.nullish()}),Kd=z.object({ServerTimeUtc:c.nullish(),Group:_d.nullish(),SecondsRemaining:_.nullish()}),Ma=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),RewardType:z.string().nullish(),MilestoneID:z.string().nullish(),Resources:M.nullish(),Inventory:Q.nullish()}),Qd=z.object({ServerTimeUtc:c.nullish(),GroupID:z.string().nullish(),Success:z.boolean().nullish()}),qe={GetGameLoops:"GetGameLoops",GetBoardDefinition:"GetBoardDefinition",GetBoardDefinitionForLevel:"GetBoardDefinitionForLevel",GetUserBoardState:"GetUserBoardState",BoardLoopRoll:"BoardLoopRoll",BoardLoopAttack:"BoardLoopAttack",BoardLoopRaid:"BoardLoopRaid",BoardLoopRaidFast:"BoardLoopRaidFast",BoardLoopBuild:"BoardLoopBuild",BoardSpecialChoose:"BoardSpecialChoose",BoardSpecialApplyMultiplier:"BoardSpecialApplyMultiplier",BoardSpecialClaim:"BoardSpecialClaim",GetCommunityChestState:"GetCommunityChestState",JoinOrCreateCommunityChest:"JoinOrCreateCommunityChest",ClaimCommunityChestMilestone:"ClaimCommunityChestMilestone",ClaimCommunityChestGrandPrize:"ClaimCommunityChestGrandPrize",LeaveCommunityChest:"LeaveCommunityChest"};var ZP={Mesh:"Mesh",Host:"Host"},Oa=z.enum(["Mesh","Host"]).catch("Mesh"),YP={ServerRelay:"ServerRelay",P2P:"P2P"},Ua=z.enum(["ServerRelay","P2P"]).catch("ServerRelay"),XP={Public:"Public",Private:"Private"},eI=z.enum(["Public","Private"]).catch("Public"),tI={Signal:"Signal",Chat:"Chat",PlayerJoined:"PlayerJoined",PlayerLeft:"PlayerLeft",HostChanged:"HostChanged",RoomClosed:"RoomClosed",MemberState:"MemberState"},iI=z.enum(["Signal","Chat","PlayerJoined","PlayerLeft","HostChanged","RoomClosed","MemberState"]).catch("Signal"),Hd=z.object({Urls:z.string().nullish(),Username:z.string().nullish(),Credential:z.string().nullish()}).passthrough(),sI=z.object({Enabled:z.boolean().nullish()}).passthrough(),$d=z.object({SystemState:sI.nullish(),DefaultTopology:Oa.nullish(),AllowCreatorTopologyOverride:z.boolean().nullish(),DefaultChatMode:Ua.nullish(),AllowCreatorChatOverride:z.boolean().nullish(),MaxPlayersPerRoom:z.number().nullish(),RoomTtlSeconds:z.number().nullish(),MaxRoomLifetimeSeconds:z.number().nullish(),HeartbeatIntervalMs:z.number().nullish(),MemberTimeoutMs:z.number().nullish(),MaxSignalPayloadBytes:z.number().nullish(),MaxChatTextLength:z.number().nullish(),RoomLogCap:z.number().nullish(),IceServers:z.array(Hd).nullish()}).passthrough(),nI=z.object({UserID:z.string().nullish(),Username:z.string().nullish(),AvatarUrl:z.string().nullish(),Level:z.number().nullish(),Power:z.number().nullish(),Ready:z.boolean().nullish(),State:z.record(z.string(),z.string()).nullish(),JoinedAt:z.number().nullish(),IsHost:z.boolean().nullish(),LastSeenMs:z.number().nullish()}).passthrough(),rI=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),Topology:Oa.nullish(),ChatMode:Ua.nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),MemberCount:z.number().nullish(),CreatedAt:z.number().nullish()}).passthrough(),oI=z.object({Seq:z.number().nullish(),Type:iI.nullish(),FromUserID:z.string().nullish(),ToUserID:z.string().nullish(),Kind:z.string().nullish(),Payload:z.string().nullish(),Ts:z.number().nullish()}).passthrough(),Ui=z.object({RoomID:z.string().nullish(),Name:z.string().nullish(),HostUserID:z.string().nullish(),OwnerUserID:z.string().nullish(),Topology:Oa.nullish(),ChatMode:Ua.nullish(),Visibility:eI.nullish(),Status:z.string().nullish(),MaxPlayers:z.number().nullish(),Mode:z.string().nullish(),Members:z.array(nI).nullish(),IceServers:z.array(Hd).nullish(),Seq:z.number().nullish(),BannedUserIDs:z.array(z.string()).nullish()}).passthrough(),Jd=z.object({Removed:z.boolean().nullish(),Banned:z.boolean().nullish()}).passthrough(),Zd=z.object({WasBanned:z.boolean().nullish()}).passthrough(),Ea=z.object({Closed:z.boolean().nullish(),NewHostUserID:z.string().nullish()}).passthrough(),Yd=z.object({Rooms:z.array(rI).nullish(),Page:z.number().nullish(),PageSize:z.number().nullish(),HasMore:z.boolean().nullish()}).passthrough(),Xd=z.object({Envelopes:z.array(oI).nullish(),MaxSeq:z.number().nullish()}).passthrough(),wr=z.object({Seq:z.number().nullish()}).passthrough(),He={CreateRoom:"CreateRoom",JoinRoom:"JoinRoom",LeaveRoom:"LeaveRoom",ListRooms:"ListRooms",GetRoom:"GetRoom",CloseRoom:"CloseRoom",Poll:"Poll",SendSignal:"SendSignal",SendChat:"SendChat",SetMemberState:"SetMemberState",ClaimHost:"ClaimHost",KickMember:"KickMember",UnbanMember:"UnbanMember"};var qa=z.object({TitleCustomData:Tr.nullish(),Character:Ws.nullish(),Item:_n.nullish(),Currency:xn.nullish(),Store:ds.nullish(),Lootbox:Sa.nullish(),Quest:Ni.nullish(),TimedEvent:As.nullish(),Leaderboard:Ls.nullish(),Season:Vs.nullish(),Reward:ba.nullish(),Collection:gr.nullish(),Craft:Pa.nullish(),DealOffer:Mo.nullish(),Premium:ya.nullish(),TimedBoost:Pr.nullish(),CoopEvent:Xs.nullish(),GameLoop:Ar.nullish(),Match:Zo.nullish(),Experiment:mh.nullish(),Blockchain:_o.nullish(),Marketplace:ia.nullish(),Multiplayer:$d.nullish(),UserCustomData:mn.nullish(),Referral:Ta.nullish(),Localization:Ph.nullish(),Analytics:sh.nullish(),Social:jc.nullish(),PlatformBridge:Nc.nullish()}).passthrough();var Xt={GetTitlePublicConfiguration:"GetTitlePublicConfiguration",GetTitlePublicConfigurationExcept:"GetTitlePublicConfigurationExcept",GetCurrencyDefinitions:"GetCurrencyDefinitions",GetItemDefinitions:"GetItemDefinitions",GetServerTime:"GetServerTime"};var Mr=class extends q{constructor(e){super(e,"Title");}getTitlePublicConfiguration(e){return this.send(Xt.GetTitlePublicConfiguration,e,qa)}getTitlePublicConfigurationExcept(e){return this.send(Xt.GetTitlePublicConfigurationExcept,e,qa)}getCurrencyDefinitions(e){return this.send(Xt.GetCurrencyDefinitions,e,xn)}getItemDefinitions(e){return this.send(Xt.GetItemDefinitions,e,_n)}getServerTime(e){return this.send(Xt.GetServerTime,e,Ue)}};var Or=class extends q{constructor(e){super(e,"GameLoop");}getGameLoops(e){return this.send(qe.GetGameLoops,e,Ar)}getBoardDefinition(e,t=false){return this.send(qe.GetBoardDefinition,e,zr,{silent:t})}getBoardDefinitionForLevel(e,t=false){return this.send(qe.GetBoardDefinitionForLevel,e,zr,{silent:t})}getUserBoardState(e){return this.send(qe.GetUserBoardState,e,Ad)}boardLoopRoll(e){return this.send(qe.BoardLoopRoll,e,Bd)}boardLoopAttack(e){return this.send(qe.BoardLoopAttack,e,Ld)}boardLoopRaid(e){return this.send(qe.BoardLoopRaid,e,wa)}boardLoopRaidFast(e){return this.send(qe.BoardLoopRaidFast,e,wa)}boardLoopBuild(e){return this.send(qe.BoardLoopBuild,e,Gd)}boardSpecialChoose(e){return this.send(qe.BoardSpecialChoose,e,Fd)}boardSpecialApplyMultiplier(e){return this.send(qe.BoardSpecialApplyMultiplier,e,Vd)}boardSpecialClaim(e){return this.send(qe.BoardSpecialClaim,e,jd)}getCommunityChestState(e){return this.send(qe.GetCommunityChestState,e,Wd)}joinOrCreateCommunityChest(e){return this.send(qe.JoinOrCreateCommunityChest,e,Kd)}claimCommunityChestMilestone(e){return this.send(qe.ClaimCommunityChestMilestone,e,Ma)}claimCommunityChestGrandPrize(e){return this.send(qe.ClaimCommunityChestGrandPrize,e,Ma)}leaveCommunityChest(e){return this.send(qe.LeaveCommunityChest,e,Qd)}};var lI={Live:"Live",Latest:"Latest",Specific:"Specific"},uI={Debug:"Debug",Info:"Info",Warning:"Warning",Error:"Error"},cI=z.enum(["Debug","Info","Warning","Error"]).catch("Debug"),pI={None:"None",Disabled:"Disabled",NoActiveRevision:"NoActiveRevision",RevisionNotFound:"RevisionNotFound",InvalidFieldName:"InvalidFieldName",RateLimited:"RateLimited",HandlerNotFound:"HandlerNotFound",HandlerDisabled:"HandlerDisabled",Timeout:"Timeout",StatementCountExceeded:"StatementCountExceeded",StackOverflow:"StackOverflow",ApiCallLimitExceeded:"ApiCallLimitExceeded",JavaScriptException:"JavaScriptException",ExecutionError:"ExecutionError"},hI=z.enum(["None","Disabled","NoActiveRevision","RevisionNotFound","InvalidFieldName","RateLimited","HandlerNotFound","HandlerDisabled","Timeout","StatementCountExceeded","StackOverflow","ApiCallLimitExceeded","JavaScriptException","ExecutionError"]).catch("None"),dI=z.object({Level:cI,Message:z.string().nullish(),Data:Ut.nullish()}),mI=z.object({Error:hI,Message:z.string().nullish(),StackTrace:z.string().nullish()}),em=z.object({FunctionName:z.string().nullish(),Revision:z.number().nullish(),FunctionResult:Ut.nullish(),FunctionResultTooLarge:z.boolean().nullish(),Logs:z.array(dI).nullish(),LogsTooLarge:z.boolean().nullish(),ExecutionTimeSeconds:z.number().nullish(),APIRequestsIssued:z.number().nullish(),Error:mI.nullish()}),Ba={Execute:"Execute"};var Ur=class extends q{constructor(e){super(e,"CloudCode");}execute(e){return this.send(Ba.Execute,e,em)}};var Er=class extends q{constructor(e){super(e,"Blockchain");}getDefinitions(e){return this.send(Qe.GetDefinitions,e,pp)}getUserState(e){return this.send(Qe.GetUserState,e,hp)}depositToken(e){return this.send(Qe.DepositToken,e,dp)}depositNFT(e){return this.send(Qe.DepositNFT,e,mp)}requestTokenWithdrawal(e){return this.send(Qe.RequestTokenWithdrawal,e,fp)}requestNFTWithdrawal(e){return this.send(Qe.RequestNFTWithdrawal,e,gp)}getTransactionHistory(e){return this.send(Qe.GetTransactionHistory,e,yp)}retryWithdrawal(e){return this.send(Qe.RetryWithdrawal,e,Rp)}confirmWithdrawal(e){return this.send(Qe.ConfirmWithdrawal,e,Cp)}donateToDeveloper(e){return this.send(Qe.DonateToDeveloper,e,Ho)}donateToUsersPool(e){return this.send(Qe.DonateToUsersPool,e,Ho)}getPlayAccess(e){return this.send(Qe.GetPlayAccess,e,up)}confirmPlayAccess(e){return this.send(Qe.ConfirmPlayAccess,e,Bt)}};var qr=class extends q{constructor(e){super(e,"Marketplace");}getDefinitions(e){return this.send(Te.GetDefinitions,e,Op)}getGroupedOffers(e){return this.send(Te.GetGroupedOffers,e,Up)}getOffersByItem(e){return this.send(Te.GetOffersByItem,e,sa)}getOffer(e){return this.send(Te.GetOffer,e,Ep)}getBuyOrders(e){return this.send(Te.GetBuyOrders,e,sa)}getMyState(e){return this.send(Te.GetMyState,e,kn)}getHistory(e){return this.send(Te.GetHistory,e,Bp)}createListing(e){return this.send(Te.CreateListing,e,Ai)}cancelListing(e){return this.send(Te.CancelListing,e,at)}buy(e){return this.send(Te.Buy,e,at)}marketBuy(e){return this.send(Te.MarketBuy,e,at)}marketSell(e){return this.send(Te.MarketSell,e,at)}createAuction(e){return this.send(Te.CreateAuction,e,Ai)}placeBid(e){return this.send(Te.PlaceBid,e,qp)}claimAuction(e){return this.send(Te.ClaimAuction,e,at)}createBuyOrder(e){return this.send(Te.CreateBuyOrder,e,Ai)}cancelBuyOrder(e){return this.send(Te.CancelBuyOrder,e,at)}fillBuyOrder(e){return this.send(Te.FillBuyOrder,e,at)}createDirectTrade(e){return this.send(Te.CreateDirectTrade,e,Ai)}respondDirectTrade(e){return this.send(Te.RespondDirectTrade,e,at)}cancelDirectTrade(e){return this.send(Te.CancelDirectTrade,e,at)}claimBack(e){return this.send(Te.ClaimBack,e,at)}};var Br=class extends q{constructor(e){super(e,"Multiplayer");}createRoom(e){return this.send(He.CreateRoom,e,Ui)}joinRoom(e){return this.send(He.JoinRoom,e,Ui)}leaveRoom(e,t=false){return this.send(He.LeaveRoom,e,Ea,{keepalive:t})}listRooms(e){return this.send(He.ListRooms,e,Yd)}getRoom(e){return this.send(He.GetRoom,e,Ui)}closeRoom(e){return this.send(He.CloseRoom,e,Ea)}poll(e){return this.send(He.Poll,e,Xd)}sendSignal(e){return this.send(He.SendSignal,e,wr,{throttleKey:`Multiplayer:SendSignal:${e.TargetUserID??""}`,silent:true})}claimHost(e){return this.send(He.ClaimHost,e,Ui)}kickMember(e){return this.send(He.KickMember,e,Jd)}unbanMember(e){return this.send(He.UnbanMember,e,Zd)}sendChat(e){return this.send(He.SendChat,e,wr)}setMemberState(e){return this.send(He.SetMemberState,e,wr)}};var fI={Free:"Free",Price:"Price",Holding:"Holding"},La=z.enum(["Free","Price","Holding"]).catch("Free"),gI={WhileHeld:"WhileHeld",UnlockOnce:"UnlockOnce"},yI=z.enum(["WhileHeld","UnlockOnce"]).catch("WhileHeld"),RI={All:"All",Any:"Any"},CI=z.enum(["All","Any"]).catch("All"),SI={Public:"Public",Unlisted:"Unlisted",Friends:"Friends"},xI=z.enum(["Public","Unlisted","Friends"]).catch("Public"),bI={Uploading:"Uploading",PendingReview:"PendingReview",Published:"Published",Hidden:"Hidden",Removed:"Removed"},DI=z.enum(["Uploading","PendingReview","Published","Hidden","Removed"]).catch("Published"),PI={Purchase:"Purchase",Free:"Free",Holding:"Holding"},im=z.enum(["Purchase","Free","Holding"]).catch("Free"),II={New:"New",Popular:"Popular",MostLiked:"MostLiked"},vI={Creator:"Creator",License:"License",Free:"Free",Holding:"Holding"},TI=z.enum(["Creator","License","Free","Holding"]).catch("License"),kI=z.object({Type:si.nullish(),CurrencyID:z.string().nullish(),CatalogID:z.string().nullish(),ItemID:z.string().nullish(),Amount:z.number().nullish(),MinLevel:z.number().nullish()}).passthrough(),zI=z.object({Requirements:z.array(kI).nullish(),Match:CI.nullish(),Mode:yI.nullish()}).passthrough(),AI=z.object({OptionID:z.string().nullish(),Mode:La.nullish(),Price:le.nullish(),Holding:zI.nullish()}).passthrough(),wI=z.object({AllowedMimeTypes:z.array(z.string()).nullish(),MaxBytes:z.number().nullish(),MaxCount:z.number().nullish(),Required:z.boolean().nullish()}).passthrough(),MI=z.object({DisplayName:z.string().nullish(),Enabled:z.boolean().nullish(),Files:z.record(z.string(),wI).nullish(),ThumbnailRequired:z.boolean().nullish(),AllowedAccessModes:z.array(La).nullish(),PricePolicy:Tn.nullish(),PublishGate:J.nullish(),PublishFeeOptions:ae.nullish(),TagVocabulary:z.array(z.string()).nullish(),MaxPublishedPerPlayer:z.number().nullish(),DailyPublishCap:z.number().nullish()}).passthrough(),OI=z.object({Allowed:z.array(zi).nullish(),MaxRequirements:z.number().nullish()}).passthrough(),UI=z.object({AutoHideReportThreshold:z.number().nullish(),RequireApproval:z.boolean().nullish(),BlockedTerms:z.array(z.string()).nullish()}).passthrough(),EI=z.object({MaxTitleLength:z.number().nullish(),MaxDescriptionLength:z.number().nullish(),MaxTags:z.number().nullish(),MaxTagLength:z.number().nullish(),MaxMetadataKeys:z.number().nullish(),MaxMetadataValueLength:z.number().nullish(),MaxAccessOptions:z.number().nullish(),ThumbnailMaxBytes:z.number().nullish()}).passthrough(),qI=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Schedule:me.nullish(),Gate:J.nullish(),Order:z.number().nullish()}).passthrough(),BI=z.object({Enabled:z.boolean().nullish(),Gate:J.nullish(),Schedule:me.nullish(),ContentTypes:z.record(z.string(),MI).nullish(),PricePolicy:Tn.nullish(),Commission:ta.nullish(),HoldingPolicy:OI.nullish(),Moderation:UI.nullish(),Limits:EI.nullish(),Featured:z.array(qI).nullish()}).passthrough(),LI=z.object({Acquisitions:z.number().nullish(),Downloads:z.number().nullish(),Likes:z.number().nullish(),Favorites:z.number().nullish(),ReportCount:z.number().nullish()}).passthrough(),ei=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),CreatorUserID:z.string().nullish(),IsOfficial:z.boolean().nullish(),CreatorPublicData:Oe.nullish(),Title:z.string().nullish(),Description:z.string().nullish(),Tags:z.array(z.string()).nullish(),Metadata:z.record(z.string(),z.string()).nullish(),ThumbnailUrl:z.string().nullish(),Visibility:xI.nullish(),Access:z.array(AI).nullish(),Status:DI.nullish(),ModerationNote:z.string().nullish(),Stats:LI.nullish(),Revision:z.number().nullish(),FileCount:z.number().nullish(),TotalBytes:z.number().nullish(),CreatedAt:c.nullish(),UpdatedAt:c.nullish(),PublishedAt:c.nullish(),IsMine:z.boolean().nullish(),Owned:z.boolean().nullish(),Liked:z.boolean().nullish(),Favorited:z.boolean().nullish()}).passthrough(),GI=z.object({OptionID:z.string().nullish(),Mode:La.nullish(),Available:z.boolean().nullish()}).passthrough(),sm=z.object({CollectionID:z.string().nullish(),Name:z.string().nullish(),Description:z.string().nullish(),ContentIDs:z.array(z.string()).nullish(),Order:z.number().nullish()}).passthrough(),nm=z.object({Definitions:BI.nullish(),IsOpenNow:z.boolean().nullish(),GatePassed:z.boolean().nullish(),CanPublish:z.record(z.string(),z.boolean()).nullish(),Collections:z.array(sm).nullish()}).passthrough(),Lr=z.object({Items:z.array(ei).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),rm=z.object({Content:ei.nullish(),AccessState:z.array(GI).nullish(),CanDownload:z.boolean().nullish()}).passthrough(),om=z.object({Collection:sm.nullish(),Items:z.array(ei).nullish()}).passthrough(),am=z.object({CreatorUserID:z.string().nullish(),PublicData:Oe.nullish(),PublishedCount:z.number().nullish(),FollowerCount:z.number().nullish(),IsFollowing:z.boolean().nullish(),Items:z.array(ei).nullish()}).passthrough(),tm=z.object({Role:z.string().nullish(),Index:z.number().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish(),ServerCopy:z.boolean().nullish()}).passthrough(),lm=z.object({ContentID:z.string().nullish(),Revision:z.number().nullish(),Uploads:z.array(tm).nullish(),ThumbnailUpload:tm.nullish(),ExpiresAt:c.nullish()}).passthrough(),um=z.object({Content:ei.nullish(),Resources:M.nullish()}).passthrough(),Ga=z.object({Content:ei.nullish()}).passthrough(),cm=z.object({ContentID:z.string().nullish(),OptionID:z.string().nullish(),Source:im.nullish(),AlreadyOwned:z.boolean().nullish(),AccessActive:z.boolean().nullish(),Settlement:bt.nullish(),Resources:M.nullish(),CommissionTaken:le.nullish()}).passthrough(),FI=z.object({Role:z.string().nullish(),Url:z.string().nullish(),ContentType:z.string().nullish(),Size:z.number().nullish()}).passthrough(),pm=z.object({ContentID:z.string().nullish(),ContentType:z.string().nullish(),Revision:z.number().nullish(),AccessVia:TI.nullish(),Files:z.array(FI).nullish(),ThumbnailUrl:z.string().nullish(),ExpiresAt:c.nullish()}).passthrough(),VI=z.object({ContentID:z.string().nullish(),Source:im.nullish(),OptionID:z.string().nullish(),PricePaid:le.nullish(),AcquiredAt:c.nullish(),Content:ei.nullish()}).passthrough(),hm=z.object({Licenses:z.array(VI).nullish(),ContinuationToken:z.string().nullish()}).passthrough(),We={GetDefinitions:"GetDefinitions",Browse:"Browse",GetContent:"GetContent",GetCollection:"GetCollection",GetCreatorProfile:"GetCreatorProfile",BeginUpload:"BeginUpload",Publish:"Publish",UpdateContent:"UpdateContent",Unpublish:"Unpublish",GetMyContent:"GetMyContent",Acquire:"Acquire",GetDownload:"GetDownload",GetMyLicenses:"GetMyLicenses",GetMyFavorites:"GetMyFavorites"};var Gr=class extends q{constructor(e){super(e,"Workshop");}getDefinitions(e){return this.send(We.GetDefinitions,e,nm)}browse(e){return this.send(We.Browse,e,Lr)}getContent(e){return this.send(We.GetContent,e,rm)}getCollection(e){return this.send(We.GetCollection,e,om)}getCreatorProfile(e){return this.send(We.GetCreatorProfile,e,am)}beginUpload(e){return this.send(We.BeginUpload,e,lm)}publish(e){return this.send(We.Publish,e,um)}updateContent(e){return this.send(We.UpdateContent,e,Ga)}unpublish(e){return this.send(We.Unpublish,e,Ga)}getMyContent(e){return this.send(We.GetMyContent,e,Lr)}acquire(e){return this.send(We.Acquire,e,cm)}getDownload(e){return this.send(We.GetDownload,e,pm)}getMyLicenses(e){return this.send(We.GetMyLicenses,e,hm)}getMyFavorites(e){return this.send(We.GetMyFavorites,e,Lr)}};var Fr=class extends q{constructor(e){super(e,"DataCollections");}sendKeyed(e,t,i,s){return this.send(e,t,i,{throttleKey:`${this.endpoint(e,t)}|${s}`})}sendPublic(e,t,i,s){let r=`api/v2/${this.ctx.settings.titleID||"0"}/Public/DataCollections/${e}`;return this.ctx.transport.post(r,t,i,{throttleKey:`${r}|${s}`})}getDefinitions(e){return this.sendKeyed("GetDefinitions",e,Np,"defs")}get(e){return this.sendKeyed("Get",e,ra,`${e.Collection}|${e.ItemID}`)}getMany(e){return this.sendKeyed("GetMany",e,Wp,`${e.Collection}|${(e.ItemIDs??[]).join(",")}`)}query(e){return this.sendKeyed("Query",e,oa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}count(e){return this.sendKeyed("Count",e,Kp,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}create(e){return this.sendKeyed("Create",e,aa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}update(e){return this.sendKeyed("Update",e,aa,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}delete(e){return this.sendKeyed("Delete",e,Qp,e.RelatedEntityID??`${e.Collection}|${e.ItemID}`)}batch(e){return this.sendKeyed("Batch",e,$p,e.RelatedEntityID??"batch")}getCounter(e){return this.sendKeyed("GetCounter",e,Hp,`${e.Collection}|${e.CounterID}|${JSON.stringify(e.Group??null)}`)}getMyRoles(e){return this.sendKeyed("GetMyRoles",e,Jp,"roles")}beginFileUpload(e){return this.sendKeyed("BeginFileUpload",e,_p,`${e.Collection}|${e.Field}|${Date.now()}|${Math.random()}`)}publicGetViews(e){return this.sendPublic("GetViews",e,Zp,`${e.Collection}`)}publicGet(e){return this.sendPublic("Get",e,ra,`${e.Collection}|${e.ItemID}`)}publicQuery(e){return this.sendPublic("Query",e,oa,`${e.Collection}|${JSON.stringify(e.Query??{})}`)}};var Vr=class{settings;emitter;platform;acquisition;playtime;clientPlatform;transport;fetchImpl;data;cache;authStore;api;auth;userService;currency;item;store;purchase;checkout;lootbox;reward;quest;tutorial;communityMarketing;chat;push;localization;timedEvent;leaderboard;season;premium;character;match;craft;ai;collection;coopEvent;dealOffer;referral;mailbox;social;timedBoost;userCustomData;titleCustomData;title;gameLoop;cloudCode;blockchain;marketplace;multiplayer;workshop;dataCollections;analytics;experiments;constructor(e$1){this.settings=_a(e$1),this.emitter=new Ci,this.platform=e$1.platform??new e,this.clientPlatform=e$1.clientPlatform??il(),this.acquisition=new Vt(this.platform),this.acquisition.capture(),this.playtime=new Si(this),this.emitter.on("auth:loggedIn",()=>{this.playtime.start(),this.analytics.start(),this.acquisition.clear();}),this.emitter.on("auth:loggedOut",()=>{this.playtime.stop(),this.analytics.stop();}),this.fetchImpl=e$1.fetch??globalThis.fetch.bind(globalThis),this.transport=new Ji({baseUrl:this.settings.baseUrl,emitter:this.emitter,fetchImpl:e$1.fetch,debugLogging:this.settings.debugLogging,throttleMs:e$1.throttleMs,maxRequestsPerSecond:e$1.maxRequestsPerSecond,clientPlatform:this.clientPlatform}),this.data=new es(this.emitter),this.cache=new is(this.emitter,this.data.config,this.settings.configStorage,this.settings.titleID,e$1.loginViews??"auto"),this.emitter.on("quest:systemProgress",t=>{this.data.user.patchQuestProgressUpdates(t);}),this.emitter.on("tutorial:systemProgress",t=>{this.data.user.patchTutorialProgress(t);}),this.emitter.on("user:stateVersions",({epoch:t,versions:i})=>{this.userService.noteStateVersions(t,i);}),this.authStore=new ss(this.platform.storage,this.settings.titleID),this.api={authentication:new Gn(this),user:new Vn(this),currency:new jn(this),item:new Wn(this),store:new Kn(this),purchase:new Jn(this),lootbox:new Xn(this),reward:new er(this),quest:new or(this),tutorial:new tr(this),communityMarketing:new ir(this),chat:new sr(this),push:new nr(this),localization:new rr(this),timedEvent:new ar(this),leaderboard:new lr(this),season:new ur(this),premium:new cr(this),character:new pr(this),match:new hr(this),craft:new mr(this),ai:new fr(this),collection:new yr(this),coopEvent:new Rr(this),dealOffer:new Cr(this),referral:new Sr(this),mailbox:new xr(this),social:new br(this),timedBoost:new Ir(this),userCustomData:new vr(this),titleCustomData:new kr(this),title:new Mr(this),gameLoop:new Or(this),cloudCode:new Ur(this),blockchain:new Er(this),marketplace:new qr(this),multiplayer:new Br(this),workshop:new Gr(this),dataCollections:new Fr(this),analytics:new Bn(this),experiment:new Ln(this)},this.userService=new ls(this),this.cache.attachState(this.userService),this.auth=new ns(this),this.currency=new cs(this),this.item=new ps(this),this.store=new fs(this),this.purchase=new gs(this),this.checkout=new ys(this),this.lootbox=new Rs(this),this.reward=new Cs(this),this.quest=new zs(this),this.tutorial=new xs(this),this.communityMarketing=new bs(this),this.chat=new Is(this),this.push=new vs(this),this.localization=new ks(this),this.timedEvent=new Ms(this),this.leaderboard=new Gs(this),this.season=new js(this),this.premium=new Ns(this),this.character=new Ks(this),this.match=new Qs(this),this.craft=new Hs(this),this.ai=new Js(this),this.collection=new Zs(this),this.coopEvent=new en(this),this.dealOffer=new nn(this),this.referral=new rn(this),this.mailbox=new ln(this),this.social=new pn(this),this.timedBoost=new hn(this),this.userCustomData=new fn(this),this.titleCustomData=new gn(this),this.title=new yn(this),this.gameLoop=new Rn(this),this.cloudCode=new Cn(this),this.blockchain=new Dn(this),this.marketplace=new zn(this),this.multiplayer=new An(this),this.workshop=new wn(this),this.dataCollections=new On(this),this.analytics=new En(this),this.experiments=new qn(this),this.transport.setSessionRefreshHandler(()=>this.auth.refreshSession());}buildAuthedBaseRequest(){let e=this.auth.context;return {UserID:e?.userID,ClientSessionTicket:e?.clientSessionTicket,BuildKey:this.settings.buildKey,WebAppLink:this.platform.getFullURL(),RelatedEntityID:d()}}authedRequest(){return this.auth.context?this.buildAuthedBaseRequest():null}};var jr=class{ctx;constructor(e){this.ctx=new Vr(e);}get titleID(){return this.ctx.settings.titleID}debugCall(e,t,i={}){let s=this.ctx.buildAuthedBaseRequest(),n=Gt(this.ctx.settings.titleID,e,t,s.UserID??"");return this.ctx.transport.post(n,{...s,...i},z.unknown(),{ticket:s.ClientSessionTicket,autoRetry:false,throttleKey:`debugCall:${e}/${t}:${Date.now()}`})}get auth(){return this.ctx.auth}get user(){return this.ctx.userService}get currency(){return this.ctx.currency}get item(){return this.ctx.item}get store(){return this.ctx.store}get purchase(){return this.ctx.purchase}get checkout(){return this.ctx.checkout}get lootbox(){return this.ctx.lootbox}get reward(){return this.ctx.reward}get quest(){return this.ctx.quest}get tutorial(){return this.ctx.tutorial}get analytics(){return this.ctx.analytics}get experiments(){return this.ctx.experiments}get communityMarketing(){return this.ctx.communityMarketing}get chat(){return this.ctx.chat}get push(){return this.ctx.push}get localization(){return this.ctx.localization}get timedEvent(){return this.ctx.timedEvent}get leaderboard(){return this.ctx.leaderboard}get season(){return this.ctx.season}get premium(){return this.ctx.premium}get character(){return this.ctx.character}get match(){return this.ctx.match}get craft(){return this.ctx.craft}get ai(){return this.ctx.ai}get collection(){return this.ctx.collection}get coopEvent(){return this.ctx.coopEvent}get dealOffer(){return this.ctx.dealOffer}get referral(){return this.ctx.referral}get mailbox(){return this.ctx.mailbox}get social(){return this.ctx.social}get timedBoost(){return this.ctx.timedBoost}get userCustomData(){return this.ctx.userCustomData}get titleCustomData(){return this.ctx.titleCustomData}get title(){return this.ctx.title}get gameLoop(){return this.ctx.gameLoop}get cloudCode(){return this.ctx.cloudCode}get blockchain(){return this.ctx.blockchain}get marketplace(){return this.ctx.marketplace}get multiplayer(){return this.ctx.multiplayer}get workshop(){return this.ctx.workshop}get dataCollections(){return this.ctx.dataCollections}get data(){return this.ctx.data}get cache(){return this.ctx.cache}get platform(){return this.ctx.platform}on(e,t){return this.ctx.emitter.on(e,t)}once(e,t){return this.ctx.emitter.once(e,t)}off(e,t){this.ctx.emitter.off(e,t);}};function NI(o){return new jr(o)}var dm="idos_sso",mm="state",Fa="idos:sso:state",_I="https://idosgames.com/sso/",WI=["https://cloud.idosgames.com","https://idosgames.com","https://www.idosgames.com"],KI=/^https:\/\/[a-z0-9]{8}(-dev)?\.idos\.games$/;function QI(){if(typeof window>"u")return false;let{origin:o}=window.location;return WI.includes(o)||KI.test(o)?true:typeof document<"u"&&document.querySelector('meta[name="idos-game-host"]')!==null}function HI(){if(typeof window>"u")return null;let o=window.location.hash?.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!o)return null;let e=new URLSearchParams(o),t=e.get(dm);if(!t)return null;let i=e.get(mm)??"",s=XI();return tv(e),ev(),s&&i!==s?null:{code:t,state:i}}function $I(o){if(typeof window>"u")return;let e=o.returnTo??JI(),t=ZI();YI(t);let i=new URL(o.ssoUrl??_I);i.searchParams.set("title",o.titleID),i.searchParams.set("return_to",e),i.searchParams.set("state",t),window.location.assign(i.toString());}function JI(){let{origin:o,pathname:e,search:t}=window.location;return `${o}${e}${t}`}function ZI(){let o=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(o);else for(let e=0;e<o.length;e++)o[e]=Math.floor(Math.random()*256);return Array.from(o,e=>e.toString(16).padStart(2,"0")).join("")}function YI(o){try{window.sessionStorage.setItem(Fa,o);}catch{}}function XI(){try{return window.sessionStorage.getItem(Fa)}catch{return null}}function ev(){try{window.sessionStorage.removeItem(Fa);}catch{}}function tv(o){o.delete(dm),o.delete(mm);let e=o.toString(),{pathname:t,search:i}=window.location;window.history.replaceState(null,"",`${t}${i}${e?`#${e}`:""}`);}var iv={EMAIL_SENDER_NOT_CONFIGURED:"Sign-in by e-mail is unavailable in this game right now. Try another way to sign in.",INVALID_VERIFICATION_CODE:"That code is not right. Check the e-mail and try again.",VERIFICATION_CODE_ATTEMPTS_EXCEEDED:"Too many wrong attempts. Ask for a new code.",INCORRECT_EMAIL_OR_PASSWORD:"Wrong e-mail or password.",INCORRECT_EMAIL:"That does not look like an e-mail address.",PASSWORD_LENGTH_INVALID:"The password must be 8 to 100 characters long.",TOO_MANY_FAILED_ATTEMPTS:"Too many attempts. Please try again a little later.",RATE_LIMIT_EXCEEDED:"Too many requests. Please try again in a moment.",APPLE_EMAIL_MISSING:"Apple did not share an e-mail address. Try again and allow it, or use another way to sign in.",INVALID_WALLET_SIGNATURE:"The signature does not match the wallet. Please try again.",WALLET_CHALLENGE_EXPIRED:"The request expired. Please try again.",WALLET_CHANGES_TOO_FREQUENT:"Too many wallets were changed this week. Try again in a few days.",WALLET_UNLINK_COOLDOWN:"This wallet was unlinked from another account less than 7 days ago. Try again after the 7 days.",PLAY_ACCESS_GUEST_DISABLED:"Guest play is off in this game. Sign in to link a crypto wallet.",PLAY_ACCESS_WALLET_LOGIN_ONLY:"This game can only be entered with a crypto wallet or your iDos Games account.",PLAY_ACCESS_WALLET_USED_BY_ANOTHER_ACCOUNT:"This wallet already plays with another account.",PLAY_ACCESS_WALLET_REQUIRED:"Link a crypto wallet to play.",PLAY_ACCESS_WALLET_NETWORK_NOT_GATED:"This wallet's network is not accepted here. Link a wallet of the required network.",PLAY_ACCESS_REQUIRED:"Check your balance to continue.",PLAY_ACCESS_CHECK_FAILED:"Could not check your balance right now. Please try again in a moment."};function sv(o,e="Something went wrong. Please try again."){return o?iv[o]??o:e}function nv(o,e){return !!o?.Claims?.[e]?.ClaimedAt}function rv(o){let e=o?.Claims;return e?Object.keys(e).filter(t=>!!e[t]?.ClaimedAt):[]}function ov(o,e){return o?.Claims?.[e]?.PremiumTiers??[]}function gm(o,e,t,i=1){if(!o)return e;let s=o.Base??e,n=Math.max(0,t-i),r;switch(o.Shape??"Flat"){case "PerStep":r=s+(o.PerStep??0)*n;break;case "PerStepRate":r=s*(1+(o.PerStepRate??0)*n);break;case "Geometric":r=s*Math.pow(1+(o.GrowthRate??0),n);break;case "Table":r=s*fm(o,t,1);break;case "TableAbsolute":r=fm(o,t,s);break;default:r=s;break}return Number.isNaN(r)?s:(o.MinResult!=null&&r<o.MinResult&&(r=o.MinResult),o.MaxResult!=null&&r>o.MaxResult&&(r=o.MaxResult),r)}function av(o,e,t=1){return gm(o,1,e,t)}function lv(o){if(!o)return false;switch(o.Shape??"Flat"){case "PerStep":return (o.PerStep??0)!==0;case "PerStepRate":return (o.PerStepRate??0)!==0;case "Geometric":return (o.GrowthRate??0)!==0;case "Table":case "TableAbsolute":return ym(o.Points).length>0;default:return o.MinResult!=null||o.MaxResult!=null}}function uv(o){if(Number.isNaN(o)||o<=0)return 0;if(!Number.isFinite(o))return Number.MAX_SAFE_INTEGER;let e=Math.round(o);return Math.abs(o-e)<=1e-9*Math.max(1,Math.abs(o))?e:Math.ceil(o)}function ym(o){if(!o)return [];let e=[];for(let t of o)t?.AtStep==null||t.Value==null||e.push({AtStep:t.AtStep,Value:t.Value});return e}function fm(o,e,t){let i=ym(o.Points);if(i.length===0)return t;let s=null,n=null,r=null;for(let p of i)(r===null||p.AtStep>r.AtStep)&&(r=p),p.AtStep<=e&&(s===null||p.AtStep>=s.AtStep)&&(s=p),p.AtStep>e&&(n===null||p.AtStep<n.AtStep)&&(n=p);if(s===null)return t;if(n===null){let p=o.TailGrowthRate??0;return p===0?r.Value:r.Value*Math.pow(1+p,e-r.AtStep)}switch(o.Interpolation??"Step"){case "Linear":{let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+p*(n.Value-s.Value)}case "Geometric":{if(s.Value<=0||n.Value<=0){let d=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value+d*(n.Value-s.Value)}let p=(e-s.AtStep)/(n.AtStep-s.AtStep);return s.Value*Math.pow(n.Value/s.Value,p)}default:return s.Value}}var cv={Banner:"Banner",Interstitial:"Interstitial",RewardedVideo:"RewardedVideo",RewardedInterstitial:"RewardedInterstitial",AppOpen:"AppOpen",Native:"Native"},Va=z.enum(["Banner","Interstitial","RewardedVideo","RewardedInterstitial","AppOpen","Native"]).catch("Banner"),pv={Top:"Top",Bottom:"Bottom",Left:"Left",Right:"Right"},hv=z.enum(["Top","Bottom","Left","Right"]).catch("Top"),dv=z.object({PlacementID:z.string().nullish(),Type:Va.nullish(),Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),CreditsRewarded:z.number().nullish(),AllowedProviderIDs:z.array(z.string()).nullish()}).passthrough(),mv=z.object({DefaultCreditsPerView:z.number().nullish(),MaxCreditsBalance:z.number().nullish(),DailyCreditEarnCap:z.number().nullish(),DailyViewCap:z.number().nullish(),MinSecondsBetweenViews:z.number().nullish()}).passthrough(),fv=z.object({CooldownSeconds:z.number().nullish(),MinSessionTimeBeforeFirstSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),gv=z.object({Enabled:z.boolean().nullish(),Position:hv.nullish(),RefreshIntervalSeconds:z.number().nullish()}).passthrough(),yv=z.object({Enabled:z.boolean().nullish(),CooldownSeconds:z.number().nullish(),DailyImpressionCap:z.number().nullish()}).passthrough(),Rv=z.object({MaxImpressionsPerHour:z.number().nullish(),MaxImpressionsPerDay:z.number().nullish(),MaxImpressionsPerSession:z.number().nullish()}).passthrough(),Cv=z.object({MinPremiumTier:z.number().nullish(),RequiredPremiumID:z.string().nullish(),DisableInterstitials:z.boolean().nullish(),DisableBanners:z.boolean().nullish(),DisableAppOpen:z.boolean().nullish()}).passthrough(),Sv=z.object({RequirePersonalizedAdsConsent:z.boolean().nullish(),RequireTrackingConsent:z.boolean().nullish(),CurrentPolicyVersion:z.string().nullish(),RegulatedRegions:z.array(z.string()).nullish()}).passthrough(),xv=z.object({RequireServerSideVerification:z.boolean().nullish(),PendingRequestTtlSeconds:z.number().nullish(),MaxPendingRequestsPerUser:z.number().nullish()}).passthrough(),bv=z.object({AndroidUnitID:z.string().nullish(),IosUnitID:z.string().nullish(),WebUnitID:z.string().nullish(),Type:Va.nullish()}).passthrough(),Dv={AppLovinMax:"AppLovinMax",LevelPlay:"LevelPlay"},Pv=z.enum(["AppLovinMax","LevelPlay"]).catch("AppLovinMax"),Iv=z.object({ProviderID:z.string().nullish(),Kind:Pv.nullish(),Enabled:z.boolean().nullish(),Priority:z.number().nullish(),AndroidAppID:z.string().nullish(),IosAppID:z.string().nullish(),WebAppID:z.string().nullish(),Units:z.record(z.string(),bv).nullish()}).passthrough();z.object({Enabled:z.boolean().nullish(),Placements:z.record(z.string(),dv).nullish(),Providers:z.record(z.string(),Iv).nullish(),RewardedVideo:mv.nullish(),Interstitial:fv.nullish(),Banner:gv.nullish(),AppOpen:yv.nullish(),FrequencyCapping:Rv.nullish(),PremiumAdReductions:z.array(Cv).nullish(),Consent:Sv.nullish(),Verification:xv.nullish()}).passthrough();var vv=z.object({RewardedVideoCredit:z.number().nullish(),TotalEarned:z.number().nullish(),TotalSpent:z.number().nullish()}).passthrough(),Tv=z.object({PlacementID:z.string().nullish(),LastShownAt:c.nullish(),LastCompletedAt:c.nullish(),TotalImpressions:z.number().nullish(),TotalCompletions:z.number().nullish(),ConsecutiveFailures:z.number().nullish()}).passthrough(),kv=z.object({Date:c.nullish(),ImpressionsByPlacement:z.record(z.string(),z.number()).nullish(),CompletionsByPlacement:z.record(z.string(),z.number()).nullish(),TotalImpressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish(),AppOpenImpressions:z.number().nullish(),CreditsEarnedToday:z.number().nullish()}).passthrough(),zv=z.object({SessionID:z.string().nullish(),SessionStartAt:c.nullish(),Impressions:z.number().nullish(),InterstitialImpressions:z.number().nullish(),RewardedCompletions:z.number().nullish()}).passthrough(),Av=z.object({PersonalizedAdsConsent:z.boolean().nullish(),TrackingConsent:z.boolean().nullish(),PolicyVersion:z.string().nullish(),Region:z.string().nullish(),ConsentGivenAt:c.nullish(),ConsentRevokedAt:c.nullish()}).passthrough(),wv=z.object({RequestID:z.string().nullish(),PlacementID:z.string().nullish(),ProviderID:z.string().nullish(),Type:Va.nullish(),IssuedAt:c.nullish(),ExpiresAt:c.nullish(),CreditsToAward:z.number().nullish()}).passthrough(),Mv=z.object({InvalidSsvCount:z.number().nullish(),OrphanCompletions:z.number().nullish(),FastCompletions:z.number().nullish(),LastFlaggedAt:c.nullish()}).passthrough();z.object({Credits:vv.nullish(),Placements:z.record(z.string(),Tv).nullish(),Daily:kv.nullish(),Session:zv.nullish(),LastImpressionAt:c.nullish(),LastInterstitialAt:c.nullish(),LastRewardedAt:c.nullish(),LastAppOpenAt:c.nullish(),TotalImpressions:z.number().nullish(),TotalRewardedCompletions:z.number().nullish(),AdsDisabledUntil:c.nullish(),Consent:Av.nullish(),PendingRequests:z.record(z.string(),wv).nullish(),FraudFlags:Mv.nullish(),UpdatedAt:c.nullish()}).passthrough();
|
|
2
|
+
export{Ge as AIAction,Hy as AIErrorCode,Wt as AIGenerationStatus,Et as AIModality,Vt as AcquisitionCapture,Dv as AdProviderKind,cv as AdType,pa as AnalyticsAction,qx as AnalyticsDropReason,ca as AnalyticsEventNaming,Ct as AnalyticsLimits,cP as AttackOutcome,Ae as AuthType,Ee as AuthenticationAction,Lt as AutomaticEvent,pv as BannerPosition,Qe as BlockchainAction,WC as BlockchainNetworkType,np as BlockchainOperationCategory,eS as BlockchainTransactionStatus,$C as BlockchainTransactionType,kS as BodyPart,eP as BoostWindowKind,je as CharacterAction,Ke as ChatAction,Lg as ChatAuthorType,qg as ChatBlockedTermAction,wg as ChatChannelType,Ug as ChatDirectAudience,Mg as ChatPartitioning,Fg as ChatReportReason,mt as ClientPlatform,Ba as CloudCodeAction,pI as CloudCodeErrorCode,uI as CloudCodeLogLevel,lI as CloudCodeRevisionSelection,Ne as CollectionAction,HS as CommissionSink,WP as CommunityChestMemberStatus,_P as CommunityChestStatus,lD as CommunityCreatorStatus,$t as CommunityMarketingAction,cD as CommunityMetricKind,oD as CommunityParticipationMode,uD as CommunityPayoutCurrencyKind,UC as ConversionRateMode,ht as CoopEventAction,oR as CoopGroupStatus,aR as CoopMemberStatus,dr as CraftAction,DD as CraftInputSelectionMode,xD as CraftOutputLevelMode,ID as CraftOutputLevelOverflow,SD as CraftType,Sn as CurrencyAction,OC as CurrencyStatus,ut as CurrencyType,Zm as CurveInterpolation,$m as CurveShape,vt as CustomDataBucket,PC as CustomDataValueType,SC as CustomDataWriter,Na as DEFAULT_BASE_URL,mx as DataAccessMode,cx as DataCollectionKind,bx as DataCollectionSchemaMode,wx as DataCollectionsAction,Rx as DataCounterKind,hx as DataFieldType,dx as DataFieldVisibility,Sx as DataOwnerDeletedPolicy,gx as DataRefKind,IR as DealComparisonOperator,yR as DealNodeRuntimeStatus,PR as DealNodeType,yt as DealOfferAction,gR as DealOfferActivationStatus,Un as EVENT_NAME_PATTERN,tI as EnvelopeType,Lm as EventTokenType,ma as ExperimentAction,Qx as ExperimentGoalKind,gC as FRIENDS_FROM_PLATFORM,ob as FodderSelectionMode,nb as FodderValuationMode,sC as FriendActionStatus,nC as FriendSource,qe as GameLoopAction,jr as IDosGamesClient,Cb as IapProductType,Ob as IapPurchaseStatus,Bm as IapStoreValues,Nn as ItemAction,JC as KycStatus,YC as KycTier,Ve as LeaderboardAction,Fn as LocalizationAction,Xx as LocalizationMissingKeyMode,Yn as LootboxAction,HR as MAILBOX_COUNTER_CAP,et as MailboxAction,jR as MailboxCategory,QR as MailboxErrors,NR as MailboxLetterSource,WR as MailboxRewardModule,vn as MarketGoodsType,QS as MarketOfferStatus,KS as MarketOfferType,Te as MarketplaceAction,Rt as MatchAction,zS as MatchStatus,He as MultiplayerAction,YP as MultiplayerChatMode,ZP as MultiplayerTopology,zg as OFFER_NOT_IN_ROTATION,RC as PlatformFriendsMode,yC as PlatformProfileMode,uS as PlayAccessMode,Jx as PlayerExperimentStatus,Si as PlaytimeTracker,Qt as PremiumAction,Ht as PurchaseAction,pi as PushAction,Pt as PushPermissionState,ey as PushTopic,Yg as PushTransport,pt as QuestAction,uf as QuestObjectiveSource,pf as QuestPrerequisiteMode,of as QuestStatus,lP as RaidMode,Jt as ReferralAction,Bi as ResourceEntryType,kt as RewardAction,XP as RoomVisibility,Qy as SKIN_ALREADY_OWNED,vo as SKIN_SLOT,Gm as ScheduleMode,Ot as SeasonAction,Re as SocialAction,uC as SocialContentStatus,oC as SocialEntityType,cC as SocialInboxVerb,aC as SocialReactionKind,lC as SocialReportReason,uP as SpecialChoiceMode,_t as StoreAction,hg as StoreRotationMode,yb as StoreType,Yt as TimedBoostAction,_D as TimedBoostStackingPolicy,ot as TimedEventAction,Xt as TitleAction,Oi as TitleCustomDataAction,sP as TitleDataBucket,iP as TitleDataScope,wD as TradeOfferStatus,tS as TransactionDirection,nt as TutorialAction,vf as TutorialBoardAction,Df as TutorialFlowStatus,Nm as TutorialGateMode,xf as TutorialRestartPolicy,If as TutorialScriptModule,Cf as TutorialStepCompletionMode,Ci as TypedEmitter,lt as UserAction,dt as UserCustomDataAction,oS as WalletGateBalanceSource,QC as WalletLinkType,fI as WorkshopAccessMode,vI as WorkshopAccessVia,We as WorkshopAction,bI as WorkshopContentStatus,RI as WorkshopHoldingMatch,gI as WorkshopHoldingMode,PI as WorkshopLicenseSource,II as WorkshopSort,SI as WorkshopVisibility,sv as authErrorText,$I as beginSsoRedirect,rv as claimedMilestoneIDs,NI as createIDosGamesClient,oi as cryptoShortfallFromError,av as curveMultiplier,$f as defineView,rh as describeUserAgent,gm as evaluateCurve,ov as grantedPremiumTiers,Pi as isAIGenerationTerminal,lv as isCurveConfigured,nv as isMilestoneClaimed,qy as isReservedSlot,QI as isSsoAvailable,bn as normalizeBlockchainCategory,$y as parseAIErrorCode,HI as readSsoCodeFromUrl,uv as roundAmount,Ox as where,ug as zPaymentProof,Ll as zPriceOption,ae as zPriceOptions};
|