@kitten-science/kitten-scientists 2.0.0-beta.11-dev.20250606105247 → 2.0.0-beta.11-dev.20250607203148
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/lib/WorkshopManager.d.ts +0 -1
- package/lib/WorkshopManager.d.ts.map +1 -1
- package/lib/WorkshopManager.js +0 -20
- package/lib/WorkshopManager.js.map +1 -1
- package/lib/settings/UpgradeSettings.d.ts +2 -1
- package/lib/settings/UpgradeSettings.d.ts.map +1 -1
- package/lib/settings/UpgradeSettings.js +7 -1
- package/lib/settings/UpgradeSettings.js.map +1 -1
- package/output/kitten-scientists-0.0.0-ci.min.user.js +7 -7
- package/output/kitten-scientists-0.0.0-ci.min.user.js.map +1 -1
- package/output/kitten-scientists-0.0.0-ci.user.js +9 -21
- package/output/kitten-scientists-0.0.0-ci.user.js.map +1 -1
- package/output/kitten-scientists-loader-0.0.0-ci.min.user.js +1 -1
- package/output/kitten-scientists-loader-0.0.0-ci.min.user.js.map +1 -1
- package/output/kitten-scientists-loader-0.0.0-ci.user.js +1 -1
- package/output/kitten-scientists.inject.js +7 -20
- package/output/kitten-scientists.inject.js.map +1 -1
- package/output/kitten-scientists.min.inject.js +1 -1
- package/output/kitten-scientists.min.inject.js.map +1 -1
- package/package.json +3 -3
|
@@ -14,7 +14,7 @@ If you submit an invalid value, it will be treated as if you hit Cancel.`,"ui.tr
|
|
|
14
14
|
内容将被自动检测并进行相应处理。`,"state.loaded.game":"已加载保存“{0}”。","state.loaded.state":"已加载状态“{0}”。","state.loadPrompt":"在此处粘贴您的 (未压缩的) 保存或设置:","state.local":"本地状态","state.localGames":"小猫游戏保存","state.localStates":"小猫科学家设置","state.new":"新的","state.noConfirm":"不要求确认","state.store":"储存","state.stored.game":"保存储存。","state.stored.state":"状态储存。","state.storeFactory":"根据出厂默认设置创建新状态。","state.storeGame":"从当前游戏中创建一个新的保存。","state.storeGame.prompt":"为此次保存提供标签:","state.storeState":"根据当前设置创建一个新状态。","state.storeState.prompt":"为该状态提供标签:","state.title":"状态管理器","state.unlabeledGame":"未标记的保存","state.unlabeledState":"未标记状态","state.update.game":"将当前游戏保存到此位置。","state.update.state":"将当前设置保存到此槽中。","state.updated.game":"保存'{0}'已更新。","state.updated.state":"状态“{0}”已更新。","status.auto.disable":"禁用自动化 {0}","status.auto.enable":"启用自动化 {0}","status.ks.disable":"太敬业了,该歇了","status.ks.enable":"神说,要有猫猫珂学家!","status.ks.init":"小猫珂学家已初始化。","status.ks.upgrade":"小猫珂学家 (当前版本:{1}) {0} 可在这里获取:{2} 。","status.reset.check.disable":"在重启时间线前不检查 {0}","status.reset.check.enable":"在重启时间线前检查 {0}","status.resource.disable":"禁用 {0} 资源管理","status.resource.enable":"启用 {0} 资源管理","status.sub.disable":"禁用 {0}","status.sub.enable":"启用 {0}","summary.accelerate":"加速时间 {0} 次","summary.adore":"通过赞美群星积累了 {0} 顿悟","summary.building":"建造了 {0} 个 {1}","summary.craft":"制作了 {0} 个 {1}","summary.day":"天","summary.days":"天","summary.distribute":"帮助 {0} 只猫猫找到工作","summary.embassy":"设立了 {0} 个大使馆","summary.feed":"向上古神献祭 {0} 只死灵兽","summary.festival":"举办了 {0} 次节日","summary.fix.cry":"修复了 {0} 个冷冻仓","summary.head":"过去 {0} 的总结","summary.hunt":"派出了 {0} 批可爱的小猫猎人","summary.praise":"通过赞美太阳积累了 {0} 虔诚","summary.promote":"提拔领袖 {0} 次","summary.refine":"已精炼 {0} {1}","summary.separator":" ","summary.show":"总结","summary.stars":"观测了 {0} 颗流星","summary.sun":"在 {1} 方面顿悟 {0} 次","summary.tech":"掌握了 {0}","summary.time.activeHeatTransferStart":"主动散热 {0} 次","summary.time.getTemporalFlux":"烧水晶获取时间通量 {0} 次","summary.time.reset.content":"获得 {0} 业.<br>获得 {1} 领导力","summary.time.reset.title":"过去 {0} 个时间线的总结","summary.time.skip":"跳过 {0} 年","summary.trade":"与 {1} 贸易了 {0} 次","summary.transcend":"超越了 {0} 次","summary.upgrade":"发明了 {0}","summary.year":"年","summary.years":"年","time.heatTransfer.cycle.disable":"停止在 {0} 主动散热","time.heatTransfer.cycle.enable":"启用在 {0} 主动散热","time.skip.cycle.disable":"停止在 {0} 跳转时间并禁止跳过该周期","time.skip.cycle.enable":"启用在 {0} 跳转时间并允许跳过该周期","time.skip.season.disable":"停止在 {0} 跳转时间","time.skip.season.enable":"启用在 {0} 跳转时间","trade.limited":"与 {0} 的交易限制为比产量更优时才会触发","trade.season.disable":"停止在 {1} 与 {0} 的交易","trade.season.enable":"启用在 {1} 与 {0} 的交易","trade.seasons":"季节","trade.unlimited":"取消与 {0} 交易的限制","ui.additional":"附加选项","ui.build":"营火","ui.close":"关闭","ui.craft":"工艺","ui.craft.resources":"资源","ui.cycles":"周期","ui.disable.all":"全部禁用","ui.distribute":"猫力资源","ui.enable.all":"全部启用","ui.engine":"启用小猫珂学家","ui.faith":"宗教","ui.filter":"日志过滤","ui.infinity":"∞","ui.internals":"小喵设置","ui.internals.interval":"运行间隔(ms): {0}","ui.internals.interval.prompt":"输入新的毫秒数作为 0 到无穷大之间的绝对值。","ui.internals.interval.promptExplainer":"游戏支持的所有符号均可接受。如果您将限制设置为 0,Kitten Scientists 将自动禁用。如果您提交了无效值,则将被视为您点击了“取消”。","ui.internals.interval.promptTitle":"小猫科学家执行间隔 (当前:{0})","ui.itemsHide":"隐藏选项","ui.itemsShow":"显示选项","ui.ksColumn":"显示在第四栏","ui.language":"语言","ui.limit":"限制","ui.limited.off":"无限","ui.limited.on":"环保模式","ui.max":"最大值:{0}","ui.max.build.prompt":"{0} 的限制 (当前:{1})","ui.max.build.promptExplainer":"游戏支持的所有符号均可接受。如果您提交空值或负值,限制将设置为无穷大。如果您将限制设置为 0,此选项将自动禁用。如果您提交无效值,将被视为您点击了“取消”。","ui.max.build.title":"构建 {0} {1}","ui.max.build.titleInfinite":"永不停止建设{0}","ui.max.build.titleZero":"不要构建{0}","ui.max.craft.prompt":"输入要制作的 {0} 数量的新限制,以 0 到无穷大之间的绝对值表示。","ui.max.craft.promptExplainer":"游戏支持的所有符号均可接受。如果您提交空值或负值,限制将设置为无穷大。如果您将限制设置为 0,此选项将自动禁用。如果您提交无效值,将被视为您点击了“取消”。","ui.max.craft.promptTitle":"制作限制 {0} (当前:{1})","ui.max.craft.title":"制造 {0} {1}","ui.max.craft.titleInfinite":"永不停止创造{0}","ui.max.craft.titleZero":"不要制造 {0}","ui.max.distribute.prompt":"输入要分配的新小猫数量 {0},作为 0 到无穷大之间的绝对值。","ui.max.distribute.promptExplainer":"游戏支持的所有符号均可接受。如果您提交空值或负值,限制将设置为无穷大。如果您将限制设置为 0,此选项将自动禁用。如果您提交无效值,将被视为您点击了“取消”。","ui.max.distribute.promptTitle":"将最大小猫数量指定为 {0} (当前:{1})","ui.max.distribute.title":"将 {0} 只小猫指定为 {1}","ui.max.distribute.titleInfinite":"分配尽可能多的小猫作为{0}","ui.max.distribute.titleZero":"不将任何小猫指定为{0}","ui.max.embassy.title":"为{1}建造{0}大使馆","ui.max.embassy.titleInfinite":"永不停止为{0}修建大使馆","ui.max.embassy.titleZero":"不要为{0}建造大使馆","ui.max.prompt.absolute":"输入新的限制作为 0 到无穷大之间的绝对值。","ui.max.prompt.float":"输入新的限制作为 0.0 和无穷大之间的绝对值。","ui.max.set":"设置 {0} 的最大值","ui.max.timeSkip.prompt":"输入新的年数作为 0 至无穷大之间的绝对值。","ui.max.timeSkip.promptExplainer":"游戏支持的所有符号均可接受。如果您提交空值或负值,限制将设置为无穷大。如果您将限制设置为 0,此选项将自动禁用。如果您提交无效值,将被视为您点击了“取消”。","ui.max.timeSkip.promptTitle":"最多跳过年份 (当前:{0})","ui.max.timeSkip.title":"一次跳过 {0} 年","ui.max.timeSkip.titleInfinite":"跳过尽可能多的年份","ui.max.timeSkip.titleZero":"不要跳过时间","ui.maximum":"上限","ui.min":"最小值 {0}","ui.options":"选项","ui.reset":"恢复至默认","ui.resources":"资源控制","ui.space":"太空","ui.time":"时间","ui.timeCtrl":"时间操纵","ui.trade":"贸易","ui.trigger":"触发值:{0}","ui.trigger.accelerateTime.prompt":"输入启用 Tempus Fugit 的新时间通量存储级别,以 0.0 至 100.0 之间的百分比表示。","ui.trigger.accelerateTime.promptExplainer":"如果您提交一个空值或者一个无效值,则被视为您点击了取消。","ui.trigger.accelerateTime.promptTitle":"加速时间的触发值 (当前:{0})","ui.trigger.activeHeatTransfer.prompt":"输入新的启用热传递的时间热存储量,以 0.0 到 100.0 之间的百分比表示。","ui.trigger.activeHeatTransfer.promptExplainer":"如果您提交一个空值或者一个无效值,则被视为您点击了取消。","ui.trigger.activeHeatTransfer.promptTitle":"热传递触发值 (当前:{0})","ui.trigger.build.blocked":`∞
|
|
15
15
|
🛈 {0} 部分未设置触发值。此构建不会被触发!`,"ui.trigger.build.inherited":"继承自部分","ui.trigger.build.prompt":"{0} 的触发值 (当前:{1})","ui.trigger.build.promptExplainer":"如果您提交了空值或负值,则将使用部分触发值。如果您提交了无效值,则将被视为您点击了“取消”。","ui.trigger.crypto.prompt":"输入交易黑币的新文物存储级别,以 0.0 到 Infinity 之间的绝对值表示。","ui.trigger.crypto.promptExplainer":"如果您提交一个空值或者一个无效值,则被视为您点击了取消。","ui.trigger.crypto.promptTitle":"触发黑币交易 (当前:{0})","ui.trigger.embassies.prompt":"以 0.0 至 100.0 之间的百分比输入建造大使馆的新文化存储级别。","ui.trigger.embassies.promptExplainer":"如果您提交一个空值或者一个无效值,则被视为您点击了取消。","ui.trigger.embassies.promptTitle":"建立大使馆的触发值 (当前:{0})","ui.trigger.hunt.prompt":"狩猎触发值 (当前:{0})","ui.trigger.hunt.promptExplainer":"如果您提交了负值,则搜索将被禁用。如果您提交了空值或无效值,则将被视为您点击了“取消”。","ui.trigger.inactive":"不活跃","ui.trigger.promoteKittens.prompt":"输入新的可用于升级小猫的黄金库存量,以 0.0 到 100.0 之间的百分比表示。","ui.trigger.promoteKittens.promptExplainer":"如果您提交一个空值或者一个无效值,则被视为您点击了取消。","ui.trigger.promoteKittens.promptTitle":"小猫促销触发值 (当前:{0})","ui.trigger.prompt.absolute":"输入新的触发值作为 0 到无穷大之间的绝对值。","ui.trigger.prompt.float":"输入新的触发值作为 0.0 到无穷大之间的绝对值。","ui.trigger.prompt.percentage":"以 0.0 至 100.0 之间的百分比形式输入新的触发值。","ui.trigger.reset.promptExplainer":"如果您提交了负值,则该项目将被禁用。如果您提交了空值或无效值,则将被视为您点击了“取消”。","ui.trigger.section":"部分默认触发值:{0}","ui.trigger.section.blocked":`∞
|
|
16
16
|
🛈 The {0} section has no trigger set. This automation will not be triggered!`,"ui.trigger.section.inactive":"∞ (nothing is triggered automatically)","ui.trigger.section.inherited":"继承自部分","ui.trigger.section.prompt":"{0} 部分的触发值 (当前:{1})","ui.trigger.section.promptExplainer":`If you submit an empty value, or a negative value, the section trigger will be set to infinity (∞). Individual automations in this section need to have their own trigger set to be activated.
|
|
17
|
-
If you submit an invalid value, it will be treated as if you hit Cancel.`,"ui.trigger.setinteger":"输入 {0} 的新触发值。范围应在 0 到任意数字之间。-1表示无穷大。","ui.trigger.setinteger.promptExplainer":"如果您提交一个空值或者一个无效值,则被视为您点击了取消。","ui.trigger.setpercentage":"输入新的 {0} 触发值,取值范围为 0 到 100 的小数。","ui.trigger.setpercentage.promptExplainer":"如果您提交一个空值或者一个无效值,则被视为您点击了取消。","ui.trigger.timeSkip.prompt":"输入跳过时间所需的时间水晶的新数量,以 1 到无穷大之间的绝对值表示。","ui.trigger.timeSkip.promptExplainer":"如果您提交了负值,时间跳过将被禁用。如果您提交了空值或无效值,它将被视为您点击了“取消”。","ui.trigger.timeSkip.promptTitle":"时间跳跃触发值 (当前:{0})","ui.upgrade":"升级","ui.upgrade.buildings":"升级建筑","ui.upgrade.missions":"探索星球","ui.upgrade.policies":"政策","ui.upgrade.races":"探险队出发!","ui.upgrade.techs":"科技","ui.upgrade.upgrades":"升级","ui.upgrades":"升级",update:"更新","upgrade.building.amphitheatre":"剧场 升级为 广播塔!","upgrade.building.aqueduct":"水渠 升级为 水电站!","upgrade.building.library":"图书馆 升级为 数据中心!","upgrade.building.pasture":"牧场 升级为 太阳能发电站!","upgrade.building.warehouse":"已将仓库升级为太空港!","upgrade.policy":"小猫通过了 {0} 法案","upgrade.race":"小猫遇到了 {0}","upgrade.space":"小猫执行了 {0}","upgrade.space.mission":"小猫执行了 {0} 的任务","upgrade.tech":"小猫掌握了 {0}","upgrade.upgrade":"小猫发明了 {0}"};class qe extends Ne{#e;#t;get building(){return this.#e}get variant(){return this.#t}constructor(e,t,i=!1){super(i),this.#e=e,this.#t=t}}class pt extends F{buildings;bestUnicornBuilding;bestUnicornBuildingCurrent;sacrificeAlicorns;sacrificeUnicorns;refineTears;refineTimeCrystals;autoPraise;adore;transcend;constructor(e=!1,t=-1,i=new y,s=new ee(!1,-1),a=new ee(!1,-1),n=new ee(!1,-1),r=new ee(!1,-1),o=new F(!1,1),l=new F(!1,1),h=new y){super(e,t),this.buildings=this.initBuildings(),this.bestUnicornBuilding=i,this.sacrificeAlicorns=s,this.sacrificeUnicorns=a,this.refineTears=n,this.refineTimeCrystals=r,this.autoPraise=o,this.adore=l,this.transcend=h,this.bestUnicornBuildingCurrent=null}initBuildings(){const e={};for(const t of ci)e[t]=new qe(t,U.OrderOfTheSun);for(const t of hi)e[t]=new qe(t,U.Cryptotheology);for(const t of ui)e[t]=new qe(t,U.Ziggurat);return e.unicornPasture=new qe("unicornPasture",U.UnicornPasture),e}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.max=i?.max??t.max,t.trigger=i?.trigger??t.trigger}),this.bestUnicornBuilding.load(e.bestUnicornBuilding),this.sacrificeAlicorns.load(e.sacrificeAlicorns),this.sacrificeUnicorns.load(e.sacrificeUnicorns),this.refineTears.load(e.refineTears),this.refineTimeCrystals.load(e.refineTimeCrystals),this.autoPraise.load(e.autoPraise),this.adore.load(e.adore),this.transcend.load(e.transcend),this.bestUnicornBuildingCurrent=e.bestUnicornBuildingCurrent??this.bestUnicornBuildingCurrent)}}class Es{_host;settings;_bulkManager;_bonfireManager;_workshopManager;constructor(e,t,i,s=new pt){this._host=e,this.settings=s,this._workshopManager=i,this._bulkManager=new Ue(this._host,this._workshopManager),this._bonfireManager=t}async tick(e){this.settings.enabled&&(this._autoBuild(e),this.settings.sacrificeUnicorns.enabled&&await this._autoSacrificeUnicorns(),this.settings.sacrificeAlicorns.enabled&&await this._autoSacrificeAlicorns(e),this.settings.refineTears.enabled&&this._autoTears(e),this.settings.refineTimeCrystals.enabled&&await this._autoTCs(e),this._autoTAP())}_autoBuild(e){if(this.settings.bestUnicornBuilding.enabled)this._buildBestUnicornBuilding(),this._buildNonUnicornBuildings(e);else{const t=Object.fromEntries(Object.entries(this.settings.buildings).filter(([,a])=>a.variant!==U.UnicornPasture)),i=Z(this.settings.buildings.unicornPasture.max),s=this._host.game.bld.getBuildingExt("unicornPasture").meta;this.settings.buildings.unicornPasture.enabled&&s.val<i&&this._bonfireManager.autoBuild(e,{unicornPasture:new mt("unicornPasture",this.settings.buildings.unicornPasture.enabled,this.settings.buildings.unicornPasture.trigger,this.settings.buildings.unicornPasture.max)}),this._buildReligionBuildings(e,t)}}_buildBestUnicornBuilding(){const e=this.getBestUnicornBuilding();if(this.settings.bestUnicornBuildingCurrent!==e&&(this.settings.bestUnicornBuildingCurrent=e,this._host.refreshEntireUserInterface()),this.settings.bestUnicornBuildingCurrent===null)return;const t=this.settings.trigger;if(this.settings.bestUnicornBuildingCurrent==="unicornPasture")this._bonfireManager.build(this.settings.bestUnicornBuildingCurrent,0,1);else{const i=this._getBuild(this.settings.bestUnicornBuildingCurrent,U.Ziggurat);let s=0;const a=f(i.model.prices).find(l=>l.name==="tears");g(a)||(s=a.val);const n=this._workshopManager.getValue("tears")-this._workshopManager.getStock("tears");if(n<s){const l=Math.floor((this._workshopManager.getValue("unicorns")-this._workshopManager.getStock("unicorns"))/2500),h=Math.ceil((s-n)/this._host.game.bld.getBuildingExt("ziggurat").meta.on),u=this._host.game.bld.get("ziggurat").on;if(h<l&&0<u){const d=new classes.ui.religion.TransformBtnController(this._host.game,{applyAtGain:v=>{this._host.game.stats.getStat("unicornsSacrificed").val+=v},gainedResource:"tears",gainMultiplier:()=>this._host.game.bld.get("ziggurat").on,logfilterID:"unicornSacrifice",logTextID:"religion.sacrificeBtn.sacrifice.msg",overcapMsgID:"religion.sacrificeBtn.sacrifice.msg.overcap"}),m=d.fetchModel({controller:d,description:"",name:"",prices:[{name:"unicorns",val:2500}]});d._transform(m,h)}else return}const r={[this.settings.bestUnicornBuildingCurrent]:this.settings.buildings[this.settings.bestUnicornBuildingCurrent]},o=this._bulkManager.bulk(r,this.getBuildMetaData(r),t,"Religion");0<o.length&&0<o[0].count&&this.build(this.settings.bestUnicornBuildingCurrent,U.Ziggurat,1)}}_buildNonUnicornBuildings(e){const t=[...De],i=Object.fromEntries(Object.entries(this.settings.buildings).filter(([,s])=>!t.includes(s.building)));this._buildReligionBuildings(e,i)}_buildReligionBuildings(e,t){const i=this.getBuildMetaData(t),s=this.settings.trigger,a=this._bulkManager.bulk(t,i,s,"Religion");for(const n of a)0<n.count&&(this.build(n.id,f(n.variant),n.count),e.requestGameUiRefresh=!0)}getBestUnicornBuilding(){const e=this._bonfireManager.getBuild("unicornPasture"),t=[...De].filter(j=>j!=="unicornPasture"),i=this._host.game.getEffect("unicornsPerTickBase")*this._host.game.getTicksPerSecondUI(),s=this._host.game.getEffect("unicornsGlobalRatio")+1,a=this._host.game.getEffect("unicornsRatioReligion")+1,n=this._host.game.prestige.getParagonProductionRatio()+1,r=this._host.game.religion.getSolarRevolutionRatio()+1,o=this._host.game.calendar.cycle,l=this._host.game.calendar.cycles[o];let h=1;l.festivalEffects.unicorns!==void 0&&this._host.game.prestige.getPerk("numeromancy").researched&&this._host.game.calendar.festivalDays&&(h=l.festivalEffects.unicorns);const u=i*s*a*n*r*h,d=Math.max(this._host.game.bld.getBuildingExt("ziggurat").meta.on,1),m=500*(1+this._host.game.getEffect("unicornsRatioReligion")*.1);let v=1;this._host.game.prestige.getPerk("unicornmancy").researched&&(v*=1.1);const p=this._host.game.getEffect("riftChance")*v/(1e4*2)*m;let w=Number.POSITIVE_INFINITY,C=null;const oe=f(this._host.game.bld.getBuildingExt("unicornPasture").meta.effects?.unicornsPerTickBase)*this._host.game.getTicksPerSecondUI()*s*a*n*r*h,K=f(e.model?.prices)[0].val/oe;K<w&&(w=K,C="unicornPasture");for(const j of t){const he=this._getBuild(j,U.Ziggurat);if(!he.model.metadata.unlocked)continue;let Y=0;for(const ve of f(he.model.prices))ve.name==="unicorns"&&(Y+=ve.val),ve.name==="tears"&&(Y+=ve.val*2500/d);const be=f(this._host.game.religion.getZU(j));let Ce=a,st=this._host.game.getEffect("riftChance");for(const ve in be.effects)ve==="unicornsRatioReligion"&&(Ce+=f(be.effects.unicornsRatioReligion)),ve==="riftChance"&&(st+=f(be.effects.riftChance));const ho=500*((Ce-1)*.1+1);let Kt=st*v/(1e4*2)*ho;Kt-=p;let Vt=i*s*Ce*n*r*h;Vt-=u,Vt+=Kt;const Xi=Y/Vt;Xi<w&&(0<Kt||a<Ce&&0<Y)&&(w=Xi,C=j)}return C}build(e,t,i){let s=i;const a=s;let n;if(t===U.Cryptotheology){const r=game.getUnlockByName(e,"transcendenceUpgrades"),o=new classes.ui.TranscendenceBtnController(this._host.game),l=o.fetchModel({controller:o,id:r.name});s=this._bulkManager.construct(l,o,s),n=r.label}else if(t===U.OrderOfTheSun){const r=game.getUnlockByName(e,"religion"),o=new com.nuclearunicorn.game.ui.ReligionBtnController(this._host.game),l=o.fetchModel({controller:o,id:r.name});s=this._bulkManager.construct(l,o,s),n=r.label}else if(t===U.Ziggurat){const r=game.getUnlockByName(e,"zigguratUpgrades"),o=new com.nuclearunicorn.game.ui.ZigguratBtnController(this._host.game),l=o.fetchModel({controller:o,id:r.name});s=this._bulkManager.construct(l,o,s),n=r.label}else throw new Ie("unsupported");s!==a&&(console.warn(...b(`${n} Amount ordered: ${a} Amount Constructed: ${s}`)),s===0)||(t===U.OrderOfTheSun?(this._host.engine.storeForSummary(n,s,"faith"),s===1?this._host.engine.iactivity("act.sun.discover",[n],"ks-faith"):this._host.engine.iactivity("act.sun.discovers",[n,this._host.renderAbsolute(s)],"ks-faith")):(this._host.engine.storeForSummary(n,s,"build"),s===1?this._host.engine.iactivity("act.build",[n],"ks-build"):this._host.engine.iactivity("act.builds",[n,this._host.renderAbsolute(s)],"ks-build")))}getBuildMetaData(e){const t={};for(const i of Object.values(e)){const s=this.getUpgradeMeta(i.building,i.variant);if(s===null)continue;t[i.building]=s;const a=f(t[i.building]);if(!this._getBuild(i.building,i.variant))a.rHidden=!0;else{const n=f(this._getBuild(i.building,i.variant)).model,r=i.variant===U.Cryptotheology?this._host.game.science.get("cryptotheology").researched:!0;a.rHidden=!(n?.visible&&n.enabled&&r)}}return t}getUpgradeMeta(e,t){switch(t){case U.Ziggurat:return this._host.game.religion.getZU(e)??null;case U.OrderOfTheSun:return this._host.game.religion.getRU(e)??null;case U.Cryptotheology:return this._host.game.religion.getTU(e)??null}throw new Error(`Unknown build: ${e} (${t})`)}_getBuild(e,t){switch(t){case U.Ziggurat:return this._host.game.time.queue.getQueueElementControllerAndModel({name:e,type:"zigguratUpgrades"});case U.OrderOfTheSun:return this._host.game.time.queue.getQueueElementControllerAndModel({name:e,type:"religion"});case U.Cryptotheology:return this._host.game.time.queue.getQueueElementControllerAndModel({name:e,type:"transcendenceUpgrades"});default:throw new Error(`Invalid variant '${t}'`)}}_transformBtnSacrificeHelper(e,t,i,s){const n=1/(e/t),o=new classes.ui.religion.TransformBtnController(game,i.controllerOpts)._newLink(s,n);return new Promise(l=>{o.handler(new Event("decoy"),l)})}async _autoSacrificeUnicorns(){const e=this._workshopManager.getResource("unicorns"),t=this._workshopManager.getValueAvailable("unicorns");if(!g(this._host.game.religionTab.sacrificeBtn)&&Z(this.settings.sacrificeUnicorns.trigger)<=t&&Z(this.settings.sacrificeUnicorns.trigger)<=e.value){const i=this._host.game.religionTab.sacrificeBtn.controller,s=this._host.game.religionTab.sacrificeBtn.model;if(g(s))return;await this._transformBtnSacrificeHelper(t,e.value,i,s);const a=this._workshopManager.getValueAvailable("unicorns"),n=t-a;this._host.engine.iactivity("act.sacrificeUnicorns",[this._host.game.getDisplayValueExt(n)],"ks-faith"),this._host.engine.storeForSummary(this._host.engine.i18n("$resources.unicorns.title"),n,"refine")}}async _autoSacrificeAlicorns(e){const t=this._workshopManager.getResource("alicorn"),i=this._workshopManager.getValueAvailable("alicorn");if(!g(this._host.game.religionTab.sacrificeAlicornsBtn)&&Z(this.settings.sacrificeAlicorns.trigger)<=i&&Z(this.settings.sacrificeAlicorns.trigger)<=t.value){this._host.game.religionTab.sacrificeAlicornsBtn.render();const s=this._host.game.religionTab.sacrificeAlicornsBtn.controller,a=this._host.game.religionTab.sacrificeAlicornsBtn.model;if(g(a)){e.requestGameUiRefresh=!0;return}await this._transformBtnSacrificeHelper(i,t.value,s,a);const n=this._workshopManager.getValueAvailable("alicorn"),r=i-n;this._host.engine.iactivity("act.sacrificeAlicorns",[this._host.game.getDisplayValueExt(r)],"ks-faith"),this._host.engine.storeForSummary(this._host.engine.i18n("$resources.alicorn.title"),r,"refine")}}_autoTears(e){const t=this._workshopManager.getResource("tears"),i=this._workshopManager.getValueAvailable("tears"),s=this._workshopManager.getResource("sorrow");if(!g(this._host.game.religionTab.refineBtn)&&Z(this.settings.refineTears.trigger)<=i&&Z(this.settings.refineTears.trigger)<=t.value&&s.value<s.maxValue){const a=i-this.settings.refineTears.trigger;if(a<1e4)return;const n=this._host.game.religionTab.refineBtn.controller,r=this._host.game.religionTab.refineBtn.model;if(g(r)){e.requestGameUiRefresh=!0;return}n.buyItem(r,new Event("decoy"),a);const o=this._workshopManager.getValueAvailable("tears"),l=i-o;this._host.engine.iactivity("act.refineTears",[this._host.game.getDisplayValueExt(l)],"ks-faith"),this._host.engine.storeForSummary(this._host.engine.i18n("$resources.tears.title"),l,"refine")}}async _autoTCs(e){const t=this._workshopManager.getResource("timeCrystal"),i=this._workshopManager.getValueAvailable("timeCrystal");if(!g(this._host.game.religionTab.refineTCBtn)&&Z(this.settings.refineTimeCrystals.trigger)<=i&&Z(this.settings.refineTimeCrystals.trigger)<=t.value){const s=this._host.game.religionTab.refineTCBtn.controller,a=this._host.game.religionTab.refineTCBtn.model;if(g(a)){e.requestGameUiRefresh=!0;return}await this._transformBtnSacrificeHelper(i,t.value,s,a);const n=this._workshopManager.getValueAvailable("timeCrystal"),r=i-n;this._host.engine.iactivity("act.refineTCs",[this._host.game.getDisplayValueExt(r)],"ks-faith"),this._host.engine.storeForSummary(this._host.engine.i18n("$resources.timeCrystal.title"),r,"refine")}}_autoTAP(){const e=this._workshopManager.getResource("faith"),t=e.value/e.maxValue;this.settings.transcend.enabled&&this.settings.autoPraise.trigger-.02<=t&&this._autoTranscend(),this.settings.autoPraise.trigger<=t&&(this.settings.adore.enabled&&f(this._host.game.religion.getRU("apocripha")).on&&this._autoAdore(this.settings.adore.trigger),this.settings.autoPraise.enabled&&this._autoPraise())}_autoAdore(e){const t=this._workshopManager.getResource("faith"),i=this._host.game.religion.faith,s=this._host.game.religion.faithRatio,n=f(this._host.game.religion.getRU("transcendence")).on?this._host.game.religion.transcendenceTier:0,r=10+this._host.game.getEffect("solarRevolutionLimit"),o=r*e,l=i/1e6*n*n*1.01,h=s+l,u=.01+t.value*(1+this._host.game.getUnlimitedDR(h,.1)*.1),d=this._host.game.getLimitedDR(this._host.game.getUnlimitedDR(u,1e3)/100,r);o<=d&&(this._host.game.religion._resetFaithInternal(1.01),this._host.engine.iactivity("act.adore",[this._host.game.getDisplayValueExt(i),this._host.game.getDisplayValueExt(l)],"ks-adore"),this._host.engine.storeForSummary("adore",l))}_autoTranscend(){let e=this._host.game.religion.faithRatio;const t=f(this._host.game.religion.getRU("transcendence")).on;let i=t?this._host.game.religion.transcendenceTier:0;if(t){const s=((i+2)/(i+1))**2,a=this._host.game.religion._getTranscendTotalPrice(i+1)-this._host.game.religion._getTranscendTotalPrice(i),n=a,r=s;if((1-r+Math.sqrt(80*(r*r-1)*n+(r-1)*(r-1)))*r/(40*(r+1)*(r+1)*(r-1))+n+n/(r*r-1)<=e){this._host.game.religion.faithRatio-=a,this._host.game.religion.tcratio+=a,this._host.game.religion.transcendenceTier+=1;const l=f(this._host.game.challenges.getChallenge("atheism"));l.calculateEffects?.(l,this._host.game);const h=f(this._host.game.religion.getTU("blackObelisk"));h.calculateEffects?.(h,this._host.game),this._host.game.msg(this._host.engine.i18n("$religion.transcend.msg.success",[this._host.game.religion.transcendenceTier])),e=this._host.game.religion.faithRatio,i=this._host.game.religion.transcendenceTier,this._host.engine.iactivity("act.transcend",[this._host.game.getDisplayValueExt(a),i],"ks-transcend"),this._host.engine.storeForSummary("transcend",1)}}}_autoPraise(){const e=this._workshopManager.getResource("faith"),t=this._host.game.religion.getApocryphaBonus(),i=e.value*(1+t);this._host.engine.storeForSummary("praise",i),this._host.engine.iactivity("act.praise",[this._host.game.getDisplayValueExt(e.value),this._host.game.getDisplayValueExt(i)],"ks-praise"),this._host.game.religion.praise()}}class Rs extends y{#e;get policy(){return this.#e}constructor(e,t=!1){super(t),this.#e=e}}class wi extends y{policies;constructor(e=!1){super(e),this.policies=this.initPolicies()}initPolicies(){const e={};for(const t of hs)e[t]=new Rs(t);return e}static validateGame(e,t){const i=Object.keys(t.policies),s=e.science.policies.map(r=>r.name),a=Q(s,i),n=Q(i,s);for(const r of a)console.warn(...b(`The policy '${r}' is not tracked in Kitten Scientists!`));for(const r of n)console.warn(...b(`The policy '${r}' is not a policy in Kittens Game!`))}load(e){g(e)||(super.load(e),O(this.policies,e.policies,(t,i)=>{t.enabled=i?.enabled??t.enabled}))}}class Ms extends F{#e;get tech(){return this.#e}constructor(e,t=!1){super(t,-1),this.#e=e}}class ki extends F{techs;constructor(e=!1){super(e,-1),this.techs=this.initTechs()}initTechs(){const e={};for(const t of us)e[t]=new Ms(t);return e}static validateGame(e,t){const i=Object.keys(t.techs),s=e.science.techs.map(r=>r.name),a=Q(s,i),n=Q(i,s);for(const r of a)gi.includes(r)||console.warn(...b(`The technology '${r}' is not tracked in Kitten Scientists!`));for(const r of n){if(gi.includes(r)){console.info(...b(`The technology '${r}' is a technology in Kittens Game, but it's no longer used.`));continue}console.warn(...b(`The technology '${r}' is not a technology in Kittens Game!`))}}load(e){g(e)||(super.load(e),O(this.techs,e.techs,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class bt extends y{policies;techs;observe;constructor(e=!1,t=new wi,i=new ki,s=new y){super(e),this.policies=t,this.techs=i,this.observe=s}static validateGame(e,t){wi.validateGame(e,t.policies),ki.validateGame(e,t.techs)}load(e){g(e)||(super.load(e),this.policies.load(e.policies),this.techs.load(e.techs),this.observe.enabled=e.observe?.enabled??this.observe.enabled)}}class ye{_host;constructor(e){this._host=e}upgrade(e,t){let i=!1;if(t==="policy"){const a=game.getUnlockByName(e.name,"policies"),n=new classes.ui.PolicyBtnController(this._host.game),r=n.fetchModel({controller:n,id:a.name});i=ye.skipConfirm(()=>n.buyItem(r)).itemBought}else if(t==="science"){const a=game.getUnlockByName(e.name,"tech"),n=new com.nuclearunicorn.game.ui.TechButtonController(this._host.game),r=n.fetchModel({controller:n,id:a.name});i=ye.skipConfirm(()=>n.buyItem(r)).itemBought}else{const a=game.getUnlockByName(e.name,"upgrades"),n=new com.nuclearunicorn.game.ui.UpgradeButtonController(this._host.game),r=n.fetchModel({controller:n,id:a.name});i=ye.skipConfirm(()=>n.buyItem(r)).itemBought}if(!i)return!1;const s=e.label;return t==="workshop"?(this._host.engine.storeForSummary(s,1,"upgrade"),this._host.engine.iactivity("upgrade.upgrade",[s],"ks-upgrade")):t==="policy"?this._host.engine.iactivity("upgrade.policy",[s]):t==="science"&&(this._host.engine.storeForSummary(s,1,"research"),this._host.engine.iactivity("upgrade.tech",[s],"ks-research")),!0}static async skipConfirmAsync(e){const t=game.ui.confirm;try{return game.ui.confirm=()=>!0,await e()}finally{game.ui.confirm=t}}static skipConfirm(e){const t=game.ui.confirm;try{return game.ui.confirm=()=>!0,e()}finally{game.ui.confirm=t}}}const As=c=>new Promise(e=>setTimeout(e,c)),we="en-US",Ps=2*60*1e3,Bs="localStorage"in globalThis&&!g(localStorage["ks.timeout"])?Number(localStorage["ks.timeout"]):void 0;class x{_gameStartSignal;_gameStartSignalResolver;_possibleEngineState;static tryEngineStateFromSaveData(e,t){const i=t;if(!(e in i)){console.debug(...b(`Failed: \`${e}\` not found in save data.`));return}const s=i.ks;if(!("state"in s)){console.debug(...b(`Failed: \`${e}.state\` not found in save data.`));return}const a=s.state;if(!Array.isArray(a)){console.debug(...b(`Failed: \`${e}.state\` not \`Array\`.`));return}return a[0]}async waitForGame(e,t,i=Bs??Ps){if(x._isGameLoaded()){const a=f(x.window.game),n=f(x.window.$I),r=localStorage["com.nuclearunicorn.kittengame.language"];return new e(a,n,r,this._possibleEngineState)}const s=[As(2e3)];if(g(this._gameStartSignal)&&typeof x.window.dojo<"u"){this._gameStartSignal=new Promise(n=>{this._gameStartSignalResolver=n});const a=x.window.dojo.subscribe("game/start",()=>{console.debug(...b(`'game/start' signal caught. Fast-tracking script load for '${t}'...`)),f(this._gameStartSignalResolver)(!0),x.window.dojo.unsubscribe(a)});if(t!==void 0){const n=x.window.dojo.subscribe("server/load",r=>{console.info(...b(`'server/load' signal caught. Looking for script state with key '${t}' in save data...`));const o=x.tryEngineStateFromSaveData(t,r);if(!o){console.info(...b(`The Kittens Game save data did not contain a script state for '${t}'.`));return}console.info(...b(`Found key '${t}'! Provided save data will be used as seed for next script instance.`)),this._possibleEngineState=o,x.window.dojo.unsubscribe(n)})}}if(g(this._gameStartSignal)||s.push(this._gameStartSignal),i<0)throw new Error("Unable to find game. Giving up. Maybe the game is not exported at `window.game`?");return console.debug(...b(`Waiting for game... (timeout: ${Math.round(i/1e3)}s)`)),await Promise.race(s),this.waitForGame(e,t,i-2e3)}static _isGameLoaded(){return!g(x.window.game)&&(x.window.document.getElementById("game")?.checkVisibility()??!1)&&!g(x.window.$I)}static get window(){try{return f(unsafeWindow)}catch{return window}}}class Is extends ye{settings;_workshopManager;constructor(e,t,i=new bt){super(e),this.settings=i,this._workshopManager=t}async tick(e){this.settings.enabled&&(this.settings.techs.enabled&&this._host.game.libraryTab.visible&&await this.autoUnlock(),this.settings.policies.enabled&&this._host.game.libraryTab.visible&&await this.autoPolicy(),this.settings.observe.enabled&&this.observeStars())}async autoUnlock(){const e=this._host.game.science.techs,t=new Array;e:for(const i of Object.values(this.settings.techs.techs)){if(!i.enabled)continue;const s=e.find(n=>n.name===i.tech);if(g(s)){console.error(...b(`Tech '${i.tech}' not found in game!`));continue}if(s.researched||!s.unlocked)continue;let a=x.window.dojo.clone(s.prices);a=this._host.game.village.getEffectLeader("scientist",a);for(const n of a){const r=this._workshopManager.getValueAvailable(n.name),o=this._workshopManager.getResource(n.name),l=te.evaluateSubSectionTrigger(this.settings.techs.trigger,i.trigger);if(l<0||r<o.maxValue*l||r<n.val)continue e}t.push(s)}for(const i of t)await this.upgrade(i,"science")}async autoPolicy(){const e=this._host.game.science.policies,t=new Array;for(const i of Object.values(this.settings.policies.policies)){if(!i.enabled)continue;const s=e.find(a=>a.name===i.policy);if(g(s)){console.error(...b(`Policy '${i.policy}' not found in game!`));continue}!s.researched&&!s.blocked&&s.unlocked&&(s.requiredLeaderJob===void 0||this._host.game.village.leader!==null&&this._host.game.village.leader.job===s.requiredLeaderJob)&&t.push(s)}for(const i of t)await this.upgrade(i,"policy")}observeStars(){this._host.game.calendar.observeBtn!==null&&(this._host.game.calendar.observeHandler(),this._host.engine.iactivity("act.observe",[],"ks-star"),this._host.engine.storeForSummary("stars",1))}}class $s extends y{#e;get mission(){return this.#e}constructor(e,t=!1){super(t),this.#e=e}}class _i extends y{missions;constructor(e=!1){super(e),this.missions=this.initMissions()}initMissions(){const e={};for(const t of ds)e[t]=new $s(t);return e}static validateGame(e,t){const i=Object.keys(t.missions),s=e.space.programs.map(r=>r.name),a=Q(s,i),n=Q(i,s);for(const r of a)console.warn(...b(`The space mission '${r}' is not tracked in Kitten Scientists!`));for(const r of n)console.warn(...b(`The space mission '${r}' is not a space mission in Kittens Game!`))}load(e){g(e)||(super.load(e),O(this.missions,e.missions,(t,i)=>{t.enabled=i?.enabled??t.enabled}))}}class Ls extends Ne{#e;get building(){return this.#e}constructor(e){super(!1,-1,0),this.#e=e}}class ze extends F{buildings;unlockMissions;constructor(e=!1,t=-1,i=new _i){super(e,t),this.buildings=this.initBuildings(),this.unlockMissions=i}initBuildings(){const e={};for(const t of mi)e[t]=new Ls(t);return e}static validateGame(e,t){_i.validateGame(e,t.unlockMissions)}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.max=i?.max??t.max,t.trigger=i?.trigger??t.trigger}),this.unlockMissions.load(e.unlockMissions))}}class Os{_host;settings;_bulkManager;_workshopManager;constructor(e,t,i=new ze){this._host=e,this.settings=i,this._workshopManager=t,this._bulkManager=new Ue(this._host,this._workshopManager)}tick(e){this.settings.enabled&&(this.autoBuild(e),this.settings.unlockMissions.enabled&&this.autoUnlock(e))}autoBuild(e,t=this.settings.buildings){const i=this._bulkManager,s=this.settings.trigger,a={};for(const r of Object.values(t))a[r.building]=this.getBuild(r.building);const n=i.bulk(t,a,s,"Space");for(const r of n)r.count<=0||this.build(r.id,r.count)!==0&&(e.requestGameUiRefresh=!0)}autoUnlock(e){if(!this._host.game.tabs[6].visible)return;const t=this._host.game.space.meta[0].meta;e:for(let i=0;i<t.length;i++){if(0<t[i].val||!t[i].unlocked||!this.settings.unlockMissions.missions[t[i].name].enabled)continue;const s=this._host.game.time.queue.getQueueElementControllerAndModel({name:t[i].name,type:"spaceMission"}),a=f(s.model.prices);for(const n of a)if(this._workshopManager.getValueAvailable(n.name)<n.val)continue e;s.controller.buyItem(s.model),i===7||i===12?this._host.engine.iactivity("upgrade.space.mission",[t[i].label],"ks-upgrade"):this._host.engine.iactivity("upgrade.space",[t[i].label],"ks-upgrade")}}build(e,t){let i=t;const s=i;let a;const n=game.getUnlockByName(e,"spaceBuilding"),r=new classes.ui.space.PlanetBuildingBtnController(this._host.game),o=r.fetchModel({controller:r,id:n.name});return i=this._bulkManager.construct(o,r,i),a=n.label,i!==s&&(console.warn(...b(`${a} Amount ordered: ${s} Amount Constructed: ${i}`)),i===0)?0:(this._host.engine.storeForSummary(a,i,"build"),i===1?this._host.engine.iactivity("act.build",[a],"ks-build"):this._host.engine.iactivity("act.builds",[a,this._host.renderAbsolute(i)],"ks-build"),i)}getBuild(e){return this._host.game.space.getBuilding(e)}}var Ci=(c=>(c.build="ks-activity type_ks-build",c.craft="ks-activity type_ks-craft",c.upgrade="ks-activity type_ks-upgrade",c.research="ks-activity type_ks-research",c.trade="ks-activity type_ks-trade",c.hunt="ks-activity type_ks-hunt",c.praise="ks-activity type_ks-praise",c.adore="ks-activity type_ks-adore",c.transcend="ks-activity type_ks-transcend",c.faith="ks-activity type_ks-faith",c.accelerate="ks-activity type_ks-accelerate",c.timeSkip="ks-activity type_ks-timeSkip",c.festival="ks-activity type_ks-festival",c.star="ks-activity type_ks-star",c.distribute="ks-activity type_ks-distribute",c.promote="ks-activity type_ks-promote",c.misc="ks-activity",c))(Ci||{});const Si=["accelerate","adore","build","craft","distribute","faith","festival","hunt","misc","praise","promote","research","star","timeSkip","trade","transcend","upgrade"];class Us extends y{#e;get variant(){return this.#e}constructor(e){super(!0),this.#e=e}}class Ds extends y{filters;disableKGLog;constructor(e=!1,t=new y(!0)){super(e),this.filters=this.initFilters(),this.disableKGLog=t}initFilters(){const e={};for(const t of Si)e[t]=new Us(Ci[t]);return e}load(e){g(e)||(super.load(e),O(this.filters,e.filters,(t,i)=>{t.enabled=i?.enabled??t.enabled}),this.disableKGLog.enabled=e.disableKGLog?.enabled??this.disableKGLog.enabled)}}class Ns extends F{#e;$upgrade;get upgrade(){return this.#e}constructor(e,t=!1){super(t,-1),this.#e=e}}class xi extends F{upgrades;constructor(e=!1){super(e,-1),this.upgrades=this.initUpgrades()}initUpgrades(){const e={};for(const t of bi)e[t]=new Ns(t);return e}static validateGame(e,t){const i=Object.keys(t.upgrades),s=e.workshop.upgrades.map(r=>r.name),a=Q(s,i),n=Q(i,s);for(const r of a)console.warn(...b(`The workshop upgrade '${r}' is not tracked in Kitten Scientists!`));for(const r of n)console.warn(...b(`The workshop upgrade '${r}' is not an upgrade in Kittens Game!`))}load(e){g(e)||(super.load(e),O(this.upgrades,e.upgrades,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class qs extends fs{#e;get resource(){return this.#e}constructor(e,t=!1,i=!0){super(t,i),this.#e=e}}class Fe extends F{resources;shipOverride;unlockUpgrades;constructor(e=!1,t=-1,i=new xi,s=new y){super(e,t),this.resources=this.initResources(),this.shipOverride=s,this.unlockUpgrades=i}initResources(){const e={};for(const t of ri)e[t]=new qs(t);return e}static validateGame(e,t){const i=Object.keys(t.resources),s=e.workshop.crafts.map(r=>r.name),a=Q(s,i),n=Q(i,s);for(const r of a)console.warn(...b(`The workshop craft '${r}' is not tracked in Kitten Scientists!`));for(const r of n)console.warn(...b(`The workshop craft '${r}' is not an upgrade in Kittens Game!`));xi.validateGame(e,t.unlockUpgrades)}load(e){g(e)||(super.load(e),O(this.resources,e.resources,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.limited=i?.limited??t.limited,t.max=i?.max??t.max,t.trigger=i?.trigger??t.trigger}),this.unlockUpgrades.load(e.unlockUpgrades),this.shipOverride.enabled=e.shipOverride?.enabled??this.shipOverride.enabled)}}class Ti extends ye{settings;static DEFAULT_CONSUME_RATE=1;constructor(e,t=new Fe){super(e),this.settings=t}tick(e){return this.settings.enabled?(this.autoCraft(),this._host.engine.settings.highlighStock.enabled&&this.refreshStock(),this.settings.unlockUpgrades.enabled?this.autoUnlock():Promise.resolve()):Promise.resolve()}async autoUnlock(){if(!this._host.game.workshopTab.visible)return;const e=this._host.game.workshop.upgrades,t=new Array;e:for(const i of Object.values(this.settings.unlockUpgrades.upgrades)){if(!i.enabled)continue;const s=i.$upgrade??e.find(n=>n.name===i.upgrade);if(g(s)){console.error(...b(`Upgrade '${i.upgrade}' not found in game!`));continue}if(i.$upgrade===void 0&&(i.$upgrade=s),s.researched||!s.unlocked)continue;let a=x.window.dojo.clone(s.prices);a=this._host.game.village.getEffectLeader("scientist",a);for(const n of a){const r=this.getValueAvailable(n.name),o=this.getResource(n.name),l=te.evaluateSubSectionTrigger(this.settings.unlockUpgrades.trigger,i.trigger);if(l<0||0<l&&r<o.maxValue*l||r<n.val)continue e}t.push(s)}for(const i of t)await this.upgrade(i,"workshop")}autoCraft(e=this.settings.resources){const t=new Map,i=this.settings.trigger;for(const n of Object.values(e)){const r=te.evaluateSubSectionTrigger(i,n.trigger);if(r<0||!n.enabled)continue;const o=n.max?this.getResource(n.resource):!1,l=Z(n.max);if(o&&l<o.value||!this.singleCraftPossible(n.resource))continue;const h=Object.keys(this.getMaterials(n.resource));h.map(m=>this.getResource(m)).filter(m=>0<m.maxValue).filter(m=>m.value/m.maxValue<r).length===0&&t.set(n,{countRequested:1,materials:h.map(m=>({consume:0,resource:m}))})}if(t.size<1)return;const s=new Map;for(const[n,r]of t)for(const o of r.materials)s.has(o.resource)||s.set(o.resource,new Array),f(s.get(o.resource)).push(n.resource);for(const[,n]of t)for(const r of n.materials){const o=this.getValueAvailable(r.resource);r.consume=o/f(s.get(r.resource)).length}for(const[n,r]of t){const o=this.getMaterials(n.resource);let l=Number.MAX_VALUE;for(const m of r.materials){const v=f(o[m.resource]),p=this.getResource(m.resource);if(!n.limited||n.resource==="ship"&&this.settings.shipOverride.enabled&&this.getResource("ship").value<243){l=Math.min(l,m.consume/v);continue}const w=this._host.game.getResCraftRatio(n.resource),C=this.getValueAvailable(m.resource)/f(s.get(m.resource)).length,A=this.getValueAvailable(n.resource),oe=v,K=1+w,j=C/oe,he=A/K,Y=Math.max(0,Math.floor(Math.log(he)/Math.LN10+1e-9));l=Math.min(l,Math.min(j-(0<p.maxValue&&p.maxValue<=p.value?0:he),10**(Y+1)),m.consume/v)}const h=this.getValueAvailable(n.resource),u=1+this._host.game.getResCraftRatio(n.resource),d=Number.MAX_VALUE/u-h/u;l=Math.min(l,d),r.countRequested=Math.max(0,n.max===-1?l:Math.min(l,(n.max-h)/u))}const a=new Array;for(const[n,r]of t)r.countRequested<1||a.push({amount:Math.floor(r.countRequested),name:n.resource});0<a.length&&this.craftMultiple(a)}craftMultiple(e){const t=new Array;for(const i of e){const s=this.getCraft(i.name),a=this._host.game.getResCraftRatio(s.name);if(!this._host.game.workshop.craft(s.name,i.amount,!0,!1,!1)){console.error(...b(`Failed trying to craft ${i.amount}x ${i.name}! This is a problem and should be reported.`));continue}const r=f(this._host.game.resPool.get(i.name)).title,o=Number.parseFloat((i.amount*(1+a)).toFixed(2));this._host.engine.storeForSummary(r,o,"craft"),t.push(this._host.engine.i18n("act.craft",[this._host.game.getDisplayValueExt(o),r]))}this._host.game.updateResources();for(const i of t)this._host.engine.printOutput("ks-activity type_ks-craft","#e65C00",i)}_canCraft(e,t){if(!this._host.game.workshopTab.visible&&e!=="wood")return!1;const i=this.getCraft(e),s=f(this.settings.resources[e]).enabled;let a=!1;if(i.unlocked&&s){a=!0;const n=this._host.game.workshop.getCraftPrice(i);for(const r of n)this.getValueAvailable(r.name)<r.val*t&&(a=!1)}return a}getCraft(e){const t=this._host.game.workshop.getCraft(e);if(!t)throw new Error(`Unable to find craft '${e}'`);return t}singleCraftPossible(e){if(!this._host.game.workshopTab.visible&&e!=="wood")return!1;const t=this.getMaterials(e);for(const[i,s]of L(t))if(this.getValueAvailable(i)<s)return!1;return!0}getMaterials(e){const t={},i=this.getCraft(e),s=this._host.game.workshop.getCraftPrice(i);for(const a of s)t[a.name]=a.val;return t}getTickVal(e,t,i=void 0){let s=this._host.game.getResourcePerTick(e.name,!0);if(e.craftable){let a=Number.MAX_VALUE;const n=this.getMaterials(e.name);for(const[r,o]of L(n)){const l=(1+this._host.game.getResCraftRatio(e.name))/o,h=this.getTickVal(this.getResource(r));h!=="ignore"&&(a=Math.min(h*l,a))}s+=a!==Number.MAX_VALUE?a:0}return s<=0&&(e.name==="spice"||e.name==="blueprint")?"ignore":(!i&&!g(t)&&(s+=t.getResValue(e.name)),s)}getAverageHunt(){const e={},t=this._host.game.getEffect("hunterRatio")+this._host.game.village.getEffectLeader("manager",0);return e.furs=40+32.5*t,e.ivory=50*Math.min(.225+.01*t,.5)+40*t*Math.min(.225+.01*t,.5),e.unicorns=.05,this.getValue("zebras")>=10&&(e.bloodstone=this.getValue("bloodstone")===0?.05:5e-4),this._host.game.ironWill&&this._host.game.workshop.get("goldOre").researched&&(e.gold=.625+.625*t),e}getResource(e){const t=this._host.game.resPool.get(e);if(g(t))throw new Error(`Unable to find resource ${e}`);return t}getValue(e){return this.getResource(e).value??0}getStock(e){const t=this._host.engine.settings.resources.resources[e];return t.enabled?t.stock:0}getConsume(e){const t=this._host.engine.settings.resources.resources[e];return t.enabled?t.consume:1}getValueAvailable(e){let t=this.getStock(e);if(e==="catnip"){const a=this._host.game.bld.getBuildingExt("pasture").meta,n=this._host.game.bld.getBuildingExt("aqueduct").meta,r=a.stage===0?a.val:0,o=n.stage===0?n.val:0,l=this.getPotentialCatnip(!0,r,o);l<0&&(t-=l*202*5)}let i=this.getValue(e);i=Math.max(i-t,0);const s=this.getConsume(e);return i*s}getPotentialCatnip(e,t,i){let s=this._host.game.getEffect("catnipPerTickBase");e?(s*=.1,s*=1+this._host.game.getLimitedDR(this._host.game.getEffect("coldHarshness"),1)):s*=this._host.game.calendar.getWeatherMod({name:"catnip"})+this._host.game.calendar.getCurSeason().modifiers.catnip,this._host.game.science.getPolicy("communism").researched&&(s=0);const a=this._host.game.village.getResProduction(),n=a.catnip?a.catnip*(1+this._host.game.getEffect("catnipJobRatio")):0;let r=s+n,o=this._host.game.space.getBuilding("hydroponics").val;this._host.game.prestige.meta[0].meta[21].researched&&(this._host.game.calendar.cycle===2&&(o*=2),this._host.game.calendar.cycle===7&&(o*=.5)),r*=1+.03*i+.025*o;const h=this._host.game.challenges.currentChallenge==="winterIsComing"?0:this._host.game.prestige.getParagonProductionRatio();r*=1+h,r*=1+this._host.game.religion.getSolarRevolutionRatio(),this._host.game.opts.disableCMBR||(r*=1+this._host.game.getCMBRBonus()),r=f(this._host.game.calendar.cycleEffectsFestival({catnip:r}).catnip);let u=this._host.game.village.getResConsumption().catnip;const d=this._host.game.bld.getBuildingExt("unicornPasture").meta.val;if(u*=1+this._host.game.getLimitedDR(t*-.005+d*-.0015,1),this._host.game.village.sim.kittens.length>0&&this._host.game.village.happiness>1){const m=this._host.game.village.happiness-1,v=this._host.game.getEffect("catnipDemandWorkerRatioGlobal");this._host.game.challenges.currentChallenge==="anarchy"?u*=1+m*(1+v):u*=1+m*(1+v)*(1-this._host.game.village.getFreeKittens()/this._host.game.village.sim.kittens.length)}return r+=u,r+=this._host.game.getResourcePerTickConvertion("catnip"),r}refreshStock(){const e=[...document.querySelectorAll("#game .res-row .res-cell.resAmount, #game .res-row .res-cell.resource-value")],t=new Map(e.map(i=>[f([...i.parentNode.classList.entries()].find(([s,a])=>a.startsWith("resource_")))[1].substring(9),i]));for(const[i,s]of L(this._host.engine.settings.resources.resources)){const a=t.get(i);if(!a)continue;if(!s.enabled||s.stock===0){(a.classList.contains("ks-stock-above")||a.classList.contains("ks-stock-below"))&&a.classList.remove("ks-stock-above","ks-stock-below");continue}const n=this._host.game.resPool.get(i).value<s.stock;a.classList.add(n?"ks-stock-below":"ks-stock-above"),a.classList.remove(n?"ks-stock-above":"ks-stock-below")}}}class zs extends y{#e;consume;stock=0;get resource(){return this.#e}constructor(e,t=!1,i=Ti.DEFAULT_CONSUME_RATE,s=0){super(t),this.#e=e,this.consume=i,this.stock=s}}class Fs extends y{resources;constructor(e=!1){super(e),this.resources=this.initResources()}initResources(){const e={};for(const t of oi)e[t]=new zs(t);return e}load(e){g(e)||(super.load(e),O(this.resources,e.resources,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.consume=i?.consume??t.consume,t.stock=i?.stock??t.stock}))}}class Hs extends y{noConfirm;compress;constructor(e=new y,t=new y(!0)){super(!0),this.noConfirm=e,this.compress=t}load(e){g(e)||(super.load(e),this.noConfirm.load(e.noConfirm),this.compress.load(e.compress))}}class Ei extends y{interval=2e3;locale;ksColumn;highlighStock;filters;resources;states;constructor(e=!1,t=new Ds,i=new Fs,s=new Hs,a=we,n=new y,r=new y){super(e),this.filters=t,this.resources=i,this.states=s,this.locale=new gt(a,[{label:"Deutsch",value:"de-DE"},{label:"English",value:"en-US"},{label:"עִברִית",value:"he-IL"},{label:"中文",value:"zh-CN"}]),this.ksColumn=n,this.highlighStock=r}load(e,t=!1){g(e)||(super.load(e),t||(this.interval=e.interval??this.interval,this.states.load(e.states),this.locale.load(e.locale),this.ksColumn.load(e.ksColumn),this.highlighStock.load(e.highlighStock)),this.filters.load(e.filters),this.resources.load(e.resources))}}class Ri extends ee{#e=void 0;get baseBuilding(){return this.#e}#t;get building(){return this.#t}#i=0;get stage(){return this.#i}constructor(e,t=!1,i=-1,s){super(t,i),this.#t=e,s&&(this.#i=1,this.#e=s)}}class Ws extends y{buildings;constructor(e=!1){super(e),this.buildings=this.initBuildings()}initBuildings(){const e={broadcasttower:"amphitheatre",dataCenter:"library",hydroplant:"aqueduct",solarfarm:"pasture",spaceport:"warehouse"},t={};for(const i of ai)i!=="unicornPasture"&&(t[i]=new Ri(i));for(const i of dt)t[i]=new Ri(i,!1,-1,e[i]);return t}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class He extends ee{#e;#t;get building(){return this.#e}get variant(){return this.#t}constructor(e,t,i=!1,s=-1){super(i,s),this.#e=e,this.#t=t}}class Gs extends y{buildings;constructor(e=!1){super(e),this.buildings=this.initBuildings()}initBuildings(){const e={};for(const t of ci)e[t]=new He(t,U.OrderOfTheSun);for(const t of hi)e[t]=new He(t,U.Cryptotheology);for(const t of ui)e[t]=new He(t,U.Ziggurat);return e.unicornPasture=new He("unicornPasture",U.UnicornPasture),e}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class Zs extends ee{#e;get resource(){return this.#e}constructor(e,t=!1,i=-1){super(t,i),this.#e=e}}class Ks extends y{resources;constructor(e=!1){super(e),this.resources=this.initResources()}initResources(){const e={};for(const t of oi)e[t]=new Zs(t);return e}load(e){g(e)||(super.load(e),O(this.resources,e.resources,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class Vs extends ee{#e;get building(){return this.#e}constructor(e,t=!1,i=-1){super(t,i),this.#e=e}}class js extends y{buildings;constructor(e=!1){super(e),this.buildings=this.initBuildings()}initBuildings(){const e={};for(const t of mi)e[t]=new Vs(t);return e}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class Mi extends ee{#e;#t;get building(){return this.#e}get variant(){return this.#t}constructor(e,t,i=!1,s=-1){super(i,s),this.#e=e,this.#t=t}}class Js extends y{buildings;constructor(e=!1){super(e),this.buildings=this.initBuildings()}initBuildings(){const e={};for(const t of fi)e[t]=new Mi(t,se.Chronoforge);for(const t of pi)t!=="usedCryochambers"&&(e[t]=new Mi(t,se.VoidSpace));return e}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class Xs extends y{#e;get upgrade(){return this.#e}constructor(e,t=!1){super(t),this.#e=e}}class Ys extends y{upgrades;constructor(e=!1){super(e),this.upgrades=this.initUpgrades()}initUpgrades(){const e={};for(const t of bi)e[t]=new Xs(t);return e}load(e){g(e)||(super.load(e),O(this.upgrades,e.upgrades,(t,i)=>{t.enabled=i?.enabled??t.enabled}))}}class Qs extends y{bonfire;religion;resources;space;time;upgrades;constructor(e=!1,t=new Ws,i=new Gs,s=new Ks,a=new js,n=new Js,r=new Ys){super(e),this.bonfire=t,this.religion=i,this.resources=s,this.space=a,this.time=n,this.upgrades=r}load(e){g(e)||(super.load(e),this.bonfire.load(e.bonfire),this.religion.load(e.religion),this.resources.load(e.resources),this.space.load(e.space),this.time.load(e.time),this.upgrades.load(e.upgrades))}}class en extends F{cycles;activeHeatTransferStatus;constructor(e=new y){super(!1,1),this.cycles=this.initCycles(),this.activeHeatTransferStatus=e}initCycles(){const e={};for(const t of ge)e[t]=new y;return e}load(e){g(e)||(super.load(e),O(this.cycles,e.cycles,(t,i)=>{t.enabled=i?.enabled??t.enabled}),this.activeHeatTransferStatus.load(e.activeHeatTransferStatus))}}class tn extends bs{cycles;seasons;activeHeatTransfer;ignoreOverheat;constructor(e=new y,t=new en){super(!1,5),this.cycles=this.initCycles(),this.seasons=this.initSeason(),this.activeHeatTransfer=t,this.ignoreOverheat=e}initCycles(){const e={};for(const t of ge)e[t]=new y;return e}initSeason(){const e={};for(const t of ls)e[t]=new y;return e}load(e){g(e)||(super.load(e),O(this.cycles,e.cycles,(t,i)=>{t.enabled=i?.enabled??t.enabled}),O(this.seasons,e.seasons,(t,i)=>{t.enabled=i?.enabled??t.enabled}),this.ignoreOverheat.load(e.ignoreOverheat),this.activeHeatTransfer.load(e.activeHeatTransfer))}}class Ai extends y{accelerateTime;timeSkip;reset;constructor(e=!1,t=new F(!1,1),i=new Qs,s=new tn){super(e),this.accelerateTime=t,this.reset=i,this.timeSkip=s}load(e){g(e)||(super.load(e),this.accelerateTime.load(e.accelerateTime),this.reset.load(e.reset),this.timeSkip.load(e.timeSkip))}}class Pi extends Ne{#e;#t;get building(){return this.#e}get variant(){return this.#t}constructor(e,t,i=!1){super(i,-1,0),this.#e=e,this.#t=t}}class Bi extends F{buildings;fixCryochambers;constructor(e=!1,t=-1,i=new y){super(e,t),this.buildings=this.initBuildings(),this.fixCryochambers=i}initBuildings(){const e={};for(const t of fi)e[t]=new Pi(t,se.Chronoforge);for(const t of pi)t!=="usedCryochambers"&&(e[t]=new Pi(t,se.VoidSpace));return e}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.max=i?.max??t.max,t.trigger=i?.trigger??t.trigger}),this.fixCryochambers.load(e.fixCryochambers))}}class sn extends yi{#e;get race(){return this.#e}constructor(e,t=!1){super(t),this.#e=e}}class nn extends F{races;constructor(e=!1){super(e),this.races=this.initRaces()}initRaces(){const e={};for(const t of di)t!=="leviathans"&&(e[t]=new sn(t));return e}load(e){g(e)||(super.load(e),O(this.races,e.races,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.max=i?.max??t.max}))}}class an extends ps{#e;seasons;#t;get race(){return this.#e}get require(){return this.#t}constructor(e,t,i,s,a,n,r,o=!1){super(t,i),this.#e=e,this.seasons={autumn:new y(a),spring:new y(r),summer:new y(s),winter:new y(n)},this.#t=o}}class Ii extends F{races;feedLeviathans;buildEmbassies;tradeBlackcoin;unlockRaces;constructor(e=!1,t=-1,i=new nn,s=new y,a=new vs(!1,1090,1095,1e4),n=new y){super(e,t),this.races=this.initRaces(),this.buildEmbassies=i,this.feedLeviathans=s,this.tradeBlackcoin=a,this.unlockRaces=n}initRaces(){const e={dragons:"titanium",griffins:"wood",leviathans:"unobtainium",lizards:"minerals",sharks:"iron"},t={};for(const i of di){const s=e[i]??!1;t[i]=new an(i,!1,!1,!1,!1,!1,!1,s)}return t}load(e){g(e)||(super.load(e),O(this.races,e.races,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.limited=i?.limited??t.limited,t.trigger=i?.trigger??t.trigger,t.seasons.autumn.enabled=i?.seasons.autumn.enabled??t.seasons.autumn.enabled,t.seasons.spring.enabled=i?.seasons.spring.enabled??t.seasons.spring.enabled,t.seasons.summer.enabled=i?.seasons.summer.enabled??t.seasons.summer.enabled,t.seasons.winter.enabled=i?.seasons.winter.enabled??t.seasons.winter.enabled}),this.buildEmbassies.load(e.buildEmbassies),this.feedLeviathans.load(e.feedLeviathans),this.tradeBlackcoin.load(e.tradeBlackcoin),this.unlockRaces.load(e.unlockRaces))}}class rn extends y{job;trait;constructor(e=!1,t=new gt("any",li.map(s=>({label:"",value:s}))),i=new gt("none",cs.map(s=>({label:"",value:s})))){super(e),this.job=t,this.trait=i}load(e){g(e)||(super.load(e),this.job.load(e.job),this.trait.load(e.trait))}}class $i extends y{jobs;holdFestivals;hunt;promoteKittens;promoteLeader;electLeader;constructor(e=!1,t=new y,i=new F(!1,.98),s=new F(!1,1),a=new y,n=new rn){super(e),this.jobs=this.initJobs(),this.holdFestivals=t,this.hunt=i,this.promoteKittens=s,this.promoteLeader=a,this.electLeader=n}initJobs(){const e={};for(const t of li)e[t]=new yi(!1,0);return e}load(e){g(e)||(super.load(e),O(this.jobs,e.jobs,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.max=i?.max??t.max}),this.holdFestivals.enabled=e.holdFestivals?.enabled??this.holdFestivals.enabled,this.hunt.load(e.hunt),this.promoteKittens.enabled=e.promoteKittens?.enabled??this.promoteKittens.enabled,this.promoteLeader.enabled=e.promoteLeader?.enabled??this.promoteLeader.enabled,this.electLeader.load(e.electLeader))}}class on{_host;settings;_bonfireManager;_religionManager;_spaceManager;_workshopManager;constructor(e,t,i,s,a,n=new Ai){this._host=e,this.settings=n,this._bonfireManager=t,this._religionManager=i,this._spaceManager=s,this._workshopManager=a}async tick(e){this.settings.enabled&&(this.settings.accelerateTime.enabled&&this.accelerateTime(),this.settings.timeSkip.enabled&&this.timeSkip(),this.settings.reset.enabled&&await this.autoReset(this._host.engine))}async autoReset(e){if(this._host.game.challenges.currentChallenge)return;const t=[],i=[],s=r=>{if(i.length!==0)for(const o of r){if(g(o.model))continue;const l=o.model,h=l.metadata.name,u=i.indexOf(h);if(u!==-1&&(i.splice(u,1),this._host.game.resPool.hasRes(f(l.prices))))return!0}return!1};for(const[r,o]of L(this.settings.reset.bonfire.buildings)){if(!o.enabled)continue;if(o.trigger<0)return;let l;try{l=this._host.game.bld.getBuildingExt(r)}catch{l=null}if(!g(l))if(t.push({name:l.meta.label??f(l.meta.stages)[f(l.meta.stage)].label,trigger:o.trigger,val:l.meta.val}),0<o.trigger){if(l.meta.val<o.trigger)return}else i.push(r)}const a=this.settings.reset.religion.buildings.unicornPasture;if(a.enabled){if(a.trigger<0)return;const r=this._host.game.bld.getBuildingExt("unicornPasture");if(t.push({name:f(r.meta.label),trigger:a.trigger,val:r.meta.val}),0<a.trigger){if(r.meta.val<a.trigger)return}else i.push("unicornPasture")}if(s(this._bonfireManager.manager.tab.children)||i.length)return;for(const[r,o]of L(this.settings.reset.space.buildings)){if(!o.enabled)continue;if(o.trigger<0)return;const l=this._host.game.space.getBuilding(r);if(t.push({name:l.label,trigger:o.trigger,val:l.val}),0<o.trigger){if(l.val<o.trigger)return}else i.push(r)}if(i.length===0){const r=f(this._host.game.spaceTab.planetPanels);for(const o of r)for(const l of o.children){const h=f(l.model),u=h.metadata.name,d=i.indexOf(u);if(d!==-1&&(i.splice(d,1),this._host.game.resPool.hasRes(f(h.prices))))break}}if(i.length)return;for(const[r,o]of L(this.settings.reset.religion.buildings)){if(!o.enabled)continue;if(o.trigger<0)return;const l=f(this._religionManager.getUpgradeMeta(r,o.variant));if(t.push({name:l.label,trigger:o.trigger,val:l.val}),0<o.trigger){if(l.val<o.trigger)return}else i.push(r)}if(s(this._religionManager.manager.tab.zgUpgradeButtons)||s(this._religionManager.manager.tab.rUpgradeButtons)||s(this._religionManager.manager.tab.ctPanel.children[0].children)||i.length)return;for(const[r,o]of L(this.settings.reset.time.buildings)){if(!o.enabled)continue;if(o.trigger<0)return;const l=f(this.getBuild(r,o.variant));if(t.push({name:l.label,trigger:o.trigger,val:l.val}),0<o.trigger){if(l.val<o.trigger)return}else i.push(r)}if(s(this.manager.tab.cfPanel.children[0].children)||s(this.manager.tab.vsPanel.children[0].children)||i.length)return;for(const[r,o]of L(this.settings.reset.resources.resources)){if(!o.enabled)continue;if(o.trigger<0)return;const l=f(this._host.game.resPool.get(r));if(t.push({name:this._host.engine.i18n(`$resources.${o.resource}.title`),trigger:o.trigger,val:l.value}),l.value<o.trigger)return}for(const[,r]of L(this.settings.reset.upgrades.upgrades))if(r.enabled){const o=f(this._host.game.workshop.upgrades.find(l=>l.name===r.upgrade));if(t.push({name:o.label,trigger:1,val:o.researched?1:0}),!o.researched)return}e.stop(!1);const n=async(r=1500)=>new Promise((o,l)=>{if(!this._host.engine.settings.enabled){l(new Error("canceled by player"));return}setTimeout(o,r)});try{for(const r of t)await n(500),this._host.engine.imessage("reset.check",[r.name,this._host.game.getDisplayValueExt(r.trigger),this._host.game.getDisplayValueExt(r.val)]);await n(0),this._host.engine.imessage("reset.checked"),await n(),this._host.engine.iactivity("reset.tip"),await n(),this._host.engine.imessage("reset.countdown.10"),await n(2e3),this._host.engine.imessage("reset.countdown.9"),await n(),this._host.engine.imessage("reset.countdown.8"),await n(),this._host.engine.imessage("reset.countdown.7"),await n(),this._host.engine.imessage("reset.countdown.6"),await n(),this._host.engine.imessage("reset.countdown.5"),await n(),this._host.engine.imessage("reset.countdown.4"),await n(),this._host.engine.imessage("reset.countdown.3"),await n(),this._host.engine.imessage("reset.countdown.2"),await n(),this._host.engine.imessage("reset.countdown.1"),await n(),this._host.engine.imessage("reset.countdown.0"),await n(),this._host.engine.iactivity("reset.last.message"),await n()}catch{this._host.engine.imessage("reset.cancel.message"),this._host.engine.iactivity("reset.cancel.activity");return}for(let r=0;r<this._host.game.challenges.challenges.length;r++)this._host.game.challenges.challenges[r].pending=!1;this._host.game.resetAutomatic()}accelerateTime(){if(this._workshopManager.getValueAvailable("temporalFlux")<=0){this._host.game.time.isAccelerated&&(this._host.game.time.isAccelerated=!1);return}if(this._host.game.time.isAccelerated)return;const t=this._host.game.resPool.get("temporalFlux");t.maxValue*this.settings.accelerateTime.trigger<=t.value&&(this._host.game.time.isAccelerated=!0,this._host.engine.iactivity("act.accelerate",[],"ks-accelerate"),this._host.engine.storeForSummary("accelerate",1))}timeSkip(){if(!this._host.game.workshop.get("chronoforge").researched||this._host.game.calendar.day<0)return;const e=this._host.game.getEffect("shatterCostIncreaseChallenge"),t=this._workshopManager.getValueAvailable("timeCrystal");if(t<this.settings.timeSkip.trigger||t<1+e)return;const i=this._host.game.getEffect("shatterVoidCost"),s=this._workshopManager.getValueAvailable("void");if(s<i)return;const a=this._host.game.calendar.season;if(!this.settings.timeSkip.seasons[this._host.game.calendar.seasons[a].name].enabled)return;const n=this._host.game.calendar.cycle;if(!this.settings.timeSkip.cycles[ge[n]].enabled)return;const r=this._host.game.getEffect("heatMax"),o=this._host.game.time.heat;if(!this.settings.timeSkip.ignoreOverheat.enabled&&r<=o)return;const l=this._host.game.challenges.getChallenge("1000Years").researched?5:10;let h=Number.POSITIVE_INFINITY;if(!this.settings.timeSkip.ignoreOverheat.enabled&&this.settings.timeSkip.activeHeatTransfer.enabled){const C=this._host.game.getEffect("heatPerTick"),A=this._host.game.ticksPerSecond;if(this.settings.timeSkip.activeHeatTransfer.activeHeatTransferStatus.enabled){o<=r*this.settings.timeSkip.activeHeatTransfer.trigger&&(this.settings.timeSkip.activeHeatTransfer.activeHeatTransferStatus.enabled=!1,this._host.refreshEntireUserInterface(),this._host.engine.iactivity("act.time.activeHeatTransferEnd",[],"ks-timeSkip"));const oe=this._host.game.getEffect("temporalFluxProduction"),K=(this._host.game.calendar.daysPerSeason+10+this._host.game.getEffect("temporalParadoxDay"))*this._host.game.calendar.seasonsPerYear,j=this._host.game.calendar.ticksPerDay,he=(1+this._host.game.timeAccelerationRatio())/j,Y=K/he,be=this._host.game.resPool.get("temporalFlux"),Ce=be.maxValue>Y,st=be.value<Y;if(!a&&this._host.game.calendar.day<10&&oe>l/C&&this.settings.accelerateTime.enabled&&Ce&&st)h=Math.ceil((Y+j*10-be.value)/oe),this._host.engine.iactivity("act.time.getTemporalFlux",[],"ks-timeSkip"),this._host.engine.storeForSummary("time.getTemporalFlux",1);else{if(this.settings.timeSkip.activeHeatTransfer.cycles[ge[n]].enabled)return;h=this._host.game.calendar.yearsPerCycle-this._host.game.calendar.cycleYear}}else o>=r-C*A*10&&(this.settings.timeSkip.activeHeatTransfer.activeHeatTransferStatus.enabled=!0,this._host.refreshEntireUserInterface(),this._host.engine.iactivity("act.time.activeHeatTransferStart",[],"ks-timeSkip"),this._host.engine.storeForSummary("time.activeHeatTransferStart",1))}const u=Z(this.settings.timeSkip.max);let d=Math.floor(Math.min(this.settings.timeSkip.ignoreOverheat.enabled?Number.POSITIVE_INFINITY:(r-o)/l,u,h,t/(1+e),0<i?s/i:Number.POSITIVE_INFINITY)),m=0;const v=this._host.game.calendar.yearsPerCycle,p=v-this._host.game.calendar.cycleYear,w=this._host.game.calendar.cyclesPerEra;if(d<p)m=d;else{m+=p,d-=p;let C=1;for(;v<d&&this.settings.timeSkip.cycles[ge[(n+C)%w]].enabled;)m+=v,d-=v,C+=1;this.settings.timeSkip.cycles[ge[(n+C)%w]].enabled&&0<d&&(m+=d)}if(0<m){const C=this._host.game.timeTab.cfPanel.children[0].children[0];if(g(C.model))return;this._host.engine.iactivity("act.time.skip",[m],"ks-timeSkip"),C.controller.doShatterAmt(C.model,m),this._host.engine.storeForSummary("time.skip",m)}}getBuild(e,t){return t===se.Chronoforge?this._host.game.time.getCFU(e):this._host.game.time.getVSU(e)}}class ln{_host;settings;_bulkManager;_workshopManager;constructor(e,t,i=new Bi){this._host=e,this.settings=i,this._bulkManager=new Ue(this._host,t),this._workshopManager=t}tick(e){this.settings.enabled&&(this.autoBuild(e),this.settings.fixCryochambers.enabled&&this.fixCryochambers())}autoBuild(e,t=this.settings.buildings){const i=this._bulkManager,s=this.settings.trigger,a={};for(const r of Object.values(t)){const o=this.getBuild(r.building,r.variant);a[r.building]=f(o);const h=(r.variant===se.Chronoforge?this._host.game.time.queue.getQueueElementControllerAndModel({name:r.building,type:"chronoforge"}):this._host.game.time.queue.getQueueElementControllerAndModel({name:r.building,type:"voidSpace"})).model,u=r.variant===se.Chronoforge?this._host.game.timeTab.cfPanel:this._host.game.timeTab.vsPanel,d=f(a[r.building]);d.tHidden=!h?.visible||!h.enabled||!u.visible}const n=i.bulk(t,a,s,"Time");for(const r of n)r.count>0&&(this.build(r.id,r.variant,r.count),e.requestGameUiRefresh=!0)}build(e,t,i){let s=i,a;const n=s;if(t===se.Chronoforge){const r=game.getUnlockByName(e,"chronoforge"),o=new classes.ui.time.ChronoforgeBtnController(this._host.game),l=o.fetchModel({controller:o,id:r.name});s=this._bulkManager.construct(l,o,s),a=r.label}else{const r=game.getUnlockByName(e,"voidSpace"),o=new classes.ui.time.VoidSpaceBtnController(this._host.game),l=o.fetchModel({controller:o,id:r.name});s=this._bulkManager.construct(l,o,s),a=r.label}s!==n&&(console.warn(...b(`${a} Amount ordered: ${n} Amount Constructed: ${s}`)),s===0)||(this._host.engine.storeForSummary(a,s,"build"),s===1?this._host.engine.iactivity("act.build",[a],"ks-build"):this._host.engine.iactivity("act.builds",[a,this._host.renderAbsolute(s)],"ks-build"))}getBuild(e,t){return t===se.Chronoforge?this._host.game.time.getCFU(e):this._host.game.time.getVSU(e)}fixCryochambers(){if(this._host.game.time.getVSU("usedCryochambers").val<1)return;const e=f(this._host.game.time.getVSU("usedCryochambers").fixPrices);for(const n of e)if(this._workshopManager.getValueAvailable(n.name)<n.val)return;const t=new classes.ui.time.FixCryochamberBtnController(this._host.game),i=t.fetchModel({});let s=0,a;do a=!1,a=t.buyItem(i).itemBought,s+=a?1:0;while(a);0<s&&(this._host.engine.iactivity("act.fix.cry",[this._host.renderAbsolute(s)],"ks-fixCry"),this._host.engine.storeForSummary("fix.cry",s))}}class cn{_host;settings;_workshopManager;constructor(e,t,i=new Ii){this._host=e,this.settings=i,this._workshopManager=t}tick(e){this.settings.enabled&&(this.autoTrade(),this.settings.unlockRaces.enabled&&this.autoUnlock(e),this.settings.buildEmbassies.enabled&&this.autoBuildEmbassies(e),this.settings.feedLeviathans.enabled&&this.autoFeedElders(),this.settings.tradeBlackcoin.enabled&&this.autoTradeBlackcoin())}autoTrade(e){const t=this._workshopManager.getResource("manpower"),i=this._workshopManager.getResource("gold"),s=this.settings.trigger,a=[],n=this._host.game.calendar.getCurSeason().name;for(const u of Object.values(this.settings.races)){const d=this.getRace(u.race),m=te.evaluateSubSectionTrigger(s,u.trigger);if(m<0||!u.enabled||!u.seasons[n].enabled||!d.unlocked||!this.singleTradePossible(s,t,i,u))continue;const v=u.require?this._workshopManager.getResource(u.require):!1,p=this.getProfitability(u.race);(u.limited&&p||!v||m<=v.value/v.maxValue)&&a.push(u.race)}if(a.length===0)return;let r=this.getLowestTradeAmount(null,!0,!1);if(r<1)return;const o=[];for(let u=0;u<a.length;u++){const d=a[u],m=this.settings.races[d],v=m.require?this._workshopManager.getResource(m.require):!1,p=te.evaluateSubSectionTrigger(s,m.trigger),w=(!v||p<=v.value/v.maxValue)&&p<=i.value/i.maxValue,C=this.getLowestTradeAmount(d,m.limited,w);if(C<1){a.splice(u,1),u--;continue}o.push(C)}if(a.length===0)return;const l={};for(;0<a.length&&1<=r;){if(r<a.length){const v=Math.floor(Math.random()*a.length),p=a[v];g(l[p])&&(l[p]=0),l[p]+=1,r-=1,a.splice(v,1),o.splice(v,1);continue}let u=Math.floor(r/a.length),d=0;const m=a[d];for(let v=0;v<a.length;++v)o[v]<u&&(u=o[v],d=v);g(l[m])&&(l[m]=0),l[m]+=u,r-=u,a.splice(d,1),o.splice(d,1)}if(Object.values(l).length===0)return;const h={};for(const[u,d]of L(l)){const m=this.getRace(u),v=this.getMaterials(u);for(const[w,C]of L(v))h[w]||(h[w]=0),h[w]-=C*d;const p=this.getAverageTrade(m);for(const[w,C]of L(p)){const A=this._workshopManager.getResource(w);h[w]||(h[w]=0),h[w]+=A.maxValue>0?Math.min(f(p[w])*f(l[u]),Math.max(A.maxValue-A.value,0)):C*f(l[u])}}g(e)||e.pushToCache({materials:h,timeStamp:this._host.game.timer.ticksTotal});for(const[u,d]of L(l))0<d&&this.trade(u,d)}autoBuildEmbassies(e){if(!this._host.game.diplomacy.races[0].embassyPrices)return;const t=this._workshopManager.getResource("culture");let i=0;const s=this.settings.buildEmbassies.trigger;if(t.value/t.maxValue<Z(s))return;const a=this._host.game.diplomacyTab.racePanels;i=this._workshopManager.getValueAvailable("culture");const n={},r=[];for(let o=0;o<a.length;o++){if(!a[o].embassyButton)continue;const l=a[o].race.name,h=this._host.game.diplomacy.get(l),u=Z(this.settings.buildEmbassies.races[l].max);!this.settings.buildEmbassies.races[l].enabled||u<=h.embassyLevel||!h.unlocked||(n[l]={basePrice:f(h.embassyPrices?.[0]).val,currentEm:h.embassyLevel,max:u,priceSum:0,race:h,val:0},r.push(l))}if(r.length!==0){for(;r.length>0;)for(let o=0;o<r.length;o++){const l=r[o],h=f(n[l]);if(h.max<=h.currentEm+h.val){r.splice(o,1),--o;continue}const u=h.basePrice*1.15**(h.currentEm+h.val);u<=i?(i-=u,h.priceSum+=u,h.val+=1,e.requestGameUiRefresh=!0):(r.splice(o,1),--o)}for(const[,o]of L(n))o.val!==0&&(i=this._workshopManager.getValueAvailable("culture"),i<o.priceSum&&console.warn(...b("Something has gone horribly wrong.",o.priceSum,i)),this._workshopManager.getResource("culture").value-=o.priceSum,o.race.embassyLevel+=o.val,this._host.engine.storeForSummary("embassy",o.val),o.val!==1?this._host.engine.iactivity("build.embassies",[o.val,o.race.title],"ks-build"):this._host.engine.iactivity("build.embassy",[o.val,o.race.title],"ks-build"))}}autoFeedElders(){const e=this._host.game.diplomacy.get("leviathans"),t=this._host.game.resPool.get("necrocorn");!e.unlocked||t.value===0||(1<=t.value?e.energy<this._host.game.diplomacy.getMarkerCap()&&(this._host.game.diplomacy.feedElders(),this._host.engine.iactivity("act.feed"),this._host.engine.storeForSummary("feed",1)):.25*(1+this._host.game.getEffect("corruptionBoostRatio"))<1&&(this._host.engine.storeForSummary("feed",t.value),this._host.game.diplomacy.feedElders(),this._host.engine.iactivity("dispose.necrocorn")))}autoUnlock(e){if(!this._host.game.tabs[4].visible)return;const t=this._host.game.diplomacy.get("leviathans").unlocked?8:7;if(this._host.game.diplomacyTab.racePanels.length<t){let i=this._workshopManager.getValueAvailable("manpower");if(!this._host.game.diplomacy.get("lizards").unlocked&&i>=1e3){this._host.game.resPool.get("manpower").value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("sharks").unlocked&&i>=1e3){this._host.game.resPool.get("manpower").value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("griffins").unlocked&&i>=1e3){this._host.game.resPool.get("manpower").value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("nagas").unlocked&&this._host.game.resPool.get("culture").value>=1500&&i>=1e3){this._host.game.resPool.get("manpower").value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("zebras").unlocked&&this._host.game.resPool.get("ship").value>=1&&i>=1e3){this._host.game.resPool.get("manpower").value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("spiders").unlocked&&f(this._host.game.resPool.get("ship")).value>=100&&f(this._host.game.resPool.get("science")).maxValue>125e3&&i>=1e3){f(this._host.game.resPool.get("manpower")).value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("dragons").unlocked&&this._host.game.science.get("nuclearFission").researched&&i>=1e3){f(this._host.game.resPool.get("manpower")).value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}}}autoTradeBlackcoin(){const e=this._host.game.calendar.cryptoPrice,t=this._host.game.resPool.get("relic").value,i=this._host.game.resPool.get("blackcoin").value;let s=0,a=0;if(e<this.settings.tradeBlackcoin.buy&&this.settings.tradeBlackcoin.trigger<t){this._host.game.diplomacy.buyBcoin();const n=this._host.game.resPool.get("blackcoin").value;s=Math.round(n-i),this._host.engine.iactivity("act.blackcoin.buy",[this._host.renderAbsolute(s)])}else if(e>this.settings.tradeBlackcoin.sell&&0<this._host.game.resPool.get("blackcoin").value){this._host.game.diplomacy.sellBcoin();const n=f(this._host.game.resPool.get("relic")).value;a=Math.round(n-t),this._host.engine.iactivity("act.blackcoin.sell",[this._host.renderAbsolute(a)])}}trade(e,t){const i=this.getRace(e);this._host.game.diplomacy.tradeMultiple(i,t),this._host.engine.storeForSummary(i.title,t,"trade"),this._host.engine.iactivity("act.trade",[this._host.renderAbsolute(t),G(i.title)],"ks-trade")}getProfitability(e){const t=this.getRace(e);let i=0;const s=this.getMaterials(e);for(const[r,o]of L(s)){const l=this._workshopManager.getTickVal(this._workshopManager.getResource(r));if(l!=="ignore"){if(l<=0)return!1;i+=o/l}}let a=0;const n=this.getAverageTrade(t);for(const[r,o]of L(n)){const l=this._workshopManager.getResource(r),h=this._workshopManager.getTickVal(l);if(h!=="ignore"){if(h<=0)return!0;a+=0<l.maxValue?Math.min(o,Math.max(l.maxValue-l.value,0))/h:o/h}}return i<=a}getAverageTrade(e){const t=this._host.game.getEffect("standingRatio")+this._host.game.diplomacy.calculateStandingFromPolicies(e.name,this._host.game),i=1+e.energy*.02,s=1+this._host.game.diplomacy.getTradeRatio()+this._host.game.diplomacy.calculateTradeBonusFromPolicies(e.name,this._host.game),a=e.standing<0?e.standing+t:0,n=0<a?1+a:1,r=0<e.standing?Math.min(e.standing+t/2,1):0,o={};for(const u of e.sells){if(!this._isValidTrade(u,e)){o[u.name]=0;continue}let d=0;const m=e.embassyPrices?u.chance*(1+this._host.game.getLimitedDR(.01*e.embassyLevel,.75)):u.chance;if(e.name==="zebras"&&u.name==="titanium"){const v=this._host.game.resPool.get("ship").value,p=Math.min(.15+v*.0035,1);d=1.5*(1+v/50)*(n*p)}else{const v=u.seasons?1+u.seasons[this._host.game.calendar.getCurSeason().name]:1,p=(n-r)*Math.min(m/100,1),w=r*Math.min(m/100,1);d=(p+1.25*w)*u.value*i*v*s}o[u.name]=d}const l=e.embassyPrices?.35*(1+.01*e.embassyLevel):.35,h=n*Math.min(l,1);return o.spice=25*h+50*h*s/2,o.blueprint=.1*n,o}_isValidTrade(e,t){return!(e.minLevel&&t.embassyLevel<e.minLevel)&&(this._host.game.resPool.get(e.name).unlocked||e.name==="titanium"||e.name==="uranium"||t.name==="leviathans")}getLowestTradeAmount(e,t,i){let s;const a=this.getMaterials(e);let n;for(const[h,u]of L(a)){if(h==="manpower"){let d=u;this._host.game.challenges.isActive("postApocalypse")&&(d=u*(1+this._host.game.bld.getPollutionLevel())),n=this._workshopManager.getValueAvailable(h)/d}else if(h==="gold"){let d=u;this._host.game.challenges.isActive("postApocalypse")&&(d=u*(1+this._host.game.bld.getPollutionLevel())),n=this._workshopManager.getValueAvailable(h)/d}else n=this._workshopManager.getValueAvailable(h)/u;s=s===void 0||n<s?n:s}if(s=Math.floor(s??0),s===0)return 0;if(e===null||e==="leviathans")return s;const r=this.getRace(e);let o=0;const l=this.getAverageTrade(r);for(const h of r.sells){const u=this._workshopManager.getResource(h.name);let d=0;if(!u.maxValue)continue;d=f(l[h.name]);const m=Math.max((u.maxValue-u.value)/d,0);o=m<o?o:m}return o=Math.ceil(o),o===0?0:(s=o<s?Math.max(o-1,1):s,Math.floor(s))}getMaterials(e=null){const t={gold:15-this._host.game.getEffect("tradeGoldDiscount"),manpower:50-this._host.game.getEffect("tradeCatpowerDiscount")};if(g(e))return t;const i=this.getRace(e).buys;for(const s of i)t[s.name]=s.val;return t}getRace(e){const t=this._host.game.diplomacy.get(e);if(g(t))throw new Error(`Unable to retrieve race '${e}'`);return t}singleTradePossible(e,t,i,s){const a=s?te.evaluateSubSectionTrigger(e,s.trigger):e;if(a<0&&s===void 0)return!0;if(a<0&&s!==void 0||t.value/t.maxValue<a||i.value/i.maxValue<a)return!1;const n=this.getMaterials(s?.race);for(const[r,o]of L(n))if(this._workshopManager.getValueAvailable(r)<o)return!1;return!0}}class hn{_host;_cache=new Array;_cacheSum={};constructor(e){this._host=e}pushToCache(e){this._cache.push(e);for(const[t,i]of L(e.materials))this._cacheSum[t]||(this._cacheSum[t]=0),this._cacheSum[t]+=i;for(let t=0;t<this._cache.length;++t){const i=this._cache[t];if(this._cache.length>1e4){const s=i.materials;for(const[a,n]of L(s))this._cacheSum[a]||(this._cacheSum[a]=0),this._cacheSum[a]-=n;this._cache.shift(),t--}else return}}getResValue(e){if(this._cache.length===0||!this._cacheSum[e])return 0;const t=this._host.game.timer.ticksTotal,i=this._cache[0].timeStamp;return this._cacheSum[e]/(t-i)}}class un{_host;settings;_cacheManager;_workshopManager;constructor(e,t,i=new $i){this._host=e,this.settings=i,this._cacheManager=new hn(this._host),this._workshopManager=t}tick(e){this.settings.enabled&&(this.autoDistributeKittens(e),this.settings.hunt.enabled&&this.autoHunt(this._cacheManager),this.settings.holdFestivals.enabled&&this.autoFestival(this._cacheManager),this.settings.electLeader.enabled&&this.autoElect(),this.settings.promoteLeader.enabled&&this.autoPromoteLeader(),this.settings.promoteKittens.enabled&&this.autoPromoteKittens())}autoDistributeKittens(e){const t=this._host.game.village.getFreeKittens();if(t){for(let i=0;i<t;++i){const s=new Array;for(const r of this._host.game.village.jobs){const o=this.settings.jobs[r.name].enabled,l=r.unlocked;if(!o||!l)continue;const h=this._host.game.village.getJobLimit(r.name),u=Z(this.settings.jobs[r.name].max),d=r.value;d<h&&d<u&&s.push({count:d,job:r,toCap:h-d})}if(!s.length)return;const a=!g(s.find(r=>r.job.name==="farmer"&&r.count===0));s.sort((r,o)=>r.count-o.count);const n=a?"farmer":s[0].job.name;this._host.game.village.assignJob(this._host.game.village.getJob(n),1),e.requestGameUiRefresh=!0,this._host.engine.iactivity("act.distribute",[this._host.engine.i18n(`$village.job.${n}`)],"ks-distribute")}this._host.engine.storeForSummary("distribute",t)}}autoElect(){if(this._host.game.challenges.isActive("anarchy"))return;const e=this._host.game.village.sim.kittens,t=this._host.game.village.leader,i=this.settings.electLeader.job.selected,s=this.settings.electLeader.trait.selected,a=e.filter(r=>(r.job===i||i==="any")&&r.trait.name===s);if(a.length===0)return;a.sort((r,o)=>o.rank-r.rank);const n=a[0];!g(t)&&t.trait.name===s&&(t.job===i||i==="any")&&n.rank<=t.rank||(this._host.game.village.makeLeader(n),this._host.engine.iactivity("act.elect"))}autoPromoteKittens(){const e=this._workshopManager.getResource("gold");if(!(this.settings.promoteKittens.trigger<e.value/e.maxValue))for(let t=0;t<this._host.game.village.sim.kittens.length;t++){let i=-1;const s=this._host.game.village.sim.kittens[t].engineerSpeciality;if(!g(s)&&(i=f(this._host.game.workshop.getCraft(s)).tier,!(i<=this._host.game.village.sim.kittens[t].rank))){this._host.game.village.promoteKittens();return}}}autoPromoteLeader(){if(this._host.game.science.get("civil").researched&&this._host.game.village.leader!==null){const e=this._host.game.village.leader,t=e.rank,i=this._workshopManager.getResource("gold"),s=this._workshopManager.getStock("gold");this._host.game.village.sim.goldToPromote(t,t+1,i.value-s)[0]&&this._host.game.village.sim.promote(e,t+1)===1&&(this._host.engine.iactivity("act.promote",[t+1],"ks-promote"),this._host.game.villageTab.censusPanel?.census.renderGovernment(this._host.game.villageTab.censusPanel.census.container),this._host.game.villageTab.censusPanel?.census.update(),this._host.engine.storeForSummary("promote",1))}}autoHunt(e){const t=this._workshopManager.getResource("manpower"),i=this.settings.hunt.trigger;if(!(t.value<100||this._host.game.challenges.isActive("pacifism"))&&i<=t.value/t.maxValue&&100<=t.value){const s=Math.floor(t.value/100);this._host.engine.storeForSummary("hunt",s),this._host.engine.iactivity("act.hunt",[this._host.renderAbsolute(s)],"ks-hunt");const a=this._workshopManager.getAverageHunt(),n={};for(const[r,o]of L(a)){const l=this._workshopManager.getResource(r);n[r]=0<l.maxValue?Math.min(o*s,Math.max(l.maxValue-l.value,0)):o*s}g(e)||e.pushToCache({materials:n,timeStamp:this._host.game.timer.ticksTotal}),this._host.game.village.huntAll()}}autoFestival(e){if(!this._host.game.science.get("drama").researched||400<this._host.game.calendar.festivalDays||!this._host.game.prestige.getPerk("carnivals").researched&&0<this._host.game.calendar.festivalDays)return;const t=this._workshopManager;if(t.getValueAvailable("manpower")<1500||t.getValueAvailable("culture")<5e3||t.getValueAvailable("parchment")<2500)return;const i=4e3*t.getTickVal(t.getResource("manpower"),e,!0)>1500,s=4e3*t.getTickVal(t.getResource("culture"),e,!0)>5e3,a=4e3*t.getTickVal(t.getResource("parchment"),e,!0)>2500;if(!i&&!s&&!a)return;const n=this._host.game.calendar.festivalDays,r=new classes.village.ui.FestivalButtonController(this._host.game),o=r.fetchModel({controller:r,description:"",handler:()=>{this._host.game.village.holdFestival(1)},name:"",prices:[{name:"manpower",val:1500},{name:"culture",val:5e3},{name:"parchment",val:2500}]});r.buyItem(o),this._host.engine.storeForSummary("festival"),n>0?this._host.engine.iactivity("festival.extend",[],"ks-festival"):this._host.engine.iactivity("festival.hold",[],"ks-festival")}}const Li={"de-DE":Ss,"en-US":Cs,"he-IL":xs,"zh-CN":Ts};class te{_i18nData;_isLoaded=!1;get isLoaded(){return this._isLoaded}_host;settings;bonfireManager;religionManager;scienceManager;spaceManager;timeControlManager;timeManager;tradeManager;villageManager;workshopManager;_activitySummary;_timeoutMainLoop=void 0;constructor(e,t){this.settings=new Ei,this._i18nData=Li,this.setLanguage(t,!1),this._host=e,this._activitySummary=new _s(this._host),this.workshopManager=new Ti(this._host),this.bonfireManager=new ks(this._host,this.workshopManager),this.religionManager=new Es(this._host,this.bonfireManager,this.workshopManager),this.scienceManager=new Is(this._host,this.workshopManager),this.spaceManager=new Os(this._host,this.workshopManager),this.timeControlManager=new on(this._host,this.bonfireManager,this.religionManager,this.spaceManager,this.workshopManager),this.timeManager=new ln(this._host,this.workshopManager),this.tradeManager=new cn(this._host,this.workshopManager),this.villageManager=new un(this._host,this.workshopManager)}isLanguageSupported(e){return Object.keys(this._i18nData).some(t=>t.startsWith(`${e}-`))}isLocaleSupported(e){return e in this._i18nData}localeSupportsFirstLetterSplits(e=this.settings.locale.selected){return e!=="zh-CN"}localeForLanguage(e){return Object.keys(this._i18nData).find(t=>t.startsWith(`${e}-`))}setLanguage(e,t=!0){const i=this.settings.locale.selected;if(!this.isLanguageSupported(e))console.warn(...b(`Requested language '${e}' is not available. Falling back to '${we}'.`)),this.settings.locale.selected=we;else{const s=f(this.localeForLanguage(e));console.info(...b(`Selecting language '${s}'.`)),this.settings.locale.selected=s}i!==this.settings.locale.selected&&t&&this._host.rebuildUi()}setLocale(e,t=!0){const i=this.settings.locale.selected;this.isLocaleSupported(e)?(console.info(...b(`Selecting language '${e}'.`)),this.settings.locale.selected=e):(console.warn(...b(`Requested language '${e}' is not available. Falling back to '${we}'.`)),this.settings.locale.selected=we),i!==this.settings.locale.selected&&t&&this._host.rebuildUi()}stateLoad(e,t=!1){this._isLoaded=!0,this.stop(!1);const i=Ae();e.v!==i&&console.warn(...b(`Attempting to load engine state with version tag '${e.v}' when engine is at version '${i}'!`));const s=(a,n)=>{try{a()}catch(r){console.error(...b(`Failed load of ${n} settings.`,r))}};s(()=>{this.settings.load(e.engine,t)},"engine"),s(()=>{this.bonfireManager.settings.load(e.bonfire)},"bonfire"),s(()=>{this.religionManager.settings.load(e.religion)},"religion"),s(()=>{this.scienceManager.settings.load(e.science)},"science"),s(()=>{this.spaceManager.settings.load(e.space)},"space"),s(()=>{this.timeControlManager.settings.load(e.timeControl)},"time control"),s(()=>{this.timeManager.settings.load(e.time)},"time"),s(()=>{this.tradeManager.settings.load(e.trade)},"trade"),s(()=>{this.villageManager.settings.load(e.village)},"village"),s(()=>{this.workshopManager.settings.load(e.workshop)},"workshop"),this.setLocale(this.settings.locale.selected),this.settings.enabled?this.start(!1):this.stop(!1)}static get DEFAULT_STATE(){return{bonfire:new ft,engine:new Ei,religion:new pt,science:new bt,space:new ze,time:new Bi,timeControl:new Ai,trade:new Ii,v:Ae(),village:new $i,workshop:new Fe}}stateReset(){this.stateLoad(te.DEFAULT_STATE)}stateSerialize(){return{bonfire:this.bonfireManager.settings,engine:this.settings,religion:this.religionManager.settings,science:this.scienceManager.settings,space:this.spaceManager.settings,time:this.timeManager.settings,timeControl:this.timeControlManager.settings,trade:this.tradeManager.settings,v:Ae(),village:this.villageManager.settings,workshop:this.workshopManager.settings}}start(e=!0){if(this._timeoutMainLoop)return;const t=()=>{const i={entry:Date.now(),exit:0,measurements:{},purchaseOrders:[],requestGameUiRefresh:!1};this._iterate(i).then(()=>{i.exit=Date.now();const s=i.exit-i.entry;document.dispatchEvent(new CustomEvent("ks.reportFrame",{detail:i})),this._timeoutMainLoop!==void 0&&(this._timeoutMainLoop=x.window.setTimeout(t,Math.max(10,this._host.engine.settings.interval-s)))}).catch(s=>{console.warn(...b(rs(s)))})};this._timeoutMainLoop=x.window.setTimeout(t,this._host.engine.settings.interval),e&&this._host.engine.imessage("status.ks.enable")}stop(e=!0){this._timeoutMainLoop&&(clearTimeout(this._timeoutMainLoop),this._timeoutMainLoop=void 0,e&&this._host.engine.imessage("status.ks.disable"))}async _iterate(e){this.settings.filters.disableKGLog.enabled||this._maintainKGLogFilters();let[,t]=await Le(()=>this.scienceManager.tick(e));e.measurements.scienceManager=t,[,t]=de(()=>{this.bonfireManager.tick(e)}),e.measurements.bonfireManager=t,[,t]=de(()=>{this.spaceManager.tick(e)}),e.measurements.spaceManager=t,[,t]=await Le(()=>this.workshopManager.tick(e)),e.measurements.workshopManager=t,[,t]=de(()=>{this.tradeManager.tick(e)}),e.measurements.tradeManager=t,[,t]=await Le(()=>this.religionManager.tick(e)),e.measurements.religionManager=t,[,t]=de(()=>{this.timeManager.tick(e)}),e.measurements.timeManager=t,[,t]=de(()=>{this.villageManager.tick(e)}),e.measurements.villageManager=t,[,t]=await Le(()=>this.timeControlManager.tick(e)),e.measurements.timeControlManager=t,[,t]=de(()=>{e.requestGameUiRefresh&&!document.hidden&&this._host.game.ui.render()}),e.measurements.gameUiRefresh=t}_maintainKGLogFilters(){for(const t of Object.values(this._host.game.console.filters))t.enabled=!1;const e=x.window.document.querySelectorAll("[id^=filter-]");for(const t of e)t.checked=!1}symbolForCycle(e){return this._host.game.calendar.cycles.find(t=>t.name===e)?.uglyph??""}labelForCycle(e){const t=this.symbolForCycle(e),i=this._host.engine.i18n(`$space.planet.${e==="redmoon"?"moon":e}.label`);return`${t} ${i}`}labelForPlanet(e){const t=e==="moon"?"redmoon":e,i=ge.includes(t)?t:void 0,s=this._host.engine.i18n(`$space.planet.${e}.label`);return i===void 0?s:`${this.symbolForCycle(i)} ${s}`}i18n(e,t=[]){let i;if(e.startsWith("$")&&(i=this._host.i18nEngine(e.slice(1))),i=i??this._i18nData[this.settings.locale.selected][e],g(i)){if(i=Li[we][e],!i)return console.warn(...b(`i18n key '${e}' not found in default language.`)),`$${e}`;console.warn(...b(`i18n key '${e}' not found in selected language.`))}for(let a=0;a<t.length;++a)i=i.replace(`{${a}}`,`${t[a]}`);return i}iactivity(e,t=[],i){const s=this.i18n(e,t);if(i){const a=`type_${i}`;this.printOutput(`ks-activity ${a}`,"#e65C00",s)}else this.printOutput("ks-activity","#e65C00",s)}imessage(e,t=[]){this.printOutput("ks-default","#aa50fe",this.i18n(e,t))}storeForSummary(e,t=1,i="other"){this._activitySummary.storeActivity(e,t,i)}getSummary(){return this._activitySummary.renderSummary()}displayActivitySummary(){const e=this.getSummary();for(const t of e)this.printOutput("ks-summary","#009933",t);this.resetActivitySummary()}resetActivitySummary(){this._activitySummary.resetActivity()}printOutput(e,t,i){if(this.settings.filters.enabled){for(const a of Object.values(this.settings.filters.filters))if(a.variant===e&&!a.enabled)return}const s=this._host.game.msg(i,e);$(s.span).css("color",t)}static evaluateSubSectionTrigger(e,t){return e<0?t:t<0?e:t}}const Oi=c=>Number.isFinite(c)?c:0,dn=c=>({days:Math.trunc(c/864e5),hours:Math.trunc(c/36e5%24),minutes:Math.trunc(c/6e4%60),seconds:Math.trunc(c/1e3%60),milliseconds:Math.trunc(c%1e3),microseconds:Math.trunc(Oi(c*1e3)%1e3),nanoseconds:Math.trunc(Oi(c*1e6)%1e3)}),gn=c=>({days:c/86400000n,hours:c/3600000n%24n,minutes:c/60000n%60n,seconds:c/1000n%60n,milliseconds:c%1000n,microseconds:0n,nanoseconds:0n}),mn=c=>{switch(typeof c){case"number":{if(Number.isFinite(c))return dn(c);break}case"bigint":return gn(c)}throw new TypeError("Expected a finite number or bigint")},fn=c=>c===0||c===0n,pn=(c,e)=>e===1||e===1n?c:`${c}s`,bn=1e-7,vn=24n*60n*60n*1000n,yn=(c,e={colonNotation:!1,compact:!1,formatSubMilliseconds:!1,keepDecimalsOnWholeSeconds:!1,millisecondsDecimalDigits:0,secondsDecimalDigits:1,separateMilliseconds:!1,unitCount:1/0,verbose:!1})=>{const t=typeof c=="bigint";if(!t&&!Number.isFinite(c))throw new TypeError("Expected a finite number or bigint");const i={...e};i.colonNotation&&(i.compact=!1,i.formatSubMilliseconds=!1,i.separateMilliseconds=!1,i.verbose=!1),i.compact&&(i.unitCount=1,i.secondsDecimalDigits=0,i.millisecondsDecimalDigits=0);let s=[];const a=(h,u)=>{const d=Math.floor(h*10**u+bn);return(Math.round(d)/10**u).toFixed(u)},n=(h,u,d,m)=>{if(!((s.length===0||!i.colonNotation)&&fn(h)&&!(i.colonNotation&&d==="m"))){if(m??=String(h),i.colonNotation){const v=m.includes(".")?m.split(".")[0].length:m.length,p=s.length>0?2:1;m="0".repeat(Math.max(0,p-v))+m}else m+=i.verbose?" "+pn(u,h):d;s.push(m)}},r=mn(c),o=BigInt(r.days);if(n(o/365n,"year","y"),n(o%365n,"day","d"),n(Number(r.hours),"hour","h"),n(Number(r.minutes),"minute","m"),i.separateMilliseconds||i.formatSubMilliseconds||!i.colonNotation&&c<1e3){const h=Number(r.seconds),u=Number(r.milliseconds),d=Number(r.microseconds),m=Number(r.nanoseconds);if(n(h,"second","s"),i.formatSubMilliseconds)n(u,"millisecond","ms"),n(d,"microsecond","µs"),n(m,"nanosecond","ns");else{const v=u+d/1e3+m/1e6,p=typeof i.millisecondsDecimalDigits=="number"?i.millisecondsDecimalDigits:0,w=v>=1?Math.round(v):Math.ceil(v),C=p?v.toFixed(p):w.toString();n(Number.parseFloat(C),"millisecond","ms",C)}}else{const h=(t?Number(c%vn):c)/1e3%60,u=typeof i.secondsDecimalDigits=="number"?i.secondsDecimalDigits:1,d=a(h,u),m=i.keepDecimalsOnWholeSeconds?d:d.replace(/\.0+$/,"");n(Number.parseFloat(m),"second","s",m)}if(s.length===0)return"0"+(i.verbose?" milliseconds":"ms");const l=i.colonNotation?":":" ";return typeof i.unitCount=="number"&&(s=s.slice(0,Math.max(i.unitCount,1))),s.join(l)},M={Bonfire:"M80-80v-183l363-491-67-90 49-35 55 75 56-75 48 35-66 90 362 491v183H80Zm400-623L140-243v103h145l195-273 195 273h145v-103L480-703ZM359-140h242L480-310 359-140Zm121-273 195 273-195-273-195 273 195-273Z",CheckboxCheck:"m419-321 289-289-43-43-246 246-119-119-43 43 162 162ZM120-120v-720h720v720H120Zm60-60h600v-600H180v600Zm0 0v-600 600Z",CheckboxUnCheck:"M120-120v-720h720v720H120Zm60-60h600v-600H180v600Z",Copy:"M240-200v-680h560v680H240Zm60-60h440v-560H300v560ZM120-80v-680h60v620h500v60H120Zm180-180v-560 560Z",Cycles:"M120-80v-740h125v-60h65v60h340v-60h65v60h125v360h-60v-110H180v430h324v60H120ZM760 0q-73 0-127.5-45.5T564-160h62q13 44 49.5 72T760-60q58 0 99-41t41-99q0-58-41-99t-99-41q-29 0-54 10.5T662-300h58v60H560v-160h60v57q27-26 63-41.5t77-15.5q83 0 141.5 58.5T960-200q0 83-58.5 141.5T760 0ZM180-630h600v-130H180v130Zm0 0v-130 130Z",DataUsage:"M480-80q-82 0-155-31.5T197.5-197q-54.5-54-86-127T80-479q0-158 106.5-272T451-877v102q-115 11-192 95.5T182-479q0 124 87 210.5T480-182q72 0 136-32.5T725-306l88 51q-58 83-145.5 129T480-80Zm362-229-88-49q12-31 18-61.5t6-60.5q0-116-76.5-201T511-776v-102q157 11 263 124.5T880-484q0 45-9.5 88.5T842-309Z",Delete:"M201-120v-630h-41v-60h188v-30h264v30h188v60h-41v630H201Zm60-60h438v-570H261v570Zm106-86h60v-399h-60v399Zm166 0h60v-399h-60v399ZM261-750v570-570Z",Draft:"M160-80v-800h421l219 219v581H160Zm391-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z",Eco:"M213-175q-43.59-45-68.3-104Q120-338 120-400q0-73 25.5-133.5T222-645q35-35 87-59t122.5-37.5Q502-755 591-758.5t198 3.5q8 108 5.5 197.5t-16 160.75q-13.5 71.25-38 124.56Q716-218.87 680-183q-51 51-110 77T444-80q-69 0-126.5-23.5T213-175Zm103 0q25 17 58 26t69.92 9Q497-140 547-162t91-64q27-27 46-70.5t31-103Q727-459 731-534t0-165q-94-2-168.5 2.5T431-680q-57 12-98 30.5T266-604q-42 43-64 91t-22 98q0 48 20.5 100.5T251-230q53-98 127-176t157-123q-87 75-141 162.5T316-175Zm0 0Zm0 0Z",Edit:"M180-180h44l472-471-44-44-472 471v44Zm-60 60v-128l617-616 128 128-617 616H120Zm659-617-41-41 41 41Zm-105 64-22-22 44 44-22-22Z",ExpandCircleDown:"m480-351 173-173-43-42-130 130-130-130-43 42 173 173Zm0 271q-82 0-155-31.5t-127.5-86Q143-252 111.5-325T80-480q0-83 31.5-156t86-127Q252-817 325-848.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 82-31.5 155T763-197.5q-54 54.5-127 86T480-80Zm0-60q142 0 241-99.5T820-480q0-142-99-241t-241-99q-141 0-240.5 99T140-480q0 141 99.5 240.5T480-140Zm0-340Z",ExpandCircleUp:"m350-394 130-130 130 130 43-42-173-173-173 173 43 42ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-155.5t85.5-127q54-54.5 127-86T480-880q83 0 155.5 31.5t127 86q54.5 54.5 86 127T880-480q0 83-31.5 156t-86 127q-54.5 54-127 85.5T480-80Zm0-60q141 0 240.5-99T820-480q0-141-99.5-240.5T480-820q-142 0-241 99.5T140-480q0 142 99 241t241 99Zm0-340Z",Import:"M450-160v-371L330-411l-43-43 193-193 193 193-43 43-120-120v371h-60ZM160-597v-203h640v203h-60v-143H220v143h-60Z",Religion:"M40-120v-560q0-45.83 32.12-77.92 32.12-32.08 78-32.08T228-757.92q32 32.09 32 77.92v31l220-191 220 191v-31q0-45.83 32.12-77.92 32.12-32.08 78-32.08T888-757.92q32 32.09 32 77.92v560H530v-250H430v250H40Zm720-510h100v-49.82q0-21.18-14.32-35.68-14.33-14.5-35.5-14.5-21.18 0-35.68 14.37Q760-701.25 760-680v50Zm-660 0h100v-49.82q0-21.18-14.32-35.68-14.33-14.5-35.5-14.5-21.18 0-35.68 14.37Q100-701.25 100-680v50Zm0 450h100v-390H100v390Zm160 0h110v-250h220v250h110v-390L480-761 260-570v390Zm500 0h100v-390H760v390ZM479.94-505Q457-505 441-521.06q-16-16.06-16-39T441.06-599q16.06-16 39-16T519-598.94q16 16.06 16 39T518.94-521q-16.06 16-39 16Z",Reset:"M480-160q-133 0-226.5-93.5T160-480q0-133 93.5-226.5T480-800q85 0 149 34.5T740-671v-129h60v254H546v-60h168q-38-60-97-97t-137-37q-109 0-184.5 75.5T220-480q0 109 75.5 184.5T480-220q83 0 152-47.5T728-393h62q-29 105-115 169t-195 64Z",Resources:"M120-40v-880h60v80h600v-80h60v880h-60v-80H180v80h-60Zm60-469h110v-160h220v160h270v-271H180v271Zm0 329h270v-160h220v160h110v-269H180v269Zm170-329h100v-100H350v100Zm160 329h100v-100H510v100ZM350-509h100-100Zm160 329h100-100Z",Save:"M840-683v563H120v-720h563l157 157Zm-60 27L656-780H180v600h600v-476ZM479.76-245q43.24 0 73.74-30.26 30.5-30.27 30.5-73.5 0-43.24-30.26-73.74-30.27-30.5-73.5-30.5-43.24 0-73.74 30.26-30.5 30.27-30.5 73.5 0 43.24 30.26 73.74 30.27 30.5 73.5 30.5ZM233-584h358v-143H233v143Zm-53-72v476-600 124Z",SaveAs:"M120-120v-720h563l157 157v117l-60 60v-150L656-780H180v600h280v60H120Zm60-660v600-600ZM520-40v-123l263-262 122 122L643-40H520Zm300-263-37-37 37 37ZM580-100h38l121-122-18-19-19-18-122 121v38Zm141-141-19-18 37 37-18-19ZM233-584h358v-143H233v143Zm247 339q14 0 27-3t24-10l39-40q7-11 10.5-24t3.5-27q0-43.33-30.26-73.67Q523.47-453 480.24-453q-43.24 0-73.74 30.26-30.5 30.27-30.5 73.5 0 43.24 30.33 73.74Q436.67-245 480-245Z",Seasons:"M306-394q-17 0-28.5-11.5T266-434q0-17 11.5-28.5T306-474q17 0 28.5 11.5T346-434q0 17-11.5 28.5T306-394Zm177 0q-17 0-28.5-11.5T443-434q0-17 11.5-28.5T483-474q17 0 28.5 11.5T523-434q0 17-11.5 28.5T483-394Zm170 0q-17 0-28.5-11.5T613-434q0-17 11.5-28.5T653-474q17 0 28.5 11.5T693-434q0 17-11.5 28.5T653-394ZM120-80v-740h125v-60h65v60h340v-60h65v60h125v740H120Zm60-60h600v-430H180v430Zm0-490h600v-130H180v130Zm0 0v-130 130Z",Settings:"m388-80-20-126q-19-7-40-19t-37-25l-118 54-93-164 108-79q-2-9-2.5-20.5T185-480q0-9 .5-20.5T188-521L80-600l93-164 118 54q16-13 37-25t40-18l20-127h184l20 126q19 7 40.5 18.5T669-710l118-54 93 164-108 77q2 10 2.5 21.5t.5 21.5q0 10-.5 21t-2.5 21l108 78-93 164-118-54q-16 13-36.5 25.5T592-206L572-80H388Zm48-60h88l14-112q33-8 62.5-25t53.5-41l106 46 40-72-94-69q4-17 6.5-33.5T715-480q0-17-2-33.5t-7-33.5l94-69-40-72-106 46q-23-26-52-43.5T538-708l-14-112h-88l-14 112q-34 7-63.5 24T306-642l-106-46-40 72 94 69q-4 17-6.5 33.5T245-480q0 17 2.5 33.5T254-413l-94 69 40 72 106-46q24 24 53.5 41t62.5 25l14 112Zm44-210q54 0 92-38t38-92q0-54-38-92t-92-38q-54 0-92 38t-38 92q0 54 38 92t92 38Zm0-130Z",Space:"m187-551 106 45q18-36 38.5-71t43.5-67l-79-16-109 109Zm154 81 133 133q57-26 107-59t81-64q81-81 119-166t41-192q-107 3-192 41T464-658q-31 31-64 81t-59 107Zm229-96q-20-20-20-49.5t20-49.5q20-20 49.5-20t49.5 20q20 20 20 49.5T669-566q-20 20-49.5 20T570-566Zm-15 383 109-109-16-79q-32 23-67 43.5T510-289l45 106Zm326-694q9 136-34 248T705-418l-2 2-2 2 22 110q3 15-1.5 29T706-250L535-78l-85-198-170-170-198-85 172-171q11-11 25-15.5t29-1.5l110 22q1-1 2-1.5t2-1.5q99-99 211-142.5T881-877ZM149-325q35-35 85.5-35.5T320-326q35 35 34.5 85.5T319-155q-26 26-80.5 43T75-80q15-109 31.5-164t42.5-81Zm42 43q-14 15-25 47t-19 82q50-8 82-19t47-25q19-17 19.5-42.5T278-284q-19-18-44.5-17.5T191-282Z",State:"M820-240v-480h60v480h-60Zm-340 1-43-42 169-169H80v-60h526L438-679l42-42 241 241-241 241Z",Summary:"M279-621h60v-60h-60v60Zm0 171h60v-60h-60v60Zm0 171h60v-60h-60v60ZM120-120v-720h522l198 198v522H120Zm60-60h600v-429H609v-171H180v600Zm0-600v171.43V-780v600-600Z",Sync:"M167-160v-60h130l-15-12q-64-51-93-111t-29-134q0-106 62.5-190.5T387-784v62q-75 29-121 96.5T220-477q0 63 23.5 109.5T307-287l30 21v-124h60v230H167Zm407-15v-63q76-29 121-96.5T740-483q0-48-23.5-97.5T655-668l-29-26v124h-60v-230h230v60H665l15 14q60 56 90 120t30 123q0 106-62 191T574-175Z",Time:"m627-287 45-45-159-160v-201h-60v225l174 181ZM480-80q-82 0-155-31.5t-127.5-86Q143-252 111.5-325T80-480q0-82 31.5-155t86-127.5Q252-817 325-848.5T480-880q82 0 155 31.5t127.5 86Q817-708 848.5-635T880-480q0 82-31.5 155t-86 127.5Q708-143 635-111.5T480-80Zm0-400Zm0 340q140 0 240-100t100-240q0-140-100-240T480-820q-140 0-240 100T140-480q0 140 100 240t240 100Z",Trigger:"m393-165 279-335H492l36-286-253 366h154l-36 255Zm-73 85 40-280H160l360-520h80l-40 320h240L400-80h-80Zm154-396Z",Workshop:"M768-120 517-371l57-57 251 251-57 57Zm-581 0-57-57 290-290-107-107-23 23-44-44v85l-24 24-122-122 24-24h86l-48-48 131-131q17-17 37-23t44-6q24 0 44 8.5t37 25.5L348-699l48 48-24 24 104 104 122-122q-8-13-12.5-30t-4.5-36q0-53 38.5-91.5T711-841q15 0 25.5 3t17.5 8l-85 85 75 75 85-85q5 8 8.5 19.5T841-709q0 53-38.5 91.5T711-579q-18 0-31-2.5t-24-7.5L187-120Z"};class N{static nextComponentId=0;componentId;host;parent;options;_element;set element(e){this._element=e,this._element[0].id=`KS${Object.getPrototypeOf(this).constructor.name}#${this.componentId}`}get element(){return f(this._element)}children=new Set;constructor(e,t){this.componentId=N.nextComponentId++,this.host=e.host,this.options=t,this.parent=e instanceof N?e:null,this._needsRefresh=!1}_needsRefresh;requestRefresh(e=!1,t=0,i=!1){if(i&&console.debug(...b(t<0?"⤒".repeat(t*-1):" ".repeat(t),this.toString(),"requestRefresh()")),this.options?.onRefreshRequest?.call(this),this.parent!==this&&!e&&this.parent?.requestRefresh(!1,t-1,i),this._needsRefresh&&i&&console.debug(...b(t<0?"⤒".repeat(t*-1):" ".repeat(t),this.toString(),"requestRefresh() <already pending>")),this._needsRefresh=!0,e){i&&console.debug(...b(t<0?"⤒".repeat(t*-1):" ".repeat(t),this.toString(),"requestRefresh()",`+ ${this.children.size} children`));for(const s of this.children)s.requestRefresh(!0,t+1,i)}else i&&console.debug(...b(t<0?"⤒".repeat(t*-1):" ".repeat(t),this.toString(),"requestRefresh()","<queued>"))}refresh(e=!1,t=0){if(!e&&!this._needsRefresh){t===0&&console.debug(...b(this.toString(),"refresh() received and ignored."));return}this.options?.onRefresh?.call(this);for(const i of this.children)i.refresh(e,t+1);this._needsRefresh=!1}addChild(e){return e.parent=this,this.children.add(e),this.element.append(e.element),this}addChildren(e){for(const t of e??[])this.addChild(t);return this}removeChild(e){this.children.has(e)&&(e.element.remove(),this.children.delete(e))}removeChildren(e){for(const t of e)this.removeChild(t)}}class E extends N{constructor(e,t){super(e,{...t}),this.element=$("<div/>");for(const i of t?.classes??[])this.element.addClass(i)}toString(){return`[${E.name}#${this.componentId}]`}}const R={label:"_label_1nlev_1",splitter:"_splitter_1nlev_16",iconLabel:"_iconLabel_1nlev_20",fillSpace:"_fillSpace_1nlev_26"},me={delimiter:"_delimiter_16hnh_1"};class ne extends N{constructor(e,t){super(e,{...t}),this.element=$("<li/>");for(const i of t?.classes??[])this.element.addClass(i);t?.delimiter===!0&&this.element.addClass(me.delimiter)}toString(){return`[${ne.name}#${this.componentId}]`}}const We={head:"_head_wr1pj_1"};class ae extends ne{head;elementLabel;constructor(e,t,i){if(super(e,i),this.head=new E(e),this.head.element.addClass(We.head),this.addChild(this.head),this.elementLabel=$("<label/>",{text:`${i?.upgradeIndicator===!0?"⮤ ":""}${t}`}).addClass(R.label).addClass(We.label),this.head.element.append(this.elementLabel),i?.icon){const s=$("<div/>",{html:`<svg style="width: 15px; height: 15px;" viewBox="0 -960 960 960" fill="currentColor"><path d="${i.icon}"/></svg>`}).addClass(R.iconLabel);this.elementLabel.prepend(s)}}toString(){return`[${ae.name}#${this.componentId}]: '${this.elementLabel.text()}'`}addChildHead(e){return this.head.addChild(e),this}addChildrenHead(e){for(const t of e??[])this.head.addChild(t);return this}}const P={setting:"_setting_1ndg5_1",checkbox:"_checkbox_1ndg5_6",panelContent:"_panelContent_1ndg5_10",hidden:"_hidden_1ndg5_17",checked:"_checked_1ndg5_22",expanded:"_expanded_1ndg5_26",readonly:"_readonly_1ndg5_34"};class _ extends ae{setting;checkbox;readOnly;constructor(e,t,i,s){super(e,i,{...s,onRefresh:()=>{this.setting.enabled?this.element.addClass(P.checked):this.element.removeClass(P.checked),this.readOnly?this.element.addClass(P.readonly):this.element.removeClass(P.readonly),g(this.checkbox)||(this.checkbox.prop("checked",this.setting.enabled),this.checkbox.prop("disabled",this.readOnly)),s?.onRefresh?.()}}),this.element.addClass(P.setting);const a=`ks-setting${this.componentId}`,n=$("<input/>",{id:a,type:"checkbox"}).addClass(P.checkbox);this.readOnly=s?.readOnly??!1,n.prop("disabled",this.readOnly),n.on("change",r=>{n.is(":checked")&&!t.enabled?this.check().catch(H(console)):!n.is(":checked")&&t.enabled&&this.uncheck().catch(H(console))}),this.elementLabel.before(n),this.elementLabel.prop("for",a),this.checkbox=n,this.setting=t}toString(){return`[${_.name}#${this.componentId}]: '${this.elementLabel.text()}'`}async check(e=!1){this.setting.enabled=!0,await this.options?.onCheck?.call(e),this.requestRefresh()}async uncheck(e=!1){this.setting.enabled=!1,await this.options.onUnCheck?.call(e),this.requestRefresh()}}const k={iconButton:"_iconButton_q7zpt_17",inactive:"_inactive_q7zpt_29",ineffective:"_ineffective_q7zpt_37",button:"_button_q7zpt_43",readonly:"_readonly_q7zpt_67",buttonIcon:"_buttonIcon_q7zpt_72",alignRight:"_alignRight_q7zpt_77",large:"_large_q7zpt_81",bordered:"_bordered_q7zpt_85",headAction:"_headAction_q7zpt_97",lastHeadAction:"_lastHeadAction_q7zpt_100",consumeButton:"_consumeButton_q7zpt_104",stockButton:"_stockButton_q7zpt_107"};class J extends N{readOnly;inactive;constructor(e,t,i,s){super(e,{...s,onRefresh:()=>{this.readOnly?this.element.addClass(k.readonly):this.element.removeClass(k.readonly),this.inactive?this.element.addClass(k.inactive):this.element.removeClass(k.inactive),s?.onRefresh?.()}}),this.element=$("<div/>",{html:`<svg style="width: 18px; height: 18px;" viewBox="0 -960 960 960" fill="currentColor"><path d="${t}"/></svg>`,title:i}).addClass(k.iconButton),this.readOnly=s?.readOnly??!1,this.inactive=s?.inactive??!1,this.element.on("click",()=>{this.readOnly||this.click().catch(H(console))})}toString(){return`[${J.name}#${this.componentId}]`}async click(){this.readOnly||(await this.options?.onClick?.call(this),this.requestRefresh())}}const Ge={listContainer:"_listContainer_1kxbq_1",itemsList:"_itemsList_1kxbq_5",list:"_list_1kxbq_1",listTools:"_listTools_1kxbq_9"};class S extends N{list;disableAllButton;enableAllButton;resetButton;constructor(e,t){super(e,{...t});const i={hasDisableAll:!0,hasEnableAll:!0,...t},s=i.hasDisableAll||i.hasEnableAll||!g(i.onReset);if(this.element=$("<div/>").addClass(Ge.listContainer),this.list=$("<ul/>").addClass(Ge.list).addClass(Ge.itemsList),this.element.append(this.list),s){const a=new E(this,{classes:[Ge.listTools]});i.hasEnableAll&&(this.enableAllButton=new J(e,M.CheckboxCheck,e.host.engine.i18n("ui.enable.all"),{onClick:async()=>{const r=new Event("enableAll",{cancelable:!0});if(this.element[0].dispatchEvent(r),!r.defaultPrevented){for(const o of this.children)Pe(o,_)&&await o.check(!0);t?.onEnableAll?.call(this)}}}),a.addChild(this.enableAllButton)),i.hasDisableAll&&(this.disableAllButton=new J(e,M.CheckboxUnCheck,e.host.engine.i18n("ui.disable.all"),{onClick:async()=>{const r=new Event("disableAll",{cancelable:!0});if(this.element[0].dispatchEvent(r),!r.defaultPrevented){for(const o of this.children)Pe(o,_)&&await o.uncheck(!0);t?.onDisableAll?.call(this)}}}),a.addChild(this.disableAllButton));const n=i.onReset;g(n)||(this.resetButton=new J(e,M.Reset,e.host.engine.i18n("ui.reset"),{onClick:()=>{n()}}),a.addChild(this.resetButton)),super.addChild(a)}}toString(){return`[${S.name}#${this.componentId}]`}addChild(e){return e.parent=this,this.children.add(e),this.list.append(e.element),this}}const xe={expandoButton:"_expandoButton_l1ukp_1",expanded:"_expanded_l1ukp_1",up:"_up_l1ukp_1",down:"_down_l1ukp_4"};class Ze extends N{readOnly;inactive;ineffective;constructor(e,t){super(e,{...t,onRefresh:()=>{this.ineffective?this.element.addClass(k.ineffective):this.element.removeClass(k.ineffective),t?.onRefresh?.()}}),this.element=$("<div/>",{html:`
|
|
17
|
+
If you submit an invalid value, it will be treated as if you hit Cancel.`,"ui.trigger.setinteger":"输入 {0} 的新触发值。范围应在 0 到任意数字之间。-1表示无穷大。","ui.trigger.setinteger.promptExplainer":"如果您提交一个空值或者一个无效值,则被视为您点击了取消。","ui.trigger.setpercentage":"输入新的 {0} 触发值,取值范围为 0 到 100 的小数。","ui.trigger.setpercentage.promptExplainer":"如果您提交一个空值或者一个无效值,则被视为您点击了取消。","ui.trigger.timeSkip.prompt":"输入跳过时间所需的时间水晶的新数量,以 1 到无穷大之间的绝对值表示。","ui.trigger.timeSkip.promptExplainer":"如果您提交了负值,时间跳过将被禁用。如果您提交了空值或无效值,它将被视为您点击了“取消”。","ui.trigger.timeSkip.promptTitle":"时间跳跃触发值 (当前:{0})","ui.upgrade":"升级","ui.upgrade.buildings":"升级建筑","ui.upgrade.missions":"探索星球","ui.upgrade.policies":"政策","ui.upgrade.races":"探险队出发!","ui.upgrade.techs":"科技","ui.upgrade.upgrades":"升级","ui.upgrades":"升级",update:"更新","upgrade.building.amphitheatre":"剧场 升级为 广播塔!","upgrade.building.aqueduct":"水渠 升级为 水电站!","upgrade.building.library":"图书馆 升级为 数据中心!","upgrade.building.pasture":"牧场 升级为 太阳能发电站!","upgrade.building.warehouse":"已将仓库升级为太空港!","upgrade.policy":"小猫通过了 {0} 法案","upgrade.race":"小猫遇到了 {0}","upgrade.space":"小猫执行了 {0}","upgrade.space.mission":"小猫执行了 {0} 的任务","upgrade.tech":"小猫掌握了 {0}","upgrade.upgrade":"小猫发明了 {0}"};class qe extends Ne{#e;#t;get building(){return this.#e}get variant(){return this.#t}constructor(e,t,i=!1){super(i),this.#e=e,this.#t=t}}class pt extends F{buildings;bestUnicornBuilding;bestUnicornBuildingCurrent;sacrificeAlicorns;sacrificeUnicorns;refineTears;refineTimeCrystals;autoPraise;adore;transcend;constructor(e=!1,t=-1,i=new y,s=new ee(!1,-1),a=new ee(!1,-1),n=new ee(!1,-1),r=new ee(!1,-1),o=new F(!1,1),l=new F(!1,1),h=new y){super(e,t),this.buildings=this.initBuildings(),this.bestUnicornBuilding=i,this.sacrificeAlicorns=s,this.sacrificeUnicorns=a,this.refineTears=n,this.refineTimeCrystals=r,this.autoPraise=o,this.adore=l,this.transcend=h,this.bestUnicornBuildingCurrent=null}initBuildings(){const e={};for(const t of ci)e[t]=new qe(t,U.OrderOfTheSun);for(const t of hi)e[t]=new qe(t,U.Cryptotheology);for(const t of ui)e[t]=new qe(t,U.Ziggurat);return e.unicornPasture=new qe("unicornPasture",U.UnicornPasture),e}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.max=i?.max??t.max,t.trigger=i?.trigger??t.trigger}),this.bestUnicornBuilding.load(e.bestUnicornBuilding),this.sacrificeAlicorns.load(e.sacrificeAlicorns),this.sacrificeUnicorns.load(e.sacrificeUnicorns),this.refineTears.load(e.refineTears),this.refineTimeCrystals.load(e.refineTimeCrystals),this.autoPraise.load(e.autoPraise),this.adore.load(e.adore),this.transcend.load(e.transcend),this.bestUnicornBuildingCurrent=e.bestUnicornBuildingCurrent??this.bestUnicornBuildingCurrent)}}class Es{_host;settings;_bulkManager;_bonfireManager;_workshopManager;constructor(e,t,i,s=new pt){this._host=e,this.settings=s,this._workshopManager=i,this._bulkManager=new Ue(this._host,this._workshopManager),this._bonfireManager=t}async tick(e){this.settings.enabled&&(this._autoBuild(e),this.settings.sacrificeUnicorns.enabled&&await this._autoSacrificeUnicorns(),this.settings.sacrificeAlicorns.enabled&&await this._autoSacrificeAlicorns(e),this.settings.refineTears.enabled&&this._autoTears(e),this.settings.refineTimeCrystals.enabled&&await this._autoTCs(e),this._autoTAP())}_autoBuild(e){if(this.settings.bestUnicornBuilding.enabled)this._buildBestUnicornBuilding(),this._buildNonUnicornBuildings(e);else{const t=Object.fromEntries(Object.entries(this.settings.buildings).filter(([,a])=>a.variant!==U.UnicornPasture)),i=Z(this.settings.buildings.unicornPasture.max),s=this._host.game.bld.getBuildingExt("unicornPasture").meta;this.settings.buildings.unicornPasture.enabled&&s.val<i&&this._bonfireManager.autoBuild(e,{unicornPasture:new mt("unicornPasture",this.settings.buildings.unicornPasture.enabled,this.settings.buildings.unicornPasture.trigger,this.settings.buildings.unicornPasture.max)}),this._buildReligionBuildings(e,t)}}_buildBestUnicornBuilding(){const e=this.getBestUnicornBuilding();if(this.settings.bestUnicornBuildingCurrent!==e&&(this.settings.bestUnicornBuildingCurrent=e,this._host.refreshEntireUserInterface()),this.settings.bestUnicornBuildingCurrent===null)return;const t=this.settings.trigger;if(this.settings.bestUnicornBuildingCurrent==="unicornPasture")this._bonfireManager.build(this.settings.bestUnicornBuildingCurrent,0,1);else{const i=this._getBuild(this.settings.bestUnicornBuildingCurrent,U.Ziggurat);let s=0;const a=f(i.model.prices).find(l=>l.name==="tears");g(a)||(s=a.val);const n=this._workshopManager.getValue("tears")-this._workshopManager.getStock("tears");if(n<s){const l=Math.floor((this._workshopManager.getValue("unicorns")-this._workshopManager.getStock("unicorns"))/2500),h=Math.ceil((s-n)/this._host.game.bld.getBuildingExt("ziggurat").meta.on),u=this._host.game.bld.get("ziggurat").on;if(h<l&&0<u){const d=new classes.ui.religion.TransformBtnController(this._host.game,{applyAtGain:v=>{this._host.game.stats.getStat("unicornsSacrificed").val+=v},gainedResource:"tears",gainMultiplier:()=>this._host.game.bld.get("ziggurat").on,logfilterID:"unicornSacrifice",logTextID:"religion.sacrificeBtn.sacrifice.msg",overcapMsgID:"religion.sacrificeBtn.sacrifice.msg.overcap"}),m=d.fetchModel({controller:d,description:"",name:"",prices:[{name:"unicorns",val:2500}]});d._transform(m,h)}else return}const r={[this.settings.bestUnicornBuildingCurrent]:this.settings.buildings[this.settings.bestUnicornBuildingCurrent]},o=this._bulkManager.bulk(r,this.getBuildMetaData(r),t,"Religion");0<o.length&&0<o[0].count&&this.build(this.settings.bestUnicornBuildingCurrent,U.Ziggurat,1)}}_buildNonUnicornBuildings(e){const t=[...De],i=Object.fromEntries(Object.entries(this.settings.buildings).filter(([,s])=>!t.includes(s.building)));this._buildReligionBuildings(e,i)}_buildReligionBuildings(e,t){const i=this.getBuildMetaData(t),s=this.settings.trigger,a=this._bulkManager.bulk(t,i,s,"Religion");for(const n of a)0<n.count&&(this.build(n.id,f(n.variant),n.count),e.requestGameUiRefresh=!0)}getBestUnicornBuilding(){const e=this._bonfireManager.getBuild("unicornPasture"),t=[...De].filter(j=>j!=="unicornPasture"),i=this._host.game.getEffect("unicornsPerTickBase")*this._host.game.getTicksPerSecondUI(),s=this._host.game.getEffect("unicornsGlobalRatio")+1,a=this._host.game.getEffect("unicornsRatioReligion")+1,n=this._host.game.prestige.getParagonProductionRatio()+1,r=this._host.game.religion.getSolarRevolutionRatio()+1,o=this._host.game.calendar.cycle,l=this._host.game.calendar.cycles[o];let h=1;l.festivalEffects.unicorns!==void 0&&this._host.game.prestige.getPerk("numeromancy").researched&&this._host.game.calendar.festivalDays&&(h=l.festivalEffects.unicorns);const u=i*s*a*n*r*h,d=Math.max(this._host.game.bld.getBuildingExt("ziggurat").meta.on,1),m=500*(1+this._host.game.getEffect("unicornsRatioReligion")*.1);let v=1;this._host.game.prestige.getPerk("unicornmancy").researched&&(v*=1.1);const p=this._host.game.getEffect("riftChance")*v/(1e4*2)*m;let w=Number.POSITIVE_INFINITY,C=null;const oe=f(this._host.game.bld.getBuildingExt("unicornPasture").meta.effects?.unicornsPerTickBase)*this._host.game.getTicksPerSecondUI()*s*a*n*r*h,K=f(e.model?.prices)[0].val/oe;K<w&&(w=K,C="unicornPasture");for(const j of t){const he=this._getBuild(j,U.Ziggurat);if(!he.model.metadata.unlocked)continue;let Y=0;for(const ve of f(he.model.prices))ve.name==="unicorns"&&(Y+=ve.val),ve.name==="tears"&&(Y+=ve.val*2500/d);const be=f(this._host.game.religion.getZU(j));let Ce=a,st=this._host.game.getEffect("riftChance");for(const ve in be.effects)ve==="unicornsRatioReligion"&&(Ce+=f(be.effects.unicornsRatioReligion)),ve==="riftChance"&&(st+=f(be.effects.riftChance));const ho=500*((Ce-1)*.1+1);let Kt=st*v/(1e4*2)*ho;Kt-=p;let Vt=i*s*Ce*n*r*h;Vt-=u,Vt+=Kt;const Xi=Y/Vt;Xi<w&&(0<Kt||a<Ce&&0<Y)&&(w=Xi,C=j)}return C}build(e,t,i){let s=i;const a=s;let n;if(t===U.Cryptotheology){const r=game.getUnlockByName(e,"transcendenceUpgrades"),o=new classes.ui.TranscendenceBtnController(this._host.game),l=o.fetchModel({controller:o,id:r.name});s=this._bulkManager.construct(l,o,s),n=r.label}else if(t===U.OrderOfTheSun){const r=game.getUnlockByName(e,"religion"),o=new com.nuclearunicorn.game.ui.ReligionBtnController(this._host.game),l=o.fetchModel({controller:o,id:r.name});s=this._bulkManager.construct(l,o,s),n=r.label}else if(t===U.Ziggurat){const r=game.getUnlockByName(e,"zigguratUpgrades"),o=new com.nuclearunicorn.game.ui.ZigguratBtnController(this._host.game),l=o.fetchModel({controller:o,id:r.name});s=this._bulkManager.construct(l,o,s),n=r.label}else throw new Ie("unsupported");s!==a&&(console.warn(...b(`${n} Amount ordered: ${a} Amount Constructed: ${s}`)),s===0)||(t===U.OrderOfTheSun?(this._host.engine.storeForSummary(n,s,"faith"),s===1?this._host.engine.iactivity("act.sun.discover",[n],"ks-faith"):this._host.engine.iactivity("act.sun.discovers",[n,this._host.renderAbsolute(s)],"ks-faith")):(this._host.engine.storeForSummary(n,s,"build"),s===1?this._host.engine.iactivity("act.build",[n],"ks-build"):this._host.engine.iactivity("act.builds",[n,this._host.renderAbsolute(s)],"ks-build")))}getBuildMetaData(e){const t={};for(const i of Object.values(e)){const s=this.getUpgradeMeta(i.building,i.variant);if(s===null)continue;t[i.building]=s;const a=f(t[i.building]);if(!this._getBuild(i.building,i.variant))a.rHidden=!0;else{const n=f(this._getBuild(i.building,i.variant)).model,r=i.variant===U.Cryptotheology?this._host.game.science.get("cryptotheology").researched:!0;a.rHidden=!(n?.visible&&n.enabled&&r)}}return t}getUpgradeMeta(e,t){switch(t){case U.Ziggurat:return this._host.game.religion.getZU(e)??null;case U.OrderOfTheSun:return this._host.game.religion.getRU(e)??null;case U.Cryptotheology:return this._host.game.religion.getTU(e)??null}throw new Error(`Unknown build: ${e} (${t})`)}_getBuild(e,t){switch(t){case U.Ziggurat:return this._host.game.time.queue.getQueueElementControllerAndModel({name:e,type:"zigguratUpgrades"});case U.OrderOfTheSun:return this._host.game.time.queue.getQueueElementControllerAndModel({name:e,type:"religion"});case U.Cryptotheology:return this._host.game.time.queue.getQueueElementControllerAndModel({name:e,type:"transcendenceUpgrades"});default:throw new Error(`Invalid variant '${t}'`)}}_transformBtnSacrificeHelper(e,t,i,s){const n=1/(e/t),o=new classes.ui.religion.TransformBtnController(game,i.controllerOpts)._newLink(s,n);return new Promise(l=>{o.handler(new Event("decoy"),l)})}async _autoSacrificeUnicorns(){const e=this._workshopManager.getResource("unicorns"),t=this._workshopManager.getValueAvailable("unicorns");if(!g(this._host.game.religionTab.sacrificeBtn)&&Z(this.settings.sacrificeUnicorns.trigger)<=t&&Z(this.settings.sacrificeUnicorns.trigger)<=e.value){const i=this._host.game.religionTab.sacrificeBtn.controller,s=this._host.game.religionTab.sacrificeBtn.model;if(g(s))return;await this._transformBtnSacrificeHelper(t,e.value,i,s);const a=this._workshopManager.getValueAvailable("unicorns"),n=t-a;this._host.engine.iactivity("act.sacrificeUnicorns",[this._host.game.getDisplayValueExt(n)],"ks-faith"),this._host.engine.storeForSummary(this._host.engine.i18n("$resources.unicorns.title"),n,"refine")}}async _autoSacrificeAlicorns(e){const t=this._workshopManager.getResource("alicorn"),i=this._workshopManager.getValueAvailable("alicorn");if(!g(this._host.game.religionTab.sacrificeAlicornsBtn)&&Z(this.settings.sacrificeAlicorns.trigger)<=i&&Z(this.settings.sacrificeAlicorns.trigger)<=t.value){this._host.game.religionTab.sacrificeAlicornsBtn.render();const s=this._host.game.religionTab.sacrificeAlicornsBtn.controller,a=this._host.game.religionTab.sacrificeAlicornsBtn.model;if(g(a)){e.requestGameUiRefresh=!0;return}await this._transformBtnSacrificeHelper(i,t.value,s,a);const n=this._workshopManager.getValueAvailable("alicorn"),r=i-n;this._host.engine.iactivity("act.sacrificeAlicorns",[this._host.game.getDisplayValueExt(r)],"ks-faith"),this._host.engine.storeForSummary(this._host.engine.i18n("$resources.alicorn.title"),r,"refine")}}_autoTears(e){const t=this._workshopManager.getResource("tears"),i=this._workshopManager.getValueAvailable("tears"),s=this._workshopManager.getResource("sorrow");if(!g(this._host.game.religionTab.refineBtn)&&Z(this.settings.refineTears.trigger)<=i&&Z(this.settings.refineTears.trigger)<=t.value&&s.value<s.maxValue){const a=i-this.settings.refineTears.trigger;if(a<1e4)return;const n=this._host.game.religionTab.refineBtn.controller,r=this._host.game.religionTab.refineBtn.model;if(g(r)){e.requestGameUiRefresh=!0;return}n.buyItem(r,new Event("decoy"),a);const o=this._workshopManager.getValueAvailable("tears"),l=i-o;this._host.engine.iactivity("act.refineTears",[this._host.game.getDisplayValueExt(l)],"ks-faith"),this._host.engine.storeForSummary(this._host.engine.i18n("$resources.tears.title"),l,"refine")}}async _autoTCs(e){const t=this._workshopManager.getResource("timeCrystal"),i=this._workshopManager.getValueAvailable("timeCrystal");if(!g(this._host.game.religionTab.refineTCBtn)&&Z(this.settings.refineTimeCrystals.trigger)<=i&&Z(this.settings.refineTimeCrystals.trigger)<=t.value){const s=this._host.game.religionTab.refineTCBtn.controller,a=this._host.game.religionTab.refineTCBtn.model;if(g(a)){e.requestGameUiRefresh=!0;return}await this._transformBtnSacrificeHelper(i,t.value,s,a);const n=this._workshopManager.getValueAvailable("timeCrystal"),r=i-n;this._host.engine.iactivity("act.refineTCs",[this._host.game.getDisplayValueExt(r)],"ks-faith"),this._host.engine.storeForSummary(this._host.engine.i18n("$resources.timeCrystal.title"),r,"refine")}}_autoTAP(){const e=this._workshopManager.getResource("faith"),t=e.value/e.maxValue;this.settings.transcend.enabled&&this.settings.autoPraise.trigger-.02<=t&&this._autoTranscend(),this.settings.autoPraise.trigger<=t&&(this.settings.adore.enabled&&f(this._host.game.religion.getRU("apocripha")).on&&this._autoAdore(this.settings.adore.trigger),this.settings.autoPraise.enabled&&this._autoPraise())}_autoAdore(e){const t=this._workshopManager.getResource("faith"),i=this._host.game.religion.faith,s=this._host.game.religion.faithRatio,n=f(this._host.game.religion.getRU("transcendence")).on?this._host.game.religion.transcendenceTier:0,r=10+this._host.game.getEffect("solarRevolutionLimit"),o=r*e,l=i/1e6*n*n*1.01,h=s+l,u=.01+t.value*(1+this._host.game.getUnlimitedDR(h,.1)*.1),d=this._host.game.getLimitedDR(this._host.game.getUnlimitedDR(u,1e3)/100,r);o<=d&&(this._host.game.religion._resetFaithInternal(1.01),this._host.engine.iactivity("act.adore",[this._host.game.getDisplayValueExt(i),this._host.game.getDisplayValueExt(l)],"ks-adore"),this._host.engine.storeForSummary("adore",l))}_autoTranscend(){let e=this._host.game.religion.faithRatio;const t=f(this._host.game.religion.getRU("transcendence")).on;let i=t?this._host.game.religion.transcendenceTier:0;if(t){const s=((i+2)/(i+1))**2,a=this._host.game.religion._getTranscendTotalPrice(i+1)-this._host.game.religion._getTranscendTotalPrice(i),n=a,r=s;if((1-r+Math.sqrt(80*(r*r-1)*n+(r-1)*(r-1)))*r/(40*(r+1)*(r+1)*(r-1))+n+n/(r*r-1)<=e){this._host.game.religion.faithRatio-=a,this._host.game.religion.tcratio+=a,this._host.game.religion.transcendenceTier+=1;const l=f(this._host.game.challenges.getChallenge("atheism"));l.calculateEffects?.(l,this._host.game);const h=f(this._host.game.religion.getTU("blackObelisk"));h.calculateEffects?.(h,this._host.game),this._host.game.msg(this._host.engine.i18n("$religion.transcend.msg.success",[this._host.game.religion.transcendenceTier])),e=this._host.game.religion.faithRatio,i=this._host.game.religion.transcendenceTier,this._host.engine.iactivity("act.transcend",[this._host.game.getDisplayValueExt(a),i],"ks-transcend"),this._host.engine.storeForSummary("transcend",1)}}}_autoPraise(){const e=this._workshopManager.getResource("faith"),t=this._host.game.religion.getApocryphaBonus(),i=e.value*(1+t);this._host.engine.storeForSummary("praise",i),this._host.engine.iactivity("act.praise",[this._host.game.getDisplayValueExt(e.value),this._host.game.getDisplayValueExt(i)],"ks-praise"),this._host.game.religion.praise()}}class Rs extends y{#e;get policy(){return this.#e}constructor(e,t=!1){super(t),this.#e=e}}class wi extends y{policies;constructor(e=!1){super(e),this.policies=this.initPolicies()}initPolicies(){const e={};for(const t of hs)e[t]=new Rs(t);return e}static validateGame(e,t){const i=Object.keys(t.policies),s=e.science.policies.map(r=>r.name),a=Q(s,i),n=Q(i,s);for(const r of a)console.warn(...b(`The policy '${r}' is not tracked in Kitten Scientists!`));for(const r of n)console.warn(...b(`The policy '${r}' is not a policy in Kittens Game!`))}load(e){g(e)||(super.load(e),O(this.policies,e.policies,(t,i)=>{t.enabled=i?.enabled??t.enabled}))}}class Ms extends F{#e;get tech(){return this.#e}constructor(e,t=!1){super(t,-1),this.#e=e}}class ki extends F{techs;constructor(e=!1){super(e,-1),this.techs=this.initTechs()}initTechs(){const e={};for(const t of us)e[t]=new Ms(t);return e}static validateGame(e,t){const i=Object.keys(t.techs),s=e.science.techs.map(r=>r.name),a=Q(s,i),n=Q(i,s);for(const r of a)gi.includes(r)||console.warn(...b(`The technology '${r}' is not tracked in Kitten Scientists!`));for(const r of n){if(gi.includes(r)){console.info(...b(`The technology '${r}' is a technology in Kittens Game, but it's no longer used.`));continue}console.warn(...b(`The technology '${r}' is not a technology in Kittens Game!`))}}load(e){g(e)||(super.load(e),O(this.techs,e.techs,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class bt extends y{policies;techs;observe;constructor(e=!1,t=new wi,i=new ki,s=new y){super(e),this.policies=t,this.techs=i,this.observe=s}static validateGame(e,t){wi.validateGame(e,t.policies),ki.validateGame(e,t.techs)}load(e){g(e)||(super.load(e),this.policies.load(e.policies),this.techs.load(e.techs),this.observe.enabled=e.observe?.enabled??this.observe.enabled)}}class ye{_host;constructor(e){this._host=e}upgrade(e,t){let i=!1;if(t==="policy"){const a=game.getUnlockByName(e.name,"policies"),n=new classes.ui.PolicyBtnController(this._host.game),r=n.fetchModel({controller:n,id:a.name});i=ye.skipConfirm(()=>n.buyItem(r)).itemBought}else if(t==="science"){const a=game.getUnlockByName(e.name,"tech"),n=new com.nuclearunicorn.game.ui.TechButtonController(this._host.game),r=n.fetchModel({controller:n,id:a.name});i=ye.skipConfirm(()=>n.buyItem(r)).itemBought}else{const a=game.getUnlockByName(e.name,"upgrades"),n=new com.nuclearunicorn.game.ui.UpgradeButtonController(this._host.game),r=n.fetchModel({controller:n,id:a.name});i=ye.skipConfirm(()=>n.buyItem(r)).itemBought}if(!i)return!1;const s=e.label;return t==="workshop"?(this._host.engine.storeForSummary(s,1,"upgrade"),this._host.engine.iactivity("upgrade.upgrade",[s],"ks-upgrade")):t==="policy"?this._host.engine.iactivity("upgrade.policy",[s]):t==="science"&&(this._host.engine.storeForSummary(s,1,"research"),this._host.engine.iactivity("upgrade.tech",[s],"ks-research")),!0}static async skipConfirmAsync(e){const t=game.ui.confirm;try{return game.ui.confirm=()=>!0,await e()}finally{game.ui.confirm=t}}static skipConfirm(e){const t=game.ui.confirm;try{return game.ui.confirm=()=>!0,e()}finally{game.ui.confirm=t}}}const As=c=>new Promise(e=>setTimeout(e,c)),we="en-US",Ps=2*60*1e3,Bs="localStorage"in globalThis&&!g(localStorage["ks.timeout"])?Number(localStorage["ks.timeout"]):void 0;class x{_gameStartSignal;_gameStartSignalResolver;_possibleEngineState;static tryEngineStateFromSaveData(e,t){const i=t;if(!(e in i)){console.debug(...b(`Failed: \`${e}\` not found in save data.`));return}const s=i.ks;if(!("state"in s)){console.debug(...b(`Failed: \`${e}.state\` not found in save data.`));return}const a=s.state;if(!Array.isArray(a)){console.debug(...b(`Failed: \`${e}.state\` not \`Array\`.`));return}return a[0]}async waitForGame(e,t,i=Bs??Ps){if(x._isGameLoaded()){const a=f(x.window.game),n=f(x.window.$I),r=localStorage["com.nuclearunicorn.kittengame.language"];return new e(a,n,r,this._possibleEngineState)}const s=[As(2e3)];if(g(this._gameStartSignal)&&typeof x.window.dojo<"u"){this._gameStartSignal=new Promise(n=>{this._gameStartSignalResolver=n});const a=x.window.dojo.subscribe("game/start",()=>{console.debug(...b(`'game/start' signal caught. Fast-tracking script load for '${t}'...`)),f(this._gameStartSignalResolver)(!0),x.window.dojo.unsubscribe(a)});if(t!==void 0){const n=x.window.dojo.subscribe("server/load",r=>{console.info(...b(`'server/load' signal caught. Looking for script state with key '${t}' in save data...`));const o=x.tryEngineStateFromSaveData(t,r);if(!o){console.info(...b(`The Kittens Game save data did not contain a script state for '${t}'.`));return}console.info(...b(`Found key '${t}'! Provided save data will be used as seed for next script instance.`)),this._possibleEngineState=o,x.window.dojo.unsubscribe(n)})}}if(g(this._gameStartSignal)||s.push(this._gameStartSignal),i<0)throw new Error("Unable to find game. Giving up. Maybe the game is not exported at `window.game`?");return console.debug(...b(`Waiting for game... (timeout: ${Math.round(i/1e3)}s)`)),await Promise.race(s),this.waitForGame(e,t,i-2e3)}static _isGameLoaded(){return!g(x.window.game)&&(x.window.document.getElementById("game")?.checkVisibility()??!1)&&!g(x.window.$I)}static get window(){try{return f(unsafeWindow)}catch{return window}}}class Is extends ye{settings;_workshopManager;constructor(e,t,i=new bt){super(e),this.settings=i,this._workshopManager=t}async tick(e){this.settings.enabled&&(this.settings.techs.enabled&&this._host.game.libraryTab.visible&&await this.autoUnlock(),this.settings.policies.enabled&&this._host.game.libraryTab.visible&&await this.autoPolicy(),this.settings.observe.enabled&&this.observeStars())}async autoUnlock(){const e=this._host.game.science.techs,t=new Array;e:for(const i of Object.values(this.settings.techs.techs)){if(!i.enabled)continue;const s=e.find(n=>n.name===i.tech);if(g(s)){console.error(...b(`Tech '${i.tech}' not found in game!`));continue}if(s.researched||!s.unlocked)continue;let a=x.window.dojo.clone(s.prices);a=this._host.game.village.getEffectLeader("scientist",a);for(const n of a){const r=this._workshopManager.getValueAvailable(n.name),o=this._workshopManager.getResource(n.name),l=te.evaluateSubSectionTrigger(this.settings.techs.trigger,i.trigger);if(l<0||r<o.maxValue*l||r<n.val)continue e}t.push(s)}for(const i of t)await this.upgrade(i,"science")}async autoPolicy(){const e=this._host.game.science.policies,t=new Array;for(const i of Object.values(this.settings.policies.policies)){if(!i.enabled)continue;const s=e.find(a=>a.name===i.policy);if(g(s)){console.error(...b(`Policy '${i.policy}' not found in game!`));continue}!s.researched&&!s.blocked&&s.unlocked&&(s.requiredLeaderJob===void 0||this._host.game.village.leader!==null&&this._host.game.village.leader.job===s.requiredLeaderJob)&&t.push(s)}for(const i of t)await this.upgrade(i,"policy")}observeStars(){this._host.game.calendar.observeBtn!==null&&(this._host.game.calendar.observeHandler(),this._host.engine.iactivity("act.observe",[],"ks-star"),this._host.engine.storeForSummary("stars",1))}}class $s extends y{#e;get mission(){return this.#e}constructor(e,t=!1){super(t),this.#e=e}}class _i extends y{missions;constructor(e=!1){super(e),this.missions=this.initMissions()}initMissions(){const e={};for(const t of ds)e[t]=new $s(t);return e}static validateGame(e,t){const i=Object.keys(t.missions),s=e.space.programs.map(r=>r.name),a=Q(s,i),n=Q(i,s);for(const r of a)console.warn(...b(`The space mission '${r}' is not tracked in Kitten Scientists!`));for(const r of n)console.warn(...b(`The space mission '${r}' is not a space mission in Kittens Game!`))}load(e){g(e)||(super.load(e),O(this.missions,e.missions,(t,i)=>{t.enabled=i?.enabled??t.enabled}))}}class Ls extends Ne{#e;get building(){return this.#e}constructor(e){super(!1,-1,0),this.#e=e}}class ze extends F{buildings;unlockMissions;constructor(e=!1,t=-1,i=new _i){super(e,t),this.buildings=this.initBuildings(),this.unlockMissions=i}initBuildings(){const e={};for(const t of mi)e[t]=new Ls(t);return e}static validateGame(e,t){_i.validateGame(e,t.unlockMissions)}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.max=i?.max??t.max,t.trigger=i?.trigger??t.trigger}),this.unlockMissions.load(e.unlockMissions))}}class Os{_host;settings;_bulkManager;_workshopManager;constructor(e,t,i=new ze){this._host=e,this.settings=i,this._workshopManager=t,this._bulkManager=new Ue(this._host,this._workshopManager)}tick(e){this.settings.enabled&&(this.autoBuild(e),this.settings.unlockMissions.enabled&&this.autoUnlock(e))}autoBuild(e,t=this.settings.buildings){const i=this._bulkManager,s=this.settings.trigger,a={};for(const r of Object.values(t))a[r.building]=this.getBuild(r.building);const n=i.bulk(t,a,s,"Space");for(const r of n)r.count<=0||this.build(r.id,r.count)!==0&&(e.requestGameUiRefresh=!0)}autoUnlock(e){if(!this._host.game.tabs[6].visible)return;const t=this._host.game.space.meta[0].meta;e:for(let i=0;i<t.length;i++){if(0<t[i].val||!t[i].unlocked||!this.settings.unlockMissions.missions[t[i].name].enabled)continue;const s=this._host.game.time.queue.getQueueElementControllerAndModel({name:t[i].name,type:"spaceMission"}),a=f(s.model.prices);for(const n of a)if(this._workshopManager.getValueAvailable(n.name)<n.val)continue e;s.controller.buyItem(s.model),i===7||i===12?this._host.engine.iactivity("upgrade.space.mission",[t[i].label],"ks-upgrade"):this._host.engine.iactivity("upgrade.space",[t[i].label],"ks-upgrade")}}build(e,t){let i=t;const s=i;let a;const n=game.getUnlockByName(e,"spaceBuilding"),r=new classes.ui.space.PlanetBuildingBtnController(this._host.game),o=r.fetchModel({controller:r,id:n.name});return i=this._bulkManager.construct(o,r,i),a=n.label,i!==s&&(console.warn(...b(`${a} Amount ordered: ${s} Amount Constructed: ${i}`)),i===0)?0:(this._host.engine.storeForSummary(a,i,"build"),i===1?this._host.engine.iactivity("act.build",[a],"ks-build"):this._host.engine.iactivity("act.builds",[a,this._host.renderAbsolute(i)],"ks-build"),i)}getBuild(e){return this._host.game.space.getBuilding(e)}}var Ci=(c=>(c.build="ks-activity type_ks-build",c.craft="ks-activity type_ks-craft",c.upgrade="ks-activity type_ks-upgrade",c.research="ks-activity type_ks-research",c.trade="ks-activity type_ks-trade",c.hunt="ks-activity type_ks-hunt",c.praise="ks-activity type_ks-praise",c.adore="ks-activity type_ks-adore",c.transcend="ks-activity type_ks-transcend",c.faith="ks-activity type_ks-faith",c.accelerate="ks-activity type_ks-accelerate",c.timeSkip="ks-activity type_ks-timeSkip",c.festival="ks-activity type_ks-festival",c.star="ks-activity type_ks-star",c.distribute="ks-activity type_ks-distribute",c.promote="ks-activity type_ks-promote",c.misc="ks-activity",c))(Ci||{});const Si=["accelerate","adore","build","craft","distribute","faith","festival","hunt","misc","praise","promote","research","star","timeSkip","trade","transcend","upgrade"];class Us extends y{#e;get variant(){return this.#e}constructor(e){super(!0),this.#e=e}}class Ds extends y{filters;disableKGLog;constructor(e=!1,t=new y(!0)){super(e),this.filters=this.initFilters(),this.disableKGLog=t}initFilters(){const e={};for(const t of Si)e[t]=new Us(Ci[t]);return e}load(e){g(e)||(super.load(e),O(this.filters,e.filters,(t,i)=>{t.enabled=i?.enabled??t.enabled}),this.disableKGLog.enabled=e.disableKGLog?.enabled??this.disableKGLog.enabled)}}class Ns extends F{#e;#t;get upgrade(){return this.#e}get $upgrade(){return this.#t}set $upgrade(e){this.#t=e}constructor(e,t=!1){super(t,-1),this.#e=e}}class xi extends F{upgrades;constructor(e=!1){super(e,-1),this.upgrades=this.initUpgrades()}initUpgrades(){const e={};for(const t of bi)e[t]=new Ns(t);return e}static validateGame(e,t){const i=Object.keys(t.upgrades),s=e.workshop.upgrades.map(r=>r.name),a=Q(s,i),n=Q(i,s);for(const r of a)console.warn(...b(`The workshop upgrade '${r}' is not tracked in Kitten Scientists!`));for(const r of n)console.warn(...b(`The workshop upgrade '${r}' is not an upgrade in Kittens Game!`))}load(e){g(e)||(super.load(e),O(this.upgrades,e.upgrades,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class qs extends fs{#e;get resource(){return this.#e}constructor(e,t=!1,i=!0){super(t,i),this.#e=e}}class Fe extends F{resources;shipOverride;unlockUpgrades;constructor(e=!1,t=-1,i=new xi,s=new y){super(e,t),this.resources=this.initResources(),this.shipOverride=s,this.unlockUpgrades=i}initResources(){const e={};for(const t of ri)e[t]=new qs(t);return e}static validateGame(e,t){const i=Object.keys(t.resources),s=e.workshop.crafts.map(r=>r.name),a=Q(s,i),n=Q(i,s);for(const r of a)console.warn(...b(`The workshop craft '${r}' is not tracked in Kitten Scientists!`));for(const r of n)console.warn(...b(`The workshop craft '${r}' is not an upgrade in Kittens Game!`));xi.validateGame(e,t.unlockUpgrades)}load(e){g(e)||(super.load(e),O(this.resources,e.resources,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.limited=i?.limited??t.limited,t.max=i?.max??t.max,t.trigger=i?.trigger??t.trigger}),this.unlockUpgrades.load(e.unlockUpgrades),this.shipOverride.enabled=e.shipOverride?.enabled??this.shipOverride.enabled)}}class Ti extends ye{settings;static DEFAULT_CONSUME_RATE=1;constructor(e,t=new Fe){super(e),this.settings=t}tick(e){return this.settings.enabled?(this.autoCraft(),this._host.engine.settings.highlighStock.enabled&&this.refreshStock(),this.settings.unlockUpgrades.enabled?this.autoUnlock():Promise.resolve()):Promise.resolve()}async autoUnlock(){if(!this._host.game.workshopTab.visible)return;const e=this._host.game.workshop.upgrades,t=new Array;e:for(const i of Object.values(this.settings.unlockUpgrades.upgrades)){if(!i.enabled)continue;const s=i.$upgrade??e.find(n=>n.name===i.upgrade);if(g(s)){console.error(...b(`Upgrade '${i.upgrade}' not found in game!`));continue}if(i.$upgrade===void 0&&(i.$upgrade=s),s.researched||!s.unlocked)continue;let a=x.window.dojo.clone(s.prices);a=this._host.game.village.getEffectLeader("scientist",a);for(const n of a){const r=this.getValueAvailable(n.name),o=this.getResource(n.name),l=te.evaluateSubSectionTrigger(this.settings.unlockUpgrades.trigger,i.trigger);if(l<0||0<l&&r<o.maxValue*l||r<n.val)continue e}t.push(s)}for(const i of t)await this.upgrade(i,"workshop")}autoCraft(e=this.settings.resources){const t=new Map,i=this.settings.trigger;for(const n of Object.values(e)){const r=te.evaluateSubSectionTrigger(i,n.trigger);if(r<0||!n.enabled)continue;const o=n.max?this.getResource(n.resource):!1,l=Z(n.max);if(o&&l<o.value||!this.singleCraftPossible(n.resource))continue;const h=Object.keys(this.getMaterials(n.resource));h.map(m=>this.getResource(m)).filter(m=>0<m.maxValue).filter(m=>m.value/m.maxValue<r).length===0&&t.set(n,{countRequested:1,materials:h.map(m=>({consume:0,resource:m}))})}if(t.size<1)return;const s=new Map;for(const[n,r]of t)for(const o of r.materials)s.has(o.resource)||s.set(o.resource,new Array),f(s.get(o.resource)).push(n.resource);for(const[,n]of t)for(const r of n.materials){const o=this.getValueAvailable(r.resource);r.consume=o/f(s.get(r.resource)).length}for(const[n,r]of t){const o=this.getMaterials(n.resource);let l=Number.MAX_VALUE;for(const m of r.materials){const v=f(o[m.resource]),p=this.getResource(m.resource);if(!n.limited||n.resource==="ship"&&this.settings.shipOverride.enabled&&this.getResource("ship").value<243){l=Math.min(l,m.consume/v);continue}const w=this._host.game.getResCraftRatio(n.resource),C=this.getValueAvailable(m.resource)/f(s.get(m.resource)).length,A=this.getValueAvailable(n.resource),oe=v,K=1+w,j=C/oe,he=A/K,Y=Math.max(0,Math.floor(Math.log(he)/Math.LN10+1e-9));l=Math.min(l,Math.min(j-(0<p.maxValue&&p.maxValue<=p.value?0:he),10**(Y+1)),m.consume/v)}const h=this.getValueAvailable(n.resource),u=1+this._host.game.getResCraftRatio(n.resource),d=Number.MAX_VALUE/u-h/u;l=Math.min(l,d),r.countRequested=Math.max(0,n.max===-1?l:Math.min(l,(n.max-h)/u))}const a=new Array;for(const[n,r]of t)r.countRequested<1||a.push({amount:Math.floor(r.countRequested),name:n.resource});0<a.length&&this.craftMultiple(a)}craftMultiple(e){const t=new Array;for(const i of e){const s=this.getCraft(i.name),a=this._host.game.getResCraftRatio(s.name);if(!this._host.game.workshop.craft(s.name,i.amount,!0,!1,!1)){console.error(...b(`Failed trying to craft ${i.amount}x ${i.name}! This is a problem and should be reported.`));continue}const r=f(this._host.game.resPool.get(i.name)).title,o=Number.parseFloat((i.amount*(1+a)).toFixed(2));this._host.engine.storeForSummary(r,o,"craft"),t.push(this._host.engine.i18n("act.craft",[this._host.game.getDisplayValueExt(o),r]))}this._host.game.updateResources();for(const i of t)this._host.engine.printOutput("ks-activity type_ks-craft","#e65C00",i)}getCraft(e){const t=this._host.game.workshop.getCraft(e);if(!t)throw new Error(`Unable to find craft '${e}'`);return t}singleCraftPossible(e){if(!this._host.game.workshopTab.visible&&e!=="wood")return!1;const t=this.getMaterials(e);for(const[i,s]of L(t))if(this.getValueAvailable(i)<s)return!1;return!0}getMaterials(e){const t={},i=this.getCraft(e),s=this._host.game.workshop.getCraftPrice(i);for(const a of s)t[a.name]=a.val;return t}getTickVal(e,t,i=void 0){let s=this._host.game.getResourcePerTick(e.name,!0);if(e.craftable){let a=Number.MAX_VALUE;const n=this.getMaterials(e.name);for(const[r,o]of L(n)){const l=(1+this._host.game.getResCraftRatio(e.name))/o,h=this.getTickVal(this.getResource(r));h!=="ignore"&&(a=Math.min(h*l,a))}s+=a!==Number.MAX_VALUE?a:0}return s<=0&&(e.name==="spice"||e.name==="blueprint")?"ignore":(!i&&!g(t)&&(s+=t.getResValue(e.name)),s)}getAverageHunt(){const e={},t=this._host.game.getEffect("hunterRatio")+this._host.game.village.getEffectLeader("manager",0);return e.furs=40+32.5*t,e.ivory=50*Math.min(.225+.01*t,.5)+40*t*Math.min(.225+.01*t,.5),e.unicorns=.05,this.getValue("zebras")>=10&&(e.bloodstone=this.getValue("bloodstone")===0?.05:5e-4),this._host.game.ironWill&&this._host.game.workshop.get("goldOre").researched&&(e.gold=.625+.625*t),e}getResource(e){const t=this._host.game.resPool.get(e);if(g(t))throw new Error(`Unable to find resource ${e}`);return t}getValue(e){return this.getResource(e).value??0}getStock(e){const t=this._host.engine.settings.resources.resources[e];return t.enabled?t.stock:0}getConsume(e){const t=this._host.engine.settings.resources.resources[e];return t.enabled?t.consume:1}getValueAvailable(e){let t=this.getStock(e);if(e==="catnip"){const a=this._host.game.bld.getBuildingExt("pasture").meta,n=this._host.game.bld.getBuildingExt("aqueduct").meta,r=a.stage===0?a.val:0,o=n.stage===0?n.val:0,l=this.getPotentialCatnip(!0,r,o);l<0&&(t-=l*202*5)}let i=this.getValue(e);i=Math.max(i-t,0);const s=this.getConsume(e);return i*s}getPotentialCatnip(e,t,i){let s=this._host.game.getEffect("catnipPerTickBase");e?(s*=.1,s*=1+this._host.game.getLimitedDR(this._host.game.getEffect("coldHarshness"),1)):s*=this._host.game.calendar.getWeatherMod({name:"catnip"})+this._host.game.calendar.getCurSeason().modifiers.catnip,this._host.game.science.getPolicy("communism").researched&&(s=0);const a=this._host.game.village.getResProduction(),n=a.catnip?a.catnip*(1+this._host.game.getEffect("catnipJobRatio")):0;let r=s+n,o=this._host.game.space.getBuilding("hydroponics").val;this._host.game.prestige.meta[0].meta[21].researched&&(this._host.game.calendar.cycle===2&&(o*=2),this._host.game.calendar.cycle===7&&(o*=.5)),r*=1+.03*i+.025*o;const h=this._host.game.challenges.currentChallenge==="winterIsComing"?0:this._host.game.prestige.getParagonProductionRatio();r*=1+h,r*=1+this._host.game.religion.getSolarRevolutionRatio(),this._host.game.opts.disableCMBR||(r*=1+this._host.game.getCMBRBonus()),r=f(this._host.game.calendar.cycleEffectsFestival({catnip:r}).catnip);let u=this._host.game.village.getResConsumption().catnip;const d=this._host.game.bld.getBuildingExt("unicornPasture").meta.val;if(u*=1+this._host.game.getLimitedDR(t*-.005+d*-.0015,1),this._host.game.village.sim.kittens.length>0&&this._host.game.village.happiness>1){const m=this._host.game.village.happiness-1,v=this._host.game.getEffect("catnipDemandWorkerRatioGlobal");this._host.game.challenges.currentChallenge==="anarchy"?u*=1+m*(1+v):u*=1+m*(1+v)*(1-this._host.game.village.getFreeKittens()/this._host.game.village.sim.kittens.length)}return r+=u,r+=this._host.game.getResourcePerTickConvertion("catnip"),r}refreshStock(){const e=[...document.querySelectorAll("#game .res-row .res-cell.resAmount, #game .res-row .res-cell.resource-value")],t=new Map(e.map(i=>[f([...i.parentNode.classList.entries()].find(([s,a])=>a.startsWith("resource_")))[1].substring(9),i]));for(const[i,s]of L(this._host.engine.settings.resources.resources)){const a=t.get(i);if(!a)continue;if(!s.enabled||s.stock===0){(a.classList.contains("ks-stock-above")||a.classList.contains("ks-stock-below"))&&a.classList.remove("ks-stock-above","ks-stock-below");continue}const n=this._host.game.resPool.get(i).value<s.stock;a.classList.add(n?"ks-stock-below":"ks-stock-above"),a.classList.remove(n?"ks-stock-above":"ks-stock-below")}}}class zs extends y{#e;consume;stock=0;get resource(){return this.#e}constructor(e,t=!1,i=Ti.DEFAULT_CONSUME_RATE,s=0){super(t),this.#e=e,this.consume=i,this.stock=s}}class Fs extends y{resources;constructor(e=!1){super(e),this.resources=this.initResources()}initResources(){const e={};for(const t of oi)e[t]=new zs(t);return e}load(e){g(e)||(super.load(e),O(this.resources,e.resources,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.consume=i?.consume??t.consume,t.stock=i?.stock??t.stock}))}}class Hs extends y{noConfirm;compress;constructor(e=new y,t=new y(!0)){super(!0),this.noConfirm=e,this.compress=t}load(e){g(e)||(super.load(e),this.noConfirm.load(e.noConfirm),this.compress.load(e.compress))}}class Ei extends y{interval=2e3;locale;ksColumn;highlighStock;filters;resources;states;constructor(e=!1,t=new Ds,i=new Fs,s=new Hs,a=we,n=new y,r=new y){super(e),this.filters=t,this.resources=i,this.states=s,this.locale=new gt(a,[{label:"Deutsch",value:"de-DE"},{label:"English",value:"en-US"},{label:"עִברִית",value:"he-IL"},{label:"中文",value:"zh-CN"}]),this.ksColumn=n,this.highlighStock=r}load(e,t=!1){g(e)||(super.load(e),t||(this.interval=e.interval??this.interval,this.states.load(e.states),this.locale.load(e.locale),this.ksColumn.load(e.ksColumn),this.highlighStock.load(e.highlighStock)),this.filters.load(e.filters),this.resources.load(e.resources))}}class Ri extends ee{#e=void 0;get baseBuilding(){return this.#e}#t;get building(){return this.#t}#i=0;get stage(){return this.#i}constructor(e,t=!1,i=-1,s){super(t,i),this.#t=e,s&&(this.#i=1,this.#e=s)}}class Ws extends y{buildings;constructor(e=!1){super(e),this.buildings=this.initBuildings()}initBuildings(){const e={broadcasttower:"amphitheatre",dataCenter:"library",hydroplant:"aqueduct",solarfarm:"pasture",spaceport:"warehouse"},t={};for(const i of ai)i!=="unicornPasture"&&(t[i]=new Ri(i));for(const i of dt)t[i]=new Ri(i,!1,-1,e[i]);return t}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class He extends ee{#e;#t;get building(){return this.#e}get variant(){return this.#t}constructor(e,t,i=!1,s=-1){super(i,s),this.#e=e,this.#t=t}}class Gs extends y{buildings;constructor(e=!1){super(e),this.buildings=this.initBuildings()}initBuildings(){const e={};for(const t of ci)e[t]=new He(t,U.OrderOfTheSun);for(const t of hi)e[t]=new He(t,U.Cryptotheology);for(const t of ui)e[t]=new He(t,U.Ziggurat);return e.unicornPasture=new He("unicornPasture",U.UnicornPasture),e}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class Zs extends ee{#e;get resource(){return this.#e}constructor(e,t=!1,i=-1){super(t,i),this.#e=e}}class Ks extends y{resources;constructor(e=!1){super(e),this.resources=this.initResources()}initResources(){const e={};for(const t of oi)e[t]=new Zs(t);return e}load(e){g(e)||(super.load(e),O(this.resources,e.resources,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class Vs extends ee{#e;get building(){return this.#e}constructor(e,t=!1,i=-1){super(t,i),this.#e=e}}class js extends y{buildings;constructor(e=!1){super(e),this.buildings=this.initBuildings()}initBuildings(){const e={};for(const t of mi)e[t]=new Vs(t);return e}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class Mi extends ee{#e;#t;get building(){return this.#e}get variant(){return this.#t}constructor(e,t,i=!1,s=-1){super(i,s),this.#e=e,this.#t=t}}class Js extends y{buildings;constructor(e=!1){super(e),this.buildings=this.initBuildings()}initBuildings(){const e={};for(const t of fi)e[t]=new Mi(t,se.Chronoforge);for(const t of pi)t!=="usedCryochambers"&&(e[t]=new Mi(t,se.VoidSpace));return e}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.trigger=i?.trigger??t.trigger}))}}class Xs extends y{#e;get upgrade(){return this.#e}constructor(e,t=!1){super(t),this.#e=e}}class Ys extends y{upgrades;constructor(e=!1){super(e),this.upgrades=this.initUpgrades()}initUpgrades(){const e={};for(const t of bi)e[t]=new Xs(t);return e}load(e){g(e)||(super.load(e),O(this.upgrades,e.upgrades,(t,i)=>{t.enabled=i?.enabled??t.enabled}))}}class Qs extends y{bonfire;religion;resources;space;time;upgrades;constructor(e=!1,t=new Ws,i=new Gs,s=new Ks,a=new js,n=new Js,r=new Ys){super(e),this.bonfire=t,this.religion=i,this.resources=s,this.space=a,this.time=n,this.upgrades=r}load(e){g(e)||(super.load(e),this.bonfire.load(e.bonfire),this.religion.load(e.religion),this.resources.load(e.resources),this.space.load(e.space),this.time.load(e.time),this.upgrades.load(e.upgrades))}}class en extends F{cycles;activeHeatTransferStatus;constructor(e=new y){super(!1,1),this.cycles=this.initCycles(),this.activeHeatTransferStatus=e}initCycles(){const e={};for(const t of ge)e[t]=new y;return e}load(e){g(e)||(super.load(e),O(this.cycles,e.cycles,(t,i)=>{t.enabled=i?.enabled??t.enabled}),this.activeHeatTransferStatus.load(e.activeHeatTransferStatus))}}class tn extends bs{cycles;seasons;activeHeatTransfer;ignoreOverheat;constructor(e=new y,t=new en){super(!1,5),this.cycles=this.initCycles(),this.seasons=this.initSeason(),this.activeHeatTransfer=t,this.ignoreOverheat=e}initCycles(){const e={};for(const t of ge)e[t]=new y;return e}initSeason(){const e={};for(const t of ls)e[t]=new y;return e}load(e){g(e)||(super.load(e),O(this.cycles,e.cycles,(t,i)=>{t.enabled=i?.enabled??t.enabled}),O(this.seasons,e.seasons,(t,i)=>{t.enabled=i?.enabled??t.enabled}),this.ignoreOverheat.load(e.ignoreOverheat),this.activeHeatTransfer.load(e.activeHeatTransfer))}}class Ai extends y{accelerateTime;timeSkip;reset;constructor(e=!1,t=new F(!1,1),i=new Qs,s=new tn){super(e),this.accelerateTime=t,this.reset=i,this.timeSkip=s}load(e){g(e)||(super.load(e),this.accelerateTime.load(e.accelerateTime),this.reset.load(e.reset),this.timeSkip.load(e.timeSkip))}}class Pi extends Ne{#e;#t;get building(){return this.#e}get variant(){return this.#t}constructor(e,t,i=!1){super(i,-1,0),this.#e=e,this.#t=t}}class Bi extends F{buildings;fixCryochambers;constructor(e=!1,t=-1,i=new y){super(e,t),this.buildings=this.initBuildings(),this.fixCryochambers=i}initBuildings(){const e={};for(const t of fi)e[t]=new Pi(t,se.Chronoforge);for(const t of pi)t!=="usedCryochambers"&&(e[t]=new Pi(t,se.VoidSpace));return e}load(e){g(e)||(super.load(e),O(this.buildings,e.buildings,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.max=i?.max??t.max,t.trigger=i?.trigger??t.trigger}),this.fixCryochambers.load(e.fixCryochambers))}}class sn extends yi{#e;get race(){return this.#e}constructor(e,t=!1){super(t),this.#e=e}}class nn extends F{races;constructor(e=!1){super(e),this.races=this.initRaces()}initRaces(){const e={};for(const t of di)t!=="leviathans"&&(e[t]=new sn(t));return e}load(e){g(e)||(super.load(e),O(this.races,e.races,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.max=i?.max??t.max}))}}class an extends ps{#e;seasons;#t;get race(){return this.#e}get require(){return this.#t}constructor(e,t,i,s,a,n,r,o=!1){super(t,i),this.#e=e,this.seasons={autumn:new y(a),spring:new y(r),summer:new y(s),winter:new y(n)},this.#t=o}}class Ii extends F{races;feedLeviathans;buildEmbassies;tradeBlackcoin;unlockRaces;constructor(e=!1,t=-1,i=new nn,s=new y,a=new vs(!1,1090,1095,1e4),n=new y){super(e,t),this.races=this.initRaces(),this.buildEmbassies=i,this.feedLeviathans=s,this.tradeBlackcoin=a,this.unlockRaces=n}initRaces(){const e={dragons:"titanium",griffins:"wood",leviathans:"unobtainium",lizards:"minerals",sharks:"iron"},t={};for(const i of di){const s=e[i]??!1;t[i]=new an(i,!1,!1,!1,!1,!1,!1,s)}return t}load(e){g(e)||(super.load(e),O(this.races,e.races,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.limited=i?.limited??t.limited,t.trigger=i?.trigger??t.trigger,t.seasons.autumn.enabled=i?.seasons.autumn.enabled??t.seasons.autumn.enabled,t.seasons.spring.enabled=i?.seasons.spring.enabled??t.seasons.spring.enabled,t.seasons.summer.enabled=i?.seasons.summer.enabled??t.seasons.summer.enabled,t.seasons.winter.enabled=i?.seasons.winter.enabled??t.seasons.winter.enabled}),this.buildEmbassies.load(e.buildEmbassies),this.feedLeviathans.load(e.feedLeviathans),this.tradeBlackcoin.load(e.tradeBlackcoin),this.unlockRaces.load(e.unlockRaces))}}class rn extends y{job;trait;constructor(e=!1,t=new gt("any",li.map(s=>({label:"",value:s}))),i=new gt("none",cs.map(s=>({label:"",value:s})))){super(e),this.job=t,this.trait=i}load(e){g(e)||(super.load(e),this.job.load(e.job),this.trait.load(e.trait))}}class $i extends y{jobs;holdFestivals;hunt;promoteKittens;promoteLeader;electLeader;constructor(e=!1,t=new y,i=new F(!1,.98),s=new F(!1,1),a=new y,n=new rn){super(e),this.jobs=this.initJobs(),this.holdFestivals=t,this.hunt=i,this.promoteKittens=s,this.promoteLeader=a,this.electLeader=n}initJobs(){const e={};for(const t of li)e[t]=new yi(!1,0);return e}load(e){g(e)||(super.load(e),O(this.jobs,e.jobs,(t,i)=>{t.enabled=i?.enabled??t.enabled,t.max=i?.max??t.max}),this.holdFestivals.enabled=e.holdFestivals?.enabled??this.holdFestivals.enabled,this.hunt.load(e.hunt),this.promoteKittens.enabled=e.promoteKittens?.enabled??this.promoteKittens.enabled,this.promoteLeader.enabled=e.promoteLeader?.enabled??this.promoteLeader.enabled,this.electLeader.load(e.electLeader))}}class on{_host;settings;_bonfireManager;_religionManager;_spaceManager;_workshopManager;constructor(e,t,i,s,a,n=new Ai){this._host=e,this.settings=n,this._bonfireManager=t,this._religionManager=i,this._spaceManager=s,this._workshopManager=a}async tick(e){this.settings.enabled&&(this.settings.accelerateTime.enabled&&this.accelerateTime(),this.settings.timeSkip.enabled&&this.timeSkip(),this.settings.reset.enabled&&await this.autoReset(this._host.engine))}async autoReset(e){if(this._host.game.challenges.currentChallenge)return;const t=[],i=[],s=r=>{if(i.length!==0)for(const o of r){if(g(o.model))continue;const l=o.model,h=l.metadata.name,u=i.indexOf(h);if(u!==-1&&(i.splice(u,1),this._host.game.resPool.hasRes(f(l.prices))))return!0}return!1};for(const[r,o]of L(this.settings.reset.bonfire.buildings)){if(!o.enabled)continue;if(o.trigger<0)return;let l;try{l=this._host.game.bld.getBuildingExt(r)}catch{l=null}if(!g(l))if(t.push({name:l.meta.label??f(l.meta.stages)[f(l.meta.stage)].label,trigger:o.trigger,val:l.meta.val}),0<o.trigger){if(l.meta.val<o.trigger)return}else i.push(r)}const a=this.settings.reset.religion.buildings.unicornPasture;if(a.enabled){if(a.trigger<0)return;const r=this._host.game.bld.getBuildingExt("unicornPasture");if(t.push({name:f(r.meta.label),trigger:a.trigger,val:r.meta.val}),0<a.trigger){if(r.meta.val<a.trigger)return}else i.push("unicornPasture")}if(s(this._bonfireManager.manager.tab.children)||i.length)return;for(const[r,o]of L(this.settings.reset.space.buildings)){if(!o.enabled)continue;if(o.trigger<0)return;const l=this._host.game.space.getBuilding(r);if(t.push({name:l.label,trigger:o.trigger,val:l.val}),0<o.trigger){if(l.val<o.trigger)return}else i.push(r)}if(i.length===0){const r=f(this._host.game.spaceTab.planetPanels);for(const o of r)for(const l of o.children){const h=f(l.model),u=h.metadata.name,d=i.indexOf(u);if(d!==-1&&(i.splice(d,1),this._host.game.resPool.hasRes(f(h.prices))))break}}if(i.length)return;for(const[r,o]of L(this.settings.reset.religion.buildings)){if(!o.enabled)continue;if(o.trigger<0)return;const l=f(this._religionManager.getUpgradeMeta(r,o.variant));if(t.push({name:l.label,trigger:o.trigger,val:l.val}),0<o.trigger){if(l.val<o.trigger)return}else i.push(r)}if(s(this._religionManager.manager.tab.zgUpgradeButtons)||s(this._religionManager.manager.tab.rUpgradeButtons)||s(this._religionManager.manager.tab.ctPanel.children[0].children)||i.length)return;for(const[r,o]of L(this.settings.reset.time.buildings)){if(!o.enabled)continue;if(o.trigger<0)return;const l=f(this.getBuild(r,o.variant));if(t.push({name:l.label,trigger:o.trigger,val:l.val}),0<o.trigger){if(l.val<o.trigger)return}else i.push(r)}if(s(this.manager.tab.cfPanel.children[0].children)||s(this.manager.tab.vsPanel.children[0].children)||i.length)return;for(const[r,o]of L(this.settings.reset.resources.resources)){if(!o.enabled)continue;if(o.trigger<0)return;const l=f(this._host.game.resPool.get(r));if(t.push({name:this._host.engine.i18n(`$resources.${o.resource}.title`),trigger:o.trigger,val:l.value}),l.value<o.trigger)return}for(const[,r]of L(this.settings.reset.upgrades.upgrades))if(r.enabled){const o=f(this._host.game.workshop.upgrades.find(l=>l.name===r.upgrade));if(t.push({name:o.label,trigger:1,val:o.researched?1:0}),!o.researched)return}e.stop(!1);const n=async(r=1500)=>new Promise((o,l)=>{if(!this._host.engine.settings.enabled){l(new Error("canceled by player"));return}setTimeout(o,r)});try{for(const r of t)await n(500),this._host.engine.imessage("reset.check",[r.name,this._host.game.getDisplayValueExt(r.trigger),this._host.game.getDisplayValueExt(r.val)]);await n(0),this._host.engine.imessage("reset.checked"),await n(),this._host.engine.iactivity("reset.tip"),await n(),this._host.engine.imessage("reset.countdown.10"),await n(2e3),this._host.engine.imessage("reset.countdown.9"),await n(),this._host.engine.imessage("reset.countdown.8"),await n(),this._host.engine.imessage("reset.countdown.7"),await n(),this._host.engine.imessage("reset.countdown.6"),await n(),this._host.engine.imessage("reset.countdown.5"),await n(),this._host.engine.imessage("reset.countdown.4"),await n(),this._host.engine.imessage("reset.countdown.3"),await n(),this._host.engine.imessage("reset.countdown.2"),await n(),this._host.engine.imessage("reset.countdown.1"),await n(),this._host.engine.imessage("reset.countdown.0"),await n(),this._host.engine.iactivity("reset.last.message"),await n()}catch{this._host.engine.imessage("reset.cancel.message"),this._host.engine.iactivity("reset.cancel.activity");return}for(let r=0;r<this._host.game.challenges.challenges.length;r++)this._host.game.challenges.challenges[r].pending=!1;this._host.game.resetAutomatic()}accelerateTime(){if(this._workshopManager.getValueAvailable("temporalFlux")<=0){this._host.game.time.isAccelerated&&(this._host.game.time.isAccelerated=!1);return}if(this._host.game.time.isAccelerated)return;const t=this._host.game.resPool.get("temporalFlux");t.maxValue*this.settings.accelerateTime.trigger<=t.value&&(this._host.game.time.isAccelerated=!0,this._host.engine.iactivity("act.accelerate",[],"ks-accelerate"),this._host.engine.storeForSummary("accelerate",1))}timeSkip(){if(!this._host.game.workshop.get("chronoforge").researched||this._host.game.calendar.day<0)return;const e=this._host.game.getEffect("shatterCostIncreaseChallenge"),t=this._workshopManager.getValueAvailable("timeCrystal");if(t<this.settings.timeSkip.trigger||t<1+e)return;const i=this._host.game.getEffect("shatterVoidCost"),s=this._workshopManager.getValueAvailable("void");if(s<i)return;const a=this._host.game.calendar.season;if(!this.settings.timeSkip.seasons[this._host.game.calendar.seasons[a].name].enabled)return;const n=this._host.game.calendar.cycle;if(!this.settings.timeSkip.cycles[ge[n]].enabled)return;const r=this._host.game.getEffect("heatMax"),o=this._host.game.time.heat;if(!this.settings.timeSkip.ignoreOverheat.enabled&&r<=o)return;const l=this._host.game.challenges.getChallenge("1000Years").researched?5:10;let h=Number.POSITIVE_INFINITY;if(!this.settings.timeSkip.ignoreOverheat.enabled&&this.settings.timeSkip.activeHeatTransfer.enabled){const C=this._host.game.getEffect("heatPerTick"),A=this._host.game.ticksPerSecond;if(this.settings.timeSkip.activeHeatTransfer.activeHeatTransferStatus.enabled){o<=r*this.settings.timeSkip.activeHeatTransfer.trigger&&(this.settings.timeSkip.activeHeatTransfer.activeHeatTransferStatus.enabled=!1,this._host.refreshEntireUserInterface(),this._host.engine.iactivity("act.time.activeHeatTransferEnd",[],"ks-timeSkip"));const oe=this._host.game.getEffect("temporalFluxProduction"),K=(this._host.game.calendar.daysPerSeason+10+this._host.game.getEffect("temporalParadoxDay"))*this._host.game.calendar.seasonsPerYear,j=this._host.game.calendar.ticksPerDay,he=(1+this._host.game.timeAccelerationRatio())/j,Y=K/he,be=this._host.game.resPool.get("temporalFlux"),Ce=be.maxValue>Y,st=be.value<Y;if(!a&&this._host.game.calendar.day<10&&oe>l/C&&this.settings.accelerateTime.enabled&&Ce&&st)h=Math.ceil((Y+j*10-be.value)/oe),this._host.engine.iactivity("act.time.getTemporalFlux",[],"ks-timeSkip"),this._host.engine.storeForSummary("time.getTemporalFlux",1);else{if(this.settings.timeSkip.activeHeatTransfer.cycles[ge[n]].enabled)return;h=this._host.game.calendar.yearsPerCycle-this._host.game.calendar.cycleYear}}else o>=r-C*A*10&&(this.settings.timeSkip.activeHeatTransfer.activeHeatTransferStatus.enabled=!0,this._host.refreshEntireUserInterface(),this._host.engine.iactivity("act.time.activeHeatTransferStart",[],"ks-timeSkip"),this._host.engine.storeForSummary("time.activeHeatTransferStart",1))}const u=Z(this.settings.timeSkip.max);let d=Math.floor(Math.min(this.settings.timeSkip.ignoreOverheat.enabled?Number.POSITIVE_INFINITY:(r-o)/l,u,h,t/(1+e),0<i?s/i:Number.POSITIVE_INFINITY)),m=0;const v=this._host.game.calendar.yearsPerCycle,p=v-this._host.game.calendar.cycleYear,w=this._host.game.calendar.cyclesPerEra;if(d<p)m=d;else{m+=p,d-=p;let C=1;for(;v<d&&this.settings.timeSkip.cycles[ge[(n+C)%w]].enabled;)m+=v,d-=v,C+=1;this.settings.timeSkip.cycles[ge[(n+C)%w]].enabled&&0<d&&(m+=d)}if(0<m){const C=this._host.game.timeTab.cfPanel.children[0].children[0];if(g(C.model))return;this._host.engine.iactivity("act.time.skip",[m],"ks-timeSkip"),C.controller.doShatterAmt(C.model,m),this._host.engine.storeForSummary("time.skip",m)}}getBuild(e,t){return t===se.Chronoforge?this._host.game.time.getCFU(e):this._host.game.time.getVSU(e)}}class ln{_host;settings;_bulkManager;_workshopManager;constructor(e,t,i=new Bi){this._host=e,this.settings=i,this._bulkManager=new Ue(this._host,t),this._workshopManager=t}tick(e){this.settings.enabled&&(this.autoBuild(e),this.settings.fixCryochambers.enabled&&this.fixCryochambers())}autoBuild(e,t=this.settings.buildings){const i=this._bulkManager,s=this.settings.trigger,a={};for(const r of Object.values(t)){const o=this.getBuild(r.building,r.variant);a[r.building]=f(o);const h=(r.variant===se.Chronoforge?this._host.game.time.queue.getQueueElementControllerAndModel({name:r.building,type:"chronoforge"}):this._host.game.time.queue.getQueueElementControllerAndModel({name:r.building,type:"voidSpace"})).model,u=r.variant===se.Chronoforge?this._host.game.timeTab.cfPanel:this._host.game.timeTab.vsPanel,d=f(a[r.building]);d.tHidden=!h?.visible||!h.enabled||!u.visible}const n=i.bulk(t,a,s,"Time");for(const r of n)r.count>0&&(this.build(r.id,r.variant,r.count),e.requestGameUiRefresh=!0)}build(e,t,i){let s=i,a;const n=s;if(t===se.Chronoforge){const r=game.getUnlockByName(e,"chronoforge"),o=new classes.ui.time.ChronoforgeBtnController(this._host.game),l=o.fetchModel({controller:o,id:r.name});s=this._bulkManager.construct(l,o,s),a=r.label}else{const r=game.getUnlockByName(e,"voidSpace"),o=new classes.ui.time.VoidSpaceBtnController(this._host.game),l=o.fetchModel({controller:o,id:r.name});s=this._bulkManager.construct(l,o,s),a=r.label}s!==n&&(console.warn(...b(`${a} Amount ordered: ${n} Amount Constructed: ${s}`)),s===0)||(this._host.engine.storeForSummary(a,s,"build"),s===1?this._host.engine.iactivity("act.build",[a],"ks-build"):this._host.engine.iactivity("act.builds",[a,this._host.renderAbsolute(s)],"ks-build"))}getBuild(e,t){return t===se.Chronoforge?this._host.game.time.getCFU(e):this._host.game.time.getVSU(e)}fixCryochambers(){if(this._host.game.time.getVSU("usedCryochambers").val<1)return;const e=f(this._host.game.time.getVSU("usedCryochambers").fixPrices);for(const n of e)if(this._workshopManager.getValueAvailable(n.name)<n.val)return;const t=new classes.ui.time.FixCryochamberBtnController(this._host.game),i=t.fetchModel({});let s=0,a;do a=!1,a=t.buyItem(i).itemBought,s+=a?1:0;while(a);0<s&&(this._host.engine.iactivity("act.fix.cry",[this._host.renderAbsolute(s)],"ks-fixCry"),this._host.engine.storeForSummary("fix.cry",s))}}class cn{_host;settings;_workshopManager;constructor(e,t,i=new Ii){this._host=e,this.settings=i,this._workshopManager=t}tick(e){this.settings.enabled&&(this.autoTrade(),this.settings.unlockRaces.enabled&&this.autoUnlock(e),this.settings.buildEmbassies.enabled&&this.autoBuildEmbassies(e),this.settings.feedLeviathans.enabled&&this.autoFeedElders(),this.settings.tradeBlackcoin.enabled&&this.autoTradeBlackcoin())}autoTrade(e){const t=this._workshopManager.getResource("manpower"),i=this._workshopManager.getResource("gold"),s=this.settings.trigger,a=[],n=this._host.game.calendar.getCurSeason().name;for(const u of Object.values(this.settings.races)){const d=this.getRace(u.race),m=te.evaluateSubSectionTrigger(s,u.trigger);if(m<0||!u.enabled||!u.seasons[n].enabled||!d.unlocked||!this.singleTradePossible(s,t,i,u))continue;const v=u.require?this._workshopManager.getResource(u.require):!1,p=this.getProfitability(u.race);(u.limited&&p||!v||m<=v.value/v.maxValue)&&a.push(u.race)}if(a.length===0)return;let r=this.getLowestTradeAmount(null,!0,!1);if(r<1)return;const o=[];for(let u=0;u<a.length;u++){const d=a[u],m=this.settings.races[d],v=m.require?this._workshopManager.getResource(m.require):!1,p=te.evaluateSubSectionTrigger(s,m.trigger),w=(!v||p<=v.value/v.maxValue)&&p<=i.value/i.maxValue,C=this.getLowestTradeAmount(d,m.limited,w);if(C<1){a.splice(u,1),u--;continue}o.push(C)}if(a.length===0)return;const l={};for(;0<a.length&&1<=r;){if(r<a.length){const v=Math.floor(Math.random()*a.length),p=a[v];g(l[p])&&(l[p]=0),l[p]+=1,r-=1,a.splice(v,1),o.splice(v,1);continue}let u=Math.floor(r/a.length),d=0;const m=a[d];for(let v=0;v<a.length;++v)o[v]<u&&(u=o[v],d=v);g(l[m])&&(l[m]=0),l[m]+=u,r-=u,a.splice(d,1),o.splice(d,1)}if(Object.values(l).length===0)return;const h={};for(const[u,d]of L(l)){const m=this.getRace(u),v=this.getMaterials(u);for(const[w,C]of L(v))h[w]||(h[w]=0),h[w]-=C*d;const p=this.getAverageTrade(m);for(const[w,C]of L(p)){const A=this._workshopManager.getResource(w);h[w]||(h[w]=0),h[w]+=A.maxValue>0?Math.min(f(p[w])*f(l[u]),Math.max(A.maxValue-A.value,0)):C*f(l[u])}}g(e)||e.pushToCache({materials:h,timeStamp:this._host.game.timer.ticksTotal});for(const[u,d]of L(l))0<d&&this.trade(u,d)}autoBuildEmbassies(e){if(!this._host.game.diplomacy.races[0].embassyPrices)return;const t=this._workshopManager.getResource("culture");let i=0;const s=this.settings.buildEmbassies.trigger;if(t.value/t.maxValue<Z(s))return;const a=this._host.game.diplomacyTab.racePanels;i=this._workshopManager.getValueAvailable("culture");const n={},r=[];for(let o=0;o<a.length;o++){if(!a[o].embassyButton)continue;const l=a[o].race.name,h=this._host.game.diplomacy.get(l),u=Z(this.settings.buildEmbassies.races[l].max);!this.settings.buildEmbassies.races[l].enabled||u<=h.embassyLevel||!h.unlocked||(n[l]={basePrice:f(h.embassyPrices?.[0]).val,currentEm:h.embassyLevel,max:u,priceSum:0,race:h,val:0},r.push(l))}if(r.length!==0){for(;r.length>0;)for(let o=0;o<r.length;o++){const l=r[o],h=f(n[l]);if(h.max<=h.currentEm+h.val){r.splice(o,1),--o;continue}const u=h.basePrice*1.15**(h.currentEm+h.val);u<=i?(i-=u,h.priceSum+=u,h.val+=1,e.requestGameUiRefresh=!0):(r.splice(o,1),--o)}for(const[,o]of L(n))o.val!==0&&(i=this._workshopManager.getValueAvailable("culture"),i<o.priceSum&&console.warn(...b("Something has gone horribly wrong.",o.priceSum,i)),this._workshopManager.getResource("culture").value-=o.priceSum,o.race.embassyLevel+=o.val,this._host.engine.storeForSummary("embassy",o.val),o.val!==1?this._host.engine.iactivity("build.embassies",[o.val,o.race.title],"ks-build"):this._host.engine.iactivity("build.embassy",[o.val,o.race.title],"ks-build"))}}autoFeedElders(){const e=this._host.game.diplomacy.get("leviathans"),t=this._host.game.resPool.get("necrocorn");!e.unlocked||t.value===0||(1<=t.value?e.energy<this._host.game.diplomacy.getMarkerCap()&&(this._host.game.diplomacy.feedElders(),this._host.engine.iactivity("act.feed"),this._host.engine.storeForSummary("feed",1)):.25*(1+this._host.game.getEffect("corruptionBoostRatio"))<1&&(this._host.engine.storeForSummary("feed",t.value),this._host.game.diplomacy.feedElders(),this._host.engine.iactivity("dispose.necrocorn")))}autoUnlock(e){if(!this._host.game.tabs[4].visible)return;const t=this._host.game.diplomacy.get("leviathans").unlocked?8:7;if(this._host.game.diplomacyTab.racePanels.length<t){let i=this._workshopManager.getValueAvailable("manpower");if(!this._host.game.diplomacy.get("lizards").unlocked&&i>=1e3){this._host.game.resPool.get("manpower").value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("sharks").unlocked&&i>=1e3){this._host.game.resPool.get("manpower").value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("griffins").unlocked&&i>=1e3){this._host.game.resPool.get("manpower").value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("nagas").unlocked&&this._host.game.resPool.get("culture").value>=1500&&i>=1e3){this._host.game.resPool.get("manpower").value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("zebras").unlocked&&this._host.game.resPool.get("ship").value>=1&&i>=1e3){this._host.game.resPool.get("manpower").value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("spiders").unlocked&&f(this._host.game.resPool.get("ship")).value>=100&&f(this._host.game.resPool.get("science")).maxValue>125e3&&i>=1e3){f(this._host.game.resPool.get("manpower")).value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}if(!this._host.game.diplomacy.get("dragons").unlocked&&this._host.game.science.get("nuclearFission").researched&&i>=1e3){f(this._host.game.resPool.get("manpower")).value-=1e3;const s=f(this._host.game.diplomacy.unlockRandomRace());this._host.engine.iactivity("upgrade.race",[s.title],"ks-upgrade"),i-=1e3,e.requestGameUiRefresh=!0}}}autoTradeBlackcoin(){const e=this._host.game.calendar.cryptoPrice,t=this._host.game.resPool.get("relic").value,i=this._host.game.resPool.get("blackcoin").value;let s=0,a=0;if(e<this.settings.tradeBlackcoin.buy&&this.settings.tradeBlackcoin.trigger<t){this._host.game.diplomacy.buyBcoin();const n=this._host.game.resPool.get("blackcoin").value;s=Math.round(n-i),this._host.engine.iactivity("act.blackcoin.buy",[this._host.renderAbsolute(s)])}else if(e>this.settings.tradeBlackcoin.sell&&0<this._host.game.resPool.get("blackcoin").value){this._host.game.diplomacy.sellBcoin();const n=f(this._host.game.resPool.get("relic")).value;a=Math.round(n-t),this._host.engine.iactivity("act.blackcoin.sell",[this._host.renderAbsolute(a)])}}trade(e,t){const i=this.getRace(e);this._host.game.diplomacy.tradeMultiple(i,t),this._host.engine.storeForSummary(i.title,t,"trade"),this._host.engine.iactivity("act.trade",[this._host.renderAbsolute(t),G(i.title)],"ks-trade")}getProfitability(e){const t=this.getRace(e);let i=0;const s=this.getMaterials(e);for(const[r,o]of L(s)){const l=this._workshopManager.getTickVal(this._workshopManager.getResource(r));if(l!=="ignore"){if(l<=0)return!1;i+=o/l}}let a=0;const n=this.getAverageTrade(t);for(const[r,o]of L(n)){const l=this._workshopManager.getResource(r),h=this._workshopManager.getTickVal(l);if(h!=="ignore"){if(h<=0)return!0;a+=0<l.maxValue?Math.min(o,Math.max(l.maxValue-l.value,0))/h:o/h}}return i<=a}getAverageTrade(e){const t=this._host.game.getEffect("standingRatio")+this._host.game.diplomacy.calculateStandingFromPolicies(e.name,this._host.game),i=1+e.energy*.02,s=1+this._host.game.diplomacy.getTradeRatio()+this._host.game.diplomacy.calculateTradeBonusFromPolicies(e.name,this._host.game),a=e.standing<0?e.standing+t:0,n=0<a?1+a:1,r=0<e.standing?Math.min(e.standing+t/2,1):0,o={};for(const u of e.sells){if(!this._isValidTrade(u,e)){o[u.name]=0;continue}let d=0;const m=e.embassyPrices?u.chance*(1+this._host.game.getLimitedDR(.01*e.embassyLevel,.75)):u.chance;if(e.name==="zebras"&&u.name==="titanium"){const v=this._host.game.resPool.get("ship").value,p=Math.min(.15+v*.0035,1);d=1.5*(1+v/50)*(n*p)}else{const v=u.seasons?1+u.seasons[this._host.game.calendar.getCurSeason().name]:1,p=(n-r)*Math.min(m/100,1),w=r*Math.min(m/100,1);d=(p+1.25*w)*u.value*i*v*s}o[u.name]=d}const l=e.embassyPrices?.35*(1+.01*e.embassyLevel):.35,h=n*Math.min(l,1);return o.spice=25*h+50*h*s/2,o.blueprint=.1*n,o}_isValidTrade(e,t){return!(e.minLevel&&t.embassyLevel<e.minLevel)&&(this._host.game.resPool.get(e.name).unlocked||e.name==="titanium"||e.name==="uranium"||t.name==="leviathans")}getLowestTradeAmount(e,t,i){let s;const a=this.getMaterials(e);let n;for(const[h,u]of L(a)){if(h==="manpower"){let d=u;this._host.game.challenges.isActive("postApocalypse")&&(d=u*(1+this._host.game.bld.getPollutionLevel())),n=this._workshopManager.getValueAvailable(h)/d}else if(h==="gold"){let d=u;this._host.game.challenges.isActive("postApocalypse")&&(d=u*(1+this._host.game.bld.getPollutionLevel())),n=this._workshopManager.getValueAvailable(h)/d}else n=this._workshopManager.getValueAvailable(h)/u;s=s===void 0||n<s?n:s}if(s=Math.floor(s??0),s===0)return 0;if(e===null||e==="leviathans")return s;const r=this.getRace(e);let o=0;const l=this.getAverageTrade(r);for(const h of r.sells){const u=this._workshopManager.getResource(h.name);let d=0;if(!u.maxValue)continue;d=f(l[h.name]);const m=Math.max((u.maxValue-u.value)/d,0);o=m<o?o:m}return o=Math.ceil(o),o===0?0:(s=o<s?Math.max(o-1,1):s,Math.floor(s))}getMaterials(e=null){const t={gold:15-this._host.game.getEffect("tradeGoldDiscount"),manpower:50-this._host.game.getEffect("tradeCatpowerDiscount")};if(g(e))return t;const i=this.getRace(e).buys;for(const s of i)t[s.name]=s.val;return t}getRace(e){const t=this._host.game.diplomacy.get(e);if(g(t))throw new Error(`Unable to retrieve race '${e}'`);return t}singleTradePossible(e,t,i,s){const a=s?te.evaluateSubSectionTrigger(e,s.trigger):e;if(a<0&&s===void 0)return!0;if(a<0&&s!==void 0||t.value/t.maxValue<a||i.value/i.maxValue<a)return!1;const n=this.getMaterials(s?.race);for(const[r,o]of L(n))if(this._workshopManager.getValueAvailable(r)<o)return!1;return!0}}class hn{_host;_cache=new Array;_cacheSum={};constructor(e){this._host=e}pushToCache(e){this._cache.push(e);for(const[t,i]of L(e.materials))this._cacheSum[t]||(this._cacheSum[t]=0),this._cacheSum[t]+=i;for(let t=0;t<this._cache.length;++t){const i=this._cache[t];if(this._cache.length>1e4){const s=i.materials;for(const[a,n]of L(s))this._cacheSum[a]||(this._cacheSum[a]=0),this._cacheSum[a]-=n;this._cache.shift(),t--}else return}}getResValue(e){if(this._cache.length===0||!this._cacheSum[e])return 0;const t=this._host.game.timer.ticksTotal,i=this._cache[0].timeStamp;return this._cacheSum[e]/(t-i)}}class un{_host;settings;_cacheManager;_workshopManager;constructor(e,t,i=new $i){this._host=e,this.settings=i,this._cacheManager=new hn(this._host),this._workshopManager=t}tick(e){this.settings.enabled&&(this.autoDistributeKittens(e),this.settings.hunt.enabled&&this.autoHunt(this._cacheManager),this.settings.holdFestivals.enabled&&this.autoFestival(this._cacheManager),this.settings.electLeader.enabled&&this.autoElect(),this.settings.promoteLeader.enabled&&this.autoPromoteLeader(),this.settings.promoteKittens.enabled&&this.autoPromoteKittens())}autoDistributeKittens(e){const t=this._host.game.village.getFreeKittens();if(t){for(let i=0;i<t;++i){const s=new Array;for(const r of this._host.game.village.jobs){const o=this.settings.jobs[r.name].enabled,l=r.unlocked;if(!o||!l)continue;const h=this._host.game.village.getJobLimit(r.name),u=Z(this.settings.jobs[r.name].max),d=r.value;d<h&&d<u&&s.push({count:d,job:r,toCap:h-d})}if(!s.length)return;const a=!g(s.find(r=>r.job.name==="farmer"&&r.count===0));s.sort((r,o)=>r.count-o.count);const n=a?"farmer":s[0].job.name;this._host.game.village.assignJob(this._host.game.village.getJob(n),1),e.requestGameUiRefresh=!0,this._host.engine.iactivity("act.distribute",[this._host.engine.i18n(`$village.job.${n}`)],"ks-distribute")}this._host.engine.storeForSummary("distribute",t)}}autoElect(){if(this._host.game.challenges.isActive("anarchy"))return;const e=this._host.game.village.sim.kittens,t=this._host.game.village.leader,i=this.settings.electLeader.job.selected,s=this.settings.electLeader.trait.selected,a=e.filter(r=>(r.job===i||i==="any")&&r.trait.name===s);if(a.length===0)return;a.sort((r,o)=>o.rank-r.rank);const n=a[0];!g(t)&&t.trait.name===s&&(t.job===i||i==="any")&&n.rank<=t.rank||(this._host.game.village.makeLeader(n),this._host.engine.iactivity("act.elect"))}autoPromoteKittens(){const e=this._workshopManager.getResource("gold");if(!(this.settings.promoteKittens.trigger<e.value/e.maxValue))for(let t=0;t<this._host.game.village.sim.kittens.length;t++){let i=-1;const s=this._host.game.village.sim.kittens[t].engineerSpeciality;if(!g(s)&&(i=f(this._host.game.workshop.getCraft(s)).tier,!(i<=this._host.game.village.sim.kittens[t].rank))){this._host.game.village.promoteKittens();return}}}autoPromoteLeader(){if(this._host.game.science.get("civil").researched&&this._host.game.village.leader!==null){const e=this._host.game.village.leader,t=e.rank,i=this._workshopManager.getResource("gold"),s=this._workshopManager.getStock("gold");this._host.game.village.sim.goldToPromote(t,t+1,i.value-s)[0]&&this._host.game.village.sim.promote(e,t+1)===1&&(this._host.engine.iactivity("act.promote",[t+1],"ks-promote"),this._host.game.villageTab.censusPanel?.census.renderGovernment(this._host.game.villageTab.censusPanel.census.container),this._host.game.villageTab.censusPanel?.census.update(),this._host.engine.storeForSummary("promote",1))}}autoHunt(e){const t=this._workshopManager.getResource("manpower"),i=this.settings.hunt.trigger;if(!(t.value<100||this._host.game.challenges.isActive("pacifism"))&&i<=t.value/t.maxValue&&100<=t.value){const s=Math.floor(t.value/100);this._host.engine.storeForSummary("hunt",s),this._host.engine.iactivity("act.hunt",[this._host.renderAbsolute(s)],"ks-hunt");const a=this._workshopManager.getAverageHunt(),n={};for(const[r,o]of L(a)){const l=this._workshopManager.getResource(r);n[r]=0<l.maxValue?Math.min(o*s,Math.max(l.maxValue-l.value,0)):o*s}g(e)||e.pushToCache({materials:n,timeStamp:this._host.game.timer.ticksTotal}),this._host.game.village.huntAll()}}autoFestival(e){if(!this._host.game.science.get("drama").researched||400<this._host.game.calendar.festivalDays||!this._host.game.prestige.getPerk("carnivals").researched&&0<this._host.game.calendar.festivalDays)return;const t=this._workshopManager;if(t.getValueAvailable("manpower")<1500||t.getValueAvailable("culture")<5e3||t.getValueAvailable("parchment")<2500)return;const i=4e3*t.getTickVal(t.getResource("manpower"),e,!0)>1500,s=4e3*t.getTickVal(t.getResource("culture"),e,!0)>5e3,a=4e3*t.getTickVal(t.getResource("parchment"),e,!0)>2500;if(!i&&!s&&!a)return;const n=this._host.game.calendar.festivalDays,r=new classes.village.ui.FestivalButtonController(this._host.game),o=r.fetchModel({controller:r,description:"",handler:()=>{this._host.game.village.holdFestival(1)},name:"",prices:[{name:"manpower",val:1500},{name:"culture",val:5e3},{name:"parchment",val:2500}]});r.buyItem(o),this._host.engine.storeForSummary("festival"),n>0?this._host.engine.iactivity("festival.extend",[],"ks-festival"):this._host.engine.iactivity("festival.hold",[],"ks-festival")}}const Li={"de-DE":Ss,"en-US":Cs,"he-IL":xs,"zh-CN":Ts};class te{_i18nData;_isLoaded=!1;get isLoaded(){return this._isLoaded}_host;settings;bonfireManager;religionManager;scienceManager;spaceManager;timeControlManager;timeManager;tradeManager;villageManager;workshopManager;_activitySummary;_timeoutMainLoop=void 0;constructor(e,t){this.settings=new Ei,this._i18nData=Li,this.setLanguage(t,!1),this._host=e,this._activitySummary=new _s(this._host),this.workshopManager=new Ti(this._host),this.bonfireManager=new ks(this._host,this.workshopManager),this.religionManager=new Es(this._host,this.bonfireManager,this.workshopManager),this.scienceManager=new Is(this._host,this.workshopManager),this.spaceManager=new Os(this._host,this.workshopManager),this.timeControlManager=new on(this._host,this.bonfireManager,this.religionManager,this.spaceManager,this.workshopManager),this.timeManager=new ln(this._host,this.workshopManager),this.tradeManager=new cn(this._host,this.workshopManager),this.villageManager=new un(this._host,this.workshopManager)}isLanguageSupported(e){return Object.keys(this._i18nData).some(t=>t.startsWith(`${e}-`))}isLocaleSupported(e){return e in this._i18nData}localeSupportsFirstLetterSplits(e=this.settings.locale.selected){return e!=="zh-CN"}localeForLanguage(e){return Object.keys(this._i18nData).find(t=>t.startsWith(`${e}-`))}setLanguage(e,t=!0){const i=this.settings.locale.selected;if(!this.isLanguageSupported(e))console.warn(...b(`Requested language '${e}' is not available. Falling back to '${we}'.`)),this.settings.locale.selected=we;else{const s=f(this.localeForLanguage(e));console.info(...b(`Selecting language '${s}'.`)),this.settings.locale.selected=s}i!==this.settings.locale.selected&&t&&this._host.rebuildUi()}setLocale(e,t=!0){const i=this.settings.locale.selected;this.isLocaleSupported(e)?(console.info(...b(`Selecting language '${e}'.`)),this.settings.locale.selected=e):(console.warn(...b(`Requested language '${e}' is not available. Falling back to '${we}'.`)),this.settings.locale.selected=we),i!==this.settings.locale.selected&&t&&this._host.rebuildUi()}stateLoad(e,t=!1){this._isLoaded=!0,this.stop(!1);const i=Ae();e.v!==i&&console.warn(...b(`Attempting to load engine state with version tag '${e.v}' when engine is at version '${i}'!`));const s=(a,n)=>{try{a()}catch(r){console.error(...b(`Failed load of ${n} settings.`,r))}};s(()=>{this.settings.load(e.engine,t)},"engine"),s(()=>{this.bonfireManager.settings.load(e.bonfire)},"bonfire"),s(()=>{this.religionManager.settings.load(e.religion)},"religion"),s(()=>{this.scienceManager.settings.load(e.science)},"science"),s(()=>{this.spaceManager.settings.load(e.space)},"space"),s(()=>{this.timeControlManager.settings.load(e.timeControl)},"time control"),s(()=>{this.timeManager.settings.load(e.time)},"time"),s(()=>{this.tradeManager.settings.load(e.trade)},"trade"),s(()=>{this.villageManager.settings.load(e.village)},"village"),s(()=>{this.workshopManager.settings.load(e.workshop)},"workshop"),this.setLocale(this.settings.locale.selected),this.settings.enabled?this.start(!1):this.stop(!1)}static get DEFAULT_STATE(){return{bonfire:new ft,engine:new Ei,religion:new pt,science:new bt,space:new ze,time:new Bi,timeControl:new Ai,trade:new Ii,v:Ae(),village:new $i,workshop:new Fe}}stateReset(){this.stateLoad(te.DEFAULT_STATE)}stateSerialize(){return{bonfire:this.bonfireManager.settings,engine:this.settings,religion:this.religionManager.settings,science:this.scienceManager.settings,space:this.spaceManager.settings,time:this.timeManager.settings,timeControl:this.timeControlManager.settings,trade:this.tradeManager.settings,v:Ae(),village:this.villageManager.settings,workshop:this.workshopManager.settings}}start(e=!0){if(this._timeoutMainLoop)return;const t=()=>{const i={entry:Date.now(),exit:0,measurements:{},purchaseOrders:[],requestGameUiRefresh:!1};this._iterate(i).then(()=>{i.exit=Date.now();const s=i.exit-i.entry;document.dispatchEvent(new CustomEvent("ks.reportFrame",{detail:i})),this._timeoutMainLoop!==void 0&&(this._timeoutMainLoop=x.window.setTimeout(t,Math.max(10,this._host.engine.settings.interval-s)))}).catch(s=>{console.warn(...b(rs(s)))})};this._timeoutMainLoop=x.window.setTimeout(t,this._host.engine.settings.interval),e&&this._host.engine.imessage("status.ks.enable")}stop(e=!0){this._timeoutMainLoop&&(clearTimeout(this._timeoutMainLoop),this._timeoutMainLoop=void 0,e&&this._host.engine.imessage("status.ks.disable"))}async _iterate(e){this.settings.filters.disableKGLog.enabled||this._maintainKGLogFilters();let[,t]=await Le(()=>this.scienceManager.tick(e));e.measurements.scienceManager=t,[,t]=de(()=>{this.bonfireManager.tick(e)}),e.measurements.bonfireManager=t,[,t]=de(()=>{this.spaceManager.tick(e)}),e.measurements.spaceManager=t,[,t]=await Le(()=>this.workshopManager.tick(e)),e.measurements.workshopManager=t,[,t]=de(()=>{this.tradeManager.tick(e)}),e.measurements.tradeManager=t,[,t]=await Le(()=>this.religionManager.tick(e)),e.measurements.religionManager=t,[,t]=de(()=>{this.timeManager.tick(e)}),e.measurements.timeManager=t,[,t]=de(()=>{this.villageManager.tick(e)}),e.measurements.villageManager=t,[,t]=await Le(()=>this.timeControlManager.tick(e)),e.measurements.timeControlManager=t,[,t]=de(()=>{e.requestGameUiRefresh&&!document.hidden&&this._host.game.ui.render()}),e.measurements.gameUiRefresh=t}_maintainKGLogFilters(){for(const t of Object.values(this._host.game.console.filters))t.enabled=!1;const e=x.window.document.querySelectorAll("[id^=filter-]");for(const t of e)t.checked=!1}symbolForCycle(e){return this._host.game.calendar.cycles.find(t=>t.name===e)?.uglyph??""}labelForCycle(e){const t=this.symbolForCycle(e),i=this._host.engine.i18n(`$space.planet.${e==="redmoon"?"moon":e}.label`);return`${t} ${i}`}labelForPlanet(e){const t=e==="moon"?"redmoon":e,i=ge.includes(t)?t:void 0,s=this._host.engine.i18n(`$space.planet.${e}.label`);return i===void 0?s:`${this.symbolForCycle(i)} ${s}`}i18n(e,t=[]){let i;if(e.startsWith("$")&&(i=this._host.i18nEngine(e.slice(1))),i=i??this._i18nData[this.settings.locale.selected][e],g(i)){if(i=Li[we][e],!i)return console.warn(...b(`i18n key '${e}' not found in default language.`)),`$${e}`;console.warn(...b(`i18n key '${e}' not found in selected language.`))}for(let a=0;a<t.length;++a)i=i.replace(`{${a}}`,`${t[a]}`);return i}iactivity(e,t=[],i){const s=this.i18n(e,t);if(i){const a=`type_${i}`;this.printOutput(`ks-activity ${a}`,"#e65C00",s)}else this.printOutput("ks-activity","#e65C00",s)}imessage(e,t=[]){this.printOutput("ks-default","#aa50fe",this.i18n(e,t))}storeForSummary(e,t=1,i="other"){this._activitySummary.storeActivity(e,t,i)}getSummary(){return this._activitySummary.renderSummary()}displayActivitySummary(){const e=this.getSummary();for(const t of e)this.printOutput("ks-summary","#009933",t);this.resetActivitySummary()}resetActivitySummary(){this._activitySummary.resetActivity()}printOutput(e,t,i){if(this.settings.filters.enabled){for(const a of Object.values(this.settings.filters.filters))if(a.variant===e&&!a.enabled)return}const s=this._host.game.msg(i,e);$(s.span).css("color",t)}static evaluateSubSectionTrigger(e,t){return e<0?t:t<0?e:t}}const Oi=c=>Number.isFinite(c)?c:0,dn=c=>({days:Math.trunc(c/864e5),hours:Math.trunc(c/36e5%24),minutes:Math.trunc(c/6e4%60),seconds:Math.trunc(c/1e3%60),milliseconds:Math.trunc(c%1e3),microseconds:Math.trunc(Oi(c*1e3)%1e3),nanoseconds:Math.trunc(Oi(c*1e6)%1e3)}),gn=c=>({days:c/86400000n,hours:c/3600000n%24n,minutes:c/60000n%60n,seconds:c/1000n%60n,milliseconds:c%1000n,microseconds:0n,nanoseconds:0n}),mn=c=>{switch(typeof c){case"number":{if(Number.isFinite(c))return dn(c);break}case"bigint":return gn(c)}throw new TypeError("Expected a finite number or bigint")},fn=c=>c===0||c===0n,pn=(c,e)=>e===1||e===1n?c:`${c}s`,bn=1e-7,vn=24n*60n*60n*1000n,yn=(c,e={colonNotation:!1,compact:!1,formatSubMilliseconds:!1,keepDecimalsOnWholeSeconds:!1,millisecondsDecimalDigits:0,secondsDecimalDigits:1,separateMilliseconds:!1,unitCount:1/0,verbose:!1})=>{const t=typeof c=="bigint";if(!t&&!Number.isFinite(c))throw new TypeError("Expected a finite number or bigint");const i={...e};i.colonNotation&&(i.compact=!1,i.formatSubMilliseconds=!1,i.separateMilliseconds=!1,i.verbose=!1),i.compact&&(i.unitCount=1,i.secondsDecimalDigits=0,i.millisecondsDecimalDigits=0);let s=[];const a=(h,u)=>{const d=Math.floor(h*10**u+bn);return(Math.round(d)/10**u).toFixed(u)},n=(h,u,d,m)=>{if(!((s.length===0||!i.colonNotation)&&fn(h)&&!(i.colonNotation&&d==="m"))){if(m??=String(h),i.colonNotation){const v=m.includes(".")?m.split(".")[0].length:m.length,p=s.length>0?2:1;m="0".repeat(Math.max(0,p-v))+m}else m+=i.verbose?" "+pn(u,h):d;s.push(m)}},r=mn(c),o=BigInt(r.days);if(n(o/365n,"year","y"),n(o%365n,"day","d"),n(Number(r.hours),"hour","h"),n(Number(r.minutes),"minute","m"),i.separateMilliseconds||i.formatSubMilliseconds||!i.colonNotation&&c<1e3){const h=Number(r.seconds),u=Number(r.milliseconds),d=Number(r.microseconds),m=Number(r.nanoseconds);if(n(h,"second","s"),i.formatSubMilliseconds)n(u,"millisecond","ms"),n(d,"microsecond","µs"),n(m,"nanosecond","ns");else{const v=u+d/1e3+m/1e6,p=typeof i.millisecondsDecimalDigits=="number"?i.millisecondsDecimalDigits:0,w=v>=1?Math.round(v):Math.ceil(v),C=p?v.toFixed(p):w.toString();n(Number.parseFloat(C),"millisecond","ms",C)}}else{const h=(t?Number(c%vn):c)/1e3%60,u=typeof i.secondsDecimalDigits=="number"?i.secondsDecimalDigits:1,d=a(h,u),m=i.keepDecimalsOnWholeSeconds?d:d.replace(/\.0+$/,"");n(Number.parseFloat(m),"second","s",m)}if(s.length===0)return"0"+(i.verbose?" milliseconds":"ms");const l=i.colonNotation?":":" ";return typeof i.unitCount=="number"&&(s=s.slice(0,Math.max(i.unitCount,1))),s.join(l)},M={Bonfire:"M80-80v-183l363-491-67-90 49-35 55 75 56-75 48 35-66 90 362 491v183H80Zm400-623L140-243v103h145l195-273 195 273h145v-103L480-703ZM359-140h242L480-310 359-140Zm121-273 195 273-195-273-195 273 195-273Z",CheckboxCheck:"m419-321 289-289-43-43-246 246-119-119-43 43 162 162ZM120-120v-720h720v720H120Zm60-60h600v-600H180v600Zm0 0v-600 600Z",CheckboxUnCheck:"M120-120v-720h720v720H120Zm60-60h600v-600H180v600Z",Copy:"M240-200v-680h560v680H240Zm60-60h440v-560H300v560ZM120-80v-680h60v620h500v60H120Zm180-180v-560 560Z",Cycles:"M120-80v-740h125v-60h65v60h340v-60h65v60h125v360h-60v-110H180v430h324v60H120ZM760 0q-73 0-127.5-45.5T564-160h62q13 44 49.5 72T760-60q58 0 99-41t41-99q0-58-41-99t-99-41q-29 0-54 10.5T662-300h58v60H560v-160h60v57q27-26 63-41.5t77-15.5q83 0 141.5 58.5T960-200q0 83-58.5 141.5T760 0ZM180-630h600v-130H180v130Zm0 0v-130 130Z",DataUsage:"M480-80q-82 0-155-31.5T197.5-197q-54.5-54-86-127T80-479q0-158 106.5-272T451-877v102q-115 11-192 95.5T182-479q0 124 87 210.5T480-182q72 0 136-32.5T725-306l88 51q-58 83-145.5 129T480-80Zm362-229-88-49q12-31 18-61.5t6-60.5q0-116-76.5-201T511-776v-102q157 11 263 124.5T880-484q0 45-9.5 88.5T842-309Z",Delete:"M201-120v-630h-41v-60h188v-30h264v30h188v60h-41v630H201Zm60-60h438v-570H261v570Zm106-86h60v-399h-60v399Zm166 0h60v-399h-60v399ZM261-750v570-570Z",Draft:"M160-80v-800h421l219 219v581H160Zm391-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z",Eco:"M213-175q-43.59-45-68.3-104Q120-338 120-400q0-73 25.5-133.5T222-645q35-35 87-59t122.5-37.5Q502-755 591-758.5t198 3.5q8 108 5.5 197.5t-16 160.75q-13.5 71.25-38 124.56Q716-218.87 680-183q-51 51-110 77T444-80q-69 0-126.5-23.5T213-175Zm103 0q25 17 58 26t69.92 9Q497-140 547-162t91-64q27-27 46-70.5t31-103Q727-459 731-534t0-165q-94-2-168.5 2.5T431-680q-57 12-98 30.5T266-604q-42 43-64 91t-22 98q0 48 20.5 100.5T251-230q53-98 127-176t157-123q-87 75-141 162.5T316-175Zm0 0Zm0 0Z",Edit:"M180-180h44l472-471-44-44-472 471v44Zm-60 60v-128l617-616 128 128-617 616H120Zm659-617-41-41 41 41Zm-105 64-22-22 44 44-22-22Z",ExpandCircleDown:"m480-351 173-173-43-42-130 130-130-130-43 42 173 173Zm0 271q-82 0-155-31.5t-127.5-86Q143-252 111.5-325T80-480q0-83 31.5-156t86-127Q252-817 325-848.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 82-31.5 155T763-197.5q-54 54.5-127 86T480-80Zm0-60q142 0 241-99.5T820-480q0-142-99-241t-241-99q-141 0-240.5 99T140-480q0 141 99.5 240.5T480-140Zm0-340Z",ExpandCircleUp:"m350-394 130-130 130 130 43-42-173-173-173 173 43 42ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-155.5t85.5-127q54-54.5 127-86T480-880q83 0 155.5 31.5t127 86q54.5 54.5 86 127T880-480q0 83-31.5 156t-86 127q-54.5 54-127 85.5T480-80Zm0-60q141 0 240.5-99T820-480q0-141-99.5-240.5T480-820q-142 0-241 99.5T140-480q0 142 99 241t241 99Zm0-340Z",Import:"M450-160v-371L330-411l-43-43 193-193 193 193-43 43-120-120v371h-60ZM160-597v-203h640v203h-60v-143H220v143h-60Z",Religion:"M40-120v-560q0-45.83 32.12-77.92 32.12-32.08 78-32.08T228-757.92q32 32.09 32 77.92v31l220-191 220 191v-31q0-45.83 32.12-77.92 32.12-32.08 78-32.08T888-757.92q32 32.09 32 77.92v560H530v-250H430v250H40Zm720-510h100v-49.82q0-21.18-14.32-35.68-14.33-14.5-35.5-14.5-21.18 0-35.68 14.37Q760-701.25 760-680v50Zm-660 0h100v-49.82q0-21.18-14.32-35.68-14.33-14.5-35.5-14.5-21.18 0-35.68 14.37Q100-701.25 100-680v50Zm0 450h100v-390H100v390Zm160 0h110v-250h220v250h110v-390L480-761 260-570v390Zm500 0h100v-390H760v390ZM479.94-505Q457-505 441-521.06q-16-16.06-16-39T441.06-599q16.06-16 39-16T519-598.94q16 16.06 16 39T518.94-521q-16.06 16-39 16Z",Reset:"M480-160q-133 0-226.5-93.5T160-480q0-133 93.5-226.5T480-800q85 0 149 34.5T740-671v-129h60v254H546v-60h168q-38-60-97-97t-137-37q-109 0-184.5 75.5T220-480q0 109 75.5 184.5T480-220q83 0 152-47.5T728-393h62q-29 105-115 169t-195 64Z",Resources:"M120-40v-880h60v80h600v-80h60v880h-60v-80H180v80h-60Zm60-469h110v-160h220v160h270v-271H180v271Zm0 329h270v-160h220v160h110v-269H180v269Zm170-329h100v-100H350v100Zm160 329h100v-100H510v100ZM350-509h100-100Zm160 329h100-100Z",Save:"M840-683v563H120v-720h563l157 157Zm-60 27L656-780H180v600h600v-476ZM479.76-245q43.24 0 73.74-30.26 30.5-30.27 30.5-73.5 0-43.24-30.26-73.74-30.27-30.5-73.5-30.5-43.24 0-73.74 30.26-30.5 30.27-30.5 73.5 0 43.24 30.26 73.74 30.27 30.5 73.5 30.5ZM233-584h358v-143H233v143Zm-53-72v476-600 124Z",SaveAs:"M120-120v-720h563l157 157v117l-60 60v-150L656-780H180v600h280v60H120Zm60-660v600-600ZM520-40v-123l263-262 122 122L643-40H520Zm300-263-37-37 37 37ZM580-100h38l121-122-18-19-19-18-122 121v38Zm141-141-19-18 37 37-18-19ZM233-584h358v-143H233v143Zm247 339q14 0 27-3t24-10l39-40q7-11 10.5-24t3.5-27q0-43.33-30.26-73.67Q523.47-453 480.24-453q-43.24 0-73.74 30.26-30.5 30.27-30.5 73.5 0 43.24 30.33 73.74Q436.67-245 480-245Z",Seasons:"M306-394q-17 0-28.5-11.5T266-434q0-17 11.5-28.5T306-474q17 0 28.5 11.5T346-434q0 17-11.5 28.5T306-394Zm177 0q-17 0-28.5-11.5T443-434q0-17 11.5-28.5T483-474q17 0 28.5 11.5T523-434q0 17-11.5 28.5T483-394Zm170 0q-17 0-28.5-11.5T613-434q0-17 11.5-28.5T653-474q17 0 28.5 11.5T693-434q0 17-11.5 28.5T653-394ZM120-80v-740h125v-60h65v60h340v-60h65v60h125v740H120Zm60-60h600v-430H180v430Zm0-490h600v-130H180v130Zm0 0v-130 130Z",Settings:"m388-80-20-126q-19-7-40-19t-37-25l-118 54-93-164 108-79q-2-9-2.5-20.5T185-480q0-9 .5-20.5T188-521L80-600l93-164 118 54q16-13 37-25t40-18l20-127h184l20 126q19 7 40.5 18.5T669-710l118-54 93 164-108 77q2 10 2.5 21.5t.5 21.5q0 10-.5 21t-2.5 21l108 78-93 164-118-54q-16 13-36.5 25.5T592-206L572-80H388Zm48-60h88l14-112q33-8 62.5-25t53.5-41l106 46 40-72-94-69q4-17 6.5-33.5T715-480q0-17-2-33.5t-7-33.5l94-69-40-72-106 46q-23-26-52-43.5T538-708l-14-112h-88l-14 112q-34 7-63.5 24T306-642l-106-46-40 72 94 69q-4 17-6.5 33.5T245-480q0 17 2.5 33.5T254-413l-94 69 40 72 106-46q24 24 53.5 41t62.5 25l14 112Zm44-210q54 0 92-38t38-92q0-54-38-92t-92-38q-54 0-92 38t-38 92q0 54 38 92t92 38Zm0-130Z",Space:"m187-551 106 45q18-36 38.5-71t43.5-67l-79-16-109 109Zm154 81 133 133q57-26 107-59t81-64q81-81 119-166t41-192q-107 3-192 41T464-658q-31 31-64 81t-59 107Zm229-96q-20-20-20-49.5t20-49.5q20-20 49.5-20t49.5 20q20 20 20 49.5T669-566q-20 20-49.5 20T570-566Zm-15 383 109-109-16-79q-32 23-67 43.5T510-289l45 106Zm326-694q9 136-34 248T705-418l-2 2-2 2 22 110q3 15-1.5 29T706-250L535-78l-85-198-170-170-198-85 172-171q11-11 25-15.5t29-1.5l110 22q1-1 2-1.5t2-1.5q99-99 211-142.5T881-877ZM149-325q35-35 85.5-35.5T320-326q35 35 34.5 85.5T319-155q-26 26-80.5 43T75-80q15-109 31.5-164t42.5-81Zm42 43q-14 15-25 47t-19 82q50-8 82-19t47-25q19-17 19.5-42.5T278-284q-19-18-44.5-17.5T191-282Z",State:"M820-240v-480h60v480h-60Zm-340 1-43-42 169-169H80v-60h526L438-679l42-42 241 241-241 241Z",Summary:"M279-621h60v-60h-60v60Zm0 171h60v-60h-60v60Zm0 171h60v-60h-60v60ZM120-120v-720h522l198 198v522H120Zm60-60h600v-429H609v-171H180v600Zm0-600v171.43V-780v600-600Z",Sync:"M167-160v-60h130l-15-12q-64-51-93-111t-29-134q0-106 62.5-190.5T387-784v62q-75 29-121 96.5T220-477q0 63 23.5 109.5T307-287l30 21v-124h60v230H167Zm407-15v-63q76-29 121-96.5T740-483q0-48-23.5-97.5T655-668l-29-26v124h-60v-230h230v60H665l15 14q60 56 90 120t30 123q0 106-62 191T574-175Z",Time:"m627-287 45-45-159-160v-201h-60v225l174 181ZM480-80q-82 0-155-31.5t-127.5-86Q143-252 111.5-325T80-480q0-82 31.5-155t86-127.5Q252-817 325-848.5T480-880q82 0 155 31.5t127.5 86Q817-708 848.5-635T880-480q0 82-31.5 155t-86 127.5Q708-143 635-111.5T480-80Zm0-400Zm0 340q140 0 240-100t100-240q0-140-100-240T480-820q-140 0-240 100T140-480q0 140 100 240t240 100Z",Trigger:"m393-165 279-335H492l36-286-253 366h154l-36 255Zm-73 85 40-280H160l360-520h80l-40 320h240L400-80h-80Zm154-396Z",Workshop:"M768-120 517-371l57-57 251 251-57 57Zm-581 0-57-57 290-290-107-107-23 23-44-44v85l-24 24-122-122 24-24h86l-48-48 131-131q17-17 37-23t44-6q24 0 44 8.5t37 25.5L348-699l48 48-24 24 104 104 122-122q-8-13-12.5-30t-4.5-36q0-53 38.5-91.5T711-841q15 0 25.5 3t17.5 8l-85 85 75 75 85-85q5 8 8.5 19.5T841-709q0 53-38.5 91.5T711-579q-18 0-31-2.5t-24-7.5L187-120Z"};class N{static nextComponentId=0;componentId;host;parent;options;_element;set element(e){this._element=e,this._element[0].id=`KS${Object.getPrototypeOf(this).constructor.name}#${this.componentId}`}get element(){return f(this._element)}children=new Set;constructor(e,t){this.componentId=N.nextComponentId++,this.host=e.host,this.options=t,this.parent=e instanceof N?e:null,this._needsRefresh=!1}_needsRefresh;requestRefresh(e=!1,t=0,i=!1){if(i&&console.debug(...b(t<0?"⤒".repeat(t*-1):" ".repeat(t),this.toString(),"requestRefresh()")),this.options?.onRefreshRequest?.call(this),this.parent!==this&&!e&&this.parent?.requestRefresh(!1,t-1,i),this._needsRefresh&&i&&console.debug(...b(t<0?"⤒".repeat(t*-1):" ".repeat(t),this.toString(),"requestRefresh() <already pending>")),this._needsRefresh=!0,e){i&&console.debug(...b(t<0?"⤒".repeat(t*-1):" ".repeat(t),this.toString(),"requestRefresh()",`+ ${this.children.size} children`));for(const s of this.children)s.requestRefresh(!0,t+1,i)}else i&&console.debug(...b(t<0?"⤒".repeat(t*-1):" ".repeat(t),this.toString(),"requestRefresh()","<queued>"))}refresh(e=!1,t=0){if(!e&&!this._needsRefresh){t===0&&console.debug(...b(this.toString(),"refresh() received and ignored."));return}this.options?.onRefresh?.call(this);for(const i of this.children)i.refresh(e,t+1);this._needsRefresh=!1}addChild(e){return e.parent=this,this.children.add(e),this.element.append(e.element),this}addChildren(e){for(const t of e??[])this.addChild(t);return this}removeChild(e){this.children.has(e)&&(e.element.remove(),this.children.delete(e))}removeChildren(e){for(const t of e)this.removeChild(t)}}class E extends N{constructor(e,t){super(e,{...t}),this.element=$("<div/>");for(const i of t?.classes??[])this.element.addClass(i)}toString(){return`[${E.name}#${this.componentId}]`}}const R={label:"_label_1nlev_1",splitter:"_splitter_1nlev_16",iconLabel:"_iconLabel_1nlev_20",fillSpace:"_fillSpace_1nlev_26"},me={delimiter:"_delimiter_16hnh_1"};class ne extends N{constructor(e,t){super(e,{...t}),this.element=$("<li/>");for(const i of t?.classes??[])this.element.addClass(i);t?.delimiter===!0&&this.element.addClass(me.delimiter)}toString(){return`[${ne.name}#${this.componentId}]`}}const We={head:"_head_wr1pj_1"};class ae extends ne{head;elementLabel;constructor(e,t,i){if(super(e,i),this.head=new E(e),this.head.element.addClass(We.head),this.addChild(this.head),this.elementLabel=$("<label/>",{text:`${i?.upgradeIndicator===!0?"⮤ ":""}${t}`}).addClass(R.label).addClass(We.label),this.head.element.append(this.elementLabel),i?.icon){const s=$("<div/>",{html:`<svg style="width: 15px; height: 15px;" viewBox="0 -960 960 960" fill="currentColor"><path d="${i.icon}"/></svg>`}).addClass(R.iconLabel);this.elementLabel.prepend(s)}}toString(){return`[${ae.name}#${this.componentId}]: '${this.elementLabel.text()}'`}addChildHead(e){return this.head.addChild(e),this}addChildrenHead(e){for(const t of e??[])this.head.addChild(t);return this}}const P={setting:"_setting_1ndg5_1",checkbox:"_checkbox_1ndg5_6",panelContent:"_panelContent_1ndg5_10",hidden:"_hidden_1ndg5_17",checked:"_checked_1ndg5_22",expanded:"_expanded_1ndg5_26",readonly:"_readonly_1ndg5_34"};class _ extends ae{setting;checkbox;readOnly;constructor(e,t,i,s){super(e,i,{...s,onRefresh:()=>{this.setting.enabled?this.element.addClass(P.checked):this.element.removeClass(P.checked),this.readOnly?this.element.addClass(P.readonly):this.element.removeClass(P.readonly),g(this.checkbox)||(this.checkbox.prop("checked",this.setting.enabled),this.checkbox.prop("disabled",this.readOnly)),s?.onRefresh?.()}}),this.element.addClass(P.setting);const a=`ks-setting${this.componentId}`,n=$("<input/>",{id:a,type:"checkbox"}).addClass(P.checkbox);this.readOnly=s?.readOnly??!1,n.prop("disabled",this.readOnly),n.on("change",r=>{n.is(":checked")&&!t.enabled?this.check().catch(H(console)):!n.is(":checked")&&t.enabled&&this.uncheck().catch(H(console))}),this.elementLabel.before(n),this.elementLabel.prop("for",a),this.checkbox=n,this.setting=t}toString(){return`[${_.name}#${this.componentId}]: '${this.elementLabel.text()}'`}async check(e=!1){this.setting.enabled=!0,await this.options?.onCheck?.call(e),this.requestRefresh()}async uncheck(e=!1){this.setting.enabled=!1,await this.options.onUnCheck?.call(e),this.requestRefresh()}}const k={iconButton:"_iconButton_q7zpt_17",inactive:"_inactive_q7zpt_29",ineffective:"_ineffective_q7zpt_37",button:"_button_q7zpt_43",readonly:"_readonly_q7zpt_67",buttonIcon:"_buttonIcon_q7zpt_72",alignRight:"_alignRight_q7zpt_77",large:"_large_q7zpt_81",bordered:"_bordered_q7zpt_85",headAction:"_headAction_q7zpt_97",lastHeadAction:"_lastHeadAction_q7zpt_100",consumeButton:"_consumeButton_q7zpt_104",stockButton:"_stockButton_q7zpt_107"};class J extends N{readOnly;inactive;constructor(e,t,i,s){super(e,{...s,onRefresh:()=>{this.readOnly?this.element.addClass(k.readonly):this.element.removeClass(k.readonly),this.inactive?this.element.addClass(k.inactive):this.element.removeClass(k.inactive),s?.onRefresh?.()}}),this.element=$("<div/>",{html:`<svg style="width: 18px; height: 18px;" viewBox="0 -960 960 960" fill="currentColor"><path d="${t}"/></svg>`,title:i}).addClass(k.iconButton),this.readOnly=s?.readOnly??!1,this.inactive=s?.inactive??!1,this.element.on("click",()=>{this.readOnly||this.click().catch(H(console))})}toString(){return`[${J.name}#${this.componentId}]`}async click(){this.readOnly||(await this.options?.onClick?.call(this),this.requestRefresh())}}const Ge={listContainer:"_listContainer_1kxbq_1",itemsList:"_itemsList_1kxbq_5",list:"_list_1kxbq_1",listTools:"_listTools_1kxbq_9"};class S extends N{list;disableAllButton;enableAllButton;resetButton;constructor(e,t){super(e,{...t});const i={hasDisableAll:!0,hasEnableAll:!0,...t},s=i.hasDisableAll||i.hasEnableAll||!g(i.onReset);if(this.element=$("<div/>").addClass(Ge.listContainer),this.list=$("<ul/>").addClass(Ge.list).addClass(Ge.itemsList),this.element.append(this.list),s){const a=new E(this,{classes:[Ge.listTools]});i.hasEnableAll&&(this.enableAllButton=new J(e,M.CheckboxCheck,e.host.engine.i18n("ui.enable.all"),{onClick:async()=>{const r=new Event("enableAll",{cancelable:!0});if(this.element[0].dispatchEvent(r),!r.defaultPrevented){for(const o of this.children)Pe(o,_)&&await o.check(!0);t?.onEnableAll?.call(this)}}}),a.addChild(this.enableAllButton)),i.hasDisableAll&&(this.disableAllButton=new J(e,M.CheckboxUnCheck,e.host.engine.i18n("ui.disable.all"),{onClick:async()=>{const r=new Event("disableAll",{cancelable:!0});if(this.element[0].dispatchEvent(r),!r.defaultPrevented){for(const o of this.children)Pe(o,_)&&await o.uncheck(!0);t?.onDisableAll?.call(this)}}}),a.addChild(this.disableAllButton));const n=i.onReset;g(n)||(this.resetButton=new J(e,M.Reset,e.host.engine.i18n("ui.reset"),{onClick:()=>{n()}}),a.addChild(this.resetButton)),super.addChild(a)}}toString(){return`[${S.name}#${this.componentId}]`}addChild(e){return e.parent=this,this.children.add(e),this.list.append(e.element),this}}const xe={expandoButton:"_expandoButton_l1ukp_1",expanded:"_expanded_l1ukp_1",up:"_up_l1ukp_1",down:"_down_l1ukp_4"};class Ze extends N{readOnly;inactive;ineffective;constructor(e,t){super(e,{...t,onRefresh:()=>{this.ineffective?this.element.addClass(k.ineffective):this.element.removeClass(k.ineffective),t?.onRefresh?.()}}),this.element=$("<div/>",{html:`
|
|
18
18
|
<svg style="width: 18px; height: 18px;" viewBox="0 -960 960 960" fill="currentColor" class="${xe.down}"><path d="${M.ExpandCircleDown}"/></svg>
|
|
19
19
|
<svg style="width: 18px; height: 18px;" viewBox="0 -960 960 960" fill="currentColor" class="${xe.up}"><path d="${M.ExpandCircleUp}"/></svg>
|
|
20
20
|
`,title:e.host.engine.i18n("ui.itemsShow")}).addClass(k.iconButton).addClass(xe.expandoButton),this.element.on("click",()=>{this.readOnly||this.click().catch(H(console))}),this.readOnly=t?.readOnly??!1,this.inactive=t?.inactive??!1,this.ineffective=!1}toString(){return`[${Ze.name}#${this.componentId}]`}setCollapsed(){this.element.removeClass(xe.expanded),this.element.prop("title",this.host.engine.i18n("ui.itemsShow"))}setExpanded(){this.element.addClass(xe.expanded),this.element.prop("title",this.host.engine.i18n("ui.itemsHide"))}async click(){this.readOnly||(await this.options?.onClick?.call(this),this.requestRefresh())}}class fe extends N{container;expando;head;_mainChildVisible;get isExpanded(){return this._mainChildVisible}constructor(e,t,i){super(e,i),this.head=t,this.container=new E(this),this.container.element.addClass(P.panelContent);const s=new Ze(e,{onClick:()=>this.toggle()});t.head.addChild(s),t.element.append(this.container.element),i?.initiallyExpanded?(this.container.element.removeClass(P.hidden),s.setExpanded()):this.container.element.addClass(P.hidden),this._mainChildVisible=i?.initiallyExpanded??!1,this.element=t.element,this.expando=s,this.addChildren([this.head,this.container])}toString(){return`[${fe.name}#${this.componentId}]`}addChildHead(e){return this.head.addChild(e),this}addChildrenHead(e){for(const t of e??[])this.head.addChild(t);return this}addChildContent(e){return this.container.addChild(e),this}addChildrenContent(e){for(const t of e??[])this.container.addChild(t);return this}toggle(e=void 0,t=!1){const i=e!==void 0?e:!this._mainChildVisible;if(i!==this._mainChildVisible&&(this._mainChildVisible=i,this._mainChildVisible?(this.container.requestRefresh(!0),this.container.element.removeClass(P.hidden),this.expando.setExpanded(),this.head.element.addClass(P.expanded),this.element[0].dispatchEvent(new CustomEvent("panelShown"))):(this.container.element.addClass(P.hidden),this.expando.setCollapsed(),this.head.element.removeClass(P.expanded),this.element[0].dispatchEvent(new CustomEvent("panelHidden")))),t){const s=a=>{for(const n of a)Pe(n,fe)?n.toggle(e,t):s(n.children)};s(this.children)}}}class B extends fe{setting;settingItem;get isExpanded(){return this._mainChildVisible}get elementLabel(){return this.head.element}get readOnly(){return!0}set readOnly(e){}async check(){this.setting.enabled=!0,this.requestRefresh()}async uncheck(){this.setting.enabled=!1,this.requestRefresh()}constructor(e,t,i,s){super(e,i,s),this.element=i.element,this.settingItem=i,this.setting=t}toString(){return`[${B.name}#${this.componentId}]: '${this.settingItem.elementLabel.text()}'`}}class wn extends B{constructor(e,t,i,s){const a=e.host.engine.i18n("ui.upgrade.buildings");super(e,t,new _(e,t,a,{onCheck:o=>{e.host.engine.imessage("status.auto.enable",[a])},onUnCheck:o=>{e.host.engine.imessage("status.auto.disable",[a])}}).addChildrenHead([new E(e,{classes:[R.fillSpace]})]),{onRefreshRequest:()=>{this.expando.ineffective=s.enabled&&t.enabled&&!Object.values(t.buildings).some(o=>o.enabled)}});const n=[];for(const o of Object.values(this.setting.buildings)){const l=this.host.engine.i18n(`$buildings.${o.upgrade}.label`),h=new _(this,o,l,{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[l])},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[l])}});n.push({button:h,label:l})}n.sort((o,l)=>o.label.localeCompare(l.label));const r=new S(this);for(const o of n)r.addChild(o.button);this.addChildContent(r)}}class W extends N{_iconElement;readOnly;inactive;ineffective;constructor(e,t,i=null,s){super(e,{...s,onRefresh:()=>{this.readOnly?this.element.addClass(k.readonly):this.element.removeClass(k.readonly),this.inactive?this.element.addClass(k.inactive):this.element.removeClass(k.inactive),this.ineffective?this.element.addClass(k.ineffective):this.element.removeClass(k.ineffective),s?.onRefresh?.()}}),this.element=$("<div/>",{title:s?.title}).addClass(k.button).text(t),s?.border!==!1&&this.element.addClass(k.bordered),s?.alignment==="right"&&this.element.addClass(k.alignRight),i!==null&&(this._iconElement=$(`<svg class="${k.buttonIcon}" style="width: 18px; height: 18px;" viewBox="0 -960 960 960" fill="currentColor"><path d="${i}"/></svg>`),s?.alignment==="right"?this.element.append(this._iconElement):this.element.prepend(this._iconElement));for(const a of s?.classes??[])this.element.addClass(a);this.element.on("click",()=>{this.readOnly||this.click().catch(H(console))}),this.readOnly=s?.readOnly??!1,this.inactive=s?.inactive??!1,this.ineffective=!1}toString(){return`[${W.name}#${this.componentId}]`}updateLabel(e){this.element.text(e),this._iconElement!==void 0&&(this.options.alignment==="right"?this.element.append(this._iconElement):this.element.prepend(this._iconElement))}updateTitle(e){this.element.prop("title",e)}async click(){this.readOnly||(await this.options?.onClick?.call(this),this.requestRefresh())}}class V extends N{constructor(e){super(e,{}),this.element=$("<div/>").addClass(me.delimiter)}toString(){return`[${V.name}#${this.componentId}]`}}const Ui={dialog:"_dialog_b4vj0_1",close:"_close_b4vj0_7"},Di={explainer:"_explainer_1idu3_1"},kn={header:"_header_19ql8_1"};class I extends N{get elementLabel(){return this.element}constructor(e,t,i){super(e,{...i}),this.element=$("<li/>",{text:t}).addClass(kn.header)}toString(){return`[${I.name}#${this.componentId}]: '${this.elementLabel.text()}'`}}class vt extends N{constructor(e,t){super(e,{...t}),this.element=$('<input type="text"/>').addClass("ks-input");for(const i of t?.classes??[])this.element.addClass(i);t?.onChange&&this.element.on("change",()=>t.onChange?.(this.element[0].value)),t?.value&&(this.element[0].value=t.value),t?.selected&&(this.element[0].selectionStart=0,this.element[0].selectionEnd=-1),this.element.on("keyup",i=>{switch(i.key){case"Enter":t?.onEnter?.(this.element[0].value);break;case"Escape":t?.onEscape?.(this.element[0].value);break}})}toString(){return`[${vt.name}#${this.componentId}]`}}class Ke extends N{constructor(e,t,i){super(e,{...i}),this.element=$("<p/>").text(t);for(const s of i?.classes??[])this.element.addClass(s)}toString(){return`[${Ke.name}#${this.componentId}]`}}const Ni={toolbar:"_toolbar_1654f_1"};class T extends N{container;head;returnValue;constructor(e,t){super(e,{...t}),this.element=$("<dialog/>").addClass("dialog").addClass("help").addClass(Ui.dialog),t?.hasClose!==!1&&this.addChild(new W(e,"close",null,{classes:[Ui.close],onClick:()=>{this.close(),t?.onCancel?.()}})),this.returnValue=t?.promptValue??"",this.head=new E(e),this.container=new E(e),this.addChildren(Be([this.head,t?.prompt?new vt(e,{onChange:i=>{this.returnValue=i},onEnter:i=>{this.returnValue=i,this.close(),t.onConfirm?.(this.returnValue)},onEscape:i=>{this.close(),t.onCancel?.()},selected:!0,value:t.promptValue}):void 0,this.container,new V(e),new E(e,{classes:[Ni.toolbar]}).addChildren(Be([new W(e,"OK",null,{classes:[k.large],onClick:()=>{this.close(),t?.onConfirm?.(this.returnValue)}}),t?.hasCancel?new W(e,"Cancel",null,{classes:[k.large],onClick:()=>{this.close(),t.onCancel?.()}}):void 0]))]))}toString(){return`[${T.name}#${this.componentId}]`}addChildHead(e){return this.head.addChild(e),this}addChildrenHead(e){for(const t of e??[])this.head.addChild(t);return this}addChildContent(e){return this.container.addChild(e),this}addChildrenContent(e){for(const t of e??[])this.container.addChild(t);return this}show(){$("#gamePageContainer").append(this.element),this.element[0].show()}showModal(){$("#gamePageContainer").append(this.element),this.element[0].showModal()}close(){this.element[0].close(),this.element.remove()}static async prompt(e,t,i,s,a){return new Promise(n=>{new T(e,{hasCancel:!0,hasClose:!1,onCancel:()=>{n(void 0)},onConfirm:r=>{n(r)},prompt:!0,promptValue:s}).addChildrenHead(Be([i?new I(e,i):void 0,new Ke(e,t)])).addChildrenContent(a?[new E(e,{classes:[Di.explainer]}).addChildren([new Ke(e,a)])]:[]).showModal()})}}const _n={maxButton:"_maxButton_133h2_1"};class Te extends W{setting;constructor(e,t,i){super(e,"",null,{...i,classes:[_n.maxButton,...i?.classes??[]]}),this.setting=t}toString(){return`[${Te.name}#${this.componentId}]`}}class ke extends W{behavior;setting;constructor(e,t,i,s){super(e,"",M.Trigger,{...s,onRefresh:()=>{const a=this.behavior==="integer"?this.host.renderAbsolute(this.setting.trigger,"invariant"):this.host.renderPercentage(this.setting.trigger,"invariant",!0);this.updateTitle(this.host.engine.i18n("ui.trigger",[a])),(this.options?.renderLabel??!0)&&this.updateLabel(a),this.inactive?this.element.addClass(k.inactive):this.element.removeClass(k.inactive),s?.onRefresh?.call(this)}}),this.behavior=t instanceof F?"percentage":"integer",this.setting=t}toString(){return`[${ke.name}#${this.componentId}]`}}class Ve extends _{maxButton;triggerButton;constructor(e,t,i,s,a){super(e,t,s,a),this.maxButton=new Te(e,t,{alignment:"right",border:!1,classes:[k.headAction],onClick:async()=>{await a.onSetMax.call(this)},onRefresh:a?.onRefreshMax?()=>a.onRefreshMax?.call(this):void 0}),this.triggerButton=new ke(e,t,i,{border:!1,classes:[k.lastHeadAction],onClick:async()=>{await a.onSetTrigger.call(this)},onRefresh:a?.onRefreshTrigger?()=>a.onRefreshTrigger?.call(this):void 0,renderLabel:a?.renderLabelTrigger??!0}),this.addChildrenHead([new E(e,{classes:[R.fillSpace]}),this.maxButton,this.triggerButton])}toString(){return`[${Ve.name}#${this.componentId}]: '${this.elementLabel.text()}'`}}const ie={getBuildOption:(c,e,t,i,s,a,n)=>{const r=async()=>{const l=await T.prompt(c,c.host.engine.i18n("ui.max.prompt.absolute"),c.host.engine.i18n("ui.max.build.prompt",[s,c.host.renderAbsolute(e.max,t.selected)]),c.host.renderAbsolute(e.max),c.host.engine.i18n("ui.max.build.promptExplainer"));if(l!==void 0){if(l===""||l.startsWith("-")){e.max=-1;return}l==="0"&&(e.enabled=!1),e.max=c.host.parseAbsolute(l)??e.max}},o=new Ve(c,e,t,s,{delimiter:n?.delimiter,onCheck:async l=>{c.host.engine.imessage("status.sub.enable",[s]),e.max===0&&!l&&await r(),await n?.onCheck?.(l)},onRefreshMax:()=>{o.maxButton.updateLabel(c.host.renderAbsolute(e.max)),o.maxButton.element[0].title=e.max<0?c.host.engine.i18n("ui.max.build.titleInfinite",[s]):e.max===0?c.host.engine.i18n("ui.max.build.titleZero",[s]):c.host.engine.i18n("ui.max.build.title",[c.host.renderAbsolute(e.max),s])},onRefreshRequest:()=>{o.maxButton.inactive=!e.enabled||e.max===-1,o.maxButton.ineffective=i.enabled&&e.enabled&&e.max===0,o.triggerButton.inactive=!e.enabled||e.trigger===-1,o.triggerButton.ineffective=i.enabled&&e.enabled&&i.trigger===-1&&e.trigger===-1},onRefreshTrigger:()=>{o.triggerButton.element[0].title=c.host.engine.i18n("ui.trigger",[e.trigger<0?i.trigger<0?c.host.engine.i18n("ui.trigger.build.blocked",[a]):`${c.host.renderPercentage(i.trigger,t.selected,!0)} (${c.host.engine.i18n("ui.trigger.build.inherited")})`:c.host.renderPercentage(e.trigger,t.selected,!0)])},onSetMax:r,onSetTrigger:async()=>{const l=await T.prompt(c,c.host.engine.i18n("ui.trigger.prompt.percentage"),c.host.engine.i18n("ui.trigger.build.prompt",[s,e.trigger!==-1?c.host.renderPercentage(e.trigger,t.selected,!0):c.host.engine.i18n("ui.trigger.build.inherited")]),e.trigger!==-1?c.host.renderPercentage(e.trigger):"",c.host.engine.i18n("ui.trigger.build.promptExplainer"));if(l!==void 0){if(l===""||l.startsWith("-")){e.trigger=-1;return}e.trigger=c.host.parsePercentage(l),await n?.onSetTrigger?.call(void 0)}},onUnCheck:l=>{c.host.engine.imessage("status.sub.disable",[s]),n?.onUnCheck?.(l)},renderLabelTrigger:n?.renderLabelTrigger,upgradeIndicator:n?.upgradeIndicator});return o}};class D extends _{triggerButton;constructor(e,t,i,s,a){super(e,t,s,a),this.triggerButton=new ke(e,t,i,{alignment:"right",border:!1,onClick:async()=>{await a.onSetTrigger.call(this)},onRefresh:a?.onRefreshTrigger?()=>a.onRefreshTrigger?.call(this):void 0,renderLabel:a?.renderLabelTrigger??!0}),this.addChildrenHead([new E(e,{classes:[R.fillSpace]}),this.triggerButton])}toString(){return`[${D.name}#${this.componentId}]: '${this.elementLabel.text()}'`}}class yt extends B{constructor(e,t,i){console.debug(...b(`Constructing ${yt.name}`));const s=e.host.engine.i18n("ui.build");super(e,t,new D(e,t,i,s,{onCheck:a=>{e.host.engine.imessage("status.auto.enable",[s])},onRefreshTrigger:()=>{this.settingItem.triggerButton.element[0].title=e.host.engine.i18n("ui.trigger.section",[t.trigger<0?e.host.engine.i18n("ui.trigger.section.inactive"):e.host.renderPercentage(t.trigger,i.selected,!0)])},onSetTrigger:async()=>{const a=await T.prompt(e,e.host.engine.i18n("ui.trigger.prompt.percentage"),e.host.engine.i18n("ui.trigger.section.prompt",[s,t.trigger!==-1?e.host.renderPercentage(t.trigger,i.selected,!0):e.host.engine.i18n("ui.infinity")]),t.trigger!==-1?e.host.renderPercentage(t.trigger):"",e.host.engine.i18n("ui.trigger.section.promptExplainer"));if(a!==void 0){if(a===""||a.startsWith("-")){t.trigger=-1;return}t.trigger=e.host.parsePercentage(a)}},onUnCheck:a=>{e.host.engine.imessage("status.auto.disable",[s])},renderLabelTrigger:!1}),{onRefreshRequest:()=>{this.settingItem.triggerButton.inactive=!t.enabled||t.trigger<0,this.settingItem.triggerButton.ineffective=t.enabled&&t.trigger<0&&Object.values(t.buildings).some(a=>a.enabled&&0<a.max&&a.trigger<0),this.expando.ineffective=t.enabled&&Object.values(t.buildings).some(a=>a.enabled&&(a.max===0||a.trigger<0&&t.trigger<0))}}),this.addChildrenContent([new S(this,{onReset:()=>{this.setting.load({buildings:new ft().buildings})}}).addChildren(Be(this.host.game.bld.buildingGroups.flatMap(a=>[new I(this,a.title),...a.buildings.flatMap(n=>this._getBuildOptions(this,t,i,s,n)),a!==this.host.game.bld.buildingGroups[this.host.game.bld.buildingGroups.length-1]?new V(this):void 0]))),new S(this,{hasDisableAll:!1,hasEnableAll:!1}).addChildren([new I(this,this.host.engine.i18n("ui.additional")),new _(this,t.gatherCatnip,this.host.engine.i18n("option.catnip"),{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[this.host.engine.i18n("option.catnip")])},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[this.host.engine.i18n("option.catnip")])}}),new _(this,t.turnOnSteamworks,this.host.engine.i18n("option.steamworks"),{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[this.host.engine.i18n("option.steamworks")])},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[this.host.engine.i18n("option.steamworks")])}}),new _(this,t.turnOnMagnetos,this.host.engine.i18n("option.magnetos"),{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[this.host.engine.i18n("option.magnetos")])},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[this.host.engine.i18n("option.magnetos")])}}),new _(this,t.turnOnReactors,this.host.engine.i18n("option.reactors"),{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[this.host.engine.i18n("option.reactors")])},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[this.host.engine.i18n("option.reactors")])}}),new wn(this,t.upgradeBuildings,i,t)])])}_getBuildOptions(e,t,i,s,a){if(a==="unicornPasture"||g(t.buildings[a]))return[];const n=e.host.game.bld.getBuildingExt(a).meta;if(!g(n.stages)){const r=Object.values(t.buildings).find(o=>o.baseBuilding===a)?.building;return[ie.getBuildOption(e,t.buildings[a],i,t,n.stages[0].label,s,{renderLabelTrigger:!1}),ie.getBuildOption(e,t.buildings[r],i,t,n.stages[1].label,s,{renderLabelTrigger:!1,upgradeIndicator:!0})]}return g(n.label)?[]:[ie.getBuildOption(e,t.buildings[a],i,t,n.label,s,{renderLabelTrigger:!1})]}}class Cn extends _{expando;constructor(e,t){const i=G(e.host.engine.i18n("ui.engine"));super(e,t,i,{onCheck:()=>{e.host.engine.start(!0)},onUnCheck:()=>{e.host.engine.stop(!0)}}),this.expando=new Ze(this),this.addChildrenHead([new E(e,{classes:[R.fillSpace]}),this.expando])}}class wt extends ne{button;constructor(e,t,i){super(e,{...i}),this.button=t,this.element.addClass(We.head),this.element.append(t.element)}}const Sn={fieldset:"_fieldset_tfwil_1"};class kt extends N{constructor(e,t,i){super(e,{...i}),this.element=$("<fieldset/>").addClass(Sn.fieldset),i?.delimiter&&this.element.addClass(me.delimiter);const s=$("<legend/>").text(t).addClass(R.label);this.element.append(s)}toString(){return`[${kt.name}#${this.componentId}]`}}class _t extends N{setting;option;elementLabel;input;readOnly;constructor(e,t,i,s,a){super(e,{...a,onRefresh:()=>{this.input.prop("disabled",this.readOnly)}}),this.element=$("<div/>"),this.element.addClass(P.setting),a?.delimiter===!0&&this.element.addClass(me.delimiter),this.elementLabel=$("<label/>",{text:`${a?.upgradeIndicator?"⮤ ":""}${i.label}`}).addClass(R.label);const n=$("<input/>",{name:s,type:"radio"}).addClass("ks-radio");this.readOnly=a?.readOnly??!1,n.on("change",()=>{this.setting.selected=i.value,g(a?.onCheck)||a.onCheck()}),this.elementLabel.prepend(n),this.element.append(this.elementLabel),this.input=n,this.setting=t,this.option=i}toString(){return`[${_t.name}#${this.componentId}]: '${this.elementLabel.text()}'`}}class Ee extends N{fieldset;setting;_items;constructor(e,t,i,s){super(e,{...s,onRefresh:()=>{for(const a of this._items)if(a.option.value===this.setting.selected){a.input.prop("checked",!0);break}s?.onRefresh?.()}}),this.element=$("<li/>"),this.fieldset=new kt(e,t),this.addChild(this.fieldset),this._items=new Array;for(const a of i.options)this._items.push(new _t(e,i,a,t,{onCheck:s?.onCheck,readOnly:s?.readOnly}));this.fieldset.addChildren(this._items),this.setting=i}toString(){return`[${Ee.name}#${this.componentId}]`}}const xn={textButton:"_textButton_1mv97_1"};class pe extends N{readOnly;constructor(e,t,i){super(e,{...i,onRefresh:()=>{this.readOnly?this.element.addClass(k.readonly):this.element.removeClass(k.readonly),i?.onRefresh?.call(this)}}),this.element=$("<div/>").addClass(xn.textButton),t!==void 0&&this.element.text(t);const s=i?.title;g(s)||this.element.prop("title",s),this.readOnly=!1,this.element.on("click",()=>{this.readOnly||this.click().catch(H(console))})}toString(){return`[${pe.name}#${this.componentId}]`}async click(){this.readOnly||(await this.options?.onClick?.call(this),this.requestRefresh())}}class Ct extends B{constructor(e,t,i){console.debug(...b(`Constructing ${Ct.name}`)),super(e,t,new ae(e,e.host.engine.i18n("ui.internals"),{classes:[P.checked,P.setting],icon:M.Settings}).addChildrenHead([new E(e,{classes:[R.fillSpace]})])),this.addChildrenContent([new S(e,{hasDisableAll:!1,hasEnableAll:!1}).addChildren([new wt(e,new pe(e,e.host.engine.i18n("ui.internals.interval",[t.interval]),{onClick:async()=>{const s=await T.prompt(e,e.host.engine.i18n("ui.internals.interval.prompt"),e.host.engine.i18n("ui.internals.interval.promptTitle",[e.host.renderAbsolute(t.interval,i.selected)]),e.host.renderAbsolute(t.interval),e.host.engine.i18n("ui.internals.interval.promptExplainer"));s===void 0||s===""||s.startsWith("-")||(s==="0"&&(t.enabled=!1),t.interval=e.host.parseAbsolute(s)??t.interval)},onRefresh(){this.element.text(e.host.engine.i18n("ui.internals.interval",[t.interval]))}})),new V(e),new _(e,t.ksColumn,e.host.engine.i18n("ui.ksColumn"),{onCheck:()=>{e.host.rebuildUi()},onUnCheck:()=>{e.host.rebuildUi()}}),new _(e,t.highlighStock,e.host.engine.i18n("ui.highlightStock")),new V(e),new Ee(e,e.host.engine.i18n("ui.language"),t.locale,{onCheck:()=>{e.host.rebuildUi()}}),new V(e),new ae(e,`Kitten Scientists ${Ae("v")}`)])])}}class St extends N{constructor(e,t,i){super(e,{...i}),this.element=$("<li/>",{text:e.host.engine.i18n(t)}).addClass(Di.explainer)}toString(){return`[${St.name}#${this.componentId}]`}}class xt extends B{constructor(e,t){console.debug(...b(`Constructing ${xt.name}`));const i=e.host.engine.i18n("ui.filter");super(e,t,new _(e,t,i,{onCheck:a=>{e.host.engine.imessage("status.auto.enable",[i])},onUnCheck:a=>{e.host.engine.imessage("status.auto.disable",[i])}}).addChildrenHead([new E(e,{classes:[R.fillSpace]})])),this.addChildContent(new S(this,{hasDisableAll:!1,hasEnableAll:!1}).addChildren([new _(this,t.disableKGLog,this.host.engine.i18n("filter.allKG"))]));const s=new S(this).addChildren(Si.map(a=>({label:this.host.engine.i18n(`filter.${a}`),name:a})).sort((a,n)=>a.label.localeCompare(n.label)).map(a=>new _(this,this.setting.filters[a.name],a.label,{onCheck:()=>{this.host.engine.imessage("filter.enable",[a.label])},onUnCheck:()=>{this.host.engine.imessage("filter.disable",[a.label])}})));this.addChildContent(s),this.addChildContent(new St(this,"filter.explainer"))}}const je={active:"_active_6c09s_16"};class Tt extends B{_unicornBuildings;_bestUnicornBuilding;constructor(e,t,i){console.debug(...b(`Constructing ${Tt.name}`));const s=e.host.engine.i18n("ui.faith");super(e,t,new D(e,t,i,s,{onCheck:n=>{e.host.engine.imessage("status.auto.enable",[s])},onRefreshTrigger(){this.triggerButton.element[0].title=e.host.engine.i18n("ui.trigger.section",[t.trigger<0?e.host.engine.i18n("ui.trigger.section.inactive"):e.host.renderPercentage(t.trigger,i.selected,!0)])},onSetTrigger:async()=>{const n=await T.prompt(e,e.host.engine.i18n("ui.trigger.prompt.percentage"),e.host.engine.i18n("ui.trigger.section.prompt",[s,t.trigger!==-1?e.host.renderPercentage(t.trigger,i.selected,!0):e.host.engine.i18n("ui.infinity")]),t.trigger!==-1?e.host.renderPercentage(t.trigger):"",e.host.engine.i18n("ui.trigger.section.promptExplainer"));if(n!==void 0){if(n===""||n.startsWith("-")){t.trigger=-1;return}t.trigger=e.host.parsePercentage(n)}},onUnCheck:n=>{e.host.engine.imessage("status.auto.disable",[s])},renderLabelTrigger:!1}),{onRefresh:()=>{for(const[n,r]of this._unicornBuildings.entries())r.elementLabel.attr("data-ks-active-from","❊"),r.elementLabel.attr("data-ks-active-to","✮"),this.setting.bestUnicornBuilding.enabled&&this.setting.bestUnicornBuildingCurrent===n?r.elementLabel.addClass(je.active):r.elementLabel.removeClass(je.active)},onRefreshRequest:()=>{this.settingItem.triggerButton.inactive=!t.enabled||t.trigger===-1,this.settingItem.triggerButton.ineffective=t.enabled&&t.trigger<0&&Object.values(t.buildings).some(n=>n.enabled&&0<n.max&&n.trigger<0),this.expando.ineffective=t.enabled&&Object.values(t.buildings).some(n=>n.enabled&&(n.max===0||n.trigger<0&&t.trigger<0));for(const[n,r]of this._unicornBuildings.entries())r.readOnly=this._bestUnicornBuilding.setting.enabled,r.maxButton.readOnly=this._bestUnicornBuilding.setting.enabled,r.triggerButton.readOnly=this._bestUnicornBuilding.setting.enabled}});const a=[...De];this._unicornBuildings=new Map([["unicornPasture",ie.getBuildOption(this,this.setting.buildings.unicornPasture,i,this.setting,this.host.engine.i18n("$buildings.unicornPasture.label"),s,{renderLabelTrigger:!1})],...this.host.game.religion.zigguratUpgrades.filter(n=>a.includes(n.name)&&!g(this.setting.buildings[n.name])).map(n=>[n.name,ie.getBuildOption(this,this.setting.buildings[n.name],i,this.setting,n.label,s,{renderLabelTrigger:!1})])]),this._bestUnicornBuilding=new _(this,this.setting.bestUnicornBuilding,this.host.engine.i18n("option.faith.best.unicorn"),{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[this.host.engine.i18n("option.faith.best.unicorn")]);for(const n of this._unicornBuildings.values())n.setting.enabled=!0,n.setting.max=-1,n.setting.trigger=-1},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[this.host.engine.i18n("option.faith.best.unicorn")])},upgradeIndicator:!0}),this.addChildrenContent([new S(this,{onReset:()=>{const n=new pt;this.setting.load({bestUnicornBuilding:n.bestUnicornBuilding,buildings:n.buildings})}}).addChildren([new I(this,this.host.engine.i18n("$religion.panel.ziggurat.label")),...this._unicornBuildings.values(),this._bestUnicornBuilding,new V(this),...this.host.game.religion.zigguratUpgrades.filter(n=>!a.includes(n.name)&&!g(this.setting.buildings[n.name])).map(n=>ie.getBuildOption(this,this.setting.buildings[n.name],i,this.setting,n.label,s,{renderLabelTrigger:!1})),new V(this),new I(this,this.host.engine.i18n("$religion.panel.orderOfTheSun.label")),...this.host.game.religion.religionUpgrades.filter(n=>!g(this.setting.buildings[n.name])).map(n=>ie.getBuildOption(this,this.setting.buildings[n.name],i,this.setting,n.label,s,{delimiter:n.name===this.host.game.religion.religionUpgrades.at(-1)?.name,renderLabelTrigger:!1})),new I(this,this.host.engine.i18n("$religion.panel.cryptotheology.label")),...this.host.game.religion.transcendenceUpgrades.filter(n=>!g(this.setting.buildings[n.name])).map(n=>ie.getBuildOption(this,this.setting.buildings[n.name],i,this.setting,n.label,s,{renderLabelTrigger:!1}))]),new S(this,{hasDisableAll:!1,hasEnableAll:!1}).addChildren([new I(this,this.host.engine.i18n("ui.additional")),...gs.map(n=>{const r=this.host.engine.i18n(`option.faith.${n}`);if(n==="transcend")return new _(this,this.setting[n],r,{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[r])},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[r])}});const o=new D(this,this.setting[n],i,r,{classes:[k.lastHeadAction],onCheck:()=>{this.host.engine.imessage("status.sub.enable",[r])},onRefresh:()=>{o.triggerButton.inactive=!this.setting[n].enabled||this.setting[n].trigger===-1},onSetTrigger:async()=>{const l=await T.prompt(this,this.host.engine.i18n(o.triggerButton.behavior==="integer"?"ui.trigger.setinteger":"ui.trigger.setpercentage",[r]),this.host.engine.i18n("ui.trigger.build.prompt",[r,o.triggerButton.behavior==="integer"?this.host.renderAbsolute(this.setting[n].trigger,i.selected):this.host.renderPercentage(this.setting[n].trigger,i.selected,!0)]),o.triggerButton.behavior==="integer"?this.host.renderAbsolute(this.setting[n].trigger):this.host.renderPercentage(this.setting[n].trigger),this.host.engine.i18n(o.triggerButton.behavior==="integer"?"ui.trigger.setinteger.promptExplainer":"ui.trigger.setpercentage.promptExplainer"));l===void 0||l===""||l.startsWith("-")||(this.setting[n].trigger=(o.triggerButton.behavior==="integer"?this.host.parseAbsolute(l):this.host.parsePercentage(l))??this.setting[n].trigger)},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[r])}});return o.triggerButton.element.addClass(k.lastHeadAction),o})])])}}class Et extends W{setting;resourceName;constructor(e,t,i,s,a){super(e,"",M.DataUsage,{...a,onClick:async()=>{const n=await T.prompt(e,e.host.engine.i18n("resources.consume.prompt"),e.host.engine.i18n("resources.consume.promptTitle",[s,e.host.renderPercentage(t.consume,i.selected,!0)]),e.host.renderPercentage(t.consume),e.host.engine.i18n("resources.consume.promptExplainer"));n!==void 0&&(n===""||n.startsWith("-")||(t.consume=e.host.parsePercentage(n)))},onRefresh:()=>{const n=this.host.renderPercentage(this.setting.consume,this.host.engine.settings.locale.selected,!0),r=this.setting.consume===0?this.host.engine.i18n("resources.consume.titleZero",[this.resourceName]):this.host.engine.i18n("resources.consume.title",[n,this.resourceName]);this.updateTitle(r),a?.onRefresh?.()}}),this.element.addClass(k.consumeButton),this.resourceName=s,this.setting=t}toString(){return`[${Et.name}#${this.componentId}]`}}class Rt extends W{setting;resourceName;constructor(e,t,i,s,a){super(e,"",null,{...a,onClick:async()=>{const n=await T.prompt(e,e.host.engine.i18n("resources.stock.prompt"),e.host.engine.i18n("resources.stock.promptTitle",[s,e.host.renderAbsolute(t.stock,i.selected)]),e.host.renderAbsolute(t.stock),e.host.engine.i18n("resources.stock.promptExplainer"));if(n!==void 0){if(n===""||n.startsWith("-")){t.stock=-1;return}n==="0"&&(t.enabled=!1),t.stock=e.host.parseAbsolute(n)??t.stock}},onRefresh:()=>{const n=this.host.renderAbsolute(this.setting.stock),r=this.setting.stock<0?this.host.engine.i18n("resources.stock.titleInfinite",[this.resourceName]):this.setting.stock===0?this.host.engine.i18n("resources.stock.titleZero",[this.resourceName]):this.host.engine.i18n("resources.stock.title",[this.host.renderAbsolute(this.setting.stock),this.resourceName]);this.updateTitle(r),this.updateLabel(n)}}),this.element.addClass(k.stockButton),this.resourceName=s,this.setting=t}toString(){return`[${Rt.name}#${this.componentId}]`}}class Mt extends B{constructor(e,t,i){console.debug(...b(`Constructing ${Mt.name}`));const s=e.host.engine.i18n("ui.resources");super(e,t,new ae(e,s,{classes:[P.checked,P.setting],icon:M.Resources}).addChildrenHead([new E(e,{classes:[R.fillSpace]})]));const a=["blackcoin","burnedParagon","elderBox","gflops","hashrates","kittens","paragon","temporalFlux","wrappingPaper","zebras"];this.addChildContent(new S(this).addChildren(this.host.game.resPool.resources.filter(n=>!a.includes(n.name)&&!g(this.setting.resources[n.name])).sort((n,r)=>n.title.localeCompare(r.title,i.selected)).map(n=>[this.setting.resources[n.name],G(n.title)]).map(([n,r])=>this._makeResourceSetting(this,n,i,r))))}_makeResourceSetting(e,t,i,s){const a=new _(e,t,s,{onCheck:()=>{e.host.engine.imessage("status.resource.enable",[s])},onUnCheck:()=>{e.host.engine.imessage("status.resource.disable",[s])}}).addChildrenHead([new E(e,{classes:[R.fillSpace]})]),n=new Rt(e,t,i,s,{alignment:"right",border:!1,classes:[k.headAction],onRefreshRequest:()=>{n.inactive=!t.enabled||t.stock===0}});a.head.addChild(n);const r=new Et(e,t,i,s,{border:!1,classes:[k.lastHeadAction],onRefreshRequest:()=>{r.inactive=!t.enabled||t.consume!==100,r.ineffective=t.enabled&&t.consume===0}});return a.head.addChild(r),a}}class Tn extends B{constructor(e,t,i,s){const a=e.host.engine.i18n("ui.upgrade.policies");super(e,t,new _(e,t,a,{onCheck:l=>{e.host.engine.imessage("status.auto.enable",[a])},onUnCheck:l=>{e.host.engine.imessage("status.auto.disable",[a])}}).addChildrenHead([new E(e,{classes:[R.fillSpace]})]),{onRefreshRequest:()=>{this.expando.ineffective=s.enabled&&t.enabled&&!Object.values(t.policies).some(l=>l.enabled)}});const n=this.host.game.science.policies.filter(l=>!g(this.setting.policies[l.name])),r=[];let o=n[0].label;for(const l of n.sort((h,u)=>h.label.localeCompare(u.label,i.selected))){const h=this.setting.policies[l.name],u=new _(this,h,l.label,{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[l.label])},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[l.label])}});this.host.engine.localeSupportsFirstLetterSplits(i.selected)&&o[0]!==l.label[0]&&u.element.addClass(R.splitter),r.push(u),o=l.label}this.addChildContent(new S(this).addChildren(r))}}class En extends B{constructor(e,t,i,s){const a=e.host.engine.i18n("ui.upgrade.techs");super(e,t,new D(e,t,i,a,{onCheck:l=>{e.host.engine.imessage("status.auto.enable",[a])},onRefreshTrigger(){this.triggerButton.element[0].title=e.host.engine.i18n("ui.trigger",[t.trigger<0?e.host.engine.i18n("ui.trigger.section.inactive"):e.host.renderPercentage(t.trigger,i.selected,!0)])},onSetTrigger:async()=>{const l=await T.prompt(e,e.host.engine.i18n("ui.trigger.prompt.percentage"),e.host.engine.i18n("ui.trigger.section.prompt",[a,t.trigger!==-1?e.host.renderPercentage(t.trigger,i.selected,!0):e.host.engine.i18n("ui.infinity")]),t.trigger!==-1?e.host.renderPercentage(t.trigger):"",e.host.engine.i18n("ui.trigger.section.promptExplainer"));if(l!==void 0){if(l===""||l.startsWith("-")){t.trigger=-1;return}t.trigger=e.host.parsePercentage(l)}},onUnCheck:l=>{e.host.engine.imessage("status.auto.disable",[a])},renderLabelTrigger:!1}),{onRefreshRequest:()=>{this.settingItem.triggerButton.inactive=!t.enabled||t.trigger===-1,this.settingItem.triggerButton.ineffective=s.enabled&&t.enabled&&t.trigger===-1&&!Object.values(t.techs).some(l=>l.enabled&&0<=l.trigger),this.expando.ineffective=s.enabled&&t.enabled&&!Object.values(t.techs).some(l=>l.enabled)}});const n=this.host.game.science.techs.filter(l=>!g(this.setting.techs[l.name])),r=[];let o=n[0].label;for(const l of n.sort((h,u)=>h.label.localeCompare(u.label,i.selected))){const h=this.setting.techs[l.name],u=new D(this,h,i,l.label,{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[l.label])},onRefresh:()=>{u.triggerButton.inactive=!h.enabled||h.trigger===-1,u.triggerButton.ineffective=s.enabled&&t.enabled&&h.enabled&&t.trigger===-1&&h.trigger===-1},onRefreshTrigger:()=>{u.triggerButton.element[0].title=this.host.engine.i18n("ui.trigger",[h.trigger<0?t.trigger<0?this.host.engine.i18n("ui.trigger.section.blocked",[a]):`${this.host.renderPercentage(t.trigger,i.selected,!0)} (${this.host.engine.i18n("ui.trigger.section.inherited")})`:this.host.renderPercentage(h.trigger,i.selected,!0)])},onSetTrigger:async()=>{const d=await T.prompt(this,this.host.engine.i18n("ui.trigger.prompt.percentage"),this.host.engine.i18n("ui.trigger.section.prompt",[a,h.trigger!==-1?this.host.renderPercentage(h.trigger,i.selected,!0):this.host.engine.i18n("ui.trigger.section.inherited")]),h.trigger!==-1?this.host.renderPercentage(h.trigger):"",this.host.engine.i18n("ui.trigger.section.promptExplainer"));if(d!==void 0){if(d===""||d.startsWith("-")){h.trigger=-1;return}h.trigger=this.host.parsePercentage(d)}},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[l.label])},renderLabelTrigger:!1});u.triggerButton.element.addClass(k.lastHeadAction),this.host.engine.localeSupportsFirstLetterSplits(i.selected)&&o[0]!==l.label[0]&&u.element.addClass(R.splitter),r.push(u),o=l.label}this.addChildContent(new S(this).addChildren(r))}}class At extends B{_policiesUi;_techsUi;_observeStars;constructor(e,t,i){console.debug(...b(`Constructing ${At.name}`));const s=e.host.engine.i18n("ui.upgrade");super(e,t,new _(e,t,s,{onCheck:n=>{e.host.engine.imessage("status.auto.enable",[s])},onUnCheck:n=>{e.host.engine.imessage("status.auto.disable",[s])}}).addChildrenHead([new E(e,{classes:[R.fillSpace]})]),{onRefresh:()=>{this.setting.observe.enabled?$("#observeButton").hide():$("#observeButton").show()},onRefreshRequest:()=>{this.expando.ineffective=t.enabled&&(this.setting.policies.enabled&&this._policiesUi.expando.ineffective||this.setting.techs.enabled&&(this._techsUi.expando.ineffective||this._techsUi.settingItem.triggerButton.ineffective))}}),this._policiesUi=new Tn(this,t.policies,i,t),this._techsUi=new En(this,t.techs,i,t),this._observeStars=new _(this,this.setting.observe,this.host.engine.i18n("option.observe"),{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[this.host.engine.i18n("option.observe")])},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[this.host.engine.i18n("option.observe")])}});const a=new S(this,{hasDisableAll:!1,hasEnableAll:!1});a.addChildren([this._techsUi,this._policiesUi,this._observeStars]),this.addChildContent(a)}}class Rn extends B{_missions;constructor(e,t,i,s){const a=e.host.engine.i18n("ui.upgrade.missions");super(e,t,new _(e,t,a,{onCheck:r=>{e.host.engine.imessage("status.auto.enable",[a])},onRefresh:()=>{this.expando.ineffective=s.enabled&&t.enabled&&!Object.values(t.missions).some(r=>r.enabled)},onUnCheck:r=>{e.host.engine.imessage("status.auto.disable",[a])}}).addChildrenHead([new E(e,{classes:[R.fillSpace]})])),this._missions=this.host.game.space.programs.filter(r=>!g(this.setting.missions[r.name])).map(r=>new _(this,this.setting.missions[r.name],r.label,{onCheck:()=>{this.host.engine.imessage("status.sub.enable",[r.label])},onUnCheck:()=>{this.host.engine.imessage("status.sub.disable",[r.label])}}));const n=new S(this).addChildren(this._missions);this.addChildContent(n)}}class Pt extends B{_missionsUi;constructor(e,t,i){console.debug(...b(`Constructing ${Pt.name}`));const s=e.host.engine.i18n("ui.space");super(e,t,new D(e,t,i,s,{onCheck:n=>{e.host.engine.imessage("status.auto.enable",[s])},onRefreshTrigger(){this.triggerButton.element[0].title=e.host.engine.i18n("ui.trigger.section",[t.trigger<0?e.host.engine.i18n("ui.trigger.section.inactive"):e.host.renderPercentage(t.trigger,i.selected,!0)])},onSetTrigger:async()=>{const n=await T.prompt(e,e.host.engine.i18n("ui.trigger.prompt.percentage"),e.host.engine.i18n("ui.trigger.section.prompt",[s,t.trigger!==-1?e.host.renderPercentage(t.trigger,i.selected,!0):e.host.engine.i18n("ui.infinity")]),t.trigger!==-1?e.host.renderPercentage(t.trigger):"",e.host.engine.i18n("ui.trigger.section.promptExplainer"));if(n!==void 0){if(n===""||n.startsWith("-")){t.trigger=-1;return}t.trigger=e.host.parsePercentage(n)}},onUnCheck:n=>{e.host.engine.imessage("status.auto.disable",[s])},renderLabelTrigger:!1}),{onRefreshRequest:()=>{this.settingItem.triggerButton.inactive=!t.enabled||t.trigger===-1,this.settingItem.triggerButton.ineffective=t.enabled&&t.trigger<0&&Object.values(t.buildings).some(n=>n.enabled&&0<n.max&&n.trigger<0),this.expando.ineffective=t.enabled&&(Object.values(t.buildings).some(n=>n.enabled&&(n.max===0||n.trigger<0&&t.trigger<0))||!Object.values(t.buildings).some(n=>n.enabled)&&!t.unlockMissions.enabled||this._missionsUi.expando.ineffective)}}),this.addChildContent(new S(this,{onReset:()=>{this.setting.load({buildings:new ze().buildings})}}).addChildren(this.host.game.space.planets.filter(n=>0<n.buildings.length).flatMap((n,r,o)=>[new I(this,this.host.engine.labelForPlanet(n.name)),...n.buildings.filter(l=>!g(this.setting.buildings[l.name])).map((l,h,u)=>ie.getBuildOption(this,this.setting.buildings[l.name],i,this.setting,l.label,s,{delimiter:r<o.length-1&&h===u.length-1,renderLabelTrigger:!1}))])));const a=new S(this,{hasDisableAll:!1,hasEnableAll:!1});a.addChild(new I(this,this.host.engine.i18n("ui.additional"))),this._missionsUi=new Rn(this,this.setting.unlockMissions,i,this.setting),a.addChild(this._missionsUi),this.addChildContent(a)}}class Bt extends ce{constructor(e,t=400){super("ERR_OS_INVALID_ARGUMENT",e,t),this.name="InvalidArgumentError",typeof Error.captureStackTrace<"u"&&Error.captureStackTrace(this,Bt)}}const Je=43200,qi=1440,zi=Symbol.for("constructDateFrom");function It(c,e){return typeof c=="function"?c(e):c&&typeof c=="object"&&zi in c?c[zi](e):c instanceof Date?new c.constructor(e):new Date(e)}function Mn(c){return It(c,Date.now())}const An={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Pn=(c,e,t)=>{let i;const s=An[c];return typeof s=="string"?i=s:e===1?i=s.one:i=s.other.replace("{{count}}",e.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+i:i+" ago":i};function X(c){return(e={})=>{const t=e.width?String(e.width):c.defaultWidth;return c.formats[t]||c.formats[c.defaultWidth]}}const Bn={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},In={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},$n={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Ln={date:X({formats:Bn,defaultWidth:"full"}),time:X({formats:In,defaultWidth:"full"}),dateTime:X({formats:$n,defaultWidth:"full"})},On={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Un=(c,e,t,i)=>On[c];function q(c){return(e,t)=>{const i=t?.context?String(t.context):"standalone";let s;if(i==="formatting"&&c.formattingValues){const n=c.defaultFormattingWidth||c.defaultWidth,r=t?.width?String(t.width):n;s=c.formattingValues[r]||c.formattingValues[n]}else{const n=c.defaultWidth,r=t?.width?String(t.width):c.defaultWidth;s=c.values[r]||c.values[n]}const a=c.argumentCallback?c.argumentCallback(e):e;return s[a]}}const Dn={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Nn={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},qn={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},zn={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},Fn={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Hn={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},Wn={ordinalNumber:(c,e)=>{const t=Number(c),i=t%100;if(i>20||i<10)switch(i%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},era:q({values:Dn,defaultWidth:"wide"}),quarter:q({values:Nn,defaultWidth:"wide",argumentCallback:c=>c-1}),month:q({values:qn,defaultWidth:"wide"}),day:q({values:zn,defaultWidth:"wide"}),dayPeriod:q({values:Fn,defaultWidth:"wide",formattingValues:Hn,defaultFormattingWidth:"wide"})};function z(c){return(e,t={})=>{const i=t.width,s=i&&c.matchPatterns[i]||c.matchPatterns[c.defaultMatchWidth],a=e.match(s);if(!a)return null;const n=a[0],r=i&&c.parsePatterns[i]||c.parsePatterns[c.defaultParseWidth],o=Array.isArray(r)?Zn(r,u=>u.test(n)):Gn(r,u=>u.test(n));let l;l=c.valueCallback?c.valueCallback(o):o,l=t.valueCallback?t.valueCallback(l):l;const h=e.slice(n.length);return{value:l,rest:h}}}function Gn(c,e){for(const t in c)if(Object.prototype.hasOwnProperty.call(c,t)&&e(c[t]))return t}function Zn(c,e){for(let t=0;t<c.length;t++)if(e(c[t]))return t}function Xe(c){return(e,t={})=>{const i=e.match(c.matchPattern);if(!i)return null;const s=i[0],a=e.match(c.parsePattern);if(!a)return null;let n=c.valueCallback?c.valueCallback(a[0]):a[0];n=t.valueCallback?t.valueCallback(n):n;const r=e.slice(s.length);return{value:n,rest:r}}}const Kn=/^(\d+)(th|st|nd|rd)?/i,Vn=/\d+/i,jn={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},Jn={any:[/^b/i,/^(a|c)/i]},Xn={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Yn={any:[/1/i,/2/i,/3/i,/4/i]},Qn={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},ea={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},ta={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},ia={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},sa={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},na={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},aa={ordinalNumber:Xe({matchPattern:Kn,parsePattern:Vn,valueCallback:c=>parseInt(c,10)}),era:z({matchPatterns:jn,defaultMatchWidth:"wide",parsePatterns:Jn,defaultParseWidth:"any"}),quarter:z({matchPatterns:Xn,defaultMatchWidth:"wide",parsePatterns:Yn,defaultParseWidth:"any",valueCallback:c=>c+1}),month:z({matchPatterns:Qn,defaultMatchWidth:"wide",parsePatterns:ea,defaultParseWidth:"any"}),day:z({matchPatterns:ta,defaultMatchWidth:"wide",parsePatterns:ia,defaultParseWidth:"any"}),dayPeriod:z({matchPatterns:sa,defaultMatchWidth:"any",parsePatterns:na,defaultParseWidth:"any"})},Fi={code:"en-US",formatDistance:Pn,formatLong:Ln,formatRelative:Un,localize:Wn,match:aa,options:{weekStartsOn:0,firstWeekContainsDate:1}};let ra={};function Hi(){return ra}function le(c,e){return It(e||c,c)}function Wi(c){const e=le(c),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+c-+t}function Ye(c,...e){const t=It.bind(null,c||e.find(i=>typeof i=="object"));return e.map(t)}function Qe(c,e){const t=+le(c)-+le(e);return t<0?-1:t>0?1:t}function oa(c,e,t){const[i,s]=Ye(t?.in,c,e),a=i.getFullYear()-s.getFullYear(),n=i.getMonth()-s.getMonth();return a*12+n}function la(c,e){const t=le(c,e?.in);return t.setHours(23,59,59,999),t}function ca(c,e){const t=le(c,e?.in),i=t.getMonth();return t.setFullYear(t.getFullYear(),i+1,0),t.setHours(23,59,59,999),t}function ha(c,e){const t=le(c,e?.in);return+la(t,e)==+ca(t,e)}function ua(c,e,t){const[i,s,a]=Ye(t?.in,c,c,e),n=Qe(s,a),r=Math.abs(oa(s,a));if(r<1)return 0;s.getMonth()===1&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-n*r);let o=Qe(s,a)===-n;ha(i)&&r===1&&Qe(i,a)===1&&(o=!1);const l=n*(r-+o);return l===0?0:l}function da(c){return e=>{const i=(c?Math[c]:Math.trunc)(e);return i===0?0:i}}function ga(c,e){return+le(c)-+le(e)}function ma(c,e,t){const i=ga(c,e)/1e3;return da(t?.roundingMethod)(i)}function fa(c,e,t){const i=Hi(),s=t?.locale??i.locale??Fi,a=2520,n=Qe(c,e);if(isNaN(n))throw new RangeError("Invalid time value");const r=Object.assign({},t,{addSuffix:t?.addSuffix,comparison:n}),[o,l]=Ye(t?.in,...n>0?[e,c]:[c,e]),h=ma(l,o),u=(Wi(l)-Wi(o))/1e3,d=Math.round((h-u)/60);let m;if(d<2)return t?.includeSeconds?h<5?s.formatDistance("lessThanXSeconds",5,r):h<10?s.formatDistance("lessThanXSeconds",10,r):h<20?s.formatDistance("lessThanXSeconds",20,r):h<40?s.formatDistance("halfAMinute",0,r):h<60?s.formatDistance("lessThanXMinutes",1,r):s.formatDistance("xMinutes",1,r):d===0?s.formatDistance("lessThanXMinutes",1,r):s.formatDistance("xMinutes",d,r);if(d<45)return s.formatDistance("xMinutes",d,r);if(d<90)return s.formatDistance("aboutXHours",1,r);if(d<qi){const v=Math.round(d/60);return s.formatDistance("aboutXHours",v,r)}else{if(d<a)return s.formatDistance("xDays",1,r);if(d<Je){const v=Math.round(d/qi);return s.formatDistance("xDays",v,r)}else if(d<Je*2)return m=Math.round(d/Je),s.formatDistance("aboutXMonths",m,r)}if(m=ua(l,o),m<12){const v=Math.round(d/Je);return s.formatDistance("xMonths",v,r)}else{const v=m%12,p=Math.trunc(m/12);return v<3?s.formatDistance("aboutXYears",p,r):v<9?s.formatDistance("overXYears",p,r):s.formatDistance("almostXYears",p+1,r)}}function Gi(c,e){return fa(c,Mn(c),e)}function Zi(c,e){const t=Hi(),i=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,s=le(c,e?.in),a=s.getDay(),n=(a<i?7:0)+a-i;return s.setDate(s.getDate()-n),s.setHours(0,0,0,0),s}function pa(c,e,t){const[i,s]=Ye(t?.in,c,e);return+Zi(i,t)==+Zi(s,t)}const Ki={lessThanXSeconds:{standalone:{one:"weniger als 1 Sekunde",other:"weniger als {{count}} Sekunden"},withPreposition:{one:"weniger als 1 Sekunde",other:"weniger als {{count}} Sekunden"}},xSeconds:{standalone:{one:"1 Sekunde",other:"{{count}} Sekunden"},withPreposition:{one:"1 Sekunde",other:"{{count}} Sekunden"}},halfAMinute:{standalone:"eine halbe Minute",withPreposition:"einer halben Minute"},lessThanXMinutes:{standalone:{one:"weniger als 1 Minute",other:"weniger als {{count}} Minuten"},withPreposition:{one:"weniger als 1 Minute",other:"weniger als {{count}} Minuten"}},xMinutes:{standalone:{one:"1 Minute",other:"{{count}} Minuten"},withPreposition:{one:"1 Minute",other:"{{count}} Minuten"}},aboutXHours:{standalone:{one:"etwa 1 Stunde",other:"etwa {{count}} Stunden"},withPreposition:{one:"etwa 1 Stunde",other:"etwa {{count}} Stunden"}},xHours:{standalone:{one:"1 Stunde",other:"{{count}} Stunden"},withPreposition:{one:"1 Stunde",other:"{{count}} Stunden"}},xDays:{standalone:{one:"1 Tag",other:"{{count}} Tage"},withPreposition:{one:"1 Tag",other:"{{count}} Tagen"}},aboutXWeeks:{standalone:{one:"etwa 1 Woche",other:"etwa {{count}} Wochen"},withPreposition:{one:"etwa 1 Woche",other:"etwa {{count}} Wochen"}},xWeeks:{standalone:{one:"1 Woche",other:"{{count}} Wochen"},withPreposition:{one:"1 Woche",other:"{{count}} Wochen"}},aboutXMonths:{standalone:{one:"etwa 1 Monat",other:"etwa {{count}} Monate"},withPreposition:{one:"etwa 1 Monat",other:"etwa {{count}} Monaten"}},xMonths:{standalone:{one:"1 Monat",other:"{{count}} Monate"},withPreposition:{one:"1 Monat",other:"{{count}} Monaten"}},aboutXYears:{standalone:{one:"etwa 1 Jahr",other:"etwa {{count}} Jahre"},withPreposition:{one:"etwa 1 Jahr",other:"etwa {{count}} Jahren"}},xYears:{standalone:{one:"1 Jahr",other:"{{count}} Jahre"},withPreposition:{one:"1 Jahr",other:"{{count}} Jahren"}},overXYears:{standalone:{one:"mehr als 1 Jahr",other:"mehr als {{count}} Jahre"},withPreposition:{one:"mehr als 1 Jahr",other:"mehr als {{count}} Jahren"}},almostXYears:{standalone:{one:"fast 1 Jahr",other:"fast {{count}} Jahre"},withPreposition:{one:"fast 1 Jahr",other:"fast {{count}} Jahren"}}},ba=(c,e,t)=>{let i;const s=t?.addSuffix?Ki[c].withPreposition:Ki[c].standalone;return typeof s=="string"?i=s:e===1?i=s.one:i=s.other.replace("{{count}}",String(e)),t?.addSuffix?t.comparison&&t.comparison>0?"in "+i:"vor "+i:i},va={full:"EEEE, do MMMM y",long:"do MMMM y",medium:"do MMM y",short:"dd.MM.y"},ya={full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},wa={full:"{{date}} 'um' {{time}}",long:"{{date}} 'um' {{time}}",medium:"{{date}} {{time}}",short:"{{date}} {{time}}"},ka={date:X({formats:va,defaultWidth:"full"}),time:X({formats:ya,defaultWidth:"full"}),dateTime:X({formats:wa,defaultWidth:"full"})},_a={lastWeek:"'letzten' eeee 'um' p",yesterday:"'gestern um' p",today:"'heute um' p",tomorrow:"'morgen um' p",nextWeek:"eeee 'um' p",other:"P"},Ca=(c,e,t,i)=>_a[c],Sa={narrow:["v.Chr.","n.Chr."],abbreviated:["v.Chr.","n.Chr."],wide:["vor Christus","nach Christus"]},xa={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1. Quartal","2. Quartal","3. Quartal","4. Quartal"]},$t={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],wide:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"]},Ta={narrow:$t.narrow,abbreviated:["Jan.","Feb.","März","Apr.","Mai","Juni","Juli","Aug.","Sep.","Okt.","Nov.","Dez."],wide:$t.wide},Ea={narrow:["S","M","D","M","D","F","S"],short:["So","Mo","Di","Mi","Do","Fr","Sa"],abbreviated:["So.","Mo.","Di.","Mi.","Do.","Fr.","Sa."],wide:["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"]},Ra={narrow:{am:"vm.",pm:"nm.",midnight:"Mitternacht",noon:"Mittag",morning:"Morgen",afternoon:"Nachm.",evening:"Abend",night:"Nacht"},abbreviated:{am:"vorm.",pm:"nachm.",midnight:"Mitternacht",noon:"Mittag",morning:"Morgen",afternoon:"Nachmittag",evening:"Abend",night:"Nacht"},wide:{am:"vormittags",pm:"nachmittags",midnight:"Mitternacht",noon:"Mittag",morning:"Morgen",afternoon:"Nachmittag",evening:"Abend",night:"Nacht"}},Ma={narrow:{am:"vm.",pm:"nm.",midnight:"Mitternacht",noon:"Mittag",morning:"morgens",afternoon:"nachm.",evening:"abends",night:"nachts"},abbreviated:{am:"vorm.",pm:"nachm.",midnight:"Mitternacht",noon:"Mittag",morning:"morgens",afternoon:"nachmittags",evening:"abends",night:"nachts"},wide:{am:"vormittags",pm:"nachmittags",midnight:"Mitternacht",noon:"Mittag",morning:"morgens",afternoon:"nachmittags",evening:"abends",night:"nachts"}},Aa={ordinalNumber:c=>Number(c)+".",era:q({values:Sa,defaultWidth:"wide"}),quarter:q({values:xa,defaultWidth:"wide",argumentCallback:c=>c-1}),month:q({values:$t,formattingValues:Ta,defaultWidth:"wide"}),day:q({values:Ea,defaultWidth:"wide"}),dayPeriod:q({values:Ra,defaultWidth:"wide",formattingValues:Ma,defaultFormattingWidth:"wide"})},Pa=/^(\d+)(\.)?/i,Ba=/\d+/i,Ia={narrow:/^(v\.? ?Chr\.?|n\.? ?Chr\.?)/i,abbreviated:/^(v\.? ?Chr\.?|n\.? ?Chr\.?)/i,wide:/^(vor Christus|vor unserer Zeitrechnung|nach Christus|unserer Zeitrechnung)/i},$a={any:[/^v/i,/^n/i]},La={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](\.)? Quartal/i},Oa={any:[/1/i,/2/i,/3/i,/4/i]},Ua={narrow:/^[jfmasond]/i,abbreviated:/^(j[aä]n|feb|mär[z]?|apr|mai|jun[i]?|jul[i]?|aug|sep|okt|nov|dez)\.?/i,wide:/^(januar|februar|märz|april|mai|juni|juli|august|september|oktober|november|dezember)/i},Da={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^j[aä]/i,/^f/i,/^mär/i,/^ap/i,/^mai/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Na={narrow:/^[smdmf]/i,short:/^(so|mo|di|mi|do|fr|sa)/i,abbreviated:/^(son?|mon?|die?|mit?|don?|fre?|sam?)\.?/i,wide:/^(sonntag|montag|dienstag|mittwoch|donnerstag|freitag|samstag)/i},qa={any:[/^so/i,/^mo/i,/^di/i,/^mi/i,/^do/i,/^f/i,/^sa/i]},za={narrow:/^(vm\.?|nm\.?|Mitternacht|Mittag|morgens|nachm\.?|abends|nachts)/i,abbreviated:/^(vorm\.?|nachm\.?|Mitternacht|Mittag|morgens|nachm\.?|abends|nachts)/i,wide:/^(vormittags|nachmittags|Mitternacht|Mittag|morgens|nachmittags|abends|nachts)/i},Fa={any:{am:/^v/i,pm:/^n/i,midnight:/^Mitte/i,noon:/^Mitta/i,morning:/morgens/i,afternoon:/nachmittags/i,evening:/abends/i,night:/nachts/i}},Ha={ordinalNumber:Xe({matchPattern:Pa,parsePattern:Ba,valueCallback:c=>parseInt(c)}),era:z({matchPatterns:Ia,defaultMatchWidth:"wide",parsePatterns:$a,defaultParseWidth:"any"}),quarter:z({matchPatterns:La,defaultMatchWidth:"wide",parsePatterns:Oa,defaultParseWidth:"any",valueCallback:c=>c+1}),month:z({matchPatterns:Ua,defaultMatchWidth:"wide",parsePatterns:Da,defaultParseWidth:"any"}),day:z({matchPatterns:Na,defaultMatchWidth:"wide",parsePatterns:qa,defaultParseWidth:"any"}),dayPeriod:z({matchPatterns:za,defaultMatchWidth:"wide",parsePatterns:Fa,defaultParseWidth:"any"})},Wa={code:"de",formatDistance:ba,formatLong:ka,formatRelative:Ca,localize:Aa,match:Ha,options:{weekStartsOn:1,firstWeekContainsDate:4}},Ga={lessThanXSeconds:{one:"פחות משנייה",two:"פחות משתי שניות",other:"פחות מ־{{count}} שניות"},xSeconds:{one:"שנייה",two:"שתי שניות",other:"{{count}} שניות"},halfAMinute:"חצי דקה",lessThanXMinutes:{one:"פחות מדקה",two:"פחות משתי דקות",other:"פחות מ־{{count}} דקות"},xMinutes:{one:"דקה",two:"שתי דקות",other:"{{count}} דקות"},aboutXHours:{one:"כשעה",two:"כשעתיים",other:"כ־{{count}} שעות"},xHours:{one:"שעה",two:"שעתיים",other:"{{count}} שעות"},xDays:{one:"יום",two:"יומיים",other:"{{count}} ימים"},aboutXWeeks:{one:"כשבוע",two:"כשבועיים",other:"כ־{{count}} שבועות"},xWeeks:{one:"שבוע",two:"שבועיים",other:"{{count}} שבועות"},aboutXMonths:{one:"כחודש",two:"כחודשיים",other:"כ־{{count}} חודשים"},xMonths:{one:"חודש",two:"חודשיים",other:"{{count}} חודשים"},aboutXYears:{one:"כשנה",two:"כשנתיים",other:"כ־{{count}} שנים"},xYears:{one:"שנה",two:"שנתיים",other:"{{count}} שנים"},overXYears:{one:"יותר משנה",two:"יותר משנתיים",other:"יותר מ־{{count}} שנים"},almostXYears:{one:"כמעט שנה",two:"כמעט שנתיים",other:"כמעט {{count}} שנים"}},Za=(c,e,t)=>{if(c==="xDays"&&t?.addSuffix&&e<=2)return t.comparison&&t.comparison>0?e===1?"מחר":"מחרתיים":e===1?"אתמול":"שלשום";let i;const s=Ga[c];return typeof s=="string"?i=s:e===1?i=s.one:e===2?i=s.two:i=s.other.replace("{{count}}",String(e)),t?.addSuffix?t.comparison&&t.comparison>0?"בעוד "+i:"לפני "+i:i},Ka={full:"EEEE, d בMMMM y",long:"d בMMMM y",medium:"d בMMM y",short:"d.M.y"},Va={full:"H:mm:ss zzzz",long:"H:mm:ss z",medium:"H:mm:ss",short:"H:mm"},ja={full:"{{date}} 'בשעה' {{time}}",long:"{{date}} 'בשעה' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Ja={date:X({formats:Ka,defaultWidth:"full"}),time:X({formats:Va,defaultWidth:"full"}),dateTime:X({formats:ja,defaultWidth:"full"})},Xa={lastWeek:"eeee 'שעבר בשעה' p",yesterday:"'אתמול בשעה' p",today:"'היום בשעה' p",tomorrow:"'מחר בשעה' p",nextWeek:"eeee 'בשעה' p",other:"P"},Ya=(c,e,t,i)=>Xa[c],Qa={narrow:["לפנה״ס","לספירה"],abbreviated:["לפנה״ס","לספירה"],wide:["לפני הספירה","לספירה"]},er={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["רבעון 1","רבעון 2","רבעון 3","רבעון 4"]},tr={narrow:["1","2","3","4","5","6","7","8","9","10","11","12"],abbreviated:["ינו׳","פבר׳","מרץ","אפר׳","מאי","יוני","יולי","אוג׳","ספט׳","אוק׳","נוב׳","דצמ׳"],wide:["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"]},ir={narrow:["א׳","ב׳","ג׳","ד׳","ה׳","ו׳","ש׳"],short:["א׳","ב׳","ג׳","ד׳","ה׳","ו׳","ש׳"],abbreviated:["יום א׳","יום ב׳","יום ג׳","יום ד׳","יום ה׳","יום ו׳","שבת"],wide:["יום ראשון","יום שני","יום שלישי","יום רביעי","יום חמישי","יום שישי","יום שבת"]},sr={narrow:{am:"לפנה״צ",pm:"אחה״צ",midnight:"חצות",noon:"צהריים",morning:"בוקר",afternoon:"אחר הצהריים",evening:"ערב",night:"לילה"},abbreviated:{am:"לפנה״צ",pm:"אחה״צ",midnight:"חצות",noon:"צהריים",morning:"בוקר",afternoon:"אחר הצהריים",evening:"ערב",night:"לילה"},wide:{am:"לפנה״צ",pm:"אחה״צ",midnight:"חצות",noon:"צהריים",morning:"בוקר",afternoon:"אחר הצהריים",evening:"ערב",night:"לילה"}},nr={narrow:{am:"לפנה״צ",pm:"אחה״צ",midnight:"חצות",noon:"צהריים",morning:"בבוקר",afternoon:"בצהריים",evening:"בערב",night:"בלילה"},abbreviated:{am:"לפנה״צ",pm:"אחה״צ",midnight:"חצות",noon:"צהריים",morning:"בבוקר",afternoon:"אחר הצהריים",evening:"בערב",night:"בלילה"},wide:{am:"לפנה״צ",pm:"אחה״צ",midnight:"חצות",noon:"צהריים",morning:"בבוקר",afternoon:"אחר הצהריים",evening:"בערב",night:"בלילה"}},ar={ordinalNumber:(c,e)=>{const t=Number(c);if(t<=0||t>10)return String(t);const i=String(e?.unit),s=["year","hour","minute","second"].indexOf(i)>=0,a=["ראשון","שני","שלישי","רביעי","חמישי","שישי","שביעי","שמיני","תשיעי","עשירי"],n=["ראשונה","שנייה","שלישית","רביעית","חמישית","שישית","שביעית","שמינית","תשיעית","עשירית"],r=t-1;return s?n[r]:a[r]},era:q({values:Qa,defaultWidth:"wide"}),quarter:q({values:er,defaultWidth:"wide",argumentCallback:c=>c-1}),month:q({values:tr,defaultWidth:"wide"}),day:q({values:ir,defaultWidth:"wide"}),dayPeriod:q({values:sr,defaultWidth:"wide",formattingValues:nr,defaultFormattingWidth:"wide"})},rr=/^(\d+|(ראשון|שני|שלישי|רביעי|חמישי|שישי|שביעי|שמיני|תשיעי|עשירי|ראשונה|שנייה|שלישית|רביעית|חמישית|שישית|שביעית|שמינית|תשיעית|עשירית))/i,or=/^(\d+|רא|שנ|של|רב|ח|שי|שב|שמ|ת|ע)/i,lr={narrow:/^ל(ספירה|פנה״ס)/i,abbreviated:/^ל(ספירה|פנה״ס)/i,wide:/^ל(פני ה)?ספירה/i},cr={any:[/^לפ/i,/^לס/i]},hr={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^רבעון [1234]/i},ur={any:[/1/i,/2/i,/3/i,/4/i]},dr={narrow:/^\d+/i,abbreviated:/^(ינו|פבר|מרץ|אפר|מאי|יוני|יולי|אוג|ספט|אוק|נוב|דצמ)׳?/i,wide:/^(ינואר|פברואר|מרץ|אפריל|מאי|יוני|יולי|אוגוסט|ספטמבר|אוקטובר|נובמבר|דצמבר)/i},gr={narrow:[/^1$/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^7/i,/^8/i,/^9/i,/^10/i,/^11/i,/^12/i],any:[/^ינ/i,/^פ/i,/^מר/i,/^אפ/i,/^מא/i,/^יונ/i,/^יול/i,/^אוג/i,/^ס/i,/^אוק/i,/^נ/i,/^ד/i]},mr={narrow:/^[אבגדהוש]׳/i,short:/^[אבגדהוש]׳/i,abbreviated:/^(שבת|יום (א|ב|ג|ד|ה|ו)׳)/i,wide:/^יום (ראשון|שני|שלישי|רביעי|חמישי|שישי|שבת)/i},fr={abbreviated:[/א׳$/i,/ב׳$/i,/ג׳$/i,/ד׳$/i,/ה׳$/i,/ו׳$/i,/^ש/i],wide:[/ן$/i,/ני$/i,/לישי$/i,/עי$/i,/מישי$/i,/שישי$/i,/ת$/i],any:[/^א/i,/^ב/i,/^ג/i,/^ד/i,/^ה/i,/^ו/i,/^ש/i]},pr={any:/^(אחר ה|ב)?(חצות|צהריים|בוקר|ערב|לילה|אחה״צ|לפנה״צ)/i},br={any:{am:/^לפ/i,pm:/^אחה/i,midnight:/^ח/i,noon:/^צ/i,morning:/בוקר/i,afternoon:/בצ|אחר/i,evening:/ערב/i,night:/לילה/i}},vr=["רא","שנ","של","רב","ח","שי","שב","שמ","ת","ע"],yr={ordinalNumber:Xe({matchPattern:rr,parsePattern:or,valueCallback:c=>{const e=parseInt(c,10);return isNaN(e)?vr.indexOf(c)+1:e}}),era:z({matchPatterns:lr,defaultMatchWidth:"wide",parsePatterns:cr,defaultParseWidth:"any"}),quarter:z({matchPatterns:hr,defaultMatchWidth:"wide",parsePatterns:ur,defaultParseWidth:"any",valueCallback:c=>c+1}),month:z({matchPatterns:dr,defaultMatchWidth:"wide",parsePatterns:gr,defaultParseWidth:"any"}),day:z({matchPatterns:mr,defaultMatchWidth:"wide",parsePatterns:fr,defaultParseWidth:"any"}),dayPeriod:z({matchPatterns:pr,defaultMatchWidth:"any",parsePatterns:br,defaultParseWidth:"any"})},wr={code:"he",formatDistance:Za,formatLong:Ja,formatRelative:Ya,localize:ar,match:yr,options:{weekStartsOn:0,firstWeekContainsDate:1}},kr={lessThanXSeconds:{one:"不到 1 秒",other:"不到 {{count}} 秒"},xSeconds:{one:"1 秒",other:"{{count}} 秒"},halfAMinute:"半分钟",lessThanXMinutes:{one:"不到 1 分钟",other:"不到 {{count}} 分钟"},xMinutes:{one:"1 分钟",other:"{{count}} 分钟"},xHours:{one:"1 小时",other:"{{count}} 小时"},aboutXHours:{one:"大约 1 小时",other:"大约 {{count}} 小时"},xDays:{one:"1 天",other:"{{count}} 天"},aboutXWeeks:{one:"大约 1 个星期",other:"大约 {{count}} 个星期"},xWeeks:{one:"1 个星期",other:"{{count}} 个星期"},aboutXMonths:{one:"大约 1 个月",other:"大约 {{count}} 个月"},xMonths:{one:"1 个月",other:"{{count}} 个月"},aboutXYears:{one:"大约 1 年",other:"大约 {{count}} 年"},xYears:{one:"1 年",other:"{{count}} 年"},overXYears:{one:"超过 1 年",other:"超过 {{count}} 年"},almostXYears:{one:"将近 1 年",other:"将近 {{count}} 年"}},_r=(c,e,t)=>{let i;const s=kr[c];return typeof s=="string"?i=s:e===1?i=s.one:i=s.other.replace("{{count}}",String(e)),t?.addSuffix?t.comparison&&t.comparison>0?i+"内":i+"前":i},Cr={full:"y'年'M'月'd'日' EEEE",long:"y'年'M'月'd'日'",medium:"yyyy-MM-dd",short:"yy-MM-dd"},Sr={full:"zzzz a h:mm:ss",long:"z a h:mm:ss",medium:"a h:mm:ss",short:"a h:mm"},xr={full:"{{date}} {{time}}",long:"{{date}} {{time}}",medium:"{{date}} {{time}}",short:"{{date}} {{time}}"},Tr={date:X({formats:Cr,defaultWidth:"full"}),time:X({formats:Sr,defaultWidth:"full"}),dateTime:X({formats:xr,defaultWidth:"full"})};function Vi(c,e,t){const i="eeee p";return pa(c,e,t)?i:c.getTime()>e.getTime()?"'下个'"+i:"'上个'"+i}const Er={lastWeek:Vi,yesterday:"'昨天' p",today:"'今天' p",tomorrow:"'明天' p",nextWeek:Vi,other:"PP p"},Rr=(c,e,t,i)=>{const s=Er[c];return typeof s=="function"?s(e,t,i):s},Mr={narrow:["前","公元"],abbreviated:["前","公元"],wide:["公元前","公元"]},Ar={narrow:["1","2","3","4"],abbreviated:["第一季","第二季","第三季","第四季"],wide:["第一季度","第二季度","第三季度","第四季度"]},Pr={narrow:["一","二","三","四","五","六","七","八","九","十","十一","十二"],abbreviated:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],wide:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]},Br={narrow:["日","一","二","三","四","五","六"],short:["日","一","二","三","四","五","六"],abbreviated:["周日","周一","周二","周三","周四","周五","周六"],wide:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]},Ir={narrow:{am:"上",pm:"下",midnight:"凌晨",noon:"午",morning:"早",afternoon:"下午",evening:"晚",night:"夜"},abbreviated:{am:"上午",pm:"下午",midnight:"凌晨",noon:"中午",morning:"早晨",afternoon:"中午",evening:"晚上",night:"夜间"},wide:{am:"上午",pm:"下午",midnight:"凌晨",noon:"中午",morning:"早晨",afternoon:"中午",evening:"晚上",night:"夜间"}},$r={narrow:{am:"上",pm:"下",midnight:"凌晨",noon:"午",morning:"早",afternoon:"下午",evening:"晚",night:"夜"},abbreviated:{am:"上午",pm:"下午",midnight:"凌晨",noon:"中午",morning:"早晨",afternoon:"中午",evening:"晚上",night:"夜间"},wide:{am:"上午",pm:"下午",midnight:"凌晨",noon:"中午",morning:"早晨",afternoon:"中午",evening:"晚上",night:"夜间"}},Lr={ordinalNumber:(c,e)=>{const t=Number(c);switch(e?.unit){case"date":return t.toString()+"日";case"hour":return t.toString()+"时";case"minute":return t.toString()+"分";case"second":return t.toString()+"秒";default:return"第 "+t.toString()}},era:q({values:Mr,defaultWidth:"wide"}),quarter:q({values:Ar,defaultWidth:"wide",argumentCallback:c=>c-1}),month:q({values:Pr,defaultWidth:"wide"}),day:q({values:Br,defaultWidth:"wide"}),dayPeriod:q({values:Ir,defaultWidth:"wide",formattingValues:$r,defaultFormattingWidth:"wide"})},Or=/^(第\s*)?\d+(日|时|分|秒)?/i,Ur=/\d+/i,Dr={narrow:/^(前)/i,abbreviated:/^(前)/i,wide:/^(公元前|公元)/i},Nr={any:[/^(前)/i,/^(公元)/i]},qr={narrow:/^[1234]/i,abbreviated:/^第[一二三四]刻/i,wide:/^第[一二三四]刻钟/i},zr={any:[/(1|一)/i,/(2|二)/i,/(3|三)/i,/(4|四)/i]},Fr={narrow:/^(一|二|三|四|五|六|七|八|九|十[二一])/i,abbreviated:/^(一|二|三|四|五|六|七|八|九|十[二一]|\d|1[12])月/i,wide:/^(一|二|三|四|五|六|七|八|九|十[二一])月/i},Hr={narrow:[/^一/i,/^二/i,/^三/i,/^四/i,/^五/i,/^六/i,/^七/i,/^八/i,/^九/i,/^十(?!(一|二))/i,/^十一/i,/^十二/i],any:[/^一|1/i,/^二|2/i,/^三|3/i,/^四|4/i,/^五|5/i,/^六|6/i,/^七|7/i,/^八|8/i,/^九|9/i,/^十(?!(一|二))|10/i,/^十一|11/i,/^十二|12/i]},Wr={narrow:/^[一二三四五六日]/i,short:/^[一二三四五六日]/i,abbreviated:/^周[一二三四五六日]/i,wide:/^星期[一二三四五六日]/i},Gr={any:[/日/i,/一/i,/二/i,/三/i,/四/i,/五/i,/六/i]},Zr={any:/^(上午?|下午?|午夜|[中正]午|早上?|下午|晚上?|凌晨|)/i},Kr={any:{am:/^上午?/i,pm:/^下午?/i,midnight:/^午夜/i,noon:/^[中正]午/i,morning:/^早上/i,afternoon:/^下午/i,evening:/^晚上?/i,night:/^凌晨/i}},Vr={ordinalNumber:Xe({matchPattern:Or,parsePattern:Ur,valueCallback:c=>parseInt(c,10)}),era:z({matchPatterns:Dr,defaultMatchWidth:"wide",parsePatterns:Nr,defaultParseWidth:"any"}),quarter:z({matchPatterns:qr,defaultMatchWidth:"wide",parsePatterns:zr,defaultParseWidth:"any",valueCallback:c=>c+1}),month:z({matchPatterns:Fr,defaultMatchWidth:"wide",parsePatterns:Hr,defaultParseWidth:"any"}),day:z({matchPatterns:Wr,defaultMatchWidth:"wide",parsePatterns:Gr,defaultParseWidth:"any"}),dayPeriod:z({matchPatterns:Zr,defaultMatchWidth:"any",parsePatterns:Kr,defaultParseWidth:"any"})},jr={code:"zh-CN",formatDistance:_r,formatLong:Tr,formatRelative:Rr,localize:Lr,match:Vr,options:{weekStartsOn:1,firstWeekContainsDate:4}};class Jr{_game;constructor(e){this._game=e}load(e){return new Promise((t,i)=>{if(e===null){t();return}this._game.saveImportDropboxText(e,s=>{if(s){i(s);return}t()})})}loadRaw(e){const t=this._game.compressLZData(JSON.stringify(e));return this.load(t)}}class Re extends ne{constructor(e,t){super(e,t),this.element.addClass(Ni.toolbar)}toString(){return`[${Re.name}#${this.componentId}]`}addChild(e){return super.addChild(e)}}class Lt extends B{games=new Array;states=new Array;gameList;stateList;locale;constructor(e,t,i){console.debug(...b(`Constructing ${Lt.name}`));const s=e.host.engine.i18n("state.title");super(e,t,new ae(e,s,{classes:[P.checked,P.setting],icon:M.State}).addChildrenHead([new E(e,{classes:[R.fillSpace]})]),{onRefresh:()=>{this._refreshGameList(),this._refreshStateList()}}),this.gameList=new S(this,{hasDisableAll:!1,hasEnableAll:!1}),this.stateList=new S(this,{hasDisableAll:!1,hasEnableAll:!1}),this.locale=i.selected==="zh-CN"?jr:i.selected==="he-IL"?wr:i.selected==="de-DE"?Wa:Fi,this.addChildContent(new S(this,{hasDisableAll:!1,hasEnableAll:!1}).addChildren([new _(this,this.setting.noConfirm,this.host.engine.i18n("state.noConfirm")),new ne(this).addChild(new V(this)),new I(this,this.host.engine.i18n("state.local")),new Re(this).addChildren([new W(this,this.host.engine.i18n("state.import"),M.Import,{onClick:()=>{this.import()},title:this.host.engine.i18n("state.importTitle")})]),new ne(this).addChild(new V(this)),new I(this,this.host.engine.i18n("state.localStates")),new Re(this).addChildren([new W(this,this.host.engine.i18n("state.store"),M.SaveAs,{onClick:()=>{this.storeState()},title:this.host.engine.i18n("state.storeState")}),new W(this,this.host.engine.i18n("copy"),M.Copy,{onClick:()=>{this.copyState().catch(H(console)),this.host.engine.imessage("state.copied.stateCurrent")},title:this.host.engine.i18n("state.copy.stateCurrent")}),new W(this,this.host.engine.i18n("state.new"),M.Draft,{onClick:()=>{this.storeStateFactoryDefaults(),this.host.engine.imessage("state.stored.state")},title:this.host.engine.i18n("state.storeFactory")}),new W(this,this.host.engine.i18n("state.exportAll"),M.Sync,{onClick:()=>{this.exportStateAll()},title:this.host.engine.i18n("state.exportAllTitle")})]),new ne(this).addChild(this.stateList),new ne(this).addChild(new V(this)),new I(this,this.host.engine.i18n("state.localGames")),new Re(this).addChildren([new W(this,this.host.engine.i18n("state.store"),M.SaveAs,{onClick:()=>{this.storeGame(),this.host.engine.imessage("state.stored.game")},title:this.host.engine.i18n("state.storeGame")}),new W(this,this.host.engine.i18n("copy"),M.Copy,{onClick:()=>{this.copyGame().catch(H(console)),this.host.engine.imessage("state.copied.gameCurrent")},title:this.host.engine.i18n("state.copy.gameCurrent")})]),new ne(this).addChild(this.gameList),new _(this,this.setting.compress,this.host.engine.i18n("state.compress"))])),this._loadGames(),this._loadStates()}_loadGames(){let e=0,t=localStorage.getItem(`ks.game.${e}`);this.games.splice(0);try{for(;!g(t);){const i=JSON.parse(t);this.games.push(new Oe(i)),t=localStorage.getItem(`ks.game.${++e}`)}}catch(i){console.error(...b(i))}}_storeGames(){let e=0,t=localStorage.getItem(`ks.game.${e}`);for(;!g(t);)localStorage.removeItem(`ks.game.${e}`),t=localStorage.getItem(`ks.game.${++e}`);e=0;for(const i of this.games)localStorage.setItem(`ks.game.${e++}`,JSON.stringify(i))}_loadStates(){let e=0,t=localStorage.getItem(`ks.state.${e}`);this.states.splice(0);try{for(;!g(t);){const i=JSON.parse(t);re.unknownAsEngineStateOrThrow(i.state),this.states.push(new Oe(i)),t=localStorage.getItem(`ks.state.${++e}`)}}catch(i){console.error(...b(i))}}_storeStates(){let e=0,t=localStorage.getItem(`ks.state.${e}`);for(;!g(t);)localStorage.removeItem(`ks.state.${e}`),t=localStorage.getItem(`ks.state.${++e}`);e=0;for(const i of this.states)localStorage.setItem(`ks.state.${e++}`,JSON.stringify(i))}_refreshGameList(){this.gameList.removeChildren(this.gameList.children),this.gameList.addChildren(this.games.sort((e,t)=>new Date(e.unwrap().timestamp).getTime()-new Date(t.unwrap().timestamp).getTime()).map(e=>[e.unwrap(),e]).map(([e,t])=>new wt(this,new pe(this,`${e.label} (${Gi(new Date(e.timestamp),{addSuffix:!0,locale:this.locale})})`,{onClick:()=>{this.loadGame(e.game).catch(H(console)),this.host.engine.imessage("state.loaded.game",[e.label])},title:new Date(e.timestamp).toLocaleString()})).addChildren([new E(this,{classes:[R.fillSpace]}),new J(this,M.Save,this.host.engine.i18n("state.update.game"),{onClick:()=>{this.updateGame(t,this.host.game.save()),this.host.engine.imessage("state.updated.game",[e.label])}}),new J(this,M.Edit,this.host.engine.i18n("state.edit.game"),{onClick:()=>{this.storeGame(e.game),this.deleteGame(t,!0),this.host.engine.imessage("state.updated.game",[e.label])}}),new J(this,M.Copy,this.host.engine.i18n("state.copy.game"),{onClick:()=>{this.copyGame(e.game).catch(H(console)),this.host.engine.imessage("state.copied.game",[e.label])}}),new J(this,M.Delete,this.host.engine.i18n("state.delete.game"),{onClick:()=>{this.deleteGame(t),this.host.engine.imessage("state.deleted.game",[e.label])}})])))}_refreshStateList(){this.stateList.removeChildren(this.stateList.children),this.stateList.addChildren(this.states.sort((e,t)=>new Date(e.unwrap().timestamp).getTime()-new Date(t.unwrap().timestamp).getTime()).map(e=>[e.unwrap(),e]).map(([e,t])=>new wt(this,new pe(this,`${e.label} (${Gi(new Date(e.timestamp),{addSuffix:!0,locale:this.locale})})`,{onClick:()=>{this.loadState(e.state),this.host.engine.imessage("state.loaded.state",[e.label])},title:new Date(e.timestamp).toLocaleString()})).addChildren([new E(this,{classes:[R.fillSpace]}),new J(this,M.Save,this.host.engine.i18n("state.update.state"),{onClick:()=>{this.updateState(t,this.host.engine.stateSerialize()),this.host.engine.imessage("state.updated.state",[e.label])}}),new J(this,M.Edit,this.host.engine.i18n("state.edit.state"),{onClick:()=>{this.storeState(e.state),this.deleteState(t,!0),this.host.engine.imessage("state.updated.state",[e.label])}}),new J(this,M.Copy,this.host.engine.i18n("state.copy.state"),{onClick:()=>{this.copyState(e.state).catch(H(console)),this.host.engine.imessage("state.copied.state",[e.label])}}),new J(this,M.Delete,this.host.engine.i18n("state.delete.state"),{onClick:()=>{this.deleteState(t),this.host.engine.imessage("state.deleted.state",[e.label])}})])))}async copyState(e){await this.host.copySettings(e,!1)}async copyGame(e){const t=e??this.host.game.save(),i=JSON.stringify(t),s=this.setting.compress.enabled?this.host.game.compressLZData(i):i;await x.window.navigator.clipboard.writeText(s)}import(){const e=x.window.prompt(this.host.engine.i18n("state.loadPrompt"));if(g(e))return;const t=new Date().toDateString();let i=1;const s=()=>this.host.engine.i18n("state.importedState",[`${t} #${i++}`]),a=n=>{try{const l=re.decodeSettings(n);this.storeState(l,s()),this.host.engine.imessage("state.imported.state");return}catch{}try{const l=JSON.parse(n),h=re.decodeSettings(l.state);this.storeState(h,l.label),this.host.engine.imessage("state.imported.state");return}catch{}let r;try{r=JSON.parse(n)}catch{const h=this.host.game.decompressLZData(n);try{r=JSON.parse(h)}catch{if(n.match(/\r?\n/))return n.split(/\r?\n/).map(d=>void a(d));throw new Bt("The provided input can not be parsed as anything we understand.")}}let o;if(!g(r)&&"ks"in r&&!g(r.ks)){const l=r.ks.state[0];o=this.storeState(l,s())??void 0,this.host.engine.imessage("state.imported.state"),r.ks=void 0}this.storeGame(r,o),this.host.engine.imessage("state.imported.game")};a(e)}storeGame(e,t){let i=t;return g(i)&&(i=x.window.prompt(this.host.engine.i18n("state.storeGame.prompt"))??void 0),g(i)?null:(i=(i===""?void 0:i)??this.host.engine.i18n("state.unlabeledGame"),i=i.substring(0,127),this.games.push(new Oe({game:e??this.host.game.save(),label:i,timestamp:new Date().toISOString()})),this._storeGames(),this.requestRefresh(),i)}storeState(e,t){let i=t;return g(i)&&(i=x.window.prompt(this.host.engine.i18n("state.storeState.prompt"))??void 0),g(i)?null:(i=(i===""?void 0:i)??this.host.engine.i18n("state.unlabeledState"),i=i.substring(0,127),this.states.push(new Oe({label:i,state:e??this.host.engine.stateSerialize(),timestamp:new Date().toISOString()})),this._storeStates(),this.requestRefresh(),i)}storeStateFactoryDefaults(){this.storeState(te.DEFAULT_STATE)}storeAutoSave(e){const t=this.states.find(i=>i.unwrap().label==="Auto-Save");if(!g(t)){console.info(...b("Updating existing Auto-Save...")),t.replace({...t.unwrap(),state:e,timestamp:new Date().toISOString()}),this._storeStates(),this.requestRefresh();return}console.info(...b("Storing new Auto-Save...")),this.storeState(e,"Auto-Save")}exportStateAll(){const e=this.states.map(a=>a.unwrap()).map(a=>JSON.stringify({label:a.label,state:re.encodeSettings(a.state,!1),timestamp:a.timestamp})).join(`
|